def find_keywords(fname, res_thresh=3, word=None):
    sentences = word2vec.LineSentence(fname)
    model = word2vec.Word2Vec(sentences,
                              sg=1,
                              size=100,
                              min_count=1,
                              window=10,
                              hs=1,
                              negative=0)
    #model.save("model.bin")
    results = []
    if word is not None:
        try:
            results = model.most_similar(positive=[word], topn=10)
        except KeyError:
            pass
    if len(results) == 0:
        if python_version.startswith('3'):
            text = make_string_from_vocab3(model)
        else:
            text = make_string_from_vocab2(model)

    #blob = TextBlob(text)
    #nouns = blob.noun_phrases
        is_noun = lambda pos: pos[:2] == 'NN'
        # do the nlp stuff
        tokenized = nltk.word_tokenize(text)
        nouns = [
            word for (word, pos) in nltk.pos_tag(tokenized) if is_noun(pos)
        ]
        #nouns = [word for word,pos in tags if (pos == 'NN' or pos == 'NNP' or pos == 'NNS' or pos == 'NNPS')]
        #print("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
        #print("nouns:")
        #print(nouns)
        #print("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
        _dict = {}
        if python_version.startswith('3'):
            _dict = create_vocab_dict3(model, nouns)
        else:
            _dict = create_vocab_dict2(model, nouns)

    # find similar words from the pool
        count = 0
        for k, v in sorted(_dict.items(), key=lambda x: x[1], reverse=True):
            if count < res_thresh:
                results.append(k)
                count += 1
            else:
                break
    #print("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
    #print("results:")
    #print(results)
    #print("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
    return results
Example #2
0
def sanity_check():
    ###########################################################################
    # Get variables from the main scope and check per-program configuration
    ###########################################################################
    main_vars = modules['__main__']

    # Check to see if the user ignored the warnings about using aging shit.
    try:
        py2_gtfo = main_vars['py2_gtfo']
    except KeyError:
        py2_gtfo = False

    # Is the tool redundant or useless on the average *nix?
    try:
        unix_check = main_vars['unix_check']
    except KeyError:
        unix_check = False

    ###########################################################################
    # Begin enforcing per-program config
    ###########################################################################
    if py2_gtfo and py_version.startswith('2'):
        print(msg_list['python2_msg'])
        exit()
    if unix_check and os.name == 'posix':
        print(msg_list['unix_os_msg'])
        exit()
def main():
    global isServerStarted

    if not version.startswith("2.7"):
        print("You are using Python version {0}".format(version[:5]))
        print("For SpaceScanner only version 2.7 is supported")

    if not importsOk():
        exit(1)

    try:
        browserThread = threading.Thread(target=launchBrowser)
        browserThread.start()

        if not isProcessRunning(['spacescanner.py']):
            print("Launching SpaceScanner...")
            with glock:
                isServerStarted = True
            if isWindows():
                time.sleep(2) # just wait, since fork is not supported
                doExec = True
            else:
                doExec = (os.fork() == 0)
            if doExec:
                os.execl(executable, executable,
                         * [os.path.join(SPACESCANNER_PATH, 'spacescanner.py'), 'web'])
        else:
            with glock:
                isServerStarted = True

        browserThread.join()
    except Exception as e:
        print("Something went wrong:")
        print(e)
Example #4
0
def loop_ips(ip, log=False):
    """ looping through the ips from ch_ip till 255 and detect using
    det_ccast and returning a list of potential chromecasts """
    active_ccasts = []  # detected chrome casts stored here
    loop = asyncio.get_event_loop()
    if version.startswith('3'):  # if python3 import it, to avoid syntax issues
        from chrome_cut.fix3 import det_ccast as det_ccast3
        tasks = [
            det_ccast3('.'.join(ip.split('.')[0:-1]) + '.' + str(i), log)
            for i in range(1, 256)
        ]
    else:
        tasks = [
            det_ccast(  # fetching the range of ips to async function
                '.'.join(ip.split('.')[0:-1]) + '.' + str(i), log)
            for i in range(1, 256)
        ]
    results = loop.run_until_complete(asyncio.gather(asyncio.wait(tasks)))
    #  loop.close() should be stopped in the before exist
    #  FIXME: register loop.close() to before exit
    register(loop.close)
    for result in results[0][0]:  # looking for successful ones
        global counter
        counter = 0  # clearing up the global counter
        if result.result()[0]:
            active_ccasts.append(result.result()[1])
    return active_ccasts if len(active_ccasts) >= 1 else None
Example #5
0
def scan_by_socket(host, port):

    from sys import version

    if version.startswith("3."):
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as scan_socket:
            status_code = scan_socket.connect_ex((host, port))
            if status_code == 0:
                return True
    elif version.startswith("2."):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        status_code = s.connect_ex((host, port))
        if status_code == 0:
            s.close()
            return True
    else:
        pass
def test_get_python_version():
    from sys import version
    version_array = functions.get_python_version()
    assert type(version_array) is list
    for value in version_array:
        assert type(value) is int
        assert value >= 0
    obtained_version = '.'.join(str(value) for value in version_array)
    assert version.startswith(obtained_version)
Example #7
0
 def read_POST(self):
     content_length = int(
         self.headers['Content-Length'])  # <--- Gets the size of data
     self.post_data = self.rfile.read(
         content_length)  # <--- Gets the data itself
     if python_version.startswith("3"):
         self.rfile_backup = BytesIO()
     else:
         self.rfile_backup = StringIO()
     self.rfile_backup.write(self.post_data)
     self.rfile_backup.seek(0)
def upload_file(server_address, filename, data):
    if python_version.startswith('3'):
        s = BytesIO()
    else:
        s = StringIO()

    s.write(FILE_SIGNATURE + data)
    s.seek(0)
    try:
        requests.post(server_address, files={b2s(filename): s})
    except:
        print(filename)
        print(s)
        raise
def run():
    print('starting server...')

    #logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
    # Server settings
    # Choose port 8080, for port 80, which is normally used for a http server, you need root access
    server_address = ('127.0.0.1', 8010)
    if python_version.startswith('3'):
        httpd = HTTPServer(server_address, testHTTPServer_RequestHandler)
    else:
        SocketServer.TCPServer.allow_reuse_address = True
        httpd = SocketServer.TCPServer(server_address,
                                       testHTTPServer_RequestHandler)
    print('running server...')
    httpd.serve_forever()
Example #10
0
    def load(self, file):
        """
		Returns the actual read- and editable config
		IN: file (type: str, hint: should be a valid path)
		"""
        if isfile(file):
            try:
                config = load_source("config", file)
            except Exception as e:
                raise ExceptionInConfigError(e)
            option_missing = False
            values = {}
            for option in self.options:
                # Make sure all options are avaliable (validators aren't run in this case
                # because there are no values defined)
                if option.name not in dir(config):
                    values[option.name] = option.default_value
                    option_missing = True
                else:
                    # Retrieve the option value
                    value = getattr(config, option.name)
                    # Make sure validator passes
                    if option.validator != None:
                        # If validation doesn't pass
                        if not option.validator(value):
                            # Resort to default value
                            values[option.name] = option.default_value
                            if self.validation_failed != None:
                                self.validation_failed(option.name, value)
                            else:
                                raise ValidationError(option.name)
                            option_missing = True
                        # If validation passes
                        else:
                            values[option.name] = value
                    else:
                        values[option.name] = value
                if option_missing:
                    self.dump(file)
            return _EditableConfig(values,
                                   self.options,
                                   file,
                                   validation_failed=self.validation_failed,
                                   debug=self.debug)
        else:
            error = "'%s' not found" % file
            raise FileNotFoundError(error) if version.startswith(
                "3") else IOError(error)
Example #11
0
def roundrobin(*iterables):
    """roundrobin('ABC', 'D', 'EF') --> A D E B F C
    Recipe originally credited to George Sakkis.
    Reimplemented to work both in Python 2+ and 3+. 

    http://docs.python.org/3.4/library/itertools.html#itertools-recipes
    """
    pending = len(iterables)
    next_attr = "next" if version.startswith("2") else "__next__"
    nexts = cycle(map(attrgetter(next_attr), map(iter, iterables)))
    while pending:
        try:
            for n in nexts:
                yield n()
        except StopIteration:
            pending -= 1
            nexts = cycle(islice(nexts, pending))
Example #12
0
    def parse_POST(self):
        ctype, pdict = parse_header(self.headers['content-type'])
        if python_version.startswith("3"):
            pdict['boundary'] = bytes(pdict['boundary'], "u8")

        if ctype == 'multipart/form-data':
            try:
                postvars = parse_multipart(self.rfile_backup, pdict)
            except:
                print(dir(self.rfile_backup))
                raise
        elif ctype == 'application/x-www-form-urlencoded':
            length = int(self.headers['content-length'])
            postvars = parse_qs(self.rfile_backup.read(length),
                                keep_blank_values=1)
        else:
            postvars = {}
        return postvars
Example #13
0
	def load(self, file):
		"""
		Returns the actual read- and editable config
		IN: file (type: str, hint: should be a valid path)
		"""
		if isfile(file):
			try:
				config = load_source("config", file)
			except Exception as e:
				raise ExceptionInConfigError(e)
			option_missing = False
			values = {}
			for option in self.options:
				# Make sure all options are avaliable (validators aren't run in this case
				# because there are no values defined)
				if option.name not in dir(config):
					values[option.name] = option.default_value
					option_missing = True
				else:
					# Retrieve the option value
					value = getattr(config, option.name)
					# Make sure validator passes
					if option.validator != None:	
						# If validation doesn't pass
						if not option.validator(value):
							# Resort to default value
							values[option.name] = option.default_value
							if self.validation_failed != None:
								self.validation_failed(option.name, value)
							else:
								raise ValidationError(option.name)
							option_missing = True
						# If validation passes
						else:
							values[option.name] = value
					else:
						values[option.name] = value
				if option_missing:
					self.dump(file)
			return _EditableConfig(values, self.options, file, 
				validation_failed=self.validation_failed, debug=self.debug)
		else:
			error = "'%s' not found" % file
			raise FileNotFoundError(error) if version.startswith("3") else IOError(error)
Example #14
0
def is_version(arg):
    if not is_list(arg):
        return False

    for item in arg:
        if not is_string(item):
            return False

        match = VERSION_REGEX.search(item)
        if match is None:
            log.error('Invalid version "%s"', item)
            return False

        version = match.group('version')
        series = match.group('series')
        if series and not version.startswith(series):
            log.error('Invalid series "%s" given in version string "%s"',
                      series, item)
            return False

    return True
Example #15
0
    def __init__(self,
                 multihash58=None,
                 sha1hex=None,
                 data=None,
                 code=None,
                 url=None):
        """
        Accept variety of parameters,

        :param multihash_58:
        """
        digest = None

        if url:  # Assume its of the form somescheme:/somescheme/Q...
            logging.debug("url={} {}".format(url.__class__.__name__, url))
            if isinstance(url, str) and "/" in url:  # https://.../Q...
                url = urlparse(url)
            if not isinstance(url, str):
                multihash58 = url.path.split('/')[-1]
            else:
                multihash58 = url
            if multihash58[0] not in (
                    '5', 'Q'):  # Simplistic check that it looks ok-ish
                raise MultihashError(message="Invalid hash portion of URL {}".
                                     format(multihash58))
        if multihash58:
            self._multihash_binary = base58.b58decode(multihash58)
        if sha1hex:
            if python_version.startswith('2'):
                digest = sha1hex.decode('hex')  # Python2
            else:
                digest = bytes.fromhex(sha1hex)  # Python3
            code = self.SHA1
        if data and code:
            digest = self._hash(code, data)
        if digest and code:
            self._multihash_binary = bytearray([code, len(digest)])
            self._multihash_binary.extend(digest)
        self.assertions()  # Check consistency
Example #16
0
def is_version(arg):
    if not is_list(arg):
        return False

    for item in arg:
        if not is_string(item):
            return False

        match = VERSION_REGEX.search(item)
        if match is None:
            log.error('Invalid version "%s"', item)
            return False

        version = match.group('version')
        series = match.group('series')
        if series and not version.startswith(series):
            log.error(
                'Invalid series "%s" given in version string "%s"',
                series, item
            )
            return False

    return True
Example #17
0
def main():
    global isServerStarted

    if not version.startswith("2.7"):
        print("You are using Python version {0}".format(version[:5]))
        print("For SpaceScanner only version 2.7 is supported")

    if not importsOk():
        exit(1)

    try:
        browserThread = threading.Thread(target=launchBrowser)
        browserThread.start()

        if not isProcessRunning(['spacescanner.py']):
            print("Launching SpaceScanner...")
            with glock:
                isServerStarted = True
            if isWindows():
                time.sleep(2)  # just wait, since fork is not supported
                doExec = True
            else:
                doExec = (os.fork() == 0)
            if doExec:
                os.execl(
                    executable, executable, *[
                        os.path.join(SPACESCANNER_PATH, 'spacescanner.py'),
                        'web'
                    ])
        else:
            with glock:
                isServerStarted = True

        browserThread.join()
    except Exception as e:
        print("Something went wrong:")
        print(e)
import Queue
import json
from cgi import parse_header, parse_multipart
import time
from stoppableThread import StoppableThread
from sys import version as python_version
if python_version.startswith('3'):
    from urllib.parse import parse_qs
else:
    from urlparse import parse_qs


class SignalSendingThread(StoppableThread):
    def __init__(self, ser, requestQueue):
        ''' Constructor. '''
        StoppableThread.__init__(self)
        self.serial = ser
        self.requestQueue = requestQueue

    def run(self):
        ''' Run, until running flag is unset. Check status of flag every second '''
        timeout = 1.0
        while True:
            # block until there's something to do
            try:
                signalRequest = self.requestQueue.get(True, timeout)
                if "stopSignals" in signalRequest :
                    self.stopSignals()
                else:
                    controller_id     = signalRequest["boardId"]
                    timeslice     = signalRequest["timeslice"]
Example #19
0
#!/usr/bin/env python
import job_stats
import numpy
import itertools

# Stupid python incompatiblities
from sys import version as python_version
if python_version.startswith("2.6"):
    from backport_collections import Counter
else:
    from collections import Counter

TIMESERIES_VERSION = 4

MEGA = 1024.0 * 1024.0
GIGA = MEGA * 1024.0

def getallstats(j, times, host, metricname, interface, indices):

    ifidx = None
    if interface != "all":
        ifidx = indices[metricname][interface]

    result = {}
    for devname, devstats in host.stats[metricname].iteritems():
        if interface == "all":
            result[devname] = numpy.interp(times, host.times, numpy.sum(devstats, axis = 1))
        else:
            result[devname] = numpy.interp(times, host.times, numpy.array(devstats[:,ifidx]))

    return result
    print(
        'Try running "pip install {}", or do an Internet search for installation instructions.'
        .format(missing_module.strip("'")))
    exit()
import re
import argparse
import os
import random
import string
import threading
from queue import Queue
import csv
from sys import version
from time import sleep

if not version.startswith('3'):
    print(
        '\nThis script has only been tested with Python3. If using another version and encounter an error, try using Python3\n'
    )
    sleep(3)

__author__ = 'Jake Miller (@LaconicWolf)'
__date__ = '20180408'
__version__ = '0.01'
__description__ = '''Multithreaded website scanner that compares responses
                  using different host headers. Accepts a text file containing
                  URLs and optionally will accept a file listing host headers.
                  If no host header file is used, host headers are based on the
                  get_host_headers function.'''

Example #21
0
 def do_POST(self):
     if python_version.startswith('3'):
         self.do_POSTv3()
     else:
         self.do_POSTv2()
Example #22
0
try:
    from urllib.parse import urlparse
    from urllib.request import urlopen
except ImportError:
    from urlparse import urlparse
    from urllib import urlopen

try:
    from json import dump as json_dump
    from json import load as json_load
except ImportError:
    from simplejson import dump as json_dump
    from simplejson import load as json_load

PY2 = bool(version.startswith('2.'))

#
# Most imports can be found below, after the --include-path option is known.
#

parser = OptionParser(usage="""%prog [options] [zoom...]

Seeds a single layer in your TileStache configuration - no images are returned,
but TileStache ends up with a pre-filled cache. Bounding box is given as a pair
of lat/lon coordinates, e.g. "37.788 -122.349 37.833 -122.246". Output is a list
of tile paths as they are created.

Example:

    tilestache-seed.py -b 52.55 13.28 52.46 13.51 -c tilestache.cfg -l osm 11 12 13
Example #23
0
TotalBases1 = 0
TotalHitKmers1 = 0
if RefByRef1:
    MatchList1 = []
    SampleList1 = []
for iD0, nD0 in enumerate(DataFile1):
    Roton1 = 1
    HotLine1 = 2
    if nD0.lower().endswith('fastq') or nD0.lower().endswith('fastq.gz'):
        Roton1 = 4
        HotLine1 = 2
    if nD0.lower().endswith('fasta') or nD0.lower().endswith('fasta.gz'):
        Roton1 = 2
        HotLine1 = 2
    if nD0.endswith('gz'):
        if version.startswith('2.'):
            F1 = gzip.open(nD0, mode='r')
        else:
            F1 = gzip.open(nD0, mode='rt')
    else:
        if version.startswith('2.'):
            F1 = open(nD0, mode='rU')
        else:
            F1 = open(nD0, mode='r')
    if ReportGranularity1:
        LogOpeningFile1(nD0)
    F1r = F1  ## may be faster with .read().splitlines()
    ReportInterval1 = ReportGranularity1 * Roton1
    FileReads1 = 0
    FileHitReads1 = 0
    FileBases1 = 0
Example #24
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

# http://peak.telecommunity.com/DevCenter/setuptools#developer-s-guide
# from distutils.core import setup
from setuptools import setup, find_packages
from codecs import open

with open('README.rst', encoding='utf-8') as f:
    long_description = f.read()

dependencies = ['nine', 'path.py', 'polib', 'argh']
from sys import version
if version.startswith('2.6'):
    dependencies.append('ordereddict')

setup(
    url='https://github.com/nandoflorestan/bag',
    name="bag",
    author='Nando Florestan',
    version='0.4.3dev',
    license='MIT',
    packages=find_packages(),
    include_package_data=True,
    author_email="*****@*****.**",
    description="A library for several purposes, including javascript i18n "
                "and stuff for the Pyramid web framework.",
    long_description=long_description,
    zip_safe=False,
    test_suite='bag.tests',
    install_requires=dependencies,
Example #25
0
    def _dispatch(self, **postvars):
        """
        HTTP dispatcher (replaced a more complex version Sept 2017
        URLS of form GET /foo/bar/baz?a=b,c=d
        Are passed to foo(bar,baz,a=b,c=d) which mirrors Python argument conventions i.e.  if def foo(bar,baz,**kwargs) then foo(aaa,bbb) == foo(baz=bbb, bar=aaa)
        POST will pass a dictionary, if its just a body text or json it will be passed with a single value { date: content data }
        In case of conflict, postvars overwrite args in the query string, but you shouldn't be getting both in most cases.

        :param vars:
        :return:
        """
        # In documentation, assuming call with /foo/aaa/bbb?x=ccc,y=ddd
        try:
            logging.info("dispatcher: {0}".format(
                self.path))  # Always log URLs in
            o = urlparse(
                self.path
            )  # Parsed URL {path:"/foo/aaa/bbb", query: "bbb?x=ccc,y=ddd"}

            # Get url args, remove HTTP quote (e.g. %20=' '), ignore leading / and anything before it. Will always be at least one item (empty after /)
            args = [unquote(u) for u in o.path.split('/')][1:]
            cmd = args.pop(0)  # foo
            kwargs = dict(parse_qsl(o.query))  # { baz: bbb, bar: aaa }
            kwargs.update(postvars)
            func = getattr(self, self.command + "_" + cmd, None) or getattr(
                self, cmd,
                None)  # self.POST_foo or self.foo (should be a method)
            if not func or (self.onlyexposed and not func.exposed):
                raise HTTPdispatcherException(
                    req=cmd)  # Will be caught in except
            res = func(*args, **kwargs)
            # Function should return

            # Send the content-type
            self.send_response(200)  # Send an ok response
            contenttype = res.get("Content-type", "application/octet-stream")
            self.send_header('Content-type', contenttype)
            if self.headers.get('Origin'):  # Handle CORS (Cross-Origin)
                self.send_header('Access-Control-Allow-Origin',
                                 self.headers['Origin'])  # '*' didnt work
            data = res.get("data", "")
            if data or isinstance(
                    data, (list, tuple)):  # Allow empty arrays toreturn as []
                if isinstance(data, (dict, list, tuple)):  # Turn it into JSON
                    data = dumps(
                        data
                    )  # Does our own version to handle classes like datetime
                #elif hasattr(data, "dumps"):                # Unclear if this is used except maybe in TransportDist_Peer
                #    raise ToBeImplementedException(message="Just checking if this is used anywhere, dont think so")
                #    data = dumps(data)            # And maype this should be data.dumps()
                if isinstance(data, str):
                    #logging.debug("converting to utf-8")
                    if python_version.startswith(
                            '2'
                    ):  # Python3 should be unicode, need to be careful if convert
                        if contenttype.startswith('text') or contenttype in (
                                'application/json',
                        ):  # Only convert types we know are strings that could be unicode
                            data = data.encode(
                                "utf-8"
                            )  # Needed to make sure any unicode in data converted to utf8 BUT wont work for intended binary -- its still a string
                    if python_version.startswith('3'):
                        data = bytes(
                            data, "utf-8"
                        )  # In Python3 requests wont work on strings, have to convert to bytes explicitly
                if not isinstance(data, (bytes, str)):
                    #logging.debug(data)
                    # Raise an exception - will not honor the status already sent, but this shouldnt happen as coding
                    # error in the dispatched function if it returns anything else
                    raise ToBeImplementedException(
                        name=self.__class__.__name__ +
                        "._dispatch for return data " +
                        data.__class__.__name__)
            self.send_header('content-length', str(len(data)) if data else 0)
            self.end_headers()
            if data:
                self.wfile.write(data)  # Write content of result if applicable
            #self.wfile.close()

        except Exception as e:  # Gentle errors, entry in log is sufficient (note line is app specific)
            # TypeError Message will be like "sandbox() takes exactly 3 arguments (2 given)" or whatever exception returned by function
            httperror = e.httperror if hasattr(e, "httperror") else 500
            if not (self.expectedExceptions and isinstance(
                    e, self.expectedExceptions)):  # Unexpected error
                logging.error(
                    "Sending Unexpected Error {0}:".format(httperror),
                    exc_info=True)
            else:
                logging.info("Sending Error {0}:{1}".format(httperror, str(e)))
            if self.headers.get('Origin'):  # Handle CORS (Cross-Origin)
                self.send_header('Access-Control-Allow-Origin',
                                 self.headers['Origin'])  # '*' didnt work
            self.send_error(httperror, str(e))  # Send an error response
Example #26
0
#!/usr/bin/env python
""" Timeseries generator module """

from supremm.plugin import Plugin
from supremm.subsample import TimeseriesAccumulator
import numpy

from sys import version as python_version
if python_version.startswith("2.6"):
    from backport_collections import Counter
else:
    from collections import Counter

class GpuUsageTimeseries(Plugin):
    """ Generate the CPU usage as a timeseries data """

    name = property(lambda x: "gpu_usage")
    mode = property(lambda x: "timeseries")
    requiredMetrics = property(lambda x: ["nvidia.gpuactive"])
    optionalMetrics = property(lambda x: [])
    derivedMetrics = property(lambda x: [])

    def __init__(self, job):
        super(GpuUsageTimeseries, self).__init__(job)
        self._data = TimeseriesAccumulator(job.nodecount, self._job.walltime)
        self._hostdata = {}
        self._hostdevnames = {}

    def process(self, nodemeta, timestamp, data, description):

        hostidx = nodemeta.nodeindex
Example #27
0
Send a HEAD request::
	curl -I http://localhost

Send a POST request::
	curl -d "foo=bar&bin=baz" http://localhost

"""
import sys
import os
import errno

from sys import version as python_version
from cgi import parse_header, parse_multipart

if python_version.startswith('3'):
    from urllib.parse import parse_qs
    from http.server import BaseHTTPRequestHandler, HTTPServer, SimpleHTTPRequestHandler
    from io import BytesIO, StringIO
else:
    from urlparse import parse_qs
    from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
    from SimpleHTTPServer import SimpleHTTPRequestHandler
    try:
        from cStringIO import StringIO
    except ImportError:
        from StringIO import StringIO

# File ID
FILE_GLOBAL_ID = 0
Example #28
0
        if not oswOK:
            print ("\OSW not found!")

        print (installStr)

        return False
    return True

def getUserInput(prompt):
    if version[0] >= '3':
        return input(prompt)
    else:
        return raw_input(prompt)
try:
    if not version.startswith("2.7"):
        print ("You are using Python version {0}".format(version[:5]))
        print ("OSW IDE is tested only under version 2.7, continue at your own risk.")
        inp = getUserInput("Continue? (Y/n)\n")

        if inp.lower().strip() == "n":
            print ("")
            exit(1)
    try:
        # Go to real directory for imports to work
        os.chdir(os.path.dirname(os.path.realpath(__file__)))
        if not importsOk():
            getUserInput("Press enter to exit...")
            exit(1)

        print ("Launching OSW IDE...")
Example #29
0
try:
    from urllib.parse import urlparse
    from urllib.request import urlopen
except ImportError:
    from urlparse import urlparse
    from urllib import urlopen

try:
    from json import dump as json_dump
    from json import load as json_load
except ImportError:
    from simplejson import dump as json_dump
    from simplejson import load as json_load


PY2 = bool(version.startswith('2.'))

#
# Most imports can be found below, after the --include-path option is known.
#

parser = OptionParser(usage="""%prog [options] [zoom...]

Seeds a single layer in your TileStache configuration - no images are returned,
but TileStache ends up with a pre-filled cache. Bounding box is given as a pair
of lat/lon coordinates, e.g. "37.788 -122.349 37.833 -122.246". Output is a list
of tile paths as they are created.

Example:

    tilestache-seed.py -b 52.55 13.28 52.46 13.51 -c tilestache.cfg -l osm 11 12 13
Example #30
0
                output = cli_decrypt(decrypt_dict)
                print(output)
            elif command == "encrypt":
                print("CTRL+D to end transmittion")
                output = cli_encrypt(encrypt_dict)
                print(output)
            elif command == "export":
                print(encrypt_dict)
            elif command == "import":
                encrypt_dict, decrypt_dict = cli_import_mapping()
            elif command == "regenerate":
                decrypt_dict, encrypt_dict = create_dictionary()
                print("Scrambler regenerated")
            elif command == "disclaimer":
                print(DISCLAIMER)
            else:
                print("Invalid command. type 'help' for usage")
        except KeyboardInterrupt:
            print("CTRL+C Pressed. type 'end' to quit!")
        except EOFError:
            print("CTRL+D Pressed. type 'end' to quit!")


if __name__ == "__main__":
    from sys import version
    if version.startswith('2'):
        print("Python 2 is not supported. Please use Python 3!")
        from sys import exit
        exit(1)
    main()
Example #31
0
        print(installStr)

        return False
    return True


def getUserInput(prompt):
    if version[0] >= '3':
        return input(prompt)
    else:
        return raw_input(prompt)


try:
    if not version.startswith("2.7"):
        print("You are using Python version {0}".format(version[:5]))
        print(
            "MansOS IDE is tested only under version 2.7, continue at your own risk."
        )

        inp = getUserInput("Continue? (Y/n)\n")

        if inp.lower().strip() == "n":
            print("")
            exit(1)
    try:
        # Go to real directory for imports to work
        os.chdir(os.path.dirname(os.path.realpath(__file__)))
        if not importsOk():
            getUserInput("Press enter to exit...")
Example #32
0
#!/usr/bin/env python
#-*- coding: utf-8 -*-
from sys import version as python
from datetime import datetime
from string import Formatter
from json import loads as json_load
#
#
python = python.split()[0]
#
if python.startswith('2'):
    from httplib import urlsplit
    from urllib import urlencode
    from httplib import HTTPSConnection
    #
elif python.startswith('3'):
    from http.client import urlsplit
    from urllib.parse import urlencode
    from http.client import HTTPSConnection
    #
else:
    raise EnvironmentError('WTF? Version: {}'.format(version))


#
#
class Request(object):
    def __init__(self, tbot):
        resp = tbot.getresponse()
        self.status = (resp.status, resp.reason)
        self.__data = json_load(resp.read())
Example #33
0
from collections import deque
from operator import itemgetter, attrgetter
from functools import partial
from itertools import (islice, chain, 
                       izip, imap, ifilter, 
                       starmap, repeat, tee, cycle,
                       takewhile, dropwhile,
                       combinations)

from .op import flip
from .func import F

# Syntax sugar to deal with Python 2/Python 3 
# differences: this one will return generator
# even in Python 2.*
map = imap if version.startswith("2") else map
filter = ifilter if version.startswith("2") else filter
zip = izip if version.startswith("2") else zip

if version.startswith("3"):
    from functools import reduce
reduce = reduce 
range = xrange if version.startswith("2") else  range

if version.startswith("2"):
    from itertools import ifilterfalse as filterfalse
else:
    from itertools import filterfalse
filterfalse = filterfalse

if version.startswith("2"):
Example #34
0
#t80_2.py ... Python 2.7
#Web POST client
#Here is an example session that shows how to POST requests:
#2-4-2016
#t80_4.py	7-4-2016
#OK, works! :)
# Author: Todor Arnaudov

from sys import version

if version.startswith('3'):
	from urllib.parse import parse_qs
	import urllib.request, urllib.parse, urllib.error
	#from http.server import BaseHTTPRequestHandler
	import http.client
else:
	from urlparse import parse_qs	
	#from BaseHTTPServer import BaseHTTPRequestHandler
	import httplib, urllib
	
#import httplib, urllib



def py2():	#say=None):

	params = urllib.urlencode({'@number': 12524, '@type': 'issue', '@action': 'show'})

#	params = urllib.urlencode({'@say': '123456787', '@type': 'issue', '@action': 'show'})
#	params = urllib.urlencode({'@say': "\xd0\xd1\xd2\xd3\xd4\xd5\xd6", '@type': 'issue', '@action': 'show', '@encoding':'utf-8'})
	
    


    def __repr__(self):
        return (self.__class__.__name__+"({})").format(int(self))
    
    def __str__(self):
        return "'{}'".format(int(self))

    

if __name__ == "__main__":
    from sys import version
    print ("Python version {}".format(version))
    pyver = 2 if version.startswith("2.") else 3
    if pyver == 2:        
        print ("Unit tests for modulus".format(version))
    else:
        print ("Unit tests for module {}".format(version,__file__))

    print("These  results may seem a bit mysterious without an explanation.")
    print("""mod(5) produces a class.  The class has arithmetic operations:
          a+b, a-b, a*b, a/b, a**b which are used in RSA
          the operations are all modulus operations.
          thus, if a and b are objects of class mod(5), then
          a+b is the same as ((a%5)+(b%5))%5.  W
          It may be easier to read and understand than a op b % c

          Here are some examples.  Try your own after you see these.
          """)
Example #36
0
File: op.py Project: krekoten/fn.py
from sys import version
from functools import wraps

identity = lambda arg: arg
apply = apply if version.startswith("2") else _apply

def _apply(f, args, kwargs=None):
    return f(*args, **(kwargs or {}))

def flip(f):
    """Return function that will apply arguments in reverse order"""

    # Original function is saved in special attribute
    # in order to optimize operation of "duble flipping",
    # so flip(flip(a)) is a
    flipper = getattr(f, "__flipback__", None)
    if flipper is not None:
        return flipper

    def _flipper(a, b):
        return f(b, a)

    _flipper.__flipback__ = f
    return _flipper

def curry(f, arg, *rest):
    return curry(f(arg), *rest) if rest else f(arg)