问:
C# switch statement limitations - why?
When writing a switch statement, there appears to be two limitations on what you can switch on in case statements.

For example (and yes, I know, if you're doing this sort of thing it probably means your object-oriented (OO) architecture is iffy - this is just a contrived example!),

```<code>  Type t = typeof(int);

  switch (t) {

    case typeof(int):
      Console.WriteLine("int!");
      break;

    case typeof(string):
      Console.WriteLine("string!");
      break;

    default:
      Console.WriteLine("unknown!");
      break;
  }
</code>```

Here the switch() statement fails with 'A value of an integral type expected' and the case statements fail with 'A constant value is expected'.

Why are these restrictions in place, and what is the underlying justification? I don't see any reason why the switch statement has to succumb to static analysis only, and why the value being switched on has to be integral (that is,  primitive). What is the justification?

答:
This is my original post, which sparked some debate... because it is wrong:

The switch statement is not the same
  thing as a big if-else statement.
  Each case must be unique and evaluated
  statically.  The switch statement does
  a constant time branch regardless of
  how many cases you have.  The if-else
  statement evaluates each condition
  until it finds one that is true.

In fact, the C# switch statement is not always a constant time branch.

In some cases the compiler will use a CIL switch statement which is indeed a constant time branch using a jump table.  However, in sparse cases as pointed out by Ivan Hamilton the compiler may generate something else entirely.

This is actually quite easy to verify by writing various C# switch statements, some sparse, some dense, and looking at the resulting CIL with the ildasm.exe tool.

OwnerDisplayName: kronoz

Title: C# switch statement limitations - why?

Body:
When writing a switch statement, there appears to be two limitations on what you can switch on in case statements.

For example (and yes, I know, if you're doing this sort of thing it probably means your object-oriented (OO) architecture is iffy - this is just a contrived example!),

  Type t = typeof(int);

  switch (t) {

    case typeof(int):
      Console.WriteLine("int!");
      break;

    case typeof(string):
      Console.WriteLine("string!");
      break;

    default:
      Console.WriteLine("unknown!");
      break;
  }

Here the switch() statement fails with 'A value of an integral type expected' and the case statements fail with 'A constant value is expected'.

Why are these restrictions in place, and what is the underlying justification? I don't see any reason why the switch statement has to succumb to static analysis only, and why the value being switched on has to be integral (that is,  primitive). What is the justification?

LastEditorDisplayName: ecleel

OwnerDisplayName: Brian Ensink

LastEditorDisplayName: Brian Ensink


来源: stackexchange

问:
How do I encode HTTP GET query strings in Perl?
This question is somewhat related to What’s the simplest way to make a HTTP GET request in Perl?.

Before making the request via LWP::Simple I have a hash of query string components that I need to serialize/escape. What's the best way to encode the query string? It should take into account spaces and all the characters that need to be escaped in valid URIs. I figure it's probably in an existing package, but I'm not sure how to go about finding it.

```<code>use LWP::Simple;
my $base_uri = 'http://example.com/rest_api/';
my %query_hash = (spam => 'eggs', foo => 'bar baz');
my $query_string = urlencode(query_hash); # Part in question.
my $query_uri = "$base_uri?$query_string";
# http://example.com/rest_api/?spam=eggs&foo=bar+baz
$contents = get($query_uri);
</code>```

答: URI::Escape is the module you are probably thinking of.</p>

OwnerDisplayName: cdleary

ContentLicense: CC BY-SA 2.5

Body:
This question is somewhat related to What’s the simplest way to make a HTTP GET request in Perl?.

Before making the request via LWP::Simple I have a hash of query string components that I need to serialize/escape. What's the best way to encode the query string? It should take into account spaces and all the characters that need to be escaped in valid URIs. I figure it's probably in an existing package, but I'm not sure how to go about finding it.

use LWP::Simple;
my $base_uri = 'http://example.com/rest_api/';
my %query_hash = (spam => 'eggs', foo => 'bar baz');
my $query_string = urlencode(query_hash); # Part in question.
my $query_uri = "$base_uri?$query_string";
# http://example.com/rest_api/?spam=eggs&foo=bar+baz
$contents = get($query_uri);

LastEditorDisplayName: cdleary

OwnerDisplayName: Dmitriy

ContentLicense: CC BY-SA 3.0


问:
Clean approach to finding a folder's parent
I have this piece of code that searches for a folder given a starting directory. Once the folder is found I need the name of it's parent. The following piece of code works but it is terribly ugly. I have a flag, "sessionFound" to assist with breaking from nested foreach loops. The following works. I was hoping I could get some eyes on this and see if I could get some suggestions on how to make this less verbose and a bit more concise.

Thanks.

```<code>    private void SetProjectFolder(string sessionid)
        {

//IoC container gives the root directory to begin search.
            string[] supportDirs = Directory.GetDirectories(ApplicationContainer.SupportDirectory);
            bool sessionFound = false;

            foreach (string directory in supportDirs)
            {
                if (!sessionFound)
                {
                    foreach (string folder in Directory.GetDirectories(directory))
                    {
                        if (!sessionFound)
                        {
                            foreach (string productSubFolder in Directory.GetDirectories(folder))
                            {
                                if (productSubFolder.Contains(sessionid))
                                {
                                    _productName = Directory.GetParent(productSubFolder).Parent.Name;
                                    sessionFound = true;
                                    break;
                                }
                            }
                        }
                        else
                        {
                            break;
                        }
                    }
                }
                else
                {
                    break;
                }
            }
        }
</code>```

答:
Try this:</p>

```<code>private void SetProjectFolder(string sessionid)
    {
        //This will simulate the contains statement
        string searchPattern = string.Format("*{0}*", sessionid);
        string[] supportDirs = Directory.GetDirectories(ApplicationContainer.SupportDirectory, searchPattern);

        foreach (string filteredFolder in supportDirs)
        {
            _productName = Directory.GetParent(filteredFolder).Name;
            break;
        }
    }
</code>```

Body:
I have this piece of code that searches for a folder given a starting directory. Once the folder is found I need the name of it's parent. The following piece of code works but it is terribly ugly. I have a flag, "sessionFound" to assist with breaking from nested foreach loops. The following works. I was hoping I could get some eyes on this and see if I could get some suggestions on how to make this less verbose and a bit more concise.

Thanks.

    private void SetProjectFolder(string sessionid)
        {

//IoC container gives the root directory to begin search.
            string[] supportDirs = Directory.GetDirectories(ApplicationContainer.SupportDirectory);
            bool sessionFound = false;

            foreach (string directory in supportDirs)
            {
                if (!sessionFound)
                {
                    foreach (string folder in Directory.GetDirectories(directory))
                    {
                        if (!sessionFound)
                        {
                            foreach (string productSubFolder in Directory.GetDirectories(folder))
                            {
                                if (productSubFolder.Contains(sessionid))
                                {
                                    _productName = Directory.GetParent(productSubFolder).Parent.Name;
                                    sessionFound = true;
                                    break;
                                }
                            }
                        }
                        else
                        {
                            break;
                        }
                    }
                }
                else
                {
                    break;
                }
            }
        }

Body:
Try this:

private void SetProjectFolder(string sessionid)
    {
        //This will simulate the contains statement
        string searchPattern = string.Format("*{0}*", sessionid);
        string[] supportDirs = Directory.GetDirectories(ApplicationContainer.SupportDirectory, searchPattern);

        foreach (string filteredFolder in supportDirs)
        {
            _productName = Directory.GetParent(filteredFolder).Name;
            break;
        }
    }


问:
Find first negative number and prepend a zero
I want to insert a 0 before the first occurrence of - followed by a number.

I have tried the below simple code.

```<code>$formula = '[ (((-594 - 0) )/ 55032411) *244 ]';
preg_match('/^-?\d+(\.\d+)?$/', $formula, $match);

print_r($match);
$result = str_replace($match[0],'0'.$match[0],$formula);
echo $result;
exit;
</code>```

I want the below result.

```<code>[ (((0-594 - 0) )/ 55032411) *244 ]
</code>```

答:
Since I'm a firm believer that Regex != 42 I made a non regex that may work.

In short, it finds the first - in the string and saves the position.

Anything before this - is $part, but I use str_replace to remove all [() and space.

Then if this part is empty then there is no number before the first - so add the 0.

It's a bit complex but since it does not use regex it may be faster. But if you use other signs than [() and space in the start of calculation you need to add them in the arrays to remove.

Now that I think about it maybe +-/* should be there.

```<code> $formula = '[ (((-594 - 0) )/ 55032411) *244 ]';
 $pos = strpos($formula, "-");
 $part = str_replace(array("(",")","["," "), array("","","",""),substr($formula, 0, $pos));

If($part ==""){
     $formula = substr($formula, 0,$pos) ."0". substr($formula, $pos);
 }

Echo $formula;
</code>```

I admit that it is complex, but I wanted to try to make a non regex solution.

https://3v4l.org/TaSjr

Body:
I want to insert a 0 before the first occurrence of - followed by a number.

I have tried the below simple code.

$formula = '[ (((-594 - 0) )/ 55032411) *244 ]';
preg_match('/^-?\d+(\.\d+)?$/', $formula, $match);

print_r($match);
$result = str_replace($match[0],'0'.$match[0],$formula);
echo $result;
exit;

I want the below result.

[ (((0-594 - 0) )/ 55032411) *244 ]

Body:
Since I'm a firm believer that Regex != 42 I made a non regex that may work.

In short, it finds the first - in the string and saves the position.

Anything before this - is $part, but I use str_replace to remove all [() and space.

Then if this part is empty then there is no number before the first - so add the 0.

It's a bit complex but since it does not use regex it may be faster. But if you use other signs than [() and space in the start of calculation you need to add them in the arrays to remove.

Now that I think about it maybe +-/* should be there.

 $formula = '[ (((-594 - 0) )/ 55032411) *244 ]';
 $pos = strpos($formula, "-");
 $part = str_replace(array("(",")","["," "), array("","","",""),substr($formula, 0, $pos));

If($part ==""){
     $formula = substr($formula, 0,$pos) ."0". substr($formula, $pos);
 }

Echo $formula;

I admit that it is complex, but I wanted to try to make a non regex solution.

https://3v4l.org/TaSjr


问:
Palindrome check in Javascript
I have the following:

```<code>function checkPalindrom(palindrom)
{

    for( var i = palindrom.length; i > 0; i-- )
    {
        if( palindrom[i] = palindrom.charAt(palindrom.length)-1 )
        {
            document.write('the word is palindrome.');
        }else{
            document.write('the word is not palindrome!');
        }
    }
}
checkPalindrom('wordthatwillbechecked');
</code>```

What is wrong with my code? I want to check if the word is a palindrome.

答:
Writing the code for checking palindromes following the best practices of JavaScript:

(function(){
 'use strict';

 var testStringOne = "Madam";
 var testStringTwo = "testing";
 var testNull = null;
 var testUndefined;

 console.log(checkIfPalindrome(testStringOne));
 console.log(checkIfPalindrome(testStringTwo));
 console.log(checkIfPalindrome(testNull));
 console.log(checkIfPalindrome(testUndefined));

 function checkIfPalindrome(testStringOne){

  if(!testStringOne){
   return false;
  }

  var testArrayOne = testStringOne.toLowerCase().split("");
  testArrayOne.reverse();

  if(testArrayOne.toString() == testStringOne.toLowerCase().split("").toString()){
   return true;
  }else{
   return false;
  }
 }

})();```

ContentLicense: CC BY-SA 4.0

Title: Palindrome check in Javascript

Body:
I have the following:

function checkPalindrom(palindrom)
{

    for( var i = palindrom.length; i > 0; i-- )
    {
        if( palindrom[i] = palindrom.charAt(palindrom.length)-1 )
        {
            document.write('the word is palindrome.');
        }else{
            document.write('the word is not palindrome!');
        }
    }
}
checkPalindrom('wordthatwillbechecked');

What is wrong with my code? I want to check if the word is a palindrome.


问:
How to merge two PunktSentenceTokenizer pickle files?
I have trained the PunktSentenceTokenizer in NLTK and obtained a pickle file "learnt.pickle":

```<code>ccopy_reg
_reconstructor
p0
(cnltk.tokenize.punkt
PunktSentenceTokenizer
p1
c__builtin__
object
p2
Ntp3
Rp4
(dp5
S'_Token'
p6
cnltk.tokenize.punkt
PunktToken
p7
sS'_lang_vars'
p8
g0
(cnltk.tokenize.punkt
PunktLanguageVars
p9
g2
Ntp10
Rp11
I1
bsS'_params'
p12
g0
(cnltk.tokenize.punkt
PunktParameters
p13
g2
Ntp14
Rp15
(dp16
S'sent_starters'
p17
c__builtin__
set
p18
((lp19
tp20
Rp21
sS'collocations'
p22
g18
((lp23
tp24
Rp25
sS'abbrev_types'
p26
g18
((lp27
Vago
p28
aVgca
p29
aVe.g`
</code>```

I have another pickle file "english.pickle":

```<code>ccopy_reg
_reconstructor
p0
(cnltk.tokenize.punkt
PunktSentenceTokenizer
p1
c__builtin__
object
p2
Ntp3
Rp4
(dp5
S'_Token'
p6
cnltk.tokenize.punkt
PunktToken
p7
sS'_lang_vars'
p8
g0
(cnltk.tokenize.punkt
PunktLanguageVars
p9
g2
Ntp10
Rp11
I1
bsS'_params'
p12
g0
(cnltk.tokenize.punkt
PunktParameters
p13
g2
Ntp14
Rp15
(dp16
S'sent_starters'
p17
c__builtin__
set
p18
((lp19
Vamong
p20
aVsince
p21
aVthey
p22
aVindeed
p23
aVsome
p24
aVsales
p25
aVin
p26
aVmoreover
p27
aVyet`
</code>```

I want to merge these to form a single .pickle file (which must be usuable with the tokenizer of the PunktSentenceTokenizer).

I'm using the following code:

```<code>import pickle
my_dict_final = {}
with open('english.pickle', 'rb') as f:
     my_dict_final.update(pickle.load(f))
 with open('learnt.pickle', 'rb') as f:
     my_dict_final.update(pickle.load(f))
out = open("finaldict.pickle","wb")
pickle.dump(my_dict_final, out)
out.close()
</code>```

But it shows this error:

TypeError: 'PunkSentenceTokenizer' object is not iterable.

I have no idea what this means (I'm not very good with programming)....But I really need a solution....

答:
You can't "merge two pickle files". Pickling is just a file ("serialization") format, so what you can do with the contents is entirely dependent on the structure of the objects you pickled. In your case, you seem to assume that the (un)pickled objects are dictionaries; but in fact they are PunktSentenceTokenizer objects, including their internal frequency tables. That accounts for the TypeError.

The only viable option would be to study the internals of the PunktSentenceTokenizer, and find out what needs to be merged and whether there is even any meaningful sense of merging two models. But for your (apparent) intended use, I recommend simply concatenating your custom training corpus to a large corpus of normally-punctuated English (e.g., the gutenberg corpus or any other collection of plain-text files), and training a single sentence detection model on the combined data.

Body:
I have trained the PunktSentenceTokenizer in NLTK and obtained a pickle file "learnt.pickle":

ccopy_reg
_reconstructor
p0
(cnltk.tokenize.punkt
PunktSentenceTokenizer
p1
c__builtin__
object
p2
Ntp3
Rp4
(dp5
S'_Token'
p6
cnltk.tokenize.punkt
PunktToken
p7
sS'_lang_vars'
p8
g0
(cnltk.tokenize.punkt
PunktLanguageVars
p9
g2
Ntp10
Rp11
I1
bsS'_params'
p12
g0
(cnltk.tokenize.punkt
PunktParameters
p13
g2
Ntp14
Rp15
(dp16
S'sent_starters'
p17
c__builtin__
set
p18
((lp19
tp20
Rp21
sS'collocations'
p22
g18
((lp23
tp24
Rp25
sS'abbrev_types'
p26
g18
((lp27
Vago
p28
aVgca
p29
aVe.g`

I have another pickle file "english.pickle":

ccopy_reg
_reconstructor
p0
(cnltk.tokenize.punkt
PunktSentenceTokenizer
p1
c__builtin__
object
p2
Ntp3
Rp4
(dp5
S'_Token'
p6
cnltk.tokenize.punkt
PunktToken
p7
sS'_lang_vars'
p8
g0
(cnltk.tokenize.punkt
PunktLanguageVars
p9
g2
Ntp10
Rp11
I1
bsS'_params'
p12
g0
(cnltk.tokenize.punkt
PunktParameters
p13
g2
Ntp14
Rp15
(dp16
S'sent_starters'
p17
c__builtin__
set
p18
((lp19
Vamong
p20
aVsince
p21
aVthey
p22
aVindeed
p23
aVsome
p24
aVsales
p25
aVin
p26
aVmoreover
p27
aVyet`

I want to merge these to form a single .pickle file (which must be usuable with the tokenizer of the PunktSentenceTokenizer).

I'm using the following code:

import pickle
my_dict_final = {}
with open('english.pickle', 'rb') as f:
     my_dict_final.update(pickle.load(f))
 with open('learnt.pickle', 'rb') as f:
     my_dict_final.update(pickle.load(f))
out = open("finaldict.pickle","wb")
pickle.dump(my_dict_final, out)
out.close()

But it shows this error:

TypeError: 'PunkSentenceTokenizer' object is not iterable.

I have no idea what this means (I'm not very good with programming)....But I really need a solution....


问:
Weird/unreadable returned json encoding read by QByteArray to post request
I try to scrap a website by requesting it api with a post request. The returned data in json has however a unreadble encoding, like this :

à^!ÚÄÆ›>Ã    ñ‹yÖž¥³ ¤hóúôë¼zC

The Content-Type of the request is "application/json; charset=utf-8". Someone has a idea about this weird encoding ? A priori the request works, else there is an explicit error. The same request with the navigator has a perfectly readable response. I'm using Qt, with QNetworkRequest. The answer goes in a QByteArray I read with toStdString(). If I try to reformat the QByteArray in QJsonDocument or QJsonObject before to read it, there is nothing in the answer.
Thank you by advance

答:
Check the QJsonDocument class, and use the static function to construct a JsonDocument by using a bytearray with UTF-8 format.

```<code>const QByteArray dataFromServer;
QJsonParseError er;
const QJsonDocument doc = QJsonDocument::fromJson(json, &er);
if (er.error != QJsonParseError::NoError) {
   return false;
}
</code>```

Then, take the QJsonObject, and check if it's a list. You can iterate over the list or acces to a given value by using the key:

```<code>const QJsonObject object = doc.object();
const QString value = object.value(QLatin1String("My_key");
const std::string stdValue = value.toStdString();
</code>```

Body:
Check the QJsonDocument class, and use the static function to construct a JsonDocument by using a bytearray with UTF-8 format.

const QByteArray dataFromServer;
QJsonParseError er;
const QJsonDocument doc = QJsonDocument::fromJson(json, &er);
if (er.error != QJsonParseError::NoError) {
   return false;
}

Then, take the QJsonObject, and check if it's a list. You can iterate over the list or acces to a given value by using the key:

const QJsonObject object = doc.object();
const QString value = object.value(QLatin1String("My_key");
const std::string stdValue = value.toStdString();


问:
Angular 4 Headers not passing
I have a REST-API to contact, it works on swagger.
Now I try to call it with my Angular 4 app.
I get the error:

```<code>  XMLHttpRequest cannot load
  "baseURL"/company/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access
</code>```

When I look at the call, I see that it doesn't pass any headers (also not the token), but I actually added them to my request in my Angular 4 code:

```<code>getCompanies(): Observable<Company[]> {
   let tokenobject =JSON.parse(sessionStorage.getItem('current_user'));
   let token = tokenobject.token;
   let headers = new Headers({ 'Access-Control-Allow-Origin' : 'http://localhost:4200','Authorization': token });
   let options = new RequestOptions({ headers: headers });
   return this.http.get(this.url + this.path, options)
          .map(this.extractData)
          .catch(this.handleError);
}
</code>```

Is there something I forgot or did wrong?

答:
Its a CORS issue. You need to enable Cross Origin Requests on your API end if you are going to make cross origin requests.

Read more about CORS here:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
https://www.maxcdn.com/one/visual-glossary/cors/

Also read this thread about CORS issue with Angular JS: AngularJS CORS Issues

Title: Angular 4 Headers not passing

Body:
I have a REST-API to contact, it works on swagger.
Now I try to call it with my Angular 4 app.
I get the error:

  XMLHttpRequest cannot load
  "baseURL"/company/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access

When I look at the call, I see that it doesn't pass any headers (also not the token), but I actually added them to my request in my Angular 4 code:

getCompanies(): Observable<Company[]> {
   let tokenobject =JSON.parse(sessionStorage.getItem('current_user'));
   let token = tokenobject.token;
   let headers = new Headers({ 'Access-Control-Allow-Origin' : 'http://localhost:4200','Authorization': token });
   let options = new RequestOptions({ headers: headers });
   return this.http.get(this.url + this.path, options)
          .map(this.extractData)
          .catch(this.handleError);
}

Is there something I forgot or did wrong?


问:
Run rails application with apache and passenger on ubuntu
I have got some source code or rails project and I need to to run in on local machine. Actually on Ubuntu virtual machine.

I am not sure what all I need to install and configure in order to run it locally. Is there a standard way to find it all throughout source code?

I have figure out that application is using SQL Lite in development environment and MySQL in production environment.

from config/database.rb

```<code># MySQL.  Versions 4.1 and 5.0 are recommended.
#
# Install the MySQL driver:
#   gem install mysql2
#
# And be sure to use new-style password hashing:
#   http://dev.mysql.com/doc/refman/5.0/en/old-client.html
development:
  adapter: sqlite3
  database: db/development.sqlite3
  pool: 5
  timeout: 5000

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  adapter: sqlite3
  database: db/test.sqlite3
  pool: 5
  timeout: 5000

staging:
  adapter: mysql2
  database: appname_staging
  username: rails
  password: somepassword
  host: localhost

production:
  adapter: mysql2
  database: appname_production
  username: rails
  password: somepassword
  host: localhost
</code>```

Also I have set proper version of ruby and rails and install it with rvm. I know that the versions are correct because of .ruby-gemset .ruby-version files. Also I did bundle install and all gems from Gemfile installed successfully.

ruby -v => ruby 1.9.3p551
rails -v => 3.2.13

apache2 -v => Server version: Apache/2.4.7 (Ubuntu)
              Server built:   Oct 14 2015 14:18:49

mysql -V => mysql  Ver 14.14 Distrib 5.5.46,
            for debian-linux-gnu (i686) using readline 6.3

lsb_release -a => No LSB modules are available.
                  Distributor ID:   Ubuntu
                  Description:  Ubuntu 14.04.3 LTS
                  Release:  14.04
                  Codename: trusty

This is pretty much where my expertise stops. I am not sure  which web server application should use. Is it predefined in source code somewhere?

I spot that there is apache, passenger and moonshine are used.

from app/manifests/application_manifest.rb

```<code># The default_stack recipe install Rails, Apache, Passenger, the database from
  # database.yml, Postfix, Cron, logrotate and NTP. See lib/moonshine/manifest/rails.rb
  # for details. To customize, remove this recipe and specify the components you want.
  recipe :default_stack
  recipe :ssh
</code>```

I also not sure what is exactly purpose of each of these individually.

How apache as web server can recognize and interpret ruby code?

I would be happy if I could host any rails app on apache. I have created some very simple app and tries these steps https://www.linode.com/docs/websites/ror/ruby-on-rails-with-apache-on-ubuntu-10-04-lucid but it always opens default apache web page.

I am not usre where to start. I just have a bunch of questions adn a lot of confustion. I do not understand how the ROR on apache actually works.

Is the passenger the thing upon apache that interprets ruby code?

I show that nginx is alternative for passenger but it is also alternative for apache, it confuses me even more.

Thanks for any help.

答:
As you stated that you use sqlite database so add gem 'sqlite3' in Gemfile and then run bundle install.

Then you have to create database and run all migrations to add tables.

Command:

```<code>rake db:create
rake db:migrate
</code>```

Next, start server

Command:

```<code>rails server
</code>```

Body:
I have got some source code or rails project and I need to to run in on local machine. Actually on Ubuntu virtual machine.

I am not sure what all I need to install and configure in order to run it locally. Is there a standard way to find it all throughout source code?

I have figure out that application is using SQL Lite in development environment and MySQL in production environment.

from config/database.rb

# MySQL.  Versions 4.1 and 5.0 are recommended.
#
# Install the MySQL driver:
#   gem install mysql2
#
# And be sure to use new-style password hashing:
#   http://dev.mysql.com/doc/refman/5.0/en/old-client.html
development:
  adapter: sqlite3
  database: db/development.sqlite3
  pool: 5
  timeout: 5000

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  adapter: sqlite3
  database: db/test.sqlite3
  pool: 5
  timeout: 5000

staging:
  adapter: mysql2
  database: appname_staging
  username: rails
  password: somepassword
  host: localhost

production:
  adapter: mysql2
  database: appname_production
  username: rails
  password: somepassword
  host: localhost

Also I have set proper version of ruby and rails and install it with rvm. I know that the versions are correct because of .ruby-gemset .ruby-version files. Also I did bundle install and all gems from Gemfile installed successfully.

ruby -v => ruby 1.9.3p551
rails -v => 3.2.13

apache2 -v => Server version: Apache/2.4.7 (Ubuntu)
              Server built:   Oct 14 2015 14:18:49

mysql -V => mysql  Ver 14.14 Distrib 5.5.46,
            for debian-linux-gnu (i686) using readline 6.3

lsb_release -a => No LSB modules are available.
                  Distributor ID:   Ubuntu
                  Description:  Ubuntu 14.04.3 LTS
                  Release:  14.04
                  Codename: trusty

This is pretty much where my expertise stops. I am not sure  which web server application should use. Is it predefined in source code somewhere?

I spot that there is apache, passenger and moonshine are used.

from app/manifests/application_manifest.rb

# The default_stack recipe install Rails, Apache, Passenger, the database from
  # database.yml, Postfix, Cron, logrotate and NTP. See lib/moonshine/manifest/rails.rb
  # for details. To customize, remove this recipe and specify the components you want.
  recipe :default_stack
  recipe :ssh

I also not sure what is exactly purpose of each of these individually.

How apache as web server can recognize and interpret ruby code?

I would be happy if I could host any rails app on apache. I have created some very simple app and tries these steps https://www.linode.com/docs/websites/ror/ruby-on-rails-with-apache-on-ubuntu-10-04-lucid but it always opens default apache web page.

I am not usre where to start. I just have a bunch of questions adn a lot of confustion. I do not understand how the ROR on apache actually works.

Is the passenger the thing upon apache that interprets ruby code?

I show that nginx is alternative for passenger but it is also alternative for apache, it confuses me even more.

Thanks for any help.

Body:
As you stated that you use sqlite database so add gem 'sqlite3' in Gemfile and then run bundle install.

Then you have to create database and run all migrations to add tables.

Command:

rake db:create
rake db:migrate

Next, start server

Command:

rails server


问:
Passing data From ListView Item to next Form
I know how to send data from an Entry, Label to the next Form , but how can i do this with a ListView.
I want a simple direct approach.

My XAML code :

```<code><ListView x:Name="MyClientslistView" HasUnevenRows="true"  ItemTapped="OnSalesReport">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>

                            <StackLayout Orientation="Vertical" VerticalOptions="Center"  Margin="5" >
                                <Label Text="{Binding client_name}" TextColor="#A7A392" />
                                <Label Text="{Binding client_address}" TextColor="Black" />
                                <Label Text="{Binding client_phone}"  TextColor="Black" />
                                <Label Text="{Binding client_email}"  TextColor="Black" />
                                <Label Text="{Binding AssignStatus}"  TextColor="Black" />
                                <Label Text="{Binding assignmentComments}"  TextColor="Black" />
                            </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
</code>```

I already have loaded data from JSON to the ListView , now currently i want to move each ID on he Item to the Next Form , how can i tackle that ?

答:
Sorry for the poor english

You can have your entire item at your event handler private void OnSalesReport(object sender, ItemTappedEventArgs e) through e.Item.
You must do var item = ((YourTypeClassItem)e.Item); then you get things like item.client_name and probably item.client_id.

I hope it helps you.

Body:
I know how to send data from an Entry, Label to the next Form , but how can i do this with a ListView.
I want a simple direct approach.

My XAML code :

<ListView x:Name="MyClientslistView" HasUnevenRows="true"  ItemTapped="OnSalesReport">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>

                            <StackLayout Orientation="Vertical" VerticalOptions="Center"  Margin="5" >

                            </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

I already have loaded data from JSON to the ListView , now currently i want to move each ID on he Item to the Next Form , how can i tackle that ?


问:
Most efficient way to reverse a numpy array
Believe it or not, after profiling my current code, the repetitive operation of numpy array reversion ate a giant chunk of the running time. What I have right now is the common view-based method:

```<code>reversed_arr = arr[::-1]
</code>```

Is there any other way to do it more efficiently, or is it just an illusion from my obsession with unrealistic numpy performance?

答:
a[::-1]
```
<p>only creates a view, so it's a constant-time operation (and as such doesn't take longer as the array grows). If you need the array to be contiguous (for example because you're performing many vector operations with it), <code>ascontiguousarray</code> is about as fast as <code>flipud</code>/<code>fliplr</code>:</p>
<p><img src="https://i.stack.imgur.com/QTJga.png" alt="enter image description here" /></p>
<hr />
<p>Code to generate the plot:</p>
<pre class="lang-py prettyprint-override"><code>import numpy
import perfplot

perfplot.show(
    setup=lambda n: numpy.random.randint(0, 1000, n),
    kernels=[
        lambda a: a[::-1],
        lambda a: numpy.ascontiguousarray(a[::-1]),
        lambda a: numpy.fliplr([a])[0],
    ],
    labels=["a[::-1]", "ascontiguousarray(a[::-1])", "fliplr"],
    n_range=[2 ** k for k in range(25)],
    xlabel="len(a)",
)
</code>```

Body:
Believe it or not, after profiling my current code, the repetitive operation of numpy array reversion ate a giant chunk of the running time. What I have right now is the common view-based method:

reversed_arr = arr[::-1]

Is there any other way to do it more efficiently, or is it just an illusion from my obsession with unrealistic numpy performance?

Body:
a[::-1]

only creates a view, so it's a constant-time operation (and as such doesn't take longer as the array grows). If you need the array to be contiguous (for example because you're performing many vector operations with it), ascontiguousarray is about as fast as flipud/fliplr:

Code to generate the plot:

import numpy
import perfplot

perfplot.show(
    setup=lambda n: numpy.random.randint(0, 1000, n),
    kernels=[
        lambda a: a[::-1],
        lambda a: numpy.ascontiguousarray(a[::-1]),
        lambda a: numpy.fliplr([a])[0],
    ],
    labels=["a[::-1]", "ascontiguousarray(a[::-1])", "fliplr"],
    n_range=[2 ** k for k in range(25)],
    xlabel="len(a)",
)


问:
Trigger a MATLAB function without opening MATLAB GUI
I have written a MATLAB function which can send an e-mail. I can call this function from the command prompt, using the following command: </p>

```<code>"C:\Program Files\MATLAB\R2017a\bin\matlab.exe"  -r "nameofthefunction;"
</code>```

<p>When I do this, the MATLAB application opens, and then the function is executed. What I want to do is write a command which would trigger the function (i.e send the e-mail), without opening the MATLAB application. </p>

答:
To run a MATLAB function you need to use either (1) the MATLAB environment or you need to (2) convert it to a standalone component. The first is obviously using the MATLAB GUI, as you call it, but maybe it is an option to close it down after using the function

```<code>"C:\Program Files\MATLAB\R2017a\bin\matlab.exe"  -r "nameofthefunction; quit;"
</code>```

For (2) look at the MATLAB Compiler and check whether your function can be converted into a standalone component.

Body:
I have written a MATLAB function which can send an e-mail. I can call this function from the command prompt, using the following command:

"C:\Program Files\MATLAB\R2017a\bin\matlab.exe"  -r "nameofthefunction;"

When I do this, the MATLAB application opens, and then the function is executed. What I want to do is write a command which would trigger the function (i.e send the e-mail), without opening the MATLAB application.

Body:
To run a MATLAB function you need to use either (1) the MATLAB environment or you need to (2) convert it to a standalone component. The first is obviously using the MATLAB GUI, as you call it, but maybe it is an option to close it down after using the function

"C:\Program Files\MATLAB\R2017a\bin\matlab.exe"  -r "nameofthefunction; quit;"

For (2) look at the MATLAB Compiler and check whether your function can be converted into a standalone component.


问:
How do I pass reference to active driver between classes
My problem is that when firstname is suppose to be set by the driver in the FetchName method I get an error message that the driver is null. Can I pass the active driver instance in some way so I can continue fetch data?

```<code>[TestFixture]
public class TestBase
{
    protected IWebDriver driverChrome;

    [SetUp]
    public void Setup()
    {
        driverChrome = new ChromeDriver();
    }

    [TearDown]
    public void CleanSite()
    {
        driverChrome.Quit();
    }

}
</code>```

Class "Tests" where I create all my [test] methods.

```<code>public void tests: Testbase
{
        [Test]
        public void testmethods()
        {
            string blabla = driverChrome.FindElement(By.id("dsd")).Text;
            Reuse.FetchName(out string firstname, out string lastname);
            Assert.isTrue(firstname.equals(lastname));
        }
}
</code>```

One Class "Reuse" where I have methods that the [test] methods will use multiple times.

```<code>public class Reuse: Testbase
{
    [Test]
    public void FetchName(out string firstname, out string lastname)
    {
            firstname = driverChrome.FindElement(By.XPath("/html/body/div[2]/table/tbody[last()]/tr/td[2]/div")).Text;
            lastname = driverChrome.FindElement(By.XPath("/html/body/div[2]/table/tbody[last()]/tr/td[2]/div")).Text;
    }
}
</code>```

答:
Reuse class is not a test case. When you add attribute [Test] to the method, the method should contains an assertion. So Reuse should not inherit from Testbase.

If you want to have a class that contains multiple actions, it should be static class.

WebDriver is a standalone process. You can use multiple classes or multiple process to access it. They all will get the same WebDriver.

The example below shows how to change the Reuse class and how to use it.

```<code>public static class Reuse
{
    public static IWebDriver driverChrome;
    public static void FetchName(out string firstname, out string lastname)
    {
            firstname = driverChrome.FindElement(By.XPath("/html/body/div[2]/table/tbody[last()]/tr/td[2]/div")).Text;
            lastname = driverChrome.FindElement(By.XPath("/html/body/div[2]/table/tbody[last()]/tr/td[2]/div")).Text;
    }
}
</code>```

You can call it like this.

```<code>public void tests: Testbase
{
    [Test]
    public void testmethods()
    {
        string blabla = driverChrome.FindElement(By.id("dsd")).Text;
        Reuse.driverChrome = driverChrome;
        Reuse.FetchName(out string firstname, out string lastname);
        Assert.isTrue(firstname.equals(lastname));
    }
</code>```

}

Body:
My problem is that when firstname is suppose to be set by the driver in the FetchName method I get an error message that the driver is null. Can I pass the active driver instance in some way so I can continue fetch data?

[TestFixture]
public class TestBase
{
    protected IWebDriver driverChrome;

    [SetUp]
    public void Setup()
    {
        driverChrome = new ChromeDriver();
    }

    [TearDown]
    public void CleanSite()
    {
        driverChrome.Quit();
    }

}

Class "Tests" where I create all my [test] methods.

public void tests: Testbase
{
        [Test]
        public void testmethods()
        {
            string blabla = driverChrome.FindElement(By.id("dsd")).Text;
            Reuse.FetchName(out string firstname, out string lastname);
            Assert.isTrue(firstname.equals(lastname));
        }
}

One Class "Reuse" where I have methods that the [test] methods will use multiple times.

public class Reuse: Testbase
{
    [Test]
    public void FetchName(out string firstname, out string lastname)
    {
            firstname = driverChrome.FindElement(By.XPath("/html/body/div[2]/table/tbody[last()]/tr/td[2]/div")).Text;
            lastname = driverChrome.FindElement(By.XPath("/html/body/div[2]/table/tbody[last()]/tr/td[2]/div")).Text;
    }
}

Body:
Reuse class is not a test case. When you add attribute [Test] to the method, the method should contains an assertion. So Reuse should not inherit from Testbase.

If you want to have a class that contains multiple actions, it should be static class.

WebDriver is a standalone process. You can use multiple classes or multiple process to access it. They all will get the same WebDriver.

The example below shows how to change the Reuse class and how to use it.

public static class Reuse
{
    public static IWebDriver driverChrome;
    public static void FetchName(out string firstname, out string lastname)
    {
            firstname = driverChrome.FindElement(By.XPath("/html/body/div[2]/table/tbody[last()]/tr/td[2]/div")).Text;
            lastname = driverChrome.FindElement(By.XPath("/html/body/div[2]/table/tbody[last()]/tr/td[2]/div")).Text;
    }
}

You can call it like this.

public void tests: Testbase
{
    [Test]
    public void testmethods()
    {
        string blabla = driverChrome.FindElement(By.id("dsd")).Text;
        Reuse.driverChrome = driverChrome;
        Reuse.FetchName(out string firstname, out string lastname);
        Assert.isTrue(firstname.equals(lastname));
    }

}


问:
How to test POST web service call that send data in Custom Object?
I am using Retrofit for REST API calls. I want to check some APIs in Postman  but some Web service APIs send input data in Custom Object form.Unable to find how to test it in Postman or online .

Example :

```<code>@POST("/InsertBusinessInfo")
Call<Boolean> postBusinessInfo(@Body BusinessInfo businessRequest);
</code>```

This BusinessInfo pojo class with some params with get/set methods

```<code>public class BusinessInfo {

    public String getFirstName() {
        return FirstName;
    }

    public void setFirstName(String firstName) {
        FirstName = firstName;
    }

    public String getLastName() {
        return LastName;
    }

    public void setLastName(String lastName) {
        LastName = lastName;
    }
}
</code>```

How to test this in Postman. Is it the same as 1 by 1 params inserted in Body? Can anyone explain it?

答:
In Postman open a request and from tabs below URL Select Body

from the options below select raw

Now mostly the object is serialized in to JSON, so get a JSON for your object

```<code>{"FirstName":"name...", "LastName":"name2..." ...}
</code>```

(filled with data) and paste it in the large text area below and click send

Body:
I am using Retrofit for REST API calls. I want to check some APIs in Postman  but some Web service APIs send input data in Custom Object form.Unable to find how to test it in Postman or online .

Example :

@POST("/InsertBusinessInfo")
Call<Boolean> postBusinessInfo(@Body BusinessInfo businessRequest);

This BusinessInfo pojo class with some params with get/set methods

public class BusinessInfo {

    public String getFirstName() {
        return FirstName;
    }

    public void setFirstName(String firstName) {
        FirstName = firstName;
    }

    public String getLastName() {
        return LastName;
    }

    public void setLastName(String lastName) {
        LastName = lastName;
    }
}

How to test this in Postman. Is it the same as 1 by 1 params inserted in Body? Can anyone explain it?

Body:
In Postman open a request and from tabs below URL Select Body

from the options below select raw

Now mostly the object is serialized in to JSON, so get a JSON for your object

{"FirstName":"name...", "LastName":"name2..." ...}

(filled with data) and paste it in the large text area below and click send


问:
RxJava2 subscribe stops observing after a while but continues when flowable completes
I'm having a hard time understanding the behaviour of the following code sample;

    Flowable<String> f = Flowable.just(1)
            .flatMap(it -> Flowable.create(e -> {

                for(int i = 1; i < 1001; ++i) {
                    log.info("Emitting: " + i);
                    if(i % 10 == 0) {
                        Thread.sleep(1000);
                    }
                    e.onNext(i);
                }

                e.onComplete();
            }, BackpressureStrategy.BUFFER))
            .map(String::valueOf)
            .subscribeOn(Schedulers.io())
            .observeOn(Schedulers.newThread());

    f.subscribe(val -> {
        Thread.sleep(100);
        log.info("Observing: " + val);
    });

    Thread.sleep(1000000);
```

The code works OK until 128 items are observed by the subscribe call. Emit and observe are in parallel. But after that, Flowable continues to emit items (which are queued somewhere obviously) but no item is observed until all 1000 of items are emitted. After all 1000 items are emitted, then the rest of items (> 128) are observed at once.

This looks to be related to backpressure bufferSize of 128 but still I would expect the emit and observe to be in parallel for the whole 1000 items, because observer is obviously not slower than the emitter. Is there something I'm missing here? What should I do to fix the code?

答:
This is due to a same pool deadlock between create and subscribeOn:

If there is a create(FlowableOnSubscribe, BackpressureStrategy) type source up in the chain, it is recommended to use subscribeOn(scheduler, false) instead to avoid same-pool deadlock because requests may pile up behind a eager/blocking emitter.

```<code>//...
.subscribeOn(Schedulers.io(), false)
//...
</code>```

Edit:

I tried the original example (plus your suggested fix) by replacing Flowable.create with a Flowable.range but I didn't encounter a problem. Can you give an example when problems may occur?

```<code>Flowable.range(1, 10)
    .subscribeOn(Schedulers.io(), false)
    .doOnNext(v -> System.out.println(Thread.currentThread().getName()))
    .observeOn(Schedulers.single(), false, 1)
    .blockingSubscribe();
</code>```

This initially prints RxCachedThreadScheduler-1 then RxSingleScheduler-1 9 times because observeOn's replenishment request will run on the single scheduler instead of routed back to the io scheduler. Try this with subscribeOn true.

Body:
I'm having a hard time understanding the behaviour of the following code sample;

    Flowable<String> f = Flowable.just(1)
            .flatMap(it -> Flowable.create(e -> {

                for(int i = 1; i < 1001; ++i) {
                    log.info("Emitting: " + i);
                    if(i % 10 == 0) {
                        Thread.sleep(1000);
                    }
                    e.onNext(i);
                }

                e.onComplete();
            }, BackpressureStrategy.BUFFER))
            .map(String::valueOf)
            .subscribeOn(Schedulers.io())
            .observeOn(Schedulers.newThread());

    f.subscribe(val -> {
        Thread.sleep(100);
        log.info("Observing: " + val);
    });

    Thread.sleep(1000000);

The code works OK until 128 items are observed by the subscribe call. Emit and observe are in parallel. But after that, Flowable continues to emit items (which are queued somewhere obviously) but no item is observed until all 1000 of items are emitted. After all 1000 items are emitted, then the rest of items (> 128) are observed at once.

This looks to be related to backpressure bufferSize of 128 but still I would expect the emit and observe to be in parallel for the whole 1000 items, because observer is obviously not slower than the emitter. Is there something I'm missing here? What should I do to fix the code?

Body:
This is due to a same pool deadlock between create and subscribeOn:

If there is a create(FlowableOnSubscribe, BackpressureStrategy) type source up in the chain, it is recommended to use subscribeOn(scheduler, false) instead to avoid same-pool deadlock because requests may pile up behind a eager/blocking emitter.

//...
.subscribeOn(Schedulers.io(), false)
//...

Edit:

I tried the original example (plus your suggested fix) by replacing Flowable.create with a Flowable.range but I didn't encounter a problem. Can you give an example when problems may occur?

Flowable.range(1, 10)
    .subscribeOn(Schedulers.io(), false)
    .doOnNext(v -> System.out.println(Thread.currentThread().getName()))
    .observeOn(Schedulers.single(), false, 1)
    .blockingSubscribe();

This initially prints RxCachedThreadScheduler-1 then RxSingleScheduler-1 9 times because observeOn's replenishment request will run on the single scheduler instead of routed back to the io scheduler. Try this with subscribeOn true.


问:
Resize MFC grid control to fit in dialog?
I have created an MFC grid control (Code Project MFC Grid control 2.27) in an MFC dialog MyDlg (C++, VS2015, 64-bit Windows 7). The MyDlg.h file contains

```<code>CGridCtrl gridCtrl;
</code>```

and the resource editor was used to add a custom control of type MFCGridCtrl. In MyDlg.cpp, I am subclassing the control with

```<code>DDX_Control(pDX, IDC_ComponentRatios, gridCtrl);
</code>```

In MyDlg::OnInitDialog, I set the number of rows and columns with

```<code>gridCtrl.SetColumnCount(2);
gridCtrl.SetRowCount(2);
gridCtrl.EnableWindow(TRUE);
</code>```

What I get is the 2 x 2 grid I expect, but the size of the custom control does not match the size of the grid.

The custom control's width is wrong, because setting the column count appears to be leaving space for a scroll bar, which is unnecessary.

The height is unchanged, which is wrong because the custom control is sized for 8 rows, and I'm only using 2 in this example (the actual number of rows required is variable).

How can I get the grid to fill the width of the custom control, and to resize the height of that control to match?

答:
As far as I understand you question you expect that the grid resizes itself to fit its contents? If so, this isn't a feature of the grid control.

The grid control shows scroll bars only if needed. Unneeded space is shown in a dark gray color. You can expand columns and rows with the function CGridCtrl::ExpandToFit to remove all scrollbars, if they are really not needed.

This function also takes care that all grid cells cover the complete controls client space.

Body:
I have created an MFC grid control (Code Project MFC Grid control 2.27) in an MFC dialog MyDlg (C++, VS2015, 64-bit Windows 7). The MyDlg.h file contains

CGridCtrl gridCtrl;

and the resource editor was used to add a custom control of type MFCGridCtrl. In MyDlg.cpp, I am subclassing the control with

DDX_Control(pDX, IDC_ComponentRatios, gridCtrl);

In MyDlg::OnInitDialog, I set the number of rows and columns with

gridCtrl.SetColumnCount(2);
gridCtrl.SetRowCount(2);
gridCtrl.EnableWindow(TRUE);

What I get is the 2 x 2 grid I expect, but the size of the custom control does not match the size of the grid.

The custom control's width is wrong, because setting the column count appears to be leaving space for a scroll bar, which is unnecessary.

The height is unchanged, which is wrong because the custom control is sized for 8 rows, and I'm only using 2 in this example (the actual number of rows required is variable).

How can I get the grid to fill the width of the custom control, and to resize the height of that control to match?


问:
proc rank vs proc means to remove the top and bottom 0.1%
I would like to remove some outlier in the top and bottom 0.1%. PROC MEANS has the p99 option which only helps to remove the top 1%, not 0.1%. Is there another way to do so? I thought of PROC RANK but not sure if it would give the same result.
my code is:

```<code>    proc means data=input noprint; by date; output out=trunc(drop=_FREQ_ _TYPE_) p99(var1)=p99_var1 p99(var2)=p99_var2; run;
data input; merge input trunc; by date;
    if var1 < p99_var1 and var2<p99_var2;run;

    versus

    proc rank data=input out=input percent;
        by date;
         var var1 var2;
         ranks percentile1 percentile2;
    run;
data input; set input;
where 0.001<percentile1<0.999 and 0.001<percentile2<0.999;run
</code>```

I am aware that in the first method I use 99% (because I don't know how to do 99.9% with this method) but I use 99.9% in the second method. If I use 99% for the second method, which one would be a better way to do? and would the 2 yield the same result?

答:
proc means only has access to certain default percentiles, however you can specify custom percentiles in proc univariate

```<code>proc univariate data=sashelp.prdsal3 noprint;
   var actual;
   output out=want pctlpre=P_ pctlpts=0.1,99.9;
run;
</code>```

Body:
I would like to remove some outlier in the top and bottom 0.1%. PROC MEANS has the p99 option which only helps to remove the top 1%, not 0.1%. Is there another way to do so? I thought of PROC RANK but not sure if it would give the same result.
my code is:

    proc means data=input noprint; by date; output out=trunc(drop=_FREQ_ _TYPE_) p99(var1)=p99_var1 p99(var2)=p99_var2; run;
data input; merge input trunc; by date;
    if var1 < p99_var1 and var2<p99_var2;run;

    versus

    proc rank data=input out=input percent;
        by date;
         var var1 var2;
         ranks percentile1 percentile2;
    run;
data input; set input;
where 0.001<percentile1<0.999 and 0.001<percentile2<0.999;run

I am aware that in the first method I use 99% (because I don't know how to do 99.9% with this method) but I use 99.9% in the second method. If I use 99% for the second method, which one would be a better way to do? and would the 2 yield the same result?

Body:
proc means only has access to certain default percentiles, however you can specify custom percentiles in proc univariate

proc univariate data=sashelp.prdsal3 noprint;
   var actual;
   output out=want pctlpre=P_ pctlpts=0.1,99.9;
run;


问:
JMeter - Multiple users reading requests from a directory
I have a directory of XML files, and I wanted to configure Jmeter such a way that multiple users(threads) should be able to read the XML files(SOAP requests) concurrently (in a round-robin way or some other way) and submit them to Web Service Endpoint, which means I wanted them to share the input files.. for example if my directory contains 100 XML files then all of my configured users(threads) should share the load and jointly have to process the XML files. (Each user should not process all the 100 files independently).

Is there any way to test the above scenario?

Thanks,
Siva

答:
I believe Directory Listing Config plugin would be the easiest option to use

Just provide path to the directory where your XML files live, configure the plugin according to your test scenario and that's it, you will be able to use just one HTTP Request sampler and refer the file name (or path) as ${filename} where required.

You can install Directory Listing Config plugin and keep it up-to-date via JMeter Plugins Manager.


问:
Installing java 7 and 8 on ubuntu
I have installed java 8 onn ubuntu. But now when i want to install
java 7 its giving me error. Bascially I will be switching from 7 to 8 or vice versa. Is it that I have to uninstall 8 first and then instal 7 and 8 in line.
I am using ubuntu 16.04

the commands i used are as follows

sudo apt-get install python-software-properties
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update

JDK 7

sudo apt-get install oracle-java7-installer

download failed
Oracle JDK 7 is NOT installed.
dpkg: error processing package oracle-java7-installer (--configure):
 subprocess installed post-installation script returned error exit status 1
Errors were encountered while processing:
 oracle-java7-installer
E: Sub-process /usr/bin/dpkg returned an error code (1)

答:
to install java 7 :

```<code>sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java7-installer
</code>```

Apt-get won't overwrite the existing java versions.

To switch between installed java versions, use the update-java-alternatives command.

List all java versions :

```<code>update-java-alternatives --list
</code>```

Set java version as default (needs root permissions):

```<code>sudo update-java-alternatives --set /path/to/java/version
</code>```

..where /path/to/java/version is one of those listed by the previous command (e.g. /usr/lib/jvm/java-7-openjdk-amd64).

Title: Installing java 7 and 8 on ubuntu

Body:
to install java 7 :

sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java7-installer

Apt-get won't overwrite the existing java versions.

To switch between installed java versions, use the update-java-alternatives command.

List all java versions :

update-java-alternatives --list

Set java version as default (needs root permissions):

sudo update-java-alternatives --set /path/to/java/version

..where /path/to/java/version is one of those listed by the previous command (e.g. /usr/lib/jvm/java-7-openjdk-amd64).


问:
Can't find info on syntax for Dictionary with three parameters in C#
I though I knew all the tricks on the map but recently I saw an assignment where the following is listed as a part of unit test. I've looked at SO and DotNetPearls but couldn't see anything that would catch my eye.

```<code>var dictionary = new Dictionary
{
  [a] = a,
  [b] = b,
  [c] = c
};
</code>```

What kind of syntax is it? Where can I find more info about it?

The syntax is from a code that's a test for job application and I'm not allowed to alter it (although I've already found other irregularities there). The question of the test isn't this particular syntax, of course, it's just a test method used to verify that the actual test satisfies the criteria (but on my VS 17 it doesn't even compile).

答:
This is the index initializer syntax, introduced in C# 6. It's equivalent to this:

```<code>var dictionary = new Dictionary();
dictionary[a] = a;
dictionary[b] = b;
dictionary[c] = c;
</code>```

but on my VS 17 it doesn't even compile

Probably because Dictionary<TKey, TValue> is a generic class, and in this code the generic type arguments are not specified.

Body:
I though I knew all the tricks on the map but recently I saw an assignment where the following is listed as a part of unit test. I've looked at SO and DotNetPearls but couldn't see anything that would catch my eye.

var dictionary = new Dictionary
{
  [a] = a,
  [b] = b,
  [c] = c
};

What kind of syntax is it? Where can I find more info about it?

The syntax is from a code that's a test for job application and I'm not allowed to alter it (although I've already found other irregularities there). The question of the test isn't this particular syntax, of course, it's just a test method used to verify that the actual test satisfies the criteria (but on my VS 17 it doesn't even compile).

Body:
This is the index initializer syntax, introduced in C# 6. It's equivalent to this:

var dictionary = new Dictionary();
dictionary[a] = a;
dictionary[b] = b;
dictionary[c] = c;

but on my VS 17 it doesn't even compile

Probably because Dictionary<TKey, TValue> is a generic class, and in this code the generic type arguments are not specified.


答:
CORS errors are server related. Here, you server isn't set to accept requests from localhost (it's written in the error). Either you allow all (*) when you develop, or you find the right Origin to accept.

Otherwise, your token should go, maybr you didn't see it because it's an OPTIONS request and not a GET one ? (OPTIONS requests are sent by the browser before other requests)

Title: Angular 4 Headers not passing

Body:
I have a REST-API to contact, it works on swagger.
Now I try to call it with my Angular 4 app.
I get the error:

  XMLHttpRequest cannot load
  "baseURL"/company/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access

When I look at the call, I see that it doesn't pass any headers (also not the token), but I actually added them to my request in my Angular 4 code:

getCompanies(): Observable<Company[]> {
   let tokenobject =JSON.parse(sessionStorage.getItem('current_user'));
   let token = tokenobject.token;
   let headers = new Headers({ 'Access-Control-Allow-Origin' : 'http://localhost:4200','Authorization': token });
   let options = new RequestOptions({ headers: headers });
   return this.http.get(this.url + this.path, options)
          .map(this.extractData)
          .catch(this.handleError);
}

Is there something I forgot or did wrong?


问:
Possible ways to get the group Last/Max record in a hierarchical query?
Assuming I have a table like this one:

```<code>CREATE TABLE user_delegates (
    [id] INT IDENTITY(1,1) NOT NULL,
    [user_from] VARCHAR(10) NOT NULL,
    [user_to] VARCHAR(10) NOT NULL,
    CONSTRAINT [PK_user_delegates] PRIMARY KEY CLUSTERED ([id] ASC),
    CONSTRAINT [UK_user_delegates] UNIQUE ([user_from] ASC)
)
</code>```

So an user A has to right to delegate her system access to another user B. When she does that, she won't be able to access the system anymore - user B will have to "break" that delegation before she is able to use the system again...

BUT also consider that, if user B delegates access to user C, user C will also start impersonating user A, and so on.

(I know this seems to be a security nightmare - please let's just forget about that, OK? :-))

Also consider those records:

```<code>INSERT INTO user_delegates([user_from], [user_to]) values ('ANTHONY', 'JOHN')
INSERT INTO user_delegates([user_from], [user_to]) values ('JOHN', 'JOHN')
INSERT INTO user_delegates([user_from], [user_to]) values ('KARL', 'JOSHUA')
INSERT INTO user_delegates([user_from], [user_to]) values ('JOSHUA', 'PIOTR')
INSERT INTO user_delegates([user_from], [user_to]) values ('PIOTR', 'HANS')
</code>```

So what I need is finding the last (which means the active) delegation for each user.

I have come to a solution that I've decided to not show here (unless everybody ignores me, which is always a possibility). All I can say is that it is a somewhat long answer, and it surely seems like using a cannon to kill a flea...

But how would you do that? Consider any relevant SQL Server extension available, and notice we're looking for an answer that is both elegant and with a good performance...

BTW, this is the expected result set:

```<code>id          user_from  user_to
----------- ---------- ----------
1           ANTHONY    JOHN
2           JOHN       JOHN
3           KARL       HANS
4           JOSHUA     HANS
5           PIOTR      HANS

(5 row(s) affected)
</code>```

And thanks in advance!

答:
```<code>WITH    q (user_initial, user_from, user_to, link) AS
        (
        SELECT  user_id, user_id, user_id, link
        FROM    users
        UNION ALL
        SELECT  user_initial, q.user_to, ud.user_to, link + 1
        FROM    q
        JOIN    user_delegates ud
        ON      ud.user_from = q.user_to
        )
SELECT  *
FROM    (
        SELECT  *, ROW_NUMBER() OVER (PARTITION BY user_initial ORDER BY link DESC) rn
        FROM    q
        )
WHERE   rn = 1
</code>```

Body:
Assuming I have a table like this one:

CREATE TABLE user_delegates (
    [id] INT IDENTITY(1,1) NOT NULL,
    [user_from] VARCHAR(10) NOT NULL,
    [user_to] VARCHAR(10) NOT NULL,
    CONSTRAINT [PK_user_delegates] PRIMARY KEY CLUSTERED ([id] ASC),
    CONSTRAINT [UK_user_delegates] UNIQUE ([user_from] ASC)
)

So an user A has to right to delegate her system access to another user B. When she does that, she won't be able to access the system anymore - user B will have to "break" that delegation before she is able to use the system again...

BUT also consider that, if user B delegates access to user C, user C will also start impersonating user A, and so on.

(I know this seems to be a security nightmare - please let's just forget about that, OK? :-))

Also consider those records:

INSERT INTO user_delegates([user_from], [user_to]) values ('ANTHONY', 'JOHN')
INSERT INTO user_delegates([user_from], [user_to]) values ('JOHN', 'JOHN')
INSERT INTO user_delegates([user_from], [user_to]) values ('KARL', 'JOSHUA')
INSERT INTO user_delegates([user_from], [user_to]) values ('JOSHUA', 'PIOTR')
INSERT INTO user_delegates([user_from], [user_to]) values ('PIOTR', 'HANS')

So what I need is finding the last (which means the active) delegation for each user.

I have come to a solution that I've decided to not show here (unless everybody ignores me, which is always a possibility). All I can say is that it is a somewhat long answer, and it surely seems like using a cannon to kill a flea...

But how would you do that? Consider any relevant SQL Server extension available, and notice we're looking for an answer that is both elegant and with a good performance...

BTW, this is the expected result set:

id          user_from  user_to
----------- ---------- ----------
1           ANTHONY    JOHN
2           JOHN       JOHN
3           KARL       HANS
4           JOSHUA     HANS
5           PIOTR      HANS

(5 row(s) affected)

And thanks in advance!


问:
How to login to website through python using request?
I have gone through all the questions on stackoverflow related to this but I can't solve my problem. When I am implementing the follwing code,it runs successfully without any error but nothing gets printed.</p>

```<code>import requests

payload = {'username': 'user','password': 'pass'}

with requests.Session() as s:
    p = s.post(' file-transfers.in/login.php?rid=worlddomains',
          params=payload)
    r = s.get('http://file-transfers.in/member_arean.php')
    print r.text
</code>```

答:
The website in question is expecting you to send your username/pass as POST data, not as URL params so:

```<code>payload = {'username': 'user','password': 'pass'}

with requests.Session() as s:
    p = s.post('http://file-transfers.in/login.php?rid=worlddomains', data=payload)
    r = s.get('http://file-transfers.in/member_arean.php')
    print(r.text)
</code>```

There might be more to it once the login passes, but without an account we cannot check what's going on.

Body:
I have gone through all the questions on stackoverflow related to this but I can't solve my problem. When I am implementing the follwing code,it runs successfully without any error but nothing gets printed.

import requests

payload = {'username': 'user','password': 'pass'}

with requests.Session() as s:
    p = s.post(' file-transfers.in/login.php?rid=worlddomains',
          params=payload)
    r = s.get('http://file-transfers.in/member_arean.php')
    print r.text

Body:
The website in question is expecting you to send your username/pass as POST data, not as URL params so:

payload = {'username': 'user','password': 'pass'}

with requests.Session() as s:
    p = s.post('http://file-transfers.in/login.php?rid=worlddomains', data=payload)
    r = s.get('http://file-transfers.in/member_arean.php')
    print(r.text)

There might be more to it once the login passes, but without an account we cannot check what's going on.


问:
SSRS and ignored "having" clause
I'm trying to get a list of data whose last update date is older than the current date minus x month.

As an example, here is a sample table :

```<code>|  DataGUID  |  UpdateDate   |
|------------|---------------|
|    AAA     |   12-05-2017  |
|    BBB     |   22-06-2017  |
|    AAA     |   14-02-2017  |
|    BBB     |   16-05-2017  |
</code>```

Currently, I have a SQL request looking somewhat like the following :

```<code>SELECT
      DataGUID,
      MAX(UpdateDate)
FROM
      Table
GROUP BY
      DataGUID
HAVING
      MAX(UpdateDate) <= DATEADD(mm, CAST('-'+@LastUpdatedXMonthAgo AS INT), GETDATE())
ORDER BY
      MAX(UpdateDate) DESC;
</code>```

Expected result is the following (with @LastUpdatedXMonthAgo = 1, and current date 13-07-2017) :

```<code>|  DataGUID  |  UpdateDate   |
|------------|---------------|
|    AAA     |   12-05-2017  |
</code>```

It works on SSMS, but SSRS seems to ignore the "having" clause, and gives me this result :

```<code>|  DataGUID  |  UpdateDate   |
|------------|---------------|
|    BBB     |   22-06-2017  |
|    AAA     |   12-05-2017  |
</code>```

Seem like SSRS just ignore the "having" clause, is there a way to make it work without using SSRS filters?

答:
The problem appears to be that you are trying to prepend concatenate a hyphen to a session variable which is a number.  This is resulting in the minus sign being ignored/dropped.  Hence, your HAVING clause is working, but it is comparing each max date against one month in the future from now, instead of one month behind.

The following query will show you one way to fix this problem:

```<code>DECLARE @LastUpdatedXMonthAgo INT;
SET @LastUpdatedXMonthAgo = 1;
SELECT
    DATEADD(mm, CAST('-'+CAST(@LastUpdatedXMonthAgo AS VARCHAR(55)) AS INT), GETDATE());
</code>```

This approach is to cast @LastUpdatedXMonthAgo to text before trying to "negate" the string.  Another approach would be to just make @LastUpdatedXMonthAgo text, but maybe this would be inconvenient for the rest of your script.

Update:

In SSMS, we could simplify this even further to:

```<code>DATEADD(mm, -@LastUpdatedXMonthAgo, GETDATE());
</code>```

Demo here:

Rextester

Title: SSRS and ignored "having" clause

Body:
I'm trying to get a list of data whose last update date is older than the current date minus x month.

As an example, here is a sample table :

|  DataGUID  |  UpdateDate   |
|------------|---------------|
|    AAA     |   12-05-2017  |
|    BBB     |   22-06-2017  |
|    AAA     |   14-02-2017  |
|    BBB     |   16-05-2017  |

Currently, I have a SQL request looking somewhat like the following :

SELECT
      DataGUID,
      MAX(UpdateDate)
FROM
      Table
GROUP BY
      DataGUID
HAVING
      MAX(UpdateDate) <= DATEADD(mm, CAST('-'+@LastUpdatedXMonthAgo AS INT), GETDATE())
ORDER BY
      MAX(UpdateDate) DESC;

Expected result is the following (with @LastUpdatedXMonthAgo = 1, and current date 13-07-2017) :

|  DataGUID  |  UpdateDate   |
|------------|---------------|
|    AAA     |   12-05-2017  |

It works on SSMS, but SSRS seems to ignore the "having" clause, and gives me this result :

|  DataGUID  |  UpdateDate   |
|------------|---------------|
|    BBB     |   22-06-2017  |
|    AAA     |   12-05-2017  |

Seem like SSRS just ignore the "having" clause, is there a way to make it work without using SSRS filters?

Body:
The problem appears to be that you are trying to prepend concatenate a hyphen to a session variable which is a number.  This is resulting in the minus sign being ignored/dropped.  Hence, your HAVING clause is working, but it is comparing each max date against one month in the future from now, instead of one month behind.

The following query will show you one way to fix this problem:

DECLARE @LastUpdatedXMonthAgo INT;
SET @LastUpdatedXMonthAgo = 1;
SELECT
    DATEADD(mm, CAST('-'+CAST(@LastUpdatedXMonthAgo AS VARCHAR(55)) AS INT), GETDATE());

This approach is to cast @LastUpdatedXMonthAgo to text before trying to "negate" the string.  Another approach would be to just make @LastUpdatedXMonthAgo text, but maybe this would be inconvenient for the rest of your script.

Update:

In SSMS, we could simplify this even further to:

DATEADD(mm, -@LastUpdatedXMonthAgo, GETDATE());

Demo here:

Rextester


问:
How do I keep java program running (loop) so I can use the scanner to input to the same text file text file?
I am trying to use the java scanner input to read multiple inputs (numbers as a string eg. 12345) from keyboard and send to a text file, I have a scanner reading input.nextLine(), where it will read in each line. I just would like to run my program and have it stay running so it will populate the text file with each scanner input. I am using the following code:</p>

```<code>import java.util.*;
import java.io.*;

public class tap1
{
    public static void main(String[] args) throws IOException
    {
        System.out.println("Please enter number:");
        File outFile = new File ("CardNumbers.txt");
        FileWriter fWriter = new FileWriter (outFile, true);
        PrintWriter pWriter = new PrintWriter (fWriter);
        Scanner scan = new Scanner(System.in);
        String num = scan.nextLine();
        pWriter.println (num);
        pWriter.close();
    }
}
</code>```

答:
You can wrap it in a loop like

```<code>  while(scanner.hasNext){
    scanner.nextLine();
  //Do some code
}
</code>```

You'll keep "scanning" for new input until EOF is reached and untill then your program keep running.

Body:
I am trying to use the java scanner input to read multiple inputs (numbers as a string eg. 12345) from keyboard and send to a text file, I have a scanner reading input.nextLine(), where it will read in each line. I just would like to run my program and have it stay running so it will populate the text file with each scanner input. I am using the following code:

import java.util.*;
import java.io.*;

public class tap1
{
    public static void main(String[] args) throws IOException
    {
        System.out.println("Please enter number:");
        File outFile = new File ("CardNumbers.txt");
        FileWriter fWriter = new FileWriter (outFile, true);
        PrintWriter pWriter = new PrintWriter (fWriter);
        Scanner scan = new Scanner(System.in);
        String num = scan.nextLine();
        pWriter.println (num);
        pWriter.close();
    }
}

Body:
You can wrap it in a loop like

  while(scanner.hasNext){
    scanner.nextLine();
  //Do some code
}

You'll keep "scanning" for new input until EOF is reached and untill then your program keep running.


问:
Android - Preventing Application data or files being deleted thru "Clear Data" settings option
I have an Android application that stores about 25-40K of private app data in few files. By default system stores these files in the directory /data/data/'my app package'/files. When the user goes to "Setting->Applications->Manage Applications->'My app package'" and chooses the "Clear data" option, all the files, databases folders for this app is being deleted. I need to keep my data on the device until the app is "uninstalled".

Is there a way to keep my application data "on the device" somewhere without being deleted? My device is not rooted. My app is not meant to be on rooted devices.

Note: I saw the /data/data/'my app package'/lib directory is not being deleted using the "clear data" option. But I couldn't programmatically write to this direcroty. I get permission denied. Is there a way to use this directory to store my data? Is there a way to use NDK (not worked on it yet) to keep the data safe? Is there a way to keep the data in application resource or something like a DLL resource in Windows programing.

Any help please to get me out of this jam?

答:
Add

android:allowClearUserData="false"

to Application tag of the manifiest
it will change the button Clear Data to Manage Space


问:
Laravel eloquent - where field is equal to one of 2 values
I need to make a query in Laravel project with which I would fetch the record in the DB that would have a slug equal to post or page:

```<code>where('slug', 'post' || 'page')
</code>```

How can I do that?

答:
Using orWhere you can do it like this:

```<code>->where('slug','page')
->orWhere('slug','post')
</code>```

Another way is,

```<code>->whereIn('slug',['post','page']);
</code>```

Another way

```<code>->whereRaw("slug = 'post' or slug = 'page'")
</code>```

Body:
I need to make a query in Laravel project with which I would fetch the record in the DB that would have a slug equal to post or page:

where('slug', 'post' || 'page')

How can I do that?

Body:
Using orWhere you can do it like this:

->where('slug','page')
->orWhere('slug','post')

Another way is,

->whereIn('slug',['post','page']);

Another way

->whereRaw("slug = 'post' or slug = 'page'")


问:
A few problems with java input exception handling
I need to handle empty input and remove the stack trace from output.

Here's a snippet of my code:

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

        for(int i = 0; i < args.length; i++)
        {
            try
            {
                Integer.parseInt(args[i]);
            }

            catch(NumberFormatException nfe)
            {
                System.err.println("\n" + "NumberFormatException is caught" + "\n" + "Please input 1, 2 or 3 valid numbers only");
            }

            if (args.length==0 ||args.length>3||Integer.parseInt(args[i])<0)
                throw new IllegalArgumentException("\n" + "IllegalArgumentException is caught" + "\n" + "Please input 1, 2 or 3 valid numbers only");
        }
</code>```

I have two problems, first is when a user inputs no value on the command line, it's supposed to throw a IllegalArguementException and the appropriate error message. When I run this code and input no values it runs without throwing the exception. It looks something like this:

C:\Users\XXX\Desktop\Folder>java TestShape

C:\Users\XXX\Desktop\Folder>_

The second problem is when I try out the other exceptions (putting a string instead of an int, negative numbers, exceeding more than 3 numbers etc.) it outputs the proper message but it also prints out the stack trace:

C:\Users\Chef Boi Logro\Desktop\Folder\ICS 112\Lab
  Exercises\LE8\New>java TestShape -1 2 -3

Exception in thread "main" java.lang.IllegalArgumentException:

IllegalArgumentException is caught Please input 1, 2 or 3 valid
  numbers only
          at TestShape.main(TestShape.java:19)

What I need is for the terminal to just display the error messages, without the stack trace.

答:
For the first problem, you are checking condition in wrong place. Refer given code for correction.
For the second problem, you are using default exception handling which shows stack trace. For custom error handling, use throws clause. Refer given code for same.

Updated Code:

```<code>if (args.length < 1)
{
    throw new IllegalArgumentException("\n" + "IllegalArgumentException is caught" + "\n" + "Please input 1, 2 or 3 valid numbers only");
}
else
{
    for(int i = 0; i < args.length; i++)
    {
        if (args[i].matches("[0-9]+") && args[i].length() <= 3)
            {
                Integer.parseInt(args[i]);
            }
            else
            {
                throw new NumberFormatException("NumberFormatException is caught" + "\n" + "Please input 1, 2 or 3 valid numbers only");
            }
    }
}
</code>```

Hope this will help. :-)

Body:
I need to handle empty input and remove the stack trace from output.

Here's a snippet of my code:

public class TestShape
{
    public static void main(String args[])
    {

        for(int i = 0; i < args.length; i++)
        {
            try
            {
                Integer.parseInt(args[i]);
            }

            catch(NumberFormatException nfe)
            {
                System.err.println("\n" + "NumberFormatException is caught" + "\n" + "Please input 1, 2 or 3 valid numbers only");
            }

            if (args.length==0 ||args.length>3||Integer.parseInt(args[i])<0)
                throw new IllegalArgumentException("\n" + "IllegalArgumentException is caught" + "\n" + "Please input 1, 2 or 3 valid numbers only");
        }

I have two problems, first is when a user inputs no value on the command line, it's supposed to throw a IllegalArguementException and the appropriate error message. When I run this code and input no values it runs without throwing the exception. It looks something like this:

C:\Users\XXX\Desktop\Folder>java TestShape

C:\Users\XXX\Desktop\Folder>_

The second problem is when I try out the other exceptions (putting a string instead of an int, negative numbers, exceeding more than 3 numbers etc.) it outputs the proper message but it also prints out the stack trace:

C:\Users\Chef Boi Logro\Desktop\Folder\ICS 112\Lab
  Exercises\LE8\New>java TestShape -1 2 -3

Exception in thread "main" java.lang.IllegalArgumentException:

IllegalArgumentException is caught Please input 1, 2 or 3 valid
  numbers only
          at TestShape.main(TestShape.java:19)

What I need is for the terminal to just display the error messages, without the stack trace.

Body:
For the first problem, you are checking condition in wrong place. Refer given code for correction.
For the second problem, you are using default exception handling which shows stack trace. For custom error handling, use throws clause. Refer given code for same.

Updated Code:

if (args.length < 1)
{
    throw new IllegalArgumentException("\n" + "IllegalArgumentException is caught" + "\n" + "Please input 1, 2 or 3 valid numbers only");
}
else
{
    for(int i = 0; i < args.length; i++)
    {
        if (args[i].matches("[0-9]+") && args[i].length() <= 3)
            {
                Integer.parseInt(args[i]);
            }
            else
            {
                throw new NumberFormatException("NumberFormatException is caught" + "\n" + "Please input 1, 2 or 3 valid numbers only");
            }
    }
}

Hope this will help. :-)


问:
Using regular exp in oracle to remove a group of codes
i've a column in my Oracle table and it has many values with a group of codes as below :

(5000311520) smart tv 40 inch + cinema/internet(high-speed)

now i'm going to remove the code : (5000311520)

it means the result should be : smart tv 40 inch + cinema/internet(high-speed)

anybody can help me?
thanks in advance.

答:
To select the part you are interested in you can try the following SELECT statement:</p>

```<code>SELECT REGEXP_REPLACE(yourColumn, '\([[:digit:]]+\) (.*)', '(\1)') AS result
  FROM yourTable;
</code>```

Body:
To select the part you are interested in you can try the following SELECT statement:

SELECT REGEXP_REPLACE(yourColumn, '\([[:digit:]]+\) (.*)', '(\1)') AS result
  FROM yourTable;


问:
how to check if a value is greater than all other values in alist by a certain value in python
do any of you know if there are any ways for me to check if a value is greater than all other values in a list by a certain value in python?Thanks
Here's my code which unfortunately doesn't work:</p>

```<code>a=[2,4,6,7,21]
print(a)
x=int(input("Enter a value:"))
if x-a>=1:
 print("The value inputted is has a difference of at least one with all the      other values in list a.")
</code>```

答:
EDIT : Try the following :</p>

```<code>def isGreater(a_value, an_array, min_diff):
  res = True
  if (not all(x <= a_value - min_diff for x in an_array)):
    res = False
  return res

a = [1, 5, 3, 2, 7]
an_input = int(input("Enter a number: "))

print(isGreater(an_input, a, 1))
</code>```

Body:
do any of you know if there are any ways for me to check if a value is greater than all other values in a list by a certain value in python?Thanks
Here's my code which unfortunately doesn't work:

a=[2,4,6,7,21]
print(a)
x=int(input("Enter a value:"))
if x-a>=1:
 print("The value inputted is has a difference of at least one with all the      other values in list a.")

Body:
EDIT : Try the following :

def isGreater(a_value, an_array, min_diff):
  res = True
  if (not all(x <= a_value - min_diff for x in an_array)):
    res = False
  return res

a = [1, 5, 3, 2, 7]
an_input = int(input("Enter a number: "))

print(isGreater(an_input, a, 1))


问:
Normal naming convention for a public static variable in a class?
My code looks like this:

```<code>public partial class App : Application
{
    public static PhrasesPage phrasesPage;
</code>```

Here's the class definition:

```<code>public partial class PhrasesPage
</code>```

Is the variable name normally written as phrasesPage or PhrasesPage?

答:
A global variable or field I would almost always start uppercase:

```<code>public int MyInt;
</code>```

And lowercase if its a local variable:

```<code>void SomeMethod()
{
    int myInt;
}
</code>```

For more detailed guidelines: MS guidelines for naming conventions

So for a public static variable you would use PascalCase

Note -- Don't name a variable the same as its type:

```<code>public static PhrasesPage PhrasesPage
</code>```

Find a descriptive name instead

Body:
My code looks like this:

public partial class App : Application
{
    public static PhrasesPage phrasesPage;

Here's the class definition:

public partial class PhrasesPage

Is the variable name normally written as phrasesPage or PhrasesPage?

Body:
A global variable or field I would almost always start uppercase:

public int MyInt;

And lowercase if its a local variable:

void SomeMethod()
{
    int myInt;
}

For more detailed guidelines: MS guidelines for naming conventions

So for a public static variable you would use PascalCase

Note -- Don't name a variable the same as its type:

public static PhrasesPage PhrasesPage

Find a descriptive name instead


问:
Emacs org-mode capture -> file+datetree+prompt template help
Hey org-mode fanatics. I'm wanting to set up my org-capture journal template to use file+datetree+prompt to dynamically set up date on creation (instead of using file+datetree which automatically sets date to today).

When I replace file+datetree with file+datetree+prompt in my template,

```<code>("j" "Journal" entry (file+datetree+prompt "~/Dropbox/doc/journal.org")
     "* %?\n----Entered on %U\n  %i\n  %a")))
</code>```

I receive error: "Invalid capture target specification.

I've tried messing with this template quite a bit and haven't had success yet. I'd appreciate any help on how to properly set up my journal template. Thanks!

Here's a link to the info page on file+datetree+prompt: Template Elements

答:
I think the problem is there is no documentation for file+datetree+prompt.
Try file+datetree instead. I had good results from that.

```<code>("j" "Journal" entry (file+datetree "~/Dropbox/doc/journal.org")
     "* %?\n----Entered on %U\n  %i\n  %a")))
</code>```

Resulted in this entry on the file journal.org:
(using the word 'Test' when prompted)

```<code>* 2010
** 2010-12 December
*** 2010-12-20 Monday
**** Test
----Entered on [2010-12-20 Mon 12:12]
</code>```

Looking at the source code for org v7.3, there is no reference to file-datetree-prompt, although I did see it mentioned in an online manual. It would be a nice feature, but I'm just manually changing the date in the entry window itself if that's necessary.

Body:
Hey org-mode fanatics. I'm wanting to set up my org-capture journal template to use file+datetree+prompt to dynamically set up date on creation (instead of using file+datetree which automatically sets date to today).

When I replace file+datetree with file+datetree+prompt in my template,

("j" "Journal" entry (file+datetree+prompt "~/Dropbox/doc/journal.org")
     "* %?\n----Entered on %U\n  %i\n  %a")))

I receive error: "Invalid capture target specification.

I've tried messing with this template quite a bit and haven't had success yet. I'd appreciate any help on how to properly set up my journal template. Thanks!

Here's a link to the info page on file+datetree+prompt: Template Elements

Body:
I think the problem is there is no documentation for file+datetree+prompt.
Try file+datetree instead. I had good results from that.

("j" "Journal" entry (file+datetree "~/Dropbox/doc/journal.org")
     "* %?\n----Entered on %U\n  %i\n  %a")))

Resulted in this entry on the file journal.org:
(using the word 'Test' when prompted)

* 2010
** 2010-12 December
*** 2010-12-20 Monday
**** Test
----Entered on [2010-12-20 Mon 12:12]

Looking at the source code for org v7.3, there is no reference to file-datetree-prompt, although I did see it mentioned in an online manual. It would be a nice feature, but I'm just manually changing the date in the entry window itself if that's necessary.


问:
Why can't I ref return a static readonly field?
The following code doesn't compile with C# 7.0 / Visual Studio 2017.2:

```<code>class C {
    private static readonly int s = 5;
    public static ref int Data => ref s;
}
</code>```

Is there an technical reason for disallowing references on static readonly fields or is this just a missing feature?

The error message says:

CS8162: A static readonly field cannot returned by reference.

答:
You can't yet return a reference to a readonly field, as ref returns are mutable. However, the ref readonly feature is planned for a future version of C# (currently pencilled in for C# 7.2, but that may change).

This feature will likely address both the ability to return references to readonly fields, as well as allowing ref parameters to be marked as readonly too, to offer the guarantee that the values referenced won't be modified by the method.

Body:
The following code doesn't compile with C# 7.0 / Visual Studio 2017.2:

class C {
    private static readonly int s = 5;
    public static ref int Data => ref s;
}

Is there an technical reason for disallowing references on static readonly fields or is this just a missing feature?

The error message says:

CS8162: A static readonly field cannot returned by reference.


问:
how decrease click for opening contact in Android
I'm new to android. I want to open contacts after getting permission. My problem is at start I need to click the button tow time, one for getting permission and one for opening contacts.

Is there any way to open contacts immediately after getting permission without any need for 2nd click

答:
When you try to get permission, you call a function and tell your requirement. (only dangerous permission needed to get permission)
after that when the user accept or reject, it come to onRequestPermissionsResult.

inside this method you can check if you gain the permission, do your action.

```<code>         @Override
         public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
            if (Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
            //do your action
         }
</code>```

hope to help you

Body:
When you try to get permission, you call a function and tell your requirement. (only dangerous permission needed to get permission)
after that when the user accept or reject, it come to onRequestPermissionsResult.

inside this method you can check if you gain the permission, do your action.

         @Override
         public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
            if (Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
            //do your action
         }

hope to help you


问:
How to create an array of non-const C strings on the stack without repetitive code in C++03?
I'm writing a unit test for a module that takes an array of mutable C strings in C++03 with getopt. The function argument is char*const[]. I want to create the arguments on the stack inside the function. My current solution is:

```<code>char args_stor[][1024] = {
    "parser",
    "-o",
    "SomeValue"
};
char* args[] = {
    args_stor[0],
    args_stor[1],
    args_stor[2]
};
</code>```

How can I avoid the repetitive part, and if possible, transform it into one statement?

The function declaration is:

```<code>int getopt(int argc, char* const argv[], const char *optstring);
</code>```

Use case is therefore:

```<code>getopt(3, args, ":o:");
</code>```

答:
From the comments to the question, it's not vital that the char array be allocated on the stack, only that it is correctly and automatically cleaned up after use, so that we can invoke the function something like this:

```<code>void f(char *const *args);

int main()
{
    const char *args[] = {
        "parser",
        "-o",
        "SomeValue"
    };
    f(transform(args)->p);
}
</code>```

To implement transform(), we can return a std::auto_ptr to a suitable structure:

```<code>#include <cstring>
#include <memory>

template<std::size_t N>
struct arg_list
{
    char *s;        // string storage
    char *p[N+1];   // pointers into s

    arg_list(const char *const *args)
        : s(new char[total_len(args)]), p()
    {
        char *dest = s;
        for (std::size_t i = 0;  i < N;  ++i) {
            std::strcpy(p[i] = dest, args[i]);
            dest += std::strlen(args[i]) + 1;
        }
        p[N] = 0;
    }

    ~arg_list() { delete[] s; }

    static std::size_t total_len(const char *const *args) {
        std::size_t length = 0;
        for (std::size_t i = 0;  i < N;  ++i)
            length += std::strlen(args[i]) + 1;
        return length;
    }
};

template<std::size_t N>
std::auto_ptr< arg_list<N> > transform(const char *const (&args)[N])
{
    return std::auto_ptr< arg_list<N> >(new arg_list<N>(args));
}
</code>```

The arg_list object will be destroyed after the call to f() in main().  We can test it, using this example f():

```<code>#include <iostream>
void f(char *const *args)
{
    while (*args)
        std::cout << *args++ << std::endl;
}
</code>```

No memory is leaked, and no accesses are made to invalid memory:

valgrind --leak-check=full ./44908185
==23361== Memcheck, a memory error detector
==23361== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==23361== Using Valgrind-3.12.0 and LibVEX; rerun with -h for copyright info
==23361== Command: ./44908185
==23361==
parser
-o
SomeValue
==23361==
==23361== HEAP SUMMARY:
==23361==     in use at exit: 0 bytes in 0 blocks
==23361==   total heap usage: 3 allocs, 3 frees, 72,764 bytes allocated
```

There are easier versions of this for newer standards of C++, but this seems to be the simplest in C++03.

Body:
I'm writing a unit test for a module that takes an array of mutable C strings in C++03 with getopt. The function argument is char*const[]. I want to create the arguments on the stack inside the function. My current solution is:

char args_stor[][1024] = {
    "parser",
    "-o",
    "SomeValue"
};
char* args[] = {
    args_stor[0],
    args_stor[1],
    args_stor[2]
};

How can I avoid the repetitive part, and if possible, transform it into one statement?

The function declaration is:

int getopt(int argc, char* const argv[], const char *optstring);

Use case is therefore:

getopt(3, args, ":o:");

Body:
From the comments to the question, it's not vital that the char array be allocated on the stack, only that it is correctly and automatically cleaned up after use, so that we can invoke the function something like this:

void f(char *const *args);

int main()
{
    const char *args[] = {
        "parser",
        "-o",
        "SomeValue"
    };
    f(transform(args)->p);
}

To implement transform(), we can return a std::auto_ptr to a suitable structure:

#include <cstring>
#include <memory>

template<std::size_t N>
struct arg_list
{
    char *s;        // string storage
    char *p[N+1];   // pointers into s

    arg_list(const char *const *args)
        : s(new char[total_len(args)]), p()
    {
        char *dest = s;
        for (std::size_t i = 0;  i < N;  ++i) {
            std::strcpy(p[i] = dest, args[i]);
            dest += std::strlen(args[i]) + 1;
        }
        p[N] = 0;
    }

    ~arg_list() { delete[] s; }

    static std::size_t total_len(const char *const *args) {
        std::size_t length = 0;
        for (std::size_t i = 0;  i < N;  ++i)
            length += std::strlen(args[i]) + 1;
        return length;
    }
};

template<std::size_t N>
std::auto_ptr< arg_list<N> > transform(const char *const (&args)[N])
{
    return std::auto_ptr< arg_list<N> >(new arg_list<N>(args));
}

The arg_list object will be destroyed after the call to f() in main().  We can test it, using this example f():

#include <iostream>
void f(char *const *args)
{
    while (*args)
        std::cout << *args++ << std::endl;
}

No memory is leaked, and no accesses are made to invalid memory:

valgrind --leak-check=full ./44908185
==23361== Memcheck, a memory error detector
==23361== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==23361== Using Valgrind-3.12.0 and LibVEX; rerun with -h for copyright info
==23361== Command: ./44908185
==23361==
parser
-o
SomeValue
==23361==
==23361== HEAP SUMMARY:
==23361==     in use at exit: 0 bytes in 0 blocks
==23361==   total heap usage: 3 allocs, 3 frees, 72,764 bytes allocated

There are easier versions of this for newer standards of C++, but this seems to be the simplest in C++03.


问:
How to Call the Column Index Number in Vlookup : VBA
How to call the column index no d in vlookup. "=vlookup(RC[-15],"& Rg.Address(True, True, xlR1C1, xlExternal) & ",d,False)" is it correct?. refer below code (note Vlookup using with one workbook to another workbook)

```<code>Sub Vlkuprangcall()
Dim strColumn As String
Dim Rg As Range
Dim wb2 As Workbook
Dim d, a, Lastrow As Long

Set wb2 = Workbooks.Open("C:\Users\ashokkumar.d\Desktop\Test\IC Raphael\Janalakshmi\MIS\MIS.xlsx")
Set Rg = wb2.Sheets(3).Range("A3:Z10000")
d = 6
Application.Workbooks(2).Activate
With ActiveSheet
    a = ActiveCell.Column
    Lastrow = 100
    strColumn = Split(ActiveCell.Address, "$")(1)
    ActiveCell.FormulaR1C1 = "=vlookup(RC[-15],"& Rg.Address(True, True, xlR1C1, xlExternal) & ",d,False)"
    ActiveCell.AutoFill Destination:=Range(ActiveCell, Range(strColumn & Lastrow))
End With
End Sub
</code>```

答:
You need to take out the d variable outside the ".

Replace your FormulaR1C1 line :

```<code>ActiveCell.FormulaR1C1 = "=vlookup(RC[-15],"& Rg.Address(True, True, xlR1C1, xlExternal) & ",d,False)"
</code>```

With :

```<code>ActiveCell.FormulaR1C1 = "=vlookup(RC[-15]," & Rg.Address(True, True, xlR1C1, xlExternal) & "," & d & ",False)"
</code>```

Note: Defining Dim d, a, Lastrow As Long , means only Lastrow As Long , while d and a will be defined as Variant.

Change this line to Dim d As Long, a As Long, Lastrow As Long

Body:
How to call the column index no d in vlookup. "=vlookup(RC[-15],"& Rg.Address(True, True, xlR1C1, xlExternal) & ",d,False)" is it correct?. refer below code (note Vlookup using with one workbook to another workbook)

Sub Vlkuprangcall()
Dim strColumn As String
Dim Rg As Range
Dim wb2 As Workbook
Dim d, a, Lastrow As Long

Set wb2 = Workbooks.Open("C:\Users\ashokkumar.d\Desktop\Test\IC Raphael\Janalakshmi\MIS\MIS.xlsx")
Set Rg = wb2.Sheets(3).Range("A3:Z10000")
d = 6
Application.Workbooks(2).Activate
With ActiveSheet
    a = ActiveCell.Column
    Lastrow = 100
    strColumn = Split(ActiveCell.Address, "$")(1)
    ActiveCell.FormulaR1C1 = "=vlookup(RC[-15],"& Rg.Address(True, True, xlR1C1, xlExternal) & ",d,False)"
    ActiveCell.AutoFill Destination:=Range(ActiveCell, Range(strColumn & Lastrow))
End With
End Sub

Body:
You need to take out the d variable outside the ".

Replace your FormulaR1C1 line :

ActiveCell.FormulaR1C1 = "=vlookup(RC[-15],"& Rg.Address(True, True, xlR1C1, xlExternal) & ",d,False)"

With :

ActiveCell.FormulaR1C1 = "=vlookup(RC[-15]," & Rg.Address(True, True, xlR1C1, xlExternal) & "," & d & ",False)"

Note: Defining Dim d, a, Lastrow As Long , means only Lastrow As Long , while d and a will be defined as Variant.

Change this line to Dim d As Long, a As Long, Lastrow As Long