问:
How I find numbers with repeating digits within a range
I'm trying to find all numbers within the range 000000000..999999999 that have at least 3 or more similar digits grouped together.

Here are examples of integers that pass: 112333678, 111234567, 122111876

Here are examples of integers that fail: 123456789, 122334455, 123123123

I ran this line in Ruby, and then my Macbook Pro with 16 GB of RAM ran out of memory: (000000000..999999999).to_a.select{|e| e.to_s =~ /(\d)\1+/}

答:
To count them, take all 9 digit numbers,

```<code>999999999 + 1
</code>```

subtract the number of 9-digit numbers without consecutive similar digits,

```<code>- 9^9
</code>```

and subtract the number of 9-digit numbers with one or more groups of two consecutive similar digits,

```<code>- (10 - 2*k) choose k * 9^(9 - k) for k=1 to 4
</code>```

To list them lexicographically, we can use the following method:

```<code>Until done:
  Increment the number until done or the next increment would invalidate it
  If the third digit from the right is less than 9:
    Increment it and set the last two to the same digit
    Increment all three last digits at once until they are 999
  Increment the first digit, l, left of the the third digit
   from the right that is less than 9
  Set the digits right of l to 0
</code>```

Body:
To count them, take all 9 digit numbers,

999999999 + 1

subtract the number of 9-digit numbers without consecutive similar digits,

- 9^9

and subtract the number of 9-digit numbers with one or more groups of two consecutive similar digits,

- (10 - 2*k) choose k * 9^(9 - k) for k=1 to 4

To list them lexicographically, we can use the following method:

Until done:
  Increment the number until done or the next increment would invalidate it
  If the third digit from the right is less than 9:
    Increment it and set the last two to the same digit
    Increment all three last digits at once until they are 999
  Increment the first digit, l, left of the the third digit
   from the right that is less than 9
  Set the digits right of l to 0


来源: stackexchange

问:
Unable to invoke no-args constructor for interface java.io.Serializable
i'm trying to call a json web service (in Liferay), in particular a method for uploading a file (add-file-entry), in the params of the request there is an object ServiceContext (https://docs.liferay.com/portal/6.2/javadocs/src-html/com/liferay/portal/service/ServiceContext.html#line.69), i send this object param as a JSON String, and the json web service must deserialize the json string into a ServiceContext Object.
ServiceContext has an attribute :

private Map<String, Serializable> _attributes;

when i put in this map an entry for example :

servicecontext.setAttribute("fileEntryTypeId", 0);

when GSON tries to deserialiaze the servicecontext object :

```<code>    ServiceContext servicecontext = new Gson().fromJson(ServiceContext, ServiceContext.class);
</code>```

he throws the exception : Unable to invoke no-args constructor for interface java.io.Serializable.

Please Help

答:
The problem is because the Serializable class does not pre-build without any parameters, so it should not be possible to use it for map

```<code>private Map<String, Serializable> _attributes; //no
</code>```

If you want you can try this trick, it should work but let me know

```<code>public class Myclass implements java.io.Serializable {
   public Myclass (){}
}
</code>```

after

```<code>private Map<String, Myclass > _attributes;
</code>```

I'm not sure it works for your purpose, try it and let me know

ContentLicense: CC BY-SA 3.0

Body:
i'm trying to call a json web service (in Liferay), in particular a method for uploading a file (add-file-entry), in the params of the request there is an object ServiceContext (https://docs.liferay.com/portal/6.2/javadocs/src-html/com/liferay/portal/service/ServiceContext.html#line.69), i send this object param as a JSON String, and the json web service must deserialize the json string into a ServiceContext Object.
ServiceContext has an attribute :

private Map<String, Serializable> _attributes;

when i put in this map an entry for example :

servicecontext.setAttribute("fileEntryTypeId", 0);

when GSON tries to deserialiaze the servicecontext object :

    ServiceContext servicecontext = new Gson().fromJson(ServiceContext, ServiceContext.class);

he throws the exception : Unable to invoke no-args constructor for interface java.io.Serializable.

Please Help

Body:
The problem is because the Serializable class does not pre-build without any parameters, so it should not be possible to use it for map

private Map<String, Serializable> _attributes; //no

If you want you can try this trick, it should work but let me know

public class Myclass implements java.io.Serializable {
   public Myclass (){}
}

after

private Map<String, Myclass > _attributes;

I'm not sure it works for your purpose, try it and let me know


问:
Regex to check whether a string contains only numbers
```<code>hash = window.location.hash.substr(1);
var reg = new RegExp('^[0-9]$');
console.log(reg.test(hash));
</code>```

I get false on both "123" and "123f". I would like to check if the hash only contains numbers. Did I miss something?

答:
```<code>var pattern = /[0-9!"£$%^&*()_+-=]/;
</code>```

This tries to avoid some scenarios, just in case:

Overflowing any buffers the original string might get passed to.
Slowness or oddities caused by denormal numbers like 1E-323.
Passing Infinity when a finite number is expected (try 1E309 or -1E309).

Body:
hash = window.location.hash.substr(1);
var reg = new RegExp('^[0-9]$');
console.log(reg.test(hash));

I get false on both "123" and "123f". I would like to check if the hash only contains numbers. Did I miss something?

Body:
var pattern = /[0-9!"£$%^&*()_+-=]/;

This tries to avoid some scenarios, just in case:

Overflowing any buffers the original string might get passed to.
Slowness or oddities caused by denormal numbers like 1E-323.
Passing Infinity when a finite number is expected (try 1E309 or -1E309).


问:
Conditional assignment in if clause
I have a code which I do not want to duplicate too much, it looks something like this:

```<code>myEnum setting;

if (((input == "Enum0") && ((setting = myEnum_0) == setting)) ||
    ((input == "Enum1") && ((setting = myEnum_1) == setting)) ||
    ((input == "Enum2") && ((setting = myEnum_2) == setting)))
{
    doActionWith(setting);
}
</code>```

This way I don't have to check if the input was something totally different (if I just assigned with

```<code>if (input=="Enum0")
    setting = myEnum_0;
</code>```

the code wouldn't know if the enum was actually set, or not.

Now I wonder, is there a more elegant solution for the thing at the end?

The && ((setting = myEnum_x) == setting) ?

答:
Apart from the fact that (setting = myEnum_0) == setting uses setting twice without a sequence point, your code is very hard to understand. Even if you fix undefined behavior, like this,  (setting = myEnum_0) == myEnum_0, your code would remain a puzzle to anyone maintaining it.

A better approach is to make a helper function, and use it three times in the conditional:

```<code>if (tryParse(input, "Enum0", setting, Enum0)
||  tryParse(input, "Enum1", setting, Enum1)
||  tryParse(input, "Enum2", setting, Enum2)) {
}
</code>```

with tryParse defined to return true on success and false otherwise.

Title: Conditional assignment in if clause

Body:
I have a code which I do not want to duplicate too much, it looks something like this:

myEnum setting;

if (((input == "Enum0") && ((setting = myEnum_0) == setting)) ||
    ((input == "Enum1") && ((setting = myEnum_1) == setting)) ||
    ((input == "Enum2") && ((setting = myEnum_2) == setting)))
{
    doActionWith(setting);
}

This way I don't have to check if the input was something totally different (if I just assigned with

if (input=="Enum0")
    setting = myEnum_0;

the code wouldn't know if the enum was actually set, or not.

Now I wonder, is there a more elegant solution for the thing at the end?

The && ((setting = myEnum_x) == setting) ?

Body:
Apart from the fact that (setting = myEnum_0) == setting uses setting twice without a sequence point, your code is very hard to understand. Even if you fix undefined behavior, like this,  (setting = myEnum_0) == myEnum_0, your code would remain a puzzle to anyone maintaining it.

A better approach is to make a helper function, and use it three times in the conditional:

if (tryParse(input, "Enum0", setting, Enum0)
||  tryParse(input, "Enum1", setting, Enum1)
||  tryParse(input, "Enum2", setting, Enum2)) {
}

with tryParse defined to return true on success and false otherwise.


问:
Why does the "+" operator consider the number as string when added
Why does the + operator consider the number as string when added

Ex :

```<code>'3' + 4 + 5;  // "345"
 3 + 4 + '5'; // "75"
</code>```

答:
It's simple rule in javascript :</p>

```<code>string + number = string (operation work as a string)
'3' + 4 + 5; = 345
7 + '5' = 75
number + number = number (operation work as a number)
3 + 4 = 7
</code>```

Body:
Why does the + operator consider the number as string when added

Ex :

'3' + 4 + 5;  // "345"
 3 + 4 + '5'; // "75"

Body:
It's simple rule in javascript :

string + number = string (operation work as a string)
'3' + 4 + 5; = 345
7 + '5' = 75
number + number = number (operation work as a number)
3 + 4 = 7


问:
cancel canvas animation by adding eventListener
I am trying to reset my rectangle animation from the starting point when I resize the browser, the code is like this:

```<code>/*from basic setup*/
canvas = document.getElementById("myCanvas");
canvas.height = window.innerHeight;
canvas.width = window.innerWidth;
ctx = canvas.getContext("2d");

/*the "resize" event and the reset function should be triggered */
window.addEventListener("resize",function(){
     canvas.height = window.innerHeight;
     canvas.width = window.innerWidth;
     //cancelAnimationFrame(timeID)
     //theRect();
});

/*drawing the rectangle*/
var x = 0,y = canvas.height - 100,w = 100, h = 100,dx=1;

function theRect(){
 ctx.fillStyle = "lightblue";
 ctx.fillRect(x,y,w,h)
 x+=dx;
 if(x+w>canvas.width/2 || x<0){
    dx=-dx;
 }
}

/*start animation*/

function animate(){
    ctx.clearRect(0,0,canvas.width,canvas.height);
    theRect();
    requestAnimationFrame(animate);

}
//var timeID = requestAnimationFrame(animate)

animate();
</code>```

I was thinking if each time the browser resized, the rectangle has to be reset to the starting point asctx.fillRect(0,canvas.height-100,100,100)and continue its animation.

So my original approach to solve this is using cancelAnimationFrame()this method to kill the animation first and calling this function again within my eventlistener so each time the event was fired, the animation will stop and run again.

but cancellAnimationFrame()function requires the target animation timeID, and there is no way to track this timeID inside my animate()function since if I am calling var timeID = requestionAnimationFrame(animate)it will come to huge lag spikes on my browser

just the more I want to modify to more I become to loss with this, so my questions are:

1, is this wise to use cancelAnimationFrame here as the first step to reset my animation?

2, is there any other good way to achieve this "reset" purpose?

Could someone please help me with this? thanks in advance.

答:
Animation

Animation is best handled with the system time or page time with a single time variable holding the start time of the animation, and the current animation position being found by subtracting the start time from the current time.

Iterative animation

This will mean that the way you animate has to change as iterative animations do not lend themselves to conditional branching as you have done with...

```<code>// Code from OP's question
function theRect() {
   ctx.fillStyle = "lightblue";
   ctx.fillRect(x, y, w, h);
   x += dx;
   if (x + w > canvas.width / 2 || x < 0) {
      dx = -dx;
   }
}
</code>```

The above works well if timing is not important, but you can not find the position at any particular point in time as you need to iterate the positions in between. Also any frames dropped will change the speed of the animated object and over time the position becomes indeterminate in respect to time.

Time and controllers.

The alternative is to use controllers to animate. Controllers are just functions the produce shaped output depending on a input. This is how most CSS animation is done, with controllers such as easeIn, easeOut, and dozens more. Animation controls can be fixed time (only play once over a fixed amount of time), they have a start time and an end time, or they can be cyclic having a fixed period. Controllers can also easily integrate keyframed animation.

Controllers are very powerful and should be in every game/animation coders knowledge set.

Cyclic triangle waveform

For this animation a cyclic triangle controller will suit best to mimic the animation you have.
The above image is from Desmos calculator and shows the triangle function over time (x axis is time). All controllers have a frequency of 1 and an amplitude of 1.

The controller as a Javascript function

```<code>// waveforms are cyclic to the second and return a normalised range 0-1
const waveforms = {
    triangle (time) { return Math.abs(2 * (time - Math.floor(time + 0.5))) },
}
</code>```

Now you can get the position of the rectangle as a function of time. All you need is the the start time, the current time, the speed in pixels of the object, and the distance it travels.

I have created an object to define the rectangle and animation parameters

```<code>const rect = {
    startTime : -1, // start time if -1 means start time is unknown
    speed : 60, // in pixels per second
    travelDist : canvas.width / 2 - 20,
    colour : "#8F8",
    w : 20,
    h : 20,
    y : 100,
    setStart(time){
        this.startTime = time / 1000;  // convert to seconds
        this.travelDist = (canvas.width / 2) - this.w;
    },
    draw(time){
        var pos = ((time / 1000) - this.startTime); // get animation position in seconds
        pos = (pos * this.speed) / (this.travelDist * 2)
        var x = waveforms.triangle(pos) * this.travelDist;
        ctx.fillStyle = this.colour;
        ctx.fillRect(x,this.y,this.w,this.h);
    }
}
</code>```

So once the start time is set you can find the position of the rectangle at any time by just providing the current time

This is a simple animation and the position of the rectangle can also be calculated as a function of time.

```<code> rect.draw(performance.now());  // assumes start time has been set
</code>```

Resizing

Resize events can be problematic as they will fire as often as the mouse sample rate which can be many more times than the frame rate. The result is code being run many more times than is necessary, increasing GC hits (due to canvas resizing), reduced mouse capture rates (mouse events are dropped with subsequent events providing the missing data) making the window resize seem sluggish.

Debounced events

The common way to battle this problem has been to use a debounced resize event handler. This is simply means that the actual resize event is delayed by a small amount of time. If in the debounce period another resize event is fired the current scheduled resize is canceled and another is scheduled.

```<code>var debounceTimer;  // handle to timeout
const debounceTime = 50; // in ms set to a few frames
addEventListener("resize",() => {
    clearTimeout(debounceTimer);
    debounceTimer = setTimeout(resizeCanvas,debounceTime);
}
function resizeCanvas(){
    canvas.width = innerWidth;
    canvas.height = innerHeight;
}
</code>```

This ensures that the canvas resizes waits before resizing give subsequent resize event a chance to happen before resizing.

Though this is better than directly handling the resize event it is still a little problematic as the delay is noticeable with the canvas not resizing until after the next frame or two.

Frame synced resize

The best solution I have found is to sync the resize to the animation frames. You can just have the resize event set a flag to indicate that the window has resized. Then in the animation main loop you monitor the flag, if true then resize. This means that the resize is synced with the display rate, and extra resize events are ignored. It also sets a better start time for animations (synced to the frame time)

```<code>var windowResized = true; // flag a resize at start so that its starts
                          // all the stuff needed at startup
addEventListener("resize",() => {windowResized = true});  // needs the {}
function resizeWindow(time){
    windowResized = false; // clear the flag
    canvas.width = innerWidth;
    canvas.height = innerHeight;
    rect.setStart(time); // reset the animation to start at current time;
}
</code>```

Then in the main loop you just check for the windowResized flag and if true call resizeWindow

Animation time

When you use the requestAnimationFrame(callback) function the callback is called with the first argument as time. Time is in ms 1/1000th of a second and accurate to microseconds 1/1,000,000th second. Eg (time > 1000.010) is time since load over 1.00001 seconds.

```<code>function mainLoop(time){ // time in ms since page load.
    requestAnimationFrame(mainLoop);
}
requestAnimationFrame(mainLoop);
</code>```

Example

Thus with all that let's rewrite the animation using controllers and synced resize events.

To highlight the usefulness of timed animations and controllers I have added two extra waveforms sin and sinTri

Also I have the original animation that will show how it slowly goes out of sync. All for animation should once every cycle be at the left edge of the canvas. Animation speed is set as a movement speed in pixels per second to match the original approximation of 1 pixel per frame the speeds are set to 60 pixels per second. Though for the sin, and sinTri animation that speed is the average speed, not the instantaneous speed.

requestAnimationFrame(animate); //Starts when ready
var ctx = canvas.getContext("2d"); // get canvas 2D API

// original animation by OP
var x = 0;
var y = 20;
var h = 20;
var w = 20;
var dx = 1;
// Code from OP's question
function theRect() {
   ctx.fillStyle = "lightblue";
   ctx.fillRect(x, y, w, h);
   x += dx;
   if (x + w > canvas.width / 2 || x < 0) {
      dx = -dx;
   }
}

// Alternative solution

// wave forms are cyclic to the second and return a normalised range 0-1
const waveforms = {
    triangle (time) { return Math.abs(2 * (time - Math.floor(time + 0.5))) },
    sin(time) { return Math.cos((time + 0.5) * Math.PI * 2)*0.5 + 0.5 },
    // just for fun the following is a composite of triangle and sin
    // Keeping the output range to 0-1 means that multiplying any controller
    // with another will always keep the value in the range 0-1
    triSin(time) { return waveforms.triangle(time) * waveforms.sin(time) }

}

// object to animate is easier to manage and replicate
const rect1 = {
    controller : waveforms.triangle,
    startTime : -1, // start time if -1 means start time is unknown
    speed : 60, // in pixels per second
    travelDist : canvas.width / 2 - 20,
    colour : "#8F8",
    w : 20,
    h : 20,
    y : 60,
    setStart(time){
        this.startTime = time / 1000;  // convert to seconds
        this.travelDist = (canvas.width / 2) - this.w;
    },
    draw(time){
        var pos = ((time / 1000) - this.startTime); // get animation position in seconds
        pos = (pos * this.speed) / (this.travelDist * 2)
        var x = this.controller(pos) * this.travelDist;
        ctx.fillStyle = this.colour;
        ctx.fillRect(x,this.y,this.w,this.h);
    }
}
// create a second object that uses a sin wave controller

const rect2 = Object.assign({},rect1,{
    colour : "#0C0",
    controller : waveforms.sin,
    y : 100,
})
const rect3 = Object.assign({},rect1,{
    colour : "#F80",
    controller : waveforms.triSin,
    y : 140,
})

// very simple window resize event, just sets flag.
addEventListener("resize",() => { windowResized = true });

var windowResized = true; // will resize canvas on first frame
function resizeCanvas(time){
    canvas.width = innerWidth;  // set canvas size to window inner size
    canvas.height = innerHeight;
    rect1.setStart(time); // restart animation
    rect2.setStart(time); // restart animation
    rect3.setStart(time); // restart animation
    x = 0; // restart the stepped animation

    // fix for stack overflow title bar getting in the way
    y = canvas.height - 4 * 40;
    rect1.y = canvas.height - 3 * 40;
    rect2.y = canvas.height - 2 * 40;
    rect3.y = canvas.height - 1 * 40;

    windowResized = false; // clear the flag
    // resizing the canvas will reset the 2d context so
    // need to setup state
    ctx.font = "16px arial";
}
function drawText(text,y){
    ctx.fillStyle = "black";
    ctx.fillText(text,10,y);
}
function animate(time){ // high resolution time since  page load in millisecond with presision to microseconds
    if(windowResized){  // has the window been resize
        resizeCanvas(time);  // yes than resize for next frame
    }
    ctx.clearRect(0,0,canvas.width,canvas.height);
    drawText("Original animation.",y-5);
    theRect(); // render original animation
    // three example animation using different waveforms
    drawText("Timed triangle wave.",rect1.y-5);
    rect1.draw(time); // render using timed animation
    drawText("Timed sin wave.",rect2.y-5);
    rect2.draw(time); // render using timed animation
    drawText("Timed sin*triangle wave.",rect3.y-5);
    rect3.draw(time); // render using timed animation
    ctx.lineWidth = 2;
    ctx.strokeRect(1,1,canvas.width - 2,canvas.height - 2);
    requestAnimationFrame(animate);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>canvas {
  position : absolute;
  top : 0px;
  left : 0px;
}</code>```

<canvas id="canvas"></canvas>```

Body:
I am trying to reset my rectangle animation from the starting point when I resize the browser, the code is like this:

/*from basic setup*/
canvas = document.getElementById("myCanvas");
canvas.height = window.innerHeight;
canvas.width = window.innerWidth;
ctx = canvas.getContext("2d");

/*the "resize" event and the reset function should be triggered */
window.addEventListener("resize",function(){
     canvas.height = window.innerHeight;
     canvas.width = window.innerWidth;
     //cancelAnimationFrame(timeID)
     //theRect();
});

/*drawing the rectangle*/
var x = 0,y = canvas.height - 100,w = 100, h = 100,dx=1;

function theRect(){
 ctx.fillStyle = "lightblue";
 ctx.fillRect(x,y,w,h)
 x+=dx;
 if(x+w>canvas.width/2 || x<0){
    dx=-dx;
 }
}

/*start animation*/

function animate(){
    ctx.clearRect(0,0,canvas.width,canvas.height);
    theRect();
    requestAnimationFrame(animate);

}
//var timeID = requestAnimationFrame(animate)

animate();

I was thinking if each time the browser resized, the rectangle has to be reset to the starting point asctx.fillRect(0,canvas.height-100,100,100)and continue its animation.

So my original approach to solve this is using cancelAnimationFrame()this method to kill the animation first and calling this function again within my eventlistener so each time the event was fired, the animation will stop and run again.

but cancellAnimationFrame()function requires the target animation timeID, and there is no way to track this timeID inside my animate()function since if I am calling var timeID = requestionAnimationFrame(animate)it will come to huge lag spikes on my browser

just the more I want to modify to more I become to loss with this, so my questions are:

1, is this wise to use cancelAnimationFrame here as the first step to reset my animation?

2, is there any other good way to achieve this "reset" purpose?

Could someone please help me with this? thanks in advance.

Body:
Animation

Animation is best handled with the system time or page time with a single time variable holding the start time of the animation, and the current animation position being found by subtracting the start time from the current time.

Iterative animation

This will mean that the way you animate has to change as iterative animations do not lend themselves to conditional branching as you have done with...

// Code from OP's question
function theRect() {
   ctx.fillStyle = "lightblue";
   ctx.fillRect(x, y, w, h);
   x += dx;
   if (x + w > canvas.width / 2 || x < 0) {
      dx = -dx;
   }
}

The above works well if timing is not important, but you can not find the position at any particular point in time as you need to iterate the positions in between. Also any frames dropped will change the speed of the animated object and over time the position becomes indeterminate in respect to time.

Time and controllers.

The alternative is to use controllers to animate. Controllers are just functions the produce shaped output depending on a input. This is how most CSS animation is done, with controllers such as easeIn, easeOut, and dozens more. Animation controls can be fixed time (only play once over a fixed amount of time), they have a start time and an end time, or they can be cyclic having a fixed period. Controllers can also easily integrate keyframed animation.

Controllers are very powerful and should be in every game/animation coders knowledge set.

Cyclic triangle waveform

For this animation a cyclic triangle controller will suit best to mimic the animation you have.
The above image is from Desmos calculator and shows the triangle function over time (x axis is time). All controllers have a frequency of 1 and an amplitude of 1.

The controller as a Javascript function

// waveforms are cyclic to the second and return a normalised range 0-1
const waveforms = {
    triangle (time) { return Math.abs(2 * (time - Math.floor(time + 0.5))) },
}

Now you can get the position of the rectangle as a function of time. All you need is the the start time, the current time, the speed in pixels of the object, and the distance it travels.

I have created an object to define the rectangle and animation parameters

const rect = {
    startTime : -1, // start time if -1 means start time is unknown
    speed : 60, // in pixels per second
    travelDist : canvas.width / 2 - 20,
    colour : "#8F8",
    w : 20,
    h : 20,
    y : 100,
    setStart(time){
        this.startTime = time / 1000;  // convert to seconds
        this.travelDist = (canvas.width / 2) - this.w;
    },
    draw(time){
        var pos = ((time / 1000) - this.startTime); // get animation position in seconds
        pos = (pos * this.speed) / (this.travelDist * 2)
        var x = waveforms.triangle(pos) * this.travelDist;
        ctx.fillStyle = this.colour;
        ctx.fillRect(x,this.y,this.w,this.h);
    }
}

So once the start time is set you can find the position of the rectangle at any time by just providing the current time

This is a simple animation and the position of the rectangle can also be calculated as a function of time.

 rect.draw(performance.now());  // assumes start time has been set

Resizing

Resize events can be problematic as they will fire as often as the mouse sample rate which can be many more times than the frame rate. The result is code being run many more times than is necessary, increasing GC hits (due to canvas resizing), reduced mouse capture rates (mouse events are dropped with subsequent events providing the missing data) making the window resize seem sluggish.

Debounced events

The common way to battle this problem has been to use a debounced resize event handler. This is simply means that the actual resize event is delayed by a small amount of time. If in the debounce period another resize event is fired the current scheduled resize is canceled and another is scheduled.

var debounceTimer;  // handle to timeout
const debounceTime = 50; // in ms set to a few frames
addEventListener("resize",() => {
    clearTimeout(debounceTimer);
    debounceTimer = setTimeout(resizeCanvas,debounceTime);
}
function resizeCanvas(){
    canvas.width = innerWidth;
    canvas.height = innerHeight;
}

This ensures that the canvas resizes waits before resizing give subsequent resize event a chance to happen before resizing.

Though this is better than directly handling the resize event it is still a little problematic as the delay is noticeable with the canvas not resizing until after the next frame or two.

Frame synced resize

The best solution I have found is to sync the resize to the animation frames. You can just have the resize event set a flag to indicate that the window has resized. Then in the animation main loop you monitor the flag, if true then resize. This means that the resize is synced with the display rate, and extra resize events are ignored. It also sets a better start time for animations (synced to the frame time)

var windowResized = true; // flag a resize at start so that its starts
                          // all the stuff needed at startup
addEventListener("resize",() => {windowResized = true});  // needs the {}
function resizeWindow(time){
    windowResized = false; // clear the flag
    canvas.width = innerWidth;
    canvas.height = innerHeight;
    rect.setStart(time); // reset the animation to start at current time;
}

Then in the main loop you just check for the windowResized flag and if true call resizeWindow

Animation time

When you use the requestAnimationFrame(callback) function the callback is called with the first argument as time. Time is in ms 1/1000th of a second and accurate to microseconds 1/1,000,000th second. Eg (time > 1000.010) is time since load over 1.00001 seconds.

function mainLoop(time){ // time in ms since page load.
    requestAnimationFrame(mainLoop);
}
requestAnimationFrame(mainLoop);

Example

Thus with all that let's rewrite the animation using controllers and synced resize events.

To highlight the usefulness of timed animations and controllers I have added two extra waveforms sin and sinTri

Also I have the original animation that will show how it slowly goes out of sync. All for animation should once every cycle be at the left edge of the canvas. Animation speed is set as a movement speed in pixels per second to match the original approximation of 1 pixel per frame the speeds are set to 60 pixels per second. Though for the sin, and sinTri animation that speed is the average speed, not the instantaneous speed.

requestAnimationFrame(animate); //Starts when ready
var ctx = canvas.getContext("2d"); // get canvas 2D API

// original animation by OP
var x = 0;
var y = 20;
var h = 20;
var w = 20;
var dx = 1;
// Code from OP's question
function theRect() {
   ctx.fillStyle = "lightblue";
   ctx.fillRect(x, y, w, h);
   x += dx;
   if (x + w > canvas.width / 2 || x < 0) {
      dx = -dx;
   }
}

// Alternative solution

// wave forms are cyclic to the second and return a normalised range 0-1
const waveforms = {
    triangle (time) { return Math.abs(2 * (time - Math.floor(time + 0.5))) },
    sin(time) { return Math.cos((time + 0.5) * Math.PI * 2)*0.5 + 0.5 },
    // just for fun the following is a composite of triangle and sin
    // Keeping the output range to 0-1 means that multiplying any controller
    // with another will always keep the value in the range 0-1
    triSin(time) { return waveforms.triangle(time) * waveforms.sin(time) }

}

// object to animate is easier to manage and replicate
const rect1 = {
    controller : waveforms.triangle,
    startTime : -1, // start time if -1 means start time is unknown
    speed : 60, // in pixels per second
    travelDist : canvas.width / 2 - 20,
    colour : "#8F8",
    w : 20,
    h : 20,
    y : 60,
    setStart(time){
        this.startTime = time / 1000;  // convert to seconds
        this.travelDist = (canvas.width / 2) - this.w;
    },
    draw(time){
        var pos = ((time / 1000) - this.startTime); // get animation position in seconds
        pos = (pos * this.speed) / (this.travelDist * 2)
        var x = this.controller(pos) * this.travelDist;
        ctx.fillStyle = this.colour;
        ctx.fillRect(x,this.y,this.w,this.h);
    }
}
// create a second object that uses a sin wave controller

const rect2 = Object.assign({},rect1,{
    colour : "#0C0",
    controller : waveforms.sin,
    y : 100,
})
const rect3 = Object.assign({},rect1,{
    colour : "#F80",
    controller : waveforms.triSin,
    y : 140,
})

// very simple window resize event, just sets flag.
addEventListener("resize",() => { windowResized = true });

var windowResized = true; // will resize canvas on first frame
function resizeCanvas(time){
    canvas.width = innerWidth;  // set canvas size to window inner size
    canvas.height = innerHeight;
    rect1.setStart(time); // restart animation
    rect2.setStart(time); // restart animation
    rect3.setStart(time); // restart animation
    x = 0; // restart the stepped animation

    // fix for stack overflow title bar getting in the way
    y = canvas.height - 4 * 40;
    rect1.y = canvas.height - 3 * 40;
    rect2.y = canvas.height - 2 * 40;
    rect3.y = canvas.height - 1 * 40;

    windowResized = false; // clear the flag
    // resizing the canvas will reset the 2d context so
    // need to setup state
    ctx.font = "16px arial";
}
function drawText(text,y){
    ctx.fillStyle = "black";
    ctx.fillText(text,10,y);
}
function animate(time){ // high resolution time since  page load in millisecond with presision to microseconds
    if(windowResized){  // has the window been resize
        resizeCanvas(time);  // yes than resize for next frame
    }
    ctx.clearRect(0,0,canvas.width,canvas.height);
    drawText("Original animation.",y-5);
    theRect(); // render original animation
    // three example animation using different waveforms
    drawText("Timed triangle wave.",rect1.y-5);
    rect1.draw(time); // render using timed animation
    drawText("Timed sin wave.",rect2.y-5);
    rect2.draw(time); // render using timed animation
    drawText("Timed sin*triangle wave.",rect3.y-5);
    rect3.draw(time); // render using timed animation
    ctx.lineWidth = 2;
    ctx.strokeRect(1,1,canvas.width - 2,canvas.height - 2);
    requestAnimationFrame(animate);
}

canvas {
  position : absolute;
  top : 0px;
  left : 0px;
}

<canvas id="canvas"></canvas>


问:
Where can i download the src jar for playframework
Sorry, I just don't know where to get this src from. I'm not familiar with github at all - is there a button that makes a src jar for me to download?</p>

答:
SBT

Downloading of the source jar, as well as Javadoc, can be forced by withSources() and withJavadoc() definitions, like

```<code>addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.5.15" withSources() withJavadoc())
</code>```

The more information in the documentation: http://www.scala-sbt.org/0.13/docs/Library-Management.html#Download+Sources

Eclipse

The eclipse plugin can be forced to download all source files by specifying with-source flag:

```<code>[my-first-app] $ eclipse with-source=true
</code>```

More information here: https://www.playframework.com/documentation/2.5.x/IDE#Generate-configuration

GitHub repository

You can always download the source from the GitHub repository, but it will not be the jar file.

Body:
SBT

Downloading of the source jar, as well as Javadoc, can be forced by withSources() and withJavadoc() definitions, like

addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.5.15" withSources() withJavadoc())

The more information in the documentation: http://www.scala-sbt.org/0.13/docs/Library-Management.html#Download+Sources

Eclipse

The eclipse plugin can be forced to download all source files by specifying with-source flag:

[my-first-app] $ eclipse with-source=true

More information here: https://www.playframework.com/documentation/2.5.x/IDE#Generate-configuration

GitHub repository

You can always download the source from the GitHub repository, but it will not be the jar file.


问:
Get the file path from the selected object in indesign
How can I get the file path from the selected object in Adobe Indesign?

Edit: I'm using InDesign CS5 (7.0) Object Model

My user should be able to select an object in Indesign (i.e. a linked file object) and then call a script upon it that edits and saves the linked file.
(We have hundresds of .ai files linked that are created by buggy software and need to replace wrongly embedded fonts in some of the .ai files.)

I tried things like

```<code>var myObj = app.selection[0];
myFilePath = myObj.filePath;
or
myFilePath = myObj.itemLink.assetURL;
</code>```

and that did not work. How can I get, in terms of object hierarchy, from the current selection to the string that is the filepath. Selection > Story > Link > Path-property?

Thank you in advance!
Kind regards, Stefan

答:
myFilePath = myObj.itemLink.filePath;```

But you may consider an illustrator script to proceed all the files in one shot.

Body:
How can I get the file path from the selected object in Adobe Indesign?

Edit: I'm using InDesign CS5 (7.0) Object Model

My user should be able to select an object in Indesign (i.e. a linked file object) and then call a script upon it that edits and saves the linked file.
(We have hundresds of .ai files linked that are created by buggy software and need to replace wrongly embedded fonts in some of the .ai files.)

I tried things like

var myObj = app.selection[0];
myFilePath = myObj.filePath;
or
myFilePath = myObj.itemLink.assetURL;

and that did not work. How can I get, in terms of object hierarchy, from the current selection to the string that is the filepath. Selection > Story > Link > Path-property?

Thank you in advance!
Kind regards, Stefan

Body:
myFilePath = myObj.itemLink.filePath;

But you may consider an illustrator script to proceed all the files in one shot.


问:
Angular 2 Communication over a service without using a Subject
I am wondering if I could solve the following scenario without a Subject. I have two components: The first component creates a hero and the other component displays a hero. Those components communicate over a service. Currently I have the following solution:

Hero Creation

```<code>@Component({
  selector: 'hero-creation',
  ....
})
export class HeroCreation{

  constructor(private heroSercice: HeroService){
  }

  onClick(){
     this.heroSercice.addHero();
  }
}
</code>```

Hero Service

```<code>@Injectable()
export class HeroService {
public hero$: Subject<string> = new Subject<string>();

  constructor() {
  }

  public addHero(hero: string): void {
    this.hero$.next(hero);
  }
}
</code>```

Hero Display

```<code>@Component({
selector: 'hero-display',
....
})
export class HeroDisplay{

  constructor(private heroSercice: HeroService){
    //Use async pipe in template to display the hero
    this.heros$ = this.heroSercice.hero$
  }
}
</code>```

The goal would be to implement the same feature just with plain Observables without using a subject.

答:
This is a use case for a subject.

The Subject class inherits both Observable and Observer, in the sense that it is both an observer and an observable.

After hero$ observable was created, new values should be added to it somehow. And they should be added through observer. Without a subject, an observer has to be exposed manually in order to reach it:

```<code>protected _heroObserver: Observer<string>;
public hero$: Observable<string> = Observable.create<string>(observer => {
    this._heroObserver = observer;
});
...
public addHero(hero: string): void {
    this._heroObserver.next(hero);
}
</code>```

And this is exactly what subjects are supposed to do. Since addHero acts as a setter, exposing a subject as public property breaks encapsulation. In order to preserve encapsulation it is possible to expose only hero$ observable instead:

```<code>protected _heroSubject: Subject<string> = new Subject<string>();
public hero$: Observable<string> = this._heroSubject.asObservable();
...
public addHero(hero: string): void {
    this._heroSubject.next(hero);
}
</code>```

Body:
I am wondering if I could solve the following scenario without a Subject. I have two components: The first component creates a hero and the other component displays a hero. Those components communicate over a service. Currently I have the following solution:

Hero Creation

@Component({
  selector: 'hero-creation',
  ....
})
export class HeroCreation{

  constructor(private heroSercice: HeroService){
  }

  onClick(){
     this.heroSercice.addHero();
  }
}

Hero Service

@Injectable()
export class HeroService {
public hero$: Subject<string> = new Subject<string>();

  constructor() {
  }

  public addHero(hero: string): void {
    this.hero$.next(hero);
  }
}

Hero Display

@Component({
selector: 'hero-display',
....
})
export class HeroDisplay{

  constructor(private heroSercice: HeroService){
    //Use async pipe in template to display the hero
    this.heros$ = this.heroSercice.hero$
  }
}

The goal would be to implement the same feature just with plain Observables without using a subject.

Body:
This is a use case for a subject.

The Subject class inherits both Observable and Observer, in the sense that it is both an observer and an observable.

After hero$ observable was created, new values should be added to it somehow. And they should be added through observer. Without a subject, an observer has to be exposed manually in order to reach it:

protected _heroObserver: Observer<string>;
public hero$: Observable<string> = Observable.create<string>(observer => {
    this._heroObserver = observer;
});
...
public addHero(hero: string): void {
    this._heroObserver.next(hero);
}

And this is exactly what subjects are supposed to do. Since addHero acts as a setter, exposing a subject as public property breaks encapsulation. In order to preserve encapsulation it is possible to expose only hero$ observable instead:

protected _heroSubject: Subject<string> = new Subject<string>();
public hero$: Observable<string> = this._heroSubject.asObservable();
...
public addHero(hero: string): void {
    this._heroSubject.next(hero);
}


问:
How to update localizable.strings from app by code?
I want to be able to update localized strings by code from the app. What I actually want to do is to make changes to the localization on a server and then let the iPhone application fetch updated localization strings from a server and then save them to the localizable.strings file.</p>

答: You can't ! Those files are part of the bundle and can't be updated. You will have to setup the whole translation framework by yourself (which is not that much work) and implement caching using either core data or serialized dictionaries (one for each language I suppose).</p>

ContentLicense: CC BY-SA 2.5


问:
Set comboBox to custom display format
I've got a WinForms comboBox that contains a list of "Regions" (a custom class I've set up). Each Region has properties Name, Abbreviation, etc. I know I can set the comboBox to comboBox.DisplayMember = "Name";, but I want the display formatting to be "(" + Abbreviation + ") " + Name (e.g. (OR) Oregon).

I know I could create a separate property for this (e.g. DisplayName) and just set the comboBox.DisplayMember = "DisplayName"; but is there another way to do it? Something like comboBox.DisplayMember = "(" + Abbreviation + ") " + Name; or whatever?

答:
This is quite old, but I struggled to find why the Format event was not fired.

You also need to set ComboBox.FormattingEnabled to true in order to get the event invoked and used.

Title: Set comboBox to custom display format


问:
Configuring uploading images in JCE
Within JCE, how can I limit the images displayed in a gallery and save the uploaded image in specific director (say, YEAR/DAY/) so that images would organized by date?

答: Add the $id or similar that is unique to the user to the upload folder/path in the settings.</p>

ContentLicense: CC BY-SA 4.0

Title: Configuring uploading images in JCE


问:
Matplotlib: IndexError: too many indices for array
I m trying to plot the numpy array with scatter function. Below is the code:
at line mtp.scatter, i get the index error.

numpy array is [ 1.   1.   3.   3.   1.1  1.1  1.3  1.3]

Corresponding color is ['red', 'green', 'red', 'red']

Error message:
mtp.scatter(X_traintest[:,0],X_traintest[:,1],s=170,c=Y_colorset[:])

IndexError: too many indices for array

```<code>X_traintest=np.array([[]])
X_traintest=np.append(X_traintest, X_trainset)

num1=len(X_trainset)
num2=len(X_testset)
for i in range (num2):
    X_traintest=np.append(X_traintest,X_testset[i], axis=0)
    emptarray=np.zeros(num1)
    for j in range (num1):
        emptarray[j]=mindist(X_testset[i], X_trainset[j])

        print emptarray
    min_index=np.argmin(emptarray)

    Y_colorset.append(Y_colorset[min_index])
    print X_traintest
    print Y_colorset

mtp.figure()
mtp.scatter(X_traintest[:,0],X_traintest[:,1],s=170,c=Y_colorset[:])
mtp.show()
</code>```

答:
This error arises when your input sizes are inconsistent.

Check the length of all of your inputs, namely

X_traintest[:,0]

X_traintest[:,1]

Y_colorset[:]

Also, check whether each of the above expressions are the same in dimension (1D)

Body:
I m trying to plot the numpy array with scatter function. Below is the code:
at line mtp.scatter, i get the index error.

numpy array is [ 1.   1.   3.   3.   1.1  1.1  1.3  1.3]

Corresponding color is ['red', 'green', 'red', 'red']

Error message:
mtp.scatter(X_traintest[:,0],X_traintest[:,1],s=170,c=Y_colorset[:])

IndexError: too many indices for array

X_traintest=np.array([[]])
X_traintest=np.append(X_traintest, X_trainset)

num1=len(X_trainset)
num2=len(X_testset)
for i in range (num2):
    X_traintest=np.append(X_traintest,X_testset[i], axis=0)
    emptarray=np.zeros(num1)
    for j in range (num1):
        emptarray[j]=mindist(X_testset[i], X_trainset[j])

        print emptarray
    min_index=np.argmin(emptarray)

    Y_colorset.append(Y_colorset[min_index])
    print X_traintest
    print Y_colorset

mtp.figure()
mtp.scatter(X_traintest[:,0],X_traintest[:,1],s=170,c=Y_colorset[:])
mtp.show()


问:
Get the columns that were actually updated to a different value?
I'm running something like this:

```<code>cursor.execute(
    '''
    UPDATE my_table
    SET name=%s, about=%s, title=%s
    WHERE id=%s
    ''',
    (name, about, title, id_)
)
</code>```

Which is guaranteed to only update one row, since it's doing the update based on the id primary key.

However,  most of the time only one of the fields actually changes, i.e. the about and title are "updated" to the same value they were already, and only name has actually changed.

How can I get which of the columns actually changed? This is needed to log every individual change.

答:
you can select values before update and using RETURNING * compare values in final query, like here:

```<code>t=# create table m1 (i int, e int);
CREATE TABLE
Time: 1.855 ms
t=# insert into m1 select 1,2;
INSERT 0 1
Time: 1.037 ms
t=# begin;
BEGIN
t=# with o as (select * from m1 where i=1)
,u as (update m1 set e=3 where i=1 returning *)
select * from o
join u on o.i = u.i
;
 i | e | i | e
---+---+---+---
 1 | 2 | 1 | 3
(1 row)
</code>```

so you can put logic against u.e <> o.e or alike

Body:
I'm running something like this:

cursor.execute(
    '''
    UPDATE my_table
    SET name=%s, about=%s, title=%s
    WHERE id=%s
    ''',
    (name, about, title, id_)
)

Which is guaranteed to only update one row, since it's doing the update based on the id primary key.

However,  most of the time only one of the fields actually changes, i.e. the about and title are "updated" to the same value they were already, and only name has actually changed.

How can I get which of the columns actually changed? This is needed to log every individual change.

Body:
you can select values before update and using RETURNING * compare values in final query, like here:

t=# create table m1 (i int, e int);
CREATE TABLE
Time: 1.855 ms
t=# insert into m1 select 1,2;
INSERT 0 1
Time: 1.037 ms
t=# begin;
BEGIN
t=# with o as (select * from m1 where i=1)
,u as (update m1 set e=3 where i=1 returning *)
select * from o
join u on o.i = u.i
;
 i | e | i | e
---+---+---+---
 1 | 2 | 1 | 3
(1 row)

so you can put logic against u.e <> o.e or alike


问:
How to display only one text box at a time and click to next display next input field
I have three fields and one next button. I have to display each field one by one after clicking on next button. Means I have to display only one field at a time.
For example. First text box displaying with next button after clicked on next button then display a second text box with next button same on third one but this time no next button. It will display submit button. Would you help me out in this?

.steps{
  max-width:500px;
  height:auto;
  margin:0 auto;
  padding:70px 0;
  background:#ffffff;
  border:1px solid #e1e8f2;
  position:relative;
  text-align:center;
}
label
{
  display: block;
}
.field-set
{
  text-align: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="steps">
  <p class="form_title">Please Fill The field Bellow</p>
  <form action="#" method="post" autocomplete="off">

    <div class="field-set">
    <label>name</label>
      <input type="text"  id="name" name="name" placeholder="Enter You Name"/>
    </div>

      <div  class="field-set">
      <label>Email</label>
        <input type="email" id="email" name="email" placeholder="Enter You Email"/>
      </div>

      <div  class="field-set">
      <label>mobile</label>
        <input type="text"  id="mob" name="mob" placeholder="Enter Your mobile no"/>
      </div>

      <div  class="field-set">
        <input type="submit" name="next" value="next" id="click_next">
      </div>

  </form>
</div></code>```

答:
Try something like this:

$(document).ready(function(){
  var step = 1;
  $('#btn').click(function(){
    if( step < 5 )
    {
      $('.txt').eq(step - 1).hide();
      $('.txt').eq(step).show();
      step++;
    }
    else
    { /*Submit the form here*/ }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input class="txt" placeholder="1">
<input class="txt" style="display:none;" placeholder="2">
<input class="txt" style="display:none;" placeholder="3"><input class="txt" style="display:none;" placeholder="4">
<input class="txt" style="display:none;" placeholder="5">

<input type="button" value="Next" id="btn"></code>```

Body:
I have three fields and one next button. I have to display each field one by one after clicking on next button. Means I have to display only one field at a time.
For example. First text box displaying with next button after clicked on next button then display a second text box with next button same on third one but this time no next button. It will display submit button. Would you help me out in this?

.steps{
  max-width:500px;
  height:auto;
  margin:0 auto;
  padding:70px 0;
  background:#ffffff;
  border:1px solid #e1e8f2;
  position:relative;
  text-align:center;
}
label
{
  display: block;
}
.field-set
{
  text-align: left;
}

Please Fill The field Bellow

  <form action="#" method="post" autocomplete="off">

    name
      <input type="text"  id="name" name="name" placeholder="Enter You Name"/>

      Email
        <input type="email" id="email" name="email" placeholder="Enter You Email"/>

      mobile
        <input type="text"  id="mob" name="mob" placeholder="Enter Your mobile no"/>

        <input type="submit" name="next" value="next" id="click_next">

  </form>

Body:
Try something like this:

$(document).ready(function(){
  var step = 1;
  $('#btn').click(function(){
    if( step < 5 )
    {
      $('.txt').eq(step - 1).hide();
      $('.txt').eq(step).show();
      step++;
    }
    else
    { /*Submit the form here*/ }
  });
});

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

<input class="txt" placeholder="1">
<input class="txt" style="display:none;" placeholder="2">
<input class="txt" style="display:none;" placeholder="3"><input class="txt" style="display:none;" placeholder="4">
<input class="txt" style="display:none;" placeholder="5">

<input type="button" value="Next" id="btn">


问:
A good thread pool queue size
Ok , let's assume we have a thread pool with a "kind of" dynamic flat container, which has a max capacity of x since the memory is on the stack to improve performance.

in minimal code (I don't want to get to specific):

```<code>template <int32 QSIZE, int32 PSIZE> class ThreadPool
{
public:
ThreadPool()
{
    for (int32 i = 0; PSIZE > i; ++i)
    {
        m_Workers.push(Thread(thread_main, m_Queue, m_Signal, m_IsRunning));
    }
}

~ThreadPool()
{
    //Wait and destroy all threads
}

void run(Task task)
{
    m_Queue.push(task);
    m_Signal.wake_all();
}

private:
    FlatVector<Thread, PSIZE> m_Workers; //PSIZE --> max capacity
    FlatQueue<Task, QSIZE>    m_Queue; //QSIZE --> max capacity
    ConditionVariable         m_Signal;
    AtomicBool                m_IsRunning;
};
</code>```

the class Task is an implementation for an inplace function with bound parameters and move semantic.

The FlatVector is a vector with memory on the stack and a max capacity of PSIZE (pool size).

the FlatQueue is basically the same construct as a queue with a capacity of QSIZE (queue size)

One Task has a maximum size of 512 bit.

Is there a good rule of thumb how large a thread pool task queue should grow in the worst case? (If possible with consideration of the given example, if not possible a guess on regular thread pools is fine as well.)

In the most cases my pool is running with 8 threads since that's my core count and the application which is using the pool can take a decent advantage of a higher thread count. (It's a simple physic simulation)

Would it be a better way to package tasks together into task bundles (As long as they wouldn't exceed the 512 bit together, considering this example.) or should I just skip the calculation which can't be placed in this frame anymore and calculate them in the next one? The physical calculation will be calculated for 2 frames then.

Usualy I am choosing a queue size something between 64 - 128 tasks which is fine (at least performance wise) but actually it feels like 128 tasks in a pool at the same time are a bit much to me and I don't want to waste this amount of memory.

Sometimes I am exceeding the limit of 64 tasks in the pool at the same time if I set the pool under high load. (that's why I decided to increase the pool size in the first place.)

Adding a single 512 bit task (worst case) to my pool takes something between 1,02 and 1,3 e power(-7) seconds on my system.

Doing the same with a "regular" thread pool and "regular" function bindings with heap allocation and move semantic takes something between 1.8 - 2.3 e power(-5) seconds, what shows there is a real benefit in using the stack in this case.

答:
A general answer to the question:

For a workload that runs constantly without waiting on other resources, logically, the maximum number of threads should be the same as the number of physical processors (or twice that if the processor has hyper-threading).

For a workload that waits on other resources (e.g. waiting for a socket to connect), you will want to compensate for this latency to get maximum throughput, by having more threads than logical processors (dependent on your wait time). Hundreds of threads would be fine if most are blocked. You might consider separating out the latency bound portion of the task and the CPU intensive part of the task to fully load balance the workload each having a different thread count.

You could empirically determine your optimum thread count assuming you want to maximise throughput.

An interesting solution to software self tuning the thread count could be achieved by using control theory. The book Feedback Control for Computer Systems by Philipp K. Janert is a good reference on this.

Title: A good thread pool queue size

Body:
Ok , let's assume we have a thread pool with a "kind of" dynamic flat container, which has a max capacity of x since the memory is on the stack to improve performance.

in minimal code (I don't want to get to specific):

template <int32 QSIZE, int32 PSIZE> class ThreadPool
{
public:
ThreadPool()
{
    for (int32 i = 0; PSIZE > i; ++i)
    {
        m_Workers.push(Thread(thread_main, m_Queue, m_Signal, m_IsRunning));
    }
}

~ThreadPool()
{
    //Wait and destroy all threads
}

void run(Task task)
{
    m_Queue.push(task);
    m_Signal.wake_all();
}

private:
    FlatVector<Thread, PSIZE> m_Workers; //PSIZE --> max capacity
    FlatQueue<Task, QSIZE>    m_Queue; //QSIZE --> max capacity
    ConditionVariable         m_Signal;
    AtomicBool                m_IsRunning;
};

the class Task is an implementation for an inplace function with bound parameters and move semantic.

The FlatVector is a vector with memory on the stack and a max capacity of PSIZE (pool size).

the FlatQueue is basically the same construct as a queue with a capacity of QSIZE (queue size)

One Task has a maximum size of 512 bit.

Is there a good rule of thumb how large a thread pool task queue should grow in the worst case? (If possible with consideration of the given example, if not possible a guess on regular thread pools is fine as well.)

In the most cases my pool is running with 8 threads since that's my core count and the application which is using the pool can take a decent advantage of a higher thread count. (It's a simple physic simulation)

Would it be a better way to package tasks together into task bundles (As long as they wouldn't exceed the 512 bit together, considering this example.) or should I just skip the calculation which can't be placed in this frame anymore and calculate them in the next one? The physical calculation will be calculated for 2 frames then.

Usualy I am choosing a queue size something between 64 - 128 tasks which is fine (at least performance wise) but actually it feels like 128 tasks in a pool at the same time are a bit much to me and I don't want to waste this amount of memory.

Sometimes I am exceeding the limit of 64 tasks in the pool at the same time if I set the pool under high load. (that's why I decided to increase the pool size in the first place.)

Adding a single 512 bit task (worst case) to my pool takes something between 1,02 and 1,3 e power(-7) seconds on my system.

Doing the same with a "regular" thread pool and "regular" function bindings with heap allocation and move semantic takes something between 1.8 - 2.3 e power(-5) seconds, what shows there is a real benefit in using the stack in this case.


问:
how can I diff two sections of the same file?
I have a source file with two similar yet subtly different sections.  I'd like to merge the two sections into one subroutine with a parameter that handles the subtle differences, but I need to be sure I'm aware of them all so I don't miss any.

What I usually do in such cases is copy each of the sections to a separate file and then use tkdiff or vimdiff to highlight the differences.  Is there any way to skip the intermediate files and just diff two parts of the same file?

答: Any diff tool that lets you manually adjust the alignment will do the job.  Diffuse (http://diffuse.sourceforge.net/) is my favourite and it also lets you manually adjust the alignment.</p>

OwnerDisplayName: Nathan Fellman

LastEditorDisplayName: Nathan Fellman

OwnerDisplayName: Derrick Moser


问:
PHP: Change only a portion of a URL string?
I’m working on a small hoppy project where I want to replace a specific page on a URL. Let me explain:

I’ve got the URL

http://www.example.com/article/paragraph/low/

I want to keep the URL but replace the last segment /low/ with /high/ so the new URL is:

http://www.example.com/article/paragraph/high/

I’ve tried different explode, split and splice but I just can’t seem to wrap my head around it and make it work. I can change the entire URL but not just the last segment and save it in a new variable.

I’m pretty confidence that it is a pretty straight forward case but I’ve never worked that much with arrays / string-manipulation in PHP so I’m pretty lost.

I guess that I have to first split the URL up in segments, using the "\" to separate it (I tried that but have problems by using explode("\", $string)) and then replace the last \low\ with \high\

Hope someone could help or point me in the right direction to what methods to use for doing this.

Sincere

Mestika

答: Use parse_url to split the URL into its components, modify them as required (here you can use explode to split the path into its segments), and then rebuild the URL with http_build_url.


问:
Execute Command SwitchCell OnChanged in a ListView
I'm fairly new to Xamarin.Forms and tried googling my question.
I have a ListView of SwitchCells, the ItemsSource is a Collection of a simple Data-Class.

Now when I change the Switch's state in the SwitchCell I want to have a Method being called...that should not be the problem, but I can't figure out how I know which SwitchCell, or in other words which Instance of the DataClass, which Item was switched.

I expect it to be something like the code I commented, but am really not sure...also I think that I'm mixing up Commands and Methods here....

My XAML:

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="slwAppTutorial.InterestsList">
  <StackLayout>
    <ListView x:Name="interestList">
      <ListView.ItemTemplate>
        <DataTemplate>
          <SwitchCell Text="{Binding Text}" On="false" > <!--OnChanged="{Binding something}" -->
          </SwitchCell>
        </DataTemplate>
      </ListView.ItemTemplate>
    </ListView>
    <Button x:Name="submit" Text="Bestätigen"></Button>
  </StackLayout>
</ContentPage>
</code>```

My CodeBehind file:

```<code>namespace slwAppTutorial
{
public partial class InterestsList : ContentPage
{
    //InterestListManager manager;
    List<InterestsItem> myList = new List<InterestsItem>();

    public InterestsList()
    {

        InitializeComponent();

        InterestsItem myInterest = new InterestsItem() { Id = "1234", Text = "Volleyball", Kind = "Sport" };
        for (int i=0; i < 25; i++) { myList.Add(myInterest); }
        //manager = InterestListManager.DefaultManager;

// My Expected Command
// someSwitch.OnChanged+= (sender, args) =>
//            {
//                var selectedItem = args.Item as InterestsItem;
//
//                Do something with my InterestsItem
//
//                DisplayAlert(title: selectedItem.Text, message: selectedItem.Kind, cancel: "OK");
//                if (selectedItem == null) return;
//            };

    protected override async void OnAppearing()
    {
        base.OnAppearing();
        interestList.ItemsSource = myList;
        //await RefreshItems(true, syncItems: false);
    }

    private async Task RefreshItems(bool showActivityIndicator, bool syncItems)
    {
        interestList.ItemsSource = myList; //await manager.GetInterestItemsAsync(syncItems);
    }

}
}
</code>```

答:
There are better ways to do this, using full data binding.

But if you would want to implement it with the code you have now, the value you're looking for is in the sender parameter. The sender will be of type SwitchCell, so cast it and get the BindingContext. The final event will look like this:

```<code>private void Handle_OnChanged(object sender, ToggledEventArgs args)
{
    var selectedItem = ((SwitchCell)sender).BindingContext as Foo;

    DisplayAlert(title: selectedItem.Text, message: selectedItem.Bar.ToString(), cancel: "OK");
}
</code>```

A sample project, similar to your code can be found here.

Body:
I'm fairly new to Xamarin.Forms and tried googling my question.
I have a ListView of SwitchCells, the ItemsSource is a Collection of a simple Data-Class.

Now when I change the Switch's state in the SwitchCell I want to have a Method being called...that should not be the problem, but I can't figure out how I know which SwitchCell, or in other words which Instance of the DataClass, which Item was switched.

I expect it to be something like the code I commented, but am really not sure...also I think that I'm mixing up Commands and Methods here....

My XAML:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="slwAppTutorial.InterestsList">
  <StackLayout>
    <ListView x:Name="interestList">
      <ListView.ItemTemplate>
        <DataTemplate>
          <SwitchCell Text="{Binding Text}" On="false" >
          </SwitchCell>
        </DataTemplate>
      </ListView.ItemTemplate>
    </ListView>
    <Button x:Name="submit" Text="Bestätigen"></Button>
  </StackLayout>
</ContentPage>

My CodeBehind file:

namespace slwAppTutorial
{
public partial class InterestsList : ContentPage
{
    //InterestListManager manager;
    List<InterestsItem> myList = new List<InterestsItem>();

    public InterestsList()
    {

        InitializeComponent();

        InterestsItem myInterest = new InterestsItem() { Id = "1234", Text = "Volleyball", Kind = "Sport" };
        for (int i=0; i < 25; i++) { myList.Add(myInterest); }
        //manager = InterestListManager.DefaultManager;

// My Expected Command
// someSwitch.OnChanged+= (sender, args) =>
//            {
//                var selectedItem = args.Item as InterestsItem;
//
//                Do something with my InterestsItem
//
//                DisplayAlert(title: selectedItem.Text, message: selectedItem.Kind, cancel: "OK");
//                if (selectedItem == null) return;
//            };

    protected override async void OnAppearing()
    {
        base.OnAppearing();
        interestList.ItemsSource = myList;
        //await RefreshItems(true, syncItems: false);
    }

    private async Task RefreshItems(bool showActivityIndicator, bool syncItems)
    {
        interestList.ItemsSource = myList; //await manager.GetInterestItemsAsync(syncItems);
    }

}
}

Body:
There are better ways to do this, using full data binding.

But if you would want to implement it with the code you have now, the value you're looking for is in the sender parameter. The sender will be of type SwitchCell, so cast it and get the BindingContext. The final event will look like this:

private void Handle_OnChanged(object sender, ToggledEventArgs args)
{
    var selectedItem = ((SwitchCell)sender).BindingContext as Foo;

    DisplayAlert(title: selectedItem.Text, message: selectedItem.Bar.ToString(), cancel: "OK");
}

A sample project, similar to your code can be found here.


答:
Is there a good rule of thumb how large a thread pool task queue should grow in the worst case?

I think the right questions to ask are:

How long can a task wait before being evaluated?

Does a new task of a particular type supercede an existing task?

Title: A good thread pool queue size


问:
Only Require input to be filled if other inputs are not filled
I have an ASP.NET application which requires the user to fill in a form to create a new object. It is defined as follows:

```<code>public class Address
    {
        public int ID { get; set; }
        [Required]
        public string AddressLine1 { get; set; }
        public string AddressLine2 { get; set; }
        public string AddressLine3 { get; set; }
        [Required]
        public string City { get; set; }
        public string Postcode { get; set; }

        public string AirportCode { get; set; }
    }
</code>```

The fields AddressLine1 and City are required when filling out the create form. However, a new development has introduced the field AirportCode, which changes the requirements. Basically, if an airport code value is given, no other values are required. If not, the address line 1 and city values are both still required. If the user neglected to fill out any of the form, I would expect all three fields to display an error message until wither the City and AddressLine1 values or the AirportCode value was given, but I can worry asbout the semantics of it later - the important thing is to not let an invalid object get through.

I guess the logic would be:

```<code>if AirportCode OR (AddressLine1 AND City)
</code>```

Here is a small sample of the City input field. It's the default generated by the application:

```<code><div class="form-group">
<label asp-for="City" class="col-md-2 control-label">City</label>
    <div class="col-md-10">
        <input asp-for="City" class="form-control" />
        <span asp-validation-for="City" class="text-danger"></span>
    </div>
</div>
</code>```

Is there a way to go about implementing this without resorting to JavaScript? The form validation has been so neat and easy so far, and I would love to be able to do this through the framework. Thanks.

An afterthought: I may later on want to grey out the other fields if AirportCode started getting filled out. It's not strictly related to validation but it might tie into this?

答:
You would need to write your own custom validation attribute.

Howerver there is a plugin called "ExpressiveAnnotations" which is very easy to use and helps you implement logic into your "DataAnnotations".

```<code>[RequiredIf("AirportCode == null",
    ErrorMessage = "Your error message.")]
public string AddressLine1 { get; set; }

[RequiredIf("AirportCode == null",
    ErrorMessage = "Your error message.")]
public string City { get; set; }

[RequiredIf("City == null")]
[RequiredIf("AddressLine1 == null")]
public string AirportCode { get; set; }
</code>```

If you feel it would be useful for your purposes, more information about ExpressiveAnnotations library can be found here. Client side validation is also supported out of the box.

A small .NET and JavaScript library which provides annotation-based
  conditional validation mechanisms. Given attributes allow to forget
  about imperative way of step-by-step verification of validation
  conditions in many cases. Since fields validation requirements are
  applied as metadata, domain-related code is more condensed.

Body:
I have an ASP.NET application which requires the user to fill in a form to create a new object. It is defined as follows:

public class Address
    {
        public int ID { get; set; }
        [Required]
        public string AddressLine1 { get; set; }
        public string AddressLine2 { get; set; }
        public string AddressLine3 { get; set; }
        [Required]
        public string City { get; set; }
        public string Postcode { get; set; }

        public string AirportCode { get; set; }
    }

The fields AddressLine1 and City are required when filling out the create form. However, a new development has introduced the field AirportCode, which changes the requirements. Basically, if an airport code value is given, no other values are required. If not, the address line 1 and city values are both still required. If the user neglected to fill out any of the form, I would expect all three fields to display an error message until wither the City and AddressLine1 values or the AirportCode value was given, but I can worry asbout the semantics of it later - the important thing is to not let an invalid object get through.

I guess the logic would be:

if AirportCode OR (AddressLine1 AND City)

Here is a small sample of the City input field. It's the default generated by the application:

City

        <input asp-for="City" class="form-control" />

Is there a way to go about implementing this without resorting to JavaScript? The form validation has been so neat and easy so far, and I would love to be able to do this through the framework. Thanks.

An afterthought: I may later on want to grey out the other fields if AirportCode started getting filled out. It's not strictly related to validation but it might tie into this?

Body:
You would need to write your own custom validation attribute.

Howerver there is a plugin called "ExpressiveAnnotations" which is very easy to use and helps you implement logic into your "DataAnnotations".

[RequiredIf("AirportCode == null",
    ErrorMessage = "Your error message.")]
public string AddressLine1 { get; set; }

[RequiredIf("AirportCode == null",
    ErrorMessage = "Your error message.")]
public string City { get; set; }

[RequiredIf("City == null")]
[RequiredIf("AddressLine1 == null")]
public string AirportCode { get; set; }

If you feel it would be useful for your purposes, more information about ExpressiveAnnotations library can be found here. Client side validation is also supported out of the box.

A small .NET and JavaScript library which provides annotation-based
  conditional validation mechanisms. Given attributes allow to forget
  about imperative way of step-by-step verification of validation
  conditions in many cases. Since fields validation requirements are
  applied as metadata, domain-related code is more condensed.


问:
how to get average of certain column values in table
I'm a beginner so I'm not sure whats wrong here. What im trying to achieve is to check if certain cells in a table (column) has numerical values in them and if they do include them in calculating the average value upon losing focus (blur) so that it would kind of be real time.

I'm not sure if calculation function is wrong itself, or if I'm addressing wrong column maybe or trying to insert calculated value in the wrong way. help would be appreciated.

Here is JSfiddle and the code excerpts:
https://jsfiddle.net/NulisDefo/03rn7ew1/5/

table

```<code><table id="myTable" class="table table-inverse">
    <thead id = "headings" class = "thead-default">
      <tr>
        <th>Tabelio Nr.</th>
        <th>Vardas</th>
        <th>Pavardė</th>
        <th>Pareigos</th>
        <th>Bazinė alga, €</th>
        <th>Valandinis atlyginimas, €</th>
        <th>Veiksmai</th>
      </tr>
    </thead>
    <tfoot class = "thead-default">
      <tr>
        <td colspan = "4">Vidurkis</td>
        <!-- <td></td>
        <td></td>
        <td></td> -->
        <td id = "alga">0</td>
        <td id = "valandinis" colspan = "2">0</td>
        <!-- <td></td> -->
      </tr>
    </tfoot>
    <tbody>
      <tr>
        <td>1</td>
        <td>Mark</td>
        <td>Otto</td>
        <td>@mdo</td>
        <td>1000</td>
        <td><input type="button" value="Delete" onclick="deleteRow(this)"></td>
        <td>
          <p class = "btn editbtn"><span class = "fa fa-edit"></span></p>
          <p class = "btn" onclick="deleteRow(this)"><span class = "fa fa-trash"></span></p>
        </td>
      </tr>
      <tr>
        <td>2</td>
        <td>Jacob</td>
        <td>Thornton</td>
        <td>@fat</td>
        <td>2000</td>
        <td>blum</td>
        <td>
          <p class = "btn editbtn"><span class = "fa fa-edit"></span></p>
          <p class = "btn" onclick="deleteRow(this)"><span class = "fa fa-trash"></span></p>
        </td>
      </tr>
      <tr class = "testas">
        <td>3</td>
        <td>Larry</td>
        <td>the Bird</td>
        <td>@twitter</td>
        <td>5000</td>
        <td>blum</td>
        <td>
          <p class = "btn editbtn"><span class = "fa fa-edit"></span></p>
          <p class = "btn" onclick="deleteRow(this)"><span class = "fa fa-trash"></span></p>
        </td>
      </tr>
    </tbody>
  </table>
</code>```

script for calculating and trigger

```<code>$("table").on("blur", "td", function(){
calculate();
} );

function calculate() {
  var sum = 0;
  var counter = 0 //daliklis
  $('#myTable tbody tr td:nth-child(5)').each(function() {
  // $("table tbody tr td:eq(4)").each(function(){
    if (!isNaN(this.value))
    {
      sum += parseFloat($(this).text());
      counter += 1;
    }
    });
    $("#alga").textContent(sum/counter);
};
</code>```

I should probably mention, that prior existing entries can be edited only after pressing edit button.

EDIT: Ok, so apparently all of the solutions work, but the problem is, that if cell is empty, instead of excluding that part from calculation the returned result is NaN

答:
You can use focusout event.

```<code>$("table").on("focusout", "tr", function(){
 calculate();
});
</code>```

I have updated the code like following.

Changed event to focusout for tr. (Because this event listens change made to the contenteditable and in your case tr has contenteditable not the td.

Added class avg in the
footer td which will tell that these columns needs average to
calculate.

Considered avg class in calculation and also updated the logic a bit.

Used jquery's text() method to set and get the text of td.

Check updated fiddle

Body:
I'm a beginner so I'm not sure whats wrong here. What im trying to achieve is to check if certain cells in a table (column) has numerical values in them and if they do include them in calculating the average value upon losing focus (blur) so that it would kind of be real time.

I'm not sure if calculation function is wrong itself, or if I'm addressing wrong column maybe or trying to insert calculated value in the wrong way. help would be appreciated.

Here is JSfiddle and the code excerpts:
https://jsfiddle.net/NulisDefo/03rn7ew1/5/

table

        Tabelio Nr.
        Vardas
        Pavardė
        Pareigos
        Bazinė alga, €
        Valandinis atlyginimas, €
        Veiksmai

        Vidurkis

        0
        0

        1
        Mark
        Otto
        @mdo
        1000
        <input type="button" value="Delete" onclick="deleteRow(this)">

        2
        Jacob
        Thornton
        @fat
        2000
        blum

        3
        Larry
        the Bird
        @twitter
        5000
        blum

script for calculating and trigger

$("table").on("blur", "td", function(){
calculate();
} );

function calculate() {
  var sum = 0;
  var counter = 0 //daliklis
  $('#myTable tbody tr td:nth-child(5)').each(function() {
  // $("table tbody tr td:eq(4)").each(function(){
    if (!isNaN(this.value))
    {
      sum += parseFloat($(this).text());
      counter += 1;
    }
    });
    $("#alga").textContent(sum/counter);
};

I should probably mention, that prior existing entries can be edited only after pressing edit button.

EDIT: Ok, so apparently all of the solutions work, but the problem is, that if cell is empty, instead of excluding that part from calculation the returned result is NaN

Body:
You can use focusout event.

$("table").on("focusout", "tr", function(){
 calculate();
});

I have updated the code like following.

Changed event to focusout for tr. (Because this event listens change made to the contenteditable and in your case tr has contenteditable not the td.

Added class avg in the
footer td which will tell that these columns needs average to
calculate.

Considered avg class in calculation and also updated the logic a bit.

Used jquery's text() method to set and get the text of td.

Check updated fiddle


问:
Is Dart truly parallel or is it concurrent
I have just found about Dart from Google and wanted to know if true parallelism can be obtained using Dart. From what I know my answer would be no because finally it runs just as Javascript(I cannot comment about how it run on the Dart VM) but then why the design decision of introducing async and await keywords?
Will this become something like Erlang?</p>

答:
A Dart application can consist of one or more isolates. Isolates run as threads (other implementations are possible) and run parallel (also on different CPUs). Communication between isolates works with message passing.

Code within a single isolate is single-threaded and there is no parallelism at all. The execution is event-driven. See also https://webdev.dartlang.org/articles/performance/event-loop

async/await is just syntactic sugar to make async code look more like sync code, but it doesn't make code running sync.


问:
file mime type validation if file is uploaded in laravel
I have a file upload field as :

```<code><input class="form-control" type="file" name="image[]" multiple="multiple">
</code>```

This field is optional. User may add file or not.

I want file type validation and I don't want to allow user to add files other than images. This is I have done so far.

```<code>$this->validate($request,[
        'image.*' => 'mimes:jpg,jpeg,png,bmp,tiff |max:4096',
    ],$messages = [
        'mimes' => 'Please insert image only',
    ]);
</code>```

But, when there is no file is uploaded, validation doesn't got passed. Any help appreciated.

答:
As per Laravel 5.8

For file validation using request data for required, mime type & file size check before uploading file:

```<code>$validator = Validator::make($request->all(),[
        'image' => 'required|mimes:jpg,jpeg,png,bmp,tiff |max:4096',
    ],$messages = [
        'mimes' => 'Please insert image only',
        'max'   => 'Image should be less than 4 MB'
    ]);

dd($validator->errors());
</code>```

Note: Don't forget to use Validator Facade

Body:
I have a file upload field as :

<input class="form-control" type="file" name="image[]" multiple="multiple">

This field is optional. User may add file or not.

I want file type validation and I don't want to allow user to add files other than images. This is I have done so far.

$this->validate($request,[
        'image.*' => 'mimes:jpg,jpeg,png,bmp,tiff |max:4096',
    ],$messages = [
        'mimes' => 'Please insert image only',
    ]);

But, when there is no file is uploaded, validation doesn't got passed. Any help appreciated.

Body:
As per Laravel 5.8

For file validation using request data for required, mime type & file size check before uploading file:

$validator = Validator::make($request->all(),[
        'image' => 'required|mimes:jpg,jpeg,png,bmp,tiff |max:4096',
    ],$messages = [
        'mimes' => 'Please insert image only',
        'max'   => 'Image should be less than 4 MB'
    ]);

dd($validator->errors());

Note: Don't forget to use Validator Facade


问:
How is a random number generated at runtime?
Since computers cannot pick random numbers(can they?) how is this random number actually generated. For example in C# we say,

```<code>Random.Next()
</code>```

What happens inside?

答:
Since computers cannot pick random numbers (can they?)

As others have noted, "Random" is actually pseudo-random. To answer your parenthetical question: yes, computers can pick truly random numbers. Doing so is much more expensive than the simple integer arithmetic of a pseudo-random number generator, and usually not required. However there are applications where you must have non-predictable true randomness: cryptography and online poker immediately come to mind.  If either use a predictable source of pseudo-randomness then attackers can decrypt/forge messages much more easily, and cheaters can figure out who has what in their hands.

The .NET crypto classes have methods that give random numbers suitable for cryptography or games where money is on the line. As for how they work: the literature on crypto-strength randomness is extensive; consult any good university undergrad textbook on cryptography for details.

Specialty hardware also exists to get random bits. If you need random numbers that are drawn from atmospheric noise, see www.random.org.

Body:
Since computers cannot pick random numbers(can they?) how is this random number actually generated. For example in C# we say,

Random.Next()

What happens inside?


问:
Amchart Dont show data where value =0
Im working in a graph where data comes from server like Object's Array.

I dont need some data to show in my graph, data where number=0, and i want to know if amchart have some function to dont show this.

Here is an example of the code:

```<code>var data =[
{'number':1, 'date':'11:00-11:59', 'duration': 3},
{'number':2, 'date':'12:00-12:59', 'duration':6},
{'number':4, 'date':'13:00-13:59', 'duration':12},
{'number':8, 'date':'14:00-14:59', 'duration':8},
{'number':0, 'date':'14:00-14:59', 'duration':0}
];

var chart = AmCharts.makeChart("chartdiv", {
"theme": "light",
"type": "serial",
"startDuration": 2,
"dataProvider": data,
"valueAxes": [{
    "id": "number",
    "position": "left",
    "title": "N Llamadas"
},{
    "id": "durationAxis",
    "position": "right",
    "title": "duration"
}],
"graphs": [{
    "balloonText": "[[category]]: <b>[[value]]</b>",
    "fillColorsField": "color",
    "fillAlphas": 1,
    "lineAlpha": 0.1,
    "type": "column",
    "valueField": "number"
},{
    "bullet": "square",
    "bulletBorderAlpha": 1,
    "bulletBorderThickness": 1,
    "dashLengthField": "dashLength",
    "legendValueText": "[[value]]",
    "title": "duration",
    "fillAlphas": 0,
    "valueField": "duration",
    "valueAxis": "durationAxis"
}],
"depth3D": 20,
"angle": 30,
"chartCursor": {
    "categoryBalloonEnabled": false,
    "cursorAlpha": 0,
    "zoomable": false
},
"categoryField": "date",
"categoryAxis": {
    "gridPosition": "start",
    "labelRotation": 0
},
"export": {
    "enabled": true
 }

});
</code>```

In this case i dont want to show the last item of the array because number is 0, i shouldnt create a new array for reasons project.
Thanks in advance

答:
Not showing a graph object when a value is 0 is pretty much impossible without modifying the array due to the bullets of the line chart (you can hide a column using alphaField, but you can't remove the bullet). You can write an init handler that nulls out zero values so that the chart doesn't show the point or column at all upon chart initialization:

```<code>//Nulls out any field that contains a zero, effectively hiding the point/column from the chart.
//Note that the category will still be visible if both points are null unless you null out that category as well.
AmCharts.addInitHandler(function(chart) {
  var valueFields = chart.graphs.map(function(graph) {
    return graph.valueField;
  });
  chart.dataProvider.forEach(function(dataItem) {
    valueFields.forEach(function(valueField) {
      if (dataItem[valueField] === 0) {
        dataItem[valueField] = null;
      }
    })
  })
}, ["serial"]);
</code>```

Note that this will effect the data export (csv, xlsx, json) as well. If you want to re-add those zero values to the data export, you can use the processData callback in the export plugin to modify your data to re-add the zeroes:

```<code>"export": {
    "enabled": true,
     //re-add nulled out values as zeroes for data export:
    "processData": function(data, cfg) {
      var valueFields = this.setup.chart.graphs.map(function(graph) {
        return graph.valueField;
      });
      data.forEach(function(dataItem) {
        valueFields.forEach(function(valueField) {
          if (dataItem[valueField] == null) {
            dataItem[valueField] = 0;
          }
        });
      });
      return data;
    }
 }
</code>```

Demo

Title: Amchart Dont show data where value =0

Body:
Im working in a graph where data comes from server like Object's Array.

I dont need some data to show in my graph, data where number=0, and i want to know if amchart have some function to dont show this.

Here is an example of the code:

var data =[
{'number':1, 'date':'11:00-11:59', 'duration': 3},
{'number':2, 'date':'12:00-12:59', 'duration':6},
{'number':4, 'date':'13:00-13:59', 'duration':12},
{'number':8, 'date':'14:00-14:59', 'duration':8},
{'number':0, 'date':'14:00-14:59', 'duration':0}
];

var chart = AmCharts.makeChart("chartdiv", {
"theme": "light",
"type": "serial",
"startDuration": 2,
"dataProvider": data,
"valueAxes": [{
    "id": "number",
    "position": "left",
    "title": "N Llamadas"
},{
    "id": "durationAxis",
    "position": "right",
    "title": "duration"
}],
"graphs": [{
    "balloonText": "[[category]]: [[value]]",
    "fillColorsField": "color",
    "fillAlphas": 1,
    "lineAlpha": 0.1,
    "type": "column",
    "valueField": "number"
},{
    "bullet": "square",
    "bulletBorderAlpha": 1,
    "bulletBorderThickness": 1,
    "dashLengthField": "dashLength",
    "legendValueText": "[[value]]",
    "title": "duration",
    "fillAlphas": 0,
    "valueField": "duration",
    "valueAxis": "durationAxis"
}],
"depth3D": 20,
"angle": 30,
"chartCursor": {
    "categoryBalloonEnabled": false,
    "cursorAlpha": 0,
    "zoomable": false
},
"categoryField": "date",
"categoryAxis": {
    "gridPosition": "start",
    "labelRotation": 0
},
"export": {
    "enabled": true
 }

});

In this case i dont want to show the last item of the array because number is 0, i shouldnt create a new array for reasons project.
Thanks in advance

Body:
Not showing a graph object when a value is 0 is pretty much impossible without modifying the array due to the bullets of the line chart (you can hide a column using alphaField, but you can't remove the bullet). You can write an init handler that nulls out zero values so that the chart doesn't show the point or column at all upon chart initialization:

//Nulls out any field that contains a zero, effectively hiding the point/column from the chart.
//Note that the category will still be visible if both points are null unless you null out that category as well.
AmCharts.addInitHandler(function(chart) {
  var valueFields = chart.graphs.map(function(graph) {
    return graph.valueField;
  });
  chart.dataProvider.forEach(function(dataItem) {
    valueFields.forEach(function(valueField) {
      if (dataItem[valueField] === 0) {
        dataItem[valueField] = null;
      }
    })
  })
}, ["serial"]);

Note that this will effect the data export (csv, xlsx, json) as well. If you want to re-add those zero values to the data export, you can use the processData callback in the export plugin to modify your data to re-add the zeroes:

"export": {
    "enabled": true,
     //re-add nulled out values as zeroes for data export:
    "processData": function(data, cfg) {
      var valueFields = this.setup.chart.graphs.map(function(graph) {
        return graph.valueField;
      });
      data.forEach(function(dataItem) {
        valueFields.forEach(function(valueField) {
          if (dataItem[valueField] == null) {
            dataItem[valueField] = 0;
          }
        });
      });
      return data;
    }
 }

Demo


问:
Column name or number of supplied values does not match table definition
In the SQL Server, I am trying to insert values from one table to another by using the below query:

```<code>delete from tblTable1

insert into tblTable1 select * from tblTable1_Link
</code>```

I am getting the following error:

Column name or number of supplied values does not match table definition.

I am sure that both the tables have the same structure, same column names and same data types.

答:
Check your id. Is it Identity? If it is then make sure it is declared as ID not null Identity(1,1)

And before creating your table , Drop table and then create table.

OwnerDisplayName: Jaison

Body:
In the SQL Server, I am trying to insert values from one table to another by using the below query:

delete from tblTable1

insert into tblTable1 select * from tblTable1_Link

I am getting the following error:

Column name or number of supplied values does not match table definition.

I am sure that both the tables have the same structure, same column names and same data types.


问:
Error when using read.gml or read.graph to read a GML file
I am trying to load a file from the spanish building census (any of the files there will serve as an example, I'm using the 03001-ADSUBIA buildings one).

I have tried the read.gml function from the Multiplex package and get the following error:
read.gml("A.ES.SDGC.BU.03001.building.gml")
Error in which(("node" == arx) == TRUE)[1]:which(("edge" == arx) == TRUE)[1] :
  NA/NaN argument

Then I tried the read.graph from the igraph package and also got an error:
read.graph("A.ES.SDGC.BU.46900.building.gml", format=c("gml"))
Error in .Call("R_igraph_read_graph_gml", file, PACKAGE = "igraph") :
  At foreign.c:1127 : Parse error in GML file, line 1 (syntax error, unexpected STRING, expecting $end), Parse error

What am I doing wrong, and what can I do to fix it?

答:
Found an alternative on this post. However I would like to know why specific packages like multiplex or igraph cannot get the job done properly...

Code:

```<code>llayer<-ogrListLayers("A.ES.SDGC.BU.03001.building.gml")[1]
a<- readOGR(dsn="A.ES.SDGC.BU.46900.building.gml", layer=llayer, encoding = "UTF-8")
</code>```

Body:
Found an alternative on this post. However I would like to know why specific packages like multiplex or igraph cannot get the job done properly...

Code:

llayer<-ogrListLayers("A.ES.SDGC.BU.03001.building.gml")[1]
a<- readOGR(dsn="A.ES.SDGC.BU.46900.building.gml", layer=llayer, encoding = "UTF-8")


问:
Font scaling different per page
I am building a website with a mobile and normal version. The normal version works fine, however, the mobile version has a strange issue. The font size is different per page, so, for instance, I defined h3 to be 48px. Now on one page this works perfectly fine however on a different page the 48px is scaled 59.5556px. This also happens a, p and every other header type, which results in the text looking big on one page and barely readable on the other page. All the css for every page is exactly the same. I cannot link the website since it is still in development.

Examples:

normal font size

scaled font size

答:
You need to put this meta tag in your head section to prevent the mobile doing it's own scaling.

<meta name="viewport" content="width=device-width">

Title: Font scaling different per page


问:
Conditional assignment in if clause
I have a code which I do not want to duplicate too much, it looks something like this:

```<code>myEnum setting;

if (((input == "Enum0") && ((setting = myEnum_0) == setting)) ||
    ((input == "Enum1") && ((setting = myEnum_1) == setting)) ||
    ((input == "Enum2") && ((setting = myEnum_2) == setting)))
{
    doActionWith(setting);
}
</code>```

This way I don't have to check if the input was something totally different (if I just assigned with

```<code>if (input=="Enum0")
    setting = myEnum_0;
</code>```

the code wouldn't know if the enum was actually set, or not.

Now I wonder, is there a more elegant solution for the thing at the end?

The && ((setting = myEnum_x) == setting) ?

答:
Personalty, I would go with a design like the one suggested by Aziuth. But if you want to keep you current design, the you could do this:</p>

```<code>bool doStuff = true;

if (input=="Enum0")
    setting = myEnum_0;
else if (input=="Enum1")
    setting = myEnum_1;
else if (input=="Enum2")
    setting = myEnum_2;
else
{
    doStuff = false;
}

if (doStuff)
{
    doActionWith(setting);
}
</code>```

Title: Conditional assignment in if clause

Body:
I have a code which I do not want to duplicate too much, it looks something like this:

myEnum setting;

if (((input == "Enum0") && ((setting = myEnum_0) == setting)) ||
    ((input == "Enum1") && ((setting = myEnum_1) == setting)) ||
    ((input == "Enum2") && ((setting = myEnum_2) == setting)))
{
    doActionWith(setting);
}

This way I don't have to check if the input was something totally different (if I just assigned with

if (input=="Enum0")
    setting = myEnum_0;

the code wouldn't know if the enum was actually set, or not.

Now I wonder, is there a more elegant solution for the thing at the end?

The && ((setting = myEnum_x) == setting) ?

Body:
Personalty, I would go with a design like the one suggested by Aziuth. But if you want to keep you current design, the you could do this:

bool doStuff = true;

if (input=="Enum0")
    setting = myEnum_0;
else if (input=="Enum1")
    setting = myEnum_1;
else if (input=="Enum2")
    setting = myEnum_2;
else
{
    doStuff = false;
}

if (doStuff)
{
    doActionWith(setting);
}