问:
How to find keys in hash by number of values? (Ruby)
I want to search through a hash for keys with only one value, and divide that value by 2.  How do I go about this?

Example

```<code>hash = { a => [4], b => [2, 4, 5], c => [3, 5] }
</code>```

Result sought

```<code>hash = { a => [2], b => [2, 4, 5], c => [3, 5] }
</code>```

Body:
I want to search through a hash for keys with only one value, and divide that value by 2.  How do I go about this?

Example

hash = { a => [4], b => [2, 4, 5], c => [3, 5] }

Result sought

hash = { a => [2], b => [2, 4, 5], c => [3, 5] }

Body:
hash = {:a=>[4], :b=>[2, 4, 5], :c=>[3, 5]}

You can use transform_values:

hash.transform_values { |v| v.one? ? [v[0]/2.0] : v }
#=> {:a=>[2.0], :b=>[2, 4, 5], :c=>[3, 5]}

Or map

hash.map { |k,v| v.one? ? [k,[v[0]/2.0]] : [k,v] }.to_h
#=> {:a=>[2.0], :b=>[2, 4, 5], :c=>[3, 5]}


来源: stackexchange

问:
s3 file downloads are unpredictable
We have uploaded several zip files to s3. All are in the hundreds of MB range.

We download the files, typically via a script, it appears that the file size and type both change.  The new file size typically is about 300 bytes and the file type once downloaded is xml.

The content of the files look similar to this (whitespace added for clarity):

```<code><?xml version="1.0" encoding="UTF-8"?>
<Error>
  <Code>NoSuchKey</Code>
  <Message>The specified key does not exist.</Message>
  <Key>gpdb-5.0.0.0/greenplum-db-5.0.0.0-rhel5-x86_64.zip</Key>
  <RequestId>83D2047BDBA195A6</RequestId>
  <HostId>tXKFaiRaNjD26j6fcrTjCk858PGBH2RAjLE1aO4+8hovD6mf+hUzJvCdWKKgrDJGaHXsjWbQP2A=</HostId>
</Error>
</code>```

Any thoughts as to what might be causing this? It does not happen all of the time. It's somewhat intermittent.

答:
As you will note in the S3 API Reference, this isn't a file -- it's an error message.

Files in S3 are called Objects, and the path + filename of the object is referred to as the object key.

A key is the unique identifier for an object within a bucket. Every object in a bucket has exactly one key. [...] Every object in Amazon S3 can be uniquely addressed through the combination of the web service endpoint, bucket name, key, and optionally, a version. For example, in the URL http://doc.s3.amazonaws.com/2006-03-01/AmazonS3.wsdl, "doc" is the name of the bucket and "2006-03-01/AmazonS3.wsdl" is the key.

http://docs.aws.amazon.com/AmazonS3/latest/dev/Introduction.html#BasicsKeys

This error message, which should have been accompanied by a 404 Not Found error code when you tried to access the object, indicates that there is no object in the bucket whose key (path + filename) is the one shown in the error -- the one you requested.  You should be able to confirm its absence in the S3 console.

If the object should have been uploaded some time in the past, this error means the object wasn't actually uploaded, or has subsequently been deleted.

If the object was very recently uploaded (typically within seconds), you should not get this error, but it is possible for this error to occur under either of two additional conditions:

If you try to check whether an object exists by sending a GET or HEAD request to the bucket, then uploaded the object.  If you do this, a short period of time may elapse before the object is accessible because of internal optimizations inside S3.  When you try to fetch a non-existent object, S3 may -- for a brief time -- have an internal concept that the object is not there, even though it has safely been stored.  Retry your request.

If you already had an object with the same key, then you deleted it, then you uploaded a new object with the same key, for a brief time after the new upload, you could either get the error above or you could actually download the old object again.

These conditions are somewhat uncommon, but they can occur, particularly if your bucket has a lot of traffic, due to S3's consistency model, which is an engineered tradeoff between performance, reliability, and immediate availability of uploaded objects when the same object has been recently downloaded, attempted to be downloaded, deleted, or overwritten.

The <RequestId> and <HostId> codes in the error response are opaque diagnostic codes that you can provide to AWS support, if you need to submit a support request about a specific problem you are experiencing with S3... they can use these to find the specific request and identify the problem.  They are not considered sensitive information, since they have no meaning outside of AWS.

In this case, there is no apparent need to contact AWS support, because it appears that you are simply trying to download an object that is not in the specific bucket from which you tried to download this particular file.  If you get alternating success and failure for the exact same file, that's unexpected, and a support case might be in order... but typically, an internal error in S3 should result in a very different response.

ContentLicense: CC BY-SA 3.0

Title: s3 file downloads are unpredictable

Body:
We have uploaded several zip files to s3. All are in the hundreds of MB range.

We download the files, typically via a script, it appears that the file size and type both change.  The new file size typically is about 300 bytes and the file type once downloaded is xml.

The content of the files look similar to this (whitespace added for clarity):

<?xml version="1.0" encoding="UTF-8"?>
<Error>
  NoSuchKey
  <Message>The specified key does not exist.</Message>
  <Key>gpdb-5.0.0.0/greenplum-db-5.0.0.0-rhel5-x86_64.zip</Key>
  <RequestId>83D2047BDBA195A6</RequestId>
  <HostId>tXKFaiRaNjD26j6fcrTjCk858PGBH2RAjLE1aO4+8hovD6mf+hUzJvCdWKKgrDJGaHXsjWbQP2A=</HostId>
</Error>

Any thoughts as to what might be causing this? It does not happen all of the time. It's somewhat intermittent.


问:
Running python code through Cython with command line arguments
I have a Python code that uses two command line arguments. I am using linux terminal for all command line tasks. Now I am trying to use Cython to speed up my Python code.
For that I have compiled the Python code to C using build_ext module by creating this setup.py file:

setup.py

```<code>from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
setup (
cmdclass = {'build_ext': build_ext } ,
ext_modules = [
Extension ("myCode", ["myCode.py"]) ,
])
</code>```

And then compiling my Python code into C using:

```<code>python setup.py build_ext -i
</code>```

The following were generated:

```<code>[file]myCode.c
[file]myCode.so
[folder]build
--[folder]temp.linux-x86_64-2.7
----[file]myCode.o
</code>```

I want to run the generated file with command line arguments.
Till now in Python I was using the usual command

```<code>>> python myCode.py arg1 arg2
</code>```

I am very new to Cython, infact I started using it to address the inherent speed issue of Python after code level algorithm optimization. I need inputs on which files to run, and how to run the converted C code and with command line arguments. Thanks in advance.

答: As mentioned you compiled a Python module.  So to call from Linux you have to write a .py script that imports your compiled module and does any calculations needed.  Then you can run it with your typical Linux command.

Body:
I have a Python code that uses two command line arguments. I am using linux terminal for all command line tasks. Now I am trying to use Cython to speed up my Python code.
For that I have compiled the Python code to C using build_ext module by creating this setup.py file:

setup.py

from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
setup (
cmdclass = {'build_ext': build_ext } ,
ext_modules = [
Extension ("myCode", ["myCode.py"]) ,
])

And then compiling my Python code into C using:

python setup.py build_ext -i

The following were generated:

[file]myCode.c
[file]myCode.so
[folder]build
--[folder]temp.linux-x86_64-2.7
----[file]myCode.o

I want to run the generated file with command line arguments.
Till now in Python I was using the usual command

>> python myCode.py arg1 arg2

I am very new to Cython, infact I started using it to address the inherent speed issue of Python after code level algorithm optimization. I need inputs on which files to run, and how to run the converted C code and with command line arguments. Thanks in advance.


问:
How to grab the nth occurence of a float on a line using regex?
The text file I'm searching through looks like a lot of text blocks like this:

MKC,2017-06-23 07:54,-94.5930,39.1230,79.00,73.90,84.41,220.00,4.00,0.00,29.68,1003.90,10.00,M,FEW,M,M,M,9500.00,M,M,M,M,KMKC 230754Z 22004KT 10SM FEW095 26/23 A2968 RMK AO2 SLP039 T02610233

(That's all one line)

I'm looking to grab the 2nd occurrence in the line that matches r',\d\.\d{2},', which in this case would be 0.00

I don't know how to specify that I want the nth occurrence of the pattern.

Extra: I've never seen the first value that matches the same pattern go over 9.99, meaning 10.00 and then it would no longer match the same pattern, but it would be nice if there was a way to take this into account.

答: You could use the re.findall(regex, string, flags) function in python. That returns non-overlapping matches of the patter in string in a list of strings. You could then grab the second member of the returned list.


答:
You can use re.findall. It returns a list which you can access like so:</p>

```<code>result = re.findall(r',\d\.\d{2},', input)
result[n] # will return nth instance
</code>```

Title: How to grab the nth occurence of a float on a line using regex?

Body:
The text file I'm searching through looks like a lot of text blocks like this:

MKC,2017-06-23 07:54,-94.5930,39.1230,79.00,73.90,84.41,220.00,4.00,0.00,29.68,1003.90,10.00,M,FEW,M,M,M,9500.00,M,M,M,M,KMKC 230754Z 22004KT 10SM FEW095 26/23 A2968 RMK AO2 SLP039 T02610233

(That's all one line)

I'm looking to grab the 2nd occurrence in the line that matches r',\d\.\d{2},', which in this case would be 0.00

I don't know how to specify that I want the nth occurrence of the pattern.

Extra: I've never seen the first value that matches the same pattern go over 9.99, meaning 10.00 and then it would no longer match the same pattern, but it would be nice if there was a way to take this into account.

Body:
You can use re.findall. It returns a list which you can access like so:

result = re.findall(r',\d\.\d{2},', input)
result[n] # will return nth instance


问:
Aws s3 copy and replicate folder in laravel
I am trying to copy a folder which is already on s3 and save it with different name on S3 in laravel 5.4 . What I have found so far is that I can copy an Image, Not folder. I have tried to copy folder like ie:

```<code> $disk->copy("admin/form/$old_form","admin/form/$new_form");
</code>```

But it doesnot work like that. It give me an error. Do i need to apply loop and get each folder item separately? Like:

```<code>$images = $disk->allFiles('admin/form/$id');
</code>```

Or is there any work around available in laravel or s3 api it self?

Please help, Its driving me crazy.

Thanks in advance.

答:
I'm in the middle of doing this same thing.  Based on what I've read so far, copying a directory itself using Laravel doesn't seem to be possible.  The suggestions I've seen so far suggest looking through and copying each image, however I'm not at all satisfied with the speed (since I'm doing this on lots of images several times a day).

Note that I'm only using the Filesystem directly like this so I can more easily access the methods in PHP Storm.  $s3 = \Storage::disk('s3'); would accomplish the same thing as my first two lines.  I'll update this answer if I find anything that works more quickly.

```<code>$filesystem = new FilesystemManager(app());
$s3 = $filesystem->disk('s3');
$images = $s3->allFiles('old-folder');

$s3->deleteDirectory('new_folder'); // If the file already exists, it will throw an exception.  In my case I'm deleting the entire folder to simplify things.
foreach($images as $image)
{
    $new_loc = str_replace('old-folder', 'new-folder', $image);
    $s3->copy($image, $new_loc);
}
</code>```

Body:
I am trying to copy a folder which is already on s3 and save it with different name on S3 in laravel 5.4 . What I have found so far is that I can copy an Image, Not folder. I have tried to copy folder like ie:

 $disk->copy("admin/form/$old_form","admin/form/$new_form");

But it doesnot work like that. It give me an error. Do i need to apply loop and get each folder item separately? Like:

$images = $disk->allFiles('admin/form/$id');

Or is there any work around available in laravel or s3 api it self?

Please help, Its driving me crazy.

Thanks in advance.

Body:
I'm in the middle of doing this same thing.  Based on what I've read so far, copying a directory itself using Laravel doesn't seem to be possible.  The suggestions I've seen so far suggest looking through and copying each image, however I'm not at all satisfied with the speed (since I'm doing this on lots of images several times a day).

Note that I'm only using the Filesystem directly like this so I can more easily access the methods in PHP Storm.  $s3 = \Storage::disk('s3'); would accomplish the same thing as my first two lines.  I'll update this answer if I find anything that works more quickly.

$filesystem = new FilesystemManager(app());
$s3 = $filesystem->disk('s3');
$images = $s3->allFiles('old-folder');

$s3->deleteDirectory('new_folder'); // If the file already exists, it will throw an exception.  In my case I'm deleting the entire folder to simplify things.
foreach($images as $image)
{
    $new_loc = str_replace('old-folder', 'new-folder', $image);
    $s3->copy($image, $new_loc);
}


问:
PHP OOP need advice
i am building this sms notification system, which will send 10 times free sms based on certain occasion to the web's member, and after a certain member reach 10 times, the system would send a last notification system saying that "this is the last free sms notification", i am currently learning PHP OOP and trying to use an OOP aproach on this

without further a do here's my code:

```<code><?php
class SmsBonus {
//bonus_sms fields = id, member_id, counter, end_status

public static function find_member($id=0){
    //query to find a certain member
}

public function add_counter($id=0){
    //query to increment the value of counter field
}

public function status_check($id=0){
    //query to check whether the given member's counter has reach the number 10
}

public static function send_sms($id, $message){
    $found = $this->find_member($id);
    $status_check = $this->status_check($id);

    if(!empty($found) && !empty($status_check) && $found->counter == 10){
        //send the sms notification saying that this member has reach the end of the bonus period

        //update this member's end_status table to 1
    }else{
        //send the regular notification
    }
}

}
?>
</code>```

would this lines:

```<code>$found = $this->find_member($id);
$status_check = $this->status_check($id);
</code>```

work as expected (i cant test this one out because i am currently building this on local)? and is this a best practice regarding OOP aproach ? or am i doing this wrong ?

i need advice, thank you very much.

EDIT:

of course on my original code i declare the class, i am sorry that by not writing it here confuses everybody :D, i am actually looking for a kind of answer (advice) that pointed the way i should implement a best approach (best practice) on my codes (in this case methods), things that i worry about is that i don't meet the requirements such as K.I.S.S or D.R.Y.

UPDATE
i manage to do some modifications based on your suggestions, how is this looks like ?

```<code><?php
    class SmsBonus{
        //bonus_sms fields = id, member_id, counter, end_status
        protected $max_sms = 10;

        public $id;
        public $member_id;
        public $counter;
        public $end_status;

        public function find_member($id=0){
            //query to find a certain member
        }

        public function add_counter($id=0){
            //query to increment the value of counter field
        }

        public function status_check($id=0){
            //query to check whether the given member's counter has reach the number 10
        }

        public function update_status($id=0){
            //query to update when a certain member reach its sms bonus limit
        }

        protected function can_still_send_sms($member_id){
            $found          = $this->find_member($member_id);
            $status_check   = $this->status_check($id);
            return !empty($found) && $found->counter < $this->max_sms && !empty($status_check);
        }

        public function send_sms($id, $message){
            $phone  = Phone::find_member($id); //
            if ($this->can_still_send_sms($id)) {
                //send the sms notification saying that this member has reach the end of the bonus period

                $this->update_status($id);
            }else{
                //send the regular notification

                $this->add_counter($id);
            }
        }
    }
    $sms_bonus = new SmsBonus();
?>
</code>```

答:
Listen to dewi.

Anyway, a nice way to test if you're using the right syntax is commenting out the content of the find_member() and status_check() functions and make them return some arbitrary values: if the values are actually returned, you're doing it right.

ContentLicense: CC BY-SA 2.5

Title: PHP OOP need advice

Body:
i am building this sms notification system, which will send 10 times free sms based on certain occasion to the web's member, and after a certain member reach 10 times, the system would send a last notification system saying that "this is the last free sms notification", i am currently learning PHP OOP and trying to use an OOP aproach on this

without further a do here's my code:

<?php
class SmsBonus {
//bonus_sms fields = id, member_id, counter, end_status

public static function find_member($id=0){
    //query to find a certain member
}

public function add_counter($id=0){
    //query to increment the value of counter field
}

public function status_check($id=0){
    //query to check whether the given member's counter has reach the number 10
}

public static function send_sms($id, $message){
    $found = $this->find_member($id);
    $status_check = $this->status_check($id);

    if(!empty($found) && !empty($status_check) && $found->counter == 10){
        //send the sms notification saying that this member has reach the end of the bonus period

        //update this member's end_status table to 1
    }else{
        //send the regular notification
    }
}

}
?>

would this lines:

$found = $this->find_member($id);
$status_check = $this->status_check($id);

work as expected (i cant test this one out because i am currently building this on local)? and is this a best practice regarding OOP aproach ? or am i doing this wrong ?

i need advice, thank you very much.

EDIT:

of course on my original code i declare the class, i am sorry that by not writing it here confuses everybody :D, i am actually looking for a kind of answer (advice) that pointed the way i should implement a best approach (best practice) on my codes (in this case methods), things that i worry about is that i don't meet the requirements such as K.I.S.S or D.R.Y.

UPDATE
i manage to do some modifications based on your suggestions, how is this looks like ?

<?php
    class SmsBonus{
        //bonus_sms fields = id, member_id, counter, end_status
        protected $max_sms = 10;

        public $id;
        public $member_id;
        public $counter;
        public $end_status;

        public function find_member($id=0){
            //query to find a certain member
        }

        public function add_counter($id=0){
            //query to increment the value of counter field
        }

        public function status_check($id=0){
            //query to check whether the given member's counter has reach the number 10
        }

        public function update_status($id=0){
            //query to update when a certain member reach its sms bonus limit
        }

        protected function can_still_send_sms($member_id){
            $found          = $this->find_member($member_id);
            $status_check   = $this->status_check($id);
            return !empty($found) && $found->counter < $this->max_sms && !empty($status_check);
        }

        public function send_sms($id, $message){
            $phone  = Phone::find_member($id); //
            if ($this->can_still_send_sms($id)) {
                //send the sms notification saying that this member has reach the end of the bonus period

                $this->update_status($id);
            }else{
                //send the regular notification

                $this->add_counter($id);
            }
        }
    }
    $sms_bonus = new SmsBonus();
?>


问:
What is the best alternative to polling a database for a value?
I have a Javascript web app and I am using Node.JS as the server component.

I want to integrate my app with a database. This database has a table with a field called 'status' which can change frequently (every couple of minutes or so).

I want my web app to know what the value of the status field is in real time.

My Current Method:

I currenlty, have an AJAX function in Javscript which sends a HTTP request to my Node.js server. The Node.js sever selects the record from the database and then returns the result to the AJAX function, which displays the result on the screen. I have setup an interval to execute the function every second.

This doesn't seem like a great option and it is causing a LOT of traffic on my server.

What is the proper way to monitor the SQL field in real time?

答:
If all your clients are interested in the same value in the database and your database situation prevents any non-polling scenario, then you will want to move the polling from the client to the server so the server can poll ONCE for all the clients.  This will dramatically limit the load on both your server and on the database server.

Then, you can have each client connect to the server with a webSocket (or socket.io) connection and when the value in the database changes (and only then), you can then send an update message to each client over the webSocket connection.  This will use a ton less sever CPU and bandwidth and client battery.


Body:
Using re.findall, capture your floats in a list and then index it as needed.

In [85]: import re

In [86]: line = '''MKC,2017-06-23 07:54,-94.5930,39.1230,79.00,73.90,84.41,220.00,4.00,0.00,29.6
    ...: 8,1003.90,10.00,M,FEW,M,M,M,9500.00,M,M,M,M,KMKC 230754Z 22004KT 10SM FEW095 26/23 A296
    ...: 8 RMK AO2 SLP039 T02610233'''

In [101]: matches = re.findall(r'(?<!\d|M)-?[\d]+\.[\d]+(?=,|$)', line, re.M)

In [102]: matches
Out[102]:
['94.5930',
 '39.1230',
 '79.00',
 ...
 '10.00',
 '9500.00']

If needed, convert to floats using a map:

In [103]: list(map(float, matches))
Out[103]:
[94.593,
 39.123,
 ...
 10.0,
 9500.0]

An update to include Ms:

In [130]: re.findall(r'(?<!\d|M)(?:-?[\d]+\.[\d]+)|M(?=,|$)', line, re.M)
Out[130]:
['-94.5930',
 '39.1230',
 '79.00',
 '73.90',
 '84.41',
 '220.00',
 '4.00',
 '0.00',
 '29.68',
 '1003.90',
 '10.00',
 'M',
 'M',
 'M',
 'M',
 '9500.00',
 'M',
 'M',
 'M',
 'M']


问:
Recursive Fibonacci in Ruby
This week is my first time doing recursion. One of the problems I was able to solve was Fibonacci's sequence to the nth number; it wasn't hard after messing with it for 5 minutes.

However, I am having trouble understanding why this works with the current return statement.

```<code>return array if num == 2
</code>```

If I push to array, it doesn't work, if I make a new variable sequence and push to that, it returns the correct answer. I am cool with that, but my base case says return array, not sequence. I initially pushed the sequence to the array, the result was not fibs sequence. I only solved the problem when I tried seeing what would happen if I pushed to the sequence array.

Instead of just making it work I was hoping someone could explain what was happening under the hood, what the stacks might be and how the problem works.

I understand recursion to an extent and somehow intuitively can make it work by assuming things, but I feel funny not actually knowing all the whys behind it.

```<code>def fib_seq(num)
  return [0] if num == 1
  return [] if num == 0

  array = [0, 1]
  return array if num <= 2

  seq = fib_seq(num - 1)
  seq << seq[-2] + seq[-1]
end
</code>```

答:
The code can be simplified a bit by removing the temporary array variable. It's a distraction. It also only applies when num == 2; num < 2 will be handled by the other base cases. num < 0 is illegal and should be handled by an error check.

I've also added in an explicit return. Explicit returns make it very obvious what's being returned and that helps understand recursion. In this case it's seq. ("Explicit returns are evil!" all the Ruby style people cry. Tough cookies. Good style isn't an absolute.)

```<code>def fib_seq(num)
  # Error check
  if num < 0 then
      raise ArgumentError, "The number must be a positive integer"
  end

  # Terminating base cases
  return [] if num == 0
  return [0] if num == 1
  return [0,1] if num == 2

  # Recursion
  seq = fib_seq(num - 1)

  # The recursive function
  seq << seq[-2] + seq[-1]

  return seq
end
</code>```

Now it's a bit clearer that return [0,1] if num == 2 is one of three base cases for the recursion. These are the terminating conditions which stops the recursion. But processing doesn't end there. The result isn't [0,1] because after that first return the stack has to unwind.

Let's walk through fib_seq(4).

```<code>fib_seq(4) calls fib_seq(3)
fib_seq(3) calls fib_seq(2)
fib_seq(2) returns `[0,1]`
</code>```

We've reached the base case, now we need to unwind that stack of calls.

The call to fib_seq(3) picks up where it left off. seq returned from fib_seq(2) is [0,1]. It adds seq[-2] + seq[-1] onto the end and returns [0,1,1].

fib_seq(4) picks up where it left off. seq returned from fib_seq(3) is [0,1,1]. It adds seq[-2] + seq[-1] to the end and returns [0,1,1,2].

The stack is unwound, so we get back [0,1,1,2].

As you can see, the actual calculation happens backwards. f(n) = f(n-1) + f(n-2) and f(2) = [0,1]. It recurses down to f(2), the base case, then unwinds back up doing f(3) using the result of f(2), and f(4) using the result of f(3) and so on.

Title: Recursive Fibonacci in Ruby

Body:
This week is my first time doing recursion. One of the problems I was able to solve was Fibonacci's sequence to the nth number; it wasn't hard after messing with it for 5 minutes.

However, I am having trouble understanding why this works with the current return statement.

return array if num == 2

If I push to array, it doesn't work, if I make a new variable sequence and push to that, it returns the correct answer. I am cool with that, but my base case says return array, not sequence. I initially pushed the sequence to the array, the result was not fibs sequence. I only solved the problem when I tried seeing what would happen if I pushed to the sequence array.

Instead of just making it work I was hoping someone could explain what was happening under the hood, what the stacks might be and how the problem works.

I understand recursion to an extent and somehow intuitively can make it work by assuming things, but I feel funny not actually knowing all the whys behind it.

def fib_seq(num)
  return [0] if num == 1
  return [] if num == 0

  array = [0, 1]
  return array if num <= 2

  seq = fib_seq(num - 1)
  seq << seq[-2] + seq[-1]
end

Body:
The code can be simplified a bit by removing the temporary array variable. It's a distraction. It also only applies when num == 2; num < 2 will be handled by the other base cases. num < 0 is illegal and should be handled by an error check.

I've also added in an explicit return. Explicit returns make it very obvious what's being returned and that helps understand recursion. In this case it's seq. ("Explicit returns are evil!" all the Ruby style people cry. Tough cookies. Good style isn't an absolute.)

def fib_seq(num)
  # Error check
  if num < 0 then
      raise ArgumentError, "The number must be a positive integer"
  end

  # Terminating base cases
  return [] if num == 0
  return [0] if num == 1
  return [0,1] if num == 2

  # Recursion
  seq = fib_seq(num - 1)

  # The recursive function
  seq << seq[-2] + seq[-1]

  return seq
end

Now it's a bit clearer that return [0,1] if num == 2 is one of three base cases for the recursion. These are the terminating conditions which stops the recursion. But processing doesn't end there. The result isn't [0,1] because after that first return the stack has to unwind.

Let's walk through fib_seq(4).

fib_seq(4) calls fib_seq(3)
fib_seq(3) calls fib_seq(2)
fib_seq(2) returns `[0,1]`

We've reached the base case, now we need to unwind that stack of calls.

The call to fib_seq(3) picks up where it left off. seq returned from fib_seq(2) is [0,1]. It adds seq[-2] + seq[-1] onto the end and returns [0,1,1].

fib_seq(4) picks up where it left off. seq returned from fib_seq(3) is [0,1,1]. It adds seq[-2] + seq[-1] to the end and returns [0,1,1,2].

The stack is unwound, so we get back [0,1,1,2].

As you can see, the actual calculation happens backwards. f(n) = f(n-1) + f(n-2) and f(2) = [0,1]. It recurses down to f(2), the base case, then unwinds back up doing f(3) using the result of f(2), and f(4) using the result of f(3) and so on.


问:
What is the use of .qmg file in android?
can anyone help me out for this?

whats the use of .qmg file for Bootanimation.

Thanx

答: Qmg files are the outdated boot animation system that Samsung uses.  Most websites only provide zip files which don't work on Samsung devices.  If you want to install zip files on Samsung phones you have to install a custom ROM.</p>


问:
Is there a way to give an iOS app to one person through Xcode?
I have built this app for my cousin. Is there a way I can give it to him and only him? I know I can build it directly on his phone, but I believe that will only work for 30 days after the build, and he lives 8+ hours away so I cannot keep doing that. Any answers would be much appreciated!</p>

答:
If you build the app directly to his phone, the app will expire after 1 week or 1 year depending if you have a free developer account or a paid account. If he has a Mac accessible, he could download Xcode and you could send him the source project for him to build it to his own phone.

You could also use Apple's TestFlight service, which requires a paid developer account. This is probably the easiest and most Apple-approved method, but the apps will expire after 60 days unless you submit an update.

You could use also use a third-party distribution service like HockeyApp or buddybuild.


问:
Why do I return a series of a chars for a pointer return type?
I am trying my best to return a pointer with a specific value. Though, I am not understanding why I am getting more chars than usual. I asked a few people and I was told that I am getting a substring?

Problem: I type in the word hotdog.
I expect to return a pointer at the index[2]. Though instead, I get the chars dog. Why is that? How would I get just index[2]? I am thinking about dereferencing it, but I am having problems in getting the return type to work.

I cannot change the return type or parameters for my function.

```<code>#include <iostream>

char * GetValueAtIndex(char * const c, int index);
void ReadString(char * c, int length);

int main()

{
    const int size = 10;
    char ma[size];
    char * pointer = ma;

    ReadString(ma, 20);
    std::cout << GetValueAtIndex(pointer, 3) << std::endl;
    system("pause");
}

void ReadString(char * c, int length)
{
    std::cin.getline(c, length);
}

char * GetValueAtIndex(char * const c, int index)
{

    return c + index;

}
</code>```

答:
Why do I return a series of a chars for a pointer return type?

You return a pointer to a character, exactly as you state what you're trying to do.

I expect to return a pointer at the index[2]

That pointer was returned, as you expected.

Though instead, I get the chars dog.

That is because you insert the pointer into a stream. The stream insertion operator for char* requires that the input is a pointer to a null terminated string and the behaviour is to print that entire string. Your pointer points to an array of chars starting from the character 'd'.

I am thinking about dereferencing it

If you dereference the pointer, you will get the character that is pointed to ('d'):

```<code>std::cout << *GetValueAtIndex(pointer, 3) << std::endl;
</code>```

Body:
I am trying my best to return a pointer with a specific value. Though, I am not understanding why I am getting more chars than usual. I asked a few people and I was told that I am getting a substring?

Problem: I type in the word hotdog.
I expect to return a pointer at the index[2]. Though instead, I get the chars dog. Why is that? How would I get just index[2]? I am thinking about dereferencing it, but I am having problems in getting the return type to work.

I cannot change the return type or parameters for my function.

#include <iostream>

char * GetValueAtIndex(char * const c, int index);
void ReadString(char * c, int length);

int main()

{
    const int size = 10;
    char ma[size];
    char * pointer = ma;

    ReadString(ma, 20);
    std::cout << GetValueAtIndex(pointer, 3) << std::endl;
    system("pause");
}

void ReadString(char * c, int length)
{
    std::cin.getline(c, length);
}

char * GetValueAtIndex(char * const c, int index)
{

    return c + index;

}

Body:
Why do I return a series of a chars for a pointer return type?

You return a pointer to a character, exactly as you state what you're trying to do.

I expect to return a pointer at the index[2]

That pointer was returned, as you expected.

Though instead, I get the chars dog.

That is because you insert the pointer into a stream. The stream insertion operator for char* requires that the input is a pointer to a null terminated string and the behaviour is to print that entire string. Your pointer points to an array of chars starting from the character 'd'.

I am thinking about dereferencing it

If you dereference the pointer, you will get the character that is pointed to ('d'):

std::cout << *GetValueAtIndex(pointer, 3) << std::endl;


问:
WinAPI AttachConsole?
I have the following code and I'm not sure if it should be == TRUE or != FALSE.

This is the code now:

```<code>void AttachConsole() {
    bool has_console = ::AttachConsole(ATTACH_PARENT_PROCESS) == TRUE;

    if (!has_console) {
        // We weren't launched from a console, so just return.
        // We could alloc our own console, but meh:
        // has_console = AllocConsole() == TRUE;
        has_console_attached_ = false;

        return;
    }

    has_console_attached_ = true;
}
</code>```

I think it should be != FALSE but I'm not sure?

答:
The return value is documented only as being 0 for failure or non-zero for success.

So yes, you could use != FALSE or you could just use:

```<code>bool has_console = ::AttachConsole(ATTACH_PARENT_PROCESS);
</code>```

The conversion from BOOL (really an integer) to bool will convert 0 to false, and anything else to true--exactly what you want.

Title: WinAPI AttachConsole?

Body:
I have the following code and I'm not sure if it should be == TRUE or != FALSE.

This is the code now:

void AttachConsole() {
    bool has_console = ::AttachConsole(ATTACH_PARENT_PROCESS) == TRUE;

    if (!has_console) {
        // We weren't launched from a console, so just return.
        // We could alloc our own console, but meh:
        // has_console = AllocConsole() == TRUE;
        has_console_attached_ = false;

        return;
    }

    has_console_attached_ = true;
}

I think it should be != FALSE but I'm not sure?

Body:
The return value is documented only as being 0 for failure or non-zero for success.

So yes, you could use != FALSE or you could just use:

bool has_console = ::AttachConsole(ATTACH_PARENT_PROCESS);

The conversion from BOOL (really an integer) to bool will convert 0 to false, and anything else to true--exactly what you want.


问:
Self signed X509 Certificate with Bouncy Castle in Java
I need to create a self signed X509 Certificate with Bouncy Castle in Java, but every class I try to include is deprecated.
How can I solve this? Is there some other class to include?
Thanks</p>

答:
Here's a complete self-signed ECDSA certificate generator that creates certificates usable in TLS connections on both client and server side. It was tested with BouncyCastle 1.57. Similar code can be used to create RSA certificates.</p>

```<code>SecureRandom random = new SecureRandom();

// create keypair
KeyPairGenerator keypairGen = KeyPairGenerator.getInstance("EC");
keypairGen.initialize(256, random);
KeyPair keypair = keypairGen.generateKeyPair();

// fill in certificate fields
X500Name subject = new X500NameBuilder(BCStyle.INSTANCE)
    .addRDN(BCStyle.CN, "stackoverflow.com")
    .build();
byte[] id = new byte[20];
random.nextBytes(id);
BigInteger serial = new BigInteger(160, random);
X509v3CertificateBuilder certificate = new JcaX509v3CertificateBuilder(
    subject,
    serial,
    Date.from(LocalDate.of(2000, 1, 1).atStartOfDay(ZoneOffset.UTC).toInstant()),
    Date.from(LocalDate.of(2035, 1, 1).atStartOfDay(ZoneOffset.UTC).toInstant()),
    subject,
    keypair.getPublic());
certificate.addExtension(Extension.subjectKeyIdentifier, false, id);
certificate.addExtension(Extension.authorityKeyIdentifier, false, id);
BasicConstraints constraints = new BasicConstraints(true);
certificate.addExtension(
    Extension.basicConstraints,
    true,
    constraints.getEncoded());
KeyUsage usage = new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature);
certificate.addExtension(Extension.keyUsage, false, usage.getEncoded());
ExtendedKeyUsage usageEx = new ExtendedKeyUsage(new KeyPurposeId[] {
    KeyPurposeId.id_kp_serverAuth,
    KeyPurposeId.id_kp_clientAuth
});
certificate.addExtension(
    Extension.extendedKeyUsage,
    false,
    usageEx.getEncoded());

// build BouncyCastle certificate
ContentSigner signer = new JcaContentSignerBuilder("SHA256withECDSA")
    .build(keypair.getPrivate());
X509CertificateHolder holder = certificate.build(signer);

// convert to JRE certificate
JcaX509CertificateConverter converter = new JcaX509CertificateConverter();
converter.setProvider(new BouncyCastleProvider());
X509Certificate x509 = converter.getCertificate(holder);

// serialize in DER format
byte[] serialized = x509.getEncoded();
</code>```

Body:
Here's a complete self-signed ECDSA certificate generator that creates certificates usable in TLS connections on both client and server side. It was tested with BouncyCastle 1.57. Similar code can be used to create RSA certificates.

SecureRandom random = new SecureRandom();

// create keypair
KeyPairGenerator keypairGen = KeyPairGenerator.getInstance("EC");
keypairGen.initialize(256, random);
KeyPair keypair = keypairGen.generateKeyPair();

// fill in certificate fields
X500Name subject = new X500NameBuilder(BCStyle.INSTANCE)
    .addRDN(BCStyle.CN, "stackoverflow.com")
    .build();
byte[] id = new byte[20];
random.nextBytes(id);
BigInteger serial = new BigInteger(160, random);
X509v3CertificateBuilder certificate = new JcaX509v3CertificateBuilder(
    subject,
    serial,
    Date.from(LocalDate.of(2000, 1, 1).atStartOfDay(ZoneOffset.UTC).toInstant()),
    Date.from(LocalDate.of(2035, 1, 1).atStartOfDay(ZoneOffset.UTC).toInstant()),
    subject,
    keypair.getPublic());
certificate.addExtension(Extension.subjectKeyIdentifier, false, id);
certificate.addExtension(Extension.authorityKeyIdentifier, false, id);
BasicConstraints constraints = new BasicConstraints(true);
certificate.addExtension(
    Extension.basicConstraints,
    true,
    constraints.getEncoded());
KeyUsage usage = new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature);
certificate.addExtension(Extension.keyUsage, false, usage.getEncoded());
ExtendedKeyUsage usageEx = new ExtendedKeyUsage(new KeyPurposeId[] {
    KeyPurposeId.id_kp_serverAuth,
    KeyPurposeId.id_kp_clientAuth
});
certificate.addExtension(
    Extension.extendedKeyUsage,
    false,
    usageEx.getEncoded());

// build BouncyCastle certificate
ContentSigner signer = new JcaContentSignerBuilder("SHA256withECDSA")
    .build(keypair.getPrivate());
X509CertificateHolder holder = certificate.build(signer);

// convert to JRE certificate
JcaX509CertificateConverter converter = new JcaX509CertificateConverter();
converter.setProvider(new BouncyCastleProvider());
X509Certificate x509 = converter.getCertificate(holder);

// serialize in DER format
byte[] serialized = x509.getEncoded();


问:
Performance decline after switching the MySql table engine from innoDB to NDB
I'm building a website based on WordPress 4.8. The default table engine is innoDB after going through the installation steps, and everything works fine. While my DBA asked me to change the table engine to NDB, for easy data replication. While after the change, the home pages loads very slowly. After some debugging, I found there are queries take over 10 seconds.

Although I will definitely add some caching mechanism when releasing the website, but I'd like to firstly figure out if there is something we can fix from the DB side, before I adding the cache or optimizing the query. As the query time is 0.4 seconds with innoDB, and my DBA told me NDB should have better performance.

Following is one query that takes 14 seconds for your references, please advice if you have any idea. Thanks!

```<code>SELECT SQL_CALC_FOUND_ROWS team_football_1001_posts.ID
FROM team_football_1001_posts
LEFT JOIN team_football_1001_postmeta
ON ( team_football_1001_posts.ID = team_football_1001_postmeta.post_id )
LEFT JOIN team_football_1001_postmeta AS mt1
ON ( team_football_1001_posts.ID = mt1.post_id )
LEFT JOIN team_football_1001_postmeta AS mt2
ON ( team_football_1001_posts.ID = mt2.post_id )
LEFT JOIN team_football_1001_postmeta AS mt3
ON (team_football_1001_posts.ID = mt3.post_id
AND mt3.meta_key = '_team_winner_id' )
WHERE 1=1
AND ( team_football_1001_postmeta.meta_key = '_date_start'
AND ( ( ( mt1.meta_key = '_date_start'
AND mt1.meta_value > '2017-07-07 06:48:49' )
OR ( ( mt2.meta_key = '_date_start'
AND mt2.meta_value < '2017-07-07 06:48:49' )
AND mt3.post_id IS NULL ) ) ) )
AND team_football_1001_posts.post_type = 'matches'
AND ((team_football_1001_posts.post_status = 'publish'))
GROUP BY team_football_1001_posts.ID
ORDER BY team_football_1001_postmeta.meta_value DESC
LIMIT 0, 3
</code>```

Attached the tables schemas for reference:

```<code>CREATE TABLE `team_football_1001_posts` (
  `ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `post_author` bigint(20) unsigned NOT NULL DEFAULT '0',
  `post_date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  `post_date_gmt` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  `post_content` longtext COLLATE utf8mb4_unicode_ci NOT NULL,
  `post_title` text COLLATE utf8mb4_unicode_ci NOT NULL,
  `post_excerpt` text COLLATE utf8mb4_unicode_ci NOT NULL,
  `post_status` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'publish',
  `comment_status` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'open',
  `ping_status` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'open',
  `post_password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  `post_name` varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  `to_ping` text COLLATE utf8mb4_unicode_ci NOT NULL,
  `pinged` text COLLATE utf8mb4_unicode_ci NOT NULL,
  `post_modified` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  `post_modified_gmt` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  `post_content_filtered` longtext COLLATE utf8mb4_unicode_ci NOT NULL,
  `post_parent` bigint(20) unsigned NOT NULL DEFAULT '0',
  `guid` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  `menu_order` int(11) NOT NULL DEFAULT '0',
  `post_type` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'post',
  `post_mime_type` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  `comment_count` bigint(20) NOT NULL DEFAULT '0',
  PRIMARY KEY (`ID`),
  KEY `post_name` (`post_name`(191)),
  KEY `type_status_date` (`post_type`,`post_status`,`post_date`,`ID`),
  KEY `post_parent` (`post_parent`),
  KEY `post_author` (`post_author`)
) ENGINE=InnoDB AUTO_INCREMENT=2200 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `team_football_1001_postmeta` (
  `meta_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `post_id` bigint(20) unsigned NOT NULL DEFAULT '0',
  `meta_key` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `meta_value` longtext COLLATE utf8mb4_unicode_ci,
  PRIMARY KEY (`meta_id`),
  KEY `post_id` (`post_id`),
  KEY `meta_key` (`meta_key`(191))
) ENGINE=InnoDB AUTO_INCREMENT=22648 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
</code>```

答: Reloading the data can already change query time (the dbms builds new histogram information and can come to a different execution plan). This is a regular and normal event on which the user has to respond and adjust either indexing or query. To stabilize the situation running regular maintenance is advisable, or sometimes data model changes are required. The goal of the maintenance or the changes is to stabilize the statistical view on the data which is used by the optimizer so that the optimizer always makes the same choice for the execution plan. Oh, often asked: Are there shortcuts? No.</p>

Body:
I'm building a website based on WordPress 4.8. The default table engine is innoDB after going through the installation steps, and everything works fine. While my DBA asked me to change the table engine to NDB, for easy data replication. While after the change, the home pages loads very slowly. After some debugging, I found there are queries take over 10 seconds.

Although I will definitely add some caching mechanism when releasing the website, but I'd like to firstly figure out if there is something we can fix from the DB side, before I adding the cache or optimizing the query. As the query time is 0.4 seconds with innoDB, and my DBA told me NDB should have better performance.

Following is one query that takes 14 seconds for your references, please advice if you have any idea. Thanks!

SELECT SQL_CALC_FOUND_ROWS team_football_1001_posts.ID
FROM team_football_1001_posts
LEFT JOIN team_football_1001_postmeta
ON ( team_football_1001_posts.ID = team_football_1001_postmeta.post_id )
LEFT JOIN team_football_1001_postmeta AS mt1
ON ( team_football_1001_posts.ID = mt1.post_id )
LEFT JOIN team_football_1001_postmeta AS mt2
ON ( team_football_1001_posts.ID = mt2.post_id )
LEFT JOIN team_football_1001_postmeta AS mt3
ON (team_football_1001_posts.ID = mt3.post_id
AND mt3.meta_key = '_team_winner_id' )
WHERE 1=1
AND ( team_football_1001_postmeta.meta_key = '_date_start'
AND ( ( ( mt1.meta_key = '_date_start'
AND mt1.meta_value > '2017-07-07 06:48:49' )
OR ( ( mt2.meta_key = '_date_start'
AND mt2.meta_value < '2017-07-07 06:48:49' )
AND mt3.post_id IS NULL ) ) ) )
AND team_football_1001_posts.post_type = 'matches'
AND ((team_football_1001_posts.post_status = 'publish'))
GROUP BY team_football_1001_posts.ID
ORDER BY team_football_1001_postmeta.meta_value DESC
LIMIT 0, 3

Attached the tables schemas for reference:

CREATE TABLE `team_football_1001_posts` (
  `ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `post_author` bigint(20) unsigned NOT NULL DEFAULT '0',
  `post_date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  `post_date_gmt` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  `post_content` longtext COLLATE utf8mb4_unicode_ci NOT NULL,
  `post_title` text COLLATE utf8mb4_unicode_ci NOT NULL,
  `post_excerpt` text COLLATE utf8mb4_unicode_ci NOT NULL,
  `post_status` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'publish',
  `comment_status` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'open',
  `ping_status` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'open',
  `post_password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  `post_name` varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  `to_ping` text COLLATE utf8mb4_unicode_ci NOT NULL,
  `pinged` text COLLATE utf8mb4_unicode_ci NOT NULL,
  `post_modified` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  `post_modified_gmt` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  `post_content_filtered` longtext COLLATE utf8mb4_unicode_ci NOT NULL,
  `post_parent` bigint(20) unsigned NOT NULL DEFAULT '0',
  `guid` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  `menu_order` int(11) NOT NULL DEFAULT '0',
  `post_type` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'post',
  `post_mime_type` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  `comment_count` bigint(20) NOT NULL DEFAULT '0',
  PRIMARY KEY (`ID`),
  KEY `post_name` (`post_name`(191)),
  KEY `type_status_date` (`post_type`,`post_status`,`post_date`,`ID`),
  KEY `post_parent` (`post_parent`),
  KEY `post_author` (`post_author`)
) ENGINE=InnoDB AUTO_INCREMENT=2200 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `team_football_1001_postmeta` (
  `meta_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `post_id` bigint(20) unsigned NOT NULL DEFAULT '0',
  `meta_key` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `meta_value` longtext COLLATE utf8mb4_unicode_ci,
  PRIMARY KEY (`meta_id`),
  KEY `post_id` (`post_id`),
  KEY `meta_key` (`meta_key`(191))
) ENGINE=InnoDB AUTO_INCREMENT=22648 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;


问:
Rails : How to build statistics per day/month/year or How database agnostic SQL functions are missing (ex. : STRFTIME, DATE_FORMAT, DATE_TRUNC)
I have been searching all over the web and I have no clue.

Suppose you have to build a dashboard in the admin area of your Rails app and you want to have the number of subscriptions per day.

Suppose that you are using SQLite3 for development, MySQL for production (pretty standard setup)

Basically, there are two options :

1) Retrieve all rows from the database using Subscriber.all and aggregate by day in the Rails app using the Enumerable.group_by :

```<code>@subscribers = Subscriber.all
@subscriptions_per_day = @subscribers.group_by { |s| s.created_at.beginning_of_day }
</code>```

I think this is a really bad idea. Retrieving all rows from the database can be acceptable for a small application, but it will not scale at all. Database aggregate and date functions to the rescue !

2) Run a SQL query in the database using aggregate and date functions :

```<code>Subscriber.select('STRFTIME("%Y-%m-%d", created_at) AS day, COUNT(*) AS subscriptions').group('day')
</code>```

Which will run in this SQL query :

```<code>SELECT STRFTIME("%Y-%m-%d", created_at) AS day, COUNT(*) AS subscriptions
FROM subscribers
GROUP BY day
</code>```

Much better. Now aggregates are done in the database which is optimized for this kind of task, and only one row per day is returned from the database to the Rails app.

... but wait... now the app has to go live in my production env which uses MySQL !
Replace STRFTIME() with DATE_FORMAT().
What if tomorrow I switch to PostgreSQL ?
Replace DATE_FORMAT() with DATE_TRUNC().

I like to develop with SQLite. Simple and easy.
I also like the idea that Rails is database agnostic.
But why Rails doesn't provide a way to translate SQL functions that do the exact same thing, but have different syntax in each RDBMS (this difference is really stupid, but hey, it's too late to complain about it) ?

I can't believe that I find so few answers on the Web for such a basic feature of a Rails app : count the subscriptions per day, month or year.

Tell me I'm missing something :)

EDIT

It's been a few years since I posted this question.
Experience has shown that I should use the same DB for dev and prod. So I now consider the database agnostic requirement irrelevant.

Dev/prod parity FTW.

答:
I ended up writing my own gem. Check it out and feel free to contribute:
https://github.com/lakim/sql_funk

It allows you to make calls like:

```<code>Subscriber.count_by("created_at", :group_by => "day")
</code>```

Body:
I have been searching all over the web and I have no clue.

Suppose you have to build a dashboard in the admin area of your Rails app and you want to have the number of subscriptions per day.

Suppose that you are using SQLite3 for development, MySQL for production (pretty standard setup)

Basically, there are two options :

1) Retrieve all rows from the database using Subscriber.all and aggregate by day in the Rails app using the Enumerable.group_by :

@subscribers = Subscriber.all
@subscriptions_per_day = @subscribers.group_by { |s| s.created_at.beginning_of_day }

I think this is a really bad idea. Retrieving all rows from the database can be acceptable for a small application, but it will not scale at all. Database aggregate and date functions to the rescue !

2) Run a SQL query in the database using aggregate and date functions :

Subscriber.select('STRFTIME("%Y-%m-%d", created_at) AS day, COUNT(*) AS subscriptions').group('day')

Which will run in this SQL query :

SELECT STRFTIME("%Y-%m-%d", created_at) AS day, COUNT(*) AS subscriptions
FROM subscribers
GROUP BY day

Much better. Now aggregates are done in the database which is optimized for this kind of task, and only one row per day is returned from the database to the Rails app.

... but wait... now the app has to go live in my production env which uses MySQL !
Replace STRFTIME() with DATE_FORMAT().
What if tomorrow I switch to PostgreSQL ?
Replace DATE_FORMAT() with DATE_TRUNC().

I like to develop with SQLite. Simple and easy.
I also like the idea that Rails is database agnostic.
But why Rails doesn't provide a way to translate SQL functions that do the exact same thing, but have different syntax in each RDBMS (this difference is really stupid, but hey, it's too late to complain about it) ?

I can't believe that I find so few answers on the Web for such a basic feature of a Rails app : count the subscriptions per day, month or year.

Tell me I'm missing something :)

EDIT

It's been a few years since I posted this question.
Experience has shown that I should use the same DB for dev and prod. So I now consider the database agnostic requirement irrelevant.

Dev/prod parity FTW.

Body:
I ended up writing my own gem. Check it out and feel free to contribute:
https://github.com/lakim/sql_funk

It allows you to make calls like:

Subscriber.count_by("created_at", :group_by => "day")


问:
How can I convert an integer into its verbal representation?
Is there a library or a class/function that I can use to convert an integer to it's verbal representation?

Example input:

4,567,788`

Example output:

Four million, Five hundred sixty-seven thousand, seven hundred eighty-eight

答:
This solution takes advantage of C# 7.0's support for local functions. I also used the new digit separator to make the larger numbers more readable.

```<code>public static class NumberExtensions
{
    private const string negativeWord = "negative";
    private static readonly Dictionary<ulong, string> _wordMap = new Dictionary<ulong, string>
    {
        [1_000_000_000_000_000_000] = "quintillion",
        [1_000_000_000_000_000] = "quadrillion",
        [1_000_000_000_000] = "trillion",
        [1_000_000_000] = "billion",
        [1_000_000] = "million",
        [1_000] = "thousand",
        [100] = "hundred",
        [90] = "ninety",
        [80] = "eighty",
        [70] = "seventy",
        [60] = "sixty",
        [50] = "fifty",
        [40] = "forty",
        [30] = "thirty",
        [20] = "twenty",
        [19] = "nineteen",
        [18] = "eighteen",
        [17] = "seventeen",
        [16] = "sixteen",
        [15] = "fifteen",
        [14] = "fourteen",
        [13] = "thirteen",
        [12] = "twelve",
        [11] = "eleven",
        [10] = "ten",
        [9] = "nine",
        [8] = "eight",
        [7] = "seven",
        [6] = "six",
        [5] = "five",
        [4] = "four",
        [3] = "three",
        [2] = "two",
        [1] = "one",
        [0] = "zero"
    };

    public static string ToWords(this short num)
    {
        var words = ToWords((ulong)Math.Abs(num));
        return num < 0 ? $"{negativeWord} {words}" : words;
    }

    public static string ToWords(this ushort num)
    {
        return ToWords((ulong)num);
    }

    public static string ToWords(this int num)
    {
        var words = ToWords((ulong)Math.Abs(num));
        return num < 0 ? $"{negativeWord} {words}" : words;
    }

    public static string ToWords(this uint num)
    {
        return ToWords((ulong)num);
    }

    public static string ToWords(this long num)
    {
        var words = ToWords((ulong)Math.Abs(num));
        return num < 0 ? $"{negativeWord} {words}" : words;
    }

    public static string ToWords(this ulong num)
    {
        var sb = new StringBuilder();
        var delimiter = String.Empty;

        void AppendWords(ulong dividend)
        {
            void AppendDelimitedWord(ulong key)
            {
                sb.Append(delimiter);
                sb.Append(_wordMap[key]);
                delimiter = 20 <= key && key < 100 ? "-" : " ";
            }

            if (_wordMap.ContainsKey(dividend))
            {
                AppendDelimitedWord(dividend);
            }
            else
            {
                var divisor = _wordMap.First(m => m.Key <= dividend).Key;
                var quotient = dividend / divisor;
                var remainder = dividend % divisor;

                if (quotient > 0 && divisor >= 100)
                {
                    AppendWords(quotient);
                }

                AppendDelimitedWord(divisor);

                if (remainder > 0)
                {
                    AppendWords(remainder);
                }
            }
        }

        AppendWords(num);
        return sb.ToString();
    }
}
</code>```

The meat is in the last ToWords overload.

OwnerDisplayName: Malfist

LastEditorDisplayName: Simucal

Body:
This solution takes advantage of C# 7.0's support for local functions. I also used the new digit separator to make the larger numbers more readable.

public static class NumberExtensions
{
    private const string negativeWord = "negative";
    private static readonly Dictionary<ulong, string> _wordMap = new Dictionary<ulong, string>
    {
        [1_000_000_000_000_000_000] = "quintillion",
        [1_000_000_000_000_000] = "quadrillion",
        [1_000_000_000_000] = "trillion",
        [1_000_000_000] = "billion",
        [1_000_000] = "million",
        [1_000] = "thousand",
        [100] = "hundred",
        [90] = "ninety",
        [80] = "eighty",
        [70] = "seventy",
        [60] = "sixty",
        [50] = "fifty",
        [40] = "forty",
        [30] = "thirty",
        [20] = "twenty",
        [19] = "nineteen",
        [18] = "eighteen",
        [17] = "seventeen",
        [16] = "sixteen",
        [15] = "fifteen",
        [14] = "fourteen",
        [13] = "thirteen",
        [12] = "twelve",
        [11] = "eleven",
        [10] = "ten",
        [9] = "nine",
        [8] = "eight",
        [7] = "seven",
        [6] = "six",
        [5] = "five",
        [4] = "four",
        [3] = "three",
        [2] = "two",
        [1] = "one",
        [0] = "zero"
    };

    public static string ToWords(this short num)
    {
        var words = ToWords((ulong)Math.Abs(num));
        return num < 0 ? $"{negativeWord} {words}" : words;
    }

    public static string ToWords(this ushort num)
    {
        return ToWords((ulong)num);
    }

    public static string ToWords(this int num)
    {
        var words = ToWords((ulong)Math.Abs(num));
        return num < 0 ? $"{negativeWord} {words}" : words;
    }

    public static string ToWords(this uint num)
    {
        return ToWords((ulong)num);
    }

    public static string ToWords(this long num)
    {
        var words = ToWords((ulong)Math.Abs(num));
        return num < 0 ? $"{negativeWord} {words}" : words;
    }

    public static string ToWords(this ulong num)
    {
        var sb = new StringBuilder();
        var delimiter = String.Empty;

        void AppendWords(ulong dividend)
        {
            void AppendDelimitedWord(ulong key)
            {
                sb.Append(delimiter);
                sb.Append(_wordMap[key]);
                delimiter = 20 <= key && key < 100 ? "-" : " ";
            }

            if (_wordMap.ContainsKey(dividend))
            {
                AppendDelimitedWord(dividend);
            }
            else
            {
                var divisor = _wordMap.First(m => m.Key <= dividend).Key;
                var quotient = dividend / divisor;
                var remainder = dividend % divisor;

                if (quotient > 0 && divisor >= 100)
                {
                    AppendWords(quotient);
                }

                AppendDelimitedWord(divisor);

                if (remainder > 0)
                {
                    AppendWords(remainder);
                }
            }
        }

        AppendWords(num);
        return sb.ToString();
    }
}

The meat is in the last ToWords overload.

ContentLicense: CC BY-SA 4.0


问:
Get ParameterizedType from scala's Type?
Helpfully, scala's universe.typeOf preserves the type parameters of a class.

```<code>import scala.reflect.runtime.universe._

case class X[T:TypeTag]() {
  val t = typeOf[T] // e.g. Seq[Int]  Holds type parameters
  val clz:Class[_] = runtimeMirror(this.getClass.getClassLoader).runtimeClass(t.typeSymbol.asClass)
}

X[Seq[Int]]().t // Seq[Int]
X[Seq[Int]]().clz // Seq    :-(
</code>```

Java's ParameterizedType holds the same un-erased information. How can I convert a scala Type into an Java ParameterizedType?

```<code>import scala.reflect.runtime.universe._

case class X[T:TypeTag]() {
  val clz:Class[_] = runtimeMirror(this.getClass.getClassLoader).runtimeClass(typeOf[T].typeSymbol.asClass)
}
</code>```

答:
```<code>  private def parameterizedType(paramType: Type): java.lang.reflect.Type = {
    val typeConstructor = currentMirror.runtimeClass(paramType)

    val innerTypes = paramType.typeArgs.map(parameterizedType).toArray

    if (innerTypes.isEmpty) {
      typeConstructor
    } else {
      new ParameterizedType {
        override def getRawType: reflect.Type = {
          typeConstructor
        }

        override def getActualTypeArguments: Array[reflect.Type] = {
          innerTypes
        }

        override def getOwnerType: reflect.Type = {
          null
        }
      }
    }
  }

  def makeType[T : TypeTag]: reflect.Type = {
      parameterizedType(typeOf[T])
  }
</code>```

Seems to do the trick. Basically just iterating through the parameterized types and converting it to a java parameterized type object

Body:
Helpfully, scala's universe.typeOf preserves the type parameters of a class.

import scala.reflect.runtime.universe._

case class X[T:TypeTag]() {
  val t = typeOf[T] // e.g. Seq[Int]  Holds type parameters
  val clz:Class[_] = runtimeMirror(this.getClass.getClassLoader).runtimeClass(t.typeSymbol.asClass)
}

X[Seq[Int]]().t // Seq[Int]
X[Seq[Int]]().clz // Seq    :-(

Java's ParameterizedType holds the same un-erased information. How can I convert a scala Type into an Java ParameterizedType?

import scala.reflect.runtime.universe._

case class X[T:TypeTag]() {
  val clz:Class[_] = runtimeMirror(this.getClass.getClassLoader).runtimeClass(typeOf[T].typeSymbol.asClass)
}

Body:
  private def parameterizedType(paramType: Type): java.lang.reflect.Type = {
    val typeConstructor = currentMirror.runtimeClass(paramType)

    val innerTypes = paramType.typeArgs.map(parameterizedType).toArray

    if (innerTypes.isEmpty) {
      typeConstructor
    } else {
      new ParameterizedType {
        override def getRawType: reflect.Type = {
          typeConstructor
        }

        override def getActualTypeArguments: Array[reflect.Type] = {
          innerTypes
        }

        override def getOwnerType: reflect.Type = {
          null
        }
      }
    }
  }

  def makeType[T : TypeTag]: reflect.Type = {
      parameterizedType(typeOf[T])
  }

Seems to do the trick. Basically just iterating through the parameterized types and converting it to a java parameterized type object


问:
Parsley.js Dynamic messages in custom validator
I'm using a custom validator to check for date of birth, so far it has almost nothing, but I'm trying to add a dynamic message depending on the error and it's not working for me it displays the container with a blank message, any ideas?

Here's the piece of code the custom validator:

```<code>window.Parsley.addValidator('age', {
            validate: function(value, id){
                switch(id){
                    case 'main':
                        var day = $('#birthdate_day').val();
                        var month = $('#birthdate_month').val();
                        var year = $('#birthdate_year').val();
                        if(!day || !month || !year){

                            window.Parsley.addMessage('en', 'age','Error1 ');

                            return false;
                        } else {
                            window.Parsley.addMessage('en', 'age','Error 2');
                        }
                    break;
                }
                return true;
            },
            messages: {
                en: 'Default error',
            }
        });
</code>```

Another thing I've tried is setting the data-parsley-age-message="error" during the execution of the validation, but it only shows the error the second time the validation is ran.

Thanks in advance.

EDIT1:

```<code> window.Parsley.addValidator('age', {
            validate: function(value, id){
                $('.birthdate_container').find('ul').remove();
                switch(id){
                    case 'main':
                        var day = $('#birthdate_day').val();
                        var month = $('#birthdate_month').val();
                        var year = $('#birthdate_year').val();
                        if(!day || !month || !year){
                            return $.Deferred().reject("One of them is blank");
                        } else if(day > 2 || month > 2 || year < 2016){
                            return $.Deferred().reject("Else test of another message");
                        } else {
                            return true;
                        }
                    break;
                }
                return true;
            },
        });
</code>```

A little cleaner solution (don't mind the else, it's there just for testing) but can't still make it work becasue I don't know how I can update the classes of the 3 elements on returning true.

EDIT 2:

Just using jQuery to handle the classes work, however, since I need to remove the ul (otherwise the messages will stack and I don't want that), whenever there's an error triggered AFTER another error is in there, it simply erases it.

```<code>window.Parsley.addValidator('age', {
            validate: function(value, id){
                $('.birthdate_container').find('ul').remove();
                switch(id){
                    case 'main':
                        var day = $('#birthdate_day').val();
                        var month = $('#birthdate_month').val();
                        var year = $('#birthdate_year').val();
                        if(!day || !month || !year){
                            $('.birthdate_container').find('.parsley-success').removeClass('parsley-success').addClass('parsley-error');
                            return $.Deferred().reject("Un campo es blanco");
                        } else if(day > 2 || month > 2 || year < 2016){
                            $('.birthdate_container').find('.parsley-success').removeClass('parsley-success').addClass('parsley-error');
                            return $.Deferred().reject("dia > 2 o mes > 2 o años < 2016");
                        } else {
                            $('.birthdate_container').find('.parsley-error').removeClass('parsley-error').addClass('parsley-success');
                            return true;
                        }
                    break;
                }
                return true;
            },
        });
</code>```

答:
If you ONLY want to deal with dynamic messages, do not include a message text in your messages object, then in your validation method:

```<code>instance.addError('en', {message: 'Hello World'});
</code>```

It's as simple as that. Just read the annotated source code and it will unveil a whole host of simple features.

EDIT: actually I just noticed you do need something or it throws it's own error message, so you can fix that with something like:

```<code>messages: {
    en: '...'
}
</code>```

I just tested and that works fine

Body:
I'm using a custom validator to check for date of birth, so far it has almost nothing, but I'm trying to add a dynamic message depending on the error and it's not working for me it displays the container with a blank message, any ideas?

Here's the piece of code the custom validator:

window.Parsley.addValidator('age', {
            validate: function(value, id){
                switch(id){
                    case 'main':
                        var day = $('#birthdate_day').val();
                        var month = $('#birthdate_month').val();
                        var year = $('#birthdate_year').val();
                        if(!day || !month || !year){

                            window.Parsley.addMessage('en', 'age','Error1 ');

                            return false;
                        } else {
                            window.Parsley.addMessage('en', 'age','Error 2');
                        }
                    break;
                }
                return true;
            },
            messages: {
                en: 'Default error',
            }
        });

Another thing I've tried is setting the data-parsley-age-message="error" during the execution of the validation, but it only shows the error the second time the validation is ran.

Thanks in advance.

EDIT1:

 window.Parsley.addValidator('age', {
            validate: function(value, id){
                $('.birthdate_container').find('ul').remove();
                switch(id){
                    case 'main':
                        var day = $('#birthdate_day').val();
                        var month = $('#birthdate_month').val();
                        var year = $('#birthdate_year').val();
                        if(!day || !month || !year){
                            return $.Deferred().reject("One of them is blank");
                        } else if(day > 2 || month > 2 || year < 2016){
                            return $.Deferred().reject("Else test of another message");
                        } else {
                            return true;
                        }
                    break;
                }
                return true;
            },
        });

A little cleaner solution (don't mind the else, it's there just for testing) but can't still make it work becasue I don't know how I can update the classes of the 3 elements on returning true.

EDIT 2:

Just using jQuery to handle the classes work, however, since I need to remove the ul (otherwise the messages will stack and I don't want that), whenever there's an error triggered AFTER another error is in there, it simply erases it.

window.Parsley.addValidator('age', {
            validate: function(value, id){
                $('.birthdate_container').find('ul').remove();
                switch(id){
                    case 'main':
                        var day = $('#birthdate_day').val();
                        var month = $('#birthdate_month').val();
                        var year = $('#birthdate_year').val();
                        if(!day || !month || !year){
                            $('.birthdate_container').find('.parsley-success').removeClass('parsley-success').addClass('parsley-error');
                            return $.Deferred().reject("Un campo es blanco");
                        } else if(day > 2 || month > 2 || year < 2016){
                            $('.birthdate_container').find('.parsley-success').removeClass('parsley-success').addClass('parsley-error');
                            return $.Deferred().reject("dia > 2 o mes > 2 o años < 2016");
                        } else {
                            $('.birthdate_container').find('.parsley-error').removeClass('parsley-error').addClass('parsley-success');
                            return true;
                        }
                    break;
                }
                return true;
            },
        });

Body:
If you ONLY want to deal with dynamic messages, do not include a message text in your messages object, then in your validation method:

instance.addError('en', {message: 'Hello World'});

It's as simple as that. Just read the annotated source code and it will unveil a whole host of simple features.

EDIT: actually I just noticed you do need something or it throws it's own error message, so you can fix that with something like:

messages: {
    en: '...'
}

I just tested and that works fine


问:
Object.keys returning as not equal
This is my first post, I have researched but I'm not sure I'm phrasing the question the right way in searches.

I am attempting to compare the keys of an object to the keys in another object (this is for freeCodeCamp algorithms). My code is below:

```<code>function whereAreYou(collection, source) {
  var arr = [];
  for (var i=0;i<collection.length;i++) {
    console.log("Object.keys(source)= " + Object.keys(source));
    console.log("Object.keys(collection[" +i + "]))= " + Object.keys(collection[i]));
    console.log("collection[" +i + "].hasOwnProperty(Object.keys(source))= " + collection[i].hasOwnProperty(Object.keys(source)));
    if (collection[i].hasOwnProperty(Object.keys(source))) {
      var prop = Object.keys(source);
      console.log("prop=" + prop);
      console.log("collection[" +i + "][prop]= " + collection[i][prop]);
      console.log("source[prop]= " + source[prop]);
      if (collection[i][prop] === source[prop]) {
        arr.push(collection[i]);
      }
    }
  }
  return arr;
}
</code>```

When there are multiple keys in the source argument, the

```<code>if (collection[i].hasOwnProperty(Object.keys(source)))
</code>```

returns false even when collection[i] does contain the keys as per below.

```<code>whereAreYou([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "b": 2 })

Object.keys(source)= a,b
Object.keys(collection[0]))= a,b
collection[0].hasOwnProperty(Object.keys(source))= false
Object.keys(source)= a,b
Object.keys(collection[1]))= a
collection[1].hasOwnProperty(Object.keys(source))= false
Object.keys(source)= a,b
Object.keys(collection[2]))= a,b,c
collection[2].hasOwnProperty(Object.keys(source))= false
[]
</code>```

My question is why aren't a,b and a,b equal? Thank you for your time!

答:
FreeCodeCamp is great.  If this is a specific question to some training they have, usually their forums are a pretty good outlet. They'll know more about what you're asking and what it pertains too.  However, if you're just trying to compare objects, this seems quite verbose.

Check out some other posts on stack to see, here are a few links that help understand comparing objects.
Object comparison in JavaScript

From MDN:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness

Title: Object.keys returning as not equal

Body:
This is my first post, I have researched but I'm not sure I'm phrasing the question the right way in searches.

I am attempting to compare the keys of an object to the keys in another object (this is for freeCodeCamp algorithms). My code is below:

function whereAreYou(collection, source) {
  var arr = [];
  for (var i=0;i<collection.length;i++) {
    console.log("Object.keys(source)= " + Object.keys(source));
    console.log("Object.keys(collection[" +i + "]))= " + Object.keys(collection[i]));
    console.log("collection[" +i + "].hasOwnProperty(Object.keys(source))= " + collection[i].hasOwnProperty(Object.keys(source)));
    if (collection[i].hasOwnProperty(Object.keys(source))) {
      var prop = Object.keys(source);
      console.log("prop=" + prop);
      console.log("collection[" +i + "][prop]= " + collection[i][prop]);
      console.log("source[prop]= " + source[prop]);
      if (collection[i][prop] === source[prop]) {
        arr.push(collection[i]);
      }
    }
  }
  return arr;
}

When there are multiple keys in the source argument, the

if (collection[i].hasOwnProperty(Object.keys(source)))

returns false even when collection[i] does contain the keys as per below.

whereAreYou([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "b": 2 })

Object.keys(source)= a,b
Object.keys(collection[0]))= a,b
collection[0].hasOwnProperty(Object.keys(source))= false
Object.keys(source)= a,b
Object.keys(collection[1]))= a
collection[1].hasOwnProperty(Object.keys(source))= false
Object.keys(source)= a,b
Object.keys(collection[2]))= a,b,c
collection[2].hasOwnProperty(Object.keys(source))= false
[]

My question is why aren't a,b and a,b equal? Thank you for your time!


问:
How to map accented characters in keyboard xml
I have to implement a simple custom soft-keyboard in my application and I want to show accented characters on the keyboard too.

These are:
í, é, á, ű, ú, ő, ó, ü, ö

My question is how to map these in the keyboard xml? What are the key codes for these? I could not found them in the official KeyEvent document.

My current keyboard definition xml looks like this:

```<code><Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
    android:keyWidth="10%p"
    android:horizontalGap="0px"
    android:verticalGap="0px"
    >

<Row android:keyHeight="16%">
    <Key android:codes="45" android:keyLabel="q" android:keyEdgeFlags="left"/>
    <Key android:codes="51" android:keyLabel="w"/>
    <Key android:codes="33" android:keyLabel="e"/>
    <Key android:codes="46" android:keyLabel="r"/>
    <Key android:codes="48" android:keyLabel="t"/>
    <Key android:codes="54" android:keyLabel="z"/>
    <Key android:codes="49" android:keyLabel="u"/>
    <Key android:codes="37" android:keyLabel="i"/>
    <Key android:codes="43" android:keyLabel="o"/>
    <Key android:codes="44" android:keyLabel="p" android:keyEdgeFlags="right"/>
</Row>

<Row android:keyHeight="16%">
    <Key android:codes="?" android:keyLabel="ö" android:keyEdgeFlags="left"/>
    <Key android:codes="?" android:keyLabel="ő"/>
    <Key android:codes="?" android:keyLabel="ü"/>
    <Key android:codes="?" android:keyLabel="ű"/>
    <Key android:codes="?" android:keyLabel="ó"/>
    <Key android:codes="?" android:keyLabel="é"/>
    <Key android:codes="?" android:keyLabel="á"/>
    <Key android:codes="?" android:keyLabel="í" android:keyEdgeFlags="right"/>
</Row>
</Keyboard>
</code>```

答:
A somewhat shorter solution is just to remove the codes because the label text gets sent in that case.

```<code><Row>
    <Key android:keyLabel="ö" android:keyEdgeFlags="left"/>
    <Key android:keyLabel="ő"/>
    <Key android:keyLabel="ü"/>
    <Key android:keyLabel="ű"/>
    <Key android:keyLabel="ó"/>
    <Key android:keyLabel="ú"/>
    <Key android:keyLabel="á"/>
    <Key android:keyLabel="é"/>
    <Key android:keyLabel="í" android:keyEdgeFlags="right"/>
</Row>
</code>```

See also How to make an Android custom keyboard.

Body:
I have to implement a simple custom soft-keyboard in my application and I want to show accented characters on the keyboard too.

These are:
í, é, á, ű, ú, ő, ó, ü, ö

My question is how to map these in the keyboard xml? What are the key codes for these? I could not found them in the official KeyEvent document.

My current keyboard definition xml looks like this:

<Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
    android:keyWidth="10%p"
    android:horizontalGap="0px"
    android:verticalGap="0px"
    >

<Row android:keyHeight="16%">
    <Key android:codes="45" android:keyLabel="q" android:keyEdgeFlags="left"/>
    <Key android:codes="51" android:keyLabel="w"/>
    <Key android:codes="33" android:keyLabel="e"/>
    <Key android:codes="46" android:keyLabel="r"/>
    <Key android:codes="48" android:keyLabel="t"/>
    <Key android:codes="54" android:keyLabel="z"/>
    <Key android:codes="49" android:keyLabel="u"/>
    <Key android:codes="37" android:keyLabel="i"/>
    <Key android:codes="43" android:keyLabel="o"/>
    <Key android:codes="44" android:keyLabel="p" android:keyEdgeFlags="right"/>
</Row>

<Row android:keyHeight="16%">
    <Key android:codes="?" android:keyLabel="ö" android:keyEdgeFlags="left"/>
    <Key android:codes="?" android:keyLabel="ő"/>
    <Key android:codes="?" android:keyLabel="ü"/>
    <Key android:codes="?" android:keyLabel="ű"/>
    <Key android:codes="?" android:keyLabel="ó"/>
    <Key android:codes="?" android:keyLabel="é"/>
    <Key android:codes="?" android:keyLabel="á"/>
    <Key android:codes="?" android:keyLabel="í" android:keyEdgeFlags="right"/>
</Row>
</Keyboard>

Body:
A somewhat shorter solution is just to remove the codes because the label text gets sent in that case.

<Row>
    <Key android:keyLabel="ö" android:keyEdgeFlags="left"/>
    <Key android:keyLabel="ő"/>
    <Key android:keyLabel="ü"/>
    <Key android:keyLabel="ű"/>
    <Key android:keyLabel="ó"/>
    <Key android:keyLabel="ú"/>
    <Key android:keyLabel="á"/>
    <Key android:keyLabel="é"/>
    <Key android:keyLabel="í" android:keyEdgeFlags="right"/>
</Row>

See also How to make an Android custom keyboard.


问:
Extract JSON value to shell variable using jq
I have a json response as shown below :

```<code>[
 {"id":10,
 "list_file":["/var/a.txt",
             "/dev/b.txt"]}
]
</code>```

I need to extract values of list_file and store it shell variable as an array. I tried doing it looping through and reading the values.

```<code>#!/bin/bash
x=()
while read -r value
do
  #echo "$value"
  x+=("$value")
done < <(jq -r '.[] | .list_file' input.json)
</code>```

But the extracted values in the array contains quotes, brackets and comma too.

```<code>[
    "/var/a.txt",
    "/dev/b.txt"
]
</code>```

Could you please help me modify the code so that the array contains only the entries /var/a.txt and /dev/b.txt. Also, I tried readarray and map, but they won't work on Mac Osx. Any help would be really appreciated.

答:
In order to handle all values properly, you need to use the declare command to incorporate the output of jq into an array assignment.

Here's some input with some corner cases to worry about: whitespace, a newline, and a glob character.

```<code>$ cat input.json
[
    {"id":10,
    "list_file":[
        "/var/a b.txt",
        "/dev/c\nd.txt",
        "*"]}
]
</code>```

A jq command that extracts and outputs properly quoted strings for use by the shell:

```<code>$ $ jq -r '.[] | .list_file[] | @sh' input.json
'/var/a b.txt'
'/dev/c
d.txt'
'*'
</code>```

And a shell command that can make use of the output:

```<code>$ declare -a "x=($(jq -r '.[] | .list_file[] | @sh' input.json))"
</code>```

Proof that it worked properly:

```<code>$ printf '==%s==\n' "${x[@]}"
==/var/a b.txt==
==/dev/c
d.txt==
==*==
</code>```

Body:
I have a json response as shown below :

[
 {"id":10,
 "list_file":["/var/a.txt",
             "/dev/b.txt"]}
]

I need to extract values of list_file and store it shell variable as an array. I tried doing it looping through and reading the values.

#!/bin/bash
x=()
while read -r value
do
  #echo "$value"
  x+=("$value")
done < <(jq -r '.[] | .list_file' input.json)

But the extracted values in the array contains quotes, brackets and comma too.

[
    "/var/a.txt",
    "/dev/b.txt"
]

Could you please help me modify the code so that the array contains only the entries /var/a.txt and /dev/b.txt. Also, I tried readarray and map, but they won't work on Mac Osx. Any help would be really appreciated.

Body:
In order to handle all values properly, you need to use the declare command to incorporate the output of jq into an array assignment.

Here's some input with some corner cases to worry about: whitespace, a newline, and a glob character.

$ cat input.json
[
    {"id":10,
    "list_file":[
        "/var/a b.txt",
        "/dev/c\nd.txt",
        "*"]}
]

A jq command that extracts and outputs properly quoted strings for use by the shell:

$ $ jq -r '.[] | .list_file[] | @sh' input.json
'/var/a b.txt'
'/dev/c
d.txt'
'*'

And a shell command that can make use of the output:

$ declare -a "x=($(jq -r '.[] | .list_file[] | @sh' input.json))"

Proof that it worked properly:

$ printf '==%s==\n' "${x[@]}"
==/var/a b.txt==
==/dev/c
d.txt==
==*==


答:
If you have a free Apple Developer account you can "side-load" the app onto your friend's device and it will last 7 days, it used to be 60 days but Apple changed this.

If you have a paid, $99 a year Apple developer account you can "side-load" the app onto your friends device and it will be on available for your friend's device for 60 days.

The ideal solution is to use Apple's TestFlight, than you can deliver multiple versions of your app quickly to your friend's device. Your friend simply installs the TestFlight app, to get your apps.

You can register your friends' Apple Ids under different roles such as Testers, Advertisers/Marketers, Administrators and control the apps they have visibility to.

Apple' TestFlight requires the $99 a year developer license, it is worth it though, if the $99 a year seems like an unnecessary expense than the app probably is not worth developing is the way I rationalize the expense.

Also, with TestFlight, app expiration is not a big deal because when the app is near expiration you simply provide a new build and your friend can get latest changes.

With 'side-loading" you have to keep physically getting your friend's device to deliver versions of the app and this gets old quick and goes strongly against the grain of agile development/rapid feedback of changes.

Title: Is there a way to give an iOS app to one person through Xcode?

Body: I have built this app for my cousin. Is there a way I can give it to him and only him? I know I can build it directly on his phone, but I believe that will only work for 30 days after the build, and he lives 8+ hours away so I cannot keep doing that. Any answers would be much appreciated!


问:
Make a delete function
I tried to implement a function that automatically does this:

```<code>del data['method_code']
del data['aqi']
del data['local_site_name']
del data['cbsa_name']
</code>```

I have this function:

```<code>def del_data_func(data,columns):
  data[columns] =  data[columns].apply(lambda x: del(x))
  return data
del_list = data.columns[['method_code','aqi','local_site_name','cbsa_name']]
del_data_func (data, del_list)
</code>```

How can i implement it in the right manner and avoid any errors like this one :

```<code>data[columns] =  data[columns].apply(lambda x: del(x))
SyntaxError: invalid syntax
</code>```

答:
I don't know if lambda is requirement, otherwise one way is to loop:
If df is:

```<code>   col1  col2  col3  col4  col5
0     1     1     1     1     1
1     2     2     2     2     2
2     3     3     3     3     3
3     4     4     4     4     4
4     5     5     5     5     5
</code>```

Then, function can be written as:

```<code>def del_data_func(data,columns):
    for column_name in columns: del data[column_name]
</code>```

Now, calling the function:

```<code>del_list = ['col2', 'col4']
del_data_func (data, del_list)
print(data)
</code>```

Output: after col2 and col4 are removed:

```<code>   col1  col3  col5
0     1     1     1
1     2     2     2
2     3     3     3
3     4     4     4
4     5     5     5
</code>```

Title: Make a delete function

Body:
I tried to implement a function that automatically does this:

del data['method_code']
del data['aqi']
del data['local_site_name']
del data['cbsa_name']

I have this function:

def del_data_func(data,columns):
  data[columns] =  data[columns].apply(lambda x: del(x))
  return data
del_list = data.columns[['method_code','aqi','local_site_name','cbsa_name']]
del_data_func (data, del_list)

How can i implement it in the right manner and avoid any errors like this one :

data[columns] =  data[columns].apply(lambda x: del(x))
SyntaxError: invalid syntax

Body:
I don't know if lambda is requirement, otherwise one way is to loop:
If df is:

   col1  col2  col3  col4  col5
0     1     1     1     1     1
1     2     2     2     2     2
2     3     3     3     3     3
3     4     4     4     4     4
4     5     5     5     5     5

Then, function can be written as:

def del_data_func(data,columns):
    for column_name in columns: del data[column_name]

Now, calling the function:

del_list = ['col2', 'col4']
del_data_func (data, del_list)
print(data)

Output: after col2 and col4 are removed:

   col1  col3  col5
0     1     1     1
1     2     2     2
2     3     3     3
3     4     4     4
4     5     5     5


问:
Angular routing non working
I'm trying to build my first web-app with MEAN stack and i'm facing an issue with the Angular routing.

```<code>    <!-- public/index.html -->
    <!DOCTYPE HTML>
    <html lang="en" content-type="text/css">
    <head name="viewport" content="width=device-width, initial-scale=1">
        <meta charset="UTF-8">
        <base href="/">

        <title>Trova colori in tinta</title>

        <!-- CSS -->
        <link rel="stylesheet" href="libs/bootstrap/dist/css/bootstrap.min.css">
        <link rel="stylesheet" href="css/style.css"> <!-- custom styles -->
         <link rel="stylesheet" href="normalize.css"> <!-- custom styles -->

        <!-- JS -->
        <script type="text/javascript" src="libs/angular/angular.min.js"></script>
        <script type="text/javascript" src="libs/angular-route/angular-route.min.js"></script>

        <!-- ANGULAR CUSTOM -->

        <script type="text/javascript" src="js/controllers/MainCtrl.js"></script>
        <script type="text/javascript" src="js/controllers/NerdCtrl.js"></script>
        <script type="text/javascript" src="js/services/NerdService.js"></script>

        <script type="text/javascript" src="js/appRoutes.js"></script>
        <script type="text/javascript" src="js/app.js"></script>

    </head>
    <body >
    <div class="container" ng-app="sampleApp" ng-controller="NerdController">

        <!-- HEADER -->
        <nav class="navbar navbar-default" >
            <div class="navbar-header">
                <a class="navbar-brand" href="/">Colori</a>
            </div>

            <!-- LINK TO OUR PAGES. ANGULAR HANDLES THE ROUTING HERE -->
            <ul class="nav navbar-nav">
                <li><a href="/nerd">Nerds</a></li>
                <li><a href="/lacci">lacci</a></li>
            </ul>
        </nav>
    <div class="container-fullwidth"></div>
        <!-- ANGULAR DYNAMIC CONTENT -->
        <div ng-view></div>

    </div>
    </body>
    </html>
</code>```

When i click on "Nerds" or "lacci" link it don't show those pages.

here is the file appRoute.js

```<code>    angular.module('appRoutes', []).config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider.when('/', {
            templateUrl: '/public/views/home.html',
            controller: 'MainController'
        }) // nerds page that will use the NerdController
      .when('/nerds', {
            templateUrl: '/public/views/nerd.html',
            controller: 'NerdController'
        }).when('/lacci', {
            templateUrl: '/public/views/lacci.html',

        }).otherwise({ redirectTo: "/home" });

    $locationProvider.html5Mode(true);}]);
</code>```

The two files are in differents folders.
Where i'm wrong?

答:
I think you forgot to inject 'ngRoute'

```<code>angular.module('appRoutes', ['ngRoute']).config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider.when('/', {
            templateUrl: '/public/views/home.html',
            controller: 'MainController'
        }) // nerds page that will use the NerdController
      .when('/nerds', {
            templateUrl: '/public/views/nerd.html',
            controller: 'NerdController'
        }).when('/lacci', {
            templateUrl: '/public/views/lacci.html',

        }).otherwise({ redirectTo: "/home" });

    $locationProvider.html5Mode(true);}]);
</code>```

Title: Angular routing non working

Body:
I'm trying to build my first web-app with MEAN stack and i'm facing an issue with the Angular routing.

    <!DOCTYPE HTML>

        <meta charset="UTF-8">
        <base href="/">

        <title>Trova colori in tinta</title>

        <link rel="stylesheet" href="libs/bootstrap/dist/css/bootstrap.min.css">
        <link rel="stylesheet" href="css/style.css">
         <link rel="stylesheet" href="normalize.css">

                Colori

Nerds

lacci

When i click on "Nerds" or "lacci" link it don't show those pages.

here is the file appRoute.js

    angular.module('appRoutes', []).config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider.when('/', {
            templateUrl: '/public/views/home.html',
            controller: 'MainController'
        }) // nerds page that will use the NerdController
      .when('/nerds', {
            templateUrl: '/public/views/nerd.html',
            controller: 'NerdController'
        }).when('/lacci', {
            templateUrl: '/public/views/lacci.html',

        }).otherwise({ redirectTo: "/home" });

    $locationProvider.html5Mode(true);}]);

The two files are in differents folders.
Where i'm wrong?

Body:
I think you forgot to inject 'ngRoute'

angular.module('appRoutes', ['ngRoute']).config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider.when('/', {
            templateUrl: '/public/views/home.html',
            controller: 'MainController'
        }) // nerds page that will use the NerdController
      .when('/nerds', {
            templateUrl: '/public/views/nerd.html',
            controller: 'NerdController'
        }).when('/lacci', {
            templateUrl: '/public/views/lacci.html',

        }).otherwise({ redirectTo: "/home" });

    $locationProvider.html5Mode(true);}]);


问:
Subtracting datetime objects with Python
I'm working on a simple program to tell an individual how long they have been alive.

I know how to get the current date, and get their birthday. The only problem is I have no way of subtracting the two, I know a way of subtracting two dates, but unfortunately it does not include hours, minutes, or seconds.

I am looking for a method that can subtract two dates and return the difference down to the second, not merely the day.

答:
```<code>import datetime
born = datetime.date(2002, 10, 31)
today = datetime.date.today()
age = today - born

print(age.total_seconds())
</code>```

Output: 463363200.0

Body:
import datetime
born = datetime.date(2002, 10, 31)
today = datetime.date.today()
age = today - born

print(age.total_seconds())

Output: 463363200.0


问:
jquery validation working on some browsers, but not on others
Why does this work for some people, and doesn't for others? Others just click the button and it doesn't work. It started doing that after I added the nospaces validation method. Any suggestions would be very much appreciated.

```<code><form method="post" action="#" id="client_form" class="order-form">
<input type="text" id="user_name" name="user_name" class="req nospaces" />
</form>
 <button id="client_next_btn"><?php echo($content->getString('order')); ?></button>
<script type="text/javascript">

$(function ()
{
jQuery.validator.addClassRules('req', { required: function (el) { return $(el).is(':visible') } });

var nums = ['0','1','2','3','4','5','6','7','8','9'];
var letters = ['q','w','e','r','t','y','u','i','o','p','a','s','d','f','g','h','j','k','l','z','x','c','v','b','n','m'];
var alphanumeric = nums.concat(letters);

jQuery.validator.addMethod("nospaces", function(value, element) {
    var val = value.split("");
    var bool = true;
    for (var i in val)
    {
        if (jQuery.inArray(val[i], alphanumeric) == -1)
        {
            bool = false;
            break;
        }
    }
    return bool;
}, "* <?php echo ($content->getString('no_spaces')); ?>");

$('#client_form').validate();
$('#client_next_btn').click(function ()
{
    $('#client_message').empty();

    if ($('#client_form').validate().form())
    {
                alert('works');
            }
    }
</code>```

}

答:
Just as a tip, you can get rid of this:

```<code>jQuery.validator.addClassRules('req', {
  required: function (el) { return $(el).is(':visible') }
});
</code>```

and use the built in required class, just add the ignore option to your .validate() call to exclude :hidden elements, like this:

```<code>$('#client_form').validate({ ignore: ':hidden' });
</code>```

Body:
Why does this work for some people, and doesn't for others? Others just click the button and it doesn't work. It started doing that after I added the nospaces validation method. Any suggestions would be very much appreciated.

<form method="post" action="#" id="client_form" class="order-form">
<input type="text" id="user_name" name="user_name" class="req nospaces" />
</form>
 <button id="client_next_btn"><?php echo($content->getString('order')); ?></button>

Body:
Just as a tip, you can get rid of this:

jQuery.validator.addClassRules('req', {
  required: function (el) { return $(el).is(':visible') }
});

and use the built in required class, just add the ignore option to your .validate() call to exclude :hidden elements, like this:

$('#client_form').validate({ ignore: ':hidden' });