working on it ...

Filters

Explore Public Snippets

Sort by

Found 90k snippets matching: python

    public by fabio.nosenzo @ Amazon_AWS_Python_API modified Aug 1, 2013  587399  4  8  0

    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/connection.py] Learn more about S3Con
    import boto.utils
    from boto.connection import AWSAuthConnection
    
    class S3Connection(AWSAuthConnection):
        DefaultHost = boto.config.get('s3', 'host', 's3.amazonaws.com')
        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,
                     validate_certs=None):
            if isinstance(calling_format, str):
                calling_format=boto.utils.find_class(calling_format)()
            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,
                    suppress_consec_slashes=suppress_consec_slashes,
                    validate_certs=validate_certs)

    public by lbottaro modified Oct 17, 2013  528868  9  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
    
    bl_old="myOldBaseline@/MyVobs"
    bl_new="myNewBaseline@/MyVobs"
    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 modified May 5, 2014  547979  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
        else:
            if 10 <= b*c  <= 15:
                return True
            else:
                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
        else:
            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"
        else:
            print "No! - in the wrong way"
            
        if decide_in_the_right_way(12,21,8):
            print "YES! - in the right way"
        else:
            print "No! - in the right way"      
    
    

    public by antlong modified Aug 10, 2015  488613  10  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.
        
        Usage:
          python extract.py filename.pdf
        
        Note:
          All extracted images will be saved to the directory 
          the script is initialized in.
        """
        try:
            pdf = file(sys.argv[1], "rb").read()
        except Exception:
            print "Usage: `python extract.py filename.pdf`"
            return
    
        startmark, endmark = "\xff\xd8", "\xff\xd9"
        startfix, endfix, i, njpg = 0, 2, 0, 0
    
        while True:
            istream = pdf.find("stream", i)
            if istream < 0:
                break
            istart = pdf.find(startmark, istream, istream+20)
            if istart < 0:
                i = istream+20
                continue
            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:
                _f.write(jpg)
            njpg += 1
            i = iend
    
        print "Extracted %s JPG files." % njpg
    
    main()
    

    public by lbottaro modified Nov 6, 2012  311065  2  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 modified Sep 10, 2013  302870  30  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")
    # EXAMPLE OF FILE FORMAT:
    # 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
        try:
            name = line.split()[0] # it will get 'abc'/'def'/'ghi'
            numList = line.split()[1:] # it will get all other stuff inline...
        except:
            print "Invalid file format"
            myfile.close()
            sys.exit(1)
        
        if not numList:
            print("Invalid numList format! name= " + str(name))
            myfile.close()
            sys.exit(1)
    
        print 'name='+str(name)
        print 'numList='+str(numList)
    
    myfile.close()

    public by lbottaro @ Amazon_AWS_Python_API modified Aug 1, 2013  303794  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](http://www.snip2code.com/Snippet/4892/Amazon-Aws-S3---Creating-a-bucket-in-pyt) [How to upload a file to a bucket](http://www.sn
    # This downloads the object foobar.pdf and saves it in /home/luca/documents/
    
    key = bucket.get_key('foobar.pdf')
    key.get_contents_to_filename('/home/luca/documents/foobar.pdf')

    public by lbottaro modified Sep 2, 2013  246962  2  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,))
        t.start()
        #Join all existing threads to main thread.
        for thread in threading.enumerate():
            if thread is not threading.currentThread():
              thread.join()
        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 modified Oct 6, 2014  253210  1  4  0

    Quick Python server

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

    public by DavidEGrayson modified Oct 20, 2015  350091  0  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 setup.py 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/setup.py';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/__init__.py", line 12, in <module>
            from setuptools.extension import Extension
          File "D:/msys64/mingw64/lib/python2.7/site-packages/setuptools/extension.py", line 9, in <module>
            from . import msvc9_support
          File "D:/msys64/mingw64/lib/python2.7/site-packages/setuptools/msvc9_support.py", line 2, in <module>
            import distutils.msvc9compiler
          File "D:/msys64/mingw64/lib/python2.7/distutils/msvc9compiler.py", 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/setup.py';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