问:
excel won't close after procedure is run
I run this code and excel session won't destroy or close.  I know that I am not using sheets.add or ws.delete because it says With Validation and I don't know how to use the single lines declaring my objects.  I don't know the syntax I guess.  Here is the code.  Can someone point out how to fix it?

```<code>Public Function ComboLists()
Dim xlApp As Excel.Application
Dim wb As Excel.Workbook
Dim ws As Excel.Worksheet
Dim MyFileName As String
Dim bfile As String
Dim MyList(1) As String
Dim lRow As Long

bfile = "S:\_Reports\KSMS\Designated Letter\KSMS Designated Letter - "

MyFileName = bfile & Format(Date, "mm-dd-yyyy") & ".xls"

On Error Resume Next
Set xlApp = CreateObject("Excel.Application")
On Error GoTo 0

Set wb = xlApp.Workbooks.Open(MyFileName)
Set ws = wb.Sheets(1)
ws.Activate
xlApp.DisplayAlerts = False

MyList(0) = "Approve Location"
MyList(1) = "Delete Location"

lRow = ws.Cells(Rows.Count, 1).End(xlUp).Row

i = 2

For Each c In wb.Sheets(1).Range("M" & lRow)

If ws.Cells(i, 12).Value = "US" Then
rng = "M" & i '& ":" & "Z" & i

With Range(rng).Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
     Operator:=xlBetween, Formula1:=Join(MyList, ",")
wb.CheckCompatibility = False
wb.Save
wb.CheckCompatibility = True
End With
Else
rng = "A" & i & ":" & "L" & i
With xlApp.Range(rng).Validation
ws.Delete
wb.CheckCompatibility = False
wb.Save
wb.CheckCompatibility = True
'wb.Close savechanges:=False
End With
End If

i = i + 1

Next c

Set ws = wb.Sheets(1)
ws.Activate

ws.Cells.Rows("1:1").Select

wb.CheckCompatibility = False
wb.Save
wb.CheckCompatibility = True
wb.Close savechanges:=False

xlApp.Quit
xlApp.Quit
xlApp.Quit
xlApp.Quit

Set xlApp = Nothing
Set wb = Nothing
Set ws = Nothing

Exit Function

End Function
</code>```

I would appreciate any help on this.

答:
Change

```<code>lRow = ws.Cells(Rows.Count, 1).End(xlUp).Row
</code>```

to

```<code>lRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
</code>```

or else you will still have a reference to the Excel application after your code finishes.

With the unqualified Rows, your application (Word? Access? PowerPoint?) needs to create a dummy ActiveSheet object to be used by the method.  Until that dummy object is destroyed, an instance of Excel needs to be maintained.  That object won't get destroyed until you exit your application and therefore the instance of Excel will hang around until you exit your app.

I didn't spot it originally, but you also have an unqualified Range

```<code>With Range(rng).Validation
</code>```

will need to be

```<code>With ws.Range(rng).Validation
</code>```

The golden rule of using multiple Application objects is always fully qualify everything.

Body:
I run this code and excel session won't destroy or close.  I know that I am not using sheets.add or ws.delete because it says With Validation and I don't know how to use the single lines declaring my objects.  I don't know the syntax I guess.  Here is the code.  Can someone point out how to fix it?

Public Function ComboLists()
Dim xlApp As Excel.Application
Dim wb As Excel.Workbook
Dim ws As Excel.Worksheet
Dim MyFileName As String
Dim bfile As String
Dim MyList(1) As String
Dim lRow As Long

bfile = "S:\_Reports\KSMS\Designated Letter\KSMS Designated Letter - "

MyFileName = bfile & Format(Date, "mm-dd-yyyy") & ".xls"

On Error Resume Next
Set xlApp = CreateObject("Excel.Application")
On Error GoTo 0

Set wb = xlApp.Workbooks.Open(MyFileName)
Set ws = wb.Sheets(1)
ws.Activate
xlApp.DisplayAlerts = False

MyList(0) = "Approve Location"
MyList(1) = "Delete Location"

lRow = ws.Cells(Rows.Count, 1).End(xlUp).Row

i = 2

For Each c In wb.Sheets(1).Range("M" & lRow)

If ws.Cells(i, 12).Value = "US" Then
rng = "M" & i '& ":" & "Z" & i

With Range(rng).Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
     Operator:=xlBetween, Formula1:=Join(MyList, ",")
wb.CheckCompatibility = False
wb.Save
wb.CheckCompatibility = True
End With
Else
rng = "A" & i & ":" & "L" & i
With xlApp.Range(rng).Validation
ws.Delete
wb.CheckCompatibility = False
wb.Save
wb.CheckCompatibility = True
'wb.Close savechanges:=False
End With
End If

i = i + 1

Next c

Set ws = wb.Sheets(1)
ws.Activate

ws.Cells.Rows("1:1").Select

wb.CheckCompatibility = False
wb.Save
wb.CheckCompatibility = True
wb.Close savechanges:=False

xlApp.Quit
xlApp.Quit
xlApp.Quit
xlApp.Quit

Set xlApp = Nothing
Set wb = Nothing
Set ws = Nothing

Exit Function

End Function

I would appreciate any help on this.

Body:
Change

lRow = ws.Cells(Rows.Count, 1).End(xlUp).Row

to

lRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row

or else you will still have a reference to the Excel application after your code finishes.

With the unqualified Rows, your application (Word? Access? PowerPoint?) needs to create a dummy ActiveSheet object to be used by the method.  Until that dummy object is destroyed, an instance of Excel needs to be maintained.  That object won't get destroyed until you exit your application and therefore the instance of Excel will hang around until you exit your app.

I didn't spot it originally, but you also have an unqualified Range

With Range(rng).Validation

will need to be

With ws.Range(rng).Validation

The golden rule of using multiple Application objects is always fully qualify everything.


来源: stackexchange

问:
Angular, ngrx/store, store select and async call in a single sequence
Does anybody know if there is a chance to get a value from store and then call angular http service? See example below. Thanks in advance.

I have a service with async method. In this method I call angular http service, but before I call angular http service I want to retrieve some value from the store (oauth access token). The thing is that I store oauth token in the store, and I have to add token to the request. If server responses with 401 error I refresh token and repeat request or requests with new token.

```<code>@Injectable()
export class Interceptor {
   public get(request: Request): Observable<any> {
      return this.store.select((s) => s.session.accessToken)
         // tried .switchMap, it wasn't working for multiple requests
         // .flatMap also is not working
         // commented below is working but I don't think that it is right solution
         // return Observable.of(request)
         // .withLatestFrom(this.store.select((s) => {
         //    return s.session.accessToken
         // }))
         // .flatMap(([config, accessToken]) => { ... })
         .flatMap((accessToken) => {
            request.headers.set("Authorization", `Bearer ${accessToken}`);

            return this.http.request(request);
         })
         .map((response) => {
            return response.json();
         })
         .catch((response) => {
            return this.handleError(response, request);
         });
   }

   // handle errors
   private handleError(response: Response, request: Request): Observable<Response> {
       // handle outdated api tokens
       if (response.status === HttpStatusesEnum.Unauthorized) {
           const deferredRequest = new DeferredRequestModel({ request });

           // appends HTTP request configuration object with deferred response
           // attached to buffer
           this.buffer(deferredRequest );

           return deferredRequest.observable;
       }

       // handle server error
       if (response.status === HttpStatusesEnum.InternalServerError) {
           ...
       }

       ...

       return Observable.throw(response);
   }
}

export class DeferredRequestModel {
    public observable: AsyncSubject<Response>;
    public request: Request;

    constructor(obj?: Partial<DeferredRequestModel>) {
        this.observable = new AsyncSubject<Response>();
        this.request = obj && obj.request || null;
    }

    public reject(error?: any): void {
        this.end({ isValue: false, value: error });
    }

    public resolve(value?: any): void {
        this.end({ isValue: true, value });
    }

    private end(result: any): void {
        if (this.observable.isStopped) {
            console.warn("Deferred already resloved/rejected.");
            return;
        }

        if (result.isValue) {
            this.observable.next(result.value);
            this.observable.complete();
        } else {
            this.observable.error(result.error);
        }
    }
}
</code>```

Then when I call some service, it will send request through interceptor.

```<code>export class SomeEffect {
   constructor(private someService: SomeService) {}

   @Effect()
   public someMethod(): Observable<Action> {
      return this.actions$.ofType(SOME_ACTION_GET)
         .map((action: SomeActions.Get) => action.payload)
         .switchMap((someObj) => {
            // someMethod call interceptor inside someService, it won't call angular
            // http service directly
            return this.someService.someMethod(someObj);
         })
         .map((someResult) => {
            return new SomeActions.GetSuccess(someResult);
         });
   }
}
</code>```

I've tried to use switchMap in the interceptor, but it won't work if the interceptor is called more than a single time.

答:
If you are only interested on the last value contained in the store, you could try the following:

```<code>public someMethod() {
   return this.store.select(s => s.config)
      .switchMap(config => {
         return this.http.request(config);
      });
}
</code>```

Although I would say that only in weird cases I would inject the Store instance into a service. Maybe you could post more info about the use case

ContentLicense: CC BY-SA 3.0

Body:
Does anybody know if there is a chance to get a value from store and then call angular http service? See example below. Thanks in advance.

I have a service with async method. In this method I call angular http service, but before I call angular http service I want to retrieve some value from the store (oauth access token). The thing is that I store oauth token in the store, and I have to add token to the request. If server responses with 401 error I refresh token and repeat request or requests with new token.

@Injectable()
export class Interceptor {
   public get(request: Request): Observable<any> {
      return this.store.select((s) => s.session.accessToken)
         // tried .switchMap, it wasn't working for multiple requests
         // .flatMap also is not working
         // commented below is working but I don't think that it is right solution
         // return Observable.of(request)
         // .withLatestFrom(this.store.select((s) => {
         //    return s.session.accessToken
         // }))
         // .flatMap(([config, accessToken]) => { ... })
         .flatMap((accessToken) => {
            request.headers.set("Authorization", `Bearer ${accessToken}`);

            return this.http.request(request);
         })
         .map((response) => {
            return response.json();
         })
         .catch((response) => {
            return this.handleError(response, request);
         });
   }

   // handle errors
   private handleError(response: Response, request: Request): Observable<Response> {
       // handle outdated api tokens
       if (response.status === HttpStatusesEnum.Unauthorized) {
           const deferredRequest = new DeferredRequestModel({ request });

           // appends HTTP request configuration object with deferred response
           // attached to buffer
           this.buffer(deferredRequest );

           return deferredRequest.observable;
       }

       // handle server error
       if (response.status === HttpStatusesEnum.InternalServerError) {
           ...
       }

       ...

       return Observable.throw(response);
   }
}

export class DeferredRequestModel {
    public observable: AsyncSubject<Response>;
    public request: Request;

    constructor(obj?: Partial<DeferredRequestModel>) {
        this.observable = new AsyncSubject<Response>();
        this.request = obj && obj.request || null;
    }

    public reject(error?: any): void {
        this.end({ isValue: false, value: error });
    }

    public resolve(value?: any): void {
        this.end({ isValue: true, value });
    }

    private end(result: any): void {
        if (this.observable.isStopped) {
            console.warn("Deferred already resloved/rejected.");
            return;
        }

        if (result.isValue) {
            this.observable.next(result.value);
            this.observable.complete();
        } else {
            this.observable.error(result.error);
        }
    }
}

Then when I call some service, it will send request through interceptor.

export class SomeEffect {
   constructor(private someService: SomeService) {}

   @Effect()
   public someMethod(): Observable<Action> {
      return this.actions$.ofType(SOME_ACTION_GET)
         .map((action: SomeActions.Get) => action.payload)
         .switchMap((someObj) => {
            // someMethod call interceptor inside someService, it won't call angular
            // http service directly
            return this.someService.someMethod(someObj);
         })
         .map((someResult) => {
            return new SomeActions.GetSuccess(someResult);
         });
   }
}

I've tried to use switchMap in the interceptor, but it won't work if the interceptor is called more than a single time.

Body:
If you are only interested on the last value contained in the store, you could try the following:

public someMethod() {
   return this.store.select(s => s.config)
      .switchMap(config => {
         return this.http.request(config);
      });
}

Although I would say that only in weird cases I would inject the Store instance into a service. Maybe you could post more info about the use case


问:
How to disable users from being able to view app through regular browsers in express / electron app
I have an express server that serves my angular front end at http://localhost:9000

I'm using electron as a desktop client.

I want to force users to view the application through electron and only through electron.  I don't want users to have the ability to browser the application through any other browser.

Is there any way to disable the ability to access the app through a regular browser?

I've attempted to find information regarding this but have come up short.

答:
EDIT: This can only be done on the client side

You can check if the window.process object exists.

if (window.process && window.process !== undefined) {
   // Likely electron
}


问:
Changing the opacity of a THREE.Mirror()
I'm pretty new to Three.js, and 3D in general, so please bear with me!

I'm trying to make a THREE.Mirror and change its opacity. I would think this would work, but unfortunately it does not, nor does any other solution I've tried thus far.

```<code>// inside init, render has no been called

// create a THREE.Mirror and add it to the provided THREE.Scene
function createMirror( props ) {
    let { name, width, height, options, scene } = props;

    this[ name ] = new THREE.Mirror( width, height, options );
    scene.add( this[ name ] );
}

// create 3js mirror and add to scene
createMirror.call( this, {
    name: "Mirror_1",
    width: 1.75,
    height: 1.75,
    options: {
        clipBias: 0.01,
        textureWidth: this.width,
        textureHeight: this.height,
        color: 0xefefef
    },
    scene: this.Main_Scene
} );
this.Mirror_1.rotation.x = -Math.PI / 2;
this.Mirror_1.material.opacity = 0.1;
this.Mirror_1.material.transparent = true;

// render is called inside an ObjectLoader after objects are loaded, here is
// the render function

renderScene() {
    requestAnimationFrame( this.renderScene );

    this.P_Camera_1.lookAt( this.Main_Scene.position );
    this.controls.update();
    this.WebGL_Renderer_1.setViewport(0, 0, this.width, this.height);
    this.WebGL_Renderer_1.render( this.Main_Scene, this.P_Camera_1 );
}
</code>```

Everything else works fine. Objects are loaded, scene renders beautifully, mirror looks great... just can't change it's opacity. Any help would be greatly appreciate. If this is not enough context, please let me know and I can provide more.

P.S. This is inside a React application. render() { ... } is a method on the component controlling the scene.

EDIT: I edited the fragmentShader portion of the Mirror.js provided in the examples\js portion of npm install three and written by @author Slayvin / http://slayvin.net.

```<code>var mirrorShader = {

    uniforms: {
        ...
    },

    vertexShader: [
        ...
    ].join( '\n' ),

    fragmentShader: [
        'uniform vec3 mirrorColor;',
        'uniform sampler2D mirrorSampler;',
        'varying vec4 mirrorCoord;',

        'float blendOverlay(float base, float blend) {',
        '   return( base < 0.5 ? ( 2.0 * base * blend ) : (1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) );',
        '}',

        'void main() {',
        '   vec4 color = texture2DProj(mirrorSampler, mirrorCoord);',

        // Changed the vec4(r, g, b, alpha) alpha from 1.0 to 0.25
        // No change in rendered THREE.Mirror

        '   color = vec4(blendOverlay(mirrorColor.r, color.r), blendOverlay(mirrorColor.g, color.g), blendOverlay(mirrorColor.b, color.b), 0.25);',
        '   gl_FragColor = color;',
        '}'
    ].join( '\n' )
}
</code>```

I'm obviously missing something though!

答:
For anyone wondering how to affect the opacity of a THREE.Mirror(), you need to do two things:

Your_Mirror.material.transparent = true; Make sure this is done before the scene is rendered, or before the mirror is added to the scene and the fragmentShader has applied it's magic.

Change the alpha in the fragmentShader used by the Your_Mirror.material.fragmentShader

Here is a solution I am using to change the opacity of a mirror dynamically.

```<code>const fragmentShaderBeforeAlpha = `
    uniform vec3 mirrorColor;
    uniform sampler2D mirrorSampler;
    varying vec4 mirrorCoord;

    float blendOverlay(float base, float blend) {
        return( base < 0.5 ? ( 2.0 * base * blend ) : (1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) );
    }

    void main() {
        vec4 color = texture2DProj(mirrorSampler, mirrorCoord);
        color = vec4(blendOverlay(mirrorColor.r, color.r), blendOverlay(mirrorColor.g, color.g), blendOverlay(mirrorColor.b, color.b),
`;

const fragmentShaderAfterAlpha = `
    );
        gl_FragColor = color;
    }
`;

export default function fragmentShader( alpha ) {
    return fragmentShaderBeforeAlpha + alpha + fragmentShaderAfterAlpha;

}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm pretty new to Three.js, and 3D in general, so please bear with me!

I'm trying to make a THREE.Mirror and change its opacity. I would think this would work, but unfortunately it does not, nor does any other solution I've tried thus far.

// inside init, render has no been called

// create a THREE.Mirror and add it to the provided THREE.Scene
function createMirror( props ) {
    let { name, width, height, options, scene } = props;

    this[ name ] = new THREE.Mirror( width, height, options );
    scene.add( this[ name ] );
}

// create 3js mirror and add to scene
createMirror.call( this, {
    name: "Mirror_1",
    width: 1.75,
    height: 1.75,
    options: {
        clipBias: 0.01,
        textureWidth: this.width,
        textureHeight: this.height,
        color: 0xefefef
    },
    scene: this.Main_Scene
} );
this.Mirror_1.rotation.x = -Math.PI / 2;
this.Mirror_1.material.opacity = 0.1;
this.Mirror_1.material.transparent = true;

// render is called inside an ObjectLoader after objects are loaded, here is
// the render function

renderScene() {
    requestAnimationFrame( this.renderScene );

    this.P_Camera_1.lookAt( this.Main_Scene.position );
    this.controls.update();
    this.WebGL_Renderer_1.setViewport(0, 0, this.width, this.height);
    this.WebGL_Renderer_1.render( this.Main_Scene, this.P_Camera_1 );
}

Everything else works fine. Objects are loaded, scene renders beautifully, mirror looks great... just can't change it's opacity. Any help would be greatly appreciate. If this is not enough context, please let me know and I can provide more.

P.S. This is inside a React application. render() { ... } is a method on the component controlling the scene.

EDIT: I edited the fragmentShader portion of the Mirror.js provided in the examples\js portion of npm install three and written by @author Slayvin / http://slayvin.net.

var mirrorShader = {

    uniforms: {
        ...
    },

    vertexShader: [
        ...
    ].join( '\n' ),

    fragmentShader: [
        'uniform vec3 mirrorColor;',
        'uniform sampler2D mirrorSampler;',
        'varying vec4 mirrorCoord;',

        'float blendOverlay(float base, float blend) {',
        '   return( base < 0.5 ? ( 2.0 * base * blend ) : (1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) );',
        '}',

        'void main() {',
        '   vec4 color = texture2DProj(mirrorSampler, mirrorCoord);',

        // Changed the vec4(r, g, b, alpha) alpha from 1.0 to 0.25
        // No change in rendered THREE.Mirror

        '   color = vec4(blendOverlay(mirrorColor.r, color.r), blendOverlay(mirrorColor.g, color.g), blendOverlay(mirrorColor.b, color.b), 0.25);',
        '   gl_FragColor = color;',
        '}'
    ].join( '\n' )
}

I'm obviously missing something though!

Body:
For anyone wondering how to affect the opacity of a THREE.Mirror(), you need to do two things:

Your_Mirror.material.transparent = true; Make sure this is done before the scene is rendered, or before the mirror is added to the scene and the fragmentShader has applied it's magic.

Change the alpha in the fragmentShader used by the Your_Mirror.material.fragmentShader

Here is a solution I am using to change the opacity of a mirror dynamically.

const fragmentShaderBeforeAlpha = `
    uniform vec3 mirrorColor;
    uniform sampler2D mirrorSampler;
    varying vec4 mirrorCoord;

    float blendOverlay(float base, float blend) {
        return( base < 0.5 ? ( 2.0 * base * blend ) : (1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) );
    }

    void main() {
        vec4 color = texture2DProj(mirrorSampler, mirrorCoord);
        color = vec4(blendOverlay(mirrorColor.r, color.r), blendOverlay(mirrorColor.g, color.g), blendOverlay(mirrorColor.b, color.b),
`;

const fragmentShaderAfterAlpha = `
    );
        gl_FragColor = color;
    }
`;

export default function fragmentShader( alpha ) {
    return fragmentShaderBeforeAlpha + alpha + fragmentShaderAfterAlpha;

}


问:
A-frame mouse-tracking changes when scene is embedded
I am creating a desktop/mobile/VR game using A-frame, involving finding a number of hidden items in an image.

The image is used as the source for an  entity, creating a 360-dgree image. In the desktop version, the user can use the mouse to pan around the image, and then click on the hidden items to reveal them. The reveal is done by positioning an  entity, with an image as it's texture, in front of the hidden item, and then animating the  to become visible when clicked on.

The game works perfectly in when the  is NOT embedded. However, I need to embed the scene in order to make it part of a larger website, and when I embed it the mouse tracking becomes unreliable. That is, in the non-embedded version I can click directly on, say Item A, and it will be revealed as expected. However, once embedded, I have to click somewhere near, but not on, Item A in order for the reveal to occur.

It seems as though embedding the scene does something to alter the local coordinates, or alter how they translate to the 2D mouse position in the window, but I have been unable to find any sort of documentation regarding this issue.

Can anyone help?

答: Okay, it turns out the issue was because I was using an older version of the aframe-mouse-cursor-component, which did not account for embedded scenes. The component has recently been updated and everything now works properly!</p>


问:
enterprise devops architecture suggestions
i am looking for some suggestions and views related to devops enterprise architecture design for a nodejs and mongoDb application.

one of the requirement is to keep the solution at low cost, hence i have kept the number of servers in test/staging and development to a minimum, and production with a fully blown architecture.

Each environment has two zones ZONE1(dmz1) and ZONE2(dmz2), zone2 being more secure, which hosts mongodb servers.
Production mongodb is a 5 node replica set, with the arbiter node on the Production environment and two members in Production DR environment, additionally the nodesjs app is loadbalanced.

questions:

Is it a good practice to keep CI/jenkins on staging and let it deploy artifacts to both production and development?

provided there will be no SSH access to servers in production what
configuration managment strategy i should use to manage the servers
and deploy application?

答:
Ok, first of all, one of the principles that the devops culture advocates for (it actually is one of its end goals) is to minimize the gap between environments and to enable an organization to make deployments while being confident on the tests that were performed earlier, so it would be in your best interest to replicate on test/dev what you will have on production as well as you can, this being said:

Is it a good practice to keep CI/jenkins on staging and let it deploy
  artifacts to both production and development?

It really depends on the ammount of of deployments you guys do (is 1 jenkins server going to be enough?) and the security concerns you might have (is having both production and testing networks connected via 1 servers making your security team worry?). At the end it all really depends, i've seen ci/cd pipelines implemented fully with 1 jenkins server as the main control and letting it deploy on test, perform some automatic tests and if it passes, promote the deployment to production. You can check jenkins blue ocean pipelines while on that.

provided there will be no SSH access to servers in production what
  configuration managment strategy i should use to manage the servers
  and deploy application?

When you say no ssh access, it means that people wont have accounts on those servers? or that there won't be ssh traffic/service at all? if it's the second option, i really doubt that cm tools would work at all, however, if it's the former you can set something along the lines of an ansible role on a control server (it can even be the jenkins ci server), set a ssh key for ansible to use and let it handle all the provisioning and deployment of your servers/application on production. Bear in mind that this last strategy not only automates your deployments but also enables you to automatically provision new servers whether that be for scaling your solution or disaster recovery,

I really hope my reply helps you out a little,

Cheers


问:
Spinner, string-array onclick performance
I am making a self service form with a set of questions during user registration.

Here is the string.xml file

```<code><resources>
sources>
 <string name="question1">What was your childhood nickname?</string>
<string name="question2">What is the name of your favorite childhood friend?</string>
<string name="question3">In what city or town did your mother and father meet?</string>
<string name="question4">What is your favorite team?</string>
<string name="question5">What was your favorite sport in high school?</string>
<string name="question6">What was your favorite food as a child?</string>
<string name="question7">What was the make and model of your first car?</string>
<string name="question8">What is you mother\'s maiden name?</string>
<string name="question9">In which city/town were you born?</string>
<string name="question10">In what town/city was your first job?</string>

<string-array name="questions">
    <item>Select a question</item>
    <item>@string/question1</item>
    <item>@string/question2</item>
    <item>@string/question3</item>
    <item>@string/question4</item>
    <item>@string/question5</item>
    <item>@string/question6</item>
    <item>@string/question7</item>
    <item>@string/question8</item>
    <item>@string/question9</item>
    <item>@string/question10</item>
</string-array>
</code>```

I have pulled these questions into 3 different spinners in the activity xml file.

activity_self_service.xml

```<code>  Spinner spinner1 = (Spinner) findViewById(R.id.spinner_q1);
    Spinner spinner2 = (Spinner) findViewById(R.id.spinner_q2);
    Spinner spinner3 = (Spinner) findViewById(R.id.spinner_q3);

    // Create an ArrayAdapter using the string array and a default spinner layout
    ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(this, R.array.questions, android.R.layout.simple_spinner_item);
    ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(this, R.array.questions, android.R.layout.simple_spinner_item);
    ArrayAdapter<CharSequence> adapter3 = ArrayAdapter.createFromResource(this, R.array.questions, android.R.layout.simple_spinner_item);
    // Specify the layout to use when the list of choices appears
    adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    spinner1.setPrompt("Select a security question");
    spinner2.setPrompt("Select a security question");
    spinner3.setPrompt("Select a security question");
     // Apply the adapter to the spinner
    spinner1.setAdapter(adapter1);
    spinner2.setAdapter(adapter2);
    spinner3.setAdapter(adapter3);
</code>```

Say the user selected question 3, question 5 and question 6 in 3 different spinners, I want to store the indexes of these questions and the answers in the database.

So, I want something like (3,answer 1) ,(5, answer 2), (6, answer 3) in the DB.

I tried to get the indexes but couldnt find a way.
Please help.

答: Set "OnItemSelectedListener" on all your spinners, it will give you the index when an item is selected.</p>

Body:
I am making a self service form with a set of questions during user registration.

Here is the string.xml file

<resources>
sources>
 <string name="question1">What was your childhood nickname?</string>
<string name="question2">What is the name of your favorite childhood friend?</string>
<string name="question3">In what city or town did your mother and father meet?</string>
<string name="question4">What is your favorite team?</string>
<string name="question5">What was your favorite sport in high school?</string>
<string name="question6">What was your favorite food as a child?</string>
<string name="question7">What was the make and model of your first car?</string>
<string name="question8">What is you mother\'s maiden name?</string>
<string name="question9">In which city/town were you born?</string>
<string name="question10">In what town/city was your first job?</string>

<string-array name="questions">
    <item>Select a question</item>
    <item>@string/question1</item>
    <item>@string/question2</item>
    <item>@string/question3</item>
    <item>@string/question4</item>
    <item>@string/question5</item>
    <item>@string/question6</item>
    <item>@string/question7</item>
    <item>@string/question8</item>
    <item>@string/question9</item>
    <item>@string/question10</item>
</string-array>

I have pulled these questions into 3 different spinners in the activity xml file.

activity_self_service.xml

  Spinner spinner1 = (Spinner) findViewById(R.id.spinner_q1);
    Spinner spinner2 = (Spinner) findViewById(R.id.spinner_q2);
    Spinner spinner3 = (Spinner) findViewById(R.id.spinner_q3);

    // Create an ArrayAdapter using the string array and a default spinner layout
    ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(this, R.array.questions, android.R.layout.simple_spinner_item);
    ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(this, R.array.questions, android.R.layout.simple_spinner_item);
    ArrayAdapter<CharSequence> adapter3 = ArrayAdapter.createFromResource(this, R.array.questions, android.R.layout.simple_spinner_item);
    // Specify the layout to use when the list of choices appears
    adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    spinner1.setPrompt("Select a security question");
    spinner2.setPrompt("Select a security question");
    spinner3.setPrompt("Select a security question");
     // Apply the adapter to the spinner
    spinner1.setAdapter(adapter1);
    spinner2.setAdapter(adapter2);
    spinner3.setAdapter(adapter3);

Say the user selected question 3, question 5 and question 6 in 3 different spinners, I want to store the indexes of these questions and the answers in the database.

So, I want something like (3,answer 1) ,(5, answer 2), (6, answer 3) in the DB.

I tried to get the indexes but couldnt find a way.
Please help.


问:
Laravel 5.4 - Update an existing record
I'm struggling to update an existing record through an Eloquent Model in Laravel 5.4

I have for creating a record that works perfectly fine, I took it and modified it to try and update the record:

```<code>public function commitEdit ($char_edit_id)
    {

    $edited_character = \DB::table('characters')->where('char_id', $char_edit_id)->first();

    $edited_character->campaign_id = 1;

    $edited_character->character_name = request('characterName');

    $edited_character->Race = request('race');

    $edited_character->Sub_Race = request('subRaceField');

    $edited_character->Class = request('class');

    $edited_character->Level = request('level');

    $edited_character->Strength = request('strength');

    $edited_character->Dexterity = request('dexterity');

    $edited_character->Constitution = request('constitution');

    $edited_character->Intelligence = request('intelligence');

    $edited_character->Wisdom = request('wisdom');

    $edited_character->Charisma = request('charisma');

    $levelVar = request('level');

    if ($levelVar >= 4) {
    $edited_character->Proficiency = 2;
    } else if ($levelVar >= 8) {
    $edited_character->Proficiency = 3;
    }

    $edited_character->Trained_Skills = request('skillsField');

    $edited_character->Languages = request('languagesField');

    $edited_character->Hit_Die = 1;

    $edited_character->max_HP = request('max-hp');

    $edited_character->Alignment = request('alignment');

    $edited_character->Armor_Class = request('armor-class');

    $edited_character->Initiative = request('initiative');

    $edited_character->Speed = request('speed');

    $edited_character->Background = request('background');

    $edited_character->update();

    return redirect('./characters');
</code>```

That gives this error:
Call to undefined method stdClass::update()

I have tried using save() but I get the same error with save() instead of update()

Thanks in advance c:

答:
Documentation

If you just need to retrieve a single row from the database table, you may use the first method. This method will return a single StdClass object:

$edited_character is a stdClass, no Eloquent model.

You can try this code:

```<code>public function commitEdit ($char_edit_id)
{
    $edited_character = \DB::table('characters')->where('char_id', $char_edit_id)->update([
        'campaign_id' => 1,
        'character_name' => request('characterName'),
        'Race' => request('race'),
        //others property
    ]);
}
</code>```

Or create Characters model which will be extends from Illuminate\Database\Eloquent\Model and use save method:

```<code>public function commitEdit ($char_edit_id)
{
    $edited_character = Characters::where('char_id', $char_edit_id)-first();
    //your code with properties
    $edited_character->save();
}
</code>```

Title: Laravel 5.4 - Update an existing record

Body:
I'm struggling to update an existing record through an Eloquent Model in Laravel 5.4

I have for creating a record that works perfectly fine, I took it and modified it to try and update the record:

public function commitEdit ($char_edit_id)
    {

    $edited_character = \DB::table('characters')->where('char_id', $char_edit_id)->first();

    $edited_character->campaign_id = 1;

    $edited_character->character_name = request('characterName');

    $edited_character->Race = request('race');

    $edited_character->Sub_Race = request('subRaceField');

    $edited_character->Class = request('class');

    $edited_character->Level = request('level');

    $edited_character->Strength = request('strength');

    $edited_character->Dexterity = request('dexterity');

    $edited_character->Constitution = request('constitution');

    $edited_character->Intelligence = request('intelligence');

    $edited_character->Wisdom = request('wisdom');

    $edited_character->Charisma = request('charisma');

    $levelVar = request('level');

    if ($levelVar >= 4) {
    $edited_character->Proficiency = 2;
    } else if ($levelVar >= 8) {
    $edited_character->Proficiency = 3;
    }

    $edited_character->Trained_Skills = request('skillsField');

    $edited_character->Languages = request('languagesField');

    $edited_character->Hit_Die = 1;

    $edited_character->max_HP = request('max-hp');

    $edited_character->Alignment = request('alignment');

    $edited_character->Armor_Class = request('armor-class');

    $edited_character->Initiative = request('initiative');

    $edited_character->Speed = request('speed');

    $edited_character->Background = request('background');

    $edited_character->update();

    return redirect('./characters');

That gives this error:
Call to undefined method stdClass::update()

I have tried using save() but I get the same error with save() instead of update()

Thanks in advance c:

Body:
Documentation

If you just need to retrieve a single row from the database table, you may use the first method. This method will return a single StdClass object:

$edited_character is a stdClass, no Eloquent model.

You can try this code:

public function commitEdit ($char_edit_id)
{
    $edited_character = \DB::table('characters')->where('char_id', $char_edit_id)->update([
        'campaign_id' => 1,
        'character_name' => request('characterName'),
        'Race' => request('race'),
        //others property
    ]);
}

Or create Characters model which will be extends from Illuminate\Database\Eloquent\Model and use save method:

public function commitEdit ($char_edit_id)
{
    $edited_character = Characters::where('char_id', $char_edit_id)-first();
    //your code with properties
    $edited_character->save();
}


问:
Color coding html table cell based on SQL flag value
So I finally have a SQL query working to take 3 conditions from my DB table and set a flag based on them.

Here is the Statement:

```<code>UPDATE staging
SET  `miuFlag` =1
WHERE  `lowSideMIUNumArriv` =    `lowSideMIUNumDepart`
AND  `miu` =  "No"
</code>```

Now my database table has a column called 'miuFlag' with either ones or zeroes. Based on this value, I want one of my html table values to be red or green (0=red, 1=green).

Here is the affected html table row:

```<code>        <td><? echo $row['miu'];?> </td>
</code>```

I know I can color this row's font by using style inside of the td element, but how exactly would I create the condition to style one color for miuFlag = 0 and another for miuFlag = 1?

答:
You can try this code:</p>

```<code><td styel="<?php $row[miuFlag] == 1 ? 'color:green' : 'color:red' ?>"><?= $row['miu'];?> <td>
</code>```

Body:
So I finally have a SQL query working to take 3 conditions from my DB table and set a flag based on them.

Here is the Statement:

UPDATE staging
SET  `miuFlag` =1
WHERE  `lowSideMIUNumArriv` =    `lowSideMIUNumDepart`
AND  `miu` =  "No"

Now my database table has a column called 'miuFlag' with either ones or zeroes. Based on this value, I want one of my html table values to be red or green (0=red, 1=green).

Here is the affected html table row:

        <? echo $row['miu'];?>

I know I can color this row's font by using style inside of the td element, but how exactly would I create the condition to style one color for miuFlag = 0 and another for miuFlag = 1?

Body:
You can try this code:

<td styel="<?php $row[miuFlag] == 1 ? 'color:green' : 'color:red' ?>"><?= $row['miu'];?>&nbsp;<td>


问:
Are dunder methods inherited?
If I define __getstate__() and __setstate__() in a parent class, would a child be able to inherit these methods? There's some related discussion in this SO answer, but only on methods with a preceding double-underscore (dunder).

Some extra info:

I'm doing this to define serialization (pickling) behavior of my classes.

Python 2.7

答:
Yes, dunder methods are inherited just fine. From the answer there, the documentation linked is Reserved classes of identifiers:

__*__

  System-defined names. These names are defined by the interpreter and its implementation (including the standard library). Current system names are discussed in the Special method names section and elsewhere. More will likely be defined in future versions of Python. Any use of __*__ names, in any context, that does not follow explicitly documented use, is subject to breakage without warning.

which is a separate class from __* class-private names.

and the other section linked is Identifiers (Names) which is perhaps clearer still:

When an identifier that textually occurs in a class definition begins with two or more underscore characters and does not end in two or more underscores, it is considered a private name of that class.

Bold emphasis mine; names that start with two underscores and end with two underscores are not class-private names.

Note that both classes of names are inherited (inheritance works by looking up attribute names in the MRO of the class). That names are mangled doesn't prevent them from being inherited, which is why the names are mangled in the first place. By prefixing such names with _ClassName subclasses can re-use the name and automatically not clash because these get their own _SubClass prefix.

Title: Are dunder methods inherited?


问:
Structured Streaming: Streaming Exception on restarts due to checkpoint data
I have one read stream to consume data from a Kafka topic , and based on an attribute value in each of the incoming messages, I have to write data to either of the 2 different locations in S3 (if value1 write to location1, otherwise to location2).

On a high level below is what I have for doing that,

```<code>Dataset<Row> kafkaStreamSet = sparkSession
            .readStream()
            .format("kafka")
            .option("kafka.bootstrap.servers", kafkaBootstrap)
            .option("subscribe", kafkaTopic)
            .option("startingOffsets", "latest")
            .option("failOnDataLoss", false)
            .option("maxOffsetsPerTrigger", offsetsPerTrigger)
            .load();

    //raw message to ClickStream
    Dataset<ClickStream> ds1 = kafkaStreamSet.mapPartitions(processClickStreamMessages, Encoders.bean(ClickStream.class));
</code>```

ClickStream.java has 2 child objects  within it  and only one of them will be populated at a time depending on if the message attribute value is  either value1 or value2,

1) BookingRequest.java if  value1,

 2) PropertyPageView.java if value2 ,

which I then separate  out as below from clickstream to write to 2 diff locations in S3,

```<code>    //fetch BookingRequests in the ClickStream
    Dataset<BookingRequest> ds2 = ds1.map(filterBookingRequests,Encoders.bean(BookingRequest.class));

    //fetch PropertyPageViews in the ClickStream
    Dataset<PropertyPageView> ds3 = ds1.map(filterPropertyPageViews,Encoders.bean(PropertyPageView.class));
</code>```

finally  ds2 and ds3 are written to 2 different locations ,

```<code>   StreamingQuery bookingRequestsParquetStreamWriter = ds2.writeStream().outputMode("append")
        .format("parquet")
        .trigger(ProcessingTime.create(bookingRequestProcessingTime, TimeUnit.MILLISECONDS))
        .option("checkpointLocation",  "s3://" + s3Bucket+ "/checkpoint/bookingRequests")
        .partitionBy("eventDate")
        .start("s3://" + s3Bucket+ "/" +  bookingRequestPath);

    StreamingQuery PageViewsParquetStreamWriter = ds3.writeStream().outputMode("append")
        .format("parquet")
        .trigger(ProcessingTime.create(pageViewProcessingTime, TimeUnit.MILLISECONDS))
        .option("checkpointLocation",  "s3://" + s3Bucket+ "/checkpoint/PageViews")
        .partitionBy("eventDate")
        .start("s3://" + s3Bucket+ "/" +  pageViewPath);

    bookingRequestsParquetStreamWriter.awaitTermination();

    PageViewsParquetStreamWriter.awaitTermination();
</code>```

it seems to work  fine and I see data written to different paths when the apps deployed. But, whenever the job is restarted on failure or on manual stops and starts, it keeps failing with below exception (where userSessionEventJoin.global is my topic name),

Caused by: org.apache.spark.sql.streaming.StreamingQueryException: Expected e.g. {"topicA":{"0":23,"1":-1},"topicB":{"0":-2}}, got {"userSessionEventJoin.global":{"92":154362528,"101 org.apache.spark.sql.kafka010.JsonUtils$.partitionOffsets(JsonUtils.scala:74)
        org.apache.spark.sql.kafka010.KafkaSourceOffset$.apply(KafkaSourceOffset.scala:59)

if I delete all the checkpointing information, then it starts again and starts new checkpointing in the given 2 locations, but that means I have to start processing from the latest offset again and lose all previous offsets.
The spark version is 2.1, and this topic has 100+ partitions.

I tested with just one writestream (one checkpoint location), same exception happens on restarts.

Please suggest any resolutions, thanks.

答:
It seems your code is a simple click stream job. In your example you create a spark streaming session and use the checkpoint directory to intermittently store checkpoint data.

Your code however does not know how to hydrate from a checkpoint.

It will be clear by the end of this paragraph.

Here is the steps for a production level streaming job.

```<code>1) Use getOrCreate API to create your spark streaming session.
   a) getOrCreate takes two parameters. A function "(....) => sparkSession" and the checkpoint directory.
2) When program starts for the first time, it uses the checkpoint directory to store it's inner details. (Among other uses)
3) When program crashes/"stops and restarted", the spark Streaming session is created from the checkpoint hence giving you what you want.
</code>```

As referring to link is not encouraged in stack overflow I am going to put the sample code below. But it is essentially taken from Spark Github example

```<code> /**
            * Counts words in text encoded with UTF8 received from the network every second. This example also
            * shows how to use lazily instantiated singleton instances for Accumulator and Broadcast so that
            * they can be registered on driver failures.
            *
            * Usage: JavaRecoverableNetworkWordCount <hostname> <port> <checkpoint-directory> <output-file>
            *   <hostname> and <port> describe the TCP server that Spark Streaming would connect to receive
            *   data. <checkpoint-directory> directory to HDFS-compatible file system which checkpoint data
            *   <output-file> file to which the word counts will be appended
            *
            * <checkpoint-directory> and <output-file> must be absolute paths
            *
            * To run this on your local machine, you need to first run a Netcat server
            *
            *      `$ nc -lk 9999`
            *
            * and run the example as
            *
            *      `$ ./bin/run-example org.apache.spark.examples.streaming.JavaRecoverableNetworkWordCount \
            *              localhost 9999 ~/checkpoint/ ~/out`
            *
            * If the directory ~/checkpoint/ does not exist (e.g. running for the first time), it will create
            * a new StreamingContext (will print "Creating new context" to the console). Otherwise, if
            * checkpoint data exists in ~/checkpoint/, then it will create StreamingContext from
            * the checkpoint data.
            *
            * Refer to the online documentation for more details.
            */
            public final class JavaRecoverableNetworkWordCount {
            private static final Pattern SPACE = Pattern.compile(" ");

            private static JavaStreamingContext createContext(String ip,
                                                                int port,
                                                                String checkpointDirectory,
                                                                String outputPath) {

                // If you do not see this printed, that means the StreamingContext has been loaded
                // from the new checkpoint
                System.out.println("Creating new context");
                File outputFile = new File(outputPath);
                if (outputFile.exists()) {
                outputFile.delete();
                }
                SparkConf sparkConf = new SparkConf().setAppName("JavaRecoverableNetworkWordCount");
                // Create the context with a 1 second batch size
                JavaStreamingContext ssc = new JavaStreamingContext(sparkConf, Durations.seconds(1));
                ssc.checkpoint(checkpointDirectory);

                // Create a socket stream on target ip:port and count the
                // words in input stream of \n delimited text (eg. generated by 'nc')
                JavaReceiverInputDStream<String> lines = ssc.socketTextStream(ip, port);
                JavaDStream<String> words = lines.flatMap(x -> Arrays.asList(SPACE.split(x)).iterator());
                JavaPairDStream<String, Integer> wordCounts = words.mapToPair(s -> new Tuple2<>(s, 1))
                    .reduceByKey((i1, i2) -> i1 + i2);

                wordCounts.foreachRDD((rdd, time) -> {
                // Get or register the blacklist Broadcast
                Broadcast<List<String>> blacklist =
                    JavaWordBlacklist.getInstance(new JavaSparkContext(rdd.context()));
                // Get or register the droppedWordsCounter Accumulator
                LongAccumulator droppedWordsCounter =
                    JavaDroppedWordsCounter.getInstance(new JavaSparkContext(rdd.context()));
                // Use blacklist to drop words and use droppedWordsCounter to count them
                String counts = rdd.filter(wordCount -> {
                    if (blacklist.value().contains(wordCount._1())) {
                    droppedWordsCounter.add(wordCount._2());
                    return false;
                    } else {
                    return true;
                    }
                }).collect().toString();
                String output = "Counts at time " + time + " " + counts;
                System.out.println(output);
                System.out.println("Dropped " + droppedWordsCounter.value() + " word(s) totally");
                System.out.println("Appending to " + outputFile.getAbsolutePath());
                Files.append(output + "\n", outputFile, Charset.defaultCharset());
                });

                return ssc;
            }

            public static void main(String[] args) throws Exception {
                if (args.length != 4) {
                System.err.println("You arguments were " + Arrays.asList(args));
                System.err.println(
                    "Usage: JavaRecoverableNetworkWordCount <hostname> <port> <checkpoint-directory>\n" +
                    "     <output-file>. <hostname> and <port> describe the TCP server that Spark\n" +
                    "     Streaming would connect to receive data. <checkpoint-directory> directory to\n" +
                    "     HDFS-compatible file system which checkpoint data <output-file> file to which\n" +
                    "     the word counts will be appended\n" +
                    "\n" +
                    "In local mode, <master> should be 'local[n]' with n > 1\n" +
                    "Both <checkpoint-directory> and <output-file> must be absolute paths");
                System.exit(1);
                }

                String ip = args[0];
                int port = Integer.parseInt(args[1]);
                String checkpointDirectory = args[2];
                String outputPath = args[3];

                // Function to create JavaStreamingContext without any output operations
                // (used to detect the new context)
                Function0<JavaStreamingContext> createContextFunc =
                    () -> createContext(ip, port, checkpointDirectory, outputPath);

                JavaStreamingContext ssc =
                JavaStreamingContext.getOrCreate(checkpointDirectory, createContextFunc);
                ssc.start();
                ssc.awaitTermination();
            }
            }
</code>```

Body:
I have one read stream to consume data from a Kafka topic , and based on an attribute value in each of the incoming messages, I have to write data to either of the 2 different locations in S3 (if value1 write to location1, otherwise to location2).

On a high level below is what I have for doing that,

Dataset<Row> kafkaStreamSet = sparkSession
            .readStream()
            .format("kafka")
            .option("kafka.bootstrap.servers", kafkaBootstrap)
            .option("subscribe", kafkaTopic)
            .option("startingOffsets", "latest")
            .option("failOnDataLoss", false)
            .option("maxOffsetsPerTrigger", offsetsPerTrigger)
            .load();

    //raw message to ClickStream
    Dataset<ClickStream> ds1 = kafkaStreamSet.mapPartitions(processClickStreamMessages, Encoders.bean(ClickStream.class));

ClickStream.java has 2 child objects  within it  and only one of them will be populated at a time depending on if the message attribute value is  either value1 or value2,

1) BookingRequest.java if  value1,

 2) PropertyPageView.java if value2 ,

which I then separate  out as below from clickstream to write to 2 diff locations in S3,

    //fetch BookingRequests in the ClickStream
    Dataset<BookingRequest> ds2 = ds1.map(filterBookingRequests,Encoders.bean(BookingRequest.class));

    //fetch PropertyPageViews in the ClickStream
    Dataset<PropertyPageView> ds3 = ds1.map(filterPropertyPageViews,Encoders.bean(PropertyPageView.class));

finally  ds2 and ds3 are written to 2 different locations ,

   StreamingQuery bookingRequestsParquetStreamWriter = ds2.writeStream().outputMode("append")
        .format("parquet")
        .trigger(ProcessingTime.create(bookingRequestProcessingTime, TimeUnit.MILLISECONDS))
        .option("checkpointLocation",  "s3://" + s3Bucket+ "/checkpoint/bookingRequests")
        .partitionBy("eventDate")
        .start("s3://" + s3Bucket+ "/" +  bookingRequestPath);

    StreamingQuery PageViewsParquetStreamWriter = ds3.writeStream().outputMode("append")
        .format("parquet")
        .trigger(ProcessingTime.create(pageViewProcessingTime, TimeUnit.MILLISECONDS))
        .option("checkpointLocation",  "s3://" + s3Bucket+ "/checkpoint/PageViews")
        .partitionBy("eventDate")
        .start("s3://" + s3Bucket+ "/" +  pageViewPath);

    bookingRequestsParquetStreamWriter.awaitTermination();

    PageViewsParquetStreamWriter.awaitTermination();

it seems to work  fine and I see data written to different paths when the apps deployed. But, whenever the job is restarted on failure or on manual stops and starts, it keeps failing with below exception (where userSessionEventJoin.global is my topic name),

Caused by: org.apache.spark.sql.streaming.StreamingQueryException: Expected e.g. {"topicA":{"0":23,"1":-1},"topicB":{"0":-2}}, got {"userSessionEventJoin.global":{"92":154362528,"101 org.apache.spark.sql.kafka010.JsonUtils$.partitionOffsets(JsonUtils.scala:74)
        org.apache.spark.sql.kafka010.KafkaSourceOffset$.apply(KafkaSourceOffset.scala:59)

if I delete all the checkpointing information, then it starts again and starts new checkpointing in the given 2 locations, but that means I have to start processing from the latest offset again and lose all previous offsets.
The spark version is 2.1, and this topic has 100+ partitions.

I tested with just one writestream (one checkpoint location), same exception happens on restarts.

Please suggest any resolutions, thanks.

Body:
It seems your code is a simple click stream job. In your example you create a spark streaming session and use the checkpoint directory to intermittently store checkpoint data.

Your code however does not know how to hydrate from a checkpoint.

It will be clear by the end of this paragraph.

Here is the steps for a production level streaming job.

1) Use getOrCreate API to create your spark streaming session.
   a) getOrCreate takes two parameters. A function "(....) => sparkSession" and the checkpoint directory.
2) When program starts for the first time, it uses the checkpoint directory to store it's inner details. (Among other uses)
3) When program crashes/"stops and restarted", the spark Streaming session is created from the checkpoint hence giving you what you want.

As referring to link is not encouraged in stack overflow I am going to put the sample code below. But it is essentially taken from Spark Github example

 /**
            * Counts words in text encoded with UTF8 received from the network every second. This example also
            * shows how to use lazily instantiated singleton instances for Accumulator and Broadcast so that
            * they can be registered on driver failures.
            *
            * Usage: JavaRecoverableNetworkWordCount <hostname> <port> <checkpoint-directory> <output-file>
            *   <hostname> and <port> describe the TCP server that Spark Streaming would connect to receive
            *   data. <checkpoint-directory> directory to HDFS-compatible file system which checkpoint data
            *   <output-file> file to which the word counts will be appended
            *
            * <checkpoint-directory> and <output-file> must be absolute paths
            *
            * To run this on your local machine, you need to first run a Netcat server
            *
            *      `$ nc -lk 9999`
            *
            * and run the example as
            *
            *      `$ ./bin/run-example org.apache.spark.examples.streaming.JavaRecoverableNetworkWordCount \
            *              localhost 9999 ~/checkpoint/ ~/out`
            *
            * If the directory ~/checkpoint/ does not exist (e.g. running for the first time), it will create
            * a new StreamingContext (will print "Creating new context" to the console). Otherwise, if
            * checkpoint data exists in ~/checkpoint/, then it will create StreamingContext from
            * the checkpoint data.
            *
            * Refer to the online documentation for more details.
            */
            public final class JavaRecoverableNetworkWordCount {
            private static final Pattern SPACE = Pattern.compile(" ");

            private static JavaStreamingContext createContext(String ip,
                                                                int port,
                                                                String checkpointDirectory,
                                                                String outputPath) {

                // If you do not see this printed, that means the StreamingContext has been loaded
                // from the new checkpoint
                System.out.println("Creating new context");
                File outputFile = new File(outputPath);
                if (outputFile.exists()) {
                outputFile.delete();
                }
                SparkConf sparkConf = new SparkConf().setAppName("JavaRecoverableNetworkWordCount");
                // Create the context with a 1 second batch size
                JavaStreamingContext ssc = new JavaStreamingContext(sparkConf, Durations.seconds(1));
                ssc.checkpoint(checkpointDirectory);

                // Create a socket stream on target ip:port and count the
                // words in input stream of \n delimited text (eg. generated by 'nc')
                JavaReceiverInputDStream<String> lines = ssc.socketTextStream(ip, port);
                JavaDStream<String> words = lines.flatMap(x -> Arrays.asList(SPACE.split(x)).iterator());
                JavaPairDStream<String, Integer> wordCounts = words.mapToPair(s -> new Tuple2<>(s, 1))
                    .reduceByKey((i1, i2) -> i1 + i2);

                wordCounts.foreachRDD((rdd, time) -> {
                // Get or register the blacklist Broadcast
                Broadcast<List<String>> blacklist =
                    JavaWordBlacklist.getInstance(new JavaSparkContext(rdd.context()));
                // Get or register the droppedWordsCounter Accumulator
                LongAccumulator droppedWordsCounter =
                    JavaDroppedWordsCounter.getInstance(new JavaSparkContext(rdd.context()));
                // Use blacklist to drop words and use droppedWordsCounter to count them
                String counts = rdd.filter(wordCount -> {
                    if (blacklist.value().contains(wordCount._1())) {
                    droppedWordsCounter.add(wordCount._2());
                    return false;
                    } else {
                    return true;
                    }
                }).collect().toString();
                String output = "Counts at time " + time + " " + counts;
                System.out.println(output);
                System.out.println("Dropped " + droppedWordsCounter.value() + " word(s) totally");
                System.out.println("Appending to " + outputFile.getAbsolutePath());
                Files.append(output + "\n", outputFile, Charset.defaultCharset());
                });

                return ssc;
            }

            public static void main(String[] args) throws Exception {
                if (args.length != 4) {
                System.err.println("You arguments were " + Arrays.asList(args));
                System.err.println(
                    "Usage: JavaRecoverableNetworkWordCount <hostname> <port> <checkpoint-directory>\n" +
                    "     <output-file>. <hostname> and <port> describe the TCP server that Spark\n" +
                    "     Streaming would connect to receive data. <checkpoint-directory> directory to\n" +
                    "     HDFS-compatible file system which checkpoint data <output-file> file to which\n" +
                    "     the word counts will be appended\n" +
                    "\n" +
                    "In local mode, <master> should be 'local[n]' with n > 1\n" +
                    "Both <checkpoint-directory> and <output-file> must be absolute paths");
                System.exit(1);
                }

                String ip = args[0];
                int port = Integer.parseInt(args[1]);
                String checkpointDirectory = args[2];
                String outputPath = args[3];

                // Function to create JavaStreamingContext without any output operations
                // (used to detect the new context)
                Function0<JavaStreamingContext> createContextFunc =
                    () -> createContext(ip, port, checkpointDirectory, outputPath);

                JavaStreamingContext ssc =
                JavaStreamingContext.getOrCreate(checkpointDirectory, createContextFunc);
                ssc.start();
                ssc.awaitTermination();
            }
            }


问:
How to check and restrict concurrent calls on a number in asterisk php agi?
We have a portal where client sets maximum concurrent call forwarding on a number. First calls come to our IP, we then forward that calls to some numbers(set by client for it). We have to make sure, the forwarded calls are less than or equal to the set maximum limit of concurrent calls on a number.
We are using asterisk as telephony software and phpagi as agi library.

How can I find count of concurrent calls already there on a number, before I forward a new call on it via my agi script.

Please suggest a proper way of doing this.

Is there any built-in way, which will automatically restrict further forward when a particular number of concurrent calls (already set for it) is already reached?

答:
You can use GROUP and GROUP_COUNT dialplan  functions.

In AGI you can do that via

$agi->set_full_variable("new_var",'${GROUP_COUNT(group_name)}')

```<code>pro-sip*CLI> core show function GROUP

  -= Info about function 'GROUP' =-

[Synopsis]
Gets or sets the channel group.

[Description]
<category> can be employed for more fine grained group management. Each channel
can only be member of exactly one group per <category>.

[Syntax]
GROUP([category])

[Arguments]
category
    Category name.

[See Also]
Not available

pro-sip*CLI> core show function GROUP_COUNT

  -= Info about function 'GROUP_COUNT' =-

[Synopsis]
Counts the number of channels in the specified group.

[Description]
Calculates the group count for the specified group, or uses the channel's
current group if not specifed (and non-empty).

[Syntax]
GROUP_COUNT([groupname][@category])

[Arguments]
groupname
    Group name.
category
    Category name

[See Also]
Not available
</code>```

https://www.voip-info.org/wiki/view/Asterisk+func+group

Body:
You can use GROUP and GROUP_COUNT dialplan  functions.

In AGI you can do that via

$agi->set_full_variable("new_var",'${GROUP_COUNT(group_name)}')

pro-sip*CLI> core show function GROUP

  -= Info about function 'GROUP' =-

[Synopsis]
Gets or sets the channel group.

[Description]
<category> can be employed for more fine grained group management. Each channel
can only be member of exactly one group per <category>.

[Syntax]
GROUP([category])

[Arguments]
category
    Category name.

[See Also]
Not available

pro-sip*CLI> core show function GROUP_COUNT

  -= Info about function 'GROUP_COUNT' =-

[Synopsis]
Counts the number of channels in the specified group.

[Description]
Calculates the group count for the specified group, or uses the channel's
current group if not specifed (and non-empty).

[Syntax]
GROUP_COUNT([groupname][@category])

[Arguments]
groupname
    Group name.
category
    Category name

[See Also]
Not available

https://www.voip-info.org/wiki/view/Asterisk+func+group


问:
php mysql issue with printing value on html page
I'm trying to query MySQL DB and print a single result on the page using PHP.

It's always going to be a single result, so I'm not sure if I need to loop

In any case, would anyone mind advising why the below doesn't work?

Thank you!!

```<code>    // Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
 else {
    echo "success";
}

$sql = "SELECT sum(Discounted_Value) as id FROM Orders WHERE Year = 2017";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "Total 2017 "  $row["id"]. "<br>";
    }
} else {
    echo "0 results";
}
$conn->close();
</code>```

答:
If there will be only one result you can simplify code to:</p>

```<code>$sql = "SELECT sum(Discounted_Value) as id FROM Orders WHERE Year = 2017";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
echo "Total 2017 " . $row["id"] . "<br>";  // Don't forget dots for concatenation
</code>```

Body:
I'm trying to query MySQL DB and print a single result on the page using PHP.

It's always going to be a single result, so I'm not sure if I need to loop

In any case, would anyone mind advising why the below doesn't work?

Thank you!!

    // Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
 else {
    echo "success";
}

$sql = "SELECT sum(Discounted_Value) as id FROM Orders WHERE Year = 2017";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "Total 2017 "  $row["id"]. "
";
    }
} else {
    echo "0 results";
}
$conn->close();

Body:
If there will be only one result you can simplify code to:

$sql = "SELECT sum(Discounted_Value) as id FROM Orders WHERE Year = 2017";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
echo "Total 2017 " . $row["id"] . "<br>";  // Don't forget dots for concatenation


问:
how to convert html to pdf with specific font or language using pdfmake
This is just a simple html file using pdfmake .
I click a button and then open a pdf file .
using :

```<code>pdfMake.createPdf(docDefinition).open();
</code>```

it's ok , but now i want to see a specific language (ex:Bangla) in my pdfpage . how it is possible . please help or suggest me .

header part:

```<code><head>
    <!--    <meta charset="utf-8" />-->
    <meta http-equiv="Content-Type" content="text/html" meta charset="utf-8" />
    <title>html to pdf</title>
    <link href="css/main.css" rel="stylesheet">
    <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
    <script src='pdfmake/build/pdfmake.min.js'></script>
    <script src='pdfmake/build/vfs_fonts.js'></script>
    <script src='build/pdfmake.min.js'></script>
    <script src='build/vfs_fonts.js'></script>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>

</head>
</code>```

body part :

```<code><body>

    <h1>Hello World</h1>
    <div class="btn-group">
        <div class="btn btn-success buttin_click_1" type="button">download</div>
        <div class="btn btn-danger button_click_2" type="button">open</div>
    </div>

</body>
</code>```

Script :

```<code><script>
    $(document).ready(function () {
        var docDefinition = {
            content: 'This is an sample PDF printed with pdfMake ami '
        };

        $('.buttin_click_1').click(function () {
            console.log('btn 1 clicked');
            pdfMake.createPdf(docDefinition).open();
        });

        $('.button_click_2').click(function () {
            console.log('btn 2 clicked');
        });
    });
</script>
</code>```

Thank you .

答:
Import the Font in pdfMake.

Afterwards update the vfs_fonts.js as described on github

assign pdfMake.fonts in your javascript

```

    $(document).ready(function () {
        pdfMake.fonts = {
            'SolaimanLipi': {
                normal: 'SolaimanLipi-Regular.ttf',
                bold: 'SolaimanLipi-Medium.ttf'
            }
        };
        var docDefinition = {
            content: 'হ্যালো',
            defaultStyle:{
                font: 'SolaimanLipi'
            }
        };

        $('.buttin_click_1').click(function () {
            console.log('btn 1 clicked');
            pdfMake.createPdf(docDefinition).open();
        });

        $('.button_click_2').click(function () {
            console.log('btn 2 clicked');
        });
    });

```

Body:
This is just a simple html file using pdfmake .
I click a button and then open a pdf file .
using :

pdfMake.createPdf(docDefinition).open();

it's ok , but now i want to see a specific language (ex:Bangla) in my pdfpage . how it is possible . please help or suggest me .

header part:

    <meta http-equiv="Content-Type" content="text/html" meta charset="utf-8" />
    <title>html to pdf</title>
    <link href="css/main.css" rel="stylesheet">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">

body part :

Hello World

download

open

Script :

Thank you .

Body:
Import the Font in pdfMake.

Afterwards update the vfs_fonts.js as described on github

assign pdfMake.fonts in your javascript

    $(document).ready(function () {
        pdfMake.fonts = {
            'SolaimanLipi': {
                normal: 'SolaimanLipi-Regular.ttf',
                bold: 'SolaimanLipi-Medium.ttf'
            }
        };
        var docDefinition = {
            content: 'হ্যালো',
            defaultStyle:{
                font: 'SolaimanLipi'
            }
        };

        $('.buttin_click_1').click(function () {
            console.log('btn 1 clicked');
            pdfMake.createPdf(docDefinition).open();
        });

        $('.button_click_2').click(function () {
            console.log('btn 2 clicked');
        });
    });


问:
Passing object as array in body in proto3
I'm wondering how I can pass an array as the body of the message without having to specify a key. I can easily do:

```<code>message TypeResponse {
  message Type {
    string ID = 1;
    string Name = 2;
    string Description = 3;
    string IsMobile = 4;
    string IsTablet = 5;
    string IsDesktop = 6;
  }
  repeated Type types = 1;
}
</code>```

That would response with:

```<code>{
  "types": [
    {
      "ID": 1
      ...
    }
  ]
}
</code>```

I'd like to structure my response as the following to match my REST API:

```<code>[
    {
      "ID": 1
      ...
    },
    {
      "ID": 2
      ...
    }
]
</code>```

答:
Proto requires that the top level concept is a message, which spills into the JSON mapping.

Something you could do is just skip the first characters until you reach a [ character, and then drop the very last character which will be a ].  The output format for JSON is specified by the Proto3 spec, so you can reasonably depend on the format.

Body:
I'm wondering how I can pass an array as the body of the message without having to specify a key. I can easily do:

message TypeResponse {
  message Type {
    string ID = 1;
    string Name = 2;
    string Description = 3;
    string IsMobile = 4;
    string IsTablet = 5;
    string IsDesktop = 6;
  }
  repeated Type types = 1;
}

That would response with:

{
  "types": [
    {
      "ID": 1
      ...
    }
  ]
}

I'd like to structure my response as the following to match my REST API:

[
    {
      "ID": 1
      ...
    },
    {
      "ID": 2
      ...
    }
]


问:
In Python, is there an elegant way to print a list in a custom format without explicit looping?
I know you can do

```<code>print str(myList)
</code>```

to get

```<code>[1, 2, 3]
</code>```

and you can do

```<code>i = 0
for entry in myList:
  print str(i) + ":", entry
  i += 1
</code>```

to get

```<code>0: 1
1: 2
2: 3
</code>```

But is there a way similar to the first to get a result similar to the last?

With my limited knowledge of Python (and some help from the documentation), my best is:

```<code>print '\n'.join([str(n) + ": " + str(entry) for (n, entry) in zip(range(0,len(myList)), myList)])
</code>```

It's not much less verbose, but at least I get a custom string in one (compound) statement.
Can you do better?

答:
```<code>from time import clock
from random import sample

n = 500
myList = sample(xrange(10000),n)
#print myList

A,B,C,D = [],[],[],[]

for i in xrange(100):
    t0 = clock()
    ecr =( '\n'.join('{}: {}'.format(*k) for k in enumerate(myList)) )
    A.append(clock()-t0)

    t0 = clock()
    ecr = '\n'.join(str(n) + ": " + str(entry) for (n, entry) in zip(range(0,len(myList)), myList))
    B.append(clock()-t0)

    t0 = clock()
    ecr = '\n'.join(map(lambda x: '%s: %s' % x, enumerate(myList)))
    C.append(clock()-t0)

    t0 = clock()
    ecr = '\n'.join('%s: %s' % x for x in enumerate(myList))
    D.append(clock()-t0)

print '\n'.join(('t1 = '+str(min(A))+'   '+'{:.1%}.'.format(min(A)/min(D)),
                 't2 = '+str(min(B))+'   '+'{:.1%}.'.format(min(B)/min(D)),
                 't3 = '+str(min(C))+'   '+'{:.1%}.'.format(min(C)/min(D)),
                 't4 = '+str(min(D))+'   '+'{:.1%}.'.format(min(D)/min(D))))
</code>```

For n=500:

```<code>150.8%.
142.7%.
110.8%.
100.0%.
</code>```

For n=5000:

```<code>153.5%.
176.2%.
109.7%.
100.0%.
</code>```

Oh, I see now: only the solution 3 with map() fits with the title of the question.

ContentLicense: CC BY-SA 2.5

Body:
I know you can do

print str(myList)

to get

[1, 2, 3]

and you can do

i = 0
for entry in myList:
  print str(i) + ":", entry
  i += 1

to get

0: 1
1: 2
2: 3

But is there a way similar to the first to get a result similar to the last?

With my limited knowledge of Python (and some help from the documentation), my best is:

print '\n'.join([str(n) + ": " + str(entry) for (n, entry) in zip(range(0,len(myList)), myList)])

It's not much less verbose, but at least I get a custom string in one (compound) statement.
Can you do better?

Body:
from time import clock
from random import sample

n = 500
myList = sample(xrange(10000),n)
#print myList

A,B,C,D = [],[],[],[]

for i in xrange(100):
    t0 = clock()
    ecr =( '\n'.join('{}: {}'.format(*k) for k in enumerate(myList)) )
    A.append(clock()-t0)

    t0 = clock()
    ecr = '\n'.join(str(n) + ": " + str(entry) for (n, entry) in zip(range(0,len(myList)), myList))
    B.append(clock()-t0)

    t0 = clock()
    ecr = '\n'.join(map(lambda x: '%s: %s' % x, enumerate(myList)))
    C.append(clock()-t0)

    t0 = clock()
    ecr = '\n'.join('%s: %s' % x for x in enumerate(myList))
    D.append(clock()-t0)

print '\n'.join(('t1 = '+str(min(A))+'   '+'{:.1%}.'.format(min(A)/min(D)),
                 't2 = '+str(min(B))+'   '+'{:.1%}.'.format(min(B)/min(D)),
                 't3 = '+str(min(C))+'   '+'{:.1%}.'.format(min(C)/min(D)),
                 't4 = '+str(min(D))+'   '+'{:.1%}.'.format(min(D)/min(D))))

For n=500:

150.8%.
142.7%.
110.8%.
100.0%.

For n=5000:

153.5%.
176.2%.
109.7%.
100.0%.

Oh, I see now: only the solution 3 with map() fits with the title of the question.


问:
.framework file as Carthage (Fabric & Crashlytics example)
I'm facing now choosing dependency manager for the second version of my project. I've done my homework and check all dependencies that I will need for Carthage support and turns out everything without Fabric & Crashlytics. For this two I would rather get some extra work than integrate whole cocoapods for that.

So my question is - can I create an example project that i will put on github and make a autobuilding dynamic scheme that allow me to integrate 3rd-party .framework files inside my project?

So what my starting point is making a script to check version of pods in a website and check if my downloaded file is in the newest version. That's done. But I have a .framework file and how to embedded it in xcode project to support carthage?

答: @Kuba - you could use the Xcodeproj gem to modify the project and include the frameworks</p>


问:
Firebase - Multi-location updates method deprecated, what now?
I had some apps that used the multi-location update method as below:

```<code>const updates = [];
updates['/location1'] = data;
updates['/location2'] = data2;

firebase.database().ref().update(updates);
</code>```

Yet, as I'm developing a new app, I got the following message:

FIREBASE WARNING: Passing an Array to Firebase.update() is deprecated. Use set() if you want to overwrite the existing data, or an Object with integer keys if you really do want to only update some of the children.

With no real info anywhere about how to perform multi-location atomic updates anywhere, and the docs are still with the old method. Chaining then() is not a good idea, as it would be a nightmare to rollback.

Any clues and/or information on new multi-location updates methods?

答:
I didn't even know you could pass an array. You should instead pass an object:

```<code>const updates = {}; // this line is different
updates['/location1'] = data;
updates['/location2'] = data2;

firebase.database().ref().update(updates);
</code>```

The array syntax we use for setting properties works on a JavaScript object too.

Body:
I had some apps that used the multi-location update method as below:

const updates = [];
updates['/location1'] = data;
updates['/location2'] = data2;

firebase.database().ref().update(updates);

Yet, as I'm developing a new app, I got the following message:

FIREBASE WARNING: Passing an Array to Firebase.update() is deprecated. Use set() if you want to overwrite the existing data, or an Object with integer keys if you really do want to only update some of the children.

With no real info anywhere about how to perform multi-location atomic updates anywhere, and the docs are still with the old method. Chaining then() is not a good idea, as it would be a nightmare to rollback.

Any clues and/or information on new multi-location updates methods?

Body:
I didn't even know you could pass an array. You should instead pass an object:

const updates = {}; // this line is different
updates['/location1'] = data;
updates['/location2'] = data2;

firebase.database().ref().update(updates);

The array syntax we use for setting properties works on a JavaScript object too.


问:
Flowtype - making a sealed empty object
Flow's docs say: When you create an object without any properties, you create an unsealed object type in Flow. Is it possible to create a sealed object without properties?

My use case is as follows. I want to initialize state to an empty object, and give state the following type:

```<code>type EmployeesViewState = {|
  employeesRequest?: Request<Array<Employee>>,
  geosRequest?: Request<Array<Geo>>,
|};
</code>```

The error I get when I try to assign an empty object is

```<code> 33:   state: EmployeesViewState = {};
                                   ^^ object literal. Inexact type is incompatible with exact type
 33:   state: EmployeesViewState = {};
              ^^^^^^^^^^^^^^^^^^ exact type: object type
</code>```

Of course, since I don't have the requests available yet, I cannot assign them. I also can't assign undefined to the object because the state is defined with pipes, i.e. it is an exact type.

I can trick flow by saying const a: any = {}; state = a; but that seems really hacky. Any other ways of tackling this issue?

答:
This is certainly one of Flow's warts. However, it has a fairly simple workaround. Just pass your object through Object.freeze:

Object.freeze({})

Of course this only works if you weren't going to mutate it, but I find that in cases like this I rarely want to anyway.

Title: Flowtype - making a sealed empty object

Body:
Flow's docs say: When you create an object without any properties, you create an unsealed object type in Flow. Is it possible to create a sealed object without properties?

My use case is as follows. I want to initialize state to an empty object, and give state the following type:

type EmployeesViewState = {|
  employeesRequest?: Request<Array<Employee>>,
  geosRequest?: Request<Array<Geo>>,
|};

The error I get when I try to assign an empty object is

 33:   state: EmployeesViewState = {};
                                   ^^ object literal. Inexact type is incompatible with exact type
 33:   state: EmployeesViewState = {};
              ^^^^^^^^^^^^^^^^^^ exact type: object type

Of course, since I don't have the requests available yet, I cannot assign them. I also can't assign undefined to the object because the state is defined with pipes, i.e. it is an exact type.

I can trick flow by saying const a: any = {}; state = a; but that seems really hacky. Any other ways of tackling this issue?


问:
Swift Spritekit change color of node when tapped multiple times
i am trying to get it to change the fillcolor of a node on my menuscene based on colors in an array.

I have an array filled with 4 colors, and when I press the node it should filter through those colors based on the position. So when I tap the node once it should change color to red, if I tap it again it changes to green, another tap would change it to purple, and then back to blue

```<code>var colors = [UIColor.blue, UIColor.red, UIColor.green, UIColor.purple]

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first!
    var index = 0
    if changeColor.contains(touch.location(in: self)) {
        index += 1
        changeColor.fillColor = colors[index]
        if index == 3 {
            index = 0
        }
    }
}
</code>```

However, this only reads one tap, and I need it register multiple taps

答:
move initialization of the index outside the touches begin function and increment the index after changing the color.</p>

```<code>var colors = [UIColor.blue, UIColor.red, UIColor.green, UIColor.purple]
var index = 0

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first!

    if changeColor.contains(touch.location(in: self)) {
        changeColor.fillColor = colors[index]
        index += 1

        if index == colors.count {
            index = 0
        }
    }
}
</code>```

Body:
i am trying to get it to change the fillcolor of a node on my menuscene based on colors in an array.

I have an array filled with 4 colors, and when I press the node it should filter through those colors based on the position. So when I tap the node once it should change color to red, if I tap it again it changes to green, another tap would change it to purple, and then back to blue

var colors = [UIColor.blue, UIColor.red, UIColor.green, UIColor.purple]

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first!
    var index = 0
    if changeColor.contains(touch.location(in: self)) {
        index += 1
        changeColor.fillColor = colors[index]
        if index == 3 {
            index = 0
        }
    }
}

However, this only reads one tap, and I need it register multiple taps

Body:
move initialization of the index outside the touches begin function and increment the index after changing the color.

var colors = [UIColor.blue, UIColor.red, UIColor.green, UIColor.purple]
var index = 0

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first!

    if changeColor.contains(touch.location(in: self)) {
        changeColor.fillColor = colors[index]
        index += 1

        if index == colors.count {
            index = 0
        }
    }
}


问:
Controlling Eclipse CDT debugger output?
When using CDT I would like to have std::string show up in the 'variable' debug window with the string it contains. For instance if it is currently holding the word "history" I would like to see history in the debugger window labeled "variables".

I think that there is a general way to have it drill down into objects but I can't put my finger on it. Does anyone out there know how to do this?

This would also be useful for me to use when outputting just a single field from a complex object.

Thanks,
Bill

答:
The only way I have found is to use the GDB command line:

In the Debug window, click on gdb.
It's just below the stack trace.

In the Console window, use the GDB up command to get to the stack frame you want

Again in the Console window, use the print command to display the
std::string variable:

p mystring

But that's a lot of trouble.

Something I have noticed is that when I hover over the variable, the fields of the std::string actually are displayed, but it is truncated, so I do not see the most interesting part: the string value.  Perhaps there is a way to increase the maximum length of the value displayed.

OwnerDisplayName: billcoke

OwnerDisplayName: John McGehee


问:
How to save file under different name in vi
I am frequently editting a file in vi and I want to save it under a different name than the name that I opened it under.

I have tried saving like this:  :w >> new_file_name but I ALWAYS get E212: Can't open file for writing.

What is the correct way around this?

答:
Enter :w filename in vi command mode, like @Yedidia said...

I think you are confusing writing terminal output to a file.

Which would be following command in order to create or overwrite text.txt:

```<code> action > text.txt
</code>```

and in order to append the output of an command to text.txt would be:

```<code>action >> text.txt
</code>```

Body:
Enter :w filename in vi command mode, like @Yedidia said...

I think you are confusing writing terminal output to a file.

Which would be following command in order to create or overwrite text.txt:

 action > text.txt

and in order to append the output of an command to text.txt would be:

action >> text.txt


问:
Cython: Not exposing parts of the implementation
I'm making a cython integration model for some code in C++, and I have the following question:

Can I chose to not expose parts of my implementation that are internal?

For example:

myclass.hpp

```<code>class MyClass {
  private:
   foo _bar;
  public:
   do_stuff();
};
</code>```

I chose to intentionally leave out _bar from the cython module, because it is internal to the implementation

myclass.pyx

```<code>cdef extern from "myclass.hpp":
    cdef cppclass MyClass:
        cdef public void do_stuff()
</code>```

答:
Yes you can omit implementation details.

Your Cython code does two things

it includes "myclass.hpp" so that the C++ compiler can access the necessary implementation details.

It tells Cython about the specific methods, attributes or subclasses (etc) you want to use (in your case do_stuff). The only consequence of not telling Cython about a method/detail is that you can't access it directly from Cython.

Body:
I'm making a cython integration model for some code in C++, and I have the following question:

Can I chose to not expose parts of my implementation that are internal?

For example:

myclass.hpp

class MyClass {
  private:
   foo _bar;
  public:
   do_stuff();
};

I chose to intentionally leave out _bar from the cython module, because it is internal to the implementation

myclass.pyx

cdef extern from "myclass.hpp":
    cdef cppclass MyClass:
        cdef public void do_stuff()


问:
How to convert date/time string to epoch?
Have the following string:

```<code>"date Thursday June 03 12:02:56 2017"
</code>```

What would be the proper way of convert it to epoch time?

答:
You can use datetime.strptime() to parse your date and then just do delta with the epoch:

```<code>from datetime import datetime as dt

epoch = dt(1970, 1, 1)
date = "date Thursday June 03 12:02:56 2017"

epoch_time = int((dt.strptime(date, "date %A %B %d %H:%M:%S %Y") - epoch).total_seconds())
# 1496491376
</code>```

Body:
Have the following string:

"date Thursday June 03 12:02:56 2017"

What would be the proper way of convert it to epoch time?

Body:
You can use datetime.strptime() to parse your date and then just do delta with the epoch:

from datetime import datetime as dt

epoch = dt(1970, 1, 1)
date = "date Thursday June 03 12:02:56 2017"

epoch_time = int((dt.strptime(date, "date %A %B %d %H:%M:%S %Y") - epoch).total_seconds())
# 1496491376


问:
Changing date format from input field in codeigniter to store in mysql
I have a text field where you can enter a date in the format dd/mm/yyyy, and I want to convert that date as yyyy-mm-dd to store in my database.

I know this has been asked many times before, and a common answer is trying something like this.

```<code>$var = '20/04/2012';
$date = str_replace('/', '-', $var);
echo date('Y-m-d', strtotime($date));
</code>```

The problem is I do not know how to apply that to my situation.

This is the code I have in my view

```<code><input type="text" name="initialDate" value="<?php echo $this->input->post('fechaElaboracion'); ?>" class="form-control" id="initialDate" />
</code>```

In my controller I get all the data from the input fields in my form, save them in an array and then call a function in my model to store them in the database.

```<code>$params = array(
    'name' => $this->input->post('name'),
    'address' => $this->input->post('address'),
    'initialDate' => $this->input->post('initialDate'),
);
$po_general_id = $this->Pogeneralmodel->add_po_general($params);
redirect('po_general/index');
</code>```

Do I need to reformat the date in the view or in the controller? How can I do it?
Thanks.

答:
Your view is only to display the results came from your Controller. In this case, it could be done in your Controller before passing to Model.</p>

```<code>$newDate = date("Y-m-d",strtotime($this->input->post('initialDate')));
$params = array(
    'name' => $this->input->post('name'),
    'address' => $this->input->post('address'),
    'initialDate' => $newDate,
);
$po_general_id = $this->Pogeneralmodel->add_po_general($params);
redirect('po_general/index');
</code>```

Body:
I have a text field where you can enter a date in the format dd/mm/yyyy, and I want to convert that date as yyyy-mm-dd to store in my database.

I know this has been asked many times before, and a common answer is trying something like this.

$var = '20/04/2012';
$date = str_replace('/', '-', $var);
echo date('Y-m-d', strtotime($date));

The problem is I do not know how to apply that to my situation.

This is the code I have in my view

<input type="text" name="initialDate" value="<?php echo $this->input->post('fechaElaboracion'); ?>" class="form-control" id="initialDate" />

In my controller I get all the data from the input fields in my form, save them in an array and then call a function in my model to store them in the database.

$params = array(
    'name' => $this->input->post('name'),
    'address' => $this->input->post('address'),
    'initialDate' => $this->input->post('initialDate'),
);
$po_general_id = $this->Pogeneralmodel->add_po_general($params);
redirect('po_general/index');

Do I need to reformat the date in the view or in the controller? How can I do it?
Thanks.

Body:
Your view is only to display the results came from your Controller. In this case, it could be done in your Controller before passing to Model.

$newDate = date("Y-m-d",strtotime($this->input->post('initialDate')));
$params = array(
    'name' => $this->input->post('name'),
    'address' => $this->input->post('address'),
    'initialDate' => $newDate,
);
$po_general_id = $this->Pogeneralmodel->add_po_general($params);
redirect('po_general/index');


问:
Odd problem with jQuery .change() event
I have the following select element with an onchange event.

```<code><select name="ftest" onchange="alert('test');">
  <option value="0"></option>
  <option value="test">test</option>
</select>
</code>```

I later bind another event on all the select elements in the page using jQuery (1.4.4).

```<code>   $("SELECT").change(function(){
    _isDirty = true;
   });
</code>```

The result is my alert showing up twice when I change the value of my select list.

Anyone has an idea why this is happening or have a way to fix this?

Thanks

答: This is a known bug with IE and jQuery, due to the way they simulate bubbling for change in IE.  Unfortunately, there isn't a clean work-around at the moment, besides removing the inline onchange handler.

Title: Odd problem with jQuery .change() event

Body:
I have the following select element with an onchange event.

<select name="ftest" onchange="alert('test');">
  <option value="0"></option>
  <option value="test">test</option>
</select>

I later bind another event on all the select elements in the page using jQuery (1.4.4).

   $("SELECT").change(function(){
    _isDirty = true;
   });

The result is my alert showing up twice when I change the value of my select list.

Anyone has an idea why this is happening or have a way to fix this?

Thanks