问:
How to prevent more than one click on an Anchor tag button
I have an anchor tag (namely Cancel button) with a class attribute and href attribute in a jsp file .

I have written an onclick event for the class attribute in a seperate js file. So when the button is clicked, the onclick event executes and then takes to the href link.

When the button is clicked more than once it takes me to an empty page or an error page.

I want to prevent more than one click on the button.

I have tried using event.preventdefault() function inside my onclick() function but the href link is not working if I do that.
Any other way?

My JS code:

```<code>$('.cancel-btn').on('click',function(evt){
            //evt.preventDefault();
           //My Code

        });
</code>```

答:
As you mentioned the event is written on that class, you can use this simple code to ensure that its clicked only once:

```<code>$('.cancel-btn').on('click', function(evt) {
  // execue your code
  $(this).removeClass('cancel-btn');
});
</code>```

This code will remove the class from the DOM and hence the click event will never get fired.

Optionally, You can use off() to remove an event like so:

```<code>$(".cancel-button").off("click");
</code>```

This will remove all click events bound to this element. In your code, it would be like:

```<code>    $('.cancel-btn').on('click', function(evt) {
      // execue your code
      $(this).off("click");
    });
</code>```

Body:
I have an anchor tag (namely Cancel button) with a class attribute and href attribute in a jsp file .

I have written an onclick event for the class attribute in a seperate js file. So when the button is clicked, the onclick event executes and then takes to the href link.

When the button is clicked more than once it takes me to an empty page or an error page.

I want to prevent more than one click on the button.

I have tried using event.preventdefault() function inside my onclick() function but the href link is not working if I do that.
Any other way?

My JS code:

$('.cancel-btn').on('click',function(evt){
            //evt.preventDefault();
           //My Code

        });

Body:
As you mentioned the event is written on that class, you can use this simple code to ensure that its clicked only once:

$('.cancel-btn').on('click', function(evt) {
  // execue your code
  $(this).removeClass('cancel-btn');
});

This code will remove the class from the DOM and hence the click event will never get fired.

Optionally, You can use off() to remove an event like so:

$(".cancel-button").off("click");

This will remove all click events bound to this element. In your code, it would be like:

    $('.cancel-btn').on('click', function(evt) {
      // execue your code
      $(this).off("click");
    });


来源: stackexchange

问:
404 when requesting json file with Angular http
I have this code in my service

```<code>import {Injectable} from '@angular/core';
import {Http, Headers, RequestOptions} from '@angular/http';
import 'rxjs/add/operator/map';
import {Client} from "../clients/client";
import {Observable} from "rxjs/Observable";

@Injectable()
export class ClientsService {

  private clientUrl = './client.json';

  private headers = new Headers({ 'Accept': 'application/json' });
  private options = new RequestOptions({ headers: this.headers });

  private client : Client;

  constructor(private http:Http) {}

  getClient() : Observable<any>{
    return this.http.get(this.clientUrl, this.options)
      .map(res => res);
  }
}
</code>```

and in my component I'm calling it:

```<code>this.client = this.clientsService.getClient()
  .subscribe(data => {
    console.log(data);
  });
</code>```

But I'm getting 404 error

But I have this json file in the same folder where my service is.

What's wrong?

答:
If you using angular-cli Keep the json file inside Assets folder (parallel to app dir) directory

In your case you need to create file like assets/client.json

```<code>return this.http.get('/client.json'))
    .map((response: Response) => {
        console.log("mock data" + response.json());
        return response.json();
    }
    )
    .catch(this.handleError);
}
</code>```

Note: here you only need to give path inside assets folder like assets/client.json then you need to write path like /client.json

If you using webpack then you need to follow above same structure inside public folder its similar like assets folder.

ContentLicense: CC BY-SA 4.0

Body:
I have this code in my service

import {Injectable} from '@angular/core';
import {Http, Headers, RequestOptions} from '@angular/http';
import 'rxjs/add/operator/map';
import {Client} from "../clients/client";
import {Observable} from "rxjs/Observable";

@Injectable()
export class ClientsService {

  private clientUrl = './client.json';

  private headers = new Headers({ 'Accept': 'application/json' });
  private options = new RequestOptions({ headers: this.headers });

  private client : Client;

  constructor(private http:Http) {}

  getClient() : Observable<any>{
    return this.http.get(this.clientUrl, this.options)
      .map(res => res);
  }
}

and in my component I'm calling it:

this.client = this.clientsService.getClient()
  .subscribe(data => {
    console.log(data);
  });

But I'm getting 404 error

But I have this json file in the same folder where my service is.

What's wrong?

Body:
If you using angular-cli Keep the json file inside Assets folder (parallel to app dir) directory

In your case you need to create file like assets/client.json

return this.http.get('/client.json'))
    .map((response: Response) => {
        console.log("mock data" + response.json());
        return response.json();
    }
    )
    .catch(this.handleError);
}

Note: here you only need to give path inside assets folder like assets/client.json then you need to write path like /client.json

If you using webpack then you need to follow above same structure inside public folder its similar like assets folder.

ContentLicense: CC BY-SA 3.0


问:
Microsoft bot error - Exception: invalid need: expected Call, have Poll
I keep getting this error and I don't know how to fix it: Exception: invalid need: expected Call, have Poll

```<code>            PromptDialog.Text(context, setEmail, "What is the contact's email? ");
            PromptDialog.Text(context, setPhone, "What is the contact's phone number? ");

    private async Task setPhone(IDialogContext context, IAwaitable<string> result)
    {
        this.contact1.Phone = await result;
        ReturnContact(context, contact1);

    }

    private async Task setEmail(IDialogContext context, IAwaitable<string> result)
    {
        this.contact1.Email = await result;
        ReturnContact(context, contact1);
    }
</code>```

the prompt dialogs are part of a different method. How do I prompt the user twice in a row without getting this error?

答:
PromptDialog.Text was not designed to be called twice, because you need two different answers from a user, so in terms of botframework it is like two separate "transactions".

Rather than making a double call you need to create a cascade of calls, where you initiate the Phone question from the Email question handler:

```<code>[Serializable]
public class SomeDialog : IDialog<object>
{
    public async Task StartAsync(IDialogContext context)
    {
        context.Wait(MessageReceivedAsync);
    }

    private async Task OnPhoneSet(IDialogContext context, IAwaitable<string> result)
    {
        var res = await result;
    }

    private async Task OnEmailSet(IDialogContext context, IAwaitable<string> result)
    {
        var res = await result;
        PromptDialog.Text(context, OnPhoneSet, "What is the contact's phone number? ");
    }

    public virtual async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> argument)
    {
        var message = await argument;

        PromptDialog.Text(context, OnEmailSet, "What is the contact's email? ");
    }
}
</code>```

The workflow is like the following:

User initiates a dialog for the first time. Callstack: StartAsync ->  MessageReceivedAsync -> PromptDialog.Text(context, OnEmailSet). Now dialog is waiting for Email posted

User posts Email. Callstack: OnEmailSet -> PromptDialog.Text(context, OnPhoneSet. Now dialog is waiting for Phone posted

User posts Phone. Callstack: OnPhoneSet. On OnPhoneSet you'll do further actions, for example you can close dialog using Context.Done or something.

Body:
I keep getting this error and I don't know how to fix it: Exception: invalid need: expected Call, have Poll

            PromptDialog.Text(context, setEmail, "What is the contact's email? ");
            PromptDialog.Text(context, setPhone, "What is the contact's phone number? ");

    private async Task setPhone(IDialogContext context, IAwaitable<string> result)
    {
        this.contact1.Phone = await result;
        ReturnContact(context, contact1);

    }

    private async Task setEmail(IDialogContext context, IAwaitable<string> result)
    {
        this.contact1.Email = await result;
        ReturnContact(context, contact1);
    }

the prompt dialogs are part of a different method. How do I prompt the user twice in a row without getting this error?

Body:
PromptDialog.Text was not designed to be called twice, because you need two different answers from a user, so in terms of botframework it is like two separate "transactions".

Rather than making a double call you need to create a cascade of calls, where you initiate the Phone question from the Email question handler:

[Serializable]
public class SomeDialog : IDialog<object>
{
    public async Task StartAsync(IDialogContext context)
    {
        context.Wait(MessageReceivedAsync);
    }

    private async Task OnPhoneSet(IDialogContext context, IAwaitable<string> result)
    {
        var res = await result;
    }

    private async Task OnEmailSet(IDialogContext context, IAwaitable<string> result)
    {
        var res = await result;
        PromptDialog.Text(context, OnPhoneSet, "What is the contact's phone number? ");
    }

    public virtual async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> argument)
    {
        var message = await argument;

        PromptDialog.Text(context, OnEmailSet, "What is the contact's email? ");
    }
}

The workflow is like the following:

User initiates a dialog for the first time. Callstack: StartAsync ->  MessageReceivedAsync -> PromptDialog.Text(context, OnEmailSet). Now dialog is waiting for Email posted

User posts Email. Callstack: OnEmailSet -> PromptDialog.Text(context, OnPhoneSet. Now dialog is waiting for Phone posted

User posts Phone. Callstack: OnPhoneSet. On OnPhoneSet you'll do further actions, for example you can close dialog using Context.Done or something.


问:
Bash script assistance with find
I'm trying to write a bash script called by a daily cron schedule that will cycle all sub directories looking for a .git directory, run a git pull --all on that repository to update the repo and grab any new branches, track those branches, and then move on to the next repo. I'm a bash script beginner and familiar with some linux. My problem is the for loop which I found at How to clone all remote branches in Git? but doesn't seem to run properly now that I've introduced it into my script and the call to cd ${line}.. which doesn't seem to work as anticipated. I'm wondering what i've done wrong and some direction on how to fix it. Thank You.

My current script gitcron.sh:

```<code>#!/bin/bash

find . -maxdepth 2 -name .git -type d -print > .gitrepos

while read -r line; do
  cd ${line}/..
  git pull --all
  for branch in $(git branch --all | grep '^\s*remotes' | egrep --invert-match '(:?HEAD|master)$'); do
     git branch --track "${branch##*/}" "$branch"
  done
done < ".gitrepos"
</code>```

.gitrepos generated file:

```<code>./codeigniter/.git
./magento/.git
./magento2/.git
</code>```

My problem:

```<code>gitcron.sh: line 6: cd: ./magento2/.git/..: No such file or directory
fatal: it does not make sense to create 'HEAD' manually
error: unknown switch `>'
</code>```

答:
The problem is that you have changed the working directory (and keep changing) with cd ${line}/.. i.e. going to the parent of the {line}. Everything is done within teh same shell session. After first run, the directory would be changed to the parent of the first value of line variable, so next run(s) would (prsumably) fail because of failing to find the parent (and hence .git would not also be present).

To solve this, you can:

Use absolute paths to the directories in find:

```<code>find /foo/bar/ ...
</code>```

and then use while as is now.

Or run cd and successive block(s) in a subshell:

```<code>while ...; do (cd ...; ...); done <file
</code>```

As a side note, (always) quote your variable expansions to prevent word splitting and pathname expansion.

Title: Bash script assistance with find

Body:
I'm trying to write a bash script called by a daily cron schedule that will cycle all sub directories looking for a .git directory, run a git pull --all on that repository to update the repo and grab any new branches, track those branches, and then move on to the next repo. I'm a bash script beginner and familiar with some linux. My problem is the for loop which I found at How to clone all remote branches in Git? but doesn't seem to run properly now that I've introduced it into my script and the call to cd ${line}.. which doesn't seem to work as anticipated. I'm wondering what i've done wrong and some direction on how to fix it. Thank You.

My current script gitcron.sh:

#!/bin/bash

find . -maxdepth 2 -name .git -type d -print > .gitrepos

while read -r line; do
  cd ${line}/..
  git pull --all
  for branch in $(git branch --all | grep '^\s*remotes' | egrep --invert-match '(:?HEAD|master)$'); do
     git branch --track "${branch##*/}" "$branch"
  done
done < ".gitrepos"

.gitrepos generated file:

./codeigniter/.git
./magento/.git
./magento2/.git

My problem:

gitcron.sh: line 6: cd: ./magento2/.git/..: No such file or directory
fatal: it does not make sense to create 'HEAD' manually
error: unknown switch `>'

Body:
The problem is that you have changed the working directory (and keep changing) with cd ${line}/.. i.e. going to the parent of the {line}. Everything is done within teh same shell session. After first run, the directory would be changed to the parent of the first value of line variable, so next run(s) would (prsumably) fail because of failing to find the parent (and hence .git would not also be present).

To solve this, you can:

Use absolute paths to the directories in find:

find /foo/bar/ ...

and then use while as is now.

Or run cd and successive block(s) in a subshell:

while ...; do (cd ...; ...); done <file

As a side note, (always) quote your variable expansions to prevent word splitting and pathname expansion.


问:
Closest point on a cubic Bezier curve?
How can I find the point B(t) along a cubic Bezier curve that is closest to an arbitrary point P in the plane?</p>

答:
I've written some quick-and-dirty code that estimates this for Bézier curves of any degree. (Note: this is pseudo-brute force, not a closed-form solution.)

Demo: http://phrogz.net/svg/closest-point-on-bezier.html

/** Find the ~closest point on a Bézier curve to a point you supply.
 * out    : A vector to modify to be the point on the curve
 * curve  : Array of vectors representing control points for a Bézier curve
 * pt     : The point (vector) you want to find out to be near
 * tmps   : Array of temporary vectors (reduces memory allocations)
 * returns: The parameter t representing the location of `out`
 */
function closestPoint(out, curve, pt, tmps) {
    let mindex, scans=25; // More scans -> better chance of being correct
    const vec=vmath['w' in curve[0]?'vec4':'z' in curve[0]?'vec3':'vec2'];
    for (let min=Infinity, i=scans+1;i--;) {
        let d2 = vec.squaredDistance(pt, bézierPoint(out, curve, i/scans, tmps));
        if (d2<min) { min=d2; mindex=i }
    }
    let t0 = Math.max((mindex-1)/scans,0);
    let t1 = Math.min((mindex+1)/scans,1);
    let d2ForT = t => vec.squaredDistance(pt, bézierPoint(out,curve,t,tmps));
    return localMinimum(t0, t1, d2ForT, 1e-4);
}

/** Find a minimum point for a bounded function. May be a local minimum.
 * minX   : the smallest input value
 * maxX   : the largest input value
 * ƒ      : a function that returns a value `y` given an `x`
 * ε      : how close in `x` the bounds must be before returning
 * returns: the `x` value that produces the smallest `y`
 */
function localMinimum(minX, maxX, ƒ, ε) {
    if (ε===undefined) ε=1e-10;
    let m=minX, n=maxX, k;
    while ((n-m)>ε) {
        k = (n+m)/2;
        if (ƒ(k-ε)<ƒ(k+ε)) n=k;
        else               m=k;
    }
    return k;
}

/** Calculate a point along a Bézier segment for a given parameter.
 * out    : A vector to modify to be the point on the curve
 * curve  : Array of vectors representing control points for a Bézier curve
 * t      : Parameter [0,1] for how far along the curve the point should be
 * tmps   : Array of temporary vectors (reduces memory allocations)
 * returns: out (the vector that was modified)
 */
function bézierPoint(out, curve, t, tmps) {
    if (curve.length<2) console.error('At least 2 control points are required');
    const vec=vmath['w' in curve[0]?'vec4':'z' in curve[0]?'vec3':'vec2'];
    if (!tmps) tmps = curve.map( pt=>vec.clone(pt) );
    else tmps.forEach( (pt,i)=>{ vec.copy(pt,curve[i]) } );
    for (var degree=curve.length-1;degree--;) {
        for (var i=0;i<=degree;++i) vec.lerp(tmps[i],tmps[i],tmps[i+1],t);
    }
    return vec.copy(out,tmps[0]);
}
```

The code above uses the vmath library to efficiently lerp between vectors (in 2D, 3D, or 4D), but it would be trivial to replace the lerp() call in bézierPoint() with your own code.

Tuning the Algorithm

The closestPoint() function works in two phases:

First, calculate points all along the curve (uniformly-spaced values of the t parameter). Record which value of t has the smallest distance to the point.

Then, use the localMinimum() function to hunt the region around the smallest distance, using a binary search to find the t and point that produces the true smallest distance.

The value of scans in closestPoint() determines how many samples to use in the first pass. Fewer scans is faster, but increases the chances of missing the true minimum point.

The ε limit passed to the localMinimum() function controls how long it continues to hunt for the best value. A value of 1e-2 quantizes the curve into ~100 points, and thus you can see the points returned from closestPoint() popping along the line. Each additional decimal point of precision—1e-3, 1e-4, …—costs about 6-8 additional calls to bézierPoint().

ContentLicense: CC BY-SA 2.5

Title: Closest point on a cubic Bezier curve?

Body:
I've written some quick-and-dirty code that estimates this for Bézier curves of any degree. (Note: this is pseudo-brute force, not a closed-form solution.)

Demo: http://phrogz.net/svg/closest-point-on-bezier.html

/** Find the ~closest point on a Bézier curve to a point you supply.
 * out    : A vector to modify to be the point on the curve
 * curve  : Array of vectors representing control points for a Bézier curve
 * pt     : The point (vector) you want to find out to be near
 * tmps   : Array of temporary vectors (reduces memory allocations)
 * returns: The parameter t representing the location of `out`
 */
function closestPoint(out, curve, pt, tmps) {
    let mindex, scans=25; // More scans -> better chance of being correct
    const vec=vmath['w' in curve[0]?'vec4':'z' in curve[0]?'vec3':'vec2'];
    for (let min=Infinity, i=scans+1;i--;) {
        let d2 = vec.squaredDistance(pt, bézierPoint(out, curve, i/scans, tmps));
        if (d2<min) { min=d2; mindex=i }
    }
    let t0 = Math.max((mindex-1)/scans,0);
    let t1 = Math.min((mindex+1)/scans,1);
    let d2ForT = t => vec.squaredDistance(pt, bézierPoint(out,curve,t,tmps));
    return localMinimum(t0, t1, d2ForT, 1e-4);
}

/** Find a minimum point for a bounded function. May be a local minimum.
 * minX   : the smallest input value
 * maxX   : the largest input value
 * ƒ      : a function that returns a value `y` given an `x`
 * ε      : how close in `x` the bounds must be before returning
 * returns: the `x` value that produces the smallest `y`
 */
function localMinimum(minX, maxX, ƒ, ε) {
    if (ε===undefined) ε=1e-10;
    let m=minX, n=maxX, k;
    while ((n-m)>ε) {
        k = (n+m)/2;
        if (ƒ(k-ε)<ƒ(k+ε)) n=k;
        else               m=k;
    }
    return k;
}

/** Calculate a point along a Bézier segment for a given parameter.
 * out    : A vector to modify to be the point on the curve
 * curve  : Array of vectors representing control points for a Bézier curve
 * t      : Parameter [0,1] for how far along the curve the point should be
 * tmps   : Array of temporary vectors (reduces memory allocations)
 * returns: out (the vector that was modified)
 */
function bézierPoint(out, curve, t, tmps) {
    if (curve.length<2) console.error('At least 2 control points are required');
    const vec=vmath['w' in curve[0]?'vec4':'z' in curve[0]?'vec3':'vec2'];
    if (!tmps) tmps = curve.map( pt=>vec.clone(pt) );
    else tmps.forEach( (pt,i)=>{ vec.copy(pt,curve[i]) } );
    for (var degree=curve.length-1;degree--;) {
        for (var i=0;i<=degree;++i) vec.lerp(tmps[i],tmps[i],tmps[i+1],t);
    }
    return vec.copy(out,tmps[0]);
}

The code above uses the vmath library to efficiently lerp between vectors (in 2D, 3D, or 4D), but it would be trivial to replace the lerp() call in bézierPoint() with your own code.

Tuning the Algorithm

The closestPoint() function works in two phases:

First, calculate points all along the curve (uniformly-spaced values of the t parameter). Record which value of t has the smallest distance to the point.

Then, use the localMinimum() function to hunt the region around the smallest distance, using a binary search to find the t and point that produces the true smallest distance.

The value of scans in closestPoint() determines how many samples to use in the first pass. Fewer scans is faster, but increases the chances of missing the true minimum point.

The ε limit passed to the localMinimum() function controls how long it continues to hunt for the best value. A value of 1e-2 quantizes the curve into ~100 points, and thus you can see the points returned from closestPoint() popping along the line. Each additional decimal point of precision—1e-3, 1e-4, …—costs about 6-8 additional calls to bézierPoint().


问:
Two column of several divs
I'm making a 2-column layout with divs.
It should be something like this: http://dl.dropbox.com/u/4976861/html-demo.html

But there is a problem. If content stretches the side blocks vertically, the left blocks shift downwards: http://dl.dropbox.com/u/4976861/html-demo-2.html

If I put the sidebar into a wrapper div, it works fine, but it will make the code quiet messy because of the paddings and some background issues which I removed to simplify the demo, so I would like to leave this option for now.

答:
Put this under the 2 divs:</p>

```<code><div style="clear:both;"></div>
</code>```

Title: Two column of several divs

Body:
Put this under the 2 divs:

<div style="clear:both;"></div>


问:
How can I group by the count number of column values and sort it?
How can I group by the count number of column values and sort it?

I am a pandas learner.

I have original dataframe called data.log. Now I want to count the numbers group by 'c-ip-1', and sort the result.

The original data.log:

```<code>   sc-status  sc-substatus  sc-win32-status  time-taken       c-ip-1
0        200             0                0         986  31.7.188.55
1        200             0                0        2539  31.7.188.55
2        200             0                0        1172  31.7.188.56
3        200             0                0        3152  31.7.188.80
4        200             0                0        1091  31.7.188.80
...
99       200             0                0        1115  31.9.200.60
100      200             0                0        2000  31.9.200.61
</code>```

The expect result is as follows:

```<code>         c-ip-1                 count
0        31.7.188.56            1
1        31.9.200.61            1
2        31.7.188.55            2
...
34       31.9.200.60            5
</code>```

I tried to write python code and run it, but it failed:

```<code>import pandas as pd

df = pd.read_table('data.log', sep=" ")

print(df[['c-ip-1']].groupby(['c-ip-1']).agg(['count'])
</code>```

How can I use python solve the problem?

答:
You can use pd.Series.value_counts.  By default, it sorts in descending order of count size.  You can pass the parameter ascending=False to reverse that.  Then rename the axis and column

```<code>df['c-ip-1'].value_counts(ascending=True) \
    .rename_axis('c-ip-1').reset_index(name='count')

        c-ip-1  count
0  31.9.200.61      1
1  31.9.200.60      1
2  31.7.188.56      1
3  31.7.188.55      2
4  31.7.188.80      2
</code>```

Body:
How can I group by the count number of column values and sort it?

I am a pandas learner.

I have original dataframe called data.log. Now I want to count the numbers group by 'c-ip-1', and sort the result.

The original data.log:

   sc-status  sc-substatus  sc-win32-status  time-taken       c-ip-1
0        200             0                0         986  31.7.188.55
1        200             0                0        2539  31.7.188.55
2        200             0                0        1172  31.7.188.56
3        200             0                0        3152  31.7.188.80
4        200             0                0        1091  31.7.188.80
...
99       200             0                0        1115  31.9.200.60
100      200             0                0        2000  31.9.200.61

The expect result is as follows:

         c-ip-1                 count
0        31.7.188.56            1
1        31.9.200.61            1
2        31.7.188.55            2
...
34       31.9.200.60            5

I tried to write python code and run it, but it failed:

import pandas as pd

df = pd.read_table('data.log', sep=" ")

print(df[['c-ip-1']].groupby(['c-ip-1']).agg(['count'])

How can I use python solve the problem?

Body:
You can use pd.Series.value_counts.  By default, it sorts in descending order of count size.  You can pass the parameter ascending=False to reverse that.  Then rename the axis and column

df['c-ip-1'].value_counts(ascending=True) \
    .rename_axis('c-ip-1').reset_index(name='count')

        c-ip-1  count
0  31.9.200.61      1
1  31.9.200.60      1
2  31.7.188.56      1
3  31.7.188.55      2
4  31.7.188.80      2


问:
Sum and difference of two numbers using 2Pointers through a single function
Main function should have a function call like adddiff(&p,&q) ... Function definition be like void adddiff(*a,*b) it should perform both addition and subtraction ,it should not return values and should not use print statement in adddiff method.</p>

答:
Both arguments are passed by reference, so you can use them to "return" the results to the main function.
Remember to save their values locally before overriding them, though!</p>

```<code>void adddiff(int* a, int* b) {
    int orig_a = *a;
    int orig_b = *b;
    *a = orig_a + orig_b;
    *b = orig_a - orig_b;
}
</code>```

Body:
Both arguments are passed by reference, so you can use them to "return" the results to the main function.
Remember to save their values locally before overriding them, though!

void adddiff(int* a, int* b) {
    int orig_a = *a;
    int orig_b = *b;
    *a = orig_a + orig_b;
    *b = orig_a - orig_b;
}


问:
How to bruteforce an RSA private-key's passphrase?
I have an encrypted RSA key which needs a pass-phrase to unlock. I have forgotten the pass-phrase, but I remember that there are only 6 digits in that pass-phrase. I think brute-forcing it would give me the pass-phrase.

Thanks for your help iabdhv liasbv

答:
Well you could google for this and as in the comment the tag john the ripper was mentioned, but is not there anymore, I still assume that you initially wanted to use jtr. A manual is given here.

It's basic steps are:

Download and compile the Jumbo version of John the Ripper from Github.

Use gpg2john to convert your rsa_key to a jtr understandable format refered as file1 now.

Use john --incremental file1 to start jtr in brute-force mode.

Note however that the third step will make jtr also use chars and not only digits. You could change this by via settings in the config or you could simply create a small script to generate a password list with all possible passwords.

```<code>for number1 in range(0,9):
  for number2 in range(0,9):
    for number3 in range(0,9):
      for number4 in range(0,9):
        for number5 in range(0,9):
          for number6 in range(0,9):
            print str(number1) + str(number2) + str(number3) + str(number4) + str(number5) + str(number6)
</code>```

And then start this script on linux using python scriptname.py > passwords.txt
after it terminated start jtr using the following command:
john --wordlist=passwords.txt file1

Body:
Well you could google for this and as in the comment the tag john the ripper was mentioned, but is not there anymore, I still assume that you initially wanted to use jtr. A manual is given here.

It's basic steps are:

Download and compile the Jumbo version of John the Ripper from Github.

Use gpg2john to convert your rsa_key to a jtr understandable format refered as file1 now.

Use john --incremental file1 to start jtr in brute-force mode.

Note however that the third step will make jtr also use chars and not only digits. You could change this by via settings in the config or you could simply create a small script to generate a password list with all possible passwords.

for number1 in range(0,9):
  for number2 in range(0,9):
    for number3 in range(0,9):
      for number4 in range(0,9):
        for number5 in range(0,9):
          for number6 in range(0,9):
            print str(number1) + str(number2) + str(number3) + str(number4) + str(number5) + str(number6)

And then start this script on linux using python scriptname.py > passwords.txt
after it terminated start jtr using the following command:
john --wordlist=passwords.txt file1


问:
Matching a row number and value to a row on another sheet
As the title suggests, I am trying to create a system where a cell (which matches to a specific row) will search another sheet, find a number which matches its row number, and then puts in the paired value. I have attached a screenshot for a clearer picture.

This is what I have tried so far without any success.

IF(INDEX(A2:B8,2,2)=?,____,"")

I sort of understand the INDEX and MATCH function independently, but have no concrete understanding of how to incorporate the two for this problem. Also, I have already attempted to search google for help on this but have had difficulty even knowing what to enter as search terms, so help on that would be great as well for future problems.

Thanks in advance!

答:
using VBA you can accomplish this.  just paste this code into a new module and run it.</p>

```<code>Sub PasteToNewSheet()
Dim wsSource As Worksheet: Set wsSource = Worksheets(1)
Dim lastrow As Long: lastrow = wsSource.Cells(Rows.Count, 1).End(xlUp).Row
Dim wsDest As Worksheet: Set wsDest = Worksheets.Add(After:=wsSource)
Dim rngRows As Range: Set rngRows = wsSource.Range("A2:A" & lastrow)
Dim rng As Range
wsDest.Range("A1").Value = "Value"

For Each rng In rngRows
    If rng = "" then
        rng = rng
    ElseIf wsDest.Cells(rng.Value, 1) = "" Then
        wsDest.Cells(rng.Value, 1) = rng.Offset(, 1).Value
    ElseIf wsDest.Cells(rng.Value, 2) = "" Then
        wsDest.Cells(rng.Value, 2) = rng.Offset(, 1).Value
    ElseIf wsDest.Cells(rng.Value, 3) = "" Then
        wsDest.Cells(rng.Value, 3) = rng.Offset(, 1).Value
    End If
Next rng

End Sub
</code>```

Body:
using VBA you can accomplish this.  just paste this code into a new module and run it.

Sub PasteToNewSheet()
Dim wsSource As Worksheet: Set wsSource = Worksheets(1)
Dim lastrow As Long: lastrow = wsSource.Cells(Rows.Count, 1).End(xlUp).Row
Dim wsDest As Worksheet: Set wsDest = Worksheets.Add(After:=wsSource)
Dim rngRows As Range: Set rngRows = wsSource.Range("A2:A" & lastrow)
Dim rng As Range
wsDest.Range("A1").Value = "Value"

For Each rng In rngRows
    If rng = "" then
        rng = rng
    ElseIf wsDest.Cells(rng.Value, 1) = "" Then
        wsDest.Cells(rng.Value, 1) = rng.Offset(, 1).Value
    ElseIf wsDest.Cells(rng.Value, 2) = "" Then
        wsDest.Cells(rng.Value, 2) = rng.Offset(, 1).Value
    ElseIf wsDest.Cells(rng.Value, 3) = "" Then
        wsDest.Cells(rng.Value, 3) = rng.Offset(, 1).Value
    End If
Next rng

End Sub


问:
How to put a combobox on datagridview programmatically iterating a Collection
Using C#, with EntityFramework and codefirst, I have follow classes on my models layer:

```<code>public class Cliente
{
    public int ClienteId { get; set; }
    public string Nome { get; set; }
    public string Email { get; set; }
    public DateTime DataCadastro { get; set; }
    public bool Ativo { get; set; }

    public virtual ICollection<Endereco> Enderecos { get; set; }
    public virtual ICollection<Telefone> Telefones { get; set; }
}

    public class Endereco
    {
        public int EnderecoId { get; set; }
        public string Cep { get; set; }
        public string Rua { get; set; }
        public string Numero { get; set; }
        public string Complemento { get; set; }
        public string Bairro { get; set; }
        public string Cidade { get; set; }
        public string Estado { get; set; }
        public decimal TaxaDeEntrega { get; set; }

        public int ClienteId { get; set; }
        public virtual  Cliente Cliente { get; set; }
    }

    public class Telefone
    {
        public int TelefoneId { get; set; }
        public string Numero { get; set; }
        public int ClienteID { get; set; }

        public virtual Cliente Cliente { get; set; }
    }
</code>```

In my Forms, I have a form with a datagridview with columns with client name, email, date and a combobox with a telephones list for each client that can have more than one telephone. These configurations was mounted like this:

```<code>private void FormClientes_Load(object sender, EventArgs e)
        {
            this.FormBorderStyle = FormBorderStyle.None;
            this.ControlBox = false;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.ShowIcon = false;
            this.Dock = DockStyle.Fill;

            dataGridViewClientes.AutoGenerateColumns = false;
            dataGridViewClientes.RowHeadersVisible = false;//Omite a primeira coluna

            DataGridViewTextBoxColumn colNome = new DataGridViewTextBoxColumn();
            colNome.HeaderText = "NOME";
            colNome.DataPropertyName = "Nome";
            dataGridViewClientes.Columns.Add(colNome);

            DataGridViewTextBoxColumn colEmail = new DataGridViewTextBoxColumn();
            colEmail.HeaderText = "EMAIL";
            colEmail.DataPropertyName = "Email";
            dataGridViewClientes.Columns.Add(colEmail);

            DataGridViewTextBoxColumn colDataCadastro = new DataGridViewTextBoxColumn();
            colDataCadastro.HeaderText = "DATA CADASTRO";
            colDataCadastro.DataPropertyName = "DataCadastro";
            dataGridViewClientes.Columns.Add(colDataCadastro);

            DataGridViewComboBoxColumn colTelefones = new DataGridViewComboBoxColumn();
            colTelefones.HeaderText = "TELEFONES";
            colTelefones.DataPropertyName = "Numero";
            dataGridViewClientes.Columns.Add(colTelefones);

            FillDataGrid();
        }

        private void FillDataGrid()
        {
            foreach (var c in _clienteApp.GetAll())
            {
                DataGridViewComboBoxCell cbc = new DataGridViewComboBoxCell();

                foreach (var t in c.Telefones)
                {
                    cbc.Items.Add(t.Numero);
                }

                dataGridViewClientes.Rows.Add(c.Nome, c.Email, c.DataCadastro, cbc);
            }
        }
</code>```

The FillDataGrid() method I take BD data and fill the columns. The problem is when I go to add the telephones combobox in end of row. The program compile, but when load the form, the combobox is not monted and the following exception is showed: System.ArgumentException: The DataGridViewComboboxCell is not valid

If I do not put the DataGridViewComboBoxCell the rows is mount, but the combobox do not show telephones. Also try to create a combobox and add it on end of  dataGridViewClientes.Rows.Add(c.Nome, c.Email, c.DataCadastro, ... ); but witout success. Where I make a mistake yet? ?

答:
I believe the issue is from the line…

```<code>dataGridViewClientes.Rows.Add(c.Nome, c.Email, c.DataCadastro, cbc);
</code>```

Adding the combo box cell this way appears to throw this error. A workaround is to set the cell manually. It IS a combo box column, so it should be valid.

```<code>dataGridViewClientes.Rows[curRow].Cells["Numero"] = cbc;
</code>```

To help, a row index curRow is used to keep track of each client, one per row. The code below demonstrates my comments above. I added the line below to the phone columns properties to allow the “Numero” reference

```<code>colTelefones.Name = "Numero";
</code>```

Hope this helps.

```<code>private void FillDataGrid() {
  int curRow = 0;
  foreach (var c in _clienteApp.GetAll()) {
    DataGridViewComboBoxCell cbc = new DataGridViewComboBoxCell();

    foreach (var t in c.Telefones) {
      cbc.Items.Add(t.Numero);
    }

    dataGridViewClientes.Rows.Add(c.Nome, c.Email, c.DataCadastro);
    dataGridViewClientes.Rows[curRow].Cells["Numero"] = cbc;
    curRow++;
  }
}
</code>```

Body:
Using C#, with EntityFramework and codefirst, I have follow classes on my models layer:

public class Cliente
{
    public int ClienteId { get; set; }
    public string Nome { get; set; }
    public string Email { get; set; }
    public DateTime DataCadastro { get; set; }
    public bool Ativo { get; set; }

    public virtual ICollection<Endereco> Enderecos { get; set; }
    public virtual ICollection<Telefone> Telefones { get; set; }
}

    public class Endereco
    {
        public int EnderecoId { get; set; }
        public string Cep { get; set; }
        public string Rua { get; set; }
        public string Numero { get; set; }
        public string Complemento { get; set; }
        public string Bairro { get; set; }
        public string Cidade { get; set; }
        public string Estado { get; set; }
        public decimal TaxaDeEntrega { get; set; }

        public int ClienteId { get; set; }
        public virtual  Cliente Cliente { get; set; }
    }

    public class Telefone
    {
        public int TelefoneId { get; set; }
        public string Numero { get; set; }
        public int ClienteID { get; set; }

        public virtual Cliente Cliente { get; set; }
    }

In my Forms, I have a form with a datagridview with columns with client name, email, date and a combobox with a telephones list for each client that can have more than one telephone. These configurations was mounted like this:

private void FormClientes_Load(object sender, EventArgs e)
        {
            this.FormBorderStyle = FormBorderStyle.None;
            this.ControlBox = false;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.ShowIcon = false;
            this.Dock = DockStyle.Fill;

            dataGridViewClientes.AutoGenerateColumns = false;
            dataGridViewClientes.RowHeadersVisible = false;//Omite a primeira coluna

            DataGridViewTextBoxColumn colNome = new DataGridViewTextBoxColumn();
            colNome.HeaderText = "NOME";
            colNome.DataPropertyName = "Nome";
            dataGridViewClientes.Columns.Add(colNome);

            DataGridViewTextBoxColumn colEmail = new DataGridViewTextBoxColumn();
            colEmail.HeaderText = "EMAIL";
            colEmail.DataPropertyName = "Email";
            dataGridViewClientes.Columns.Add(colEmail);

            DataGridViewTextBoxColumn colDataCadastro = new DataGridViewTextBoxColumn();
            colDataCadastro.HeaderText = "DATA CADASTRO";
            colDataCadastro.DataPropertyName = "DataCadastro";
            dataGridViewClientes.Columns.Add(colDataCadastro);

            DataGridViewComboBoxColumn colTelefones = new DataGridViewComboBoxColumn();
            colTelefones.HeaderText = "TELEFONES";
            colTelefones.DataPropertyName = "Numero";
            dataGridViewClientes.Columns.Add(colTelefones);

            FillDataGrid();
        }

        private void FillDataGrid()
        {
            foreach (var c in _clienteApp.GetAll())
            {
                DataGridViewComboBoxCell cbc = new DataGridViewComboBoxCell();

                foreach (var t in c.Telefones)
                {
                    cbc.Items.Add(t.Numero);
                }

                dataGridViewClientes.Rows.Add(c.Nome, c.Email, c.DataCadastro, cbc);
            }
        }

The FillDataGrid() method I take BD data and fill the columns. The problem is when I go to add the telephones combobox in end of row. The program compile, but when load the form, the combobox is not monted and the following exception is showed: System.ArgumentException: The DataGridViewComboboxCell is not valid

If I do not put the DataGridViewComboBoxCell the rows is mount, but the combobox do not show telephones. Also try to create a combobox and add it on end of  dataGridViewClientes.Rows.Add(c.Nome, c.Email, c.DataCadastro, ... ); but witout success. Where I make a mistake yet? ?

Body:
I believe the issue is from the line…

dataGridViewClientes.Rows.Add(c.Nome, c.Email, c.DataCadastro, cbc);

Adding the combo box cell this way appears to throw this error. A workaround is to set the cell manually. It IS a combo box column, so it should be valid.

dataGridViewClientes.Rows[curRow].Cells["Numero"] = cbc;

To help, a row index curRow is used to keep track of each client, one per row. The code below demonstrates my comments above. I added the line below to the phone columns properties to allow the “Numero” reference

colTelefones.Name = "Numero";

Hope this helps.

private void FillDataGrid() {
  int curRow = 0;
  foreach (var c in _clienteApp.GetAll()) {
    DataGridViewComboBoxCell cbc = new DataGridViewComboBoxCell();

    foreach (var t in c.Telefones) {
      cbc.Items.Add(t.Numero);
    }

    dataGridViewClientes.Rows.Add(c.Nome, c.Email, c.DataCadastro);
    dataGridViewClientes.Rows[curRow].Cells["Numero"] = cbc;
    curRow++;
  }
}


问:
Remove HTML tag from string in AngularJS
I am getting HTML tags in my response, which I want to remove or parse it.

I got the output like

```<code><sometext>
</code>```

but I want output only

```<code>sometext
</code>```

In the view, I have used the following code

```<code><div ng-bind-html="description"></div>
</code>```

And in controller

```<code> $scope.description = '<sometext>';
</code>```

答:
Filters are used to modify the data in AngularJS. We can create our own custom filter to remove the HTML tags from a string.

Look at http://www.codeexpertz.com/blog/angularjs/remove-html-tags-angularjs-using-user-defined-filters-example-and-demo for Demo and Sample Code

Filter Code:

```<code>return text ? String(text).replace(/<[^>]+>/gm, '') : '';
</code>```

Body:
I am getting HTML tags in my response, which I want to remove or parse it.

I got the output like

<sometext>

but I want output only

sometext

In the view, I have used the following code

And in controller

 $scope.description = '<sometext>';

Body:
Filters are used to modify the data in AngularJS. We can create our own custom filter to remove the HTML tags from a string.

Look at http://www.codeexpertz.com/blog/angularjs/remove-html-tags-angularjs-using-user-defined-filters-example-and-demo for Demo and Sample Code

Filter Code:

return text ? String(text).replace(/<[^>]+>/gm, '') : '';


问:
Apply regular expressions on a specific column in Pandas
I have a dataset with columns tweetID, tweet-text, RegExp1, RegExp2, RegExp3, RegExp4 and a list of 4 regular expressions.
I want to apply regular expressions one by one on tweet-text column, if tweet-text satisfy the regular expression then I want to set value to 1 in corresponding RegExp column, and if it does not satisfy then I want to set it to 0.

For example, suppose tweet-text satisfy regular expression number 1 then I want to set corresponding RegExp1 columns's value to 1, and does not satisfy regular expression 2 then I want to set corresponding RegExp2 column's value to 0 and so on. I tried the code given at the end, but it didn't worked for me.

My dataset look like

```<code>tweetID | tweet-text         | RegExp1 | RexExp2 | RegExp3 | RexExp4
---------------------------------------------------------------------
10001   | to get it or?      |         |         |         |
10333   | I just wonder :)   |         |         |         |
10933   | is it possible dude|         |         |         |
14633   | he is good at      |         |         |         |
</code>```

code:

```<code> `regexes = [
    re.compile('i asked .* said'),
    re.compile('you asked me what .*'),
    re.compile('(to get|to see|to look|is it true|is it possible) .*'),
    re.compile('I .* wonder .*')
]
for regex, i in zip(regexes, range(4)):
    columnName = "RegExp"+str(i+1)
    for row in df['tweet-text']:
      if(regex.search(row) != None):
        df[columnName] = 1
      else:
        df[columnName] = 0`
</code>```

(use of pandas will be preferred)thanks

答:
You can use str.contains inside a loop. You'll need to pass the regex pattern (not a compiled regex object).

This is what I'm starting with:

```<code>In [1062]: df.head()
Out[1062]:
   tweetID            tweet-text    RegExp1    RegExp2    RegExp3 RegExp4
0    10001   to get it or?
1    10333   I just wonder :)
2    10933   is it possible dude
3    14633   he is good at

In [1063]: regexes = [
      ...:     'i asked .* said',
      ...:     'you asked me what .*',
      ...:     '(?:to get|to see|to look|is it true|is it possible) .*',
      ...:     'I .* wonder .*'
      ...: ]
</code>```

Next, run a loop for each regex pattern. Call str.contains and assign the result to each column in turn:

```<code>In [1090]: for i, r in enumerate(regexes):
      ...:     df['RegExp%d' %(i + 1)] = df['tweet-text'].str.contains(r).astype(int)
      ...:

In [1091]: df.head()
Out[1091]:
   tweetID            tweet-text  RegExp1  RegExp2  RegExp3  RegExp4
0    10001   to get it or?              0        0        1        0
1    10333   I just wonder :)           0        0        0        1
2    10933   is it possible dude        0        0        1        0
3    14633   he is good at              0        0        0        0
</code>```

Body:
I have a dataset with columns tweetID, tweet-text, RegExp1, RegExp2, RegExp3, RegExp4 and a list of 4 regular expressions.
I want to apply regular expressions one by one on tweet-text column, if tweet-text satisfy the regular expression then I want to set value to 1 in corresponding RegExp column, and if it does not satisfy then I want to set it to 0.

For example, suppose tweet-text satisfy regular expression number 1 then I want to set corresponding RegExp1 columns's value to 1, and does not satisfy regular expression 2 then I want to set corresponding RegExp2 column's value to 0 and so on. I tried the code given at the end, but it didn't worked for me.

My dataset look like

tweetID | tweet-text         | RegExp1 | RexExp2 | RegExp3 | RexExp4
---------------------------------------------------------------------
10001   | to get it or?      |         |         |         |
10333   | I just wonder :)   |         |         |         |
10933   | is it possible dude|         |         |         |
14633   | he is good at      |         |         |         |

code:

 `regexes = [
    re.compile('i asked .* said'),
    re.compile('you asked me what .*'),
    re.compile('(to get|to see|to look|is it true|is it possible) .*'),
    re.compile('I .* wonder .*')
]
for regex, i in zip(regexes, range(4)):
    columnName = "RegExp"+str(i+1)
    for row in df['tweet-text']:
      if(regex.search(row) != None):
        df[columnName] = 1
      else:
        df[columnName] = 0`

(use of pandas will be preferred)thanks

Body:
You can use str.contains inside a loop. You'll need to pass the regex pattern (not a compiled regex object).

This is what I'm starting with:

In [1062]: df.head()
Out[1062]:
   tweetID            tweet-text    RegExp1    RegExp2    RegExp3 RegExp4
0    10001   to get it or?
1    10333   I just wonder :)
2    10933   is it possible dude
3    14633   he is good at

In [1063]: regexes = [
      ...:     'i asked .* said',
      ...:     'you asked me what .*',
      ...:     '(?:to get|to see|to look|is it true|is it possible) .*',
      ...:     'I .* wonder .*'
      ...: ]

Next, run a loop for each regex pattern. Call str.contains and assign the result to each column in turn:

In [1090]: for i, r in enumerate(regexes):
      ...:     df['RegExp%d' %(i + 1)] = df['tweet-text'].str.contains(r).astype(int)
      ...:

In [1091]: df.head()
Out[1091]:
   tweetID            tweet-text  RegExp1  RegExp2  RegExp3  RegExp4
0    10001   to get it or?              0        0        1        0
1    10333   I just wonder :)           0        0        0        1
2    10933   is it possible dude        0        0        1        0
3    14633   he is good at              0        0        0        0


问:
Why am I getting NaN when I should be getting a double?
My problem is somewhere in the definition of first_x and second_x. When I call the quad_eq function, I get a -nan(ind) return based on the code below. If I change the .pushback() method parameter to be a literal integer, I get that integer returned instead of NaN. This leads me to believe that the problem is with my calculation/definition of first_x and second_x. Maybe there is some trick to C++ that I am not seeing or understanding. Can anyone see what my problem is? (If this helps I am working out of Bjarne Stroustrup's C++ Principles and Practice Using C++ where he gives me the std_lib_facilities.h file to use as I do not understand headers yet)

```<code>vector<double>quad_eq(double a, double b, double c) {
    vector<double>answers;
    double first_x = (-b + sqrt((b * 2) - (4 * a * c))) / 2 * a;
    double second_x = (-b - sqrt((b * 2) - (4 * a * c))) / 2 * a;
    answers.push_back(first_x);
    answers.push_back(second_x);
    return answers;
}
</code>```

答:
Depending on the input, you are taking the square root of negative numbers, so you get NaN (which is, in fact, a double) out of that, and any other operations propagate that.

Sidenote: the code you show doesn't compile as-is, because it is missing #include <vector> and using namespace std;. The latter is also usually frowned upon.

Body:
My problem is somewhere in the definition of first_x and second_x. When I call the quad_eq function, I get a -nan(ind) return based on the code below. If I change the .pushback() method parameter to be a literal integer, I get that integer returned instead of NaN. This leads me to believe that the problem is with my calculation/definition of first_x and second_x. Maybe there is some trick to C++ that I am not seeing or understanding. Can anyone see what my problem is? (If this helps I am working out of Bjarne Stroustrup's C++ Principles and Practice Using C++ where he gives me the std_lib_facilities.h file to use as I do not understand headers yet)

vector<double>quad_eq(double a, double b, double c) {
    vector<double>answers;
    double first_x = (-b + sqrt((b * 2) - (4 * a * c))) / 2 * a;
    double second_x = (-b - sqrt((b * 2) - (4 * a * c))) / 2 * a;
    answers.push_back(first_x);
    answers.push_back(second_x);
    return answers;
}


问:
My fixed background made scrolling the site very slow, what can I do to improve it?
I changed the background of my discussion forum using the CSS below

http://forum.antinovaordemmundial.com

```<code>html {
    background: url(http://antinovaordemmundial.com/mystuff/logo_blog.jpg) no-repeat center center fixed;
    background-image: url(http://antinovaordemmundial.com/mystuff/logo_blog.jpg);
    background-repeat-x: no-repeat;
    background-repeat-y: no-repeat;
    background-attachment: fixed;
    background-position-x: 50%;
    background-position-y: 50%;
    background-origin: initial;
    background-clip: initial;
    background-color: initial;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}
</code>```

The image is 1600x711 and 88k. The scrolling of the pages are now very slow. Is the CSS problematic or the image should be smaller somehow?

Edit: I tried changing to:

```<code>body {
    color: #000;
    font-family: Verdana, Arial, Sans-Serif;
    font-size: 13px;
    text-align: center; /* IE 5 fix */
    line-height: 1.4;
    background-attachment: fixed;
    background-clip: initial;
    background-color: #51010E;
    background-image: url(http://antinovaordemmundial.com/mystuff/logo_blog.jpg);
    background-origin: initial;
    background-position: initial initial;
    background-repeat: initial initial;
    margin-bottom: 0;
    margin-left: auto;
    margin-right: auto;
    margin-top: 0;
    padding-bottom: 0;
    padding-left: 0;
    padding-right: 0;
    padding-top: 0;
}
</code>```

But it is still very slow on scrolling.

答:
Compressing the image (reducing  the size), solved my issue, I highly recommend using a tool like Radical Image Optimization Tool (RIOT), very effective and easy.

On linux, this can be done using GIMP , you can also remove image's metadata to reduce the size, use tool like exiftool.

Body:
I changed the background of my discussion forum using the CSS below

http://forum.antinovaordemmundial.com

html {
    background: url(http://antinovaordemmundial.com/mystuff/logo_blog.jpg) no-repeat center center fixed;
    background-image: url(http://antinovaordemmundial.com/mystuff/logo_blog.jpg);
    background-repeat-x: no-repeat;
    background-repeat-y: no-repeat;
    background-attachment: fixed;
    background-position-x: 50%;
    background-position-y: 50%;
    background-origin: initial;
    background-clip: initial;
    background-color: initial;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

The image is 1600x711 and 88k. The scrolling of the pages are now very slow. Is the CSS problematic or the image should be smaller somehow?

Edit: I tried changing to:

body {
    color: #000;
    font-family: Verdana, Arial, Sans-Serif;
    font-size: 13px;
    text-align: center; /* IE 5 fix */
    line-height: 1.4;
    background-attachment: fixed;
    background-clip: initial;
    background-color: #51010E;
    background-image: url(http://antinovaordemmundial.com/mystuff/logo_blog.jpg);
    background-origin: initial;
    background-position: initial initial;
    background-repeat: initial initial;
    margin-bottom: 0;
    margin-left: auto;
    margin-right: auto;
    margin-top: 0;
    padding-bottom: 0;
    padding-left: 0;
    padding-right: 0;
    padding-top: 0;
}

But it is still very slow on scrolling.


问:
handle lines in region or not
I have N lines with code like this:

```<code>let aafdafa
let bfaf
let cb
</code>```

I want translate this code to this:

```<code>let aafdafa = aafdafa.len();
let bfaf = bfaf.len();
let cb = cb.len();
</code>```

replace-regexp not work with selection,
how should I solve this task in emacs?

答:
This would be a task for an Emacs Macro: https://www.emacswiki.org/emacs/KeyboardMacros

Macros are built-in powerful features to record and repeat key strokes. You could:

Go to the beginning of the line

Jump one word (to the var) and yank it

Add an =

Paste the var

Add .len();

And then repeat n times.

Title: handle lines in region or not

Body:
I have N lines with code like this:

let aafdafa
let bfaf
let cb

I want translate this code to this:

let aafdafa = aafdafa.len();
let bfaf = bfaf.len();
let cb = cb.len();

replace-regexp not work with selection,
how should I solve this task in emacs?


问:
Update multiple columns in a database using meta keys and meta values
am trying to update multiple fields in a database using their respective meta key but it doesn't work. It works only when I update them one at a time. How do I it to update multiple fields?

Below works:

```<code>$sql = "UPDATE wp_usermeta SET meta_value = '$meta_value' WHERE meta_key = '$meta_key' AND user_id= $user_ID";
</code>```

Below does not work:

```<code>$sql = "UPDATE wp_usermeta SET (meta_value = '$meta_value', meta_key = '$meta_key'), (meta_value = 'The freak I wants', meta_key = 'on_the_weekends_i' WHERE user_id= $user_id)";
</code>```

答:
```<code>UPDATE wp_usermeta SET meta_value = CASE
    WHEN user_id = 1 THEN 329152
    WHEN user_id = 2 THEN 349325
    WHEN user_id = 3 THEN 111592
    ELSE meta_value
    END
WHERE user_id  in (1,2,3)
</code>```

<p>Here is how to do bulk update in MySql </p>

Body:
am trying to update multiple fields in a database using their respective meta key but it doesn't work. It works only when I update them one at a time. How do I it to update multiple fields?

Below works:

$sql = "UPDATE wp_usermeta SET meta_value = '$meta_value' WHERE meta_key = '$meta_key' AND user_id= $user_ID";

Below does not work:

$sql = "UPDATE wp_usermeta SET (meta_value = '$meta_value', meta_key = '$meta_key'), (meta_value = 'The freak I wants', meta_key = 'on_the_weekends_i' WHERE user_id= $user_id)";

Body:
UPDATE wp_usermeta SET meta_value = CASE
    WHEN user_id = 1 THEN 329152
    WHEN user_id = 2 THEN 349325
    WHEN user_id = 3 THEN 111592
    ELSE meta_value
    END
WHERE user_id  in (1,2,3)

Here is how to do bulk update in MySql


问:
How to access UI objects from loaded storyboard view in swift playground?
I have got a storyboard loading in a playground. It works as intended, but now I want to be able add playground code, but don't know how to access the objects in the view from the storyboard. How would I add the @IBOutput and @IBAction in the playground. I have a UILabel called label & a UIButton called button.

Here is the playground code.

```<code>import UIKit
import PlaygroundSupport

let vc = UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController() as! UIViewController

PlaygroundPage.current.liveView = vc
</code>```

playground view screenshot

Thx

答:
One way you could do it, is to set a unique tag for each of your objects.

yourLabel.tag = 10 for example.

Then you could access it with

var myLabel = self.view.viewWithTag(10) as? UILabel

For your button you would do:

```<code>yourButton.tag = 11

var myButton = self.view.viewWithTag(11) as? UIButton

myButton.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)

func buttonAction(_ sender: UIButton){
    print("Button with tag \(sender.tag) tapped")
}
</code>```

This code is untested, but you should be able to get the idea

Good luck

Body:
I have got a storyboard loading in a playground. It works as intended, but now I want to be able add playground code, but don't know how to access the objects in the view from the storyboard. How would I add the @IBOutput and @IBAction in the playground. I have a UILabel called label & a UIButton called button.

Here is the playground code.

import UIKit
import PlaygroundSupport

let vc = UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController() as! UIViewController

PlaygroundPage.current.liveView = vc

playground view screenshot

Thx

Body:
One way you could do it, is to set a unique tag for each of your objects.

yourLabel.tag = 10 for example.

Then you could access it with

var myLabel = self.view.viewWithTag(10) as? UILabel

For your button you would do:

yourButton.tag = 11

var myButton = self.view.viewWithTag(11) as? UIButton

myButton.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)

func buttonAction(_ sender: UIButton){
    print("Button with tag \(sender.tag) tapped")
}

This code is untested, but you should be able to get the idea

Good luck


问:
How to use tf.check_numerics
I am trying to use tf.check_numerics (TensorFlow 1.2) to prevent NaN in my gradients, inspired by this SO post. My code is:

```<code>optimizer = tf.train.RMSPropOptimizer(learning_rate, decay=0.99)
grads_and_vars = optimizer.compute_gradients(graph.loss_total)
grads, variables = zip(*grads_and_vars)
clipped_gradients, _ = (tf.clip_by_global_norm(grads, 1.))

grad_check = tf.check_numerics(clipped_gradients, 'check_numerics caught bad gradients')
     # ^ this line causes an error
with tf.control_dependencies([grad_check]):
    graph.train_op = optimizer.apply_gradients(zip(clipped_gradients, variables))
</code>```

But I get the error message:

```<code>ValueError: Tried to convert 'tensor' to a tensor and failed. Error: Shapes must be equal rank, but are 2 and 1
    From merging shape 2 with other shapes. for 'training/CheckNumerics/packed' (op: 'Pack') with input shapes: [4,16], [16], [16,2], [2].
</code>```

What am I doing wrong, and how do I fix it?

答:
clipped_gradients is a list. Try

```<code>grad_check = tf.check_numerics(clipped_gradients[0], 'check_numerics caught bad gradients')
</code>```

Title: How to use tf.check_numerics

Body:
I am trying to use tf.check_numerics (TensorFlow 1.2) to prevent NaN in my gradients, inspired by this SO post. My code is:

optimizer = tf.train.RMSPropOptimizer(learning_rate, decay=0.99)
grads_and_vars = optimizer.compute_gradients(graph.loss_total)
grads, variables = zip(*grads_and_vars)
clipped_gradients, _ = (tf.clip_by_global_norm(grads, 1.))

grad_check = tf.check_numerics(clipped_gradients, 'check_numerics caught bad gradients')
     # ^ this line causes an error
with tf.control_dependencies([grad_check]):
    graph.train_op = optimizer.apply_gradients(zip(clipped_gradients, variables))

But I get the error message:

ValueError: Tried to convert 'tensor' to a tensor and failed. Error: Shapes must be equal rank, but are 2 and 1
    From merging shape 2 with other shapes. for 'training/CheckNumerics/packed' (op: 'Pack') with input shapes: [4,16], [16], [16,2], [2].

What am I doing wrong, and how do I fix it?

Body:
clipped_gradients is a list. Try

grad_check = tf.check_numerics(clipped_gradients[0], 'check_numerics caught bad gradients')


问:
Access property after inheriting from an abstract class Java
I cannot access a field of a class that is a concrete type inheriting from an abstract class.

In Java I create a class of External student that extends Student

```<code> */
public class ExternalStudent extends Student  {
String currentSchool;

  public ExternalStudent(String name, Integer age, String studentIdentifier, String currentSchool) {
    super(name, age, studentIdentifier);
    this.currentSchool = currentSchool;
  }
}
</code>```

where student is

```<code>public abstract class Student {

    //Attributes
    String studentIdentifier;
    Integer age;
    String name;

    //Associations
    List<Subject> subject =  new ArrayList<Subject>();
    PersonalDetails personaldetails;

    //Methods
    public void setSubject () {
        this.subject.add(new Subject("Name"));
    }

    //Constructors
    public Student(String name, Integer age, String studentIdentifier){
       this.age = age;
       this.name = name;
       this.studentIdentifier = studentIdentifier;
    }
}
</code>```

and external student is set up by my class Application

```<code>public class ApplicationC {
    //Attributes
    private String personalStatement;
    private String applicationForm;

    //Associations
    Registration registration;
    Student student;
    ApplicationTest applicationtest;

    //Methods
    public void setApplicationResult(String result){
        this.applicationtest = new ApplicationTest(result);
    }

    //Constructor
    public ApplicationC (String personalStatement, String name){
        this.registration = new Registration();
        this.student = new ExternalStudent("Tom",16,"78954","DHS");
    }
}
</code>```

I've set up a simple test class

```<code>public void testPostCondition() throws ParseException{
 ApplicationC instance = new ApplicationC("test statement","test name");
    instance.setApplicationResult("pass");
    assertEquals("pass",instance.applicationtest.result);
         instance.student.age = 16;
     instance.student.studentIdentifier = "78954";
     instance.student.name = "Tom";
     instance.student.currentSchool = "test"; //Error as field does not exist
}
</code>```

But I cannot access the current school of the student instance (who must be an externalStudent). How can I access this field in order to test my code?

答:
In ApplicationC, the student field is declared with the Student class :

```<code>Student student;
</code>```

Methods available on an objects relies on the declared type, not the object really instantiated.

And currentSchool is only declared in the subclass ExternalStudent.

So, you cannot access it in this way.

A workaround is  downcasting Student to ExternalStudent :

```<code> ((ExternalStudent)instance.student).studentIdentifier = "78954";
</code>```

And generally, it is better to check the type of the instance before doing it :

```<code> if (instance.student instanceof ExternalStudent){
    ((ExternalStudent)instance.student).studentIdentifier = "78954";
 }
</code>```

As a general advice, in Java, you should favor the private modifier for fields and if you need to manipulate the base class and access to some fields specific to the subclass, you could define a method in the base class that returns null or Optional and override it in the subclass with the return of the field.

It avoids cast that may be error prone and that often are symptoms of a conception problem.

Body:
I cannot access a field of a class that is a concrete type inheriting from an abstract class.

In Java I create a class of External student that extends Student

 */
public class ExternalStudent extends Student  {
String currentSchool;

  public ExternalStudent(String name, Integer age, String studentIdentifier, String currentSchool) {
    super(name, age, studentIdentifier);
    this.currentSchool = currentSchool;
  }
}

where student is

public abstract class Student {

    //Attributes
    String studentIdentifier;
    Integer age;
    String name;

    //Associations
    List<Subject> subject =  new ArrayList<Subject>();
    PersonalDetails personaldetails;

    //Methods
    public void setSubject () {
        this.subject.add(new Subject("Name"));
    }

    //Constructors
    public Student(String name, Integer age, String studentIdentifier){
       this.age = age;
       this.name = name;
       this.studentIdentifier = studentIdentifier;
    }
}

and external student is set up by my class Application

public class ApplicationC {
    //Attributes
    private String personalStatement;
    private String applicationForm;

    //Associations
    Registration registration;
    Student student;
    ApplicationTest applicationtest;

    //Methods
    public void setApplicationResult(String result){
        this.applicationtest = new ApplicationTest(result);
    }

    //Constructor
    public ApplicationC (String personalStatement, String name){
        this.registration = new Registration();
        this.student = new ExternalStudent("Tom",16,"78954","DHS");
    }
}

I've set up a simple test class

public void testPostCondition() throws ParseException{
 ApplicationC instance = new ApplicationC("test statement","test name");
    instance.setApplicationResult("pass");
    assertEquals("pass",instance.applicationtest.result);
         instance.student.age = 16;
     instance.student.studentIdentifier = "78954";
     instance.student.name = "Tom";
     instance.student.currentSchool = "test"; //Error as field does not exist
}

But I cannot access the current school of the student instance (who must be an externalStudent). How can I access this field in order to test my code?

Body:
In ApplicationC, the student field is declared with the Student class :

Student student;

Methods available on an objects relies on the declared type, not the object really instantiated.

And currentSchool is only declared in the subclass ExternalStudent.

So, you cannot access it in this way.

A workaround is  downcasting Student to ExternalStudent :

 ((ExternalStudent)instance.student).studentIdentifier = "78954";

And generally, it is better to check the type of the instance before doing it :

 if (instance.student instanceof ExternalStudent){
    ((ExternalStudent)instance.student).studentIdentifier = "78954";
 }

As a general advice, in Java, you should favor the private modifier for fields and if you need to manipulate the base class and access to some fields specific to the subclass, you could define a method in the base class that returns null or Optional and override it in the subclass with the return of the field.

It avoids cast that may be error prone and that often are symptoms of a conception problem.


问:
Issue with Java SSLSocket
I'm currently working on a client-server project.

I've decided I should use SSL for security reasons.

I tried converting all Socket and ServerSocket objects to their SSL variants, but to no avail.

When I use the SSLServerSocket and connect to it, socket output on the server-side freezes in the middle of outputstream.write(byte[]).

Here are the functions I use to create the SSL Sockets,
ContextController.CONTEXT is the SSLContext and Constants.DEBUG is a fast way for me to toggle SSL:

```<code>public static ServerSocket server(int port, int backlog) throws IOException {
    return Constants.DEBUG ? new ServerSocket(port, backlog) : CONTEXT.getServerSocketFactory().createServerSocket(port, backlog);
}

public static Socket client(InetSocketAddress address) throws IOException {
    return Constants.DEBUG ? new Socket(address.getHostName(), address.getPort())
            : ContextController.CONTEXT.getSocketFactory().createSocket(address.getHostName(), address.getPort());
}

public static Socket client() throws IOException {
    return Constants.DEBUG ? new Socket() : ContextController.CONTEXT.getSocketFactory().createSocket();
}
</code>```

When Constants.DEBUG = true (i.e. SSL is off) it works, but when SSL is on it freezes as stated above after sending some data indefinitely. How can I fix this?

EDIT:

Here is the source of ContextController.CONTEXT:

(note, I know I should use an actual TrustManager but first I want this to work)

```<code>    if (server) {// load the keystore
        try (FileInputStream fis = new FileInputStream(ks)) {
            CONTEXT = SSLContext.getInstance("SSL");

            // load the keystore from the file
            KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            keystore.load(fis, PASSWORD);

            // setup the KeyManagerFactory (used by the server)
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(keystore, PASSWORD);

            CONTEXT.init(kmf.getKeyManagers(), null, null);
        }
        catch (Exception e) {
        }
    }
    else {
        CONTEXT = SSLContext.getInstance("SSL");
        CONTEXT.init(null, new TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } }, null);
    }
</code>```

EDIT 2:

Here is a stacktrace of where it freezes, note it doesn't crash, it hangs:

```<code>Thread [ClientExecThread #0] (Suspended)
owns: AppOutputStream  (id=54)
owns: ByteArrayOutputStream  (id=55)
SocketOutputStream.socketWrite0(FileDescriptor, byte[], int, int) line: not available [native method]
SocketOutputStream.socketWrite(byte[], int, int) line: 111
SocketOutputStream.write(byte[], int, int) line: 155
OutputRecord.writeBuffer(OutputStream, byte[], int, int, int) line: 431
OutputRecord.write(OutputStream, boolean, ByteArrayOutputStream) line: 417
SSLSocketImpl.writeRecordInternal(OutputRecord, boolean) line: 876
SSLSocketImpl.writeRecord(OutputRecord, boolean) line: 847
AppOutputStream.write(byte[], int, int) line: 123
ByteArrayOutputStream.writeTo(OutputStream) line: 167
SocketStream.streamPacket(Packet) line: 181
ClientThread.lambda$8(Group) line: 150
1427646530.run(Object) line: not available
ClientThread.execute() line: 444
ClientThread$ClientExecThread.run() line: 261
</code>```

I've placed a breakpoint the line after SocketStream.streamPacket(Packet) 181 and it never reaches it.

答:
I really don't know why this happened and I don't need all aspects of SSL (only the encryption part, that why I didn't implement the TrustManager) so I decided to implement a Diffie Hellman instead.

This works as intended and combining the DH with AES I have encrypted traffic per my requirements.

Thank you everyone for you help!

Title: Issue with Java SSLSocket

Body:
I'm currently working on a client-server project.

I've decided I should use SSL for security reasons.

I tried converting all Socket and ServerSocket objects to their SSL variants, but to no avail.

When I use the SSLServerSocket and connect to it, socket output on the server-side freezes in the middle of outputstream.write(byte[]).

Here are the functions I use to create the SSL Sockets,
ContextController.CONTEXT is the SSLContext and Constants.DEBUG is a fast way for me to toggle SSL:

public static ServerSocket server(int port, int backlog) throws IOException {
    return Constants.DEBUG ? new ServerSocket(port, backlog) : CONTEXT.getServerSocketFactory().createServerSocket(port, backlog);
}

public static Socket client(InetSocketAddress address) throws IOException {
    return Constants.DEBUG ? new Socket(address.getHostName(), address.getPort())
            : ContextController.CONTEXT.getSocketFactory().createSocket(address.getHostName(), address.getPort());
}

public static Socket client() throws IOException {
    return Constants.DEBUG ? new Socket() : ContextController.CONTEXT.getSocketFactory().createSocket();
}

When Constants.DEBUG = true (i.e. SSL is off) it works, but when SSL is on it freezes as stated above after sending some data indefinitely. How can I fix this?

EDIT:

Here is the source of ContextController.CONTEXT:

(note, I know I should use an actual TrustManager but first I want this to work)

    if (server) {// load the keystore
        try (FileInputStream fis = new FileInputStream(ks)) {
            CONTEXT = SSLContext.getInstance("SSL");

            // load the keystore from the file
            KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            keystore.load(fis, PASSWORD);

            // setup the KeyManagerFactory (used by the server)
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(keystore, PASSWORD);

            CONTEXT.init(kmf.getKeyManagers(), null, null);
        }
        catch (Exception e) {
        }
    }
    else {
        CONTEXT = SSLContext.getInstance("SSL");
        CONTEXT.init(null, new TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } }, null);
    }

EDIT 2:

Here is a stacktrace of where it freezes, note it doesn't crash, it hangs:

Thread [ClientExecThread #0] (Suspended)
owns: AppOutputStream  (id=54)
owns: ByteArrayOutputStream  (id=55)
SocketOutputStream.socketWrite0(FileDescriptor, byte[], int, int) line: not available [native method]
SocketOutputStream.socketWrite(byte[], int, int) line: 111
SocketOutputStream.write(byte[], int, int) line: 155
OutputRecord.writeBuffer(OutputStream, byte[], int, int, int) line: 431
OutputRecord.write(OutputStream, boolean, ByteArrayOutputStream) line: 417
SSLSocketImpl.writeRecordInternal(OutputRecord, boolean) line: 876
SSLSocketImpl.writeRecord(OutputRecord, boolean) line: 847
AppOutputStream.write(byte[], int, int) line: 123
ByteArrayOutputStream.writeTo(OutputStream) line: 167
SocketStream.streamPacket(Packet) line: 181
ClientThread.lambda$8(Group) line: 150
1427646530.run(Object) line: not available
ClientThread.execute() line: 444
ClientThread$ClientExecThread.run() line: 261

I've placed a breakpoint the line after SocketStream.streamPacket(Packet) 181 and it never reaches it.


问:
How do I add my bot to a Telegram channel?
I'm using my bot to tell important news, but when I use sendMessage to the channel I'm receiving the following error:

{"ok":false,"error_code":403,"description":"Error: Forbidden: bot is not a participant of the channel"}
```

In the Change Log they mention it's not possible via the client to send a message to a channel, but then what is the other way to do that?

So, the question is, how to add my bot to the channel?

答:
As of now:

Only the creator of the channel can add a bot.

Other administrators can't add bots to channels.

Channel can be public or private (doesn't matter)

bots can be added only as admins, not members.*

To add the bot to your channel:

click on the channel name:

click on admins:

click on Add Admin:

search for your bot like @your_bot_name, and click add:**

* In some platforms like mac native telegram client it may look like that you can add bot as a member, but at the end it won't work.

** the bot doesn't need to be in your contact list.

Body:
I'm using my bot to tell important news, but when I use sendMessage to the channel I'm receiving the following error:

{"ok":false,"error_code":403,"description":"Error: Forbidden: bot is not a participant of the channel"}

In the Change Log they mention it's not possible via the client to send a message to a channel, but then what is the other way to do that?

So, the question is, how to add my bot to the channel?


问:
How to initialize members in Go struct
I am new to Golang so allocation in it makes me insane:

```<code>import "sync"

type SyncMap struct {
        lock *sync.RWMutex
        hm map[string]string
}
func (m *SyncMap) Put (k, v string) {
        m.lock.Lock()
        defer m.lock.Unlock()

        m.hm[k] = v, true
}
</code>```

and later, I just call:

```<code>sm := new(SyncMap)
sm.Put("Test, "Test")
</code>```

At this moment I get a nil pointer panic.

I've worked around it by using another one function, and calling it right after new():

```<code>func (m *SyncMap) Init() {
        m.hm = make(map[string]string)
        m.lock = new(sync.RWMutex)
}
</code>```

But I wonder, if it's possible to get rid of this boilerplate initializing?

答:
You just need a constructor. A common used pattern is

```<code>func NewSyncMap() *SyncMap {
    return &SyncMap{hm: make(map[string]string)}
}
</code>```

In case of more fields inside your struct, starting a goroutine as backend, or registering a finalizer everything could be done in this constructor.

```<code>func NewSyncMap() *SyncMap {
    sm := SyncMap{
        hm: make(map[string]string),
        foo: "Bar",
    }

    runtime.SetFinalizer(sm, (*SyncMap).stop)

    go sm.backend()

    return &sm
}
</code>```

Title: How to initialize members in Go struct

Body:
I am new to Golang so allocation in it makes me insane:

import "sync"

type SyncMap struct {
        lock *sync.RWMutex
        hm map[string]string
}
func (m *SyncMap) Put (k, v string) {
        m.lock.Lock()
        defer m.lock.Unlock()

        m.hm[k] = v, true
}

and later, I just call:

sm := new(SyncMap)
sm.Put("Test, "Test")

At this moment I get a nil pointer panic.

I've worked around it by using another one function, and calling it right after new():

func (m *SyncMap) Init() {
        m.hm = make(map[string]string)
        m.lock = new(sync.RWMutex)
}

But I wonder, if it's possible to get rid of this boilerplate initializing?

Body:
You just need a constructor. A common used pattern is

func NewSyncMap() *SyncMap {
    return &SyncMap{hm: make(map[string]string)}
}

In case of more fields inside your struct, starting a goroutine as backend, or registering a finalizer everything could be done in this constructor.

func NewSyncMap() *SyncMap {
    sm := SyncMap{
        hm: make(map[string]string),
        foo: "Bar",
    }

    runtime.SetFinalizer(sm, (*SyncMap).stop)

    go sm.backend()

    return &sm
}


问:
How could I determine which AWS location is best for serving customers from a particular region?
AWS has several locations for storage and EC2 instances to run upon with different pricing. How could I determine which location is best for a particular region. Is it intuitive (closer to your serving region is the best) or are there any reliability concerns (particular AWS location facing more outages than others). Is there any data available for making such decision?

I am developing an application that is mainly targeted towards Indian customers. So, I am considering Singapore or Tokyo as an option.

答:
Good tool/site to Check Latency from our location

http://www.cloudwatch.in/


问:
Get the name of folder name after unzip
This my code unzip file and it's working. How get the name of unzip folder name after unzip. Like zip file name is 'demo65856.zip' and unzip folder name is 'demo'.
Thanks</p>

```<code>if(isset($_POST['submit'])){

WP_Filesystem();
$destination = wp_upload_dir();
$normal_path = $path_array;
$filename = $result->theme_file_name;
$link_filename = substr($filename, 0, -4);
$destination_path = $destination['basedir'].'/theme/';
$demo_link = $destination['baseurl'].'/theme/'.$link_filename;
$unzipfile = unzip_file( $destination_path.$filename, $destination_path);

   if ( $unzipfile ) {
    echo '<h3> <a href="'.$demo_link.'">demo link has created</a></h3>';
   } else {
      echo 'There was an error unzipping the file.';
   }
}
</code>```

答:
From the manual, using ZipArchive...

```<code><?php
$zip = new ZipArchive;
if ($zip->open($filename))
{
     for($i = 0; $i < $zip->numFiles; $i++)
     {
          echo 'Filename: ' . $zip->getNameIndex($i) . '<br />';
     }
}
else
{
     echo 'Error reading zip-archive!';
}
?>
</code>```

So it depends on how many files are at the base level, you may just have a base directory or a list of files. You need to try it and see what you get.

Title: Get the name of folder name after unzip

Body:
This my code unzip file and it's working. How get the name of unzip folder name after unzip. Like zip file name is 'demo65856.zip' and unzip folder name is 'demo'.
Thanks

if(isset($_POST['submit'])){

WP_Filesystem();
$destination = wp_upload_dir();
$normal_path = $path_array;
$filename = $result->theme_file_name;
$link_filename = substr($filename, 0, -4);
$destination_path = $destination['basedir'].'/theme/';
$demo_link = $destination['baseurl'].'/theme/'.$link_filename;
$unzipfile = unzip_file( $destination_path.$filename, $destination_path);

   if ( $unzipfile ) {
    echo '
 demo link has created
';
   } else {
      echo 'There was an error unzipping the file.';
   }
}

Body:
From the manual, using ZipArchive...

<?php
$zip = new ZipArchive;
if ($zip->open($filename))
{
     for($i = 0; $i < $zip->numFiles; $i++)
     {
          echo 'Filename: ' . $zip->getNameIndex($i) . '<br />';
     }
}
else
{
     echo 'Error reading zip-archive!';
}
?>

So it depends on how many files are at the base level, you may just have a base directory or a list of files. You need to try it and see what you get.


问:
Using FileSystemObject or the Input # statement to read data from text files
I have to read in some data from text files formated like the example below, with e.g. 5 variables separated by a tab or space delimiter (not fixed-width columns).

```<code>Montreal 0.2 h 3 500
Otherplace 0.1 m 50 25
Thirdplace 0.05 m 62 112
[...]
</code>```

I could read these in using the Input # statement, and that's what I've mostly been doing, because it's the easiest/laziest approach. But:

The Input # statement doesn't always recognize tabs as delimiters.

The whole Input # vernacular has a very "deprecated" feel to it!

I'm thinking about modernizing and reading files using the FileSystemObject methods (already do so for writing files).

But doesn't this requires a lot of string manipulation to parse out my 5 variable values? Any suggestions on how best to do this?

Also, what's a good way of determining how many lines there are in the text file? So I can ReDim my arrays ahead of time.

答:
Instead of INPUT# you could use LINE INPUT#, this will read the whole line.

Determing how many lines there are would be difficult because you're line length is variable. You could however make a educated guess by using : Lines=LOF(Filehandle)/AvarageLineLength
And you can dynamically resize your array by using REDIM PRESERVE

Using Fileobject will only add overhead and dependencies to your program.
The same goes for the Jet driver.
It's not that hard to write a string splitting function ? Search on this site.

Body:
I have to read in some data from text files formated like the example below, with e.g. 5 variables separated by a tab or space delimiter (not fixed-width columns).

Montreal 0.2 h 3 500
Otherplace 0.1 m 50 25
Thirdplace 0.05 m 62 112
[...]

I could read these in using the Input # statement, and that's what I've mostly been doing, because it's the easiest/laziest approach. But:

The Input # statement doesn't always recognize tabs as delimiters.

The whole Input # vernacular has a very "deprecated" feel to it!

I'm thinking about modernizing and reading files using the FileSystemObject methods (already do so for writing files).

But doesn't this requires a lot of string manipulation to parse out my 5 variable values? Any suggestions on how best to do this?

Also, what's a good way of determining how many lines there are in the text file? So I can ReDim my arrays ahead of time.


问:
How to disable class in a particular table column?
i am not sure if this is possible or not.
Anyway i want to disable .sorting class from one column, the class is of bootstrap. Please check the URL image for more.

http://prntscr.com/ftebsr

Thank you.

答:
I think your code is like this

```<code><th><b>#</b> <i class="fa fa-fw fa-sort"></i></th>
</code>```

then you can use css to disable for any column like this(eg:-first column)

```<code>th:nth-child(1) .fa-sort{
  display:none;
}
</code>```

Body:
I think your code is like this

<th><b>#</b> <i class="fa fa-fw fa-sort"></i></th>

then you can use css to disable for any column like this(eg:-first column)

th:nth-child(1) .fa-sort{
  display:none;
}


问:
Replacing strings in a 2d python list
I am reading in a text file as lines and then splitting those lines by white space, giving me a 2d list. Some of the strings in the embedded arrays contain junk that I'm trying to filter out using str.replace, but it's not working.

```<code>import os

infile = 'CMULEX.txt'

data = []
with open(infile, 'r') as f:
    read_data = f.readlines()

    for row in read_data[:5]:
        split_line = (row.split())
        data.append(split_line)

for line in data[:5]:
    for wd in line:
        wd = wd.replace('Coda', '')
</code>```

答:
wd is a local variable. It's not a "pointer" back to the list. A list comprehension seems like an elegant solution here:

```<code>for row in read_data[:5]:
    split_line = (row.split())
    data.append([wd.replace("Coda", "") for wd in split_line])
</code>```

Title: Replacing strings in a 2d python list

Body:
I am reading in a text file as lines and then splitting those lines by white space, giving me a 2d list. Some of the strings in the embedded arrays contain junk that I'm trying to filter out using str.replace, but it's not working.

import os

infile = 'CMULEX.txt'

data = []
with open(infile, 'r') as f:
    read_data = f.readlines()

    for row in read_data[:5]:
        split_line = (row.split())
        data.append(split_line)

for line in data[:5]:
    for wd in line:
        wd = wd.replace('Coda', '')

Body:
wd is a local variable. It's not a "pointer" back to the list. A list comprehension seems like an elegant solution here:

for row in read_data[:5]:
    split_line = (row.split())
    data.append([wd.replace("Coda", "") for wd in split_line])


问:
Pycharm django configuration removed on git pull
I have my Django project repo on github. My problem is whenever I take a pull request ,my Pycharm project configuration gets deleted.</p>

答:
If that pycharm project is versioned in your Git repo, you can try and make sure it remains untouched:

```<code>git update-index --skip-worktree -- yourSetting
</code>```

If that setting is actually multiple files in a folder, you might need:

```<code>find path/to/dir -type f -exec git update-index --skip-worktree '{}' \;
</code>```

Then try again to take a pull request locally.

Body:
If that pycharm project is versioned in your Git repo, you can try and make sure it remains untouched:

git update-index --skip-worktree -- yourSetting

If that setting is actually multiple files in a folder, you might need:

find path/to/dir -type f -exec git update-index --skip-worktree '{}' \;

Then try again to take a pull request locally.


问:
Several instances of a @Singleton OpenEJB bean present
I have a class which looks like this:

```<code>@Singleton
public class MySingletonImpl implements MySingleton{
    @Override
    public void init(){
        ...
    }

    @Override
    public void test(){
        ...
    }

}
</code>```

It is called from the ApplicationComposer testng test which looks like this:

```<code>@Listeners(ApplicationComposerListener.class)
public class MyTest{
     @EJB
     MySingleton mySingleton;

     @Module
     @Classes(cdi=true, value={MySingletonImpl.class})
     public EjbModule ejbModule() throws Exception{
          return new EjbModule(new EjbJar());
     }

     @BeforeClass
     public void setup(){
          mySingleton.init();
     }

     @Test
     public void test(){
          mySigleton.test();
     }
}
</code>```

The problem I observe when the test runs, is that the object id of the instance of MySingletonImpl class that the test() method  called on is not the same as the instance on which the init() method is called.

The behavior seems strange.

First, how my problem can be fixed? I want to init and then call methods on the same object, not different instances of the same class.

Second, why at all would the container instantiate multiple @Singletons?

答:
Is your interface is @Remote or local? If its @Local change it to @Remote:

"EJB specification doesn’t guarantee any behaviour when
    you use the local business interfaces for inter-modules
    communication even if those modules are part of the
    same Application Server / JVM."

https://coderanch.com/mobile/t/608212/java/instances-Singleton-EJB

Body:
I have a class which looks like this:

@Singleton
public class MySingletonImpl implements MySingleton{
    @Override
    public void init(){
        ...
    }

    @Override
    public void test(){
        ...
    }

}

It is called from the ApplicationComposer testng test which looks like this:

@Listeners(ApplicationComposerListener.class)
public class MyTest{
     @EJB
     MySingleton mySingleton;

     @Module
     @Classes(cdi=true, value={MySingletonImpl.class})
     public EjbModule ejbModule() throws Exception{
          return new EjbModule(new EjbJar());
     }

     @BeforeClass
     public void setup(){
          mySingleton.init();
     }

     @Test
     public void test(){
          mySigleton.test();
     }
}

The problem I observe when the test runs, is that the object id of the instance of MySingletonImpl class that the test() method  called on is not the same as the instance on which the init() method is called.

The behavior seems strange.

First, how my problem can be fixed? I want to init and then call methods on the same object, not different instances of the same class.

Second, why at all would the container instantiate multiple @Singletons?


问:
Truth table fun, Java
My program is currently printing out a preprogrammed truth table followed by the correct char at the end of each line. I would like to go above and beyond this program but I've run into a wall, I have never linked the output of a column to a function call in a for loop, and I can't seem to find anything close to it online. Essentially what I want to do is if 0 comes up in the p column I would assign p char 'F', and if a 1 comes up I would assign p char 'T'. My planned code is as follows:

```<code>public static void main(String args[])
{
    char p = 'T';
    char q = 'F';
    char r = 'T';
    int rows = (int) Math.pow(2,3);

    for (int i=0; i<rows; i++) {
        for (int j=3-1; j>=0; j--) {
            System.out.print((i/(int) Math.pow(2, j))%2 + " ");

        }
        System.out.println(LProp(p,q,r));
    }

}
</code>```

Here is my LProp function:

```<code>private static char LProp(char p, char q, char r)
{
    // Logical expression
    //(~q /\r /\~p) \/(~(r \/~p))

    return return ORlogic(ANDlogic(NOTlogic(q),ANDlogic(r,NOTlogic(p))), NOTlogic(ORlogic(r,NOTlogic(p))));
}
</code>```

Is it worth it, or even possible to assign the columns 1 and 0s to my chars?
The output, by the way, is a 4 column table with 8 rows outputting the char T or F in the 4th column.

```<code>p q r LProp(p,q,r)
0 0 0 F
0 0 1 T
</code>```

etc.

答:
You can write a simple helper method to get the correct char value for a given boolean value:

```<code>public static char getCharForBoolean(boolean value)
{
    if (value) {
        return 'T';
    } else {
        return 'F';
    }
}
</code>```

You can optimize this method by writing something like return value ? 'T' : 'F'; if you understand the ? operator.

Use this method in your code where you want the character instead of the boolean value.

```<code>bool result = LProp(p, q, r); // assuming it does return a boolean value
System.out.println(getCharForBoolean(result));
</code>```

Title: Truth table fun, Java

Body:
My program is currently printing out a preprogrammed truth table followed by the correct char at the end of each line. I would like to go above and beyond this program but I've run into a wall, I have never linked the output of a column to a function call in a for loop, and I can't seem to find anything close to it online. Essentially what I want to do is if 0 comes up in the p column I would assign p char 'F', and if a 1 comes up I would assign p char 'T'. My planned code is as follows:

public static void main(String args[])
{
    char p = 'T';
    char q = 'F';
    char r = 'T';
    int rows = (int) Math.pow(2,3);

    for (int i=0; i<rows; i++) {
        for (int j=3-1; j>=0; j--) {
            System.out.print((i/(int) Math.pow(2, j))%2 + " ");

        }
        System.out.println(LProp(p,q,r));
    }

}

Here is my LProp function:

private static char LProp(char p, char q, char r)
{
    // Logical expression
    //(~q /\r /\~p) \/(~(r \/~p))

    return return ORlogic(ANDlogic(NOTlogic(q),ANDlogic(r,NOTlogic(p))), NOTlogic(ORlogic(r,NOTlogic(p))));
}

Is it worth it, or even possible to assign the columns 1 and 0s to my chars?
The output, by the way, is a 4 column table with 8 rows outputting the char T or F in the 4th column.

p q r LProp(p,q,r)
0 0 0 F
0 0 1 T

etc.

Body:
You can write a simple helper method to get the correct char value for a given boolean value:

public static char getCharForBoolean(boolean value)
{
    if (value) {
        return 'T';
    } else {
        return 'F';
    }
}

You can optimize this method by writing something like return value ? 'T' : 'F'; if you understand the ? operator.

Use this method in your code where you want the character instead of the boolean value.

bool result = LProp(p, q, r); // assuming it does return a boolean value
System.out.println(getCharForBoolean(result));


问:
How to call local json file using http get method using angular 2 webpack
I am using angular2 webpack and i want to call local json file using get method but its given me same above error

I tried above solution in my demo cli project its work fine for me but its same in webpack not working

Can any one please help me?

答:
Thanks Meir

You correct but if we using angular-cli but in webpack its not create assets folder its not work in my case.

But after many R&D i found answer is same like above but need to define that folder inside config details and put json file inside that folder in my case like

```<code>config.devServer = {
    contentBase: './src/public',
    historyApiFallback: true,
    quiet: true,
    stats: 'minimal' // none (or false), errors-only, minimal, normal (or true) and verbose
  };
</code>```

So in my case i need to put json file inside public folder.

Its resolve for me.

Body:
Thanks Meir

You correct but if we using angular-cli but in webpack its not create assets folder its not work in my case.

But after many R&D i found answer is same like above but need to define that folder inside config details and put json file inside that folder in my case like

config.devServer = {
    contentBase: './src/public',
    historyApiFallback: true,
    quiet: true,
    stats: 'minimal' // none (or false), errors-only, minimal, normal (or true) and verbose
  };

So in my case i need to put json file inside public folder.

Its resolve for me.


问:
Retrieving an entry from a column and comparing with other entries from the same column
I have a database of employees with salary and names as columns. I want to list all employees who are paid more than a particular person named 'x' from the database itself.

How do I solve this query?

答:
Can you try this:

```<code>Select * from Employees where salary > (select salary from Employees where name = 'Katz' );
</code>```

Little Example

Body:
Can you try this:

Select * from Employees where salary > (select salary from Employees where name = 'Katz' );

Little Example