def __init__(self):
     self.serial = serial.Serial(
         port    =config()['port'],\
         baudrate=config()['baudrate'],\
         parity  =serial.PARITY_NONE,\
         stopbits=serial.STOPBITS_ONE,\
         bytesize=serial.EIGHTBITS,\
         timeout =config()['timeout']
     )
Example #2
0
    def backup(self,backup_location=None):
        # If they just called backup(), then use the path specified in the config
        if not backup_location:
            backup_location = settings.config()["Storage"]["backup directory"]
        # If backup_location is still undefined, then we have no idea where to do the backup, so
        # we just return after printing a message
        if not backup_location:
            ice_logger.log("No backup location specified. Not creating backup file.")
            return None

        # If the shortcuts file is undefined, print an error and return
        if not self.shortcuts_file:
            print "SteamShortcutManager Backup Error: No file specified"
            return None

        # Get the user id using the location of the shortcuts file and create a directory
        # in the backup location using the same directory structure Steam uses
        user_id = os.path.split(os.path.dirname(os.path.dirname(self.shortcuts_file)))[1]
        new_dir = os.path.expanduser(os.path.join(os.path.join(backup_location,user_id),"config"))
        try:  # Handle possible race condition
            os.makedirs(new_dir)
        except OSError:
            if not os.path.isdir(new_dir):
                raise

        backup_file_name = "shortcuts." + datetime.now().strftime('%Y%m%d%H%M%S') + ".vdf"
        open(os.path.join(new_dir,backup_file_name),"w").write(open(self.shortcuts_file,"r").read())
Example #3
0
 def should_download_images():
     try:
         should_download = settings.config()["Grid Images"]["source"] != ""
         return should_download
     except KeyError:
         log_both("Could not find '[Grid Images] Source' in config.txt.")
         return False
def create_app():
    app = Flask(__name__, instance_relative_config=True)
    env = os.environ.get("FLASK_ENV")
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass
    else:
        with open(app.instance_path + "/application.cfg", "w") as conf:
            from config import DevelopmentConfig
            line = '{}="{}"\n'
            for key, value in DevelopmentConfig.fields().items():
                if isinstance(value, (bool, int)):
                    conf.write('{}={}\n'.format(key, value))
                else:
                    conf.write(line.format(key, value))
            conf.writelines([
                line.format(key, value)
                for key, value in DevelopmentConfig.fields().items()
            ])
    if env:
        app.config.from_object(config(env))
    else:
        app.config.from_pyfile("application.cfg")
    db.init_app(app)
    app.register_blueprint(user)
    return app
Example #5
0
def save_user_to_postgresql(user_name, sex, age, weight, work):
    """
    save user data to postgresql
    """
    connection = config()
    cursor = connection.cursor()
    try:
        postgres_insert_users = """
        INSERT INTO users
        (username, sex, age, weight, work)
        VALUES (%s, %s, %s, %s, %s)"""
        records_to_users = (user_name, sex, age, weight, work)
        cursor.execute(postgres_insert_users, records_to_users)

    except psycopg2.errors.UniqueViolation:
        connection.rollback()

        postgres_insert_users = """
        UPDATE users SET
        sex=%s, age=%s, weight=%s, work=%s WHERE username=%s
        """
        records_to_users = (sex, age, weight, work, user_name)
        cursor.execute(postgres_insert_users, records_to_users)

    finally:
        cursor.close()
        connection.commit()
        connection.close()
Example #6
0
def save_pressure_to_postgresql(username,
                                systolic,
                                diastolic,
                                timestamp,
                                arm,
                                pulse=None):
    """
    save username(unique), systolic, diastolic, timestamp, date, arm
    """
    connection = config()
    cursor = connection.cursor()
    try:
        postgres_insert_users = """INSERT INTO users (username) VALUES (%s)"""
        record_to_users = username
        cursor.execute(postgres_insert_users, [record_to_users])
    except psycopg2.errors.UniqueViolation:
        connection.rollback()

    finally:
        postgres_insert_pressure = """
        INSERT INTO pressure (
            username, systolic, diastolic, timestamp, arm, pulse
            )
        VALUES (%s, %s, %s, %s, %s, %s)
        """
        records_to_pressure = (username, systolic, diastolic, timestamp, arm,
                               pulse)

        cursor.execute(postgres_insert_pressure, records_to_pressure)
        cursor.close()
        connection.commit()
        connection.close()
Example #7
0
def roms_directory():
    """
    Returns the path to the ROMs directory, as specified by config.txt.
    """
    path = os.path.expanduser(settings.config()['Storage']['roms directory'])
    if not os.access(path, os.W_OK):
        path = os.path.join(os.path.expanduser('~'),'ROMs')
    return path
Example #8
0
def roms_directory():
    """
    Returns the path to the ROMs directory, as specified by config.txt.
    """
    path = os.path.expanduser(settings.config()["Storage"]["roms directory"])
    if not os.access(path, os.W_OK):
        path = os.path.join(os.path.expanduser("~"), "ROMs")
    return path
Example #9
0
def roms_directory():
    """
    Returns the path to the ROMs directory, as specified by config.txt.
    """
    path = os.path.expanduser(settings.config()['Storage']['roms directory'])
    if not os.access(path, os.W_OK):
        path = os.path.expanduser("~")
    return os.path.join(path, "ROMs")
Example #10
0
def roms_directory():
    """
    Returns the path to the ROMs directory, as specified by config.txt.
    """
    path = os.path.expanduser(settings.config()['Storage']['roms directory'])
    if path == "":
        path = os.path.join(os.path.expanduser("~"), "ROMs")
    if not available_to_use(path, create_if_needed=True):
        fix_instructions = "Ice does not have permission to write to your ROMs Directory, %s. Please choose a different folder or change your permissions." % path
        raise ConfigError("Storage", "ROMs Directory", fix_instructions)
    return path
Example #11
0
def roms_directory():
    """
    Returns the path to the ROMs directory, as specified by config.txt.
    """
    path = os.path.expanduser(settings.config()['Storage']['roms directory'])
    if path == "":
        path = os.path.join(os.path.expanduser("~"), "ROMs")
    if os.path.exists(path) and not os.access(path, os.W_OK):
        fix_instructions = "Ice does not have permission to write to your ROMs Directory, %s. Please choose a different folder or change your permissions." % path
        raise ConfigError("Storage","ROMs Directory", fix_instructions)
    return path
Example #12
0
def roms_directory():
    """
    Returns the path to the ROMs directory, as specified by config.txt.
    """
    path = os.path.expanduser(settings.config()['Storage']['roms directory'])
    if path == "":
        path = os.path.join(os.path.expanduser("~"), "ROMs")
    if not available_to_use(path, create_if_needed=True):
        fix_instructions = "Ice does not have permission to write to your ROMs Directory, %s. Please choose a different folder or change your permissions." % path
        raise ConfigError("Storage","ROMs Directory", fix_instructions)
    return path
def create_tables():
    """
    create 2 tables:
    users: - username, sex, age, weight, work
    pressure: pressure_id, username, systolic, diastoic,
    timestamp, date, arm, foreign key to users
    """

    tables = (
        """
        CREATE TABLE IF NOT EXISTS users (
          username VARCHAR(50) PRIMARY KEY NOT NULL,
          sex VARCHAR(20),
          age VARCHAR(15),
          weight VARCHAR(15),
          work VARCHAR(15)
        );
        """,

        """
        CREATE TABLE IF NOT EXISTS pressure(
            pressure_id SERIAL PRIMARY KEY,
            username VARCHAR(50),
            systolic VARCHAR(3) NOT NULL,
            diastolic VARCHAR(3) NOT NULL,
            timestamp timestamptz NOT NULL,
            arm VARCHAR(50) NOT NULL,
            pulse VARCHAR(3),
            FOREIGN KEY (username) REFERENCES users
        );
        """
        )
    try:
        connection = config()
        cursor = connection.cursor()

        for table in tables:
            cursor.execute(table)

        cursor.close()
        connection.commit()

    except (Exception, psycopg2.DatabaseError) as error:
        print(error)

    finally:
        if connection is not None:
            connection.close()
Example #14
0
def get(endpoint):
    """
    GET a json payload from the photostreamer-server
    """
    cfg = settings.config()
    url = cfg.get('server', 'url') + endpoint
    try:
        r = requests.get(url)
        if r.status_code == 200:
            l.debug("photostreamer-server endpoint %s responded with %s", endpoint, r.json())
            return r.json()
        else:
            l.error("Received HTTP status code %d while trying to reach %s.",
                r.status_code, url)
            return False
    except requests.ConnectionError:
        l.error("Network error trying to GET %s.", url)
        return False
Example #15
0
def select_data_from_postgresql(user, first_date, last_date):
    """
    select data for the user and time period
    """
    connection = config()
    cursor = connection.cursor()
    postgreSQL_select_query = """
            SELECT * FROM pressure WHERE username = %s
            AND timestamp >= %s AND timestamp <= %s;
        """
    details = [user, first_date, last_date]
    cursor.execute(postgreSQL_select_query, details)

    pressure_data = cursor.fetchall()
    cursor.close()
    connection.close()

    return pressure_data
Example #16
0
def lookup_emulator(platform,console):
    emulators_key = platform + ' Emulators' # ex: "Windows Emulators"
    console_key = console.shortname.lower()
    try:
        user_supplied_name = settings.config()[emulators_key][console_key]
        if not user_supplied_name:
            log_file("No user supplied name for %s" % console.shortname)
            return None
        name = emulator_platform_prefix(platform) + user_supplied_name
        return emulator_from_name(name)(console.shortname)
    except KeyError as e:
        # TODO(#28) Throw a ConfigError once it will be caught...
        log_file("Configuration missing key for %s on %s" % (console.shortname, platform))
        return None
    except AttributeError as e:
        # TODO(#28) Throw a ConfigError once it will be caught...
        log_user("Cannot load emulator for %s. Check that your spelling is correct, and that the emulator you request is supported" % console.shortname)
        log_file("Error loading [%s] %s" % (emulator_key, console_key))
        return None
Example #17
0
def lookup_emulator(platform,console):
    emulators_key = platform + ' Emulators' # ex: "Windows Emulators"
    console_key = console.shortname.lower()

    try:
        user_supplied_name = settings.config()[emulators_key][console_key]
    except KeyError as e:
        log_file("Configuration missing key for %s on %s" % (console.shortname, platform))
        return None

    if not user_supplied_name:
        log_file("No user supplied name for %s" % console.shortname)
        return None

    name = emulator_platform_prefix(platform) + user_supplied_name
    try:
        return emulator_from_name(name)(console.shortname)
    except (KeyError, AttributeError) as e:
        message = "Could not load emulator. Check your spelling, and make sure the emulator is supported for your console"
        raise ConfigError(emulators_key, console.shortname, message)
Example #18
0
def base_environment(environment=""):
    """ Base environment for all environments """
    _env.environment = environment.lower()
    environment = environment.upper()
    application_name = config(environment + "_APPLICATION_NAME", '') or \
        config("APPLICATION_NAME", '')

    _env.host = config(environment + "_SERVER_HOST", '')
    _env.user = config(environment + "_OS_USER", 'root')
    _env.environment_variables = config(
        environment + '_ENVIRONMENT_VARIABLES', '')
    _env.dokku_command = "ssh dokku@" + \
        config(environment + "_SERVER_HOST", '')
    _env.app_name_dokku = application_name

    print("Connecting to %s..." % environment.lower())
Example #19
0
def connect():
    """
    Return a connected S3 bucket based on settings in
    config.cfg.
    """
    # Reduce the number of retries to 1 if it's not set already so requests
    # fail quickly rather than delaying the downloading of photos
    if not boto.config.has_option('Boto', 'num_retries'):
        if not boto.config.has_section('Boto'):
            boto.config.add_section('Boto')
            boto.config.set('Boto', 'num_retries', '1')
    cfg = settings.config()
    try:
        aws_access_key = cfg.get('s3', 'access_key')
        aws_secret_key = cfg.get('s3', 'secret_key')
        aws_s3_bucket = cfg.get('s3', 'bucket')
    except NoOptionError as e:
        l.error("Error reading a setting from the config.cfg file: %s", e)
        raise
    conn = S3Connection(aws_access_key, aws_secret_key)
    bucket = conn.get_bucket(aws_s3_bucket, validate=False)
    return bucket
Example #20
0
def lookup_emulator(platform, console):
    emulators_key = platform + ' Emulators'  # ex: "Windows Emulators"
    console_key = console.shortname.lower()
    try:
        user_supplied_name = settings.config()[emulators_key][console_key]
        if not user_supplied_name:
            log_file("No user supplied name for %s" % console.shortname)
            return None
        name = emulator_platform_prefix(platform) + user_supplied_name
        return emulator_from_name(name)(console.shortname)
    except KeyError as e:
        # TODO(#28) Throw a ConfigError once it will be caught...
        log_file("Configuration missing key for %s on %s" %
                 (console.shortname, platform))
        return None
    except AttributeError as e:
        # TODO(#28) Throw a ConfigError once it will be caught...
        log_user(
            "Cannot load emulator for %s. Check that your spelling is correct, and that the emulator you request is supported"
            % console.shortname)
        log_file("Error loading [%s] %s" % (emulator_key, console_key))
        return None
Example #21
0
def connect():
    """
    Return a connected S3 bucket based on settings in
    config.cfg.
    """
    # Reduce the number of retries to 1 if it's not set already so requests
    # fail quickly rather than delaying the downloading of photos
    if not boto.config.has_option('Boto', 'num_retries'):
        if not boto.config.has_section('Boto'):
            boto.config.add_section('Boto')
            boto.config.set('Boto', 'num_retries', '1')
    cfg = settings.config()
    try:
        aws_access_key = cfg.get('s3', 'access_key')
        aws_secret_key = cfg.get('s3', 'secret_key')
        aws_s3_bucket = cfg.get('s3', 'bucket')
    except NoOptionError as e:
        l.error("Error reading a setting from the config.cfg file: %s", e)
        raise
    conn = S3Connection(aws_access_key, aws_secret_key)
    bucket = conn.get_bucket(aws_s3_bucket, validate=False)
    return bucket
Example #22
0
def post(endpoint, payload, resend=False):
    """
    POST a json payload to the photostreamer-server
    """
    cfg = settings.config()
    url = cfg.get('server', 'url') + endpoint
    try:
        r = requests.post(url, 
            data=json.dumps(payload), headers={'content-type':'application/json'})
        if r.status_code == 200:
            l.debug("POSTed %s to photostreamer-server endpoint %s.", payload, endpoint)
            return True
        else:
            l.error("Received HTTP status code %d while POSTing to %s.",
                r.status_code, url)
            if resend == False:
                post_later(endpoint, payload)
            return False
    except requests.ConnectionError:
        l.exception("Network error trying to POST to %s.", url)
        if resend == False:
            post_later(endpoint, payload)
        return False
    @properness_tests.add_method
    def is_proper_position(self, circle):
        """
        Test if the scale is in the correct position.

        @param Circle circle: the inscribed circle of clock face
        @return True for locates in correct position
        """
        return circle.is_in_sector(self.center, self._sector_no) and \
               (type(self)._MIN_FIT_POINTS <= \
                       reduce(lambda points_no, nxt: points_no + \
               circle.is_in_sector(tuple(nxt), self._sector_no),
                                   [ 0 ] + self.box_points.tolist()))

config(ScaleElement)


import unittest


class TestScaleElement(unittest.TestCase):
    """
    Test ScaleElement class.
    """
    def test_is_proper_position(self):
        self.assertIsNotNone(ScaleElement.is_proper_position.__doc__)


if __name__ == '__main__':
    # run unittest TestScaleElement
Example #24
0
# XXX: This file is not being used!
#
# It was left here because someday we might add the preferences window back.

import gtk
import logging
from settings import config

logger = logging.getLogger("batterymon")
settings = config()


class prefs:
    def destroy(self,widget):
        self.pref_win.hide()

    def Radio_Call_Back(self,widget,data=None):
        test = (("OFF","ON")[widget.get_active()])
        Toggled = data +" " + test
        if Toggled == "Always_show ON":
            logger.debug("DEBUG Always show an icon")
            settings.write_settings_int("show_icon","1")
            return
        elif Toggled == "show_charging_discharging ON":
            logger.debug("DEBUG only show when battery is charging or discharing")
            settings.write_settings_int("show_icon","3")
            return
        elif Toggled == "Show_discharging_only ON":
            logger.debug("DEBUG Show an icon when discharging")
            settings.write_settings_int("show_icon","2")
            return
def config_userdata_location():
    return os.path.expanduser(settings.config()["Steam"]["userdata directory"])
Example #26
0
# encoding: utf-8
import requests
import json
import Cookie,os
#import settings as set
from settings import config

cfg = config()

#ws = set.Wsh()


class Product(object):
    baseurl = cfg.URL
    proxylist = cfg.PROXY
    headers = cfg.HEADERS
    headers_json = cfg.HEADERS_JSON

    ######### 商品 ##########
    def get_product_list(self,sessionid):

        print u"---Test 获取商品列表---"
        url = self.baseurl+"/product/list-ajax"
        #url = "http://betanewwsh.vikduo.com/reduction/list-ajax"
        headers = self.headers
        cookies = {'PHPSESSID': sessionid}

        r = requests.post(url, headers=headers,cookies=cookies)
        print "Headers:", r.headers
        print "Response:", r.content
        return r
        @return list sorted elements
        """
        # zip the element list with their angles to the center of the circle
        sorted_element_angles = sorted(map(lambda e: (e, np.arctan2(
                                *np.subtract(e.center, center))), elements),
                                key=lambda e_ag: e_ag[1], reverse=True)

        # sort and return the element list
        return list(map(lambda e_ag: e_ag[0],
               list(filter(lambda e_ag: e_ag[1] >= type(self)._START_RAD,
                           sorted_element_angles)) +
               sorted(filter(lambda e_ag: e_ag[1] < type(self)._START_RAD,
                             sorted_element_angles), key=lambda e_ag: e_ag[1],
                      reverse=True)))

config(ScaleImageMixin)


import unittest


class TestScaleImageMixin(unittest.TestCase):
    """
    Test ScaleImageMixin class.
    """
    def test_elements(self):
        """
        Test lazy property elements.
        """
        self.assertIsNotNone(ScaleImageMixin.elements.__doc__)
Example #28
0
#!/usr/bin/env python
import os
import time
from PIL import Image
from ConfigParser import NoOptionError

import s3
import server
import settings
import db
import logger
l = logger.setup('hook')
cfg = settings.config()

sender = 0


def generate_key(fileName):
    """
    Generate a unique filename based on the current timestamp.
    """
    timestamp = str(time.time()).replace(".", "")
    file_extension = fileName.split(".")[1]
    return timestamp + "." + file_extension


def generate_thumb(src, dest):
    """
    Create a thumbnail of the file using Pillow and return
    the path to the created thumbnail.
    """
Example #29
0
# XXX: This file is not being used!
#
# It was left here because someday we might add the preferences window back.

import gtk
import logging
from settings import config

logger = logging.getLogger("batterymon")
settings = config()


class prefs:
    def destroy(self, widget):
        self.pref_win.hide()

    def Radio_Call_Back(self, widget, data=None):
        test = (("OFF", "ON")[widget.get_active()])
        Toggled = data + " " + test
        if Toggled == "Always_show ON":
            logger.debug("DEBUG Always show an icon")
            settings.write_settings_int("show_icon", "1")
            return
        elif Toggled == "show_charging_discharging ON":
            logger.debug(
                "DEBUG only show when battery is charging or discharing")
            settings.write_settings_int("show_icon", "3")
            return
        elif Toggled == "Show_discharging_only ON":
            logger.debug("DEBUG Show an icon when discharging")
            settings.write_settings_int("show_icon", "2")
Example #30
0
        Use pointPolygonTest to see if the given point is inside the specified
        sector (one of the sectors).

        @param tuple point: a given point
               int sector_no: which sector (clockwise order, 0 ~ 11)
                              find all sectors if not specified
        @return True if the point is in the sector (one of the sectors)
        """
        if sector_no < 0:
            return reduce(lambda result, sector: result or \
                                cv.pointPolygonTest(sector, point, False) > 0,
                          [ False ] + self.sectors)
        return cv.pointPolygonTest(self.sectors[sector_no], point, False) > 0


config(Circle)

import unittest


class TestCircle(unittest.TestCase):
    """
    Test Circle class.
    """
    # create a test circle class for unittest
    _TestCircle = type('_TestCircle', (Circle, ), {})

    def test_sectors(self):
        """
        Test evaluation method for sectors.
        """
Example #31
0
import pygame as pg
from settings import Settings as config
import assets.values.booleans as bools

pg.init()

conf = config(pg)

conf.loadDefaults()
conf.createSession()

while bools.isPlaying:
    conf.setBackground()
    conf.buildMapRelay()

    for event in pg.event.get():
        if event.type is pg.QUIT:
            bools.playing = False

    conf.setControls()

    conf.buldMarioRelay()

    conf.physicsRelay()

    pg.display.flip()
    pg.time.delay(conf.setFPS())
Example #32
0
 def provider_with_protocol(self):
     host = settings.config()["Grid Images"]["source"]
     if not host.startswith("http://"):
         host = "http://" + host
     return host
        Formula: (4 * pi * area) / perimeter ^ 2

        @param ClockFace clock_face: clock face of the image
               ElementMixin element: useless here
        @return bool True for being circular
        """
        perimeter = cv.arcLength(clock_face.main_contour, True)
        area = clock_face.area

        # calculate and return circularity
        return ((4 * np.pi * area) / (perimeter * perimeter)) > \
               type(self)._CIRCULARITY_THRESH_VAL


config(Circularity)

import unittest


class TestCircularity(unittest.TestCase):
    """
    Test Circularity class.
    """
    def test_inscribed_circle_mtd(self):
        """
        Test _inscribed_circle_mtd method with a square and a perfect circle.
        """
        from utils.create_imgs import create_square, create_circle
        from models.clock_face import ClockFace
        from models.model_mixins.image_mixin import ImageMixin
def config_userdata_location():
    return os.path.expanduser(settings.config()["Steam"]["userdata directory"])
Example #35
0
#!/usr/bin/env python
# -*- coding: utf8 -*-

import boto.ec2
import settings

c = settings.config()
conn = boto.ec2.connect_to_region(c.ec2_region_name,
                                  aws_access_key_id=c.aws_key,
                                  aws_secret_access_key=c.aws_secret,
                                  debug=c.debug)
print conn.get_all_instances()
Example #36
0
 def provider_with_protocol(self):
     host = settings.config()["Grid Images"]["source"]
     if not host.startswith("http://"):
       host = "http://" + host
     return host
        return map(list, zip(*clean_contours_info))

    @lazy_property
    def img(self):
        """
        The lazy property img. Preprocessed raw image.

        @return ndarray img preprocessed with binarization
        """
        return self._preprocess(self._raw_img,
                                binarization=True,
                                opening=False,
                                closing=False)


config(ImageMixin)

import unittest


class TestImageMixin(unittest.TestCase):
    """
    Test ImageMixin class.
    """
    def test_preprocess(self):
        """
        Test _preprocess method.
        """
        self.assertIsNotNone(ImageMixin._preprocess.__doc__)

    def test_find_clean_contours(self):
Example #38
0
# encoding: utf-8
import requests
import json
import Cookie,os
from urllib import urlencode
import re
from settings import config

cfg = config()
#ws = set.Wsh()

defaultapp = 'android'

class Shop(object):
    capt = cfg.CAPTCHA
    user = cfg.USER
    passwd = cfg.PASSWORD
    baseurl = cfg.URL
    terminalurl = cfg.URL_TERMINAL
    proxylist = cfg.PROXY
    headers = cfg.HEADERS
    headers_json = cfg.HEADERS_JSON


    def __init__(self):
        pass

    def wsh_test(self):
        print "mytest"

    #### 获取活动详情
from settings import config
from dev_script import emailLoader, extractFile
import datetime
import os


if __name__ == "__main__":

	params = config()

	date_jour = datetime.datetime.today().strftime('%d-%b-%Y') 
	files_path = os.path.join('..','data_storage','itop')
	emailLoader(dateJ=date_jour,configuration=params, path=files_path)
	extractFile(input_path=files_path)