问:
How to set ticket with AFHTTPSessionOperation or AFHTTPSessionManager?
Does anyone know how to set ticket inside AFHTTPSessionOperation?
This is the previous call using AFNetworking framework 1.0

```<code>NSURLRequest* request = [self.myClient requestWithMethod:@"POST" path:[NSString stringWithFormat:@"%@/%@", controller, action] parameters:parameters];
AFHTTPRequestOperation* operation = [self.myClient HTTPRequestOperationWithRequest:request success:success failure:failure];
[self.mirrorClient enqueueHTTPRequestOperation:operation];
</code>```

The ticket is stored inside the self.myClient. self.myClient.ticket

But I'm not sure how to implement that in the following call using AFHTTPSessionOperation with AFNetworking framework 3.1.

```<code>AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] init];
AFHTTPRequestSerializer <AFURLRequestSerialization> * requestSerializer = manager.requestSerializer;
[requestSerializer  setValue:[NSString stringWithFormat:@"%@", self.myClient.ticket] forHTTPHeaderField:@"Authorization"];

NSOperation *operation = [AFHTTPSessionOperation operationWithManager:manager HTTPMethod:@"POST"
URLString:urlString parameters:parameters
uploadProgress:nil downloadProgress: nil
success:success failure:failure];
</code>```

Thank you

答:
This code looks basically correct. You could simplify the requestSerializer configuration a tad, and I might not instantiate a new session for every request, but the following worked fine for me:

```<code>- (void)performRequest:(NSString *)urlString
            parameters:(id)parameters
               success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success
               failure:(nullable void (^)(NSURLSessionDataTask *task, NSError *error))failure {

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setValue:self.myClient.ticket forHTTPHeaderField:@"Authorization"];

    NSOperation *operation = [AFHTTPSessionOperation operationWithManager:manager
                                                               HTTPMethod:@"POST"
                                                                URLString:urlString
                                                               parameters:parameters
                                                           uploadProgress:nil
                                                         downloadProgress:nil
                                                                  success:success
                                                                  failure:failure];
    [self.queue addOperation:operation];
}
</code>```

I watched it in Charles, and the ticket, 12345678 appeared in my request header, as expected:

I suspect your problem rests elsewhere. This code does set the Authorization header to ticket. Make sure this is the right place to set the ticket. Also, make sure the ticket is what you think it is.

Body:
Does anyone know how to set ticket inside AFHTTPSessionOperation?
This is the previous call using AFNetworking framework 1.0

NSURLRequest* request = [self.myClient requestWithMethod:@"POST" path:[NSString stringWithFormat:@"%@/%@", controller, action] parameters:parameters];
AFHTTPRequestOperation* operation = [self.myClient HTTPRequestOperationWithRequest:request success:success failure:failure];
[self.mirrorClient enqueueHTTPRequestOperation:operation];

The ticket is stored inside the self.myClient. self.myClient.ticket

But I'm not sure how to implement that in the following call using AFHTTPSessionOperation with AFNetworking framework 3.1.

AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] init];
AFHTTPRequestSerializer <AFURLRequestSerialization> * requestSerializer = manager.requestSerializer;
[requestSerializer  setValue:[NSString stringWithFormat:@"%@", self.myClient.ticket] forHTTPHeaderField:@"Authorization"];

NSOperation *operation = [AFHTTPSessionOperation operationWithManager:manager HTTPMethod:@"POST"
URLString:urlString parameters:parameters
uploadProgress:nil downloadProgress: nil
success:success failure:failure];

Thank you

Body:
This code looks basically correct. You could simplify the requestSerializer configuration a tad, and I might not instantiate a new session for every request, but the following worked fine for me:

- (void)performRequest:(NSString *)urlString
            parameters:(id)parameters
               success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success
               failure:(nullable void (^)(NSURLSessionDataTask *task, NSError *error))failure {

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setValue:self.myClient.ticket forHTTPHeaderField:@"Authorization"];

    NSOperation *operation = [AFHTTPSessionOperation operationWithManager:manager
                                                               HTTPMethod:@"POST"
                                                                URLString:urlString
                                                               parameters:parameters
                                                           uploadProgress:nil
                                                         downloadProgress:nil
                                                                  success:success
                                                                  failure:failure];
    [self.queue addOperation:operation];
}

I watched it in Charles, and the ticket, 12345678 appeared in my request header, as expected:

I suspect your problem rests elsewhere. This code does set the Authorization header to ticket. Make sure this is the right place to set the ticket. Also, make sure the ticket is what you think it is.


来源: stackexchange

问:
How to get the sizes of the tables of a MySQL database?
I can run this query to get the sizes of all tables in a MySQL database:

```<code>show table status from myDatabaseName;
</code>```

I would like some help in understanding the results. I am looking for tables with the largest sizes.

Which column should I look at?

答:
Adapted from ChapMic's answer to suite my particular need.

Only specify your database name, then sort all the tables in descending order - from LARGEST to SMALLEST table inside selected database. Needs only 1 variable to be replaced = your database name.

```<code>SELECT
table_name AS `Table`,
round(((data_length + index_length) / 1024 / 1024), 2) AS `size`
FROM information_schema.TABLES
WHERE table_schema = "YOUR_DATABASE_NAME_HERE"
ORDER BY size DESC;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I can run this query to get the sizes of all tables in a MySQL database:

show table status from myDatabaseName;

I would like some help in understanding the results. I am looking for tables with the largest sizes.

Which column should I look at?

Body:
Adapted from ChapMic's answer to suite my particular need.

Only specify your database name, then sort all the tables in descending order - from LARGEST to SMALLEST table inside selected database. Needs only 1 variable to be replaced = your database name.

SELECT
table_name AS `Table`,
round(((data_length + index_length) / 1024 / 1024), 2) AS `size`
FROM information_schema.TABLES
WHERE table_schema = "YOUR_DATABASE_NAME_HERE"
ORDER BY size DESC;

ContentLicense: CC BY-SA 3.0


问:
Nil Coalescing Operator with mixed types
Is there any good concise swifty way to take an optional of a non-String type and get a String value that is either the String interpretation of that value if it is .some() or some default value if it is .none() besides the following:

```<code>let statusCode = (resp as? HTTPURLResponse)?.statusCode
let statusCodeString: String
if let statusCode = statusCode {
    statusCodeString = "\(statusCode)"
} else {
    statusCodeString = "None"
}
</code>```

It just seems awfully verbose for a relatively simple thing, and it feels like I'm missing something obvious.

Just using the nil-coalescing operator doesn't work because you have to provide a default value of the same type.

答:
You can write some thing like this:

```<code>let statusCodeString = statusCode?.description ?? "None"
</code>```

Or if you want to work with some types which does not have the property description:

```<code>let statusCodeString = statusCode.map{String(describing: $0)} ?? "None"
</code>```

Body:
Is there any good concise swifty way to take an optional of a non-String type and get a String value that is either the String interpretation of that value if it is .some() or some default value if it is .none() besides the following:

let statusCode = (resp as? HTTPURLResponse)?.statusCode
let statusCodeString: String
if let statusCode = statusCode {
    statusCodeString = "\(statusCode)"
} else {
    statusCodeString = "None"
}

It just seems awfully verbose for a relatively simple thing, and it feels like I'm missing something obvious.

Just using the nil-coalescing operator doesn't work because you have to provide a default value of the same type.

Body:
You can write some thing like this:

let statusCodeString = statusCode?.description ?? "None"

Or if you want to work with some types which does not have the property description:

let statusCodeString = statusCode.map{String(describing: $0)} ?? "None"


问:
How to print out and load all variables's names and values in Tensorflow
I have two simple functions as below. When I call the sim_train(), I expect the names and the values should be calculated avg_mean and avg_variance. However, the output is like this----all values are 0, although when I print out directly avg_mean and avg_variance and the values are correct.

```<code>SSS/avg_mean:0 [ 0.]
SSS/avg_variance:0 [ 0.]
-2.5 1.25
</code>```

When I call sim_test(), it also shows

```<code>SSS/avg_mean:0 [ 0.]
SSS/avg_variance:0 [ 0.]
</code>```

Is there any way for me to use the correct values in sim_test()? Thank you

```<code>def sim_train():
  x = tf.constant([-1,-2,-3,-4], tf.float32)
  with tf.variable_scope("SSS"):
    avg_mean = tf.get_variable(
        'avg_mean', [1], tf.float32,
        initializer=tf.constant_initializer(0.0, tf.float32))
    avg_variance = tf.get_variable(
        'avg_variance', [1], tf.float32,
        initializer=tf.constant_initializer(0.0, tf.float32))

    avg_mean, avg_variance = tf.nn.moments(x, [0], name='moments')

  sess = tf.InteractiveSession()
  sess.run(tf.global_variables_initializer())

  allVars = tf.global_variables()
  values = sess.run(allVars)

  for var, val in zip(allVars, values):
    print(var.name, val)

  print(avg_mean.eval(), avg_variance.eval())

  saver = tf.train.Saver()
  saver.save(sess, "/tmp/test_EMA/sim_save.ckpt")

def sim_test():
  #saver = tf.train.Saver()
  sess = tf.InteractiveSession()
  saver = tf.train.import_meta_graph('/tmp/test_EMA/sim_save.ckpt.meta')
  saver.restore(sess, "/tmp/test_EMA/sim_save.ckpt")
  allVars = tf.global_variables()
  values = sess.run(allVars)
  for var, val in zip(allVars, values):
    print(var.name, val)
</code>```

答:
This code is not doing what you think is doing.

If you do

```<code>avg_mean = tf.get_variable(
    'avg_mean', [1], tf.float32,
    initializer=tf.constant_initializer(0.0, tf.float32))
print type(avg_mean)
</code>```

the response will be

```<code><class 'tensorflow.python.ops.variables.Variable'>
</code>```

but if you do

```<code>avg_mean, avg_variance = tf.nn.moments(x, [0], name='moments')
type(avg_mean)
</code>```

the response will be

```<code><class 'tensorflow.python.framework.ops.Tensor'>
</code>```

So the saver will go through and save your Variable successfully initialized to 0

To really assign the output of the moments function to the variable you need to use the assign op

for example:

```<code>mean, variance = tf.nn.moments(x, [0], name='moments')
assign_op = avg_mean.assign([mean])
</code>```

then in your session, you need to call sess.run(assign_op) and the value will be successfully stored to the Variable.
Now Saver can save the value and you can restore it for later use.

Body:
I have two simple functions as below. When I call the sim_train(), I expect the names and the values should be calculated avg_mean and avg_variance. However, the output is like this----all values are 0, although when I print out directly avg_mean and avg_variance and the values are correct.

SSS/avg_mean:0 [ 0.]
SSS/avg_variance:0 [ 0.]
-2.5 1.25

When I call sim_test(), it also shows

SSS/avg_mean:0 [ 0.]
SSS/avg_variance:0 [ 0.]

Is there any way for me to use the correct values in sim_test()? Thank you

def sim_train():
  x = tf.constant([-1,-2,-3,-4], tf.float32)
  with tf.variable_scope("SSS"):
    avg_mean = tf.get_variable(
        'avg_mean', [1], tf.float32,
        initializer=tf.constant_initializer(0.0, tf.float32))
    avg_variance = tf.get_variable(
        'avg_variance', [1], tf.float32,
        initializer=tf.constant_initializer(0.0, tf.float32))

    avg_mean, avg_variance = tf.nn.moments(x, [0], name='moments')

  sess = tf.InteractiveSession()
  sess.run(tf.global_variables_initializer())

  allVars = tf.global_variables()
  values = sess.run(allVars)

  for var, val in zip(allVars, values):
    print(var.name, val)

  print(avg_mean.eval(), avg_variance.eval())

  saver = tf.train.Saver()
  saver.save(sess, "/tmp/test_EMA/sim_save.ckpt")

def sim_test():
  #saver = tf.train.Saver()
  sess = tf.InteractiveSession()
  saver = tf.train.import_meta_graph('/tmp/test_EMA/sim_save.ckpt.meta')
  saver.restore(sess, "/tmp/test_EMA/sim_save.ckpt")
  allVars = tf.global_variables()
  values = sess.run(allVars)
  for var, val in zip(allVars, values):
    print(var.name, val)

Body:
This code is not doing what you think is doing.

If you do

avg_mean = tf.get_variable(
    'avg_mean', [1], tf.float32,
    initializer=tf.constant_initializer(0.0, tf.float32))
print type(avg_mean)

the response will be

<class 'tensorflow.python.ops.variables.Variable'>

but if you do

avg_mean, avg_variance = tf.nn.moments(x, [0], name='moments')
type(avg_mean)

the response will be

<class 'tensorflow.python.framework.ops.Tensor'>

So the saver will go through and save your Variable successfully initialized to 0

To really assign the output of the moments function to the variable you need to use the assign op

for example:

mean, variance = tf.nn.moments(x, [0], name='moments')
assign_op = avg_mean.assign([mean])

then in your session, you need to call sess.run(assign_op) and the value will be successfully stored to the Variable.
Now Saver can save the value and you can restore it for later use.


问:
why use Retrofit when we have OkHttp
With OkHttp we can make HTTP request then get response from server:

OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
   .url(url)
   .build();
Response response = client.newCall(request).execute();
```

Then with Gson lib convert response to object we need.

This is from Square/OkHttp doc:

Its request/response API is designed with fluent builders and
immutability. It supports both synchronous blocking calls and async
calls with callbacks

I read from Stackoverflow:

Retrofit uses OkHTTP automatically if available.

So my questions are:

What, exactly, is Retrofit for?

What Retrofit can do that OkHttp cannot?

I think OkHttp and Gson solve the request API problem,
but what problem does retrofit solve for us?

答:
You should use retrofit if you are trying to map your server API inside your application (type-safing). Retrofit is just an API adapter wrapped over okHTTP.

If you want to type safe and modularise the interaction code with your API, use retrofit. Apart from that, the underlying performance, request defaults, etc of okHTTP and Retrofit are the same.

Also I would recommend listening to this podcast from Jesse Wilson (developer of major android HTTP clients), where he talks in-depth of the history of development of Apache HTTP client, HTTPURLConnection, okHTTP and Retrofit.

Title: why use Retrofit when we have OkHttp

Body:
With OkHttp we can make HTTP request then get response from server:

OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
   .url(url)
   .build();
Response response = client.newCall(request).execute();

Then with Gson lib convert response to object we need.

This is from Square/OkHttp doc:

Its request/response API is designed with fluent builders and
immutability. It supports both synchronous blocking calls and async
calls with callbacks

I read from Stackoverflow:

Retrofit uses OkHTTP automatically if available.

So my questions are:

What, exactly, is Retrofit for?

What Retrofit can do that OkHttp cannot?

I think OkHttp and Gson solve the request API problem,
but what problem does retrofit solve for us?


问:
Index 0 of array is undefined after someEmptyArray.push(data)
I am running fs.readdir to return an array of the filenames in a directory. I am running some regex functions to filter out certain  filenames and/or filetypes that I don't want displayed.

With the following code I have returned a new filtered array, but the array's 0 index is returning undefined.

Sorry in advance for the code formatting, I'm on my cell phone and I don't have access to a computer with internet.

```<code>fs.readdir('./schema', function(err,files){
  var filelist = [];
  if(err)
    throw err;
  else{
    var index = files.length;
    while(index>0){
      filelist.push(isNOTswapfile(files[index]));
      index--;
      }
    console.log(filelist)
    }
  }
)
</code>```

This returns `[undefined, 'file_1.js']
Why is this happening and how do I get rid of it?

Thanks

答:
files[index] the first time is undefined since the length of an array will always be greater than the biggest index (zero based indexes). Move index-- one line up, and it will work, however you'll be leaving out the first element, so compare to >=0 or index-1 to get all elements.

```<code>fs.readdir('./schema', function(err, files) {
    var filelist = [];
    if (err) {
        throw err;
    } else {
        var index = files.length;
        while (index >= 0) {
            index--;
            filelist.push(isNOTswapfile(files[index]));
        }
        console.log(filelist)
    }
})
</code>```

Body:
I am running fs.readdir to return an array of the filenames in a directory. I am running some regex functions to filter out certain  filenames and/or filetypes that I don't want displayed.

With the following code I have returned a new filtered array, but the array's 0 index is returning undefined.

Sorry in advance for the code formatting, I'm on my cell phone and I don't have access to a computer with internet.

fs.readdir('./schema', function(err,files){
  var filelist = [];
  if(err)
    throw err;
  else{
    var index = files.length;
    while(index>0){
      filelist.push(isNOTswapfile(files[index]));
      index--;
      }
    console.log(filelist)
    }
  }
)

This returns `[undefined, 'file_1.js']
Why is this happening and how do I get rid of it?

Thanks

Body:
files[index] the first time is undefined since the length of an array will always be greater than the biggest index (zero based indexes). Move index-- one line up, and it will work, however you'll be leaving out the first element, so compare to >=0 or index-1 to get all elements.

fs.readdir('./schema', function(err, files) {
    var filelist = [];
    if (err) {
        throw err;
    } else {
        var index = files.length;
        while (index >= 0) {
            index--;
            filelist.push(isNOTswapfile(files[index]));
        }
        console.log(filelist)
    }
})


问:
How to access NgFormControl in custom Ng2 form element
I wrote my own custom form element DateInputComponent by implementing ControlValueAccessor and use it like this:

```<code><my-date-input ngControl="date"></my-date-input>
</code>```

From what I understand, ngControl is syntactic sugar for [ngFormControl]="myControlGroup.controls['date']".

Now, inside my DateInputComponent I would like to access the NgFormControl.

I tried to bind it with @Input NgFormControl ngFormControl; but it never gets set, and I tried injecting it with DateInputComponent(NgFormControl ngFormControl) but that fails because there is no provider.

What is the correct approach to get it?

(Maybe I'm also approaching it the wrong way... I'd like for this DateInputComponent to be able to display all validation errors by itself that might occur.)

答:
You are on the right approach with injecting the directive, but the problem is while ngControl could be considered syntactic sugar for NgFormControl it isn't the same class.

All of the form controls extend from NgControl and this is what you should be injecting into your component. DateInputComponent(NgControl ngControl)

All the form directives are meant to work interchangeably so they all provide NgControl as the interface they are exposing. This allows the user of your date component to use whatever directive works for their use case:

NgModel: if they just want provide or listen to the value

NgFormControl: if they want to provide the control

NgControlName: if they want to use the string identifier into the ControlMap (This is the one you are using above)

Body:
I wrote my own custom form element DateInputComponent by implementing ControlValueAccessor and use it like this:

<my-date-input ngControl="date"></my-date-input>

From what I understand, ngControl is syntactic sugar for [ngFormControl]="myControlGroup.controls['date']".

Now, inside my DateInputComponent I would like to access the NgFormControl.

I tried to bind it with @Input NgFormControl ngFormControl; but it never gets set, and I tried injecting it with DateInputComponent(NgFormControl ngFormControl) but that fails because there is no provider.

What is the correct approach to get it?

(Maybe I'm also approaching it the wrong way... I'd like for this DateInputComponent to be able to display all validation errors by itself that might occur.)


问:
Looking for duplicates in arrays inside arrays (multi-dimensional array)
I've gotten into a bit of a jam and was wondering if someone could clear it up.
What I want to do is:

Opening a bunch of data containing .txt files

Creating a multidimensional array that holds @array[@filenames][@data]

Find which files are duplicates of eachother in terms of data

Here I slurp a file into a variable, use regex to obtain my data and put it into an array:

```<code>    while (my $row = <$fh>) {
        unless ($. == 0) {
            {
            local $/; # enable slurp
            @datalist = <$fh> =~ /\s*\d*\/\s*\d*\|\s*(.*?)\|.*?(?:.*?\|){4}\s*(\S*)\|(\S*).*\|/g; #extract article numbers # $1 = article number, $2 = quantity, $3 = unit
            }
            push(@arrayofarrays,[@datalist]);
            push(@filenames,$file);
            last;
            }
        }
        $numr++;
}
open(my $feh,">","test.txt");
print {$feh} Dumper \@arrayofarrays;
</code>```

A Dumper shows that my data looks fine (pseudoresults to make it easy to read and short):

```<code>$VAR1 = [
          [
            'data type1',
            'data type2',
            'data type3',
            'data type1',
            'data type2',
            'data type3',
            ...
          ],
          [
            'data type1',
            'data type2',
            'data type3',
            ...
          ],
        ...
     ];
</code>```

So I'm wondering if anyone knows an easy way to check for duplicates between sets of data? I know I can print individual data sets using

What I tried might give a better idea as to what I need to do:

```<code>my $i = 0;
my $j = 0;
while ( $i <= scalar @arrayofarrays) {
    $j = 0;
    while ( $j <= scalar @arrayofarrays) {
        if (@{$arrayofarrays[$i]} eq @{$arrayofarrays[$j]}) {
            print "\n'$filenames[$i]' is duplicate to '$filenames[$j]'.";
            } $j++;
        } $i++;
    }
</code>```

答:
Instead of array of arrays I'd create a hash of arrays, producing keys from subarrays' data by flattening subarrays to strings optionally turning them to checksums (this would be appropriate for multidimensional subarrays). You may want to read this discussion on PerlMonks:

http://www.perlmonks.org/?node_id=1121378

The abstract example given an already existing array with duplicate data in subarrays (you may test it here on ideone.com):

```<code>#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my @array = (
    [1,'John','ABXC12132328'],
    [0,'John','ABXC12132322'],
    [0,'John','ABXC12132322'],
    [0,'John','ABXC12132322'],
    [0,'John','ABXC12132322'],
    [0,'John','ABXC12132322'],
    [0,'John','ABXC12132322'],
    [0,'John','ABXC12132322'],
    [0,'John','ABXC12132322'],
    [0,'John','ABXC12132322'],
    [0,'John','ABXC12132322'],
    [0,'John','ABXC12132322'],
    [0,'John','ABXC12132322'],
    [0,'John','ABXC12132322'],
    [0,'John','ABXC12132322']
);
my %uniq_helper = ();
my @uniq_data = grep { !$uniq_helper{"@$_"}++ } @array;
print Dumper(\%uniq_helper) . "\n";
print Dumper(\@uniq_data) . "\n";
</code>```

For your case it will probably look like this:

```<code>my %datalist;
while (my $row = <$fh>) {
    unless ($. == 0) {
        {
            local $/; # enable slurp
            @data = <$fh> =~ /\s*\d*\/\s*\d*\|\s*(.*?)\|.*?(?:.*?\|){4}\s*(\S*)\|(\S*).*\|/g; #extract article numbers # $1 = article number, $2 = quantity, $3 = unit
        }
        $datalist{"@data"} = \@data;
        push(@filenames,$file);
        last;
    }
}
$numr++;
</code>```

Body:
I've gotten into a bit of a jam and was wondering if someone could clear it up.
What I want to do is:

Opening a bunch of data containing .txt files

Creating a multidimensional array that holds @array[@filenames][@data]

Find which files are duplicates of eachother in terms of data

Here I slurp a file into a variable, use regex to obtain my data and put it into an array:

    while (my $row = <$fh>) {
        unless ($. == 0) {
            {
            local $/; # enable slurp
            @datalist = <$fh> =~ /\s*\d*\/\s*\d*\|\s*(.*?)\|.*?(?:.*?\|){4}\s*(\S*)\|(\S*).*\|/g; #extract article numbers # $1 = article number, $2 = quantity, $3 = unit
            }
            push(@arrayofarrays,[@datalist]);
            push(@filenames,$file);
            last;
            }
        }
        $numr++;
}
open(my $feh,">","test.txt");
print {$feh} Dumper \@arrayofarrays;

A Dumper shows that my data looks fine (pseudoresults to make it easy to read and short):

$VAR1 = [
          [
            'data type1',
            'data type2',
            'data type3',
            'data type1',
            'data type2',
            'data type3',
            ...
          ],
          [
            'data type1',
            'data type2',
            'data type3',
            ...
          ],
        ...
     ];

So I'm wondering if anyone knows an easy way to check for duplicates between sets of data? I know I can print individual data sets using

What I tried might give a better idea as to what I need to do:

my $i = 0;
my $j = 0;
while ( $i <= scalar @arrayofarrays) {
    $j = 0;
    while ( $j <= scalar @arrayofarrays) {
        if (@{$arrayofarrays[$i]} eq @{$arrayofarrays[$j]}) {
            print "\n'$filenames[$i]' is duplicate to '$filenames[$j]'.";
            } $j++;
        } $i++;
    }

Body:
Instead of array of arrays I'd create a hash of arrays, producing keys from subarrays' data by flattening subarrays to strings optionally turning them to checksums (this would be appropriate for multidimensional subarrays). You may want to read this discussion on PerlMonks:

http://www.perlmonks.org/?node_id=1121378

The abstract example given an already existing array with duplicate data in subarrays (you may test it here on ideone.com):

#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my @array = (
    [1,'John','ABXC12132328'],
    [0,'John','ABXC12132322'],
    [0,'John','ABXC12132322'],
    [0,'John','ABXC12132322'],
    [0,'John','ABXC12132322'],
    [0,'John','ABXC12132322'],
    [0,'John','ABXC12132322'],
    [0,'John','ABXC12132322'],
    [0,'John','ABXC12132322'],
    [0,'John','ABXC12132322'],
    [0,'John','ABXC12132322'],
    [0,'John','ABXC12132322'],
    [0,'John','ABXC12132322'],
    [0,'John','ABXC12132322'],
    [0,'John','ABXC12132322']
);
my %uniq_helper = ();
my @uniq_data = grep { !$uniq_helper{"@$_"}++ } @array;
print Dumper(\%uniq_helper) . "\n";
print Dumper(\@uniq_data) . "\n";

For your case it will probably look like this:

my %datalist;
while (my $row = <$fh>) {
    unless ($. == 0) {
        {
            local $/; # enable slurp
            @data = <$fh> =~ /\s*\d*\/\s*\d*\|\s*(.*?)\|.*?(?:.*?\|){4}\s*(\S*)\|(\S*).*\|/g; #extract article numbers # $1 = article number, $2 = quantity, $3 = unit
        }
        $datalist{"@data"} = \@data;
        push(@filenames,$file);
        last;
    }
}
$numr++;


问:
Finding direct child of an element
I'm writing a solution to test this phenomenon in Python. I have most of the logic done, but there are many edge cases that arise when following links in Wikipedia articles.

The problem I'm running into arises for a page like this where the first
 has multiple levels of child elements and the first  tag after the first set of parentheses needs to be extracted. In this case, (to extract this link), you have to skip over the parentheses, and then get to the very next anchor tag/href. In most articles, my algorithm can skip over the parentheses, but with the way that it looks for links in front of parentheses (or if they don't exist), it is finding the anchor tag in the wrong place. Specifically, here: Coordinates

The algorithm works by iterating through the elements in the first paragraph tag (in the main body of the article), stringifying each element iteratively, and first checking to see if it contains either an '(' or an '

Is there any straight forward way to avoid embedded anchor tags and only take the first link that is a direct child of the first
 ?

Below is the function with this code for reference:

```<code>**def getValidLink(self, currResponse):
        currRoot = BeautifulSoup(currResponse.text,"lxml")
        temp = currRoot.body.findAll('p')[0]
        parenOpened = False
        parenCompleted = False
        openCount = 0
        foundParen = False
        while temp.next:
            temp = temp.next
            curr = str(temp)
            if '(' in curr and str(type(temp)) == "<class 'bs4.element.NavigableString'>":
                foundParen = True
                break
            if '<a' in curr and str(type(temp)) == "<class 'bs4.element.Tag'>":
                link = temp
                break

        temp = currRoot.body.findAll('p')[0]
        if foundParen:
            while temp.next and not parenCompleted:
                temp = temp.next
                curr = str(temp)
                if '(' in curr:
                    openCount += 1
                    if parenOpened is False:
                        parenOpened = True
                if ')' in curr and parenOpened and openCount > 1:
                    openCount -= 1
                elif ')' in curr and parenOpened and openCount == 1:
                    parenCompleted = True
            try:
                return temp.findNext('a').attrs['href']
            except KeyError:
                print "\nReached article with no main body!\n"
                return None
        try:
            return str(link.attrs['href'])
        except KeyError:
            print "\nReached article with no main body\n"
            return None**
</code>```

答:
I think you are seriously overcomplicating the problem.

There are multiple ways to use the direct parent-child relationship between the elements in BeautifulSoup. One way is the > CSS selector:

```<code>In [1]: import requests

In [2]: from bs4 import BeautifulSoup

In [3]: url = "https://en.wikipedia.org/wiki/Sierra_Leone"

In [4]: response = requests.get(url)

In [5]: soup = BeautifulSoup(response.content, "html.parser")

In [6]: [a.get_text() for a in soup.select("#mw-content-text > p > a")]
Out[6]:
['West Africa',
 'Guinea',
 'Liberia',
 ...
 'Allen Iverson',
 'Magic Johnson',
 'Victor Oladipo',
 'Frances Tiafoe']
</code>```

Here we've found a elements that are located directly under the p elements directly under the element with id="mw-content-text" - from what I understand this is where the main Wikipedia article is located in.

If you need a single element, use select_one() instead of select().

Also, if you want to solve it via find*(), pass the recursive=False argument.

Title: Finding direct child of an element

Body:
I'm writing a solution to test this phenomenon in Python. I have most of the logic done, but there are many edge cases that arise when following links in Wikipedia articles.

The problem I'm running into arises for a page like this where the first
 has multiple levels of child elements and the first  tag after the first set of parentheses needs to be extracted. In this case, (to extract this link), you have to skip over the parentheses, and then get to the very next anchor tag/href. In most articles, my algorithm can skip over the parentheses, but with the way that it looks for links in front of parentheses (or if they don't exist), it is finding the anchor tag in the wrong place. Specifically, here: Coordinates

The algorithm works by iterating through the elements in the first paragraph tag (in the main body of the article), stringifying each element iteratively, and first checking to see if it contains either an '(' or an '

Is there any straight forward way to avoid embedded anchor tags and only take the first link that is a direct child of the first
 ?

Below is the function with this code for reference:

**def getValidLink(self, currResponse):
        currRoot = BeautifulSoup(currResponse.text,"lxml")
        temp = currRoot.body.findAll('p')[0]
        parenOpened = False
        parenCompleted = False
        openCount = 0
        foundParen = False
        while temp.next:
            temp = temp.next
            curr = str(temp)
            if '(' in curr and str(type(temp)) == "<class 'bs4.element.NavigableString'>":
                foundParen = True
                break
            if '<a' in curr and str(type(temp)) == "<class 'bs4.element.Tag'>":
                link = temp
                break

        temp = currRoot.body.findAll('p')[0]
        if foundParen:
            while temp.next and not parenCompleted:
                temp = temp.next
                curr = str(temp)
                if '(' in curr:
                    openCount += 1
                    if parenOpened is False:
                        parenOpened = True
                if ')' in curr and parenOpened and openCount > 1:
                    openCount -= 1
                elif ')' in curr and parenOpened and openCount == 1:
                    parenCompleted = True
            try:
                return temp.findNext('a').attrs['href']
            except KeyError:
                print "\nReached article with no main body!\n"
                return None
        try:
            return str(link.attrs['href'])
        except KeyError:
            print "\nReached article with no main body\n"
            return None**

Body:
I think you are seriously overcomplicating the problem.

There are multiple ways to use the direct parent-child relationship between the elements in BeautifulSoup. One way is the > CSS selector:

In [1]: import requests

In [2]: from bs4 import BeautifulSoup

In [3]: url = "https://en.wikipedia.org/wiki/Sierra_Leone"

In [4]: response = requests.get(url)

In [5]: soup = BeautifulSoup(response.content, "html.parser")

In [6]: [a.get_text() for a in soup.select("#mw-content-text > p > a")]
Out[6]:
['West Africa',
 'Guinea',
 'Liberia',
 ...
 'Allen Iverson',
 'Magic Johnson',
 'Victor Oladipo',
 'Frances Tiafoe']

Here we've found a elements that are located directly under the p elements directly under the element with id="mw-content-text" - from what I understand this is where the main Wikipedia article is located in.

If you need a single element, use select_one() instead of select().

Also, if you want to solve it via find*(), pass the recursive=False argument.


问:
Can I change size of fedex label pdf?
I've created label using fedex API.

and I save that PDF Image into AWS. Below is url.

https://s3-ap-northeast-2.amazonaws.com/gmp01/temp/tmp-137164OTxA4P5MVJ1.pdf

This label has 4X6 size. but you can see pdf size is A4 in that link.

I've tried to find How can I remove this white space but I can't find in Fedex API Document.

If you have had this similar issue, please help me.

I am using Angular.js 1.x and Node.js

答:
We get the 4x6 PDF label for FedEx and trim the white space by getting the PNG file first. Below you can find the parameter.

LabelFormatType = COMMON2D

ImageType = PNG

LabelStockType = PAPER_4X6

If you want to save time, you can use RESTful shipping API like Postmen which simplifies the API request for label generation.

Title: Can I change size of fedex label pdf?


问:
How to search multiple text box from database
How can I search multiple text boxes from a database using ASP.Net?    </p>

```<code>protected void SearchButton_Click(object sender, EventArgs e)
        {if (RefNo.Text == "@search")
            {
              string str = "Select [ITEM No#], [Company Name], [Discipline Required], [Service Description], Institution, [Award Date] from PSP_Report where ([ITEM NO#] like '%' + @search + '%')";
                SqlCommand xp = new SqlCommand(str, con);
                xp.Parameters.Add("@search", SqlDbType.NVarChar).Value = RefNo.Text;
                con.Open();
                xp.ExecuteNonQuery();
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = xp;
                DataSet ds = new DataSet();
                da.Fill(ds, "ITEM No#");
                Search.DataSource = ds;
                Search.DataBind();
                con.Close();
            }
            else if (CompanyName.Text == "@searche")
            {
                string str = "Select [ITEM No#], [Company Name], [Discipline Required], [Service Description], Institution, [Award Date] from PSP_Report where ([Company Name] like '%' + @searche + '%')";
                SqlCommand xp = new SqlCommand(str, con);
                xp.Parameters.Add("@search", SqlDbType.NVarChar).Value = RefNo.Text;
                con.Open();
                xp.ExecuteNonQuery();
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = xp;
                DataSet ds = new DataSet();
                da.Fill(ds, "Company Name");
                Search.DataSource = ds;
                Search.DataBind();
                con.Close();
            }
        }
    }
</code>```

答:
Based on my understanding, I assume you have multiple text boxes on your search GUI, and you want to dynamically build a select statement based on user input.

one way to do is something like below. After you are sure the select is what you want then have a method to execute your query with your constructed select.

```<code>protected void SearchButton_Click(object sender, EventArgs e)
    {
        string str = "Select [ITEM No#], [Company Name], [Discipline Required], [Service Description], Institution, [Award Date] from PSP_Report where 1=1 ";

        if (!string.IsNullOrWhiteSpace(RefNo.Text))
        {
            str += $" and ([ITEM NO#] like '%'{RefNo.Text}'%')";
        }
        if (!string.IsNullOrWhiteSpace(CompanyName.Text))
        {
            str += $" and ([Company Name] like '%'{CompanyName.Text}'%')";
        }
</code>```

PS:

Be aware about SQL injection.

I wouldn't use # or space on column names.

Body:
How can I search multiple text boxes from a database using ASP.Net?

protected void SearchButton_Click(object sender, EventArgs e)
        {if (RefNo.Text == "@search")
            {
              string str = "Select [ITEM No#], [Company Name], [Discipline Required], [Service Description], Institution, [Award Date] from PSP_Report where ([ITEM NO#] like '%' + @search + '%')";
                SqlCommand xp = new SqlCommand(str, con);
                xp.Parameters.Add("@search", SqlDbType.NVarChar).Value = RefNo.Text;
                con.Open();
                xp.ExecuteNonQuery();
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = xp;
                DataSet ds = new DataSet();
                da.Fill(ds, "ITEM No#");
                Search.DataSource = ds;
                Search.DataBind();
                con.Close();
            }
            else if (CompanyName.Text == "@searche")
            {
                string str = "Select [ITEM No#], [Company Name], [Discipline Required], [Service Description], Institution, [Award Date] from PSP_Report where ([Company Name] like '%' + @searche + '%')";
                SqlCommand xp = new SqlCommand(str, con);
                xp.Parameters.Add("@search", SqlDbType.NVarChar).Value = RefNo.Text;
                con.Open();
                xp.ExecuteNonQuery();
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = xp;
                DataSet ds = new DataSet();
                da.Fill(ds, "Company Name");
                Search.DataSource = ds;
                Search.DataBind();
                con.Close();
            }
        }
    }

Body:
Based on my understanding, I assume you have multiple text boxes on your search GUI, and you want to dynamically build a select statement based on user input.

one way to do is something like below. After you are sure the select is what you want then have a method to execute your query with your constructed select.

protected void SearchButton_Click(object sender, EventArgs e)
    {
        string str = "Select [ITEM No#], [Company Name], [Discipline Required], [Service Description], Institution, [Award Date] from PSP_Report where 1=1 ";

        if (!string.IsNullOrWhiteSpace(RefNo.Text))
        {
            str += $" and ([ITEM NO#] like '%'{RefNo.Text}'%')";
        }
        if (!string.IsNullOrWhiteSpace(CompanyName.Text))
        {
            str += $" and ([Company Name] like '%'{CompanyName.Text}'%')";
        }

PS:

Be aware about SQL injection.

I wouldn't use # or space on column names.


问:
Excel VBA - Bitcoin
I'm trying to run this macro on Microsoft Excel, but every time I do, I get a

Run-time error '5'

What am I doing wrong?
This is my first time doing something like this.

What's suppose to happen is that everytime I run the Keyboard Shortcut, it's suppose to get the data from the blockchain website.

It's essentially just code that says..

1 USD is worth this many BTC

```<code>Sub USD_to_BTC()
'
' USD_to_BTC Macro
' Get the price of 1 btc if purchased by 1 USD
'
' Keyboard Shortcut: Ctrl+Shift+B
'
    With ActiveSheet.QueryTables.Add(Connection:= _
        "URL;https://blockchain.info/tobtc?currency=USD&value=1", Destination:=Range( _
        "$D$8"))
        .CommandType = 0
        .Name = "tobtc?currency=USD&value=1_1"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .BackgroundQuery = True
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .WebSelectionType = xlAllTables
        .WebFormatting = xlWebFormattingNone
        .WebPreFormattedTextToColumns = True
        .WebConsecutiveDelimitersAsOne = True
        .WebSingleBlockTextImport = False
        .WebDisableDateRecognition = False
        .WebDisableRedirections = False
        .Refresh BackgroundQuery:=False
    End With
End Sub
</code>```

答:
Try to use XHR instead of QueryTable:

Sub USD_to_BTC()

    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", "https://blockchain.info/tobtc?currency=USD&value=1", False
        .Send
        Range("D8").Value = .responseText
    End With

End Sub
```

Title: Excel VBA - Bitcoin

Body:
I'm trying to run this macro on Microsoft Excel, but every time I do, I get a

Run-time error '5'

What am I doing wrong?
This is my first time doing something like this.

What's suppose to happen is that everytime I run the Keyboard Shortcut, it's suppose to get the data from the blockchain website.

It's essentially just code that says..

1 USD is worth this many BTC

Sub USD_to_BTC()
'
' USD_to_BTC Macro
' Get the price of 1 btc if purchased by 1 USD
'
' Keyboard Shortcut: Ctrl+Shift+B
'
    With ActiveSheet.QueryTables.Add(Connection:= _
        "URL;https://blockchain.info/tobtc?currency=USD&value=1", Destination:=Range( _
        "$D$8"))
        .CommandType = 0
        .Name = "tobtc?currency=USD&value=1_1"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .BackgroundQuery = True
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .WebSelectionType = xlAllTables
        .WebFormatting = xlWebFormattingNone
        .WebPreFormattedTextToColumns = True
        .WebConsecutiveDelimitersAsOne = True
        .WebSingleBlockTextImport = False
        .WebDisableDateRecognition = False
        .WebDisableRedirections = False
        .Refresh BackgroundQuery:=False
    End With
End Sub


问:
Partitioning in spark while reading from RDBMS via JDBC
I am running spark in cluster mode and reading data from RDBMS via JDBC.

As per Spark docs, these partitioning parameters describe how to partition the table when reading in parallel from multiple workers:

partitionColumn

lowerBound

upperBound

numPartitions

These are optional parameters.

What would happen if I don't specify these:

Only 1 worker read the whole data?

If it still reads parallelly, how does it partition data?

答:
If you don't specify either {partitionColumn, lowerBound, upperBound, numPartitions} or {predicates} Spark will use a single executor and create a single non-empty partition. All data will be processed using a single transaction and reads will be neither distributed nor parallelized.

See also:

How to optimize partitioning when migrating data from JDBC source?

How to improve performance for slow Spark jobs using DataFrame and JDBC connection?


问:
Prevent column change without the other
No-one should be allowed to update the customer address column unless the postcode column is also updated. If an attempt is made to update one without the other, then a trigger will fire and the user will be shown an error message.

Any help on how I can do this in Microsoft SQL Server 2012 will be appreciated!

答:
You can use below logic

```<code>CREATE TRIGGER [dbo].AU_MyTrigger ON [dbo].MyTable
FOR  UPDATE
AS
BEGIN
    declare @bu_addr varchar(100)
    declare @bu_zip varchar(100)
    declare @au_addr varchar(100)
    declare @au_zip varchar(100)

    select @bu_addr = addr, @bu_zip = zip from DELETED
    select @au_addr = addr, @ay_zip = zip from INSERTED
    if (@bu_addr <> @au_addr) and (@bu_zip = @au_zip)
    BEGIN
        -- update table with old values
        -- raise error
    END
END
</code>```

Note that if this update can happen in batch, you need to loop through each record and update their value to old and only return error at the end of trigger (outside of loop). In that case, for iterating on updated rows, you need to use CURSOR

You case might not be as easy as I explained, but this is the approach that works.

Title: Prevent column change without the other

Body:
You can use below logic

CREATE TRIGGER [dbo].AU_MyTrigger ON [dbo].MyTable
FOR  UPDATE
AS
BEGIN
    declare @bu_addr varchar(100)
    declare @bu_zip varchar(100)
    declare @au_addr varchar(100)
    declare @au_zip varchar(100)

    select @bu_addr = addr, @bu_zip = zip from DELETED
    select @au_addr = addr, @ay_zip = zip from INSERTED
    if (@bu_addr <> @au_addr) and (@bu_zip = @au_zip)
    BEGIN
        -- update table with old values
        -- raise error
    END
END

Note that if this update can happen in batch, you need to loop through each record and update their value to old and only return error at the end of trigger (outside of loop). In that case, for iterating on updated rows, you need to use CURSOR

You case might not be as easy as I explained, but this is the approach that works.


问:
Python: Find URLs and add querystring pair
I'm trying to affilliateize some legacy text in a Django webapp. It's a pretty simple scope. The text has some amazon URLs in and I want to munge my ?tag=xxx identifier onto the end of them.

I've written a template filter that I can quickly pass my text through but I'm slightly stuck on writing the regex logic.

```<code>t = text_from_template_engine
return re.sub(r'(https?://(?:www\.)?amazon\.co\.uk[\S]+)', r'\\\1?tag=xxx', t)
</code>```

This seems to work on a very basic level but if the URL already has a querystring (as lots of organic Amazon URLs do by default), I would need an ampersand instead of a question mark.

There might be a quick way to detect two question marks and replace the second. I'm open to that suggestion.

What I'm really looking for is a regex-replace where I can pass the found string off to another method (in which I can detect existing question marks) that is expected to return the replacement string. Something like PHP's preg_replace_callback (et al). Does that exist?

答: Yes, the second parameter to re.sub can be a function, which takes a match object and returns a string. See the documentation.

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to affilliateize some legacy text in a Django webapp. It's a pretty simple scope. The text has some amazon URLs in and I want to munge my ?tag=xxx identifier onto the end of them.

I've written a template filter that I can quickly pass my text through but I'm slightly stuck on writing the regex logic.

t = text_from_template_engine
return re.sub(r'(https?://(?:www\.)?amazon\.co\.uk[\S]+)', r'\\\1?tag=xxx', t)

This seems to work on a very basic level but if the URL already has a querystring (as lots of organic Amazon URLs do by default), I would need an ampersand instead of a question mark.

There might be a quick way to detect two question marks and replace the second. I'm open to that suggestion.

What I'm really looking for is a regex-replace where I can pass the found string off to another method (in which I can detect existing question marks) that is expected to return the replacement string. Something like PHP's preg_replace_callback (et al). Does that exist?


问:
Select only unique values from a column in codeigniter
i have a table like this

```<code>name|subjects|location
......................
BUET|CSE|Dhaka
BUET|EEE|Dhaka
RUET|CE |Rajshahi
RU  |CE |Rajshahi
</code>```

here all the rows are distinct.And if I use

```<code> $this->db->select('*') and $this->db->distinct()
</code>```

it would select  all the rows of BUET but i only want like this

```<code>name|subjects|location
......................
BUET|CSE|Dhaka
RUET|CE |Rajshahi
RU  |CE |Rajshahi
</code>```

That means only the first column must be distinct and select all the columns as usual.And it would work if i use $this->db->select('name') and $this->db->distinct(). Then what would be about the other columns??

As my original table has many columns so I want to use $this->db->select('*'). I think  $this->db->distinct() does not take any column as parameter. It differentiate result based on select. How can I do this?

答:
```<code>   $this->db->select('job,id');
   $this->db->group_by('job');
   $query= $this->db->get('technicals')->result_array();
   if(!empty($query)){
       return $query;
   }else{
       return false;
   }
</code>```

Body:
i have a table like this

name|subjects|location
......................
BUET|CSE|Dhaka
BUET|EEE|Dhaka
RUET|CE |Rajshahi
RU  |CE |Rajshahi

here all the rows are distinct.And if I use

 $this->db->select('*') and $this->db->distinct()

it would select  all the rows of BUET but i only want like this

name|subjects|location
......................
BUET|CSE|Dhaka
RUET|CE |Rajshahi
RU  |CE |Rajshahi

That means only the first column must be distinct and select all the columns as usual.And it would work if i use $this->db->select('name') and $this->db->distinct(). Then what would be about the other columns??

As my original table has many columns so I want to use $this->db->select('*'). I think  $this->db->distinct() does not take any column as parameter. It differentiate result based on select. How can I do this?


问:
How to deploy a database file with a Xamarin.from app?
I created a sqlite file in my project with some data in it, but I don't know how to link it to my app. I expect the data could be loaded on a Android simulator.

I found a tutorial which was published in 2015, it works no longer, such as GetLocalFilePath function cannot be found after new a FileAccessHelper Class. And the tutorial project seemed using an olde version of SQLite.net-PCL package, because SQLite.Net.Platform.XamarinAndroid was used in the tutorial project, while this package is no longer exist. Any ideas?

http://arteksoftware.com/deploying-a-database-file-with-a-xamarin-forms-app/

This is the code from the tutorial:

```<code>[Activity (Label = "People", Icon = "@drawable/icon", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
{
    protected override void OnCreate (Bundle bundle)
    {
        base.OnCreate (bundle);
        global::Xamarin.Forms.Forms.Init (this, bundle);

        string dbPath = FileAccessHelper.GetLocalFilePath ("people.db3");

        LoadApplication (new People.App (dbPath, new SQLitePlatformAndroid ()));
    }
}
</code>```

FileAccessHelper.cs

```<code>public class FileAccessHelper
{
    public static string GetLocalFilePath (string filename)
    {
        string path = Environment.GetFolderPath (Environment.SpecialFolder.Personal);
        string dbPath = Path.Combine (path, filename);

        CopyDatabaseIfNotExists (dbPath);

        return dbPath;
    }

    private static void CopyDatabaseIfNotExists (string dbPath)
    {
        if (!File.Exists (dbPath)) {
            using (var br = new BinaryReader (Application.Context.Assets.Open ("people.db3"))) {
                using (var bw = new BinaryWriter (new FileStream (dbPath, FileMode.Create))) {
                    byte[] buffer = new byte[2048];
                    int length = 0;
                    while ((length = br.Read (buffer, 0, buffer.Length)) > 0) {
                        bw.Write (buffer, 0, length);
                    }
                }
            }
        }
    }
}
</code>```

答:
Try assigning your dbpath variable in your Android project with the following (and forget about the FileAccessHelper class):

```<code>[Activity (Label = "People", Icon = "@drawable/icon", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
{
    protected override void OnCreate (Bundle bundle)
    {
        base.OnCreate (bundle);
        global::Xamarin.Forms.Forms.Init (this, bundle);

        // Retrieves the "AppHome"/files folder which is the root of your app sandbox on Android
        var appDir = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
        // Locates your dbPath.
        string dbPath = Path.Combine(appDir , "people.db3");

        LoadApplication (new People.App (dbPath, new SQLitePlatformAndroid()));
    }
}
</code>```

Hope this helps!

Body:
I created a sqlite file in my project with some data in it, but I don't know how to link it to my app. I expect the data could be loaded on a Android simulator.

I found a tutorial which was published in 2015, it works no longer, such as GetLocalFilePath function cannot be found after new a FileAccessHelper Class. And the tutorial project seemed using an olde version of SQLite.net-PCL package, because SQLite.Net.Platform.XamarinAndroid was used in the tutorial project, while this package is no longer exist. Any ideas?

http://arteksoftware.com/deploying-a-database-file-with-a-xamarin-forms-app/

This is the code from the tutorial:

[Activity (Label = "People", Icon = "@drawable/icon", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
{
    protected override void OnCreate (Bundle bundle)
    {
        base.OnCreate (bundle);
        global::Xamarin.Forms.Forms.Init (this, bundle);

        string dbPath = FileAccessHelper.GetLocalFilePath ("people.db3");

        LoadApplication (new People.App (dbPath, new SQLitePlatformAndroid ()));
    }
}

FileAccessHelper.cs

public class FileAccessHelper
{
    public static string GetLocalFilePath (string filename)
    {
        string path = Environment.GetFolderPath (Environment.SpecialFolder.Personal);
        string dbPath = Path.Combine (path, filename);

        CopyDatabaseIfNotExists (dbPath);

        return dbPath;
    }

    private static void CopyDatabaseIfNotExists (string dbPath)
    {
        if (!File.Exists (dbPath)) {
            using (var br = new BinaryReader (Application.Context.Assets.Open ("people.db3"))) {
                using (var bw = new BinaryWriter (new FileStream (dbPath, FileMode.Create))) {
                    byte[] buffer = new byte[2048];
                    int length = 0;
                    while ((length = br.Read (buffer, 0, buffer.Length)) > 0) {
                        bw.Write (buffer, 0, length);
                    }
                }
            }
        }
    }
}

Body:
Try assigning your dbpath variable in your Android project with the following (and forget about the FileAccessHelper class):

[Activity (Label = "People", Icon = "@drawable/icon", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
{
    protected override void OnCreate (Bundle bundle)
    {
        base.OnCreate (bundle);
        global::Xamarin.Forms.Forms.Init (this, bundle);

        // Retrieves the "AppHome"/files folder which is the root of your app sandbox on Android
        var appDir = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
        // Locates your dbPath.
        string dbPath = Path.Combine(appDir , "people.db3");

        LoadApplication (new People.App (dbPath, new SQLitePlatformAndroid()));
    }
}

Hope this helps!


问:
In GitHub, is there a way to see all (recent) commits on all branches?
In GitHub, is there a way to see all recent commits on all branches.  It would be best in reverse chronological order.

Maybe I'm snoopy, but I'd like to be able to see what my developers have been up to recently, at least in terms of commits to the repository on github.  So far the closest I've seen is the network graph, which is certainly very useful.

答:
This is an old feature of GitHub but not really that intuitive.

Using the GitHub website:

Click a project

Click the 'Insights' tab  (moved inside the Meatballs menu)

Click 'Network'

Click on the 'node/circle' for each commit to go to that commit.

Diagram below.

Additionally, you can drag to the left to see all commits throughout time for all forks and branches.


问:
SQL JOIN COUNT then using that count value in where clause
I'm trying to select if a user rating (user.rating) is greater then 6 or if the user has more then 100 transactions (transaction table count). Basically count how many transactions the user has then where (transaction count >= 100 OR user rating >= 6).</p>

```<code>SELECT *
FROM   `user`
JOIN   (SELECT COUNT(*)
        FROM   transaction
        WHERE  transaction.user_id=user.id
        AND type='L'
        AND status='S') AS tcount
WHERE  (user.rating >= '6' OR tcount >= '100')
</code>```

答:
Use an alias on COUNT(*)</p>

```<code>SELECT *
FROM   `user`
JOIN   (SELECT user_id, COUNT(*) cnt
        FROM   transaction
        WHERE type='L'
        AND status='S'
        GROUP BY user_id) AS tcount
ON      user.id = tcount.user_id
WHERE  (user.rating >= '6' OR tcount.cnt >= '100')
</code>```

Body:
I'm trying to select if a user rating (user.rating) is greater then 6 or if the user has more then 100 transactions (transaction table count). Basically count how many transactions the user has then where (transaction count >= 100 OR user rating >= 6).

SELECT *
FROM   `user`
JOIN   (SELECT COUNT(*)
        FROM   transaction
        WHERE  transaction.user_id=user.id
        AND type='L'
        AND status='S') AS tcount
WHERE  (user.rating >= '6' OR tcount >= '100')

Body:
Use an alias on COUNT(*)

SELECT *
FROM   `user`
JOIN   (SELECT user_id, COUNT(*) cnt
        FROM   transaction
        WHERE type='L'
        AND status='S'
        GROUP BY user_id) AS tcount
ON      user.id = tcount.user_id
WHERE  (user.rating >= '6' OR tcount.cnt >= '100')


问:
Java Stream - Collecting rows of data into less rows with one column grouped into set
I'm new to working with Java streams so I apologize for any misunderstandings.

I'm looking to use Collect on my stream to return a stream that has a grouped rows that match all elements but one into a singular row, in which that one element is added to a set.

For example, if my stream contains data:

```<code>[{12, "Apple", "Gala"},
 {12, "Apple", "Fuji"},
 {13, "Orange", "Navel"},
 {13, "Orange", "Valencia"}]
</code>```

After collecting for column 3 it would return stream with data:

```<code>[{12, "Apple", ["Gala", "Fuji"]},
 {13, "Orange", ["Navel", "Valencia"]}]
</code>```

Is this possible using the stream collect method? Any and all help is greatly appreciated!

Thank you.

答:
What you need to do is to create a fruit class.
Once you've done that, you have three getters

getNumber, getType, getName.

So now you have a List of Fruit named list.

Once you have that, you would do:

```<code>list.stream()
    .collect(Collectors.groupingBy(Fruit::getNumber,
        Collectors.groupingBy(Fruit::getName, Collectors.mapping(Fruit::getType, Collectors.toList())))));
</code>```

This will return a HashMap of hashmaps that will look like this:

```<code>{12={Apple=[Gala]}, 13={Orange=[Navel, Valencia]}}
</code>```

You can replace Fruit::getName with Function.identity() if you want the fruit object to be the key rather than the name.

Body:
I'm new to working with Java streams so I apologize for any misunderstandings.

I'm looking to use Collect on my stream to return a stream that has a grouped rows that match all elements but one into a singular row, in which that one element is added to a set.

For example, if my stream contains data:

[{12, "Apple", "Gala"},
 {12, "Apple", "Fuji"},
 {13, "Orange", "Navel"},
 {13, "Orange", "Valencia"}]

After collecting for column 3 it would return stream with data:

[{12, "Apple", ["Gala", "Fuji"]},
 {13, "Orange", ["Navel", "Valencia"]}]

Is this possible using the stream collect method? Any and all help is greatly appreciated!

Thank you.

Body:
What you need to do is to create a fruit class.
Once you've done that, you have three getters

getNumber, getType, getName.

So now you have a List of Fruit named list.

Once you have that, you would do:

list.stream()
    .collect(Collectors.groupingBy(Fruit::getNumber,
        Collectors.groupingBy(Fruit::getName, Collectors.mapping(Fruit::getType, Collectors.toList())))));

This will return a HashMap of hashmaps that will look like this:

{12={Apple=[Gala]}, 13={Orange=[Navel, Valencia]}}

You can replace Fruit::getName with Function.identity() if you want the fruit object to be the key rather than the name.


问:
Redirect site specific domain to a new extension
My htaccess controls multiple domains (it's a custom CMS). I need to redirect all requests to my domain "mydomian.com.br" to "mydomain.org.br" This includes calls to sites such as "mydomain.com.br/contact".

I tried this but it just redirects everything to the homepage:

```<code>RewriteCond %{HTTP_HOST} ^(www\.)?mydomain\.com\.br$ [NC]
RewriteRule ^(.*)$ http://www.mydomain.org.br/$1 [R=301,L]
</code>```

答:
Try this:</p>

```<code>RewriteEngine on
RedirectMatch permanent ^(.*)$ http://mydomain.org.br$1
</code>```

Body:
My htaccess controls multiple domains (it's a custom CMS). I need to redirect all requests to my domain "mydomian.com.br" to "mydomain.org.br" This includes calls to sites such as "mydomain.com.br/contact".

I tried this but it just redirects everything to the homepage:

RewriteCond %{HTTP_HOST} ^(www\.)?mydomain\.com\.br$ [NC]
RewriteRule ^(.*)$ http://www.mydomain.org.br/$1 [R=301,L]

Body:
Try this:

RewriteEngine on
RedirectMatch permanent ^(.*)$ http://mydomain.org.br$1


问:
Asp.Net Core validation without jQuery
Is there any mode to use Asp.Net Core client side validation without jquery + jquery validation + jq unobtrusive validation?
I mean it's 2017, every browser can handle lots of HTML5 input validators without JavaScript.</p>

答:
I don't know of  any package that turns TagHelper for input fields into html5 element tags. You could probably quite easily make one. Check out the source code of the tag helpers: https://github.com/aspnet/AspNetCore/blob/master/src/Mvc/Mvc.TagHelpers/src/InputTagHelper.cs

Advise

Best approach would be to make sure you receive a json error object when validation fails and process this in javascript to show errrors (maybe show which fields fail). make a generic function you can use for any form.

Later manually fine tune/add additional tags/validation if needed in frontend. but that shouldn't be part of your MVP (minimal viable product).

old answer

Depends on what kind of validation you are looking for.

jQuery validation in combination with data annotations is the easiest one and the default one. Although html 5 can tackle quite some extensive tests. it can't handle any indepth stuff like properties being dependent on eachother.

Another option is to use the Popular FluentValidation. Validate only serverside but use Ajax and a small client side framework to show the errors

The last option would be to use Html5 input validations. This can only be partly achieved by default using dotnet types or some annotations: http://www.davepaquette.com/archive/2015/05/13/mvc6-input-tag-helper-deep-dive.aspx. You'd have to extend the taghelpers yourself if you'd want to add more in depth html 5 attribute support.

Too bad you can't use the same frontend and serverside code (like nodejs could) but for big projects i'd advise you to take option 2. it might not sound very snappy but dotnet is generally pretty fast and if you use FluentValidation in combination with Ajax Api calls no one will notice validation actually serverside. In the end i found data annotations always lack proper possibilities to test properties dependent on each other and it gets very hacky very fast. The only downside of this option is that you split the validation from the input-model and thus not always the validation is directly visible for external developers.

Title: Asp.Net Core validation without jQuery


答:
Here is the rextester for this demo</p>

```<code>Map<Integer, Map<String, Set<String>>> fruitsByIdByType =
                   fruits.stream()
                    .collect(Collectors.groupingBy(Fruit::getId, Collectors.groupingBy(Fruit::getName, Collectors.mapping(Fruit::getType, Collectors.toSet()))));
</code>```

Title: Java Stream - Collecting rows of data into less rows with one column grouped into set

Body:
Here is the rextester for this demo

Map<Integer, Map<String, Set<String>>> fruitsByIdByType =
                   fruits.stream()
                    .collect(Collectors.groupingBy(Fruit::getId, Collectors.groupingBy(Fruit::getName, Collectors.mapping(Fruit::getType, Collectors.toSet()))));


问:
How to load a gzipped rdf file to rdf4j Repository?
I want to load a gzipped rdf file into a org.eclipse.rdf4j.repository.Repository. During the upload, status messages must be logged to the console. The size of my rdf file is ~1GB of uncompressed or ~50MB of compressed data.

答:
Actually an RDF4J repository will automatically process a compressed (zip/gzip) file correctly, already. So you can simply do this:

```<code>   RepositoryConnection conn = ... ; // your store connection
   conn.add(new File("file.zip"), null, RDFFormat.NTRIPLES):
</code>```

If you want to include reporting, a different (somewhat simpler) approach  is to use an org.eclipse.rdf4j.repository.util.RDFLoader class in combination with an RDFInserter:

```<code>RepositoryConnection conn = ... ; // your store connection
RDFInsert inserter = new RDFInserter(conn);
RDFLoader loader = new RDFLoader(conn.getParserConfig(), conn.getValueFactory());

loader.load(new File("file.zip"), RDFFormat.NTRIPLES, inserter));
</code>```

The RDFLoader takes care of properly uncompressing the (zip or gzip) file.

To get intermediate reporting you can wrap your RDFInserter in your own custom AbstractRDFHandler that does the counting and reporting (before passing on to the wrapper inserter).

Body:
Actually an RDF4J repository will automatically process a compressed (zip/gzip) file correctly, already. So you can simply do this:

   RepositoryConnection conn = ... ; // your store connection
   conn.add(new File("file.zip"), null, RDFFormat.NTRIPLES):

If you want to include reporting, a different (somewhat simpler) approach  is to use an org.eclipse.rdf4j.repository.util.RDFLoader class in combination with an RDFInserter:

RepositoryConnection conn = ... ; // your store connection
RDFInsert inserter = new RDFInserter(conn);
RDFLoader loader = new RDFLoader(conn.getParserConfig(), conn.getValueFactory());

loader.load(new File("file.zip"), RDFFormat.NTRIPLES, inserter));

The RDFLoader takes care of properly uncompressing the (zip or gzip) file.

To get intermediate reporting you can wrap your RDFInserter in your own custom AbstractRDFHandler that does the counting and reporting (before passing on to the wrapper inserter).


问:
Error when converting MATLAB's datenum to Python's datetime
I have to convert a MATLAB's datenum to Python's datetime.
The following code is as below:

```<code>import datetime
matlab_datenum = 63650571169.50261
python_datetime = datetime.date.fromordinal(int(matlab_datenum)) + \
    datetime.timedelta(days=matlab_datenum%1) - datetime.timedelta(days=366)
print(matlab_datenum)
</code>```

The above code generates this error:

```<code>OverflowError: Python int too large to convert to C long
</code>```

How, can I resolve this problem?

答:
Your datenum is in seconds from the matlab epoch.  To convert to a datetime you need to offset that number of seconds to a datetime that python understands.  This function uses the Unix epoch as that reference.

Code:

```<code>import datetime as dt

# define some constants
epoch = dt.datetime(1970, 1, 1)
matlab_to_epoch_days = 719529  # days from 1-1-0000 to 1-1-1970
matlab_to_epoch_seconds = matlab_to_epoch_days * 24 * 60 * 60

def matlab_to_datetime(matlab_date_num_seconds):
    # get number of seconds from epoch
    from_epoch = matlab_date_num_seconds - matlab_to_epoch_seconds

    # convert to python datetime
    return epoch + dt.timedelta(seconds=from_epoch)
</code>```

Test Code:

```<code>print(matlab_to_datetime(63650571169.50261))
</code>```

Results:

```<code>2017-01-01 10:12:49.502609
</code>```

Body:
I have to convert a MATLAB's datenum to Python's datetime.
The following code is as below:

import datetime
matlab_datenum = 63650571169.50261
python_datetime = datetime.date.fromordinal(int(matlab_datenum)) + \
    datetime.timedelta(days=matlab_datenum%1) - datetime.timedelta(days=366)
print(matlab_datenum)

The above code generates this error:

OverflowError: Python int too large to convert to C long

How, can I resolve this problem?

Body:
Your datenum is in seconds from the matlab epoch.  To convert to a datetime you need to offset that number of seconds to a datetime that python understands.  This function uses the Unix epoch as that reference.

Code:

import datetime as dt

# define some constants
epoch = dt.datetime(1970, 1, 1)
matlab_to_epoch_days = 719529  # days from 1-1-0000 to 1-1-1970
matlab_to_epoch_seconds = matlab_to_epoch_days * 24 * 60 * 60

def matlab_to_datetime(matlab_date_num_seconds):
    # get number of seconds from epoch
    from_epoch = matlab_date_num_seconds - matlab_to_epoch_seconds

    # convert to python datetime
    return epoch + dt.timedelta(seconds=from_epoch)

Test Code:

print(matlab_to_datetime(63650571169.50261))

Results:

2017-01-01 10:12:49.502609


问:
VB6 Run time error 424
I am getting error 424 on this line, can anyone help me please.

```<code>lblprvbal.Text = Val(NewItem.SubItems(11))
</code>```

```<code>Private Sub cmdShow_Click()
'lblTotPur/lblTotPayRet/lblBalance
Dim strShow, mSlNo
Dim rsShow As New ADODB.Recordset
Dim NewItem As Variant
If Trim(txtCustomer.Text) = "" Then
    MsgBox "Please select customer to proceed...", vbCritical, POPUP_COMP
    Exit Sub
End If

Dim recCnt
pgrPartyLedger.Min = 0
recCnt = 0
'VOUCHMST_P//VNO,DATED,VTYPE,REMARKS,byUser CASH PURCHASE RETURN
strShow = "select Count(*) as mCnt from VOUCHMST A,VOUCHDAT B, Prevbal C  "
strShow = strShow & " where A.VNO=B.VNO and B.IDNO=C.obd and (A.REMARKS='CASH SALE RETURN' OR A.REMARKS='CREDIT SALE RETURN' OR A.REMARKS='CREDIT SALE' OR A.REMARKS='CASH SALE' OR A.REMARKS='RECEIPT' OR A.REMARKS='CREDIT NOTE') "
strShow = strShow & " and A.DATED between #" & Format(dtFrom.Value, "MM/dd/yyyy") & "# "
strShow = strShow & " and #" & Format(dtTo.Value, "MM/dd/yyyy") & "# "
strShow = strShow & " and B.IDNO = '" & Trim(txtCustomerId.Text) & "' "
'strShow = strShow & " order by A.ID,A.DATED,A.VNO"
rsShow.Open strShow, cn
recCnt = rsShow("mCnt")
rsShow.Close
pgrPartyLedger.Max = recCnt + 1

'VOUCHMST_P//VNO,DATED,VTYPE,REMARKS,byUser
strShow = "select A.Id,A.cmnt,A.ADV,A.VNO,A.DATED,B.IDNO,B.IDNAME,B.AMOUNT,B.DR_CR,B.VNARRATION,A.REMARKS,B.CQ_TYPE, B.BANKNAME, B.BANKBRANCH, B.CQ_NO, C.amnt from VOUCHMST A,VOUCHDAT B, Prevbal C "
strShow = strShow & " where A.VNO=B.VNO and B.IDNO=C.obd and (A.REMARKS='CASH SALE RETURN' OR A.REMARKS='CREDIT SALE RETURN' OR A.REMARKS='CREDIT SALE' OR A.REMARKS='CASH SALE' OR A.REMARKS='RECEIPT' OR A.REMARKS='CREDIT NOTE') "
strShow = strShow & " and A.DATED between #" & Format(dtFrom.Value, "MM/dd/yyyy") & "# "
strShow = strShow & " and #" & Format(dtTo.Value, "MM/dd/yyyy") & "# "
strShow = strShow & " and B.IDNO = '" & Trim(txtCustomerId.Text) & "' "
strShow = strShow & " order by A.ID,A.DATED,A.VNO"
rsShow.Open strShow, cn

Dim mPur, mPayRet, mAnyAdv, mTempVNO
mPur = 0
mPayRet = 0
mAnyAdv = 0

mSlNo = 1
ShowPaymentHeader
Do While Not rsShow.EOF
    mTempVNO = rsShow("VNO")

    Set NewItem = listViewPayment.ListItems.Add(, "C" & mSlNo, Format(rsShow("DATED"), "dd/MM/yyyy"))
    NewItem.SubItems(1) = mTempVNO
    NewItem.SubItems(2) = IIf(IsNull(rsShow("IDNAME")), "", CommaFilterText(rsShow("IDNAME"), 1))
    NewItem.SubItems(11) = rsShow("amnt")
    If Trim(rsShow("REMARKS")) = "CASH SALE" Then
        NewItem.SubItems(3) = FormatTakaPaisa(rsShow("AMOUNT"))
        NewItem.SubItems(4) = FormatTakaPaisa(rsShow("AMOUNT"))
    ElseIf Trim(rsShow("REMARKS")) = "CREDIT SALE" Then
        mAnyAdv = ShowPartialAdvance(rsShow("VNO"))
        NewItem.SubItems(3) = FormatTakaPaisa(rsShow("AMOUNT") + Val(mAnyAdv))

        If Val(mAnyAdv) > 0 Then
            NewItem.SubItems(4) = FormatTakaPaisa(mAnyAdv)

        Else
            NewItem.SubItems(4) = ""

        End If
    Else
        NewItem.SubItems(3) = ""
        NewItem.SubItems(4) = FormatTakaPaisa(rsShow("AMOUNT"))
        NewItem.SubItems(7) = rsShow("CQ_TYPE")
        NewItem.SubItems(8) = rsShow("BANKNAME")
        NewItem.SubItems(9) = rsShow("BANKBRANCH")
        NewItem.SubItems(10) = rsShow("CQ_NO")

        NewItem.SubItems(13) = "" & rsShow("cmnt")

    End If
    NewItem.SubItems(6) = rsShow("IDNO")

    mPur = mPur + Val(NewItem.SubItems(3))
    mPayRet = mPayRet + Val(NewItem.SubItems(4))

    NewItem.SubItems(5) = rsShow("REMARKS")

    NewItem.SubItems(12) = GetVoucherRefNo(mTempVNO)

    pgrPartyLedger.Value = mSlNo

    mSlNo = mSlNo + 1
    rsShow.MoveNext
Loop
rsShow.Close

lblprvbal.Text = Val(NewItem.SubItems(11))
lblTotPur.Caption = FormatTakaPaisa(mPur) + Val(lblprvbal.Text)
lblTotPayRet.Caption = FormatTakaPaisa(mPayRet)
lblBalance.Caption = FormatTakaPaisa(mPur - mPayRet) + Val(lblprvbal.Text)

pgrPartyLedger.Value = 0
End Sub
</code>```

答: Looks like lblprvbal isn't an object.  Meaning, you don't have a TextBox called lblprvbal in your form, even if you think you do.  Maybe because its real name is lblPrvBal? That would be consistent with your other object names. As a side note, you probably don't want to start a TextBox with lbl, which suggests it's a label.

Title: VB6 Run time error 424

Body:
I am getting error 424 on this line, can anyone help me please.

lblprvbal.Text = Val(NewItem.SubItems(11))

Private Sub cmdShow_Click()
'lblTotPur/lblTotPayRet/lblBalance
Dim strShow, mSlNo
Dim rsShow As New ADODB.Recordset
Dim NewItem As Variant
If Trim(txtCustomer.Text) = "" Then
    MsgBox "Please select customer to proceed...", vbCritical, POPUP_COMP
    Exit Sub
End If

Dim recCnt
pgrPartyLedger.Min = 0
recCnt = 0
'VOUCHMST_P//VNO,DATED,VTYPE,REMARKS,byUser CASH PURCHASE RETURN
strShow = "select Count(*) as mCnt from VOUCHMST A,VOUCHDAT B, Prevbal C  "
strShow = strShow & " where A.VNO=B.VNO and B.IDNO=C.obd and (A.REMARKS='CASH SALE RETURN' OR A.REMARKS='CREDIT SALE RETURN' OR A.REMARKS='CREDIT SALE' OR A.REMARKS='CASH SALE' OR A.REMARKS='RECEIPT' OR A.REMARKS='CREDIT NOTE') "
strShow = strShow & " and A.DATED between #" & Format(dtFrom.Value, "MM/dd/yyyy") & "# "
strShow = strShow & " and #" & Format(dtTo.Value, "MM/dd/yyyy") & "# "
strShow = strShow & " and B.IDNO = '" & Trim(txtCustomerId.Text) & "' "
'strShow = strShow & " order by A.ID,A.DATED,A.VNO"
rsShow.Open strShow, cn
recCnt = rsShow("mCnt")
rsShow.Close
pgrPartyLedger.Max = recCnt + 1

'VOUCHMST_P//VNO,DATED,VTYPE,REMARKS,byUser
strShow = "select A.Id,A.cmnt,A.ADV,A.VNO,A.DATED,B.IDNO,B.IDNAME,B.AMOUNT,B.DR_CR,B.VNARRATION,A.REMARKS,B.CQ_TYPE, B.BANKNAME, B.BANKBRANCH, B.CQ_NO, C.amnt from VOUCHMST A,VOUCHDAT B, Prevbal C "
strShow = strShow & " where A.VNO=B.VNO and B.IDNO=C.obd and (A.REMARKS='CASH SALE RETURN' OR A.REMARKS='CREDIT SALE RETURN' OR A.REMARKS='CREDIT SALE' OR A.REMARKS='CASH SALE' OR A.REMARKS='RECEIPT' OR A.REMARKS='CREDIT NOTE') "
strShow = strShow & " and A.DATED between #" & Format(dtFrom.Value, "MM/dd/yyyy") & "# "
strShow = strShow & " and #" & Format(dtTo.Value, "MM/dd/yyyy") & "# "
strShow = strShow & " and B.IDNO = '" & Trim(txtCustomerId.Text) & "' "
strShow = strShow & " order by A.ID,A.DATED,A.VNO"
rsShow.Open strShow, cn

Dim mPur, mPayRet, mAnyAdv, mTempVNO
mPur = 0
mPayRet = 0
mAnyAdv = 0

mSlNo = 1
ShowPaymentHeader
Do While Not rsShow.EOF
    mTempVNO = rsShow("VNO")

    Set NewItem = listViewPayment.ListItems.Add(, "C" & mSlNo, Format(rsShow("DATED"), "dd/MM/yyyy"))
    NewItem.SubItems(1) = mTempVNO
    NewItem.SubItems(2) = IIf(IsNull(rsShow("IDNAME")), "", CommaFilterText(rsShow("IDNAME"), 1))
    NewItem.SubItems(11) = rsShow("amnt")
    If Trim(rsShow("REMARKS")) = "CASH SALE" Then
        NewItem.SubItems(3) = FormatTakaPaisa(rsShow("AMOUNT"))
        NewItem.SubItems(4) = FormatTakaPaisa(rsShow("AMOUNT"))
    ElseIf Trim(rsShow("REMARKS")) = "CREDIT SALE" Then
        mAnyAdv = ShowPartialAdvance(rsShow("VNO"))
        NewItem.SubItems(3) = FormatTakaPaisa(rsShow("AMOUNT") + Val(mAnyAdv))

        If Val(mAnyAdv) > 0 Then
            NewItem.SubItems(4) = FormatTakaPaisa(mAnyAdv)

        Else
            NewItem.SubItems(4) = ""

        End If
    Else
        NewItem.SubItems(3) = ""
        NewItem.SubItems(4) = FormatTakaPaisa(rsShow("AMOUNT"))
        NewItem.SubItems(7) = rsShow("CQ_TYPE")
        NewItem.SubItems(8) = rsShow("BANKNAME")
        NewItem.SubItems(9) = rsShow("BANKBRANCH")
        NewItem.SubItems(10) = rsShow("CQ_NO")

        NewItem.SubItems(13) = "" & rsShow("cmnt")

    End If
    NewItem.SubItems(6) = rsShow("IDNO")

    mPur = mPur + Val(NewItem.SubItems(3))
    mPayRet = mPayRet + Val(NewItem.SubItems(4))

    NewItem.SubItems(5) = rsShow("REMARKS")

    NewItem.SubItems(12) = GetVoucherRefNo(mTempVNO)

    pgrPartyLedger.Value = mSlNo

    mSlNo = mSlNo + 1
    rsShow.MoveNext
Loop
rsShow.Close

lblprvbal.Text = Val(NewItem.SubItems(11))
lblTotPur.Caption = FormatTakaPaisa(mPur) + Val(lblprvbal.Text)
lblTotPayRet.Caption = FormatTakaPaisa(mPayRet)
lblBalance.Caption = FormatTakaPaisa(mPur - mPayRet) + Val(lblprvbal.Text)

pgrPartyLedger.Value = 0
End Sub


问:
VB.NET Limit to Tab Ordering?
I have inherited a frankenstein VB6 "Converted" to VB.NET winform application. This application has a metric ton of fields in it, the users rightfully complained that the tab order is off (after a certain point it starts jumping all over the form).

Figuring something in tab order was off, I went in and turned on View > Tab Order and it looked good.

To be sure I went through the form again fresh and when I'm in tab order view all is well, but when the app runs it still starts jumping around the same area as before?! Has anyone else encountered this and how did you resolve if you did?

[Edit]: These input forms are all on separate tabs within a tab control, which probably muddies the situation even more.

答:
If you have many controls on a form chances are that they are organized with containers such as panels and group boxes. When setting the tab order you have to consider the order of the containers as well. An inconsistency between tab orders on in the containers could explain the weird jumping. This can happen especially if two or more controls/containers have the same tab order value which makes the tabbing process arbitrary.

Solution Idea: Of course updating and correcting the tab order is slow, error-prone work. It may behoove you to write a routine that iterates through the form's containers and controls recursively and assigning tab order values properly. You would set the tab order by comparing the Location point of each control of the container where top and left most point is the "lower" rank and the bottom, right-most component is the "highest". This would of course need a custom sorting alg. And if you look around, something like this may already be out there.

Solution Idea 2: Refactor! Divide and conquer. It will take some time but if you move the UI components into separate, logically-organized user controls you'll get tighter of the codebase. You'll also uncover a lot of bugs!

Title: VB.NET Limit to Tab Ordering?


问:
Compiling Java program with VBScripts? (NetBeans)
I have a Java program created that runs VBSscripts after button clicks.

examplescript.vbs

How do I compile these vbs files and then call them to run in the program code? I've been troubleshooting for several days and can't find an answer. Once again I need to be able to run these scripts, at one point I had an input stream created to it but couldn't get it as a vbs file. Hopefully I'm overlooking something here

Edit:
This is what I currently have. With this code I receive the error "Windows Script Host. There is no script extension for file extension ".BufferedInputStream@4e34904""

```<code>ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    InputStream is = classloader.getResourceAsStream("hello.vbs");
    try {
        Runtime.getRuntime().exec("wscript " + is);
    }
    catch( IOException e ) {
    System.out.println(e);
    System.exit(0);
    }
    System.out.print(is);
</code>```

答:
As already mentioned, VBScript is a script and doesn't need compiling. If you want to run code written in VBScript then you can do it this way:

This example uses VBScript to get the Motherboard Serial Number of a computer that is running Microsoft Windows:

```<code>try {
    // Create a temporary script file named MBSerialxxxxxxxx.vbs
    File file = File.createTempFile("MBSerial",".vbs");
     // Delete the temporary file when virtual machines terminates
    file.deleteOnExit();
    try (FileWriter fw = new java.io.FileWriter(file)) {
        String vbs = "Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"
                + "Set colItems = objWMIService.ExecQuery _ \n"
                + "   (\"Select * from Win32_BaseBoard\") \n"
                + "For Each objItem in colItems \n"
                + "    Wscript.Echo objItem.SerialNumber \n"
                + "    exit for  ' do the first cpu only! \n"
                + "Next \n";
        fw.write(vbs);
    }

    // Run the VBScript file....
    Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());

    // Read in any output to the command window.
    BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line;
    while ((line = input.readLine()) != null) {
        // display the output...
        System.out.println(line.trim());
    }
    input.close();
}
catch(IOException e){
    e.printStackTrace();
}
</code>```

Body:
I have a Java program created that runs VBSscripts after button clicks.

examplescript.vbs

How do I compile these vbs files and then call them to run in the program code? I've been troubleshooting for several days and can't find an answer. Once again I need to be able to run these scripts, at one point I had an input stream created to it but couldn't get it as a vbs file. Hopefully I'm overlooking something here

Edit:
This is what I currently have. With this code I receive the error "Windows Script Host. There is no script extension for file extension ".BufferedInputStream@4e34904""

ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    InputStream is = classloader.getResourceAsStream("hello.vbs");
    try {
        Runtime.getRuntime().exec("wscript " + is);
    }
    catch( IOException e ) {
    System.out.println(e);
    System.exit(0);
    }
    System.out.print(is);

Body:
As already mentioned, VBScript is a script and doesn't need compiling. If you want to run code written in VBScript then you can do it this way:

This example uses VBScript to get the Motherboard Serial Number of a computer that is running Microsoft Windows:

try {
    // Create a temporary script file named MBSerialxxxxxxxx.vbs
    File file = File.createTempFile("MBSerial",".vbs");
     // Delete the temporary file when virtual machines terminates
    file.deleteOnExit();
    try (FileWriter fw = new java.io.FileWriter(file)) {
        String vbs = "Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"
                + "Set colItems = objWMIService.ExecQuery _ \n"
                + "   (\"Select * from Win32_BaseBoard\") \n"
                + "For Each objItem in colItems \n"
                + "    Wscript.Echo objItem.SerialNumber \n"
                + "    exit for  ' do the first cpu only! \n"
                + "Next \n";
        fw.write(vbs);
    }

    // Run the VBScript file....
    Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());

    // Read in any output to the command window.
    BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line;
    while ((line = input.readLine()) != null) {
        // display the output...
        System.out.println(line.trim());
    }
    input.close();
}
catch(IOException e){
    e.printStackTrace();
}


问:
How can I convert from degrees to radians?
I am trying to convert this Obj-C code to Swift code but I don't know what the equivalent of this code should be ?

```<code>#define DEGREES_TO_RADIANS(degrees)((M_PI * degrees)/180)
</code>```

I googled and found this

But I don't understand how to convert that in Swift in my case?

答:
```<code>let angle = 45° // angle will be in radians, 45 is in degrees
</code>```

Compiles under Swift 3. Still keep all values, do all calculations in radians with CGFloats..., but make the code more readable with the constants in degrees. For example: 90°
The ° sign will magically do the degrees to radians conversion.

How to set this up:

Define and use a postfix operator for the ° sign. This operator will do the conversion from degrees to radians.
This example is for Ints, extend these also for the Float types if you have the need.

```<code>postfix operator °

protocol IntegerInitializable: ExpressibleByIntegerLiteral {
  init (_: Int)
}

extension Int: IntegerInitializable {
  postfix public static func °(lhs: Int) -> CGFloat {
    return CGFloat(lhs) * .pi / 180
  }
}
</code>```

Some examples of usage:

```<code>let angle = 45°

contentView.transform = CGAffineTransform(rotationAngle: 45°)

let angle = 45
contentView.transform = CGAffineTransform(rotationAngle: angle°)
</code>```

Warning!

It is too easy to use this conversion twice (on a value already in radians by mistake), you will get a very small number as the result, and seemingly the resulting angle will be always zero... DO NOT use ° on the same value twice (do not convert twice)!!:

```<code>// OBVIOUSLY WRONG!
let angle = 45°° // ° used twice here

// WRONG! BUT EASY TO MISS
let angle = 45° // ° used here
contentView.transform = CGAffineTransform(rotationAngle: angle°) // ° also used here
</code>```

Body:
I am trying to convert this Obj-C code to Swift code but I don't know what the equivalent of this code should be ?

#define DEGREES_TO_RADIANS(degrees)((M_PI * degrees)/180)

I googled and found this

But I don't understand how to convert that in Swift in my case?

Body:
let angle = 45° // angle will be in radians, 45 is in degrees

Compiles under Swift 3. Still keep all values, do all calculations in radians with CGFloats..., but make the code more readable with the constants in degrees. For example: 90°
The ° sign will magically do the degrees to radians conversion.

How to set this up:

Define and use a postfix operator for the ° sign. This operator will do the conversion from degrees to radians.
This example is for Ints, extend these also for the Float types if you have the need.

postfix operator °

protocol IntegerInitializable: ExpressibleByIntegerLiteral {
  init (_: Int)
}

extension Int: IntegerInitializable {
  postfix public static func °(lhs: Int) -> CGFloat {
    return CGFloat(lhs) * .pi / 180
  }
}

Some examples of usage:

let angle = 45°

contentView.transform = CGAffineTransform(rotationAngle: 45°)

let angle = 45
contentView.transform = CGAffineTransform(rotationAngle: angle°)

Warning!

It is too easy to use this conversion twice (on a value already in radians by mistake), you will get a very small number as the result, and seemingly the resulting angle will be always zero... DO NOT use ° on the same value twice (do not convert twice)!!:

// OBVIOUSLY WRONG!
let angle = 45°° // ° used twice here

// WRONG! BUT EASY TO MISS
let angle = 45° // ° used here
contentView.transform = CGAffineTransform(rotationAngle: angle°) // ° also used here


问:
Angular 2 - not working with Webstorm 11.01 and Jade 4.2
I have been working through the Angular 2 guide example that can be found at this location: https://plnkr.co/edit/I4ArEQTniO7MJtfzpBWl?p=preview .

On my desktop this application works fine with the inline template code but as soon as I change to the templateUrl file I have a problem.  I have found that this is due to issues with the combination of WebStorm, Jade and Angular 2. See blogs at: https://youtrack.jetbrains.com/issue/WEB-19625 and https://github.com/donpark/html2jade/issues/102.

One problem is that the html2jade converter changes attributes to lower case. Below is an example where the Link of routerlink and the Link & Active of routerlinkactive have the first letters changed to lower case.  I can fix that by changing attribute names as required.

The problem I cannot fix is the WebStorm errors that show up as indicated in the blogs.   In my case the last routerlink line, the one for contacts, causes a syntax error.

I would like to continue to use both WebStorm and Jade.  Does anyone know of a work around or if other versions of either product fix these problems?

```<code>h1.title Angular Router
 nav
   a(routerlink='/crisis-center', routerlinkactive='active') Crisis Center
   a(routerlink='/heroes', routerlinkactive='active') Heroes
   a(routerlink='/admin', routerlinkactive='active') Admin
   a(routerlink='/login', routerlinkactive='active') Login
   a([routerlink]="[{ outlets: { popup: ['compose'] } }]") Contact
 router-outlet
 router-outlet(name='popup')
</code>```

答: I downloaded WebStorm 2017.1 released March 17, 2017 and it appears that the errors I was getting with the JADE have gone away.  I still have to manually change lowercase letters in attributes to upper case but that should not be a big issue.</p>

Body:
I have been working through the Angular 2 guide example that can be found at this location: https://plnkr.co/edit/I4ArEQTniO7MJtfzpBWl?p=preview .

On my desktop this application works fine with the inline template code but as soon as I change to the templateUrl file I have a problem.  I have found that this is due to issues with the combination of WebStorm, Jade and Angular 2. See blogs at: https://youtrack.jetbrains.com/issue/WEB-19625 and https://github.com/donpark/html2jade/issues/102.

One problem is that the html2jade converter changes attributes to lower case. Below is an example where the Link of routerlink and the Link & Active of routerlinkactive have the first letters changed to lower case.  I can fix that by changing attribute names as required.

The problem I cannot fix is the WebStorm errors that show up as indicated in the blogs.   In my case the last routerlink line, the one for contacts, causes a syntax error.

I would like to continue to use both WebStorm and Jade.  Does anyone know of a work around or if other versions of either product fix these problems?

h1.title Angular Router
 nav
   a(routerlink='/crisis-center', routerlinkactive='active') Crisis Center
   a(routerlink='/heroes', routerlinkactive='active') Heroes
   a(routerlink='/admin', routerlinkactive='active') Admin
   a(routerlink='/login', routerlinkactive='active') Login
   a([routerlink]="[{ outlets: { popup: ['compose'] } }]") Contact
 router-outlet
 router-outlet(name='popup')