问:
Using Hammer JS as a carousel
In building a custom carousel with Hammer JS 2.0.8, I had some trouble making it work fluidly. After multiple tries, I found a snippet that really helped, and when I eventually completed the module, I decided to equally share here</p>

答:
This was the snippet that really helped from Richard Liu.

For some reason, switching back to Hammer 2.0.4 made the pancancel/panend callbacks more reliable. From there, I was able to complete my solution. A complete demo is also on JSFiddle

```<code>class Carousel {
constructor(options) {
    this.transiting = false;
    this.activeCard = 1;
    this.offset = 0;
    this.delta = 0;
    this.element = options.carousel;
    this.slides = this.element.children.length;
    this.element.style.width = `${this.slides * 100}%`;
    this.width = options.carousel.clientWidth;
    this.boundaryLeft = 0;
    this.boundaryRight = ((this.count - 1) / this.count) * this.width;
    this.outOfBounds = false;
    this.panRequiredToMove = options.container.clientWidth * 0.25;
    this.hammer = new Hammer(options.container);

    this.init();
}

init() {
    var self = this;

    function handleHammer(e) {
        switch (e.type) {
            case 'swipeleft':
            case 'swiperight':
                self.handleSwipe(e);
                break;
            case 'panleft':
            case 'panright':
            case 'panend':
            case 'pancancel':
                self.handlePan(e);
                break;
        }
    }

    this.hammer.on('swipeleft swiperight panleft panright panend pancancel', handleHammer);
    this.element.addEventListener("transitionend", function (event) {
        this.classList.remove('carousel--in-motion');
    }, false);
}

handleSwipe(e) {
    switch (e.direction) {
        case Hammer.DIRECTION_LEFT:
            this.next();
            break;
        case Hammer.DIRECTION_RIGHT:
            this.previous();
            break;
    }
    this.hammer.stop(true);
}

checkBounds() {
    var beforeFirstCard = this.activeCard === 1 && (this.offset + this.delta) >= this.boundaryLeft;
    var afterLastCard = this.activeCard === this.slides && Math.abs(this.offset + this.delta) >= this.boundaryRight;

    if (beforeFirstCard) {
        this.outOfBounds = { recoilPosition: this.boundaryLeft };
    } else if (afterLastCard) {
        this.outOfBounds = { recoilPosition: this.boundaryRight * -1 };
    } else {
        this.outOfBounds = false;
    }
}

handlePan(e) {
    switch (e.type) {
        case 'panleft':
        case 'panright':
                this.checkBounds();
            if (this.outOfBounds) e.deltaX *= .2;
            this.transition(e.deltaX);
            break;
        case 'panend':
        case 'pancancel':
            if (this.outOfBounds) {
                this.recoil(this.outOfBounds.recoilPosition);
            } else if (Math.abs(e.deltaX) > this.panRequiredToMove) {
                e.deltaX > 0 ? this.previous() : this.next();
            } else {
                this.recoil();
            }
            break;
    }
}

next() {
    if (this.activeCard < this.slides) {
        let newPosition = this.activeCard / this.slides * this.width * -1;
        this.goToSlide(newPosition, () => {
            this.activeCard++;
        });
    }
}

previous() {
    if (this.activeCard > 1) {
        let activeCard = this.activeCard - (this.slides - 1);
        let newPosition = activeCard / this.slides * this.width * -1;
        this.goToSlide(newPosition, () => {
            this.activeCard--;
        });
    }
}

goToSlide(position, callback) {
    let self = this;
    let currentPosition = this.offset + this.delta;
    this.transiting = true;

// I used AnimatePlus for the other movement between slides
    animate({
        el: this.element,
        translateX: [`${currentPosition}px`, `${position}px`],
        duration: 300,
        easing: "easeInOutQuad",
        complete() {
            self.transiting = false;
            self.offset = position;
            self.delta = 0;
            if (callback) callback();
        }
    });
}

transition(deltaX) {
    this.delta = deltaX;
    let position = this.offset + this.delta;
    this.element.style.webkitTransform = `translateX(${position}px)`;
}

recoil(position) {
    this.element.classList.add('carousel--in-motion');
    this.element.style.webkitTransform = `translateX(${position || this.offset}px)`;
}
}
</code>```

Title: Using Hammer JS as a carousel

Body:
This was the snippet that really helped from Richard Liu.

For some reason, switching back to Hammer 2.0.4 made the pancancel/panend callbacks more reliable. From there, I was able to complete my solution. A complete demo is also on JSFiddle

class Carousel {
constructor(options) {
    this.transiting = false;
    this.activeCard = 1;
    this.offset = 0;
    this.delta = 0;
    this.element = options.carousel;
    this.slides = this.element.children.length;
    this.element.style.width = `${this.slides * 100}%`;
    this.width = options.carousel.clientWidth;
    this.boundaryLeft = 0;
    this.boundaryRight = ((this.count - 1) / this.count) * this.width;
    this.outOfBounds = false;
    this.panRequiredToMove = options.container.clientWidth * 0.25;
    this.hammer = new Hammer(options.container);

    this.init();
}

init() {
    var self = this;

    function handleHammer(e) {
        switch (e.type) {
            case 'swipeleft':
            case 'swiperight':
                self.handleSwipe(e);
                break;
            case 'panleft':
            case 'panright':
            case 'panend':
            case 'pancancel':
                self.handlePan(e);
                break;
        }
    }

    this.hammer.on('swipeleft swiperight panleft panright panend pancancel', handleHammer);
    this.element.addEventListener("transitionend", function (event) {
        this.classList.remove('carousel--in-motion');
    }, false);
}

handleSwipe(e) {
    switch (e.direction) {
        case Hammer.DIRECTION_LEFT:
            this.next();
            break;
        case Hammer.DIRECTION_RIGHT:
            this.previous();
            break;
    }
    this.hammer.stop(true);
}

checkBounds() {
    var beforeFirstCard = this.activeCard === 1 && (this.offset + this.delta) >= this.boundaryLeft;
    var afterLastCard = this.activeCard === this.slides && Math.abs(this.offset + this.delta) >= this.boundaryRight;

    if (beforeFirstCard) {
        this.outOfBounds = { recoilPosition: this.boundaryLeft };
    } else if (afterLastCard) {
        this.outOfBounds = { recoilPosition: this.boundaryRight * -1 };
    } else {
        this.outOfBounds = false;
    }
}

handlePan(e) {
    switch (e.type) {
        case 'panleft':
        case 'panright':
                this.checkBounds();
            if (this.outOfBounds) e.deltaX *= .2;
            this.transition(e.deltaX);
            break;
        case 'panend':
        case 'pancancel':
            if (this.outOfBounds) {
                this.recoil(this.outOfBounds.recoilPosition);
            } else if (Math.abs(e.deltaX) > this.panRequiredToMove) {
                e.deltaX > 0 ? this.previous() : this.next();
            } else {
                this.recoil();
            }
            break;
    }
}

next() {
    if (this.activeCard < this.slides) {
        let newPosition = this.activeCard / this.slides * this.width * -1;
        this.goToSlide(newPosition, () => {
            this.activeCard++;
        });
    }
}

previous() {
    if (this.activeCard > 1) {
        let activeCard = this.activeCard - (this.slides - 1);
        let newPosition = activeCard / this.slides * this.width * -1;
        this.goToSlide(newPosition, () => {
            this.activeCard--;
        });
    }
}

goToSlide(position, callback) {
    let self = this;
    let currentPosition = this.offset + this.delta;
    this.transiting = true;

// I used AnimatePlus for the other movement between slides
    animate({
        el: this.element,
        translateX: [`${currentPosition}px`, `${position}px`],
        duration: 300,
        easing: "easeInOutQuad",
        complete() {
            self.transiting = false;
            self.offset = position;
            self.delta = 0;
            if (callback) callback();
        }
    });
}

transition(deltaX) {
    this.delta = deltaX;
    let position = this.offset + this.delta;
    this.element.style.webkitTransform = `translateX(${position}px)`;
}

recoil(position) {
    this.element.classList.add('carousel--in-motion');
    this.element.style.webkitTransform = `translateX(${position || this.offset}px)`;
}
}


来源: stackexchange

问:
Java application crashing and producing an error log file
I have a java application that uses ICEpdf to render pdf documents.  Recently, java has been crashing and producing this error log:

```<code>#
# A fatal error has been detected by the Java Runtime Environment:
#
#  EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x76dca05b, pid=2224, tid=1072
#
# JRE version: 6.0_23-b05
# Java VM: Java HotSpot(TM) Client VM (19.0-b09 mixed mode windows-x86 )
# Problematic frame:
# C  [msvcrt.dll+0xa05b]
#
# If you would like to submit a bug report, please visit:
#   http://java.sun.com/webapps/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#

---------------  T H R E A D  ---------------

Current thread (0x6148c000):  JavaThread "AWT-EventQueue-0" [_thread_in_native, id=1072, stack(0x61930000,0x61980000)]

siginfo: ExceptionCode=0xc0000005, writing address 0x00000000

Registers:
EAX=0x00000000, EBX=0x680b0020, ECX=0x0000333b, EDX=0x00000000
ESP=0x6197ef5c, EBP=0x6197ef64, ESI=0x680b0020, EDI=0x00000000
EIP=0x76dca05b, EFLAGS=0x00010212

Register to memory mapping:

EAX=0x00000000
0x00000000 is pointing to unknown location

EBX=0x680b0020
0x680b0020 is pointing to unknown location

ECX=0x0000333b
0x0000333b is pointing to unknown location

EDX=0x00000000
0x00000000 is pointing to unknown location

ESP=0x6197ef5c
0x6197ef5c is pointing into the stack for thread: 0x6148c000
"AWT-EventQueue-0" prio=6 tid=0x6148c000 nid=0x430 runnable [0x6197f000]
   java.lang.Thread.State: RUNNABLE

EBP=0x6197ef64
0x6197ef64 is pointing into the stack for thread: 0x6148c000
"AWT-EventQueue-0" prio=6 tid=0x6148c000 nid=0x430 runnable [0x6197f000]
   java.lang.Thread.State: RUNNABLE

ESI=0x680b0020
0x680b0020 is pointing to unknown location

EDI=0x00000000
0x00000000 is pointing to unknown location

Top of Stack: (sp=0x6197ef5c)
0x6197ef5c:   00199d80 00000000 6197ef94 76dca00b
0x6197ef6c:   00000000 680b0020 00199d80 6197ef84
0x6197ef7c:   00000020 c4a8eee9 680b0020 00000000
0x6197ef8c:   61a76ae8 08000030 6197efb4 704f7a70
0x6197ef9c:   00000000 680b0020 00199da0 0a435d04
0x6197efac:   08000030 61a76ae8 6197efcc 704dc9ab
0x6197efbc:   08000030 61a76ae8 08000000 2c827bd4
0x6197efcc:   6197efe8 704e81b2 00000145 08000028

Instructions: (pc=0x76dca05b)
0x76dca04b:   06 66 0f 6f 4e 10 66 0f 6f 56 20 66 0f 6f 5e 30
0x76dca05b:   66 0f 7f 07 66 0f 7f 4f 10 66 0f 7f 57 20 66 0f

Stack: [0x61930000,0x61980000],  sp=0x6197ef5c,  free space=315k
Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)
C  [msvcrt.dll+0xa05b]
C  [msvcrt.dll+0xa00b]
C  [prl_gldd.dll+0x27a70]
C  [prl_gldd.dll+0xc9ab]
C  [prl_gldd.dll+0x181b2]
C  [jogl.dll+0xf286]
j  com.sun.opengl.impl.GLImpl.glTexSubImage2D1(IIIIIIIILjava/lang/Object;I)V+0
j  com.sun.opengl.impl.GLImpl.glTexSubImage2D(IIIIIIIILjava/nio/Buffer;)V+85
j      com.sun.opengl.util.texture.Texture.updateSubImageImpl(Lcom/sun/opengl/util/texture/TextureData;IIIIIIII)V+658
j  com.sun.opengl.util.texture.Texture.updateImage(Lcom/sun/opengl/util/texture/TextureData;I)V+1001
j  com.sun.opengl.util.texture.Texture.updateImage(Lcom/sun/opengl/util/texture/TextureData;)V+3
j  com.sun.opengl.util.texture.Texture.<init>(Lcom/sun/opengl/util/texture/TextureData;)V+18
j  com.sun.opengl.util.texture.TextureIO.newTexture(Lcom/sun/opengl/util/texture/TextureData;)Lcom/sun/opengl/util/texture/Texture;+19
j  gov.nasa.worldwind.render.BasicWWTexture.initializeTexture(Lgov/nasa/worldwind/render/DrawContext;Ljava/lang/Object;)Lcom/sun/opengl/util/texture/Texture;+203
j  gov.nasa.worldwind.render.BasicWWTexture.bind(Lgov/nasa/worldwind/render/DrawContext;)Z+42
j  gov.nasa.worldwind.render.AbstractAnnotation.doDrawBackgroundTexture(Lgov/nasa/worldwind/render/DrawContext;IIDLgov/nasa/worldwind/geom/Position;Lgov/nasa/worldwind/render/WWTexture;)V+36
j  gov.nasa.worldwind.render.AbstractAnnotation.drawBackgroundImage(Lgov/nasa/worldwind/render/DrawContext;IIDLgov/nasa/worldwind/geom/Position;)V+35
j  gov.nasa.worldwind.render.AbstractAnnotation.drawContent(Lgov/nasa/worldwind/render/DrawContext;IIDLgov/nasa/worldwind/geom/Position;)V+19
j  gov.nasa.worldwind.render.AbstractAnnotation.doDraw(Lgov/nasa/worldwind/render/DrawContext;IIDLgov/nasa/worldwind/geom/Position;)V+35
j  gov.nasa.worldwind.render.AbstractAnnotation.draw(Lgov/nasa/worldwind/render/DrawContext;IIDLgov/nasa/worldwind/geom/Position;)V+47
j  gov.nasa.worldwind.render.AbstractAnnotation.drawTopLevelAnnotation(Lgov/nasa/worldwind/render/DrawContext;IIIIDDLgov/nasa/worldwind/geom/Position;)V+68
j  gov.nasa.worldwind.render.GlobeAnnotation.doRenderNow(Lgov/nasa/worldwind/render/DrawContext;)V+139
j  gov.nasa.worldwind.render.AbstractAnnotation.renderNow(Lgov/nasa/worldwind/render/DrawContext;)V+56
j  gov.nasa.worldwind.render.BasicAnnotationRenderer$OrderedAnnotation.doRender(Lgov/nasa/worldwind/render/DrawContext;Lgov/nasa/worldwind/render/BasicAnnotationRenderer$OrderedAnnotation;)V+22
j  gov.nasa.worldwind.render.BasicAnnotationRenderer$OrderedAnnotation.render(Lgov/nasa/worldwind/render/DrawContext;)V+20
J  gov.nasa.worldwind.AbstractSceneController.draw(Lgov/nasa/worldwind/render/DrawContext;)V
j  gov.nasa.worldwind.AbstractSceneController.repaint()I+49
j  gov.nasa.worldwind.WorldWindowGLAutoDrawable.doDisplay()I+4
j  gov.nasa.worldwind.WorldWindowGLAutoDrawable.display(Ljavax/media/opengl/GLAutoDrawable;)V+111
j  com.sun.opengl.impl.GLDrawableHelper.display(Ljavax/media/opengl/GLAutoDrawable;)V+29
j  javax.media.opengl.GLCanvas$DisplayAction.run()V+80
j  com.sun.opengl.impl.GLDrawableHelper.invokeGL(Ljavax/media/opengl/GLDrawable;Ljavax/media/opengl/GLContext;Ljava/lang/Runnable;Ljava/lang/Runnable;)V+418
j  javax.media.opengl.GLCanvas.maybeDoSingleThreadedWorkaround(Ljava/lang/Runnable;Ljava/lang/Runnable;)V+36
j  javax.media.opengl.GLCanvas.display()V+9
j  javax.media.opengl.GLCanvas.paint(Ljava/awt/Graphics;)V+125
j  javax.media.opengl.GLCanvas.update(Ljava/awt/Graphics;)V+2
j  sun.awt.RepaintArea.updateComponent(Ljava/awt/Component;Ljava/awt/Graphics;)V+6
j  sun.awt.RepaintArea.paint(Ljava/lang/Object;Z)V+263
j  sun.awt.windows.WComponentPeer.handleEvent(Ljava/awt/AWTEvent;)V+107
j  java.awt.Component.dispatchEventImpl(Ljava/awt/AWTEvent;)V+853
j  java.awt.Component.dispatchEvent(Ljava/awt/AWTEvent;)V+2
j  java.awt.EventQueue.dispatchEvent(Ljava/awt/AWTEvent;)V+46
j  java.awt.EventDispatchThread.pumpOneEventForFilters(I)Z+204
j  java.awt.EventDispatchThread.pumpEventsForFilter(ILjava/awt/Conditional;Ljava/awt/EventFilter;)V+30
j  java.awt.EventDispatchThread.pumpEventsForHierarchy(ILjava/awt/Conditional;Ljava/awt/Component;)V+11
j  java.awt.EventDispatchThread.pumpEvents(ILjava/awt/Conditional;)V+4
j  java.awt.EventDispatchThread.pumpEvents(Ljava/awt/Conditional;)V+3
j  java.awt.EventDispatchThread.run()V+9
v  ~StubRoutines::call_stub
V  [jvm.dll+0xf33c9]
V  [jvm.dll+0x188a91]
V  [jvm.dll+0xf3587]
V  [jvm.dll+0xf35eb]
V  [jvm.dll+0x11e780]
V  [jvm.dll+0x1ea6c4]
V  [jvm.dll+0x18843c]
C  [msvcr71.dll+0x9565]
C  [kernel32.dll+0x51194]
C  [ntdll.dll+0x5b495]
C  [ntdll.dll+0x5b468]
</code>```

I have never seen this before so I have no idea how to figure out what the problem is.

答: Usually I google the message in this case "msvcrt.dll+0xa05b" but there were no matches.  You can log this bug.  The error occurred in a windows driver so I suggest you check your windows service pack level. However, if your problem persists you may need to try a newer or older version of Java.</p>

ContentLicense: CC BY-SA 2.5

Body:
I have a java application that uses ICEpdf to render pdf documents.  Recently, java has been crashing and producing this error log:

#
# A fatal error has been detected by the Java Runtime Environment:
#
#  EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x76dca05b, pid=2224, tid=1072
#
# JRE version: 6.0_23-b05
# Java VM: Java HotSpot(TM) Client VM (19.0-b09 mixed mode windows-x86 )
# Problematic frame:
# C  [msvcrt.dll+0xa05b]
#
# If you would like to submit a bug report, please visit:
#   http://java.sun.com/webapps/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#

---------------  T H R E A D  ---------------

Current thread (0x6148c000):  JavaThread "AWT-EventQueue-0" [_thread_in_native, id=1072, stack(0x61930000,0x61980000)]

siginfo: ExceptionCode=0xc0000005, writing address 0x00000000

Registers:
EAX=0x00000000, EBX=0x680b0020, ECX=0x0000333b, EDX=0x00000000
ESP=0x6197ef5c, EBP=0x6197ef64, ESI=0x680b0020, EDI=0x00000000
EIP=0x76dca05b, EFLAGS=0x00010212

Register to memory mapping:

EAX=0x00000000
0x00000000 is pointing to unknown location

EBX=0x680b0020
0x680b0020 is pointing to unknown location

ECX=0x0000333b
0x0000333b is pointing to unknown location

EDX=0x00000000
0x00000000 is pointing to unknown location

ESP=0x6197ef5c
0x6197ef5c is pointing into the stack for thread: 0x6148c000
"AWT-EventQueue-0" prio=6 tid=0x6148c000 nid=0x430 runnable [0x6197f000]
   java.lang.Thread.State: RUNNABLE

EBP=0x6197ef64
0x6197ef64 is pointing into the stack for thread: 0x6148c000
"AWT-EventQueue-0" prio=6 tid=0x6148c000 nid=0x430 runnable [0x6197f000]
   java.lang.Thread.State: RUNNABLE

ESI=0x680b0020
0x680b0020 is pointing to unknown location

EDI=0x00000000
0x00000000 is pointing to unknown location

Top of Stack: (sp=0x6197ef5c)
0x6197ef5c:   00199d80 00000000 6197ef94 76dca00b
0x6197ef6c:   00000000 680b0020 00199d80 6197ef84
0x6197ef7c:   00000020 c4a8eee9 680b0020 00000000
0x6197ef8c:   61a76ae8 08000030 6197efb4 704f7a70
0x6197ef9c:   00000000 680b0020 00199da0 0a435d04
0x6197efac:   08000030 61a76ae8 6197efcc 704dc9ab
0x6197efbc:   08000030 61a76ae8 08000000 2c827bd4
0x6197efcc:   6197efe8 704e81b2 00000145 08000028

Instructions: (pc=0x76dca05b)
0x76dca04b:   06 66 0f 6f 4e 10 66 0f 6f 56 20 66 0f 6f 5e 30
0x76dca05b:   66 0f 7f 07 66 0f 7f 4f 10 66 0f 7f 57 20 66 0f

Stack: [0x61930000,0x61980000],  sp=0x6197ef5c,  free space=315k
Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)
C  [msvcrt.dll+0xa05b]
C  [msvcrt.dll+0xa00b]
C  [prl_gldd.dll+0x27a70]
C  [prl_gldd.dll+0xc9ab]
C  [prl_gldd.dll+0x181b2]
C  [jogl.dll+0xf286]
j  com.sun.opengl.impl.GLImpl.glTexSubImage2D1(IIIIIIIILjava/lang/Object;I)V+0
j  com.sun.opengl.impl.GLImpl.glTexSubImage2D(IIIIIIIILjava/nio/Buffer;)V+85
j      com.sun.opengl.util.texture.Texture.updateSubImageImpl(Lcom/sun/opengl/util/texture/TextureData;IIIIIIII)V+658
j  com.sun.opengl.util.texture.Texture.updateImage(Lcom/sun/opengl/util/texture/TextureData;I)V+1001
j  com.sun.opengl.util.texture.Texture.updateImage(Lcom/sun/opengl/util/texture/TextureData;)V+3
j  com.sun.opengl.util.texture.Texture.<init>(Lcom/sun/opengl/util/texture/TextureData;)V+18
j  com.sun.opengl.util.texture.TextureIO.newTexture(Lcom/sun/opengl/util/texture/TextureData;)Lcom/sun/opengl/util/texture/Texture;+19
j  gov.nasa.worldwind.render.BasicWWTexture.initializeTexture(Lgov/nasa/worldwind/render/DrawContext;Ljava/lang/Object;)Lcom/sun/opengl/util/texture/Texture;+203
j  gov.nasa.worldwind.render.BasicWWTexture.bind(Lgov/nasa/worldwind/render/DrawContext;)Z+42
j  gov.nasa.worldwind.render.AbstractAnnotation.doDrawBackgroundTexture(Lgov/nasa/worldwind/render/DrawContext;IIDLgov/nasa/worldwind/geom/Position;Lgov/nasa/worldwind/render/WWTexture;)V+36
j  gov.nasa.worldwind.render.AbstractAnnotation.drawBackgroundImage(Lgov/nasa/worldwind/render/DrawContext;IIDLgov/nasa/worldwind/geom/Position;)V+35
j  gov.nasa.worldwind.render.AbstractAnnotation.drawContent(Lgov/nasa/worldwind/render/DrawContext;IIDLgov/nasa/worldwind/geom/Position;)V+19
j  gov.nasa.worldwind.render.AbstractAnnotation.doDraw(Lgov/nasa/worldwind/render/DrawContext;IIDLgov/nasa/worldwind/geom/Position;)V+35
j  gov.nasa.worldwind.render.AbstractAnnotation.draw(Lgov/nasa/worldwind/render/DrawContext;IIDLgov/nasa/worldwind/geom/Position;)V+47
j  gov.nasa.worldwind.render.AbstractAnnotation.drawTopLevelAnnotation(Lgov/nasa/worldwind/render/DrawContext;IIIIDDLgov/nasa/worldwind/geom/Position;)V+68
j  gov.nasa.worldwind.render.GlobeAnnotation.doRenderNow(Lgov/nasa/worldwind/render/DrawContext;)V+139
j  gov.nasa.worldwind.render.AbstractAnnotation.renderNow(Lgov/nasa/worldwind/render/DrawContext;)V+56
j  gov.nasa.worldwind.render.BasicAnnotationRenderer$OrderedAnnotation.doRender(Lgov/nasa/worldwind/render/DrawContext;Lgov/nasa/worldwind/render/BasicAnnotationRenderer$OrderedAnnotation;)V+22
j  gov.nasa.worldwind.render.BasicAnnotationRenderer$OrderedAnnotation.render(Lgov/nasa/worldwind/render/DrawContext;)V+20
J  gov.nasa.worldwind.AbstractSceneController.draw(Lgov/nasa/worldwind/render/DrawContext;)V
j  gov.nasa.worldwind.AbstractSceneController.repaint()I+49
j  gov.nasa.worldwind.WorldWindowGLAutoDrawable.doDisplay()I+4
j  gov.nasa.worldwind.WorldWindowGLAutoDrawable.display(Ljavax/media/opengl/GLAutoDrawable;)V+111
j  com.sun.opengl.impl.GLDrawableHelper.display(Ljavax/media/opengl/GLAutoDrawable;)V+29
j  javax.media.opengl.GLCanvas$DisplayAction.run()V+80
j  com.sun.opengl.impl.GLDrawableHelper.invokeGL(Ljavax/media/opengl/GLDrawable;Ljavax/media/opengl/GLContext;Ljava/lang/Runnable;Ljava/lang/Runnable;)V+418
j  javax.media.opengl.GLCanvas.maybeDoSingleThreadedWorkaround(Ljava/lang/Runnable;Ljava/lang/Runnable;)V+36
j  javax.media.opengl.GLCanvas.display()V+9
j  javax.media.opengl.GLCanvas.paint(Ljava/awt/Graphics;)V+125
j  javax.media.opengl.GLCanvas.update(Ljava/awt/Graphics;)V+2
j  sun.awt.RepaintArea.updateComponent(Ljava/awt/Component;Ljava/awt/Graphics;)V+6
j  sun.awt.RepaintArea.paint(Ljava/lang/Object;Z)V+263
j  sun.awt.windows.WComponentPeer.handleEvent(Ljava/awt/AWTEvent;)V+107
j  java.awt.Component.dispatchEventImpl(Ljava/awt/AWTEvent;)V+853
j  java.awt.Component.dispatchEvent(Ljava/awt/AWTEvent;)V+2
j  java.awt.EventQueue.dispatchEvent(Ljava/awt/AWTEvent;)V+46
j  java.awt.EventDispatchThread.pumpOneEventForFilters(I)Z+204
j  java.awt.EventDispatchThread.pumpEventsForFilter(ILjava/awt/Conditional;Ljava/awt/EventFilter;)V+30
j  java.awt.EventDispatchThread.pumpEventsForHierarchy(ILjava/awt/Conditional;Ljava/awt/Component;)V+11
j  java.awt.EventDispatchThread.pumpEvents(ILjava/awt/Conditional;)V+4
j  java.awt.EventDispatchThread.pumpEvents(Ljava/awt/Conditional;)V+3
j  java.awt.EventDispatchThread.run()V+9
v  ~StubRoutines::call_stub
V  [jvm.dll+0xf33c9]
V  [jvm.dll+0x188a91]
V  [jvm.dll+0xf3587]
V  [jvm.dll+0xf35eb]
V  [jvm.dll+0x11e780]
V  [jvm.dll+0x1ea6c4]
V  [jvm.dll+0x18843c]
C  [msvcr71.dll+0x9565]
C  [kernel32.dll+0x51194]
C  [ntdll.dll+0x5b495]
C  [ntdll.dll+0x5b468]

I have never seen this before so I have no idea how to figure out what the problem is.


问:
SQL get latest row in one to many relationship using where clause only
I have two tables in which (roll_no) is same in both tables.
I have a table (student) having columns name and roll_no. e.g

```<code>roll_no    name
----------------
123        John
</code>```

It has relation with another table (student_changed). Which has columns name, roll_no and LastEditTime. e.g.

```<code>roll_no    name     LastEditTime
--------------------------------------
123        Johny    2017-11-09 06:00:00
123        John     2017-11-08 07:00:00
</code>```

What I want to ask is, how can I get the join having the most recent LastEditTime.
There are many similar questions but my limitation is that I can only use/modify where clause.
e.g.
I cannot modify the select query as well.
Consider it like this

```<code>select * from student, student_changed <-- *this part cannot be changed*
where <-- This can be modified
</code>```

答:
You do not need the join. Table student_changed has all you need:

```<code>select roll_no, name, max(LastEditTime) as LastEditTime
from student_changed
group by roll_no, name
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have two tables in which (roll_no) is same in both tables.
I have a table (student) having columns name and roll_no. e.g

roll_no    name
----------------
123        John

It has relation with another table (student_changed). Which has columns name, roll_no and LastEditTime. e.g.

roll_no    name     LastEditTime
--------------------------------------
123        Johny    2017-11-09 06:00:00
123        John     2017-11-08 07:00:00

What I want to ask is, how can I get the join having the most recent LastEditTime.
There are many similar questions but my limitation is that I can only use/modify where clause.
e.g.
I cannot modify the select query as well.
Consider it like this

select * from student, student_changed <-- *this part cannot be changed*
where <-- This can be modified

Body:
You do not need the join. Table student_changed has all you need:

select roll_no, name, max(LastEditTime) as LastEditTime
from student_changed
group by roll_no, name


问:
Create new string from existing one using regex in Postgresql
I am using postgresql as database system (v 9.6.5). I have a table T with a column code. I want to add a new column sorting_code. sorting_code is an another way to write the code.

code is a combination of (in this order) characters, numbers and +, e.g 12e+, 234rr++ or 9999mo are examples of codes. In regex, my code is something like:

[0-9]+[a-z]*\+*
(only numbers are required)

What I want to do for my column sorting_code is to transform my code like that:

12e+ => 000120000e0000+

234rr++ => 00234000rr000++

9999mo => 09999000mo00000

In other words, each part (characters, numbers and +) must be exactly 5 characters long. Missing characters being replaced by 0.

I have already a lot of rows in my table T with code. What could be my psql request to create my new column sorting_code?

Thank you

答:
you can do it which such bicycle:</p>

```<code>t=# with s(v) as (values('12e+'),('234rr++'),('9999mo'))
, m as (select regexp_matches(v,'[a-z]{1,}','g') l,v,e,p , max(p) over(partition by v)
from s, regexp_split_to_table(v,'[a-z]') with ordinality o (e,p)
)
select lpad(m.e,5,'0')||lpad(m.l[1],5,'0')||lpad(n.e,5,'0') from m join m n on m.v = n.v and m.p=1 and n.p = n.max;
    ?column?
-----------------
 000120000e0000+
 00234000rr000++
 09999000mo00000
(3 rows)
</code>```

Body:
you can do it which such bicycle:

t=# with s(v) as (values('12e+'),('234rr++'),('9999mo'))
, m as (select regexp_matches(v,'[a-z]{1,}','g') l,v,e,p , max(p) over(partition by v)
from s, regexp_split_to_table(v,'[a-z]') with ordinality o (e,p)
)
select lpad(m.e,5,'0')||lpad(m.l[1],5,'0')||lpad(n.e,5,'0') from m join m n on m.v = n.v and m.p=1 and n.p = n.max;
    ?column?
-----------------
 000120000e0000+
 00234000rr000++
 09999000mo00000
(3 rows)


问:
Changing CSS across all pages
I would like to be able to swap between two different style sheets and keep the style being selected on the home page but keeping the use consistent throughout all the pages.

```<code><link id="pagestyle" rel="stylesheet" href="style1.css">
<script type="text/javascript">
  function swapStyleSheet(sheet){
    document.getElementById('pagestyle').setAttribute('href', sheet);
  }
</script>

<button onclick="swapStyleSheet('style.css')">Blue</button>
<button onclick="swapStyleSheet('style1.css')">White</button>
</code>```

This only changes the style sheet for the homepage, but how do I apply this change to all the other pages in the website?

答:
You can use the local storage to store the current stylesheet.</p>

```<code>var stylesheet = localStorage.getItem("stylesheet");

function swapStyleSheet(sheet){
    document.getElementById('pagestyle').setAttribute('href', sheet);
    localStorage.setItem('stylesheet', sheet);
}

if(stylesheet) {
    swapStyleSheet(stylesheet)
}
</code>```

Title: Changing CSS across all pages

Body:
I would like to be able to swap between two different style sheets and keep the style being selected on the home page but keeping the use consistent throughout all the pages.

<link id="pagestyle" rel="stylesheet" href="style1.css">

<button onclick="swapStyleSheet('style.css')">Blue</button>
<button onclick="swapStyleSheet('style1.css')">White</button>

This only changes the style sheet for the homepage, but how do I apply this change to all the other pages in the website?

Body:
You can use the local storage to store the current stylesheet.

var stylesheet = localStorage.getItem("stylesheet");

function swapStyleSheet(sheet){
    document.getElementById('pagestyle').setAttribute('href', sheet);
    localStorage.setItem('stylesheet', sheet);
}

if(stylesheet) {
    swapStyleSheet(stylesheet)
}


问:
While Loop to Iterate through Databases
I was wondering if someone could help me with creating a while loop to iterate through several databases to obtain data from one table from two columns.  this is was I have done so far.  nothing works because i do not know how to make the select statement work through each database with regards to the table that I am querying from each database (dbo.tbldoc)</p>

```<code>DECLARE @Loop int
DECLARE @DBName varchar(300)
DECLARE @SQL varchar(max)
DECLARE @tableName VARCHAR(255)

SET @Loop = 1
SET @DBName = ''

   WHILE @Loop = 1
BEGIN

   SELECT [name] FROM sys.databases
   WHERE [name] like 'z%' and create_date between '2010-10-17' and '2011-01-15'
   ORDER BY [name]

      SET @Loop = @@ROWCOUNT

   IF @Loop = 0
      BREAK

   SET @SQL = ('USE ['+ @DBNAME +']')
      IF EXISTS(SELECT [name] FROM sys.tables WHERE name != 'dbo.tbldoc' )
                  BEGIN
               SELECT SUM(PGCOUNT), CREATED FROM **dbo.tbldoc**
            END
            ELSE
            --BEGIN
               PRINT 'ErrorLog'
            END
</code>```

答:
My code to search for data from more than one database would be:</p>
```<code>use [master]
go
if object_id('tempdb.dbo.#database') is not null
    drop TABLE #database
go

create TABLE #database(id INT identity primary key, name sysname)
go

set nocount on
insert into #database(name)

select name
from sys.databases
where name like '%tgsdb%' --CHANGE HERE THE FILTERING RULE FOR YOUR DATABASES!
and source_database_id is null
order by name

select *
from #database

declare @id INT, @cnt INT, @sql NVARCHAR(max), @currentDb sysname;

select @id = 1, @cnt = max(id)
from #database
while @id <= @cnt

BEGIN
    select @currentDb = name
    from #database
    where id = @id
    set @sql = 'select Column1, Column2 from ' + @currentDb + '.dbo.Table1'
    print @sql
    exec (@sql);
    print '--------------------------------------------------------------------------'
    set @id = @id + 1;
END
go
</code>```

Title: While Loop to Iterate through Databases

Body:
I was wondering if someone could help me with creating a while loop to iterate through several databases to obtain data from one table from two columns.  this is was I have done so far.  nothing works because i do not know how to make the select statement work through each database with regards to the table that I am querying from each database (dbo.tbldoc)

DECLARE @Loop int
DECLARE @DBName varchar(300)
DECLARE @SQL varchar(max)
DECLARE @tableName VARCHAR(255)

SET @Loop = 1
SET @DBName = ''

   WHILE @Loop = 1
BEGIN

   SELECT [name] FROM sys.databases
   WHERE [name] like 'z%' and create_date between '2010-10-17' and '2011-01-15'
   ORDER BY [name]

      SET @Loop = @@ROWCOUNT

   IF @Loop = 0
      BREAK

   SET @SQL = ('USE ['+ @DBNAME +']')
      IF EXISTS(SELECT [name] FROM sys.tables WHERE name != 'dbo.tbldoc' )
                  BEGIN
               SELECT SUM(PGCOUNT), CREATED FROM **dbo.tbldoc**
            END
            ELSE
            --BEGIN
               PRINT 'ErrorLog'
            END

Body:
My code to search for data from more than one database would be:

use [master]
go
if object_id('tempdb.dbo.#database') is not null
    drop TABLE #database
go

create TABLE #database(id INT identity primary key, name sysname)
go

set nocount on
insert into #database(name)

select name
from sys.databases
where name like '%tgsdb%' --CHANGE HERE THE FILTERING RULE FOR YOUR DATABASES!
and source_database_id is null
order by name

select *
from #database

declare @id INT, @cnt INT, @sql NVARCHAR(max), @currentDb sysname;

select @id = 1, @cnt = max(id)
from #database
while @id <= @cnt

BEGIN
    select @currentDb = name
    from #database
    where id = @id
    set @sql = 'select Column1, Column2 from ' + @currentDb + '.dbo.Table1'
    print @sql
    exec (@sql);
    print '--------------------------------------------------------------------------'
    set @id = @id + 1;
END
go

ContentLicense: CC BY-SA 4.0


问:
repeat a group of characters
I have the following input to be matched by a regex:

```<code>1.1.1.1
1.01.1.1
01.01.091.01
1.10.100.0010
</code>```

So I have allways four groups consisting of digits. While the first three ones should match, the last one should not.

So I wrote this regex:

```<code>^(\d*[1-9]+\.){4}$
</code>```

In general this regex should return all those strings where any of the digits in any of the groups is not followed by a zero. Or more easily: I want to not match all numbers with trailing zeros.

However this doesn´t match anything. regex1010.com tells this:

A repeated capturing group will only capture the last iteration. Put a
  capturing group around the repeated group to capture all iterations or
  use a non-capturing group instead if you're not interested in the data

But when I add a further capturing group I get the same message:

```<code>^((\d*[1-9]+\.)){4}$
</code>```

The same applies to a non-capturing group:

```<code>^(?:\d*[1-9]+\.){4}$
</code>```

Of course I could just write the same group four times, but that´s fairly clumsy and hard to read.

答:
The problem with your regex is by not including the . your regex fails to find four matches of digits because they always have dots in between.'

Try this instead:

```<code>(?:(\d*[1-9])\.?){4}
</code>```

Title: repeat a group of characters

Body:
I have the following input to be matched by a regex:

1.1.1.1
1.01.1.1
01.01.091.01
1.10.100.0010

So I have allways four groups consisting of digits. While the first three ones should match, the last one should not.

So I wrote this regex:

^(\d*[1-9]+\.){4}$

In general this regex should return all those strings where any of the digits in any of the groups is not followed by a zero. Or more easily: I want to not match all numbers with trailing zeros.

However this doesn´t match anything. regex1010.com tells this:

A repeated capturing group will only capture the last iteration. Put a
  capturing group around the repeated group to capture all iterations or
  use a non-capturing group instead if you're not interested in the data

But when I add a further capturing group I get the same message:

^((\d*[1-9]+\.)){4}$

The same applies to a non-capturing group:

^(?:\d*[1-9]+\.){4}$

Of course I could just write the same group four times, but that´s fairly clumsy and hard to read.

Body:
The problem with your regex is by not including the . your regex fails to find four matches of digits because they always have dots in between.'

Try this instead:

(?:(\d*[1-9])\.?){4}


问:
Create a variable capturing the most frequent occurence by group
Define:

```<code>df1 <-data.frame(
id=c(rep(1,3),rep(2,3)),
v1=as.character(c("a","b","b",rep("c",3)))
)
</code>```

s.t.

```<code>> df1
  id v1
1  1  a
2  1  b
3  1  b
4  2  c
5  2  c
6  2  c
</code>```

I want to create a third variable freq that contains the most frequent observation in v1 by id s.t.

```<code>> df2
  id v1 freq
1  1  a    b
2  1  b    b
3  1  b    b
4  2  c    c
5  2  c    c
6  2  c    c
</code>```

答:
Another way consists of using tidyverse functions:

grouping first, using group_by(), and counting the occurrence of the second variable using tally()

arranging by the number of occurrences with arrange()

summarizing and picking out the first row with summarize() and first()

Therefore:

```<code>df1 %>%
group_by(id, v1) %>%
tally() %>%
arrange(id, desc(n)) %>%
summarize(freq = first(v1))
</code>```

This will give you just the mapping (which I find cleaner):

```<code># A tibble: 2 x 2
     id   freq
  <dbl> <fctr>
1     1      b
2     2      c
</code>```

You can then left_join your original data frame with that table.

Body:
Define:

df1 <-data.frame(
id=c(rep(1,3),rep(2,3)),
v1=as.character(c("a","b","b",rep("c",3)))
)

s.t.

> df1
  id v1
1  1  a
2  1  b
3  1  b
4  2  c
5  2  c
6  2  c

I want to create a third variable freq that contains the most frequent observation in v1 by id s.t.

> df2
  id v1 freq
1  1  a    b
2  1  b    b
3  1  b    b
4  2  c    c
5  2  c    c
6  2  c    c

Body:
Another way consists of using tidyverse functions:

grouping first, using group_by(), and counting the occurrence of the second variable using tally()

arranging by the number of occurrences with arrange()

summarizing and picking out the first row with summarize() and first()

Therefore:

df1 %>%
group_by(id, v1) %>%
tally() %>%
arrange(id, desc(n)) %>%
summarize(freq = first(v1))

This will give you just the mapping (which I find cleaner):

# A tibble: 2 x 2
     id   freq
  <dbl> <fctr>
1     1      b
2     2      c

You can then left_join your original data frame with that table.


问:
How to setup a lock for a read-manipulate-write operation?
Considering the following table

The sequence value is a custom auto increment key combining letters and numbers that a particular client need for his system.

We made a function called GetNextSequence() which should return the next value of the sequence. The step to reading and updating the sequence goes as follow

Read the sequence value using the KeyId: SELECT Sequence FROM [Key] WHERE KeyId = @Id

Parse the sequence value and determine the next value

Write the sequence value to the table: UPDATE [Key] SET Sequence = @Sequence WHERE KeyId = @Id

Here is the C# code (simplified for clarity):

```<code>var transaction = connection.BeginTransaction(IsolationLevel.RepeatableRead);
var currentSequenceValue = SqlUtils.ExecuteScalar(connection, transaction, "SELECT Sequence FROM [Key] WHERE KeyId = @Id", new SqlParameter("@Id", keyId));
var updatedSequenceValue = ParseSequence(currentSequenceValue);
SqlUtils.ExecuteScalar(connection, transaction, "UPDATE [Key] SET Sequence = @Sequence WHERE KeyId = @Id", new SqlParameter("@Id", keyId), new SqlParameter("@Sequence", updatedSequenceValue));
transaction.Commit();
return updatedSequenceValue;
</code>```

Our problem reside in that two different servers can access the same sequence and we end up getting a deadlock

Transaction (Process ID X) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.

In C#, I tried to set up different lock combination like a transaction isolation IsolationLevel.RepeatableRead or IsolationLevel.Serializable or in SQL using table hint ROWLOCK and HOLDLOCK, but without success.

I want that each server be able to read, manipulate and update a sequence in a atomic way. What is the proper way to setup a lock for this situation?

答:
The problem is that the default locks being acquired for reading do not avoid race conditions, because multiple read locks can be acquired on the same record.

The situation is, process A acquires a Read lock on row X. Process B then acquires a reader lock while A is working on its "client side" (within the server program). A then requests an upgrade to a Write lock while B is working on the client side, at which point it is told to wait until B's read lock is released. B then requests a Write lock and is tols to wait until A releases its Read. Both are now waiting on the other so they can acquire the more exclusive Write lock.

The solution is an exclusive lock; you can specify this using the XLOCK hint. An exclusive lock is basically a Write-level lock acquired for a read, and is used in this exact case, where you expect to write something you're reading. As noted in the comments, an exclusive lock is only maintained if the statement is executed in the scope of an explicit transaction, so make sure you are setting one up during the "unit of work" that is reading the value, determining how to advance it, and then updating it.

I would use this at the row level (ROWLOCK), unless you are updating a lot of similar sequences all at once; acquiring a page or table-level exclusive lock makes EVERYBODY wait for data that you don't need if you're only working on one row per transaction.

Body:
Considering the following table

The sequence value is a custom auto increment key combining letters and numbers that a particular client need for his system.

We made a function called GetNextSequence() which should return the next value of the sequence. The step to reading and updating the sequence goes as follow

Read the sequence value using the KeyId: SELECT Sequence FROM [Key] WHERE KeyId = @Id

Parse the sequence value and determine the next value

Write the sequence value to the table: UPDATE [Key] SET Sequence = @Sequence WHERE KeyId = @Id

Here is the C# code (simplified for clarity):

var transaction = connection.BeginTransaction(IsolationLevel.RepeatableRead);
var currentSequenceValue = SqlUtils.ExecuteScalar(connection, transaction, "SELECT Sequence FROM [Key] WHERE KeyId = @Id", new SqlParameter("@Id", keyId));
var updatedSequenceValue = ParseSequence(currentSequenceValue);
SqlUtils.ExecuteScalar(connection, transaction, "UPDATE [Key] SET Sequence = @Sequence WHERE KeyId = @Id", new SqlParameter("@Id", keyId), new SqlParameter("@Sequence", updatedSequenceValue));
transaction.Commit();
return updatedSequenceValue;

Our problem reside in that two different servers can access the same sequence and we end up getting a deadlock

Transaction (Process ID X) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.

In C#, I tried to set up different lock combination like a transaction isolation IsolationLevel.RepeatableRead or IsolationLevel.Serializable or in SQL using table hint ROWLOCK and HOLDLOCK, but without success.

I want that each server be able to read, manipulate and update a sequence in a atomic way. What is the proper way to setup a lock for this situation?


问:
How to close timepicker (pickatime) popup from js
When I use the date picker, it can be closed by:

```<code>$('.datepicker').pickadate().pickadate('picker').close();
</code>```

But it doesn't work for the time picker, I tried to use another approach and it also didn't work. I use timepicker from the Materialize package.
Did anybody have the same problem and maybe solved it?

Here is a fiddle with the problem.

答:
Found weird but working solution.

```<code>$(document.body).click();
</code>```

This will close the time picker popup.

Fiddle

Body:
When I use the date picker, it can be closed by:

$('.datepicker').pickadate().pickadate('picker').close();

But it doesn't work for the time picker, I tried to use another approach and it also didn't work. I use timepicker from the Materialize package.
Did anybody have the same problem and maybe solved it?

Here is a fiddle with the problem.

Body:
Found weird but working solution.

$(document.body).click();

This will close the time picker popup.

Fiddle


问:
How to compile big c++ project using MsBuild.exe with x64 compiler
I have the big Visual Studio 2015 C++ project and can't compile it on the computer with 12GB RAM (fatal error C1060: compiler is out of heap space).

Command line:

```<code>"C:\Program Files (x86)\MSBuild\14.0\Bin\MSBuild.exe" Project.sln /t:Rebuild /p:Configuration=Release;Platform=x64
</code>```

I've read this https://msdn.microsoft.com/en-us/library/x4d2c09s.aspx?f=255&MSPPError=-2147217396
and decided to use x64 compiler, but I can't figure out how it can be done using MsBuild.exe (or with another way but without generate make file - it is hard to maintain it because the project frequently changed).

I was tried to call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin\amd64\vcvars64.bat" before MsBuild.exe, but it doesn't help.

答:
Found solution here: https://msdn.microsoft.com/en-us/library/ee662426.aspx?f=255&MSPPError=-2147217396

Where is the property PreferredToolArchitecture which by default equals x86.
Set it to x64 to use the 64-bit compiler and tools to build your application.

```<code>msbuild myProject.vcxproj /p:PreferredToolArchitecture=x64
</code>```

Body:
I have the big Visual Studio 2015 C++ project and can't compile it on the computer with 12GB RAM (fatal error C1060: compiler is out of heap space).

Command line:

"C:\Program Files (x86)\MSBuild\14.0\Bin\MSBuild.exe" Project.sln /t:Rebuild /p:Configuration=Release;Platform=x64

I've read this https://msdn.microsoft.com/en-us/library/x4d2c09s.aspx?f=255&MSPPError=-2147217396
and decided to use x64 compiler, but I can't figure out how it can be done using MsBuild.exe (or with another way but without generate make file - it is hard to maintain it because the project frequently changed).

I was tried to call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin\amd64\vcvars64.bat" before MsBuild.exe, but it doesn't help.

Body:
Found solution here: https://msdn.microsoft.com/en-us/library/ee662426.aspx?f=255&MSPPError=-2147217396

Where is the property PreferredToolArchitecture which by default equals x86.
Set it to x64 to use the 64-bit compiler and tools to build your application.

msbuild myProject.vcxproj /p:PreferredToolArchitecture=x64


问:
Expand environment variable for My Documents
I know I can read environment variables like this:

```<code>Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
</code>```

However, it would be really helpful to me if I could do something like this:

```<code>Environment.ExpandEnvironmentVariables(@"%MyDocuments%\Foo");
</code>```

Is there an environement variable that equals SpecialFolder.MyDocuments?

I also tried to do something like this, but this doesn't lead to the expected result:

```<code>Environment.ExpandEnvironmentVariables(@"%USERPROFILE%\My Documents\Foo");
</code>```

This way I ended up with something like @"C:\Users\<MyUser>\My Documents\Foo" but I what I need is @"\\someservername\users$\<MyUser>\My Documents\Foo".

EDIT: My Goal is NOT to hardcode either environment variable nor the part after that.

Any other suggestions?

答:
No there is no environment variable for the MyDocuments special folder (the same is true for most members of the SpecialFolder enumeration).

Check out this snippet, it might be exactly what you are searching for.

It allows you to do something like that:

```<code>string fullPath = SpecialFolder.ExpandVariables(@"%MyDocuments%\Foo");
</code>```

Note: SpecialFolder.ExpandVariables is a static method of a helper class introduced in the above snippet.

Body:
I know I can read environment variables like this:

Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

However, it would be really helpful to me if I could do something like this:

Environment.ExpandEnvironmentVariables(@"%MyDocuments%\Foo");

Is there an environement variable that equals SpecialFolder.MyDocuments?

I also tried to do something like this, but this doesn't lead to the expected result:

Environment.ExpandEnvironmentVariables(@"%USERPROFILE%\My Documents\Foo");

This way I ended up with something like @"C:\Users\<MyUser>\My Documents\Foo" but I what I need is @"\\someservername\users$\<MyUser>\My Documents\Foo".

EDIT: My Goal is NOT to hardcode either environment variable nor the part after that.

Any other suggestions?

Body:
No there is no environment variable for the MyDocuments special folder (the same is true for most members of the SpecialFolder enumeration).

Check out this snippet, it might be exactly what you are searching for.

It allows you to do something like that:

string fullPath = SpecialFolder.ExpandVariables(@"%MyDocuments%\Foo");

Note: SpecialFolder.ExpandVariables is a static method of a helper class introduced in the above snippet.


问:
RuntimeException when I create a new Symfony Project
good afternoon. I'm having trouble creating a new symfony project.
When I enter the following command in the terminal:

```<code>symfony new mufasa
</code>```

The terminal return to me the next message:

[RuntimeException]

    The selected version (3.3.12) cannot be installed because it does not exist

    .

    Execute the following command to install the latest stable Symfony release:

    /usr/local/bin/symfony new mufasa

I have tried to update the symfony application using symfony self-update but is up to date:

// Symfony Installer is already updated to the latest version (1.5.9).

What can I do to solve this problem?

答:
try this please:

```<code>symfony new mufasa 3.3.11
</code>```

release 3.3.12 was released some hours ago:

https://github.com/symfony/symfony/releases

But there is a similar issue:

https://github.com/symfony/symfony-installer/issues/141

Body:
good afternoon. I'm having trouble creating a new symfony project.
When I enter the following command in the terminal:

symfony new mufasa

The terminal return to me the next message:

[RuntimeException]

    The selected version (3.3.12) cannot be installed because it does not exist

    .

    Execute the following command to install the latest stable Symfony release:

    /usr/local/bin/symfony new mufasa

I have tried to update the symfony application using symfony self-update but is up to date:

// Symfony Installer is already updated to the latest version (1.5.9).

What can I do to solve this problem?

Body:
try this please:

symfony new mufasa 3.3.11

release 3.3.12 was released some hours ago:

https://github.com/symfony/symfony/releases

But there is a similar issue:

https://github.com/symfony/symfony-installer/issues/141


问:
Pin encryption 4 digit number to hexadecimal
These are the steps the program must follow:

Request user input for 4 digit pin. [done]

Convert 4 digit pin to hexadecimal. [?]

Generate two random numbers greater than 1000 and convert to hexadecimal.[?]

Sandwich the converted pin between the two random converted numbers. [can be done]

So far the code I have is:

```<code>public static void main(String[] args)
{
    int digit = 0;
    Scanner scan = new Scanner(System.in);
    System.out.println("Please enter a four digit pin:");
    digit = scan.nextInt(); // scanning for user input

    String Hexpin =Integer.toHexString(digit);
    System.out.println(Hexpin);
}
</code>```

I currently need help converting the pin to hexadecimal and generating two random numbers greater than 1000 and converting them to hexadecimal also. I can then however do the sandwich easily. I tried searching for an answer before this and cant find anything other than:

C# convert integer to hex and back again

This article however converts the int to a hex string not a decimal.

答:
Give this a try I think this is what you are asking for. Just needed a small fix. Hope that helps!</p>

```<code>    public static void main(String[] args){

    Scanner scan = new Scanner(System.in);
    System.out.println("Please enter a four digit pin:");
    int digit = scan.nextInt(); // scanning for user input as INT
    String hexDigit = Integer.toHexString(digit); //convert PIN to hex

    int one = ((int)(Math.random()+1000)*10000); //two randoms bw 1000 and 10000
    int two = ((int)(Math.random()+1000)*10000);

    String oneStr = Integer.toHexString(one); //convert to hex
    String twoStr = Integer.toHexString(two); //convert to hex

    System.out.println(oneStr + hexDigit + twoStr); //print concated
}
</code>```

Body:
These are the steps the program must follow:

Request user input for 4 digit pin. [done]

Convert 4 digit pin to hexadecimal. [?]

Generate two random numbers greater than 1000 and convert to hexadecimal.[?]

Sandwich the converted pin between the two random converted numbers. [can be done]

So far the code I have is:

public static void main(String[] args)
{
    int digit = 0;
    Scanner scan = new Scanner(System.in);
    System.out.println("Please enter a four digit pin:");
    digit = scan.nextInt(); // scanning for user input

    String Hexpin =Integer.toHexString(digit);
    System.out.println(Hexpin);
}

I currently need help converting the pin to hexadecimal and generating two random numbers greater than 1000 and converting them to hexadecimal also. I can then however do the sandwich easily. I tried searching for an answer before this and cant find anything other than:

C# convert integer to hex and back again

This article however converts the int to a hex string not a decimal.

Body:
Give this a try I think this is what you are asking for. Just needed a small fix. Hope that helps!

    public static void main(String[] args){

    Scanner scan = new Scanner(System.in);
    System.out.println("Please enter a four digit pin:");
    int digit = scan.nextInt(); // scanning for user input as INT
    String hexDigit = Integer.toHexString(digit); //convert PIN to hex

    int one = ((int)(Math.random()+1000)*10000); //two randoms bw 1000 and 10000
    int two = ((int)(Math.random()+1000)*10000);

    String oneStr = Integer.toHexString(one); //convert to hex
    String twoStr = Integer.toHexString(two); //convert to hex

    System.out.println(oneStr + hexDigit + twoStr); //print concated
}


问:
R lubridate: weekdays in local language
How can I get the weekdays and month in my local language?

My code:

```<code>library(lubridate)
data <- c("10-02-2015", "11-03-2015")
data.lubri <- dmy(data)
wday(data.lubri, label=TRUE)
</code>```

Always returns

```<code>[1] Tues Wed
Levels: Sun < Mon < Tues < Wed < Thurs < Fri < Sat
</code>```

and

```<code>month(data.lubri, label = TRUE)
</code>```

Always returns

```<code>[1] Feb Mar
Levels: Jan < Feb < Mar < Apr < May < Jun < Jul < Aug < Sep < Oct < Nov < Dec
</code>```

I need it in Portuguese, using lubridate, and already tried a ton of locale options, but nothing lubridate related seems to work.

The base functions, weekdays() and months(), work, though.

The problem is base months() gives me a unordered vector when working with dates.

I need them as an ordered factor, for later plotting.

My current work around is getting my hands dirty:

```<code>factor(months(data.lubri, abbreviate=TRUE),
             levels = c("Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul",
                        "Ago", "Set", "Out", "Nov", "Dez"),
             ordered=TRUE)

[1] Fev Mar
Levels: Jan < Fev < Mar < Abr < Mai < Jun < Jul < Ago < Set < Out < Nov < Dez
</code>```

but this isn't classy...

答:
Current versions of lubridate (at least 1.7.1) allow this by default:

```<code>wday(x, label = FALSE, abbr = TRUE,
  week_start = getOption("lubridate.week.start", 7),
  locale = Sys.getlocale("LC_TIME"))
</code>```

In older versions, you can do simply add labels to the factor variable that hold your week days (Dutch in this example):

```<code>variable <- factor(variable, levels = c('Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun'), labels = c('Maandag', 'Dinsdag', 'Woensdag', 'Donderdag', 'Vrijdag', 'Zaterdag', 'Zondag'))
</code>```

Title: R lubridate: weekdays in local language

Body:
How can I get the weekdays and month in my local language?

My code:

library(lubridate)
data <- c("10-02-2015", "11-03-2015")
data.lubri <- dmy(data)
wday(data.lubri, label=TRUE)

Always returns

[1] Tues Wed
Levels: Sun < Mon < Tues < Wed < Thurs < Fri < Sat

and

month(data.lubri, label = TRUE)

Always returns

[1] Feb Mar
Levels: Jan < Feb < Mar < Apr < May < Jun < Jul < Aug < Sep < Oct < Nov < Dec

I need it in Portuguese, using lubridate, and already tried a ton of locale options, but nothing lubridate related seems to work.

The base functions, weekdays() and months(), work, though.

The problem is base months() gives me a unordered vector when working with dates.

I need them as an ordered factor, for later plotting.

My current work around is getting my hands dirty:

factor(months(data.lubri, abbreviate=TRUE),
             levels = c("Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul",
                        "Ago", "Set", "Out", "Nov", "Dez"),
             ordered=TRUE)

[1] Fev Mar
Levels: Jan < Fev < Mar < Abr < Mai < Jun < Jul < Ago < Set < Out < Nov < Dez

but this isn't classy...

Body:
Current versions of lubridate (at least 1.7.1) allow this by default:

wday(x, label = FALSE, abbr = TRUE,
  week_start = getOption("lubridate.week.start", 7),
  locale = Sys.getlocale("LC_TIME"))

In older versions, you can do simply add labels to the factor variable that hold your week days (Dutch in this example):

variable <- factor(variable, levels = c('Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun'), labels = c('Maandag', 'Dinsdag', 'Woensdag', 'Donderdag', 'Vrijdag', 'Zaterdag', 'Zondag'))


问:
Display an alert over the lock screen?
On the iPhone, when your phone is locked and screen off, if a SMS message comes in, the screen turns on and an alert shows up.

Currently I am using UIAlertView to create the alert dialog (with 2 buttons).
If the phone is off/locked, nothing shows up until I turn it back on and unlock it.
Is there any way to simulate the 'SMS preview' behavior, possibly with another class, and hopefully still allow the user to interact with the buttons there?

答:
CFUserNotificationCreate is your friend.

Not in the official iPhone SDK? Too bad, I remember that a year ago on the big presentation of the yet-to-come SDK, an Apple evangelist/chief saying that the SDK would include exactly the same API as used internally by Apple... Pfff...

/John

OwnerDisplayName: justinb

Title: Display an alert over the lock screen?

LastEditorDisplayName: Chris Hanson

OwnerDisplayName: John Lane


问:
Handle last iteration of asp.net repeater differently
Is it possible to detect or use a different template in the asp.net repeater for the last iteration in the repeater?

If not I could just use a for loop but I'm curious if it can be done.

答:
Sometimes I do this by using PlaceHolder instances in my ItemTemplates. I.e.:

```<code><ItemTemplate>
<asp:PlaceHolder id="phIsNotLastOne" runat="server">Is not last</asp:PlaceHolder>
<asp:PlaceHolder id="phIsLastOne" runat="server">Is last</asp:PlaceHolder>
</ItemTemplate>
</code>```

I usually have a variable to track the OnItemDataBound counter in my class as a protected class member:

```<code>protected int _bindCtr = 0;
</code>```

Then in my ItemDataBound method:

```<code>protected void MyItemDataBound(object sender, RepeaterItemEventArgs args)
{
    if (args.Item.ItemType == ListItemType.AlternatingItem ||
        args.Item.ItemType == ListItemType.Item)
    {
        ++this._bindCtr;
        this.phIsLastOne.Visible = this._bindCtr == this._dataSource.Count;
        this.phIsNotLastOne.Visible = this._bindCtr < this._dataSource.Count;
    }
}
</code>```

More or less. Just make sure to have your data source assessible, and set your counter to 0 before binding.

Better to look at ItemIndex as suggested, versus approach above.
Also the Repeater type has a DataSource property that is not strongly typed, but has a reference to your data source.

Body:
Sometimes I do this by using PlaceHolder instances in my ItemTemplates. I.e.:

<ItemTemplate>
<asp:PlaceHolder id="phIsNotLastOne" runat="server">Is not last</asp:PlaceHolder>
<asp:PlaceHolder id="phIsLastOne" runat="server">Is last</asp:PlaceHolder>
</ItemTemplate>

I usually have a variable to track the OnItemDataBound counter in my class as a protected class member:

protected int _bindCtr = 0;

Then in my ItemDataBound method:

protected void MyItemDataBound(object sender, RepeaterItemEventArgs args)
{
    if (args.Item.ItemType == ListItemType.AlternatingItem ||
        args.Item.ItemType == ListItemType.Item)
    {
        ++this._bindCtr;
        this.phIsLastOne.Visible = this._bindCtr == this._dataSource.Count;
        this.phIsNotLastOne.Visible = this._bindCtr < this._dataSource.Count;
    }
}

More or less. Just make sure to have your data source assessible, and set your counter to 0 before binding.

Better to look at ItemIndex as suggested, versus approach above.
Also the Repeater type has a DataSource property that is not strongly typed, but has a reference to your data source.


问:
Quicksort 3 way partition code is not doing what it's told
I need to make a quicksort method that utilizes 3 way partitioning. The algorithm I'm using can be found here https://algs4.cs.princeton.edu/lectures/23DemoPartitioning.pdf scroll down to the Dijkstra 3-way partitioning demo. For some arrays such as, 5 5 7 3 5 1 6 2 4 8, my method works. However when I put an array such as, 5 5 7 3 5 1 6 2 4 8 9 8, my code does not work properly. I get the output: 1 2 3 4 5 5 5 6 7 8 9 8. I know what the problem is, but I don't understand why my code isn't handling it. Here is my code:

```<code>import java.util.Scanner;

public class QuickSortDriver {

    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        System.out.print("\n\nEnter array elements: ");
        String s = scan.nextLine();
        String[] token = s.split(" ");
        int[] array = new int[token.length];

        for(int i=0; i < array.length; i++)
            array[i] = Integer.parseInt(token[i]);

        quicksort(array, 0, array.length - 1);

        System.out.print("\nSorted array: ");

        for(int i = 0; i < array.length; i++)
            System.out.printf("%d ", array[i]);

        System.out.print("\n\n");
        scan.close();
    }

    public static void quicksort(int [] array, int low, int high)
    {
        //debugging: shows what the array is
        //before the while loop
        System.out.print("\n");
        for(int j = low; j <= high; j++)
            System.out.printf("%d ", array[j]);

        if(high <= low)
            return;

        int lt = low;
        int gt = high;
        int i = low;

        while(i <= gt)
        {
            if(array[i] < array[low])
                swap(array, lt++, i++);
            else if(array[i] > array[low])
                swap(array, i, gt--);
            else
                i++;
        }

        //debugging: shows what the array is
        //after the while loop
        System.out.print("\n");
        for(int j = low; j <= high; j++)
            System.out.printf("%d ", array[j]);

        quicksort(array, low, lt -1);
        quicksort(array, gt + 1, high);
    }

    public static void swap(int array[], int i, int j)
    {
        int tmp = array[i];
        array[i] = array[j];
        array[j] = tmp;
    }

}
</code>```

I put the for loops that print out the array at the beginning and end of the sorting method for debugging purposes and by doing that I found the problem. Here is my input output with the debugging statements printed:

```<code>Enter array elements: 5 5 7 3 5 1 6 2 4 8 9 8

5 5 7 3 5 1 6 2 4 8 9 8
4 3 2 1 5 5 6 5 8 9 8 7
4 3 2 1
3 2 1 4
3 2 1
2 1 3
2 1
1 2
1

6 5 8 9 8 7
5 6 9 8 7 8
5
9 8 7 8
8 7 9 8 <--right here is the problem
8 7
7 8
7

Sorted array: 1 2 3 4 5 5 5 6 7 8 9 8
</code>```

When my program gets to the 9 8 7 8 part of the array, it should do this:

(Please follow along with the logic in the Dijkstra 3-way partitioning algorithm.)

```<code>9 8 7 8

i = 9 lt = 9 gt = 8(at end) increment i

9 8 7 8

i = 8 lt = 9 gt = 8(at end) swap i and lt and increment i

8 9 7 8

i = 7 lt = 9 gt = 8(at end) swap i and lt and increment i

8 7 9 8
</code>```

i = 8(at end) lt = 9 gt = 8(at end) Now at this point it should swap i and lt and increment i. However, it doesn't and I have no idea why. The condition in my while loop is while(i <= gt), therefore it should keep iterating at that point because i and gt are at the same indices (refer to the code), but it doesn't. If anyone here can help me fix this bug it would be greatly appreciated I'm literally about to start pulling my hair out.

答:
This is not a bug fix. Merely some help to identify the problem:

Add more debugging like this:

```<code>    System.out.println("Part 1: " + low + " to " + (lt-1));
    System.out.println("Part 2: " + (gt+1) + " to " + high);
    quicksort(array, low, lt -1);
    quicksort(array, gt + 1, high);
</code>```

If the initial input array is 9, 8, 7, 8 the array will be 8, 7, 9, 8 after the first while iteration. The new output becomes

```<code>Part 1: 0 to 1
Part 2: 4 to 3
</code>```

which means the first two items - 8, 7 - will be sorted in the next round. But after that nothing happens since 4>3, so 9, 8 will remain in the wrong order. It is clear that if (in this case) Part 2 was "2 to 3", it all would be ok.

Sadly, it is less clear how to fix that. In this case, the following would work but I suspect that's not how Quicksort should work, and it might not work in other cases:

```<code>    quicksort(array, low, lt -1);
    quicksort(array, lt, high);
</code>```

Body:
I need to make a quicksort method that utilizes 3 way partitioning. The algorithm I'm using can be found here https://algs4.cs.princeton.edu/lectures/23DemoPartitioning.pdf scroll down to the Dijkstra 3-way partitioning demo. For some arrays such as, 5 5 7 3 5 1 6 2 4 8, my method works. However when I put an array such as, 5 5 7 3 5 1 6 2 4 8 9 8, my code does not work properly. I get the output: 1 2 3 4 5 5 5 6 7 8 9 8. I know what the problem is, but I don't understand why my code isn't handling it. Here is my code:

import java.util.Scanner;

public class QuickSortDriver {

    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        System.out.print("\n\nEnter array elements: ");
        String s = scan.nextLine();
        String[] token = s.split(" ");
        int[] array = new int[token.length];

        for(int i=0; i < array.length; i++)
            array[i] = Integer.parseInt(token[i]);

        quicksort(array, 0, array.length - 1);

        System.out.print("\nSorted array: ");

        for(int i = 0; i < array.length; i++)
            System.out.printf("%d ", array[i]);

        System.out.print("\n\n");
        scan.close();
    }

    public static void quicksort(int [] array, int low, int high)
    {
        //debugging: shows what the array is
        //before the while loop
        System.out.print("\n");
        for(int j = low; j <= high; j++)
            System.out.printf("%d ", array[j]);

        if(high <= low)
            return;

        int lt = low;
        int gt = high;
        int i = low;

        while(i <= gt)
        {
            if(array[i] < array[low])
                swap(array, lt++, i++);
            else if(array[i] > array[low])
                swap(array, i, gt--);
            else
                i++;
        }

        //debugging: shows what the array is
        //after the while loop
        System.out.print("\n");
        for(int j = low; j <= high; j++)
            System.out.printf("%d ", array[j]);

        quicksort(array, low, lt -1);
        quicksort(array, gt + 1, high);
    }

    public static void swap(int array[], int i, int j)
    {
        int tmp = array[i];
        array[i] = array[j];
        array[j] = tmp;
    }

}

I put the for loops that print out the array at the beginning and end of the sorting method for debugging purposes and by doing that I found the problem. Here is my input output with the debugging statements printed:

Enter array elements: 5 5 7 3 5 1 6 2 4 8 9 8

5 5 7 3 5 1 6 2 4 8 9 8
4 3 2 1 5 5 6 5 8 9 8 7
4 3 2 1
3 2 1 4
3 2 1
2 1 3
2 1
1 2
1

6 5 8 9 8 7
5 6 9 8 7 8
5
9 8 7 8
8 7 9 8 <--right here is the problem
8 7
7 8
7

Sorted array: 1 2 3 4 5 5 5 6 7 8 9 8

When my program gets to the 9 8 7 8 part of the array, it should do this:

(Please follow along with the logic in the Dijkstra 3-way partitioning algorithm.)

9 8 7 8

i = 9 lt = 9 gt = 8(at end) increment i

9 8 7 8

i = 8 lt = 9 gt = 8(at end) swap i and lt and increment i

8 9 7 8

i = 7 lt = 9 gt = 8(at end) swap i and lt and increment i

8 7 9 8

i = 8(at end) lt = 9 gt = 8(at end) Now at this point it should swap i and lt and increment i. However, it doesn't and I have no idea why. The condition in my while loop is while(i <= gt), therefore it should keep iterating at that point because i and gt are at the same indices (refer to the code), but it doesn't. If anyone here can help me fix this bug it would be greatly appreciated I'm literally about to start pulling my hair out.

Body:
This is not a bug fix. Merely some help to identify the problem:

Add more debugging like this:

    System.out.println("Part 1: " + low + " to " + (lt-1));
    System.out.println("Part 2: " + (gt+1) + " to " + high);
    quicksort(array, low, lt -1);
    quicksort(array, gt + 1, high);

If the initial input array is 9, 8, 7, 8 the array will be 8, 7, 9, 8 after the first while iteration. The new output becomes

Part 1: 0 to 1
Part 2: 4 to 3

which means the first two items - 8, 7 - will be sorted in the next round. But after that nothing happens since 4>3, so 9, 8 will remain in the wrong order. It is clear that if (in this case) Part 2 was "2 to 3", it all would be ok.

Sadly, it is less clear how to fix that. In this case, the following would work but I suspect that's not how Quicksort should work, and it might not work in other cases:

    quicksort(array, low, lt -1);
    quicksort(array, lt, high);


问:
How to restrict user to entering only "Y" or "N" in a single column
I want to restrict user entry in column A and column D.

In column A, the user should enter the values as R00yyyyyy where yyyyyy is a number between 000000 and 999999.

In column D they should only enter y or n.

My code below doesn't seem to work properly. The column A part works fine, just having issues with column D.

Can anyone suggest a way to enable restricting the entry in column D?

```<code>Private Sub Worksheet_Change(ByVal Target As Excel.Range)

Dim rngCell As Range

If Intersect(Target, Range("A:A")) Is Nothing Then Exit Sub

Application.EnableEvents = False
For Each rngCell In Target.Cells
    rngCell = UCase(rngCell)
    If rngCell.Characters.Count > 9 Then
    MsgBox ("Student number too long")
    rngCell.Clear
    End If
   If Not IsEmpty(rngCell.Value) Then
    Dim s As String
    Dim s1 As String
    Dim y As String
    Dim y1 As String
    s = CStr(rngCell.Value)
    s1 = Left(s, 3)
    y = CStr(rngCell.Value)
    y1 = Right(y, 6)
    If s1 <> "R00" Or Not IsNumeric(y1) Then
    MsgBox ("Must be in the form R00yyyyyy, where yyyyyy is a number between 000000 and 999999")
    rngCell.Clear
    End If
   Else
   End If
Next
Application.EnableEvents = True

Dim rngCell2 As Range

If Intersect(Target, Range("D:D")) Is Nothing Then Exit Sub

Application.EnableEvents = False
For Each rngCell2 In Target.Cells
    rngCell2 = UCase(rngCell2)
    Dim b As String
    b = CStr(rngCell2.Value)
    If b <> "y" Or b <> "n" Then
    MsgBox ("The only allowable entry here is Y or N")
    End If
Next
Application.EnableEvents = True

End Sub
</code>```

答:
You have this line

```<code> If Intersect(Target, Range("A:A")) Is Nothing Then Exit Sub
</code>```

So when they change anything in column D, it's not in A and the code exits before ever reaching your code for D

Body:
I want to restrict user entry in column A and column D.

In column A, the user should enter the values as R00yyyyyy where yyyyyy is a number between 000000 and 999999.

In column D they should only enter y or n.

My code below doesn't seem to work properly. The column A part works fine, just having issues with column D.

Can anyone suggest a way to enable restricting the entry in column D?

Private Sub Worksheet_Change(ByVal Target As Excel.Range)

Dim rngCell As Range

If Intersect(Target, Range("A:A")) Is Nothing Then Exit Sub

Application.EnableEvents = False
For Each rngCell In Target.Cells
    rngCell = UCase(rngCell)
    If rngCell.Characters.Count > 9 Then
    MsgBox ("Student number too long")
    rngCell.Clear
    End If
   If Not IsEmpty(rngCell.Value) Then
    Dim s As String
    Dim s1 As String
    Dim y As String
    Dim y1 As String
    s = CStr(rngCell.Value)
    s1 = Left(s, 3)
    y = CStr(rngCell.Value)
    y1 = Right(y, 6)
    If s1 <> "R00" Or Not IsNumeric(y1) Then
    MsgBox ("Must be in the form R00yyyyyy, where yyyyyy is a number between 000000 and 999999")
    rngCell.Clear
    End If
   Else
   End If
Next
Application.EnableEvents = True

Dim rngCell2 As Range

If Intersect(Target, Range("D:D")) Is Nothing Then Exit Sub

Application.EnableEvents = False
For Each rngCell2 In Target.Cells
    rngCell2 = UCase(rngCell2)
    Dim b As String
    b = CStr(rngCell2.Value)
    If b <> "y" Or b <> "n" Then
    MsgBox ("The only allowable entry here is Y or N")
    End If
Next
Application.EnableEvents = True

End Sub

Body:
You have this line

 If Intersect(Target, Range("A:A")) Is Nothing Then Exit Sub

So when they change anything in column D, it's not in A and the code exits before ever reaching your code for D


问:
Push Notification Error in IOS
I have used a firebase push notification in my application . I have created SSL certificate and uploaded p.12 file to my firebase project properly and there is no error in a code , but when i send a notification message from firebase , it shows message sent completed , but in my console i got this:

<Warning> [Firebase/Messaging][I-FCM002019] FIRMessaging received data-message, but FIRMessagingDelegate's-messaging:didReceiveMessage: not implemented

My code for firebase push notification is this:

```<code>#import "AppDelegate.h"
</code>```

@import Firebase;
@import FirebaseMessaging;

```<code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(tokenRefreshCallBack:) name:kFIRInstanceIDTokenRefreshNotification object:nil];

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(tokenRefreshCallBack:) name:kFIRInstanceIDTokenRefreshNotification object:nil];

UIUserNotificationType altype=(UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound);
UIUserNotificationSettings *settings=[UIUserNotificationSettings settingsForTypes:altype categories:nil];

[application registerUserNotificationSettings:settings];
[application registerForRemoteNotifications];

[FIRApp configure];

return YES;
</code>```

}

```<code>- (void)applicationDidEnterBackground:(UIApplication *)application {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

[FIRMessaging messaging];
NSLog(@"Disconnected from FCM");
</code>```

}

```<code>- (void)applicationDidBecomeActive:(UIApplication *)application {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
 [self connectFirebase];
</code>```

}

```<code>-(void)application:(UIApplication *)application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler{
NSLog(@"Message ID %@:",userInfo[@"gcm.message_id"]);
NSLog(@"MMM %@",userInfo);
</code>```

}

```<code>-(void)tokenRefreshCallBack:(NSNotification *)notification{
NSString *token=[[FIRInstanceID instanceID]token];
NSLog(@"Token is %@",token);
[self connectFirebase];
</code>```

}

```<code>-(void)connectFirebase{
[[FIRMessaging messaging]connectWithCompletion:^(NSError *_Nullable error){
    if (error!=nil) {
        NSLog(@"Unable to connect to FCM %@",error);
    }else{
        NSLog(@"Connect to FCM");
    }
}];
</code>```

}

答: Error says clearly that you need to implement the FIRMessaging delegate method messaging:didReceiveMessage: to receive the message.

Title: Push Notification Error in IOS

Body:
I have used a firebase push notification in my application . I have created SSL certificate and uploaded p.12 file to my firebase project properly and there is no error in a code , but when i send a notification message from firebase , it shows message sent completed , but in my console i got this:

<Warning> [Firebase/Messaging][I-FCM002019] FIRMessaging received data-message, but FIRMessagingDelegate's-messaging:didReceiveMessage: not implemented

My code for firebase push notification is this:

#import "AppDelegate.h"

@import Firebase;
@import FirebaseMessaging;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(tokenRefreshCallBack:) name:kFIRInstanceIDTokenRefreshNotification object:nil];

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(tokenRefreshCallBack:) name:kFIRInstanceIDTokenRefreshNotification object:nil];

UIUserNotificationType altype=(UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound);
UIUserNotificationSettings *settings=[UIUserNotificationSettings settingsForTypes:altype categories:nil];

[application registerUserNotificationSettings:settings];
[application registerForRemoteNotifications];

[FIRApp configure];

return YES;

}

- (void)applicationDidEnterBackground:(UIApplication *)application {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

[FIRMessaging messaging];
NSLog(@"Disconnected from FCM");

}

- (void)applicationDidBecomeActive:(UIApplication *)application {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
 [self connectFirebase];

}

-(void)application:(UIApplication *)application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler{
NSLog(@"Message ID %@:",userInfo[@"gcm.message_id"]);
NSLog(@"MMM %@",userInfo);

}

-(void)tokenRefreshCallBack:(NSNotification *)notification{
NSString *token=[[FIRInstanceID instanceID]token];
NSLog(@"Token is %@",token);
[self connectFirebase];

}

-(void)connectFirebase{
[[FIRMessaging messaging]connectWithCompletion:^(NSError *_Nullable error){
    if (error!=nil) {
        NSLog(@"Unable to connect to FCM %@",error);
    }else{
        NSLog(@"Connect to FCM");
    }
}];

}


问:
How to override background color of body without changing the existing background color?
how do i change the body background color red without overriding css or removing the css property?
https://i.stack.imgur.com/vNkRh.png</p>

答:
this is a challenge you should not overide the styles using html, css, Javasript or Jquery ...this is a interview question...is there any other way possible?

From the challange we can assume this is trick question.

You should tell your interviewer that this can't be done without overriding CSS, but if he meant how would you do it without changing css file directly you would use inline css or javascript.

Here is inline css example:

```<code><body style='background: blue'>
</code>```

Here is JS > JQ example:

```<code>$('body').css('background','blue');
</code>```

Code in action http://jsbin.com/latajuquwo/edit?html,js,output

Body:
this is a challenge you should not overide the styles using html, css, Javasript or Jquery ...this is a interview question...is there any other way possible?

From the challange we can assume this is trick question.

You should tell your interviewer that this can't be done without overriding CSS, but if he meant how would you do it without changing css file directly you would use inline css or javascript.

Here is inline css example:

<body style='background: blue'>

Here is JS > JQ example:

$('body').css('background','blue');

Code in action http://jsbin.com/latajuquwo/edit?html,js,output


问:
Why does my getColor function always return false?
I have a function that gets user input and its supposed to validate the user input from a list of options. The last part of the function, where I cycle through results and return true, if there's a true boolean value in results doesn't seem to be working properly. It keeps returning false. </p>

```<code>    function getColor(){
        //gets user color and makes all characters lower case;
        let color=prompt("Pick a color, your options are white, yellow, brown, black, tan, red, orange").toLowerCase();

        //stores acceptable colors
        let acceptableColors=["white","yellow", "brown", "black","tan","red","orange"];

        function validate(){
            let results=[];
            for(let i=0; i<acceptableColors.length; i++){//loops through and stores a true value in results if user color is in list of acceptableColors
                    if(color===acceptableColors[i]){
                        results.push(true);
                    }
                    else{
                        results.push(false);
                    }

            }

            results.forEach(function(item){//loops through results to search for true value and returns true, if it finds one
                if(item===true){
                    return true
                }
            });
             return false;//returns false if user entered invalid color

        }
        return validate();

    }
</code>```

答:
Your whole function can be simplified. There's no need to push booleans in an array, and then check that array for truthy values. Just use includes to check if the color array includes the user's prompted color.

```<code>function getColor() {
  let color = prompt("Pick a color, your options are white, yellow, brown, black, tan, red, orange").toLowerCase();
  let acceptableColors = ["white", "yellow", "brown", "black", "tan", "red", "orange"];
  return acceptableColors.includes(color);
}

getColor();
</code>```

Body:
I have a function that gets user input and its supposed to validate the user input from a list of options. The last part of the function, where I cycle through results and return true, if there's a true boolean value in results doesn't seem to be working properly. It keeps returning false.

    function getColor(){
        //gets user color and makes all characters lower case;
        let color=prompt("Pick a color, your options are white, yellow, brown, black, tan, red, orange").toLowerCase();

        //stores acceptable colors
        let acceptableColors=["white","yellow", "brown", "black","tan","red","orange"];

        function validate(){
            let results=[];
            for(let i=0; i<acceptableColors.length; i++){//loops through and stores a true value in results if user color is in list of acceptableColors
                    if(color===acceptableColors[i]){
                        results.push(true);
                    }
                    else{
                        results.push(false);
                    }

            }

            results.forEach(function(item){//loops through results to search for true value and returns true, if it finds one
                if(item===true){
                    return true
                }
            });
             return false;//returns false if user entered invalid color

        }
        return validate();

    }

Body:
Your whole function can be simplified. There's no need to push booleans in an array, and then check that array for truthy values. Just use includes to check if the color array includes the user's prompted color.

function getColor() {
  let color = prompt("Pick a color, your options are white, yellow, brown, black, tan, red, orange").toLowerCase();
  let acceptableColors = ["white", "yellow", "brown", "black", "tan", "red", "orange"];
  return acceptableColors.includes(color);
}

getColor();


问:
epoll_wait() receives socket closed twice (read()/recv() returns 0)
We have an application that uses epoll to listen and process http-connections. Sometimes epoll_wait() receives close event on fd twice in a "row". Meaning: epoll_wait() returns connection fd on which read()/recv() returns 0. This is a problem, since I have malloc:ed pointer saved in epoll_event struct (struct epoll_event.data.ptr) and which is freed when fd(socket) is detected as closed the first time. Second time it crashes.

This problem occurs very rarely in real use (except one site, which actually has around 500-1000 users per server). I can replicate the problem using http siege with >1000 simultaneous connections per second. In this case application segfaults (because of invalid pointer) very randomly, sometimes after few seconds, usually after tens of minutes. I have been able to replicate the problem with fewer connections per second, but for that I have to run the application a long time, many days, even weeks.

All new accept() connection fd:s are set as non-blocking and added to epoll as one-shot, edge-triggering and waiting for read() to be available. So somewhy when the server load is high, epoll thinks that my application didn't get the close-event and queues new one?

epoll_wait() is running in it's own thread and queues fd events to be handled elsewhere. I noticed that there was multiple closes incoming with simple code that checks if there comes event twice in a row from epoll to same fd. It did happen and the events where both closes (recv(.., MSG_PEEK) told this to me :)).

epoll fd is created: ```epoll_create(1024);```

epoll_wait() is run as follows: ```epoll_wait(epoll_fd, events, 256, 300);```

new fd is set as non-blocking after accept():

```
int flags = fcntl(fd, F_GETFL, 0);
err = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
```

new fd is added to epoll (client is malloc:ed struct pointer):

```
static struct epoll_event ev;
ev.events = EPOLLIN | EPOLLONESHOT | EPOLLET;
ev.data.ptr = client;
err = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client->fd, &ev);
```

And after receiving and handling data from fd, it is re-armed (of course since EPOLLONESHOT). At first I wasn't using edge-triggering and non-blocking io, but I tested it and got a nice perfomance boost using those. This problem existed before adding them though. Btw. shutdown(fd, SHUT_RDWR) is used on other threads to trigger proper close event to be received trough epoll when the server needs to close the fd because of some http-error etc (I don't actually know if this is the right way to do it, but it has worked perfectly).

答:
I would re-check myself against the following sections from epoll(7):

Q6
Will closing a file descriptor cause it to be removed from all epoll sets automatically?

and

o If using an event cache...

There're some good points there.

Body:
We have an application that uses epoll to listen and process http-connections. Sometimes epoll_wait() receives close event on fd twice in a "row". Meaning: epoll_wait() returns connection fd on which read()/recv() returns 0. This is a problem, since I have malloc:ed pointer saved in epoll_event struct (struct epoll_event.data.ptr) and which is freed when fd(socket) is detected as closed the first time. Second time it crashes.

This problem occurs very rarely in real use (except one site, which actually has around 500-1000 users per server). I can replicate the problem using http siege with >1000 simultaneous connections per second. In this case application segfaults (because of invalid pointer) very randomly, sometimes after few seconds, usually after tens of minutes. I have been able to replicate the problem with fewer connections per second, but for that I have to run the application a long time, many days, even weeks.

All new accept() connection fd:s are set as non-blocking and added to epoll as one-shot, edge-triggering and waiting for read() to be available. So somewhy when the server load is high, epoll thinks that my application didn't get the close-event and queues new one?

epoll_wait() is running in it's own thread and queues fd events to be handled elsewhere. I noticed that there was multiple closes incoming with simple code that checks if there comes event twice in a row from epoll to same fd. It did happen and the events where both closes (recv(.., MSG_PEEK) told this to me :)).

epoll fd is created:
epoll_create(1024);

epoll_wait() is run as follows:
epoll_wait(epoll_fd, events, 256, 300);

new fd is set as non-blocking after accept():

int flags = fcntl(fd, F_GETFL, 0);
err = fcntl(fd, F_SETFL, flags | O_NONBLOCK);

new fd is added to epoll (client is malloc:ed struct pointer):

static struct epoll_event ev;
ev.events = EPOLLIN | EPOLLONESHOT | EPOLLET;
ev.data.ptr = client;
err = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client->fd, &ev);

And after receiving and handling data from fd, it is re-armed (of course since EPOLLONESHOT). At first I wasn't using edge-triggering and non-blocking io, but I tested it and got a nice perfomance boost using those. This problem existed before adding them though. Btw. shutdown(fd, SHUT_RDWR) is used on other threads to trigger proper close event to be received trough epoll when the server needs to close the fd because of some http-error etc (I don't actually know if this is the right way to do it, but it has worked perfectly).


问:
Create new string from existing one using regex in Postgresql
I am using postgresql as database system (v 9.6.5). I have a table T with a column code. I want to add a new column sorting_code. sorting_code is an another way to write the code.

code is a combination of (in this order) characters, numbers and +, e.g 12e+, 234rr++ or 9999mo are examples of codes. In regex, my code is something like:

[0-9]+[a-z]*\+*
(only numbers are required)

What I want to do for my column sorting_code is to transform my code like that:

12e+ => 000120000e0000+

234rr++ => 00234000rr000++

9999mo => 09999000mo00000

In other words, each part (characters, numbers and +) must be exactly 5 characters long. Missing characters being replaced by 0.

I have already a lot of rows in my table T with code. What could be my psql request to create my new column sorting_code?

Thank you

答:
I think the Regular expression implementation of substring along with lpad could get you there:

```<code>select
  val,
  lpad (coalesce (substring (val, '\d+'), ''), 5, '0') ||
  lpad (coalesce (substring (val, '[A-Za-z]+'), ''), 5, '0') ||
  lpad (coalesce (substring (val, '\++'), ''), 5, '0') as sorting_code
from t
</code>```

Body:
I think the Regular expression implementation of substring along with lpad could get you there:

select
  val,
  lpad (coalesce (substring (val, '\d+'), ''), 5, '0') ||
  lpad (coalesce (substring (val, '[A-Za-z]+'), ''), 5, '0') ||
  lpad (coalesce (substring (val, '\++'), ''), 5, '0') as sorting_code
from t


问:
Modify keyword not working Drools
I am testing infinite loops using Modify keyword.

But it is not re triggering the rule.

Rule 1:

```<code>rule "Entitle for promotion"

when
$i: EmployeeFinancialFact(rating==Rating.ONE.getRating())
then
  PromotionFact $promotion=new PromotionFact($i.getEmpID(),$i.getEmpName());
  insert($promotion);
end
</code>```

Rule 2:

```<code>rule "Print EmployeeFinancialFact name entitled for promotion"

when
$p:  PromotionFact()
then
modify($p) {setSentForApproval(true);}
end
</code>```

I am expecting RHS of rule 2 will re-trigger the rule 2 again but it is getting fired only once.

Can anyone please tell me the reason.

答:
Disable property reactive in Kmodule.xml in Drools 7 by adding following lines:</p>

```<code><configuration>
  <property key="drools.propertySpecific" value="ALLOWED"/>
</configuration>
</code>```

Title: Modify keyword not working Drools

Body:
I am testing infinite loops using Modify keyword.

But it is not re triggering the rule.

Rule 1:

rule "Entitle for promotion"

when
$i: EmployeeFinancialFact(rating==Rating.ONE.getRating())
then
  PromotionFact $promotion=new PromotionFact($i.getEmpID(),$i.getEmpName());
  insert($promotion);
end

Rule 2:

rule "Print EmployeeFinancialFact name entitled for promotion"

when
$p:  PromotionFact()
then
modify($p) {setSentForApproval(true);}
end

I am expecting RHS of rule 2 will re-trigger the rule 2 again but it is getting fired only once.

Can anyone please tell me the reason.

Body:
Disable property reactive in Kmodule.xml in Drools 7 by adding following lines:

<configuration>
  <property key="drools.propertySpecific" value="ALLOWED"/>
</configuration>


问:
Error occurring as : w0 Fail to read json file with error:No JSON object could be decoded while launching couchbase image using docker-compose
I am using couchbase image with base version 4.6.3 in docker-compose . But I am getting the below error while launching docker-compose up : -</p>

```<code>couchbase_1   | SUCCESS: init/edit couchbase.docker
couchbase_1   | SUCCESS: set hostname for couchbase.docker
couchbase_1   | SUCCESS: bucket-create
couchbase_1   | ....2017-11-13 09:57:06,301: w0 Fail to read json file with error:No JSON object could be decoded
couchbase_1   | .
couchbase_1   | bucket: ., msgs transferred...
couchbase_1   |        :                total |       last |    per sec
couchbase_1   |  byte  :               251515 |     251515 |  3987233.9
couchbase_1   | done
couchbase_1   | /entrypoint.sh couchbase-server
</code>```

答: Making the Json file to compact single line resolved  the error.</p>

Body:
I am using couchbase image with base version 4.6.3 in docker-compose . But I am getting the below error while launching docker-compose up : -

couchbase_1   | SUCCESS: init/edit couchbase.docker
couchbase_1   | SUCCESS: set hostname for couchbase.docker
couchbase_1   | SUCCESS: bucket-create
couchbase_1   | ....2017-11-13 09:57:06,301: w0 Fail to read json file with error:No JSON object could be decoded
couchbase_1   | .
couchbase_1   | bucket: ., msgs transferred...
couchbase_1   |        :                total |       last |    per sec
couchbase_1   |  byte  :               251515 |     251515 |  3987233.9
couchbase_1   | done
couchbase_1   | /entrypoint.sh couchbase-server