问:
set selected page number - kendo grid
I am creating a grid using kendo-telrik. In this suppose I am having 100 data. From this in json I have only 10 data(suppose first page contains 10 data in pagination). And I am showing all pages(10 pages for 100 data) all the time.

When I click on another page then get next 10 data and show it in ui. For this I am using page change function of kendo grid and get next 10 data.Now I want to list that data in grid with page which I selected.

For this I create sample which is as - http://jsfiddle.net/pporwal26/y6KdK/76/

```<code> var jsonData = JSON.parse("{\"Report\":\"type1\",\"FileList\":[{\"owner\":\"machine-174\\\\admin\",\"path\":\"C:\\\\workarea\\\\WinTest1lakhfileinKB\\\\WinTest\\\\nGYh\\\\SMv\\\\U1P8FLx\\\\vMbhdo\\\\TgFSW\\\\42Ioulj0w.txt\"},{\"owner\":\"machine-174admin\",\"path\":\"C:\\\\workarea\\\\bada_data\\\\Employee Database - Copy (7) - Copy.mdb\"}],\"Count\":100,\"total\":100,\"page\":1}");
function nextData(page){
jsonData = JSON.parse("{\"Report\":\"type1\",\"FileList\":[{\"owner\":\"machine-170\\\\admin\",\"path\":\"C:\\\\workarea\\\\WinTest1lakhfileinKB\\\\WinTest\\\\nGYh\\\\SMv\\\\U1P8FLx\"},{\"owner\":\"machine-170admin\",\"path\":\"C:\\\\workarea\"}],\"Count\":100,\"total\":100,\"page\":"+page+"}");
createGrid(jsonData);
}
createGrid(jsonData);
function createGrid(jsonData){
$("#grid").kendoGrid({
   pageable: true,
   scrollable: true,
   page: jsonData.page,
   pageable: {
         pageSize: 2,
         refresh: true,
         change:function(e){
           nextData(e.index);
         }
     },
   dataSource: {
       serverPaging: true,
       schema: {
           data: "FileList",
           total: "total"

       },
       data: jsonData
   }
});
}
</code>```

In this sample when I click on change event than it always show 1 page not the page which I selected. and also want that on each click grid is always create new not add in it. What can I do for that?

答:
Well I know that calling createGrid(jsonData); inside of the nextData function, you're going to create a table for every time you increment, that alone will cause bugs. Have you tried commenting that out?

I've personally never used kendoGrid, so if my answer's no good, I do apologies, but from having had a look online, this seems to work?

Worst case, you do need that change, in which case, can't you target the data inside the table and just over ride it in some other function? A pretty morbid way of doing it would be to delete/destroy the current one in order to make a new one. But it would work I guess?

Title: set selected page number - kendo grid

Body:
I am creating a grid using kendo-telrik. In this suppose I am having 100 data. From this in json I have only 10 data(suppose first page contains 10 data in pagination). And I am showing all pages(10 pages for 100 data) all the time.

When I click on another page then get next 10 data and show it in ui. For this I am using page change function of kendo grid and get next 10 data.Now I want to list that data in grid with page which I selected.

For this I create sample which is as - http://jsfiddle.net/pporwal26/y6KdK/76/

 var jsonData = JSON.parse("{\"Report\":\"type1\",\"FileList\":[{\"owner\":\"machine-174\\\\admin\",\"path\":\"C:\\\\workarea\\\\WinTest1lakhfileinKB\\\\WinTest\\\\nGYh\\\\SMv\\\\U1P8FLx\\\\vMbhdo\\\\TgFSW\\\\42Ioulj0w.txt\"},{\"owner\":\"machine-174admin\",\"path\":\"C:\\\\workarea\\\\bada_data\\\\Employee Database - Copy (7) - Copy.mdb\"}],\"Count\":100,\"total\":100,\"page\":1}");
function nextData(page){
jsonData = JSON.parse("{\"Report\":\"type1\",\"FileList\":[{\"owner\":\"machine-170\\\\admin\",\"path\":\"C:\\\\workarea\\\\WinTest1lakhfileinKB\\\\WinTest\\\\nGYh\\\\SMv\\\\U1P8FLx\"},{\"owner\":\"machine-170admin\",\"path\":\"C:\\\\workarea\"}],\"Count\":100,\"total\":100,\"page\":"+page+"}");
createGrid(jsonData);
}
createGrid(jsonData);
function createGrid(jsonData){
$("#grid").kendoGrid({
   pageable: true,
   scrollable: true,
   page: jsonData.page,
   pageable: {
         pageSize: 2,
         refresh: true,
         change:function(e){
           nextData(e.index);
         }
     },
   dataSource: {
       serverPaging: true,
       schema: {
           data: "FileList",
           total: "total"

       },
       data: jsonData
   }
});
}

In this sample when I click on change event than it always show 1 page not the page which I selected. and also want that on each click grid is always create new not add in it. What can I do for that?


来源: 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.

答:
This is not going to be fun to debug. i suggest a google search like this one to maybe find an exsiting bug report dealing with this:

http://www.google.com/search?rlz=1C1ASUT_enUS401US401&sourceid=chrome&ie=UTF-8&q=glTexSubImage2D1+core+dump#sclient=psy&hl=en&rlz=1C1ASUT_enUS401US401&source=hp&q=glTexSubImage2D+core+dump&aq=f&aqi=&aql=&oq=&pbx=1&fp=f478bdfafcb0c911

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.


问:
Effect of call by reference function inside call by value function on structures
I am programming in C. I send a structure as an argument to a function by "call by value method". Inside the function, I call another function which needs "call by reference" to the same structure. The call by value, should make a copy of structure and send a pointer of this copied version, to the inside function. My question is whether the original structure, outside both function will remain intact, no matter, how I play inside the functions.

Also, call by value, makes a copy of the structure. Is this very fast, compared to manually copying its member stuff, by using other algorithms like memcpy etc.

Example where function play changes the value

```<code>#include<stdio.h>
#include<stdlib.h>

typedef struct{
    int dimension;
    double *vector;
}myVector;

void changeVec(myVector *X)
{
    X->vector[0]=100;
    X->vector[1]=200;
}

void foo(myVector X)
{
    changeVec(&X);
}

int main()
{
    myVector X;
    X.dimension=2;
    X.vector=malloc(sizeof(double)*X.dimension);
    X.vector[0]=1;
    X.vector[1]=2;
    printf("before function calling\n");
    for(int i=0; i<X.dimension; i++)
    {
        printf("%f ",X.vector[i]);
    }
    printf("\n");
    foo(X);
    printf("after function calling\n");
    for(int i=0; i<X.dimension; i++)
    {
        printf("%f ",X.vector[i]);
    }
    printf("\n");
    return 0;
}
</code>```

答:
Anything passed by value to a function remains "intact" as far as the caller is concerned.   The reason is that the value passed is a COPY of the argument provided by the caller, and any changes to the COPY don't affect the original.

If the structure contains a pointer, the pointer can be dereferenced.   Any changes made that way - to data that the pointer points at - WILL be visible to the caller.   But the value of the pointer in the structure itself cannot be changed.

The compiler, when creating a copy of a structure, will generally pick the most efficient means of copying it.    Your chances of beating that by copying members "by hand" are remote.

ContentLicense: CC BY-SA 3.0

Body:
I am programming in C. I send a structure as an argument to a function by "call by value method". Inside the function, I call another function which needs "call by reference" to the same structure. The call by value, should make a copy of structure and send a pointer of this copied version, to the inside function. My question is whether the original structure, outside both function will remain intact, no matter, how I play inside the functions.

Also, call by value, makes a copy of the structure. Is this very fast, compared to manually copying its member stuff, by using other algorithms like memcpy etc.

Example where function play changes the value

#include<stdio.h>
#include<stdlib.h>

typedef struct{
    int dimension;
    double *vector;
}myVector;

void changeVec(myVector *X)
{
    X->vector[0]=100;
    X->vector[1]=200;
}

void foo(myVector X)
{
    changeVec(&X);
}

int main()
{
    myVector X;
    X.dimension=2;
    X.vector=malloc(sizeof(double)*X.dimension);
    X.vector[0]=1;
    X.vector[1]=2;
    printf("before function calling\n");
    for(int i=0; i<X.dimension; i++)
    {
        printf("%f ",X.vector[i]);
    }
    printf("\n");
    foo(X);
    printf("after function calling\n");
    for(int i=0; i<X.dimension; i++)
    {
        printf("%f ",X.vector[i]);
    }
    printf("\n");
    return 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.

答:
You never specify the dot in your patterns. What you ask for is, in fact, not a repetition of four, it is a specific single pattern of four numbers separated with dots.

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

The only thing in there you could consider a repetition is the "number + dot" part, but then you repeat that three times and add another number. Then the regex would become this:

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

However, your third line contains a space at the end, so you may want to add extra checks to trim those off.

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:
You never specify the dot in your patterns. What you ask for is, in fact, not a repetition of four, it is a specific single pattern of four numbers separated with dots.

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

The only thing in there you could consider a repetition is the "number + dot" part, but then you repeat that three times and add another number. Then the regex would become this:

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

However, your third line contains a space at the end, so you may want to add extra checks to trim those off.


问:
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>

答:
I'm not sure if I understand your question, but you can try a JavaScript approach?

JS:

```<code>document.getElementById("yourElementID").style.backgroundColor = "yourColor";
</code>```

JQuery

```<code>$("#yourElementID").css("background-color", "yourColor");
</code>```

If you can, try to explain a little better what your issue is so we can provide the appropriate support.

Body:
I'm not sure if I understand your question, but you can try a JavaScript approach?

JS:

document.getElementById("yourElementID").style.backgroundColor = "yourColor";

JQuery

$("#yourElementID").css("background-color", "yourColor");

If you can, try to explain a little better what your issue is so we can provide the appropriate support.


问:
OpenNETCF: is it free to use?
I downloaded all the OpenNETCF dlls. Is it free? Or will it stop working after a year?</p>

答:
If you mean the Smart Device Framework (migrated from Codeplex), then yes the binaries are free to use and distribute.  There is no limitation in features or time on them for any edition, including the free Community Edition.

If you mean any of our other products or libraries (we've got quite a few), then you'll have to be a bit more specific.

Title: OpenNETCF: is it free to use?

ContentLicense: CC BY-SA 4.0


问:
Replacing values with groupby means
I have a DataFrame with a column that has some bad data with various negative values. I would like to replace values < 0 with the mean of the group that they are in.

For missing values as NAs, I would do:

```<code>data = df.groupby(['GroupID']).column
data.transform(lambda x: x.fillna(x.mean()))
</code>```

But how to do this operation on a condition like x < 0?

Thanks!

答:
I had the same issue and came up with a rather simple solution

```<code>func = lambda x : np.where(x < 0, x.mean(), x)

df['Bad_Column'].transform(func)
</code>```

Note that if you want to return the mean of the correct values (mean based on positive values only)  you'd have to specify:

```<code>func = lambda x : np.where(x < 0, x.mask(x < 0).mean(), x)
</code>```

Title: Replacing values with groupby means

Body:
I have a DataFrame with a column that has some bad data with various negative values. I would like to replace values < 0 with the mean of the group that they are in.

For missing values as NAs, I would do:

data = df.groupby(['GroupID']).column
data.transform(lambda x: x.fillna(x.mean()))

But how to do this operation on a condition like x < 0?

Thanks!

Body:
I had the same issue and came up with a rather simple solution

func = lambda x : np.where(x < 0, x.mean(), x)

df['Bad_Column'].transform(func)

Note that if you want to return the mean of the correct values (mean based on positive values only)  you'd have to specify:

func = lambda x : np.where(x < 0, x.mask(x < 0).mean(), x)


问:
RxJava - make a request then request every time event happens
I found I have a common mechanic and I wonder if there is a better way to achieve it or an alternative way.

I want to make a network request when I subscribe to an Observable, and I want it to "refresh" - request again every time certain events happen, so the observable will become infinite.

for example let's say I have a request getScreenData() so when I open the screen I call it, but if there is an event such as relogin and needRefresh I want it to make the request again.

what I come up with is as follows:

```<code>Merge(onRelogin().map(a-> null),onNeedRefresh().map(r -> null)).switchMap(o->getData()).startWith(getData);
</code>```

I don't like it very much as I need to map all those events to some object just so I will be able to merge them (I don't care about the values...) and I need to write getData() twice for the switch and for the startWith to get what I want.

So is there a better way to achieve this? with other operators which will get me just that. and how would you make a transformer out of this? so you will get that pattern without repeating yourself, please not we can listen to as many observables as we want to make the request again.

Edit: Observable.merge() can return Observable thus solving the need for map

答:
Use the repeatWhen operator.

```<code>Observable
    .fromCallable(() -> getScreenData())
    .repeatWhen(it -> it.mergeWith(whenToRepeat))
    .subscribe()
</code>```

Where whenToRepeat is an observable that triggers a repeat by emmitting anything.

Further explanation of the repeatWhen operator here.

Body:
I found I have a common mechanic and I wonder if there is a better way to achieve it or an alternative way.

I want to make a network request when I subscribe to an Observable, and I want it to "refresh" - request again every time certain events happen, so the observable will become infinite.

for example let's say I have a request getScreenData() so when I open the screen I call it, but if there is an event such as relogin and needRefresh I want it to make the request again.

what I come up with is as follows:

Merge(onRelogin().map(a-> null),onNeedRefresh().map(r -> null)).switchMap(o->getData()).startWith(getData);

I don't like it very much as I need to map all those events to some object just so I will be able to merge them (I don't care about the values...) and I need to write getData() twice for the switch and for the startWith to get what I want.

So is there a better way to achieve this? with other operators which will get me just that. and how would you make a transformer out of this? so you will get that pattern without repeating yourself, please not we can listen to as many observables as we want to make the request again.

Edit: Observable.merge() can return Observable thus solving the need for map

Body:
Use the repeatWhen operator.

Observable
    .fromCallable(() -> getScreenData())
    .repeatWhen(it -> it.mergeWith(whenToRepeat))
    .subscribe()

Where whenToRepeat is an observable that triggers a repeat by emmitting anything.

Further explanation of the repeatWhen operator here.


问:
Can't Call result on futures tornado , always result object
```<code>from somefolder import somelibrary

@gen.coroutine
def detailproduct(url):
    datafromlib=yield somelibrary(url)
    raise gen.Return(datafromlib)
</code>```

expectation:
See the result without request handler.
not result like

```<code>{"data":<tornado.concurrent.future>}
</code>```

I try like this link:
"Can't call result() on futures in tornado"
But not work.

Somebody help me! tx

答:
There are the two rules that you've to keep in mind while working with gen.coroutine:

gen.coroutine decorated functions will automatically return a Future.

If a function/coroutine is calling another coroutine decorated with gen.coroutine, it must also be decorated with gen.coroutine and must use the yield keyword to get its result.

detailproduct is decorated with gen.coroutine - which means it will always return the datafromlib wrapped in a Future.

How to fix

According to Rule 2, you've to decorate the caller with gen.coroutine and use the yield keyword to get the result of the Future.

```<code>@gen.coroutine
def my_func():
    data = yield detailproduct(url)
    # do something with the data ...
</code>```

OR

You can set a callback function on the Future that will be called when it gets resolved. But it makes the code messy.

```<code>def my_fun():
    data_future = detailproduct(url)
    data_future.add_done_callback(my_callback)

def my_callback(future):
    data = future.result()
    # do something with the data ...
</code>```

Body:
from somefolder import somelibrary

@gen.coroutine
def detailproduct(url):
    datafromlib=yield somelibrary(url)
    raise gen.Return(datafromlib)

expectation:
See the result without request handler.
not result like

{"data":<tornado.concurrent.future>}

I try like this link:
"Can't call result() on futures in tornado"
But not work.

Somebody help me! tx

Body:
There are the two rules that you've to keep in mind while working with gen.coroutine:

gen.coroutine decorated functions will automatically return a Future.

If a function/coroutine is calling another coroutine decorated with gen.coroutine, it must also be decorated with gen.coroutine and must use the yield keyword to get its result.

detailproduct is decorated with gen.coroutine - which means it will always return the datafromlib wrapped in a Future.

How to fix

According to Rule 2, you've to decorate the caller with gen.coroutine and use the yield keyword to get the result of the Future.

@gen.coroutine
def my_func():
    data = yield detailproduct(url)
    # do something with the data ...

OR

You can set a callback function on the Future that will be called when it gets resolved. But it makes the code messy.

def my_fun():
    data_future = detailproduct(url)
    data_future.add_done_callback(my_callback)

def my_callback(future):
    data = future.result()
    # do something with the data ...


问:
How to create compile-time class fields using templates?

Little background and rationale

I am designing a compile-time ECS. The design has its specifics - for instance, there will be a great variety of entities. This means that the overall number of components is likely to be fairly high whilst number of components per entity will be fairly low (having some obvious present-almost-everywhere-commons such as Sprite or BoundingBox)

My approach

I would implement the following interface:

```<code>/* Tell the compiler which fields we would use in this entity */
Entity<GraphicsComponent, PhysicsComponent> entity;

/* Populate the handles with the appropriate data (integer, pointer, doesn't matter) */
// via explicit creation
Entity.add<GraphicsComponent>(RenderSystem::create<GraphicsComponent>());
// or in some other way?
</code>```

The inception of the Entity class I wrote:

```<code>template <typename ...>
class Entity final {};
</code>```

I have, however, no idea how would I create the handle data fields for the respective Component types, and if it is even possible at all. Can anyone help me or explain why it wouldn't work (or possibly suggest a different solution)?

答:
Just use std::tuple. N.b. the get requires that each of Components... is a distinct type

```<code>template <typename ... Components>
class Entity final {
    std::tuple<Components...> components;
    template<typename Component>
    void add(Component component) // possibly cv / ref qualified
    {
        std::get<std::decay_t<Component>>(components) = component;
    }
};
</code>```

Body:
Little background and rationale

I am designing a compile-time ECS. The design has its specifics - for instance, there will be a great variety of entities. This means that the overall number of components is likely to be fairly high whilst number of components per entity will be fairly low (having some obvious present-almost-everywhere-commons such as Sprite or BoundingBox)

My approach

I would implement the following interface:

/* Tell the compiler which fields we would use in this entity */
Entity<GraphicsComponent, PhysicsComponent> entity;

/* Populate the handles with the appropriate data (integer, pointer, doesn't matter) */
// via explicit creation
Entity.add<GraphicsComponent>(RenderSystem::create<GraphicsComponent>());
// or in some other way?

The inception of the Entity class I wrote:

template <typename ...>
class Entity final {};

I have, however, no idea how would I create the handle data fields for the respective Component types, and if it is even possible at all. Can anyone help me or explain why it wouldn't work (or possibly suggest a different solution)?

Body:
Just use std::tuple. N.b. the get requires that each of Components... is a distinct type

template <typename ... Components>
class Entity final {
    std::tuple<Components...> components;
    template<typename Component>
    void add(Component component) // possibly cv / ref qualified
    {
        std::get<std::decay_t<Component>>(components) = component;
    }
};


问:
Using application.caller to change other cells
If I for example have this in the code of a function:

```<code>If TypeOf Application.Caller Is Range Then
    Rng = Application.Caller
    With Rng
        With .Offset(0, -4)
            .Value = 0
        End With
        With .Offset(0, -6)
            .Value = 0
        End With
    End With
End If
</code>```

It returns error.

How would I go about changing the value of other cells using Application.Caller.Offset when calling a function?

答: You cannot change other cells in a function - Excel won't let you. This feature is by design: a function may only change the cell in which it is entered</p>

Body:
If I for example have this in the code of a function:

If TypeOf Application.Caller Is Range Then
    Rng = Application.Caller
    With Rng
        With .Offset(0, -4)
            .Value = 0
        End With
        With .Offset(0, -6)
            .Value = 0
        End With
    End With
End If

It returns error.

How would I go about changing the value of other cells using Application.Caller.Offset when calling a function?


问:
The operation cannot be started by an account that uses SQL Server Authentication error When running ssis from stored proc in SSRS
I am getting the following error:

The operation cannot be started by an account that uses SQL Server Authentication. Start the operation with an account that uses Windows Authentication

I have a ssrs report which uses a dataset derived from a stored procedure.  The stored procedure first creates an execution and executes a ssis package before drawing the data.  In visual studio I can preview the report fine.  The data source uses integrated security (though I wish I could pass a sql server account).  When I upload the report to SSRS it gives me the error about using an account with windows auth.  I checked the datasource on the server and it is set to use windows auth.  I'm not sure what I am doing wrong or how to fix this.

my sql server is 2012 r2 (ssrs is 2008)

答:
The issue is that you cannot execute SSIS packages which are stored on your SSISDB Catalog using a SQL Server account.

This is why changing the user which is attempting to start the SSIS package to a 'Windows Authentication user' works.

A similar issue can be found here;

https://social.msdn.microsoft.com/Forums/sqlserver/en-US/bbd2b556-8f68-4e04-94d1-754127886361/unable-to-execute-ssis-package-from-sql-server-login?forum=sqlintegrationservices


问:
Identify XPath from particular element
I'm working on a page, where page loads dynamically and the data gets added while scrolling. To identify the properties of an item, I identified the parent div, where to identify the address, I have to locate an XPath from the parent to span element.
Below is my DOM structure:

```<code><div class = "parentdiv">
    <div class = "search">
    <div class="header">
    <div class="data"></div>
    <div class="address-data">
      <div class="address" itemprop="address">
        <a itemprop="url" href="/search/Los-Angeles-CA-90025">
                <span itemprop="streetAddress">
                    Avenue
                </span>

                <br>
                <span itemprop="Locality">Los Angeles</span>
                <span itemprop="Region">CA</span>
            </a>
        </div>
        </div>
        </div>
    </div>
</div>
</div>
</code>```

Here I want to locate the three spans, where I' currently in parent div.
Can someone guide how to locate an element using XPath from particular div?

答:
To print the list of  tagged WebElements with texts like Avenue with respect to div class = "parentdiv" node you can use the following block of code :

```<code>IList<IWebElement> myList = Driver.FindElements(By.CssSelector("div.parentdiv > div.address > a[itemprop=url] > span"));
foreach (IWebElement element in myList)
{
    string my_add = element.GetAttribute("innerHTML");
    Console.WriteLine(my_add);
}
</code>```

Title: Identify XPath from particular element

Body:
I'm working on a page, where page loads dynamically and the data gets added while scrolling. To identify the properties of an item, I identified the parent div, where to identify the address, I have to locate an XPath from the parent to span element.
Below is my DOM structure:

                    Avenue

                Los Angeles
                CA

Here I want to locate the three spans, where I' currently in parent div.
Can someone guide how to locate an element using XPath from particular div?

Body:
To print the list of <span> tagged WebElements with texts like Avenue with respect to div class = "parentdiv" node you can use the following block of code :

IList<IWebElement> myList = Driver.FindElements(By.CssSelector("div.parentdiv > div.address > a[itemprop=url] > span"));
foreach (IWebElement element in myList)
{
    string my_add = element.GetAttribute("innerHTML");
    Console.WriteLine(my_add);
}


问:
Disable part of textarea content
I have textarea with a static content. So I disabled the textarea to prevent any modification in the content. But I want to modify some part of this content. How can I do this ?

I have created a select box as follows :

```<code><div class="scroll-inside">
    <?php if($transactionalTemplates->num_rows() > 0) {
        foreach($transactionalTemplates->result_array() as $template) { ?>
            <a href="#" class="transactionalTemplate" data-text="<?php echo $template['TemplateText']?>">
                <?php echo $template['TemplateText'];?>
            </a>

    <?php   }
       }
   ?>
</div>
</code>```

When I select an item, the selected item will pasted to the following textarea

```<code><textarea placeholder="Enter your message here.." maxlength="160" class="messageTransactional" name="messageTransactional" id="messageTransactionalEnglish"></textarea>
</code>```

here is my script code:

```<code>$('.transactionalTemplate').click(function() {
        $('.messageTransactional').val($(this).data('text'));
        flag = true;
        $('.messageTransactional').keypress(function(e) {
            e.preventDefault();
        });
    });
</code>```

After adding the content to textarea, I prevent typing new content using the above function.
here is an example:

Suppose Dear (123), thanks for registering with us. Please subscribe our new offer to send unlimited SMS. For details please call (123) is my content.

I need to edit this content as Dear John, thanks for registering with us. Please subscribe our new offer to send unlimited SMS. For details please call 91xxxxxxxx

Which means, I need to change the content in paranthesis, keeping the format static.

答:
I would highly suggest not using a textarea. There is no real way to stop that. You would need to do it yourself and try to catch every possibility to change that.

Instead, a simple text-input usually looks the best.

Alternatively, if it has to be seamless, you can use a contenteditable span, like this:

Dear (please enter your name here), thanks for registering with us. Please subscribe our new offer to send unlimited SMS. For details please call (please enter your tel. number here)```

Title: Disable part of textarea content

Body:
I have textarea with a static content. So I disabled the textarea to prevent any modification in the content. But I want to modify some part of this content. How can I do this ?

I have created a select box as follows :

    <?php if($transactionalTemplates->num_rows() > 0) {
        foreach($transactionalTemplates->result_array() as $template) { ?>
            <a href="#" class="transactionalTemplate" data-text="<?php echo $template['TemplateText']?>">
                <?php echo $template['TemplateText'];?>

    <?php   }
       }
   ?>

When I select an item, the selected item will pasted to the following textarea

<textarea placeholder="Enter your message here.." maxlength="160" class="messageTransactional" name="messageTransactional" id="messageTransactionalEnglish"></textarea>

here is my script code:

$('.transactionalTemplate').click(function() {
        $('.messageTransactional').val($(this).data('text'));
        flag = true;
        $('.messageTransactional').keypress(function(e) {
            e.preventDefault();
        });
    });

After adding the content to textarea, I prevent typing new content using the above function.
here is an example:

Suppose Dear (123), thanks for registering with us. Please subscribe our new offer to send unlimited SMS. For details please call (123) is my content.

I need to edit this content as Dear John, thanks for registering with us. Please subscribe our new offer to send unlimited SMS. For details please call 91xxxxxxxx

Which means, I need to change the content in paranthesis, keeping the format static.

Body:
I would highly suggest not using a textarea. There is no real way to stop that. You would need to do it yourself and try to catch every possibility to change that.

Instead, a simple text-input usually looks the best.

Alternatively, if it has to be seamless, you can use a contenteditable span, like this:

Dear <span contenteditable="true">(please enter your name here)</span>, thanks for registering with us. Please subscribe our new offer to send unlimited SMS. For details please call <span contenteditable="true">(please enter your tel. number here)</span>


问:
Hibernate : org.hibernate.PropertyAccessException: IllegalArgumentException
I have a parent table  (MHS_USER) and associated child table (GROUP) mapped with ManyToMany relation as follows (the relevant code below)

```<code>@Entity
@Table(name = "mhs_user")
public class MHSUser extends implements Comparable<User> {
        @ManyToMany(fetch = FetchType.EAGER, cascade = { CascadeType.ALL })
        @JoinTable(name = "user_group_rel", joinColumns = @JoinColumn(name = "mhs_user_id"), inverseJoinColumns = @JoinColumn(name = "group_id"))
        public List<Group> getGroups() {
                return groups;
        }
        public void setGroups(List<Group> groups) {
                this.groups = groups;
        }

}
</code>```

In the above, mhs_user_id  is the identity column in the MHS_USER table and grp_id is the identity key in the GROUP table. USER_GROUP_REL table is the join table that holds the relation between the two. When I persist a new User instance, it works as expected (by inserting a record into the parent table as well as the child table). However, when I try updating any values to the User instance, PropertyAccessException is thrown.  Below is the selective stack trace

```------------------------------------------------------------------------------------------
[1/14/11 13:59:10:154 CST] 0000004b SystemErr     R Caused by: org.hibernate.PropertyAccessException: IllegalArgumentException occurred calling getter of edu.mayo.hcdm.mhsr.businessobject.Group.id
        at org.hibernate.property.BasicPropertyAccessor$BasicGetter.get(BasicPropertyAccessor.java:171)
        at org.hibernate.tuple.entity.AbstractEntityTuplizer.getIdentifier(AbstractEntityTuplizer.java:183)
………………………………………………………………………………………………………………………………………………..
………………………………………………………………………………………………………………………………………………..
………………………………………………………………………………………………………………………………………………..
……………………………………………………………………………………………………………………………………………….. [1/14/11 13:59:10:154 CST] 0000004b SystemErr     R    ... 90 more
[1/14/11 13:59:10:154 CST] 0000004b SystemErr     R Caused by: java.lang.IllegalArgumentException: object is not an instance of declaring class
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:79)
------------------------------------------------------------------------------------------
```

It get’s confusing as Hibernate throws an error that the "object is not an instance of declaring class" when searching for the group_id from the GROUP table only on updates. I found a lot of threads online about it being a hibernate bug (am using Hibernate 3.3.1). Has anyone encountered the same problem and if so, how did you end up solving it?
Any input is highly appreciated.

答: Make sure groups list doesn't contain objects other than Groups - it seems to be the most obvious cause.

Body:
I have a parent table  (MHS_USER) and associated child table (GROUP) mapped with ManyToMany relation as follows (the relevant code below)

@Entity
@Table(name = "mhs_user")
public class MHSUser extends implements Comparable<User> {
        @ManyToMany(fetch = FetchType.EAGER, cascade = { CascadeType.ALL })
        @JoinTable(name = "user_group_rel", joinColumns = @JoinColumn(name = "mhs_user_id"), inverseJoinColumns = @JoinColumn(name = "group_id"))
        public List<Group> getGroups() {
                return groups;
        }
        public void setGroups(List<Group> groups) {
                this.groups = groups;
        }

}

In the above, mhs_user_id  is the identity column in the MHS_USER table and grp_id is the identity key in the GROUP table. USER_GROUP_REL table is the join table that holds the relation between the two. When I persist a new User instance, it works as expected (by inserting a record into the parent table as well as the child table). However, when I try updating any values to the User instance, PropertyAccessException is thrown.  Below is the selective stack trace

------------------------------------------------------------------------------------------
[1/14/11 13:59:10:154 CST] 0000004b SystemErr     R Caused by: org.hibernate.PropertyAccessException: IllegalArgumentException occurred calling getter of edu.mayo.hcdm.mhsr.businessobject.Group.id
        at org.hibernate.property.BasicPropertyAccessor$BasicGetter.get(BasicPropertyAccessor.java:171)
        at org.hibernate.tuple.entity.AbstractEntityTuplizer.getIdentifier(AbstractEntityTuplizer.java:183)
………………………………………………………………………………………………………………………………………………..
………………………………………………………………………………………………………………………………………………..
………………………………………………………………………………………………………………………………………………..
……………………………………………………………………………………………………………………………………………….. [1/14/11 13:59:10:154 CST] 0000004b SystemErr     R    ... 90 more
[1/14/11 13:59:10:154 CST] 0000004b SystemErr     R Caused by: java.lang.IllegalArgumentException: object is not an instance of declaring class
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:79)
------------------------------------------------------------------------------------------

It get’s confusing as Hibernate throws an error that the "object is not an instance of declaring class" when searching for the group_id from the GROUP table only on updates. I found a lot of threads online about it being a hibernate bug (am using Hibernate 3.3.1). Has anyone encountered the same problem and if so, how did you end up solving it?
Any input is highly appreciated.


问:
Sorting Struct array in Swift 4
I've got the below struct and would like to sort the items within sessions by startTime field. I'm completely lost on how to do this.

I tried:

```<code>let sortedArray = sessionsData?.items.sorted{ ($0["startTime"] as! String) < ($1["startTime"] as! String) }
</code>```

but that just gives me an error about no subscript members?

Any pointers would really be appreciated, thank you.

```<code>public struct sessions: Decodable {
  let status: String?
  let start: Int?
  let count: Int?
  let items: [sessionInfo]?
  let itemsCount: Int?
  let multipart: Bool?
  let startTime: Int?
  let endTime: Int?
}

public struct sessionInfo: Decodable {
  let name: String?
  let datalist: String?
  let sessionType: Int?
  let status: Int?
  let backupType: Int?
  let startTime: Int?
  let endTime: Int?
  let owner: String?
  let numOfErrors: Int?
  let numOfWarnings: Int?
  let flags: Int?
}
</code>```

I tried the below, but get an error:

```<code>var sortedArray = sessionsData?.items?.sorted(by: { (lhs, rhs) -> Bool in
        return lhs.startTime < rhs.startTime
    })
</code>```

error:

```<code>Binary operator '<' cannot be applied to two 'Int?' operands
</code>```

答:
Try below code, it sorts the struct in asc order but it pushes nil timestamps to bottom.
if you want nil timestamps to be at top, make all nil checks in below code to return opposite of what i return in below code.</p>

```<code>var sortedArray = sessionsData?.items?.sorted(by: { (lhs, rhs) -> Bool in

if let lhsTime = lhs.startTime, let rhsTime = rhs.startTime {
    return lhs.startTime < rhs.startTime
}

if lhs.startTime == nil && rhs.startTime == nil {
    // return true to stay at top
    return false
}

if lhs.startTime == nil {
    // return true to stay at top
    return false
}

if rhs.startTime == nil {
    // return false to stay at top
    return true
}

})
</code>```

Title: Sorting Struct array in Swift 4

Body:
I've got the below struct and would like to sort the items within sessions by startTime field. I'm completely lost on how to do this.

I tried:

let sortedArray = sessionsData?.items.sorted{ ($0["startTime"] as! String) < ($1["startTime"] as! String) }

but that just gives me an error about no subscript members?

Any pointers would really be appreciated, thank you.

public struct sessions: Decodable {
  let status: String?
  let start: Int?
  let count: Int?
  let items: [sessionInfo]?
  let itemsCount: Int?
  let multipart: Bool?
  let startTime: Int?
  let endTime: Int?
}

public struct sessionInfo: Decodable {
  let name: String?
  let datalist: String?
  let sessionType: Int?
  let status: Int?
  let backupType: Int?
  let startTime: Int?
  let endTime: Int?
  let owner: String?
  let numOfErrors: Int?
  let numOfWarnings: Int?
  let flags: Int?
}

I tried the below, but get an error:

var sortedArray = sessionsData?.items?.sorted(by: { (lhs, rhs) -> Bool in
        return lhs.startTime < rhs.startTime
    })

error:

Binary operator '<' cannot be applied to two 'Int?' operands

Body:
Try below code, it sorts the struct in asc order but it pushes nil timestamps to bottom.
if you want nil timestamps to be at top, make all nil checks in below code to return opposite of what i return in below code.

var sortedArray = sessionsData?.items?.sorted(by: { (lhs, rhs) -> Bool in

if let lhsTime = lhs.startTime, let rhsTime = rhs.startTime {
    return lhs.startTime < rhs.startTime
}

if lhs.startTime == nil && rhs.startTime == nil {
    // return true to stay at top
    return false
}

if lhs.startTime == nil {
    // return true to stay at top
    return false
}

if rhs.startTime == nil {
    // return false to stay at top
    return true
}

})


问:
JSON parse error from server when making request with Alamofire in swift 4
I need to make a post request to the api and obtain data from the response. The api returns the following response:

```<code>{
    valid: true
}
</code>```

or

```<code>{
    valid: false
}
</code>```

My Alamofire request looks something like this:

```<code>parameters = ["key": "somekey"]
let headers: HTTPHeaders = [
                "Content-Type": "application/json",
                "Authorization": "JWT \(token)"
            ]
Alamofire.request(baseURL, method: .post, parameters: parameters, headers: headers).responseJSON{
    response in
    if let result = response.result.value {
                        let JSON = result as! NSDictionary
                        print(JSON) //{ detail = "JSON parse error - Expecting value: line 1 column 1 (char 0)"}
                    }
</code>```

I can't seem to be able to get the JSON data from the server to extract the value of valid. Instead I get the error: detail = "JSON parse error - Expecting value: line 1 column 1 (char 0)" from the server

答:
Turns out I wasn't including one important parameter in the request encoding: JSONEncoding.default.(I guess the order matters) Here's what worked:

```<code>parameters = ["key": "somekey"]
let headers: HTTPHeaders = [
                "Content-Type": "application/json",
                "Authorization": "JWT \(token)"
            ]
Alamofire.request(baseURL, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers)
                .responseJSON{
                    response in
                    if let result = response.result.value {
                        let JSON = result as! NSDictionary
                        print(JSON) //SUCCESS :{valid: 0}
                    }
</code>```

Body:
I need to make a post request to the api and obtain data from the response. The api returns the following response:

{
    valid: true
}

or

{
    valid: false
}

My Alamofire request looks something like this:

parameters = ["key": "somekey"]
let headers: HTTPHeaders = [
                "Content-Type": "application/json",
                "Authorization": "JWT \(token)"
            ]
Alamofire.request(baseURL, method: .post, parameters: parameters, headers: headers).responseJSON{
    response in
    if let result = response.result.value {
                        let JSON = result as! NSDictionary
                        print(JSON) //{ detail = "JSON parse error - Expecting value: line 1 column 1 (char 0)"}
                    }

I can't seem to be able to get the JSON data from the server to extract the value of valid. Instead I get the error: detail = "JSON parse error - Expecting value: line 1 column 1 (char 0)" from the server

Body:
Turns out I wasn't including one important parameter in the request encoding: JSONEncoding.default.(I guess the order matters) Here's what worked:

parameters = ["key": "somekey"]
let headers: HTTPHeaders = [
                "Content-Type": "application/json",
                "Authorization": "JWT \(token)"
            ]
Alamofire.request(baseURL, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers)
                .responseJSON{
                    response in
                    if let result = response.result.value {
                        let JSON = result as! NSDictionary
                        print(JSON) //SUCCESS :{valid: 0}
                    }


问:
Emptying previous tabbed iframe contents each time new tab selected
I have a tabbed container with iframes in each tab (don't scold me... I have no alternative on this one). The contents of each iframe are very large, so when a user selects a different tab, I want the contents (HTML) of the iframe from the 'old' tab to be removed before the new tab and its iframe contents are loaded and displayed. In this way, only ever should the contents of the iframe in the currently selected tab be loaded, while all iframe content in the other tabs is empty.  I've researched how to clear iframe contents, but despite my efforts I'm just not able to apply it successfully to the tabs jquery code.  Can anyone help?  Fiddle: https://jsfiddle.net/kxh47qjo/

```<code>https://code.jquery.com/jquery-1.12.4.js
https://code.jquery.com/ui/1.12.1/jquery-ui.js
https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css

<div id="tabs">
  <ul>
    <li><a class="tabref" href="#tabs-1" rel="https://bing.com">Table1</a></li>
    <li><a class="tabref" href="#tabs-2" rel="https://jsfiddle.net">Table2</a></li>
    <li><a class="tabref" href="#tabs-3" rel="https://jqueryui.com/demos/tabs">Table3</a>
  </ul>

  <div id="tabs-1">
  </div>

  <div id="tabs-2">
  </div>

  <div id="tabs-3">
  </div>
</div>
</code>```

.

```<code>$(function() {

  var $tabs = $('#tabs').tabs();

  // Select start tab index number
  var MASTER_STARTtab = 0;
  $("#tabs").tabs({active: MASTER_STARTtab
  });

  //Get tab contents
  beginTab = $("#tabs ul li:eq(" + MASTER_STARTtab + ")").find("a");
  loadTabFrame($(beginTab).attr("href"), $(beginTab).attr("rel"));

  // -----------------------------------

  $("a.tabref").click(function() {
    loadTabFrame($(this).attr("href"), $(this).attr("rel"));
  });

  //tab switching function
  function loadTabFrame(tab, url) {
    if ($(tab).find("iframe").length == 0) {
      var html = [];
      html.push('<div class="tabIframeWrapper">');
      html.push('<div class="openout"><a href="' + url + '"><border="0"
alt="Open" title="Remove iFrame" /></a></div><iframe class="iframetab" src="' + url + '">Load Failed?</iframe>');
      html.push('</div>');
      $(tab).append(html.join(""));
      $(tab).find("iframe").height($(window).height() - 80);
    }
    return false;
  }
});
</code>```

答:
If I understood correctly, you want to remove the iframe div of the old tab. I think you can do that using the tabs event "beforeActivate", to access the old tab and remove the iframe div, or other element. Also take into account that loadTabFrame function always adds the iframe when you return to the tab.

```<code>  $( "#tabs" ).tabs({
    beforeActivate: function( event, ui ) {
      $(ui.oldPanel).find('div.tabIframeWrapper').remove();
    }
  });
</code>```

Here is the updated jsfiddle

Body:
I have a tabbed container with iframes in each tab (don't scold me... I have no alternative on this one). The contents of each iframe are very large, so when a user selects a different tab, I want the contents (HTML) of the iframe from the 'old' tab to be removed before the new tab and its iframe contents are loaded and displayed. In this way, only ever should the contents of the iframe in the currently selected tab be loaded, while all iframe content in the other tabs is empty.  I've researched how to clear iframe contents, but despite my efforts I'm just not able to apply it successfully to the tabs jquery code.  Can anyone help?  Fiddle: https://jsfiddle.net/kxh47qjo/

https://code.jquery.com/jquery-1.12.4.js
https://code.jquery.com/ui/1.12.1/jquery-ui.js
https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css

Table1

Table2

Table3

.

$(function() {

  var $tabs = $('#tabs').tabs();

  // Select start tab index number
  var MASTER_STARTtab = 0;
  $("#tabs").tabs({active: MASTER_STARTtab
  });

  //Get tab contents
  beginTab = $("#tabs ul li:eq(" + MASTER_STARTtab + ")").find("a");
  loadTabFrame($(beginTab).attr("href"), $(beginTab).attr("rel"));

  // -----------------------------------

  $("a.tabref").click(function() {
    loadTabFrame($(this).attr("href"), $(this).attr("rel"));
  });

  //tab switching function
  function loadTabFrame(tab, url) {
    if ($(tab).find("iframe").length == 0) {
      var html = [];
      html.push('
');
      html.push('
<border="0"
alt="Open" title="Remove iFrame" />
Load Failed?');
      html.push('
');
      $(tab).append(html.join(""));
      $(tab).find("iframe").height($(window).height() - 80);
    }
    return false;
  }
});

Body:
If I understood correctly, you want to remove the iframe div of the old tab. I think you can do that using the tabs event "beforeActivate", to access the old tab and remove the iframe div, or other element. Also take into account that loadTabFrame function always adds the iframe when you return to the tab.

  $( "#tabs" ).tabs({
    beforeActivate: function( event, ui ) {
      $(ui.oldPanel).find('div.tabIframeWrapper').remove();
    }
  });

Here is the updated jsfiddle


问:
normalizr -How to use for grouping based on a property
I need to restructure the data from server API to use in my client application and I came to know about normalizr. I am trying to use this library if possible.

The structure of the data is as follows.

```<code>{
    "history": [{
            "_id": "5a09d7a48134664b58eb9ff7",
            "created": "2017-11-13"
        }, {
            "_id": "5a09d79c8134664b58eb9ff6",
            "created": "2017-11-13"
        }, {
            "_id": "5a09d7968134664b58eb9ff5",
            "created": "2017-11-13"
        }, {
            "_id": "5a0349da81069a3754ac1a91",
            "created": "2017-11-08"
        }
    ]
}
</code>```

I want to group this based on 'created', as follows.

```<code>{
    "history": {
        "2017-11-13": [{
                "_id": "5a09d7a48134664b58eb9ff7",
                "created": "2017-11-13"
            }, {
                "_id": "5a09d79c8134664b58eb9ff6",
                "created": "2017-11-13"
            }, {
                "_id": "5a09d7968134664b58eb9ff5",
                "created": "2017-11-13"
            }

        ],
        "2017-11-08": [{
                "_id": "5a0349da81069a3754ac1a91",
                "created": "2017-11-08"
            }
        ]
    }
}
</code>```

How to do this with normalizr? I know what I need is just restructuring of the data, is normalizr the best option for this?

答:
You could use ES6 version to accomplish this by the following function

```<code>function grouping (arr, key) {
 return (arr || []).reduce((acc, x = {}) => ({
  ...acc,
   [x[key]]: [...acc[x[key]] || [], x]
 }), {})
}
</code>```

which takes two parameters, array and the key for grouping by

function grouping (arr, key) {
  return (arr || []).reduce((acc, x = {}) => ({
    ...acc,
    [x[key]]: [...acc[x[key]] || [], x]
  }), {})
}

let history = [{
            "_id": "5a09d7a48134664b58eb9ff7",
            "created": "2017-11-13"
        }, {
            "_id": "5a09d79c8134664b58eb9ff6",
            "created": "2017-11-13"
        }, {
            "_id": "5a09d7968134664b58eb9ff5",
            "created": "2017-11-13"
        }, {
            "_id": "5a0349da81069a3754ac1a91",
            "created": "2017-11-08"
        }
    ];
console.log(grouping(history,'created'));```

Body:
I need to restructure the data from server API to use in my client application and I came to know about normalizr. I am trying to use this library if possible.

The structure of the data is as follows.

{
    "history": [{
            "_id": "5a09d7a48134664b58eb9ff7",
            "created": "2017-11-13"
        }, {
            "_id": "5a09d79c8134664b58eb9ff6",
            "created": "2017-11-13"
        }, {
            "_id": "5a09d7968134664b58eb9ff5",
            "created": "2017-11-13"
        }, {
            "_id": "5a0349da81069a3754ac1a91",
            "created": "2017-11-08"
        }
    ]
}

I want to group this based on 'created', as follows.

{
    "history": {
        "2017-11-13": [{
                "_id": "5a09d7a48134664b58eb9ff7",
                "created": "2017-11-13"
            }, {
                "_id": "5a09d79c8134664b58eb9ff6",
                "created": "2017-11-13"
            }, {
                "_id": "5a09d7968134664b58eb9ff5",
                "created": "2017-11-13"
            }

        ],
        "2017-11-08": [{
                "_id": "5a0349da81069a3754ac1a91",
                "created": "2017-11-08"
            }
        ]
    }
}

How to do this with normalizr? I know what I need is just restructuring of the data, is normalizr the best option for this?

Body:
You could use ES6 version to accomplish this by the following function

function grouping (arr, key) {
 return (arr || []).reduce((acc, x = {}) => ({
  ...acc,
   [x[key]]: [...acc[x[key]] || [], x]
 }), {})
}

which takes two parameters, array and the key for grouping by

function grouping (arr, key) {
  return (arr || []).reduce((acc, x = {}) => ({
    ...acc,
    [x[key]]: [...acc[x[key]] || [], x]
  }), {})
}

let history = [{
            "_id": "5a09d7a48134664b58eb9ff7",
            "created": "2017-11-13"
        }, {
            "_id": "5a09d79c8134664b58eb9ff6",
            "created": "2017-11-13"
        }, {
            "_id": "5a09d7968134664b58eb9ff5",
            "created": "2017-11-13"
        }, {
            "_id": "5a0349da81069a3754ac1a91",
            "created": "2017-11-08"
        }
    ];
console.log(grouping(history,'created'));


问:
Binding database resultset array into a comma seperated string in php
I have an array which is an output of a database query like this(in JSON format) :

```<code>[
 {
  "id":1,
  "name":"Category group sidebar",
  "location":"category_group_sidebar",
  "width":250,
  "height":225
  },
{
  "id":2,
  "name":"Category sidebar",
  "location":"category_sidebar",
  "width":250,
  "height":225
  }
]
</code>```

I want this result to be appended with following string and results to be comma separated as following:

```<code>The ad space names are Category group sidebar,Category sidebar and the dimensions are 250,225
</code>```

答:
Try this (can't test):

```<code>$json = json_decode($json_data, true);

$insert = "";

foreach ($json as $data) {
  $insert .= $data['name'] . ",";
}

$insert = rtrim($insert, ",");

$text = "The ad space names are {$insert} and the dimensions are 250,225"
</code>```

New response:

```<code>$json = json_decode($json_data, true);

$insert = "";

foreach ($json as $data) {
  $insert .= $data['name'] . " with dimension " . $data['width'] . "*" . $data['height'] . ",";
}

$insert = rtrim($insert, ",");

$text = "Ad spaces are, {$insert}"
</code>```

Body:
I have an array which is an output of a database query like this(in JSON format) :

[
 {
  "id":1,
  "name":"Category group sidebar",
  "location":"category_group_sidebar",
  "width":250,
  "height":225
  },
{
  "id":2,
  "name":"Category sidebar",
  "location":"category_sidebar",
  "width":250,
  "height":225
  }
]

I want this result to be appended with following string and results to be comma separated as following:

The ad space names are Category group sidebar,Category sidebar and the dimensions are 250,225

Body:
Try this (can't test):

$json = json_decode($json_data, true);

$insert = "";

foreach ($json as $data) {
  $insert .= $data['name'] . ",";
}

$insert = rtrim($insert, ",");

$text = "The ad space names are {$insert} and the dimensions are 250,225"

New response:

$json = json_decode($json_data, true);

$insert = "";

foreach ($json as $data) {
  $insert .= $data['name'] . " with dimension " . $data['width'] . "*" . $data['height'] . ",";
}

$insert = rtrim($insert, ",");

$text = "Ad spaces are, {$insert}"


问:
Replace everything not in the String
I know when I use .replace I can replace a specified String for another string. For example:

```<code>String string = “hi fjrkfinnek”;

string.replace(“fjrkfinnek”, “”);
</code>```

I know using this will replace that specified part of the string with a blank space in this example. However, is it possible to remove everything that’s not “hi” instead of referencing what I want to replace?

The output I would desire is to remove everything but Hi by saying Remove everything that’s not Hi if that can be done!

答:
Right now you are asking: howto remove all that is "not X" from

```<code>Xxyz
</code>```

The simple answer is: when you already know that X is supposed to be the leftover, then well "X" should do.

And a bit more seriously: one could think of using regular expressions here - but they only allow you to match something. Not to match on "not something".

You could start with [^hi] - but this doesn't do what you hope for: it simply says: anything that doesn't contain h/i will match.

Title: Replace everything not in the String

Body:
I know when I use .replace I can replace a specified String for another string. For example:

String string = “hi fjrkfinnek”;

string.replace(“fjrkfinnek”, “”);

I know using this will replace that specified part of the string with a blank space in this example. However, is it possible to remove everything that’s not “hi” instead of referencing what I want to replace?

The output I would desire is to remove everything but Hi by saying Remove everything that’s not Hi if that can be done!

Body:
Right now you are asking: howto remove all that is "not X" from

Xxyz

The simple answer is: when you already know that X is supposed to be the leftover, then well "X" should do.

And a bit more seriously: one could think of using regular expressions here - but they only allow you to match something. Not to match on "not something".

You could start with [^hi] - but this doesn't do what you hope for: it simply says: anything that doesn't contain h/i will match.


问:
delete duplicate records without using common table expression (CTE)
I know how to delete duplicate records using CTE.

How can we achieve this without using CTE [Interview Question]

Is it possible?

Example: Table with the following data:

```<code>name     salary
-----------------
Husain   20000.00
Husain   20000.00
Husain   20000.00
Munavvar 50000.00
Munavvar 50000.00
</code>```

After deleting the duplicate records
table should contains data like this :

```<code>name     salary
-----------------
Husain   20000.00
Munavvar 50000.00
</code>```

答:
Most common use of Common Table Expression (CTE) is  Deleting duplicate record from table which not having Primary Key

```<code>WITH a as
(
SELECT A,ROW_NUMBER() OVER(PARTITION by A, B ORDER BY A)
AS duplicateRecCount dbo.A
)
--Now Delete Duplicate Records
DELETE FROM A
WHERE duplicateRecCount > 1 [enter image description here][1]
</code>```

Body:
I know how to delete duplicate records using CTE.

How can we achieve this without using CTE [Interview Question]

Is it possible?

Example: Table with the following data:

name     salary
-----------------
Husain   20000.00
Husain   20000.00
Husain   20000.00
Munavvar 50000.00
Munavvar 50000.00

After deleting the duplicate records
table should contains data like this :

name     salary
-----------------
Husain   20000.00
Munavvar 50000.00

Body:
Most common use of Common Table Expression (CTE) is  Deleting duplicate record from table which not having Primary Key

WITH a as
(
SELECT A,ROW_NUMBER() OVER(PARTITION by A, B ORDER BY A)
AS duplicateRecCount dbo.A
)
--Now Delete Duplicate Records
DELETE FROM A
WHERE duplicateRecCount > 1 [enter image description here][1]


问:
Keeping trailing zero's when transferring from excel to word VBA
I have this VBA code, where i pull data from word to Excel and then i transfer other data the other way around.

I have this code:
Call findAndReplace(Replace(Round(vbaSheet.Cells(i, "U").Value, 2), ",", "."), "Freight:", 3)

And this code for example takes a number like this from excel "155,40" and returns it to word as this "155.4".

This problem only occurs when there's a zero at the end of the decimals. But i want the number to be transferred as "155.40".
What can i add to t

The returned number in word
The number from excel

答:
```<code>Format(findAndReplace(...),"0.00")
</code>```

Or

```<code>vbaSheet.Cells(i, "U").NumberFormat = "0.00"
</code>```

is exactly what you need. Format takes the value and it forces it to return two digits after the comma.

Simply select tha cell and run this:

```<code>Sub Makro1()
    Selection.NumberFormat = "0.00"
End Sub
</code>```

Then make it work in your loop.

https://msdn.microsoft.com/en-us/vba/language-reference-vba/articles/format-function-visual-basic-for-applications

Body:
Format(findAndReplace(...),"0.00")

Or

vbaSheet.Cells(i, "U").NumberFormat = "0.00"

is exactly what you need. Format takes the value and it forces it to return two digits after the comma.

Simply select tha cell and run this:

Sub Makro1()
    Selection.NumberFormat = "0.00"
End Sub

Then make it work in your loop.

https://msdn.microsoft.com/en-us/vba/language-reference-vba/articles/format-function-visual-basic-for-applications


问:
Why can't get the main window handle for a started process?
I have a situation where I'm starting a process in my code in order to set up an IPC channel.  The process I'm starting is an MFC application with no CLR support.  The application from which I am starting this process is a C# module in a WPF application (thought I don't think that that is consequential to my problem).  This works with a version of the application that does support CLR, and it works on every computer except the deployment target, a touch screen computer with Windows 7.   But for some reason, when I try it with this exact scenario, the Process object never resolves a main window handle (Process.MainWindowHandle).   Is there another (perhaps even pinvoke) method of doing this?  Is this a security thing?  I'm the one staring the process.  The process's main window handle does exist.  I don't see what could be wrong.

If it helps, here is my code.

```<code>        _applicationProcess = new Process();
        _applicationProcess.StartInfo.FileName = _strProcessPath;
        _applicationProcess.StartInfo.Arguments = _strProcessArguments;
        _applicationProcess.Start();

        long nTicks = Environment.TickCount;
        if (_applicationProcess.WaitForInputIdle(1 /*minute(s)*/ * 60000))
        {
            try
            {
                do
                {
                    // Don't let total processing take more than 1 minute(s).
                    if (Environment.TickCount > nTicks + 1 /*minute(s)*/ * 60000)
                        throw new ApplicationException("MFCApplication.Startup failed! The main window handle is zero!");

                    _applicationProcess.Refresh();
                }
                while (_applicationProcess.MainWindowHandle.ToInt32() == 0);

                _applicationHandle = new IntPtr(_applicationProcess.MainWindowHandle.ToInt32());
            }
            catch (Exception ex)
            {
                //Do some stuff...
                throw;
            }
        }
        else
        {
            // Do exception handling.
        }
</code>```

The ApplicationException is hit after a minute of trying to get a main window handle other than zero.

答:
I don't know why it could be different, but after you create the process, try doing:

```<code>Process[] allProcesses = Process.GetProcessesByName("YourWindowTitle");
</code>```

and see if any of the processes returned have a MainWindowHandle.

Body:
I have a situation where I'm starting a process in my code in order to set up an IPC channel.  The process I'm starting is an MFC application with no CLR support.  The application from which I am starting this process is a C# module in a WPF application (thought I don't think that that is consequential to my problem).  This works with a version of the application that does support CLR, and it works on every computer except the deployment target, a touch screen computer with Windows 7.   But for some reason, when I try it with this exact scenario, the Process object never resolves a main window handle (Process.MainWindowHandle).   Is there another (perhaps even pinvoke) method of doing this?  Is this a security thing?  I'm the one staring the process.  The process's main window handle does exist.  I don't see what could be wrong.

If it helps, here is my code.

        _applicationProcess = new Process();
        _applicationProcess.StartInfo.FileName = _strProcessPath;
        _applicationProcess.StartInfo.Arguments = _strProcessArguments;
        _applicationProcess.Start();

        long nTicks = Environment.TickCount;
        if (_applicationProcess.WaitForInputIdle(1 /*minute(s)*/ * 60000))
        {
            try
            {
                do
                {
                    // Don't let total processing take more than 1 minute(s).
                    if (Environment.TickCount > nTicks + 1 /*minute(s)*/ * 60000)
                        throw new ApplicationException("MFCApplication.Startup failed! The main window handle is zero!");

                    _applicationProcess.Refresh();
                }
                while (_applicationProcess.MainWindowHandle.ToInt32() == 0);

                _applicationHandle = new IntPtr(_applicationProcess.MainWindowHandle.ToInt32());
            }
            catch (Exception ex)
            {
                //Do some stuff...
                throw;
            }
        }
        else
        {
            // Do exception handling.
        }

The ApplicationException is hit after a minute of trying to get a main window handle other than zero.

Body:
I don't know why it could be different, but after you create the process, try doing:

Process[] allProcesses = Process.GetProcessesByName("YourWindowTitle");

and see if any of the processes returned have a MainWindowHandle.


问:
C# - T type, array, list indexing
I want to write a method where i can send any type of [], List<>...etc. But in the code when I use T and I want to index the input array, list or anything the error says "Cannot apply indexing with [] to an expression of type 'T'". Theres any solution for this or I have to write a separate code for array, list..etc?

public void NormSort<T>(ref T input, int n)
{
    for (int i = 0; i < n - 2; i++)
    {
        for (int j = 0; j < n - 1; j++)
        {
            if (Comparer<T>.Default.Compare(input[i], input[j]) > 0)
            {
                Swap<T>(input[i], input[j]);
            }
        }
    }
}

public void Swap<T>(T item1, T item2)
 {
     var temp = item1;
     item1 = item2;
     item2 = temp;
 }
```

So wheres the input[i], input[j], there i got that error.

答:
Use IEnumerable and you can have all type of collections:</p>

```<code>public void NormSort<T>(ref IEnumerable<T> input, int n)
{ ...
}
</code>```

Title: C# - T type, array, list indexing

Body:
I want to write a method where i can send any type of [], List<>...etc. But in the code when I use T and I want to index the input array, list or anything the error says "Cannot apply indexing with [] to an expression of type 'T'". Theres any solution for this or I have to write a separate code for array, list..etc?

public void NormSort<T>(ref T input, int n)
{
    for (int i = 0; i < n - 2; i++)
    {
        for (int j = 0; j < n - 1; j++)
        {
            if (Comparer<T>.Default.Compare(input[i], input[j]) > 0)
            {
                Swap<T>(input[i], input[j]);
            }
        }
    }
}

public void Swap<T>(T item1, T item2)
 {
     var temp = item1;
     item1 = item2;
     item2 = temp;
 }

So wheres the input[i], input[j], there i got that error.

Body:
Use IEnumerable and you can have all type of collections:

public void NormSort<T>(ref IEnumerable<T> input, int n)
{ ...
}


问:
Attribute img not allowed on element img at this point
Hello I've got a problem.
I started coding yesterday and I got an error when I wanted to verify my website on W3Validator:

Error: Attribute img not allowed on element img at this point.

Here is the code which causes the problem:

```<code><li><a href="https://twitter.com/Koeen_Yt?lang=fr"><img src="twitter.png" alt="Twitter" img style="vertical-align:middle" width="100" height="85" > Follow moi grow ! </a></li>
</code>```

答:
You are trying to define a boolean attribute. But since img is not a boolean attribute, it causes the error. Validator expects an assignment to the attribute. Custom attributes without assignments are not allowed except boolean. If you need to add attributes, there are following ways:

use img=""

use data-img=""

Refer: https://www.w3.org/TR/html5/dom.html#custom-data-attribute

https://www.w3.org/TR/html/syntax.html#elements-attributes

https://www.w3.org/TR/html5/embedded-content-0.html#the-img-element

Body:
Hello I've got a problem.
I started coding yesterday and I got an error when I wanted to verify my website on W3Validator:

Error: Attribute img not allowed on element img at this point.

Here is the code which causes the problem:

 Follow moi grow !


问:
How to download yaml as it is on linux box using python
I have yaml file ex:http://server:1234/test.yaml WebUrl
When I download the file with below code on Linux box, its became HTML file, But I need an exact replica of yaml file.

```<code>import urllib
urllib.urlretrieve('http://server:1234/test.yaml','downloaded.yaml')
</code>```

but the downloaded.yaml file in HTML format rather a yaml file.

how to download same as yaml?

答:
You can either try and persuade the webserver to serve it as plain text (application/x-yaml, text/x-yaml), or you will have to parse the HTML to extract the yaml.

The latter will be painful, because things like & and < which are not special to yaml, will be escaped in the HTML.  There are plenty of libraries to help parse HTML (but a request for which one to use is explicitly off-topic on Stack Overflow).

If you have any influence over the webserver, I would strongly recommend trying to make it serve the file as text.

Body:
I have yaml file ex:http://server:1234/test.yaml WebUrl
When I download the file with below code on Linux box, its became HTML file, But I need an exact replica of yaml file.

import urllib
urllib.urlretrieve('http://server:1234/test.yaml','downloaded.yaml')

but the downloaded.yaml file in HTML format rather a yaml file.

how to download same as yaml?


问:
Cloud Functions for Firebase firebase deploy error: "Error parsing triggers: Cannot find module 'firebase-admin'"
When I run firebase deploy I get this error:

```<code>Error parsing triggers: Cannot find module 'firebase-admin'
</code>```

Here's my code:

```<code>const functions = require('firebase-functions');

const admin = require('firebase-admin');
</code>```

My package.json is:

```<code>  {
  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "dependencies": {
    "firebase-admin": "^5.2.1",
    "firebase-functions": "^0.6.2",
    "request": "^2.83.0"
  },
  "private": true
}
</code>```

Here are my global node modules:

```<code>npm list -g --depth=0
/Users/TDK/.nvm/versions/node/v6.11.2/lib
├── child_process@1.0.2
├── firebase-admin@5.3.0
├── firebase-tools@3.12.0
├── fs@0.0.2
├── npm@5.4.2
└── request@2.83.0
</code>```

I don't have firebase-admin installed locally:

Running npm install, npm install firebase-admin, and npm install --save firebase-admin in the local functions directory return this error message:

```<code>npm ERR! Cannot read property '0' of undefined
</code>```

I'm using npm version 5.4.2.

I changed ~5.2.1 to ^5.2.1.

I removed package-lock.json but that didn't fix the problem.

I get the same error message when I do this in the project root directory and in the functions directory.

Any suggestions?

答:
```<code>rm -rf node_modules/

npm install
</code>```

This did the trick for me.

Body:
When I run firebase deploy I get this error:

Error parsing triggers: Cannot find module 'firebase-admin'

Here's my code:

const functions = require('firebase-functions');

const admin = require('firebase-admin');

My package.json is:

  {
  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "dependencies": {
    "firebase-admin": "^5.2.1",
    "firebase-functions": "^0.6.2",
    "request": "^2.83.0"
  },
  "private": true
}

Here are my global node modules:

npm list -g --depth=0
/Users/TDK/.nvm/versions/node/v6.11.2/lib
├── child_process@1.0.2
├── firebase-admin@5.3.0
├── firebase-tools@3.12.0
├── fs@0.0.2
├── npm@5.4.2
└── request@2.83.0

I don't have firebase-admin installed locally:

Running npm install, npm install firebase-admin, and npm install --save firebase-admin in the local functions directory return this error message:

npm ERR! Cannot read property '0' of undefined

I'm using npm version 5.4.2.

I changed ~5.2.1 to ^5.2.1.

I removed package-lock.json but that didn't fix the problem.

I get the same error message when I do this in the project root directory and in the functions directory.

Any suggestions?

Body:
rm -rf node_modules/

npm install

This did the trick for me.


问:
SQL Developer returns query results on one computer but not on another
I can run a query on views in SQL Developer 3.1.07 and it returns the results I expect. My co-worker, who is in Mexico using the same user, can connect to the same database, sees the same views, runs the same query and gets no results, even from a simple "select * from VIEWNAME" query. The column headers display, but no data. If he selects a view from the connections window and selects the DATA tab no data displays. This user does not have access to any tables on this specific database.

I'm not certain he is running the same version of Developer, but it's not far off. I have checked as many settings in SQL Developer that I think could be the issue, but see no significant difference in his settings from mine.

Connecting to another database allows him to access data in both tables and views

Any thoughts on what we're missing?

答:
I know I'm a few years late, but check if the underlying view doesn't filter on something that is based on localisation! I just had the issue and it turned out to be a statment like this that was causing issues:</p>

```<code>SELECT *
FROM sometable
WHERE language = userenv('LANG')
</code>```

Body:
I know I'm a few years late, but check if the underlying view doesn't filter on something that is based on localisation! I just had the issue and it turned out to be a statment like this that was causing issues:

SELECT *
FROM sometable
WHERE language = userenv('LANG')


问:
How to create a second set of records in Oracle
I have set of records:

```<code>Title     Format
ABC       CD
DEF       CD
</code>```

I want to add a an additional format. The final set will look like:

```<code>Title     Format
ABC       CD
DEF       CD
ABC       LP
DEF       LP
</code>```

What will the query look like?

答:
I would use UNION ALL

```<code>SELECT title, format FROM table
UNION ALL
SELECT title, 'LP' FROM table
</code>```

Body:
I have set of records:

Title     Format
ABC       CD
DEF       CD

I want to add a an additional format. The final set will look like:

Title     Format
ABC       CD
DEF       CD
ABC       LP
DEF       LP

What will the query look like?

Body:
I would use UNION ALL

SELECT title, format FROM table
UNION ALL
SELECT title, 'LP' FROM table


答:
Well there are of course methods to make this working. For example replace accepts regex which is capable of negating by using negative lookahead (How to negate specific word in regex?). Or you can manually traverse the input etc.

Solution

However there is a much more easy solution. If you want to delete everything which is not foo in your input

```<code>test foo bar 123 test
</code>```

then the result can either be completely empty (if foo is not contained) or only foo (if it was contained). So simply check for your needle being present:

```<code>public String deleteAllExceptFirst(String input, String needle) {
    if (input.contains(needle)) {
        return needle;
    } else {
        return "";
    }
}
</code>```

Multiple instances

Note that if you want to preserve multiple foo occurrences you need additional work. Just count how many times foo is contained and then print it concatenated:

```<code>public String deleteAllExcept(String input, String needle) {
    StringBuilder sb = new StringBuilder();

    // Find all occurrences
    Pattern needlePatt = Pattern.compile(needle);
    Matcher matcher = needlePatt.matcher(input);
    while (m.find()) {
        // Build the result
        sb.append(needle);
    }

    return sb.toString();
}
</code>```

For the test input

```<code>test foo bar 123 test foo foo bar foo
</code>```

this yields

```<code>foofoofoofoo
</code>```

Title: Replace everything not in the String

Body:
Well there are of course methods to make this working. For example replace accepts regex which is capable of negating by using negative lookahead (How to negate specific word in regex?). Or you can manually traverse the input etc.

Solution

However there is a much more easy solution. If you want to delete everything which is not foo in your input

test foo bar 123 test

then the result can either be completely empty (if foo is not contained) or only foo (if it was contained). So simply check for your needle being present:

public String deleteAllExceptFirst(String input, String needle) {
    if (input.contains(needle)) {
        return needle;
    } else {
        return "";
    }
}

Multiple instances

Note that if you want to preserve multiple foo occurrences you need additional work. Just count how many times foo is contained and then print it concatenated:

public String deleteAllExcept(String input, String needle) {
    StringBuilder sb = new StringBuilder();

    // Find all occurrences
    Pattern needlePatt = Pattern.compile(needle);
    Matcher matcher = needlePatt.matcher(input);
    while (m.find()) {
        // Build the result
        sb.append(needle);
    }

    return sb.toString();
}

For the test input

test foo bar 123 test foo foo bar foo

this yields

foofoofoofoo


问:
How to get a group of toggle buttons to act like radio buttons in WPF?
I have a group of buttons that should act like toggle buttons, but also as radio buttons where only one button can be selected / pressed down at a current time. It also need to have a state where none of the buttons are selected / pressed down.

The behavior will be kind of like Photoshop toolbar, where zero or one of the tools are selected at any time!

Any idea how this can be implemented in WPF?

答:
To help people like Julian and me (two minutes ago...). You can derive from the RadioButton like this.

```<code>class RadioToggleButton : RadioButton
{
    protected override void OnToggle()
    {
        if (IsChecked == true) IsChecked = IsThreeState ? (bool?)null : (bool?)false;
        else IsChecked = IsChecked.HasValue;
    }
}
</code>```

Then, you can use it like Uday Kiran suggested...

```<code><Window x:Class="Sample.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:Sample"
    Title="MainWindow" Height="600" Width="600">
    <StackPanel>
        <local:RadioToggleButton Content="Button" Style="{StaticResource {x:Type ToggleButton}}" />
    </StackPanel>
</Window>
</code>```

This method allows only one ToggleButton to be Checked at a time, and it also allows UnChecking.

Body:
To help people like Julian and me (two minutes ago...). You can derive from the RadioButton like this.

class RadioToggleButton : RadioButton
{
    protected override void OnToggle()
    {
        if (IsChecked == true) IsChecked = IsThreeState ? (bool?)null : (bool?)false;
        else IsChecked = IsChecked.HasValue;
    }
}

Then, you can use it like Uday Kiran suggested...

<Window x:Class="Sample.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:Sample"
    Title="MainWindow" Height="600" Width="600">
    <StackPanel>
        <local:RadioToggleButton Content="Button" Style="{StaticResource {x:Type ToggleButton}}" />
    </StackPanel>
</Window>

This method allows only one ToggleButton to be Checked at a time, and it also allows UnChecking.