问:
if a number is divisible by all the entries of a list then
This came up while attempting Problem 5 of Project Euler, I'm sorry if this is vague or obvious I am new to programming.

Suppose I have a list of integers

v = range(1,n) = [1, ..., n]

What I want to do is this:

if m is divisible by all the entries of v then I want to set

m/v[i]  for i starting at 2 and iterating up

then I want to keep repeating this process until I eventually get something which is not divisible by all the entries of v.

Here is a specific example:

let v=[1,2,3,4] and m = 24

m is divisible by 1, 2, 3, and 4, so we divide m by 2 giving us

m=12 which is divisible by 1, 2, 3, and 4 , so we divide by 3

giving us m=4 which is not divisible by 1, 2, 3, and 4. So we stop here.

Is there a way to do this in python using a combination of loops?

答:
I think this piece of code should do what you're asking for:

```<code>v = [1,2,3,4]
m = 24
index = 1
done = False

while not done:
    if all([m % x == 0 for x in v]):
        m = m // v[index]
        if index + 1 == len(v):
            print('Exhausted v')
            done = True
        else:
            index += 1
    else:
        done = True
        print('Not all elements in v evenly divide m')
</code>```

That said, this is not the best way to go about solving Project Euler problem 5. A more straightforward and faster approach would be:

```<code>solved = False
num = 2520
while not solved:
    num += 2520
    if all([num % x == 0 for x in [11, 13, 14, 16, 17, 18, 19, 20]]):
        solved = True
print(num)
</code>```

In this approach, we known that the answer will be a multiple of 2520, so we increment the value we're checking by that amount. We also know that the only values that need to be checked are in [11, 13, 14, 16, 17, 18, 19, 20], because the number in the range [1,20] that aren't in that list are factors of at least one of the numbers in the list.

Body:
I think this piece of code should do what you're asking for:

v = [1,2,3,4]
m = 24
index = 1
done = False

while not done:
    if all([m % x == 0 for x in v]):
        m = m // v[index]
        if index + 1 == len(v):
            print('Exhausted v')
            done = True
        else:
            index += 1
    else:
        done = True
        print('Not all elements in v evenly divide m')

That said, this is not the best way to go about solving Project Euler problem 5. A more straightforward and faster approach would be:

solved = False
num = 2520
while not solved:
    num += 2520
    if all([num % x == 0 for x in [11, 13, 14, 16, 17, 18, 19, 20]]):
        solved = True
print(num)

In this approach, we known that the answer will be a multiple of 2520, so we increment the value we're checking by that amount. We also know that the only values that need to be checked are in [11, 13, 14, 16, 17, 18, 19, 20], because the number in the range [1,20] that aren't in that list are factors of at least one of the numbers in the list.


来源: stackexchange

问:
Using deftransform/defknown in SBCL internals to get the compiler to transform user authored functions
At the end of section 6.5 in the current SBCL manual, we have the following quote:

If your system's performance is suffering because of some construct which could in principle be compiled efficiently, but which the SBCL compiler can't in practice compile efficiently, consider writing a patch to the compiler and submitting it for inclusion in the main sources. Such code is often reasonably straightforward to write; search the sources for the string “deftransform” to find many examples (some straightforward, some less so).

I've been playing around and found the likes of sb-c::defknown and sb-c::deftransform but thus far have had little luck in successfully adding any new transforms that do anything.

Lets pretend i have the following 3 toy functions:

```<code>(defun new-+ (x y)
  (+ x y))

(defun fixnum-+ (x y)
  (declare (optimize (speed 3) (safety 0))
           (fixnum x y))
  (+ x y))

(defun string-+ (x y)
  (declare (optimize (speed 3) (safety 0))
           (string x y))
  (concatenate 'string x y))
</code>```

As a purely toy example, lets say we wanted to tell the compiler that it could transform calls to my user defined function new-+ into calls to either fixnum-+ or string-+.

The condition for the compiler transforming (new-+ x y) into (fixnum-+ x y) would be knowing that the arguments x and y are both of type fixnum, and the conditions for transforming into (string-+ x y) would be knowing that the arguments x and y are both of type string.

So the questions:

Can I actually do this?

What are the actual mechanics of doing so and generating other user based transforms/extensions?

Any reading or sources apart from manually reading through the source to discover more info regarding this?

If i can't do this using the likes of deftransform, is there any other way I could do so?

Note: I'm aware of the operations and nature of macros and generic functions in general common lisp coding, and don't consider using them an answer to this question, since I'm specifically curious about extending the SBCL internals and interacting with its compiler.

答:
You achieve what you want in portable Common Lisp using define-compiler-macro

AFAIK reading the SBCL sources is the only way to learn how deftransform works. But before diving into SBCL sources checkout Paul Khuong's Starting to Hack on SBCL or at the very least The Python Compiler for CMU Common Lisp it links to to have an overview of how SBCL works.

ContentLicense: CC BY-SA 3.0

Body:
At the end of section 6.5 in the current SBCL manual, we have the following quote:

If your system's performance is suffering because of some construct which could in principle be compiled efficiently, but which the SBCL compiler can't in practice compile efficiently, consider writing a patch to the compiler and submitting it for inclusion in the main sources. Such code is often reasonably straightforward to write; search the sources for the string “deftransform” to find many examples (some straightforward, some less so).

I've been playing around and found the likes of sb-c::defknown and sb-c::deftransform but thus far have had little luck in successfully adding any new transforms that do anything.

Lets pretend i have the following 3 toy functions:

(defun new-+ (x y)
  (+ x y))

(defun fixnum-+ (x y)
  (declare (optimize (speed 3) (safety 0))
           (fixnum x y))
  (+ x y))

(defun string-+ (x y)
  (declare (optimize (speed 3) (safety 0))
           (string x y))
  (concatenate 'string x y))

As a purely toy example, lets say we wanted to tell the compiler that it could transform calls to my user defined function new-+ into calls to either fixnum-+ or string-+.

The condition for the compiler transforming (new-+ x y) into (fixnum-+ x y) would be knowing that the arguments x and y are both of type fixnum, and the conditions for transforming into (string-+ x y) would be knowing that the arguments x and y are both of type string.

So the questions:

Can I actually do this?

What are the actual mechanics of doing so and generating other user based transforms/extensions?

Any reading or sources apart from manually reading through the source to discover more info regarding this?

If i can't do this using the likes of deftransform, is there any other way I could do so?

Note: I'm aware of the operations and nature of macros and generic functions in general common lisp coding, and don't consider using them an answer to this question, since I'm specifically curious about extending the SBCL internals and interacting with its compiler.


问:
PHP - Merge two arrays (same-length) into one associative?
pretty straightforward question actually..

is it possible in PHP to combine two separate arrays of the same length to one associative array where the values of the first array are used as keys in the associative array?

I could ofcourse do this, but I'm looking for another (built-in) function, or more efficient solution..?

```<code>function Combine($array1, $array2) {
    if(count($array1) == count($array2)) {
        $assArray = array();
        for($i=0;$i<count($array1);$i++) {
            $assArray[$array1[$i]] = $array2[$i];
        }
        return $assArray;
    }
}
</code>```

答:
hello everybody i will show you how to merge 2 arrays in one array

we have 2 arrays and i will make one array from them

```<code> $data_key  = array('key1','key2');
 $data_value = array('val1','val2');
</code>```

lets declare the main array

```<code>$main_array = array();
</code>```

now let's fill it with the 2 arrays

```<code>foreach ($data_key as $i => $key) {
         $main_array[$key] = $data_value[$i];
}
</code>```

now let's see the result  by using var_dump($main_array);

```<code>array(2) {
["key1"]=> string(4) "val1"
["key2"]=> string(4) "val2"
}
</code>```

i hope that can help someone :)

ContentLicense: CC BY-SA 2.5

Body:
pretty straightforward question actually..

is it possible in PHP to combine two separate arrays of the same length to one associative array where the values of the first array are used as keys in the associative array?

I could ofcourse do this, but I'm looking for another (built-in) function, or more efficient solution..?

function Combine($array1, $array2) {
    if(count($array1) == count($array2)) {
        $assArray = array();
        for($i=0;$i<count($array1);$i++) {
            $assArray[$array1[$i]] = $array2[$i];
        }
        return $assArray;
    }
}

Body:
hello everybody i will show you how to merge 2 arrays in one array

we have 2 arrays and i will make one array from them

 $data_key  = array('key1','key2');
 $data_value = array('val1','val2');

lets declare the main array

$main_array = array();

now let's fill it with the 2 arrays

foreach ($data_key as $i => $key) {
         $main_array[$key] = $data_value[$i];
}

now let's see the result  by using var_dump($main_array);

array(2) {
["key1"]=> string(4) "val1"
["key2"]=> string(4) "val2"
}

i hope that can help someone :)


问:
Gnuplot: Parametric plot on top of pm3d map
I want to plot a 2d pm3d map from a file and then add a curve on top of it. I tried

```<code>set pm3d map
set parametric
fx(t) = r*cos(t)
fy(t) = r*sin(t)
plot fx(t),fy(t) w l, 'GapRM.dat' u 1:2:3 w pm3d
</code>```

but then I get the error message

```<code>Too many using specs for this style
</code>```

How can I do this?

答:
I found a simple way. In this example a plot an ellipse on top of a 3d map:</p>

```<code>set parametric
set view map
set urange [0:6.281]
set vrange [0:2*pi]
set xrange [-6:6]
set yrange [-6:6]
splot 'file.dat' using 1:2:3 w pm3d, 2*cos(u),3*sin(u),0 ls 1
</code>```

Body:
I want to plot a 2d pm3d map from a file and then add a curve on top of it. I tried

set pm3d map
set parametric
fx(t) = r*cos(t)
fy(t) = r*sin(t)
plot fx(t),fy(t) w l, 'GapRM.dat' u 1:2:3 w pm3d

but then I get the error message

Too many using specs for this style

How can I do this?

Body:
I found a simple way. In this example a plot an ellipse on top of a 3d map:

set parametric
set view map
set urange [0:6.281]
set vrange [0:2*pi]
set xrange [-6:6]
set yrange [-6:6]
splot 'file.dat' using 1:2:3 w pm3d, 2*cos(u),3*sin(u),0 ls 1


问:
Android sdk for Intellij IDEA
I'm trying to setup IntelliJ IDEA to develop android applications and I faced an issue with android sdk. As far as I know, I need to download the sdk separately. But I all I managed to find was Android command line tools which is obviously not something I need. So my question how can I get android sdk for IntelliJ IDEA?   </p>

答: I had the same issue. I tried downloading sdk via android eclipse setup process. Eclipse automatically downloads the sdk. This sdk has a gui sdkmanager and can be used in idea as well. Here is the link to download eclipse.</p>

Title: Android sdk for Intellij IDEA


问:
Python: ArgParse with a Main command and Sub command
Hi I'm using ArgParse to handle my arguments. I would like the code to work like this

```<code># Main function
$ myApp -i INPUT -o OUTPUT -s STUFF
</code>```

```<code># Configure function
$ myApp config -a conf1 -b conf2
</code>```

```<code>import argparse
from argparse import RawTextHelpFormatter

parser = argparse.ArgumentParser(description='myApp',formatter_class=RawTextHelpFormatter)
parser.add_argument('-i',help='input',required=True)
parser.add_argument('-o',help='output',required=True)
parser.add_argument('-s',help='stuff',default=None,required=False)
args = parser.parse_args()

subp = parser.add_subparsers()
conf_parser = subp.add_parser('config', help='configure')
conf_parser.add_argument('-a',help='a config file',default=None,required=False)
conf_parser.add_argument('-b',help='b config file',default=None,required=False)
conf_args = conf_arser.parse_args()
</code>```

Here's the output

```<code>python sandbox/test1.py  --help
usage: test1.py [-h] -i I -o O [-s S]

myApp

optional arguments:
  -h, --help  show this help message and exit
  -i I        input
  -o O        output
  -s S        stuff
</code>```

I'm not getting the config args to show. I'm not sure what I'm doing wrong here.

Thanks!

答:
Solved it

```<code>import argparse
from argparse import RawTextHelpFormatter

parser = argparse.ArgumentParser(description='myApp',formatter_class=RawTextHelpFormatter)
parser.add_argument('-i',help='input',required=True)
parser.add_argument('-o',help='output',required=True)
parser.add_argument('-s',help='stuff',default=None,required=False)

subp = parser.add_subparsers(help='configure')
conf_parser = subp.add_parser('config')
conf_parser.add_argument('-a',help='a config file',default=None,required=False)
conf_parser.add_argument('-b',help='b config file',default=None,required=False)
args = parser.parse_args()
</code>```

```<code>python sandbox/test1.py --help
usage: test1.py [-h] -i I -o O [-s S] {config} ...

myApp

positional arguments:
  {config}    configure

optional arguments:
  -h, --help  show this help message and exit
  -i I        input
  -o O        output
  -s S        stuff
</code>```

```<code>python sandbox/test1.py config --help
usage: test1.py config [-h] [-a A] [-b B]

optional arguments:
  -h, --help  show this help message and exit
  -a A        a config file
  -b B        b config file
</code>```

Body:
Hi I'm using ArgParse to handle my arguments. I would like the code to work like this

# Main function
$ myApp -i INPUT -o OUTPUT -s STUFF

# Configure function
$ myApp config -a conf1 -b conf2

import argparse
from argparse import RawTextHelpFormatter

parser = argparse.ArgumentParser(description='myApp',formatter_class=RawTextHelpFormatter)
parser.add_argument('-i',help='input',required=True)
parser.add_argument('-o',help='output',required=True)
parser.add_argument('-s',help='stuff',default=None,required=False)
args = parser.parse_args()

subp = parser.add_subparsers()
conf_parser = subp.add_parser('config', help='configure')
conf_parser.add_argument('-a',help='a config file',default=None,required=False)
conf_parser.add_argument('-b',help='b config file',default=None,required=False)
conf_args = conf_arser.parse_args()

Here's the output

python sandbox/test1.py  --help
usage: test1.py [-h] -i I -o O [-s S]

myApp

optional arguments:
  -h, --help  show this help message and exit
  -i I        input
  -o O        output
  -s S        stuff

I'm not getting the config args to show. I'm not sure what I'm doing wrong here.

Thanks!

Body:
Solved it

import argparse
from argparse import RawTextHelpFormatter

parser = argparse.ArgumentParser(description='myApp',formatter_class=RawTextHelpFormatter)
parser.add_argument('-i',help='input',required=True)
parser.add_argument('-o',help='output',required=True)
parser.add_argument('-s',help='stuff',default=None,required=False)

subp = parser.add_subparsers(help='configure')
conf_parser = subp.add_parser('config')
conf_parser.add_argument('-a',help='a config file',default=None,required=False)
conf_parser.add_argument('-b',help='b config file',default=None,required=False)
args = parser.parse_args()

python sandbox/test1.py --help
usage: test1.py [-h] -i I -o O [-s S] {config} ...

myApp

positional arguments:
  {config}    configure

optional arguments:
  -h, --help  show this help message and exit
  -i I        input
  -o O        output
  -s S        stuff

python sandbox/test1.py config --help
usage: test1.py config [-h] [-a A] [-b B]

optional arguments:
  -h, --help  show this help message and exit
  -a A        a config file
  -b B        b config file


问:
Why does cached_property always update the data?
There is a model, in its geoposition field, latitude and longitude are stored, as a string, in this form '27 .234234234,53.23423423434'.

This field is provided by django-geoposition. Thanks to him it is very convenient to enter the address.

I also need to store the real address. I do not know whether to do this correctly, but I decided to use geocoder, and store the result in cached_property

```<code>class Address(models.Model):
    geoposition = GeopositionField(null=True)
    city = models.ForeignKey('cities_light.City', null=True)
    country = models.ForeignKey('cities_light.Country', null=True)
    entrance = models.CharField(null=True, max_length=4, blank=True)
    floor = models.CharField(null=True, max_length=4, blank=True)
    flat = models.CharField(null=True, max_length=4, blank=True)

    @cached_property
    def address(self):
        g = geocoder.yandex([
            str(self.geoposition).split(',')[0],
            str(self.geoposition).split(',')[1]
        ],
        method='reverse', lang='ru-RU')
        return g.address

    def save(self, *args, **kwargs):
        if not self.address:
            self.address()

        super(Address, self).save(*args, **kwargs)

    def __str__(self):
        if self.address:
            return '%s' % str(self.address)
        return '%s' % str(self.pk)
</code>```

But the problem is that with every attempt to edit a model that is associated with the Address, I see that the property is being computed, and even in some cases I catch connection time out from external services.

I can not understand the reason for this behavior.

答: The thing was that in the save () method, I did not call the address property, but the address() method, so there was no caching.

Body:
There is a model, in its geoposition field, latitude and longitude are stored, as a string, in this form '27 .234234234,53.23423423434'.

This field is provided by django-geoposition. Thanks to him it is very convenient to enter the address.

I also need to store the real address. I do not know whether to do this correctly, but I decided to use geocoder, and store the result in cached_property

class Address(models.Model):
    geoposition = GeopositionField(null=True)
    city = models.ForeignKey('cities_light.City', null=True)
    country = models.ForeignKey('cities_light.Country', null=True)
    entrance = models.CharField(null=True, max_length=4, blank=True)
    floor = models.CharField(null=True, max_length=4, blank=True)
    flat = models.CharField(null=True, max_length=4, blank=True)

    @cached_property
    def address(self):
        g = geocoder.yandex([
            str(self.geoposition).split(',')[0],
            str(self.geoposition).split(',')[1]
        ],
        method='reverse', lang='ru-RU')
        return g.address

    def save(self, *args, **kwargs):
        if not self.address:
            self.address()

        super(Address, self).save(*args, **kwargs)

    def __str__(self):
        if self.address:
            return '%s' % str(self.address)
        return '%s' % str(self.pk)

But the problem is that with every attempt to edit a model that is associated with the Address, I see that the property is being computed, and even in some cases I catch connection time out from external services.

I can not understand the reason for this behavior.


问:
SmartScreen Reputation and singned application
So we have our application installer that is signed by our new certificate (standard [not EV]). SmartScreen shows publisher correct but application is still untrusted. So the problem is with application reputation.

Is there any way to build a reputation?

In some old topic i found information that you can use Windows App Certification Kit (WACK) to generate XML file and upload it to https://sysdev.microsoft.com, and after few days SmartScreen will be aware of the digital signature. But it doesn't seem to work anymore, at the moment you need to have Symantec Code Signing Certificate.

答:
If it's any help, I can confirm that I have just completed the WACK process today and I actually used a Comodo certificate (standard, not EV). I'm still waiting to see if it gets rid of the SmartScreen warning (since it may take a few days). As far as I can tell, it accepted my signed certificate so I don't think it needs to be Symantec.

One thing I will mention is that the site did ask for URLs for my webpage (home page, support page etc.) and wouldn't let me proceed without completing them. If you have a website, that's no big deal, but if you're doing a personal project and don't have one set up then you may have to make one.


问:
Change ghci version on stack
I have stack installed on my computer for haskell:

```<code>Developers-MacBook-Pro:~ developer$ stack ghci
Configuring GHCi with the following packages:
GHCi, version 8.0.1: http://www.haskell.org/ghc/  :? for help
Loaded GHCi configuration from /private/var/folders/2x/t_2cl03x2092dkzvc702d7lc0000gn/T/ghci2170/ghci-script
Prelude>
</code>```

As you can see version is still 8.0.1. Then I upgraded the stack as follow:

```<code>Developers-MacBook-Pro:~ developer$ stack upgrade
Current Stack version: 1.3.2, available download version: 1.4.0
Newer version detected, downloading
Querying for archive location for platform: osx-x86_64-static
Querying for archive location for platform: osx-x86_64
Downloading from: https://github.com/commercialhaskell/stack/releases/download/v1.4.0/stack-1.4.0-osx-x86_64.tar.gz
Download complete, testing executable
Version 1.4.0, Git revision e714f1dd3fade19496d91bd6a017e435a96a6bcd (4640 commits) x86_64 hpack-0.17.0
New stack executable available at /Users/developer/.local/bin/stack
</code>```

After I start stack ghci again and I've got still version 8.0.1, what am I doing wrong?

The image shows, that ghci version 8.0.2 has successfully installed:

The path is /Users/developer/.stack/programs/x86_64-osx/

Update
In the path /Users/developer/.stack/, there is a folder called global-project and I change the yaml as follow:

Now stack ghci run on version 8.0.2:

```<code>Developers-MBP:~ developer$ stack ghci
Configuring GHCi with the following packages:
GHCi, version 8.0.2: http://www.haskell.org/ghc/  :? for help
Loaded GHCi configuration from /private/var/folders/2x/t_2cl03x2092dkzvc702d7lc0000gn/T/ghci526/ghci-script
</code>```

答:
stack is a build tool that coordinates building projects with different versions of GHC and sets of dependencies. So you can upgrade stack independently of ghc.

I'm not quite sure what the expected behavior of stack ghci is when it's run outside of a project directory. Presumably you con configure the default version of ghc to use in that case in your ~/.stack/config.yaml. See: http://docs.haskellstack.org/en/stable/yaml_configuration/

You should also be able to do:

```<code>$ stack ghci --with-ghc ghc-7.10.3
</code>```

But usually the version of ghc is determined by the stackage snapshot you've configured for your project, for instance if you have a stack.yaml with:

```<code>resolver: lts-3.3
</code>```

...you will be using ghc-7.10.3

Title: Change ghci version on stack

Body:
I have stack installed on my computer for haskell:

Developers-MacBook-Pro:~ developer$ stack ghci
Configuring GHCi with the following packages:
GHCi, version 8.0.1: http://www.haskell.org/ghc/  :? for help
Loaded GHCi configuration from /private/var/folders/2x/t_2cl03x2092dkzvc702d7lc0000gn/T/ghci2170/ghci-script
Prelude>

As you can see version is still 8.0.1. Then I upgraded the stack as follow:

Developers-MacBook-Pro:~ developer$ stack upgrade
Current Stack version: 1.3.2, available download version: 1.4.0
Newer version detected, downloading
Querying for archive location for platform: osx-x86_64-static
Querying for archive location for platform: osx-x86_64
Downloading from: https://github.com/commercialhaskell/stack/releases/download/v1.4.0/stack-1.4.0-osx-x86_64.tar.gz
Download complete, testing executable
Version 1.4.0, Git revision e714f1dd3fade19496d91bd6a017e435a96a6bcd (4640 commits) x86_64 hpack-0.17.0
New stack executable available at /Users/developer/.local/bin/stack

After I start stack ghci again and I've got still version 8.0.1, what am I doing wrong?

The image shows, that ghci version 8.0.2 has successfully installed:

The path is /Users/developer/.stack/programs/x86_64-osx/

Update
In the path /Users/developer/.stack/, there is a folder called global-project and I change the yaml as follow:

Now stack ghci run on version 8.0.2:

Developers-MBP:~ developer$ stack ghci
Configuring GHCi with the following packages:
GHCi, version 8.0.2: http://www.haskell.org/ghc/  :? for help
Loaded GHCi configuration from /private/var/folders/2x/t_2cl03x2092dkzvc702d7lc0000gn/T/ghci526/ghci-script

Body:
stack is a build tool that coordinates building projects with different versions of GHC and sets of dependencies. So you can upgrade stack independently of ghc.

I'm not quite sure what the expected behavior of stack ghci is when it's run outside of a project directory. Presumably you con configure the default version of ghc to use in that case in your ~/.stack/config.yaml. See: http://docs.haskellstack.org/en/stable/yaml_configuration/

You should also be able to do:

$ stack ghci --with-ghc ghc-7.10.3

But usually the version of ghc is determined by the stackage snapshot you've configured for your project, for instance if you have a stack.yaml with:

resolver: lts-3.3

...you will be using ghc-7.10.3


问:
Is there a way to publish Amazon Lex chatbots to Channels Beyond Mobile, Slack, FB, or Twilio SMS?
Amazon Lex was an amazingly easy setup process prior to deployment to channels.  It looks like we can only publish to the following channels: Mobile, Slack, FB, or Twilio SMS. Are there any other options, for example, leverage the simple "Test Bot" (from the Bot Editor Menu) as a "no frills" Chatbot UI and embed it in an existing web page?

I don't want to limit to a Mobile platform, and I want to keep
coding to a minimum.

Slack users must belong to my chatbot team. I'd like to deploy my chatbot to "the world"

Don't want to conduct business within Facebook

Don't want to use [Twilio] SMS messaging to conduct Chatbot communication

Any other deployment options would be greatly appreciated.
Best Regards,
Ian

答: You can use SDKs provided by Amazon Lex to create your own client applications (Mobile/Desktop/Web). For example you can use Javascript SDK for talking to Lex runtime service in your web page.</p>


问:
How to determine whether a file has been closed
I'm writing a unit test, and I'm trying to find a way to test whether my class has properly closed a file handle (it uses old-style open() and close()). Ideally I'd like to be able to do it without having access to the actual handle - I want to be able to check a file in the file system and determine whether it is currently open elsewhere.

I've tried doing it through exclusive file locks, but I haven't had much luck. Besides, file locks are very much not cross-platform (this needs to work on Solaris, Linux and Windows).

Any suggestions?

答:
In Unix/Solaris/Linux, you can examine /proc/pid/fd/* if you know the pid.  You could also scan all the /proc/*/fd entries.

For Windows, I'd look into what the sysinternals.com tool ProcMon, now called Process Monitor does.  I can't recall if there used to be source code available for that or not.


问:
UICollectionView, full width cells, allow autolayout dynamic height?
Note For 2021!  See @Ely answer regarding UICollectionLayoutListConfiguration !!!!

In a vertical UICollectionView ,

Is it possible to have full-width cells, but, allow the dynamic height to be controlled by autolayout?

This strikes me as perhaps the "most important question in iOS with no really good answer."

Important:

Note that in 99% of cases, to achieve full width cells + autolayout dynamic height, simply use a table view. It's that easy.

So what's an example of where you need a collection view?

Collection views are far more powerful than table views.

One straightforward example where you must use a collection view with autolayout dynamic height:

If you animate between two layouts in a collection view. For example, between a 1 and 2 column layout, when the device rotates.

That's a common idiom in iOS. Unfortunately it can only be achieved by solving the problem posed in this QA.  :-/

答:
Personally I found the best ways to have a UICollectionView where AutoLayout determines the size while each Cell can have a different size is to implement the UICollectionViewDelegateFlowLayout sizeForItemAtIndexPath function while using an actual Cell to measure the size.

I talked about this in one of my blog posts

Hopefully this one will help you to achieve what you want. I'm not 100% sure but I believe unlike UITableView where you can actually have a fully automatic height of cells by using AutoLayout inconjunction with

```<code>tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 44
</code>```

UICollectionView does not have such a way of letting AutoLayout determine the size because UICollectionViewCell does not necessarily fills the whole width of the screen.

But here is a question for you: If you need full screen width cells, why do you even bother using the UICollectionView over a good old UITableView which comes with the auto sizing cells?

ContentLicense: CC BY-SA 4.0

Body:
Personally I found the best ways to have a UICollectionView where AutoLayout determines the size while each Cell can have a different size is to implement the UICollectionViewDelegateFlowLayout sizeForItemAtIndexPath function while using an actual Cell to measure the size.

I talked about this in one of my blog posts

Hopefully this one will help you to achieve what you want. I'm not 100% sure but I believe unlike UITableView where you can actually have a fully automatic height of cells by using AutoLayout inconjunction with

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 44

UICollectionView does not have such a way of letting AutoLayout determine the size because UICollectionViewCell does not necessarily fills the whole width of the screen.

But here is a question for you: If you need full screen width cells, why do you even bother using the UICollectionView over a good old UITableView which comes with the auto sizing cells?


问:
What is the fastest way to get the value of π?
I'm looking for the fastest way to obtain the value of π, as a personal challenge. More specifically, I'm using ways that don't involve using #define constants like M_PI, or hard-coding the number in.

The program below tests the various ways I know of. The inline assembly version is, in theory, the fastest option, though clearly not portable. I've included it as a baseline to compare against the other versions. In my tests, with built-ins, the 4 * atan(1) version is fastest on GCC 4.2, because it auto-folds the atan(1) into a constant. With -fno-builtin specified, the atan2(0, -1) version is fastest.

Here's the main testing program (pitimes.c):

#include <math.h>
#include <stdio.h>
#include <time.h>

#define ITERS 10000000
#define TESTWITH(x) {                                                       \
    diff = 0.0;                                                             \
    time1 = clock();                                                        \
    for (i = 0; i < ITERS; ++i)                                             \
        diff += (x) - M_PI;                                                 \
    time2 = clock();                                                        \
    printf("%s\t=> %e, time => %f\n", #x, diff, diffclock(time2, time1));   \
}

static inline double
diffclock(clock_t time1, clock_t time0)
{
    return (double) (time1 - time0) / CLOCKS_PER_SEC;
}

int
main()
{
    int i;
    clock_t time1, time2;
    double diff;

    /* Warmup. The atan2 case catches GCC's atan folding (which would
     * optimise the ``4 * atan(1) - M_PI'' to a no-op), if -fno-builtin
     * is not used. */
    TESTWITH(4 * atan(1))
    TESTWITH(4 * atan2(1, 1))

#if defined(__GNUC__) && (defined(__i386__) || defined(__amd64__))
    extern double fldpi();
    TESTWITH(fldpi())
#endif

    /* Actual tests start here. */
    TESTWITH(atan2(0, -1))
    TESTWITH(acos(-1))
    TESTWITH(2 * asin(1))
    TESTWITH(4 * atan2(1, 1))
    TESTWITH(4 * atan(1))

    return 0;
}
```

<p>And the inline assembly stuff (<code>fldpi.c</code>) that will only work for x86 and x64 systems:</p>

<pre class="lang-c prettyprint-override"><code>double
fldpi()
{
    double pi;
    asm("fldpi" : "=t" (pi));
    return pi;
}
</code>```

And a build script that builds all the configurations I'm testing (build.sh):

```<code>#!/bin/sh
gcc -O3 -Wall -c           -m32 -o fldpi-32.o fldpi.c
gcc -O3 -Wall -c           -m64 -o fldpi-64.o fldpi.c

gcc -O3 -Wall -ffast-math  -m32 -o pitimes1-32 pitimes.c fldpi-32.o
gcc -O3 -Wall              -m32 -o pitimes2-32 pitimes.c fldpi-32.o -lm
gcc -O3 -Wall -fno-builtin -m32 -o pitimes3-32 pitimes.c fldpi-32.o -lm
gcc -O3 -Wall -ffast-math  -m64 -o pitimes1-64 pitimes.c fldpi-64.o -lm
gcc -O3 -Wall              -m64 -o pitimes2-64 pitimes.c fldpi-64.o -lm
gcc -O3 -Wall -fno-builtin -m64 -o pitimes3-64 pitimes.c fldpi-64.o -lm
</code>```

Apart from testing between various compiler flags (I've compared 32-bit against 64-bit too because the optimizations are different), I've also tried switching the order of the tests around. But still, the atan2(0, -1) version still comes out on top every time.

答:
Calculating π from circle area :-)

<input id="range" type="range" min="10" max="960" value="10" step="50" oninput="calcPi()">

```

Body:
I'm looking for the fastest way to obtain the value of π, as a personal challenge. More specifically, I'm using ways that don't involve using #define constants like M_PI, or hard-coding the number in.

The program below tests the various ways I know of. The inline assembly version is, in theory, the fastest option, though clearly not portable. I've included it as a baseline to compare against the other versions. In my tests, with built-ins, the 4 * atan(1) version is fastest on GCC 4.2, because it auto-folds the atan(1) into a constant. With -fno-builtin specified, the atan2(0, -1) version is fastest.

Here's the main testing program (pitimes.c):

#include <math.h>
#include <stdio.h>
#include <time.h>

#define ITERS 10000000
#define TESTWITH(x) {                                                       \
    diff = 0.0;                                                             \
    time1 = clock();                                                        \
    for (i = 0; i < ITERS; ++i)                                             \
        diff += (x) - M_PI;                                                 \
    time2 = clock();                                                        \
    printf("%s\t=> %e, time => %f\n", #x, diff, diffclock(time2, time1));   \
}

static inline double
diffclock(clock_t time1, clock_t time0)
{
    return (double) (time1 - time0) / CLOCKS_PER_SEC;
}

int
main()
{
    int i;
    clock_t time1, time2;
    double diff;

    /* Warmup. The atan2 case catches GCC's atan folding (which would
     * optimise the ``4 * atan(1) - M_PI'' to a no-op), if -fno-builtin
     * is not used. */
    TESTWITH(4 * atan(1))
    TESTWITH(4 * atan2(1, 1))

#if defined(__GNUC__) && (defined(__i386__) || defined(__amd64__))
    extern double fldpi();
    TESTWITH(fldpi())
#endif

    /* Actual tests start here. */
    TESTWITH(atan2(0, -1))
    TESTWITH(acos(-1))
    TESTWITH(2 * asin(1))
    TESTWITH(4 * atan2(1, 1))
    TESTWITH(4 * atan(1))

    return 0;
}

And the inline assembly stuff (fldpi.c) that will only work for x86 and x64 systems:

double
fldpi()
{
    double pi;
    asm("fldpi" : "=t" (pi));
    return pi;
}

And a build script that builds all the configurations I'm testing (build.sh):

#!/bin/sh
gcc -O3 -Wall -c           -m32 -o fldpi-32.o fldpi.c
gcc -O3 -Wall -c           -m64 -o fldpi-64.o fldpi.c

gcc -O3 -Wall -ffast-math  -m32 -o pitimes1-32 pitimes.c fldpi-32.o
gcc -O3 -Wall              -m32 -o pitimes2-32 pitimes.c fldpi-32.o -lm
gcc -O3 -Wall -fno-builtin -m32 -o pitimes3-32 pitimes.c fldpi-32.o -lm
gcc -O3 -Wall -ffast-math  -m64 -o pitimes1-64 pitimes.c fldpi-64.o -lm
gcc -O3 -Wall              -m64 -o pitimes2-64 pitimes.c fldpi-64.o -lm
gcc -O3 -Wall -fno-builtin -m64 -o pitimes3-64 pitimes.c fldpi-64.o -lm

Apart from testing between various compiler flags (I've compared 32-bit against 64-bit too because the optimizations are different), I've also tried switching the order of the tests around. But still, the atan2(0, -1) version still comes out on top every time.

LastEditorDisplayName: Chris Jester-Young

Body:
Calculating π from circle area :-)

<input id="range" type="range" min="10" max="960" value="10" step="50" oninput="calcPi()">
<br>
<div id="cont"></div>

<script>
function generateCircle(width) {
    var c = width/2;
    var delta = 1.0;
    var str = "";
    var xCount = 0;
    for (var x=0; x <= width; x++) {
        for (var y = 0; y <= width; y++) {
            var d = Math.sqrt((x-c)*(x-c) + (y-c)*(y-c));
            if (d > (width-1)/2) {
                str += '.';
            }
            else {
                xCount++;
                str += 'o';
            }
            str += "&nbsp;"
        }
        str += "\n";
    }
    var pi = (xCount * 4) / (width * width);
    return [str, pi];
}

function calcPi() {
    var e = document.getElementById("cont");
    var width = document.getElementById("range").value;
    e.innerHTML = "<h4>Generating circle...</h4>";
    setTimeout(function() {
        var circ = generateCircle(width);
        e.innerHTML  = "<pre>" + "π = " + circ[1].toFixed(2) + "\n" + circ[0] +"</pre>";
    }, 200);
}
calcPi();
</script>


问:
Database vs fstream access
I have a (local) database (MySQL 5.1 at Ubuntu 10.10) with some 15000 tables each with ~1 000 000 rows on average. Each table has 6 DOUBLE columns. The storage engine is MyISAM. I have a C++ application that loads the data one table at a time and performs some calculations.
The way I retrieve the data from the database is simply by: SELECT * FROM table ORDER BY timestamp; (timestamp is the first column (DOUBLE) marked as UNIQUE)
By far most of the time is spent in loading and fetching. It takes ~15s to load and fetch all the rows in one table (tried with the native C API, C++ Connector and MySQL Query Browser).
When I load the same dataset from disk (plain text file) using fstream the same operation takes only ~4s.

Is it possible for MySQL or any other database (SQLite?) to get anywhere near this value?
Although, I have mostly simple SELECTS and INSERTS (+ one simple JOIN) I like the idea of database because it is somewhat easier to manage large data sets, so I would stick with it even at cost of some performance loss, but 15/4s per table is way too much given the number of tables. I would be fine with 6/4s though...

Thanks.
Petr

答:
Firstly, you're absuing the database fairly badly by having 15,000 tables. This is not how these databases are intended to work.

Secondly, any client-server database is likely to need several copy operations in memory, which will impose an upper limit on the speed even when the data are already in memory. Something like sqlite may avoid (some of) these copies by using data directly from the buffer.

You're using a SQL database for something it's not intended for - and abusing it, at that. I wouldn't expect it to do a very good job.

Title: Database vs fstream access


问:
How to revert the last migration?
I've made a migration that added a new table and want to revert it and delete the migration, without creating a new migration.

How do I do it? Is there a command to revert last migration and then I can simply delete the migration file?

答:
Here is my solution, since the above solution do not really cover the use-case, when you use RunPython.

You can access the table via the ORM with

```<code>from django.db.migrations.recorder import MigrationRecorder

>>> MigrationRecorder.Migration.objects.all()
>>> MigrationRecorder.Migration.objects.latest('id')
Out[5]: <Migration: Migration 0050_auto_20170603_1814 for model>
>>> MigrationRecorder.Migration.objects.latest('id').delete()
Out[4]: (1, {u'migrations.Migration': 1})
</code>```

So you can query the tables and delete those entries that are relevant for you. This way you can modify in detail. With RynPython migrations you also need to take care of the data that was added/changed/removed. The above example only displays, how you access the table via Djang ORM.

Title: How to revert the last migration?

Body:
Here is my solution, since the above solution do not really cover the use-case, when you use RunPython.

You can access the table via the ORM with

from django.db.migrations.recorder import MigrationRecorder

>>> MigrationRecorder.Migration.objects.all()
>>> MigrationRecorder.Migration.objects.latest('id')
Out[5]: <Migration: Migration 0050_auto_20170603_1814 for model>
>>> MigrationRecorder.Migration.objects.latest('id').delete()
Out[4]: (1, {u'migrations.Migration': 1})

So you can query the tables and delete those entries that are relevant for you. This way you can modify in detail. With RynPython migrations you also need to take care of the data that was added/changed/removed. The above example only displays, how you access the table via Djang ORM.


问:
Finding the first instance of a variable
I have a dataset that is asking me to find the first time a registered online shopper purchased something and apply a 5% discount to that purchase.

The dataset has 28 columns but for the purpose of this question I will condense it to only what i think is relevant.

I need to create a new column that will tell me the first time someone purchased something. We can assume that purchases made on the same day are the same purchase but belonging to a different item.

```<code>Obs     ID    Trans_Date   Order_Number   Value       Status
----------------------------------------------------------------
1874    866   30/07/2016   191            $4,217.90   Registered
1875    866   30/07/2016   191            $4,217.90   Registered
1876    866   31/07/2016   192            $2,422.75   Registered
1877    866   31/07/2016   192            $2,422.75   Registered
1878    .     31/07/2016   193            $4,162.66   Unregistered
1879    .     31/07/2016   193            $4,162.66   Unregistered
1880    344   31/07/2016   194            $4,405.51   Registered
1881    344   31/07/2016   194            $4,405.51   Registered
1882    .     31/07/2016   195            $2,114.76   Unregistered
1883    .     31/07/2016   195            $2,114.76   Unregistered
1884    250   31/07/2016   196            $3,310.72   Registered
1885    250   31/07/2016   196            $3,310.72   Registered
1886    .     31/07/2016   197            $4,633.48   Unregistered
1887    .     31/07/2016   197            $4,633.48   Unregistered
1888    .     31/07/2016   197            $4,633.48   Unregistered
1889    .     31/07/2016   197            $4,633.48   Unregistered
1890    .     31/07/2016   198            $6,224.43   Unregistered
1891    .     31/07/2016   198            $6,224.43   Unregistered
1892    .     31/07/2016   198            $6,224.43   Unregistered
1893    .     31/07/2016   198            $6,224.43   Unregistered
</code>```

Body:
I have a dataset that is asking me to find the first time a registered online shopper purchased something and apply a 5% discount to that purchase.

The dataset has 28 columns but for the purpose of this question I will condense it to only what i think is relevant.

I need to create a new column that will tell me the first time someone purchased something. We can assume that purchases made on the same day are the same purchase but belonging to a different item.

Obs     ID    Trans_Date   Order_Number   Value       Status
----------------------------------------------------------------
1874    866   30/07/2016   191            $4,217.90   Registered
1875    866   30/07/2016   191            $4,217.90   Registered
1876    866   31/07/2016   192            $2,422.75   Registered
1877    866   31/07/2016   192            $2,422.75   Registered
1878    .     31/07/2016   193            $4,162.66   Unregistered
1879    .     31/07/2016   193            $4,162.66   Unregistered
1880    344   31/07/2016   194            $4,405.51   Registered
1881    344   31/07/2016   194            $4,405.51   Registered
1882    .     31/07/2016   195            $2,114.76   Unregistered
1883    .     31/07/2016   195            $2,114.76   Unregistered
1884    250   31/07/2016   196            $3,310.72   Registered
1885    250   31/07/2016   196            $3,310.72   Registered
1886    .     31/07/2016   197            $4,633.48   Unregistered
1887    .     31/07/2016   197            $4,633.48   Unregistered
1888    .     31/07/2016   197            $4,633.48   Unregistered
1889    .     31/07/2016   197            $4,633.48   Unregistered
1890    .     31/07/2016   198            $6,224.43   Unregistered
1891    .     31/07/2016   198            $6,224.43   Unregistered
1892    .     31/07/2016   198            $6,224.43   Unregistered
1893    .     31/07/2016   198            $6,224.43   Unregistered

Body:
Here's my 'first' dataset:

'obs'  ,   'id'  ,  'trans_date' ,  'order_number' ,  'value'      , 'status'
1874 ,   866 ,  30/07/2016 ,  191          ,  4217.90  , Registered
1875 ,   866 ,  30/07/2016 ,  191          ,  4217.90  , Registered
1876 ,   866 ,  31/07/2016 ,  192          ,  2422.75  , Registered
1877 ,   866 ,  31/07/2016 ,  192          ,  2422.75  , Registered
1878 ,   344 ,  30/07/2016 ,  193          ,  4162.66  , Unregistered
1879 ,   344 ,  30/07/2016 ,  193          ,  4162.66  , Unregistered
1880 ,   344 ,  31/07/2016 ,  194          ,  4405.51  , Registered
1881 ,   344 ,  31/07/2016 ,  194          ,  4405.51  , Registered
1882 ,   250 ,  30/07/2016 ,  195          ,  2114.76  , Unregistered
1883 ,   250 ,  30/07/2016 ,  195          ,  2114.76  , Unregistered
1884 ,   250 ,  31/07/2016 ,  196          ,  3310.72  , Registered
1885 ,   250 ,  31/07/2016 ,  196          ,  3310.72  , Registered
1886 ,   275 ,  30/07/2016 ,  197          ,  4633.48  , Unregistered
1887 ,   275 ,  30/07/2016 ,  197          ,  4633.48  , Unregistered
1888 ,   275 ,  30/07/2016 ,  197          ,  4633.48  , Unregistered
1889 ,   275 ,  30/07/2016 ,  197          ,  4633.48  , Unregistered
1890 ,   275 ,  31/07/2016 ,  198          ,  6224.43  , Unregistered
1891 ,   275 ,  31/07/2016 ,  198          ,  6224.43  , Unregistered
1892 ,   275 ,  31/07/2016 ,  198          ,  6224.43  , Unregistered
1893 ,   275 ,  31/07/2016 ,  198          ,  6224.43  , Unregistered

and here's some proc sql:

proc sql noprint;
create table temp as
select *,min(trans_date) format=date9. as first
from first
group by id
order by order_number;

create table final as
select obs,id,trans_date,order_number,value,status,
   case when first = trans_date then 'FIRST'
        else 'NOT FIRST'
   end as flag
from temp;
quit;


问:
Leave only two decimal places after the dot
```<code>public void LoadAveragePingTime()
{
    try
    {
        PingReply pingReply = pingClass.Send("logon.chronic-domination.com");
        double AveragePing = (pingReply.RoundtripTime / 1.75);

        label4.Text = (AveragePing.ToString() + "ms");
    }
    catch (Exception)
    {
        label4.Text = "Server is currently offline.";
    }
}
</code>```

Currently my label4.Text get's something like: "187.371698712637".

I need it to show something like: "187.37"

Only two posts after the DOT. Can someone help me out?

答:
Simple solution:</p>

```<code>double totalCost = 123.45678;
totalCost = Convert.ToDouble(String.Format("{0:0.00}", totalCost));

//output: 123.45
</code>```

Body:
public void LoadAveragePingTime()
{
    try
    {
        PingReply pingReply = pingClass.Send("logon.chronic-domination.com");
        double AveragePing = (pingReply.RoundtripTime / 1.75);

        label4.Text = (AveragePing.ToString() + "ms");
    }
    catch (Exception)
    {
        label4.Text = "Server is currently offline.";
    }
}

Currently my label4.Text get's something like: "187.371698712637".

I need it to show something like: "187.37"

Only two posts after the DOT. Can someone help me out?

Body:
Simple solution:

double totalCost = 123.45678;
totalCost = Convert.ToDouble(String.Format("{0:0.00}", totalCost));

//output: 123.45


问:
python beautiful soup output into excel
I am trying to get the output from the python script into excel. The script works fine in Python, but when I try and do the import CSV and writerow rule it doesn't work. It says price not defined in writerow and how would I print multiple items. Any help would be appreciated. </p>

```<code>import csv
import requests
from bs4 import BeautifulSoup

f = open('dataoutput.csv','w', newline = "")
writer = csv.writer(f)

def trade_spider(max_pages):
    page = 1
    while page <= max_pages:
        url = 'http://www.zoopla.co.uk/for-sale/property/manchester/?identifier=manchester&q=manchester&search_source=home&radius=0&pn=' + str(page)
        source_code = requests.get(url)
        plain_text = source_code.text
        soup = BeautifulSoup(plain_text)
        for link in soup.findAll('a', {'class': 'listing-results-price text-price'}):
            href = "http://www.zoopla.co.uk" + link.get('href')
            title = link.string
            get_single_item_data(href)
        page +=1

def get_single_item_data(item_url):
    source_code = requests.get(item_url)
    plain_text = source_code.text
    soup = BeautifulSoup(plain_text)
    for item_name in soup.findAll('div', {'class': 'listing-details-address'}):
     address = item_name.string
     print(item_name.get_text(strip=True))
    for item_fame in soup.findAll('div', {'class' : 'listing-details-price text-price'}):
        price = item_fame.string
        print(item_fame.get_text(strip=True))

writer.writerow(price)

trade_spider(1)
</code>```

答:
The object price is not defined anywhere in your script outside of the function get_single_item_data. Outside of that function your code cannot recognize any object with that name. Also, get_single_item_data does not return anything from the BeautifulSoup object. It only prints it. You should rewrite your function to be something like this:

```<code>def get_single_item_data(item_url):
    source_code = requests.get(item_url)
    plain_text = source_code.text
    soup = BeautifulSoup(plain_text)

    #create list to contain addresses
    addresses = []

    for item_name in soup.findAll('div', {'class': 'listing-details-address'}):
        address = item_name.string

        #add each address to the list
        addresses.append(address)

        print(item_name.get_text(strip=True))

    #create list for prices
    prices = []

    for item_fame in soup.findAll('div', {'class' : 'listing-details-price text-price'}):
        price = item_fame.string

        #add prices to list
        prices.append(price)

        print(item_fame.get_text(strip=True))

  #alter the code to return the data structure you prefer.
  return([addresses,prices])
</code>```

Title: python beautiful soup output into excel

Body:
I am trying to get the output from the python script into excel. The script works fine in Python, but when I try and do the import CSV and writerow rule it doesn't work. It says price not defined in writerow and how would I print multiple items. Any help would be appreciated.

import csv
import requests
from bs4 import BeautifulSoup

f = open('dataoutput.csv','w', newline = "")
writer = csv.writer(f)

def trade_spider(max_pages):
    page = 1
    while page <= max_pages:
        url = 'http://www.zoopla.co.uk/for-sale/property/manchester/?identifier=manchester&q=manchester&search_source=home&radius=0&pn=' + str(page)
        source_code = requests.get(url)
        plain_text = source_code.text
        soup = BeautifulSoup(plain_text)
        for link in soup.findAll('a', {'class': 'listing-results-price text-price'}):
            href = "http://www.zoopla.co.uk" + link.get('href')
            title = link.string
            get_single_item_data(href)
        page +=1

def get_single_item_data(item_url):
    source_code = requests.get(item_url)
    plain_text = source_code.text
    soup = BeautifulSoup(plain_text)
    for item_name in soup.findAll('div', {'class': 'listing-details-address'}):
     address = item_name.string
     print(item_name.get_text(strip=True))
    for item_fame in soup.findAll('div', {'class' : 'listing-details-price text-price'}):
        price = item_fame.string
        print(item_fame.get_text(strip=True))

writer.writerow(price)

trade_spider(1)

Body:
The object price is not defined anywhere in your script outside of the function get_single_item_data. Outside of that function your code cannot recognize any object with that name. Also, get_single_item_data does not return anything from the BeautifulSoup object. It only prints it. You should rewrite your function to be something like this:

def get_single_item_data(item_url):
    source_code = requests.get(item_url)
    plain_text = source_code.text
    soup = BeautifulSoup(plain_text)

    #create list to contain addresses
    addresses = []

    for item_name in soup.findAll('div', {'class': 'listing-details-address'}):
        address = item_name.string

        #add each address to the list
        addresses.append(address)

        print(item_name.get_text(strip=True))

    #create list for prices
    prices = []

    for item_fame in soup.findAll('div', {'class' : 'listing-details-price text-price'}):
        price = item_fame.string

        #add prices to list
        prices.append(price)

        print(item_fame.get_text(strip=True))

  #alter the code to return the data structure you prefer.
  return([addresses,prices])


问:
post time don't change in loop - wordpress
I want a simple loop to get latest five posts, which only consist of post title and time i wrote the loop below and the title generates fine, however the time doesn't change. as it get the first post in the loop's time for other posts as well. so all the post time is same.

Please advise why time don't loop ?

<?php
   $args = array( 'numberposts' => '5' );
   $recent_posts = wp_get_recent_posts( $args );
   foreach( $recent_posts as $recent ){ ?>

                           " class="ticker-a">
                              <?php echo get_the_time($recent["g:i a"]); ?>
                              <?php echo $recent["post_title"]; ?>

 <?php  }
   wp_reset_query();
?>```

答:
On a side note. This is a much more efficient piece of code and it is easier to output content.</p>

```<code><?php
$args = array( 'posts_per_page' => '5', 'orderby' => 'most_recent' );
$recent_posts = new WP_Query( $args );
if ( $recent_posts->have_posts() ) : while ( $recent_posts->have_posts() ) : $recent_posts->the_post(); ?>
  <li class="orbit-slide">
    <div>
      <a href="<?php the_permalink(); ?>" class="ticker-a">
        <span><?php the_time("g:i a"); ?>   </span>
        <?php the_title(); ?>
      </a>
    </div>
  </li>
<?php
endwhile; endif;
wp_reset_query();
?>
</code>```

Body:
I want a simple loop to get latest five posts, which only consist of post title and time i wrote the loop below and the title generates fine, however the time doesn't change. as it get the first post in the loop's time for other posts as well. so all the post time is same.

Please advise why time don't loop ?

<?php
   $args = array( 'numberposts' => '5' );
   $recent_posts = wp_get_recent_posts( $args );
   foreach( $recent_posts as $recent ){ ?>

                           <a href="<?php echo get_permalink($recent["ID"]); ?>" class="ticker-a">
                              <?php echo get_the_time($recent["g:i a"]); ?>
                              <?php echo $recent["post_title"]; ?>

 <?php  }
   wp_reset_query();
?>

Body:
On a side note. This is a much more efficient piece of code and it is easier to output content.

<?php
$args = array( 'posts_per_page' => '5', 'orderby' => 'most_recent' );
$recent_posts = new WP_Query( $args );
if ( $recent_posts->have_posts() ) : while ( $recent_posts->have_posts() ) : $recent_posts->the_post(); ?>
  <li class="orbit-slide">
    <div>
      <a href="<?php the_permalink(); ?>" class="ticker-a">
        <span><?php the_time("g:i a"); ?>  &nbsp;</span>
        <?php the_title(); ?>
      </a>
    </div>
  </li>
<?php
endwhile; endif;
wp_reset_query();
?>


问:
UITableView dynamic cell height scroll to top after calling reloadData
I have dynamic cell height in my tableView

```<code>tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 100
</code>```

I want to do same as whatsapp app (pagination), i want to load 25 by 25 row so when user scroll at top, i want to load new data but i want to keep same position of scroll, here is what i did

```<code>func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if isMore && scrollView.contentOffset.y == 0 {
         loadMore() // function that add new data in my model
         self.tableView.reloadData()
    }
}
</code>```

The problem that i have is after i reach top of my tableview it call reloadData but the tableView scroll to UP

I tester some other solution like this:

```<code>var cellHeights: [IndexPath : CGFloat] = [:]

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    cellHeights[indexPath] = cell.frame.size.height
}

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    guard let height = cellHeights[indexPath] else { return 70.0 }
    return height
}
</code>```

But still not working

答:
I faced the same problem in a messaging App. Here's how I solved it:

Assigned an unique messageId to every message in datasource array.

In cellForRow:, I save that messageId of very first row in a variable called messageIdFirst.

```<code>if(indexPath.row == 0){
    messageIdFirst = message.id!
}
</code>```

In loadMore() method, I check which current indexpath row have the same messageId in now updated datasource array.

```<code>if(message.id == messageIdFirst){
    previousTopIndexPath = i
}
</code>```

,where i being that index in datasource array which have the same messageId.

Now, I scroll to that previousTopIndexPath like this:

tableview.scrollToRow(at: previousTopIndexPath, at: .middle, animated: true)

Note 1: As this was not working efficiently in UITableView, I end up using UICollectionView with the same solution.

Note 2: While this does work smoothly, I know there must exist a cleaner way to do this.

Body:
I have dynamic cell height in my tableView

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 100

I want to do same as whatsapp app (pagination), i want to load 25 by 25 row so when user scroll at top, i want to load new data but i want to keep same position of scroll, here is what i did

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if isMore && scrollView.contentOffset.y == 0 {
         loadMore() // function that add new data in my model
         self.tableView.reloadData()
    }
}

The problem that i have is after i reach top of my tableview it call reloadData but the tableView scroll to UP

I tester some other solution like this:

var cellHeights: [IndexPath : CGFloat] = [:]

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    cellHeights[indexPath] = cell.frame.size.height
}

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    guard let height = cellHeights[indexPath] else { return 70.0 }
    return height
}

But still not working

Body:
I faced the same problem in a messaging App. Here's how I solved it:

Assigned an unique messageId to every message in datasource array.

In cellForRow:, I save that messageId of very first row in a variable called messageIdFirst.

if(indexPath.row == 0){
    messageIdFirst = message.id!
}

In loadMore() method, I check which current indexpath row have the same messageId in now updated datasource array.

if(message.id == messageIdFirst){
    previousTopIndexPath = i
}

,where i being that index in datasource array which have the same messageId.

Now, I scroll to that previousTopIndexPath like this:

tableview.scrollToRow(at: previousTopIndexPath, at: .middle, animated: true)

Note 1: As this was not working efficiently in UITableView, I end up using UICollectionView with the same solution.

Note 2: While this does work smoothly, I know there must exist a cleaner way to do this.


问:
How to unbind event only from one item in a list
I have a list with 3 input elements. Every element have name attribute with the same value "shipping_method" and have different id values.

```<code><ul>
<li>
<input type="radio" name="shipping_method" id="shipping_method_1"  class="shipping_method" checked="checked">
<label for="shipping_method_1">Method 1</label>
</li>
<li>
<input type="radio" name="shipping_method" id="shipping_method_2"  class="shipping_method">
<label for="shipping_method_1">Method 2</label>
</li>
<li>
<input type="radio" name="shipping_method" id="shipping_method_3"  class="shipping_method">
<label for="shipping_method_1">Method 3</label>
</li>
</ul>
</code>```

To each element using jquery .on() event bound

```<code>$(document).on("change", "input[name^=shipping_method]", shipping_method_selected)
</code>```

I can't change the code which binds the event! I have to decouple event from the second input element. I have tried to use jquery .off(), but in this case, it unbinds the events of the three elements. What are the options of unbinding events in such situations?

答:
Instead of using off you can specify which element to exclude from a selector, I've used :eq selector to deselect the second element.

$('input[name^=shipping_method]:not(:eq(1))').on("change", shipping_method_selected)

function shipping_method_selected() {
 console.log('called');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
<input type="radio" name="shipping_method" id="shipping_method_1"  class="shipping_method" checked="checked">
<label for="shipping_method_1">Method 1</label>
</li>
<li>
<input type="radio" name="shipping_method" id="shipping_method_2"  class="shipping_method">
<label for="shipping_method_1">Method 2</label>
</li>
<li>
<input type="radio" name="shipping_method" id="shipping_method_3"  class="shipping_method">
<label for="shipping_method_1">Method 3</label>
</li>
</ul></code>```

Body:
I have a list with 3 input elements. Every element have name attribute with the same value "shipping_method" and have different id values.

<input type="radio" name="shipping_method" id="shipping_method_1"  class="shipping_method" checked="checked">
Method 1

<input type="radio" name="shipping_method" id="shipping_method_2"  class="shipping_method">
Method 2

<input type="radio" name="shipping_method" id="shipping_method_3"  class="shipping_method">
Method 3

To each element using jquery .on() event bound

$(document).on("change", "input[name^=shipping_method]", shipping_method_selected)

I can't change the code which binds the event! I have to decouple event from the second input element. I have tried to use jquery .off(), but in this case, it unbinds the events of the three elements. What are the options of unbinding events in such situations?

Body:
Instead of using off you can specify which element to exclude from a selector, I've used :eq selector to deselect the second element.

$('input[name^=shipping_method]:not(:eq(1))').on("change", shipping_method_selected)

function shipping_method_selected() {
 console.log('called');
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
<input type="radio" name="shipping_method" id="shipping_method_1"  class="shipping_method" checked="checked">
<label for="shipping_method_1">Method 1</label>
</li>
<li>
<input type="radio" name="shipping_method" id="shipping_method_2"  class="shipping_method">
<label for="shipping_method_1">Method 2</label>
</li>
<li>
<input type="radio" name="shipping_method" id="shipping_method_3"  class="shipping_method">
<label for="shipping_method_1">Method 3</label>
</li>
</ul>


问:
How to create a java client to connect to Websphere server using SOAP protocol
I am using a software called Splunk, which is supposed to connect to a websphere server. This is not working.

To rule out any problems with my Websphere server, I want to write a Java program like this:

Connect to the websphere server by passing in:

Host name/IP

Port port ('SOAP_CONNECTOR_ADDRESS=18024' specified in websphere console)

Username + password for authentication

I have successfully tested the basic program:

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

public class Test {

public static void main(String args[]) throws IOException {
    final String host = "abd-def-ghi";
    final int portNumber = 81;
    System.out.println("Creating socket to '" + host + "' on port " + portNumber);

    while (true) {
        Socket socket = new Socket(host, portNumber);
        if(socket.getInetAddress().isReachable(60)) {
            System.out.println("Still connected");
        }
        else {
            System.out.println("Disconnected");
            socket.close();
            break;
        }
    }
}
</code>```

}

How do I pass in the username + password and connect to the SOAP connector port?

答: You might be able to do this test without writing any code, using wsadmin with -conntype SOAP option.  </p>

Body:
I am using a software called Splunk, which is supposed to connect to a websphere server. This is not working.

To rule out any problems with my Websphere server, I want to write a Java program like this:

Connect to the websphere server by passing in:

Host name/IP

Port port ('SOAP_CONNECTOR_ADDRESS=18024' specified in websphere console)

Username + password for authentication

I have successfully tested the basic program:

import java.io.*;

public class Test {

public static void main(String args[]) throws IOException {
    final String host = "abd-def-ghi";
    final int portNumber = 81;
    System.out.println("Creating socket to '" + host + "' on port " + portNumber);

    while (true) {
        Socket socket = new Socket(host, portNumber);
        if(socket.getInetAddress().isReachable(60)) {
            System.out.println("Still connected");
        }
        else {
            System.out.println("Disconnected");
            socket.close();
            break;
        }
    }
}

}

How do I pass in the username + password and connect to the SOAP connector port?


问:
Node.js: "process run out of memory"
I have the following code which leads to the error: FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory

It doesn't make any difference whether I set --max_old_space_size=4096 (or bigger numbers) or not. I have 16 GB RAM on my PC.

System: win10/node.js 6.9.2/mongodb 3.4

I have over 16 000 000 messages in the "chatModel". With a smaller amount of messages the code works.

Do you have any suggestions how to solve the problem/optimize the code?

```<code>function sortOutMessages(){

var atSymbol = "@";
var rgx = new RegExp("^\\" +atSymbol);

chatModel.find({messageContent: rgx}, function (err, doc){

    var docs = doc;
    var docsLength = docs.length;

    for (var i =0; i<docsLength;i++) {
        var directedMessagesObj = new directedMessagesModel
        ({
            timeStamp: docs[i].timeStamp,
            channelName: docs[i].channelName,
            userName: docs[i].userName,
            userID: docs[i].userID,
            messageContent: docs[i].messageContent,
            messageLength: docs[i].messageLength,
            subscriber: docs[i].subscriber,
            turbo: docs[i].turbo,
            moderator: docs[i].moderator
        });

        directedMessagesObj.save({upsert:true}, function (err) {
            var fs = require('fs');
            if (err) {
                    fs.appendFile("undefinedLog.txt", "error at " + new Date().toLocaleString() + " directedMessagesObj.save " + "\r\n")
                    loggerWinston.warn("error at " + new Date().toLocaleString() + " directedMessagesObj.save " + "\r\n");
                    return console.log(err);
            }

        });
    }

});

}
</code>```

答:
You are creating docs.length amount of new Promise with this code. What you should be doing instead is to limit the amount of Promise that can be running.

Since what you have been trying to write is a synchronous code, I would advise calling the next dbSave in the callback of the previous one.

If you are after a parallel system, I would create a simple semaphore system.

Title: Node.js: "process run out of memory"

Body:
I have the following code which leads to the error: FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory

It doesn't make any difference whether I set --max_old_space_size=4096 (or bigger numbers) or not. I have 16 GB RAM on my PC.

System: win10/node.js 6.9.2/mongodb 3.4

I have over 16 000 000 messages in the "chatModel". With a smaller amount of messages the code works.

Do you have any suggestions how to solve the problem/optimize the code?

function sortOutMessages(){

var atSymbol = "@";
var rgx = new RegExp("^\\" +atSymbol);

chatModel.find({messageContent: rgx}, function (err, doc){

    var docs = doc;
    var docsLength = docs.length;

    for (var i =0; i<docsLength;i++) {
        var directedMessagesObj = new directedMessagesModel
        ({
            timeStamp: docs[i].timeStamp,
            channelName: docs[i].channelName,
            userName: docs[i].userName,
            userID: docs[i].userID,
            messageContent: docs[i].messageContent,
            messageLength: docs[i].messageLength,
            subscriber: docs[i].subscriber,
            turbo: docs[i].turbo,
            moderator: docs[i].moderator
        });

        directedMessagesObj.save({upsert:true}, function (err) {
            var fs = require('fs');
            if (err) {
                    fs.appendFile("undefinedLog.txt", "error at " + new Date().toLocaleString() + " directedMessagesObj.save " + "\r\n")
                    loggerWinston.warn("error at " + new Date().toLocaleString() + " directedMessagesObj.save " + "\r\n");
                    return console.log(err);
            }

        });
    }

});

}


问:
Store many numbers as a single unique number
I have the necessity to store many numbers (i can decide which numbers) as a single unique number from which i should be able to retrieve the original number.

I already know 2 ways to do this:

1) Fundamental theorem of arithmetic (Prime Numbers)

Say i have 5 values, i assign a prime number other than 1 to each value

```<code>a = 2
b = 3
c = 5
d = 7
e = 13
</code>```

If i want to store a, b and c i can multiply them 2*3*5=30 and i know no other product of primes can be 30. Then to check if a value contains, for example, b, all i need to do is 30 % b == 0

2) Bitmask
Just like Linux permissions, use powers of 2 and sum each value

But these 2 methods grow up fast (1st way faster than 2nd), and using prime numbers requires me to have a lot of primes.

Is there any other method to do this efficiently when you have, for example, a thousand values?

答:
Is there any other method to do this efficiently when you have, for example, a thousand values?

I an not a mathematician but it's basic math, all depends on range

Range 0-1: You want to store 4 numbers 0-1 - it's basically binary system

```<code>Number1 + Number2 * 2^1 + Number3 * 2^2 + Number4 * 2^3
</code>```

Range 0-50 You want to store 4 numbers 0-49

```<code>Number1 + Number2 * 50^1 + Number3 * 50^2 + Number4 * 50^3
</code>```

Range 0-X You want to store N numbers 0-X

```<code>Number1 + Number2 * (X+1)^1 + Number3 * (X+1)^2 + ... + NumberN * (X+1)^(N-1)
</code>```

If you have no pattern for your numbers (so it can get compressed in some way) there is really no other way.

It's also super easy for computer to resolve the number unlike the prime numbers

Predetermined values

@FlorainK comment pointed me to fact I missed

(i can decide which numbers)

The only logical solution is give your numbers references

```<code>0 is 15342
1 is 6547
2 is 76234
3 is "i like stack overflow"
4 is 42141
</code>```

so you'll work range 0-4 (5 options) and whatever combination  length. Use reference when "encoding" and "decoding" the number

a thousand values?

so you'll work with Range 0-999

```<code>0 is 62342
1 is 7456345653
2 is 45656234532
...
998 is 7623452
999 is 4324234326453
</code>```

Let's say you use 64-bit system and programming/db language that works with 64-bit integers

```<code>2^64 = 18446744073709551616
</code>```

your max range is 1000^X < 18446744073709551616 where X is number of numbers you can store in one single 64-bit integer number

Which is only 6.

You can store only 6 separate numbers 0-999 that will fit one 64-bit integer number.

```<code>0,0,0,0,0,0 is 0
1,0,0,0,0,0 is 1
0,1,0,0,0,0 is 1000
999,999,999,999,999,999 is ~1e+18
</code>```

Body:
I have the necessity to store many numbers (i can decide which numbers) as a single unique number from which i should be able to retrieve the original number.

I already know 2 ways to do this:

1) Fundamental theorem of arithmetic (Prime Numbers)

Say i have 5 values, i assign a prime number other than 1 to each value

a = 2
b = 3
c = 5
d = 7
e = 13

If i want to store a, b and c i can multiply them 2*3*5=30 and i know no other product of primes can be 30. Then to check if a value contains, for example, b, all i need to do is 30 % b == 0

2) Bitmask
Just like Linux permissions, use powers of 2 and sum each value

But these 2 methods grow up fast (1st way faster than 2nd), and using prime numbers requires me to have a lot of primes.

Is there any other method to do this efficiently when you have, for example, a thousand values?

Body:
Is there any other method to do this efficiently when you have, for example, a thousand values?

I an not a mathematician but it's basic math, all depends on range

Range 0-1: You want to store 4 numbers 0-1 - it's basically binary system

Number1 + Number2 * 2^1 + Number3 * 2^2 + Number4 * 2^3

Range 0-50 You want to store 4 numbers 0-49

Number1 + Number2 * 50^1 + Number3 * 50^2 + Number4 * 50^3

Range 0-X You want to store N numbers 0-X

Number1 + Number2 * (X+1)^1 + Number3 * (X+1)^2 + ... + NumberN * (X+1)^(N-1)

If you have no pattern for your numbers (so it can get compressed in some way) there is really no other way.

It's also super easy for computer to resolve the number unlike the prime numbers

Predetermined values

@FlorainK comment pointed me to fact I missed

(i can decide which numbers)

The only logical solution is give your numbers references

0 is 15342
1 is 6547
2 is 76234
3 is "i like stack overflow"
4 is 42141

so you'll work range 0-4 (5 options) and whatever combination  length. Use reference when "encoding" and "decoding" the number

a thousand values?

so you'll work with Range 0-999

0 is 62342
1 is 7456345653
2 is 45656234532
...
998 is 7623452
999 is 4324234326453

Let's say you use 64-bit system and programming/db language that works with 64-bit integers

2^64 = 18446744073709551616

your max range is 1000^X < 18446744073709551616 where X is number of numbers you can store in one single 64-bit integer number

Which is only 6.

You can store only 6 separate numbers 0-999 that will fit one 64-bit integer number.

0,0,0,0,0,0 is 0
1,0,0,0,0,0 is 1
0,1,0,0,0,0 is 1000
999,999,999,999,999,999 is ~1e+18


问:
tracking canvas x and y coordinates animation on mousemove event
I am trying to make a circle moving animation with mousemove event, each time the circle will moving from my mouse.x and mouse.ycoordinates on the screen. so I declare my mouse coordinates object and drawCricleobject constructor:

```<code>    var mouse = {
        x:canvas.width/2,
        y:canvas.height/2
    }

        function Circle (x,y,r,dy){
        this.x = x;
        this.y = y;
        this.r = r;
        this.dy = dy;
        this.update = function(){
            ctx.beginPath();
            ctx.arc(this.x,this.y,this.r,0,Math.PI*2);
            ctx.fillStyle = 'blue';
            ctx.fill();

            this.y+=this.dy;

            if(this.y<this.r || this.y+this.r>canvas.height){
                this.dy=-this.dy;
            }
        }
    }
</code>```

and after i add the mousemoveevent so i am thinking i can assign the mouse x/y coordinate through my mouvemove eventListenter:

```<code>    var myCircle = new Circle(mouse.x,mouse.y,30,2);

    function animate(){
        ctx.clearRect(0,0,canvas.width,canvas.height);
        myCircle.update();
        requestAnimationFrame(animate);
    }

window.addEventListener("mousemove",function(e){
        mouse.x = e.clientX;
        mouse.y = e.clientY;
        animate();
    });
</code>```

the problem is the mouse.xandmouse.yvalue won't change from the original canvas.width/2value, so i have tried to wrapper my animation()function inside the window.addEventListener instead just calling it within, just like:

```<code>    window.addEventListener("mousemove",function(e){
        mouse.x = e.clientX;
        mouse.y = e.clientY;
        var myCircle = new Circle(mouse.x,mouse.y,30,2);

        function animate(){
        ctx.clearRect(0,0,canvas.width,canvas.height);
        myCircle.update();
        requestAnimationFrame(animate);
    }
animate();
    });
</code>```

this could work a bit but it looks really stupid and makes my browser comes huge laggy spikes, is there any other way to do this?

答:
You would also need to pass the mouse coordinates when calling the update function ...

var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');
var mouse = {
   x: canvas.width / 2,
   y: canvas.height / 2
};

function Circle(x, y, r, dy) {
   this.r = r;
   this.dy = dy;
   this.update = function(x, y) {
      ctx.beginPath();
      ctx.arc(x, y, this.r, 0, Math.PI * 2);
      ctx.fillStyle = 'blue';
      ctx.fill();
      this.y += this.dy;
      if (this.y < this.r || this.y + this.r > canvas.height) {
         this.dy = -this.dy;
      }
   };
}

var myCircle = new Circle(mouse.x, mouse.y, 30, 2);

function animate() {
   ctx.clearRect(0, 0, canvas.width, canvas.height);
   myCircle.update(mouse.x, mouse.y);
   requestAnimationFrame(animate);
}

canvas.addEventListener("mousemove", function(e) {
   mouse.x = e.offsetX;
   mouse.y = e.offsetY;
});

animate();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{margin:10px 0 0 0;overflow:hidden}canvas{border:1px solid #e4e6e8}</code>```

<canvas id="canvas" width="635" height="208"></canvas>```

Body:
I am trying to make a circle moving animation with mousemove event, each time the circle will moving from my mouse.x and mouse.ycoordinates on the screen. so I declare my mouse coordinates object and drawCricleobject constructor:

    var mouse = {
        x:canvas.width/2,
        y:canvas.height/2
    }

        function Circle (x,y,r,dy){
        this.x = x;
        this.y = y;
        this.r = r;
        this.dy = dy;
        this.update = function(){
            ctx.beginPath();
            ctx.arc(this.x,this.y,this.r,0,Math.PI*2);
            ctx.fillStyle = 'blue';
            ctx.fill();

            this.y+=this.dy;

            if(this.y<this.r || this.y+this.r>canvas.height){
                this.dy=-this.dy;
            }
        }
    }

and after i add the mousemoveevent so i am thinking i can assign the mouse x/y coordinate through my mouvemove eventListenter:

    var myCircle = new Circle(mouse.x,mouse.y,30,2);

    function animate(){
        ctx.clearRect(0,0,canvas.width,canvas.height);
        myCircle.update();
        requestAnimationFrame(animate);
    }

window.addEventListener("mousemove",function(e){
        mouse.x = e.clientX;
        mouse.y = e.clientY;
        animate();
    });

the problem is the mouse.xandmouse.yvalue won't change from the original canvas.width/2value, so i have tried to wrapper my animation()function inside the window.addEventListener instead just calling it within, just like:

    window.addEventListener("mousemove",function(e){
        mouse.x = e.clientX;
        mouse.y = e.clientY;
        var myCircle = new Circle(mouse.x,mouse.y,30,2);

        function animate(){
        ctx.clearRect(0,0,canvas.width,canvas.height);
        myCircle.update();
        requestAnimationFrame(animate);
    }
animate();
    });

this could work a bit but it looks really stupid and makes my browser comes huge laggy spikes, is there any other way to do this?

Body:
You would also need to pass the mouse coordinates when calling the update function ...

var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');
var mouse = {
   x: canvas.width / 2,
   y: canvas.height / 2
};

function Circle(x, y, r, dy) {
   this.r = r;
   this.dy = dy;
   this.update = function(x, y) {
      ctx.beginPath();
      ctx.arc(x, y, this.r, 0, Math.PI * 2);
      ctx.fillStyle = 'blue';
      ctx.fill();
      this.y += this.dy;
      if (this.y < this.r || this.y + this.r > canvas.height) {
         this.dy = -this.dy;
      }
   };
}

var myCircle = new Circle(mouse.x, mouse.y, 30, 2);

function animate() {
   ctx.clearRect(0, 0, canvas.width, canvas.height);
   myCircle.update(mouse.x, mouse.y);
   requestAnimationFrame(animate);
}

canvas.addEventListener("mousemove", function(e) {
   mouse.x = e.offsetX;
   mouse.y = e.offsetY;
});

animate();

body{margin:10px 0 0 0;overflow:hidden}canvas{border:1px solid #e4e6e8}

<canvas id="canvas" width="635" height="208"></canvas>


问:
Issue with getting information from a music track
I am trying to get some information from a music track, everything works fine but some music has no title , artist and cover artwork , and in this case I have to provide a default value for example Unknown.

I am filling table view with track's information like this :

```<code>//MARK: - Get Data From Track :
func getDataFromTrack(file:URL)  {

    //Get data from track
    urlAsset = AVURLAsset(url: file)
    for format in urlAsset.availableMetadataFormats {

        for metadata in urlAsset.metadata(forFormat: format) {

            //Track Name :
            if metadata.commonKey == "title" {
                if let title = metadata.stringValue {
                    appDefaults.setTrack(Name: title)
                } else {
                    appDefaults.setTrack(Name: "Unknown")
                }
            }

                //Track Artist:
            if metadata.commonKey == "artist" {
                    if let artist = metadata.stringValue {
                        appDefaults.setArtist(Name: artist)
                    } else {
                        appDefaults.setArtist(Name: "Unknown")
                    }
                }

            //Track Cover:
            if metadata.commonKey == "artwork" {
                if let data = metadata.dataValue {
                    let image = UIImage(data: data)
                    appDefaults.setCover(Image: image!)
                }  else {
                    appDefaults.setCover(Image: #imageLiteral(resourceName: "Defualt cover"))
                }
            }

            appDefaults.setTrack(duration: Float(CMTimeGetSeconds(urlAsset.duration)))
        }
    }
}
</code>```

In table view :

```<code>  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

... setup cell

 let fileName = player.MP3DirectoryFiles[indexPath.row-2] as! NSString
            let absoluteFileName = String(describing: fileName.lastPathComponent)
            let removeSpaceString = absoluteFileName.replacingOccurrences(of: "%20", with: " ")

            //Get MP3 Infromations
            let documentsURL = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!,isDirectory: true )
            let urlToMyPath = documentsURL.appendingPathComponent(removeSpaceString)!

            player.getDataFromTrack(file: urlToMyPath)

}
</code>```

If there is no data from track cell fill its data for example title with other tracks information !

I tried to get nil value like this , but did not help me :

```<code>if metadata.commonKey == "artist" {
                    if let artist = metadata.stringValue {
                        appDefaults.setArtist(Name: artist)
                    } else {
                        appDefaults.setArtist(Name: "Unknown")
                    }
                }
</code>```

答:
Try setting your default values first, and then updating them if and when the corresponding tags are found for the asset:

```<code>//MARK: - Get Data From Track :
func getDataFromTrack(file:URL)  {
    // Set defaults
    appDefaults.setTrack(Name: "Unknown")
    appDefaults.setArtist(Name: "Unknown")
    appDefaults.setCover(Image: #imageLiteral(resourceName: "Defualt cover"))
    appDefaults.setTrack(duration: Float(CMTimeGetSeconds(urlAsset.duration)))

    //Get data from track
    urlAsset = AVURLAsset(url: file)
    for format in urlAsset.availableMetadataFormats {
        for metadata in urlAsset.metadata(forFormat: format) {

            //Track Name :
            if metadata.commonKey == "title" {
                if let title = metadata.stringValue, !title.isEmpty {
                    appDefaults.setTrack(Name: title)
                }
            }

            //Track Artist:
            if metadata.commonKey == "artist" {
                if let artist = metadata.stringValue, !artist.isEmpty {
                    appDefaults.setArtist(Name: artist)
                }
            }

            //Track Cover:
            if metadata.commonKey == "artwork" {
                if let data = metadata.dataValue {
                    let image = UIImage(data: data)
                    appDefaults.setCover(Image: image!)
                }
            }
        }
    }
}
</code>```

The code where you try to set the default value will never be called if the asset does not contain the appropriate key. Also, setting the track duration inside the for loops will cause it to be unnecessarily executed multiple times.

Body:
I am trying to get some information from a music track, everything works fine but some music has no title , artist and cover artwork , and in this case I have to provide a default value for example Unknown.

I am filling table view with track's information like this :

//MARK: - Get Data From Track :
func getDataFromTrack(file:URL)  {

    //Get data from track
    urlAsset = AVURLAsset(url: file)
    for format in urlAsset.availableMetadataFormats {

        for metadata in urlAsset.metadata(forFormat: format) {

            //Track Name :
            if metadata.commonKey == "title" {
                if let title = metadata.stringValue {
                    appDefaults.setTrack(Name: title)
                } else {
                    appDefaults.setTrack(Name: "Unknown")
                }
            }

                //Track Artist:
            if metadata.commonKey == "artist" {
                    if let artist = metadata.stringValue {
                        appDefaults.setArtist(Name: artist)
                    } else {
                        appDefaults.setArtist(Name: "Unknown")
                    }
                }

            //Track Cover:
            if metadata.commonKey == "artwork" {
                if let data = metadata.dataValue {
                    let image = UIImage(data: data)
                    appDefaults.setCover(Image: image!)
                }  else {
                    appDefaults.setCover(Image: #imageLiteral(resourceName: "Defualt cover"))
                }
            }

            appDefaults.setTrack(duration: Float(CMTimeGetSeconds(urlAsset.duration)))
        }
    }
}

In table view :

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

... setup cell

 let fileName = player.MP3DirectoryFiles[indexPath.row-2] as! NSString
            let absoluteFileName = String(describing: fileName.lastPathComponent)
            let removeSpaceString = absoluteFileName.replacingOccurrences(of: "%20", with: " ")

            //Get MP3 Infromations
            let documentsURL = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!,isDirectory: true )
            let urlToMyPath = documentsURL.appendingPathComponent(removeSpaceString)!

            player.getDataFromTrack(file: urlToMyPath)

}

If there is no data from track cell fill its data for example title with other tracks information !

I tried to get nil value like this , but did not help me :

if metadata.commonKey == "artist" {
                    if let artist = metadata.stringValue {
                        appDefaults.setArtist(Name: artist)
                    } else {
                        appDefaults.setArtist(Name: "Unknown")
                    }
                }

Body:
Try setting your default values first, and then updating them if and when the corresponding tags are found for the asset:

//MARK: - Get Data From Track :
func getDataFromTrack(file:URL)  {
    // Set defaults
    appDefaults.setTrack(Name: "Unknown")
    appDefaults.setArtist(Name: "Unknown")
    appDefaults.setCover(Image: #imageLiteral(resourceName: "Defualt cover"))
    appDefaults.setTrack(duration: Float(CMTimeGetSeconds(urlAsset.duration)))

    //Get data from track
    urlAsset = AVURLAsset(url: file)
    for format in urlAsset.availableMetadataFormats {
        for metadata in urlAsset.metadata(forFormat: format) {

            //Track Name :
            if metadata.commonKey == "title" {
                if let title = metadata.stringValue, !title.isEmpty {
                    appDefaults.setTrack(Name: title)
                }
            }

            //Track Artist:
            if metadata.commonKey == "artist" {
                if let artist = metadata.stringValue, !artist.isEmpty {
                    appDefaults.setArtist(Name: artist)
                }
            }

            //Track Cover:
            if metadata.commonKey == "artwork" {
                if let data = metadata.dataValue {
                    let image = UIImage(data: data)
                    appDefaults.setCover(Image: image!)
                }
            }
        }
    }
}

The code where you try to set the default value will never be called if the asset does not contain the appropriate key. Also, setting the track duration inside the for loops will cause it to be unnecessarily executed multiple times.


问:
argparse on demand imports for types, choices etc
I have quite a big program which has a CLI interaction based on argparse, with several sub parsers. The list of supported choices for the subparsers arguments are determined based on DB queries, parsing different xml files, making different calculations etc, so it is quite IO intensive and time consuming.

The problem is that argparse seems to fetch choices for all sub parser when I run the script, which adds a considerable and annoying startup delay.

Is there a way to make argparse only fetch and validate choices for the currently used sub parser?

One solution could be to move all the validation logic deeper inside the code but that would mean quite a lot of work which I would like to avoid, if possible.

Thank you

答:
This is a script that tests the idea of delaying the creation of a subparser until it is actually needed.  In theory it might save start up time, by only creating the subparser that's actually needed.

I use the nargs=argparse.PARSER to replicate the subparser behavior in the main parser.  help behavior is similar.

```<code># lazy subparsers test
# lazy behaves much like a regular subparser case, but only creates one subparser
# for N=5 time differences do not rise above the noise

import argparse

def regular(N):
    parser = argparse.ArgumentParser()
    sp = parser.add_subparsers(dest='cmd')
    for i in range(N):
        spp = sp.add_parser('cmd%s'%i)
        spp.set_defaults(func='cmd%s'%(10*i))
        spp.add_argument('-f','--foo')
        spp.add_argument('pos', nargs='*')
    return parser

def lazy(N):
    parser = argparse.ArgumentParser()
    sp = parser.add_argument('cmd', nargs=argparse.PARSER, choices=[])
    for i in range(N):
        sp.choices.append('cmd%s'%i)
    return parser

def subpar(cmd):
    cmd, argv = cmd[0], cmd[1:]
    parser = argparse.ArgumentParser(prog=cmd)
    parser.add_argument('-f','--foo')
    parser.add_argument('pos', nargs='*')
    parser.set_defaults(func=cmd)
    args = parser.parse_args(argv)
    return args

N = 5
mode = True #False
argv = 'cmd1 -f1 a b c'.split()
if mode:
    args = regular(N).parse_args(argv)
    print(args)
else:
    args = lazy(N).parse_args(argv)
    print(args)
    if isinstance(args.cmd, list):
        sargs = subpar(args.cmd)
        print(sargs)
</code>```

test runs with different values of mode (and N=5)

```<code>1004:~/mypy$ time python3 stack44315696.py
Namespace(cmd='cmd1', foo='1', func='cmd10', pos=['a', 'b', 'c'])

real    0m0.052s
user    0m0.044s
sys 0m0.008s
1011:~/mypy$ time python3 stack44315696.py
Namespace(cmd=['cmd1', '-f1', 'a', 'b', 'c'])
Namespace(foo='1', func='cmd1', pos=['a', 'b', 'c'])

real    0m0.051s
user    0m0.048s
sys 0m0.000s
</code>```

N has to be much larger to start seeing a effect.

Body:
This is a script that tests the idea of delaying the creation of a subparser until it is actually needed.  In theory it might save start up time, by only creating the subparser that's actually needed.

I use the nargs=argparse.PARSER to replicate the subparser behavior in the main parser.  help behavior is similar.

# lazy subparsers test
# lazy behaves much like a regular subparser case, but only creates one subparser
# for N=5 time differences do not rise above the noise

import argparse

def regular(N):
    parser = argparse.ArgumentParser()
    sp = parser.add_subparsers(dest='cmd')
    for i in range(N):
        spp = sp.add_parser('cmd%s'%i)
        spp.set_defaults(func='cmd%s'%(10*i))
        spp.add_argument('-f','--foo')
        spp.add_argument('pos', nargs='*')
    return parser

def lazy(N):
    parser = argparse.ArgumentParser()
    sp = parser.add_argument('cmd', nargs=argparse.PARSER, choices=[])
    for i in range(N):
        sp.choices.append('cmd%s'%i)
    return parser

def subpar(cmd):
    cmd, argv = cmd[0], cmd[1:]
    parser = argparse.ArgumentParser(prog=cmd)
    parser.add_argument('-f','--foo')
    parser.add_argument('pos', nargs='*')
    parser.set_defaults(func=cmd)
    args = parser.parse_args(argv)
    return args

N = 5
mode = True #False
argv = 'cmd1 -f1 a b c'.split()
if mode:
    args = regular(N).parse_args(argv)
    print(args)
else:
    args = lazy(N).parse_args(argv)
    print(args)
    if isinstance(args.cmd, list):
        sargs = subpar(args.cmd)
        print(sargs)

test runs with different values of mode (and N=5)

1004:~/mypy$ time python3 stack44315696.py
Namespace(cmd='cmd1', foo='1', func='cmd10', pos=['a', 'b', 'c'])

real    0m0.052s
user    0m0.044s
sys 0m0.008s
1011:~/mypy$ time python3 stack44315696.py
Namespace(cmd=['cmd1', '-f1', 'a', 'b', 'c'])
Namespace(foo='1', func='cmd1', pos=['a', 'b', 'c'])

real    0m0.051s
user    0m0.048s
sys 0m0.000s

N has to be much larger to start seeing a effect.


问:
Iterate on a range of iterable
I have interface that returns a iterable object.
I need to iterate on the first 1000 items of it.
What is the best way to combine iterating using Iterator and stop after a certain count is reached.

Thanks

答:
Make a standard loop that iterates over your collection, but check to see if the index has progress past the target index.

You may want to extract a seperate counter from the main loop index for your specific application.

```<code>int stopIndex = 1000;

for (int index = 0; index <= theInterface.Count; index++)
{
    // check to see if we're at/past the stopIndex
    if (index >= stopIndex)
        break;

    // we're still within the conditions, so do something with your interface
    myObjectType localObject = (MyObjectType)theInterface.IndexOf(index);
}
</code>```

Title: Iterate on a range of iterable

Body:
Make a standard loop that iterates over your collection, but check to see if the index has progress past the target index.

You may want to extract a seperate counter from the main loop index for your specific application.

int stopIndex = 1000;

for (int index = 0; index <= theInterface.Count; index++)
{
    // check to see if we're at/past the stopIndex
    if (index >= stopIndex)
        break;

    // we're still within the conditions, so do something with your interface
    myObjectType localObject = (MyObjectType)theInterface.IndexOf(index);
}


问:
How can i create a canvas in a framelayout that is part of a xml layoutfile
I'm a total beginner on Android, I only have some java experience from school.
For programing a Game I want to draw on a canvas in a Frame layout, that's part of a xml layoutfile.
My java.class should relate to this layoutfile.
Is this possible, and if yes, how? I didn't found a solution on the web.
best regards,
Slarti.</p>

答: Creating a custom view by extending View class and add that view in your FrameLayout. In your custom view file override onDraw(Canvas canvas) and draw anything on that canvas.