working on it ...


Explore Public Snippets

Sort by

Found 101k snippets matching: python

    public by fabio.nosenzo @ Amazon_AWS_Python_API  588161  5  8  -1

    Amazon S3 Aws - S3Connection object from python boto API

    This snippet is about the S3Connection object provided by python boto package for Amazon AWS API. Here the __init__ method is listed with all its variables. The AWSAuthConnection object is initialized and it handles all the data for managing requests and response from Amazon AWS service. Path: [boto/s3/] Learn more about S3Con
    import boto.utils
    from boto.connection import AWSAuthConnection
    class S3Connection(AWSAuthConnection):
        DefaultHost = boto.config.get('s3', 'host', '')
        DefaultCallingFormat = boto.config.get('s3', 'calling_format', 'boto.s3.connection.SubdomainCallingFormat')
        QueryString = 'Signature=%s&Expires=%d&AWSAccessKeyId=%s'
        def __init__(self, aws_access_key_id=None, aws_secret_access_key=None,
                     is_secure=True, port=None, proxy=None, proxy_port=None,
                     proxy_user=None, proxy_pass=None,
                     host=DefaultHost, debug=0, https_connection_factory=None,
                     calling_format=DefaultCallingFormat, path='/',
                     provider='aws', bucket_class=Bucket, security_token=None,
                     suppress_consec_slashes=True, anon=False,
            if isinstance(calling_format, str):
            self.calling_format = calling_format
            self.bucket_class = bucket_class
            self.anon = anon
            AWSAuthConnection.__init__(self, host,
                    aws_access_key_id, aws_secret_access_key,
                    is_secure, port, proxy, proxy_port, proxy_user, proxy_pass,
                    debug=debug, https_connection_factory=https_connection_factory,
                    path=path, provider=provider, security_token=security_token,

    public by lbottaro  529684  10  8  0

    How to get the list of all the activities comparing two UCM streams in python

    This script shows how to get the list of all the activities comparing two ucm streams. The command returns a list object you can easily loop and print.
    import os
    myView = "MyView"
    diff_act=os.popen("cleartool setview -exec \"cleartool diffbl -nmerge -activities "+bl_old+" "+ bl_new+" \" " +myView).readlines()
    for act in diff_act:
      print ("ACTIVITY: "+str(act))

    public by mprisznyak  548603  3  8  8

    Avoid complicated 'if' statements

    The Bad, Ugly Villain and the Good, Handsome Hero
    def decide_in_the_wrong_way(a, b, c):
        return True if one of the conditions holds true
        using a bunch of complicated, messy if statements, multiple exit points
        if a < 12 and b*c > 80:
            return True
        if a >= 12 and b*c/a > 20:
            return True
        if a < 0:
            return True
            if 10 <= b*c  <= 15:
                return True
                return False
        # ... and a bunch of other conditions..
        return False
    def decide_in_the_right_way(a, b, c):
        return True if one of the conditions holds true
        using innner functions which express the conditions in 
        in an easily understandable form
        def decision1(a, b, c):
            return a < 12 and b*c > 80
        def decision2(a, b, c):
            return 12 and b*c/a > 20
        def decision3(a, b, c):
            def sensibly_named_condition(b, c):
                return 10 <= b*c <= 15
            return a < 0 or sensibly_named_condition(b,c)
        # ... and a bunch of other similar boolean functions..
        # collect the decision functions in a list
        decisions = [decision_fv for name, decision_fv in locals().items() 
                          if name.startswith("decision")]
        # note the use of "for ... else"!
        for decision in decisions:
            result =  decision(a, b, c)
            if result: break
            result = False # executed only if no "break" occurred in the loop
        return result # note that the function has a single exit point
    if __name__ == "__main__":
        if decide_in_the_wrong_way(12,21,8):
            print "YES! - in the wrong way"
            print "No! - in the wrong way"
        if decide_in_the_right_way(12,21,8):
            print "YES! - in the right way"
            print "No! - in the right way"      

    public by antlong  489215  15  7  1

    Extract JPG images from a PDF

    A command line tool to extract jpg images from pdf files.
    #!/usr/bin/env python
    import sys
    def main():
        """Extract JPG's from PSD's.
          python filename.pdf
          All extracted images will be saved to the directory 
          the script is initialized in.
            pdf = file(sys.argv[1], "rb").read()
        except Exception:
            print "Usage: `python filename.pdf`"
        startmark, endmark = "\xff\xd8", "\xff\xd9"
        startfix, endfix, i, njpg = 0, 2, 0, 0
        while True:
            istream = pdf.find("stream", i)
            if istream < 0:
            istart = pdf.find(startmark, istream, istream+20)
            if istart < 0:
                i = istream+20
            iend = pdf.find("endstream", istart)
            if iend < 0:
                raise Exception("Couldn't find end of stream.")
            iend = pdf.find(endmark, iend-20)
            if iend < 0:
                raise Exception("Couldn't find end of JPG.")
            istart += startfix
            iend += endfix
            jpg = pdf[istart:iend]
            with open("jpg%d.jpg" % njpg, "wb") as _f:
            njpg += 1
            i = iend
        print "Extracted %s JPG files." % njpg

    public by lbottaro  311381  3  6  0

    Get MAC address of current interface in Python

    This python uses uuid.getnode to get current mac address as an integer. It formats the number in a standard mac address form (i.e. bytes splitted by :)
    import uuid
    print ':'.join(['{:02x}'.format((uuid.getnode() >> i) & 0xff) for i in range(0,8*6,8)][::-1])

    public by lbottaro  303303  31  7  0

    How to read and parse a txt file in python

    This code shows how to read a txt file and parse the data
    import os
    import sys
    myfile = open('/some/path/to/file.txt', "r")
    # abc 123 234 456 678
    # def 122223 2333334 454446 611178
    # ghi 144423 211134 44456 61114478
    for line in myfile.readlines():
        name= ''
        numList = list()
        print line
            name = line.split()[0] # it will get 'abc'/'def'/'ghi'
            numList = line.split()[1:] # it will get all other stuff inline...
            print "Invalid file format"
        if not numList:
            print("Invalid numList format! name= " + str(name))
        print 'name='+str(name)
        print 'numList='+str(numList)

    public by lbottaro @ Amazon_AWS_Python_API  304432  0  8  0

    Amazon S3 Aws - How to download a file from a bucket to a target directory

    This code shows how to download a file from an existing bucket invoking the boto python API, saving to a target directory. You need to specify the filename and path where to save the data. [How to create a bucket]( [How to upload a file to a bucket](
    # This downloads the object foobar.pdf and saves it in /home/luca/documents/
    key = bucket.get_key('foobar.pdf')

    public by lbottaro  247352  3  7  0

    Lock and synchronization in python

    This example shows how to deal with lock in python parallel programming. Here we want to calculate the disk occupancy for a given directory in Linux OS, evaluating the disk occupancy for any subdirectory using threads. Note the usage of lock mechanism to ensure atomic operation on the total sum.
    import os
    import string
    import threading
    from threading import Thread
    disk_usage = 0
    lock = threading.Lock()
    for dir in os.popen('ls -d *').readlines():
        print "Dir: " + dir
        t = Thread(target=methodToBeExecutedInParallel, args=(dir,))
        #Join all existing threads to main thread.
        for thread in threading.enumerate():
            if thread is not threading.currentThread():
        print "Disk usage = " + str(disk_usage)
    # Function invoked by each thread
    def methodToBeExecutedInParallel(directory):
        print "Working on dir = " + directory
        cmd = 'du -s ' + directory
        line = os.popen(cmd).readlines()[0]
        dirUsage = int(line.split()[0])
        print "Acquiring lock for "+directory+"..."
        with lock:
            print "Acquired lock for "+directory
            global disk_usage
            disk_usage += dirUsage
        print "Disk usage = " + str(dirUsage)

    public by sh1nu11bi  253558  1  4  0

    Quick Python server

    Quick Python server: gistfile1.txt
    python -m SimpleHTTPServer & ncat --ssl -l 8443 --sh-exec "ncat 8000" --keep-open

    public by DavidEGrayson  351124  2  3  0

    Trying to install the cryptography pip in MSYS2 with mingw-w64-x86_64-python2-pip.

    Trying to install the cryptography pip in MSYS2 with mingw-w64-x86_64-python2-pip.: output.txt
    $ pip install -U cryptography
    Collecting cryptography
      Downloading cryptography-1.0.2.tar.gz (332kB)
    Collecting idna>=2.0 (from cryptography)
      Downloading idna-2.0-py2.py3-none-any.whl (61kB)
    Collecting pyasn1>=0.1.8 (from cryptography)
      Downloading pyasn1-0.1.9-py2.py3-none-any.whl
    Collecting six>=1.4.1 (from cryptography)
      Downloading six-1.10.0-py2.py3-none-any.whl
    Collecting setuptools (from cryptography)
      Downloading setuptools-18.4-py2.py3-none-any.whl (462kB)
    Collecting enum34 (from cryptography)
      Downloading enum34-1.0.4.tar.gz
    Collecting ipaddress (from cryptography)
      Downloading ipaddress-1.0.14-py27-none-any.whl
    Collecting cffi>=1.1.0 (from cryptography)
      Downloading cffi-1.2.1.tar.gz (335kB)
    Collecting pycparser (from cffi>=1.1.0->cryptography)
      Downloading pycparser-2.14.tar.gz (223kB)
    Installing collected packages: idna, pyasn1, six, setuptools, enum34, ipaddress, pycparser, cffi, cryptography
      Found existing installation: setuptools 18.3.2
        Uninstalling setuptools-18.3.2:
          Successfully uninstalled setuptools-18.3.2
      Running install for enum34
        Complete output from command D:/msys64/mingw64/bin/python2.exe -c "import setuptools, tokenize;__file__='c:/users/david/appdata/local/temp/pip-build-ojokdu/enum34/';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record c:\users\david\appdata\local\temp/pip-egkxlc-record/install-record.txt --single-version-externally-managed --compile:
        Traceback (most recent call last):
          File "<string>", line 1, in <module>
          File "D:/msys64/mingw64/lib/python2.7/site-packages/setuptools/", line 12, in <module>
            from setuptools.extension import Extension
          File "D:/msys64/mingw64/lib/python2.7/site-packages/setuptools/", line 9, in <module>
            from . import msvc9_support
          File "D:/msys64/mingw64/lib/python2.7/site-packages/setuptools/", line 2, in <module>
            import distutils.msvc9compiler
          File "D:/msys64/mingw64/lib/python2.7/distutils/", line 306, in <module>
            raise DistutilsPlatformError("VC %0.1f is not supported by this module" % VERSION)
        distutils.errors.DistutilsPlatformError: VC 6.0 is not supported by this module
    Command "D:/msys64/mingw64/bin/python2.exe -c "import setuptools, tokenize;__file__='c:/users/david/appdata/local/temp/pip-build-ojokdu/enum34/';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record c:\users\david\appdata\local\temp/pip-egkxlc-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in c:/users/david/appdata/local/temp/pip-build-ojokdu/enum34
    • Public Snippets
    • Channels Snippets