<commit_before>#-------------------------------------------------------------------------------
# Name:        vis
# Purpose:
#
# Authors:     Maik Heistermann, Stephan Jacobi and Thomas Pfaff
#
# Created:     26.10.2011
# Copyright:   (c) Maik Heistermann, Stephan Jacobi and Thomas Pfaff 2011
# Licence:     The MIT License
#-------------------------------------------------------------------------------
#!/usr/bin/env python

"""
Visualisation
^^^^^^^^^^^^^

Standard plotting and mapping procedures

.. autosummary::
   :nosignatures:
   :toctree: generated/

   polar_plot

"""

import os.path as path
import numpy as np
import pylab as pl

def polar_plot(data, title='', saveto=None, saveformat='png'):
    """Plots data from a polar grid.

    Parameters
    ----------
    data : 2-d array
        polar grid data to be plotted
        1st dimension must be azimuth angles, 2nd must be ranges!
    title : string
        a title of the plot

    """
    n_theta, n_r = data.shape
    R = 1.
    theta = np.linspace(0, 2*np.pi, n_theta+1)
    r = np.linspace(0., R, n_r + 1)

    # plot as pcolormesh
    fig = pl.figure(figsize=(8,8))
    ax = fig.add_subplot(111, projection="polar", aspect=1.)
    pl.jet()
    circle = ax.pcolormesh(theta+np.pi/2, r, np.fliplr(np.transpose(data)),rasterized=True)
    pl.colorbar(circle, shrink=0.75)
    pl.title(title)
    if saveto==None:
        # show plot
        pl.show()
        pl.close()
    else:
        # save plot to file
        if path.exists(path.dirname(saveto)):
            pl.savefig(saveto+'.png')

if __name__ == '__main__':
    print 'wradlib: Calling module <vis> as main...'
<commit_msg>modified path definition for saving plot figures<commit_after>#-------------------------------------------------------------------------------
# Name:        vis
# Purpose:
#
# Authors:     Maik Heistermann, Stephan Jacobi and Thomas Pfaff
#
# Created:     26.10.2011
# Copyright:   (c) Maik Heistermann, Stephan Jacobi and Thomas Pfaff 2011
# Licence:     The MIT License
#-------------------------------------------------------------------------------
#!/usr/bin/env python

"""
Visualisation
^^^^^^^^^^^^^

Standard plotting and mapping procedures

.. autosummary::
   :nosignatures:
   :toctree: generated/

   polar_plot

"""

import os.path as path
import numpy as np
import pylab as pl

def polar_plot(data, title='', saveto=''):
    """Plots data from a polar grid.

    Parameters
    ----------
    data : 2-d array
        polar grid data to be plotted
        1st dimension must be azimuth angles, 2nd must be ranges!
    title : string
        a title of the plot
    saveto : string - path of the file in which the figure should be saved
        if string is empty, no figure will be saved and the plot will be
        sent to screen

    """
    n_theta, n_r = data.shape
    R = 1.
    theta = np.linspace(0, 2*np.pi, n_theta+1)
    r = np.linspace(0., R, n_r + 1)

    # plot as pcolormesh
    fig = pl.figure(figsize=(8,8))
    ax = fig.add_subplot(111, projection="polar", aspect=1.)
    pl.jet()
    circle = ax.pcolormesh(theta+np.pi/2, r, np.fliplr(np.transpose(data)),rasterized=True)
    pl.colorbar(circle, shrink=0.75)
    pl.title(title)
    if saveto=='':
        # show plot
        pl.show()
        if not pl.isinteractive():
            # close figure eplicitely if pylab is not in interactive mode
            pl.close()
    else:
        # save plot to file
        if ( path.exists(path.dirname(saveto)) ) or ( path.dirname(saveto)=='' ):
            pl.savefig(saveto)

if __name__ == '__main__':
    print 'wradlib: Calling module <vis> as main...'
<|endoftext|>


<commit_before># Copyright 2015 The Meson development team
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import flask
import os

# Create the application.
APP = flask.Flask(__name__)

APP.config.from_object("wrapweb.default_config")
if "WRAPDB_CONFIG" in os.environ:
    APP.config.from_envvar("WRAPDB_CONFIG")

@APP.teardown_appcontext
def close_connection(exception):
    db = getattr(flask.g, "_query_database", None)
    if db is not None:
        db.close()
    db = getattr(flask.g, "_update_database", None)
    if db is not None:
        db.close()

# Finalize the import of other controllers
import wrapweb.api
import wrapweb.ui
<commit_msg>app: disable linting unused import for importing api and ui<commit_after># Copyright 2015 The Meson development team
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import flask
import os

# Create the application.
APP = flask.Flask(__name__)

APP.config.from_object("wrapweb.default_config")
if "WRAPDB_CONFIG" in os.environ:
    APP.config.from_envvar("WRAPDB_CONFIG")

@APP.teardown_appcontext
def close_connection(exception):
    db = getattr(flask.g, "_query_database", None)
    if db is not None:
        db.close()
    db = getattr(flask.g, "_update_database", None)
    if db is not None:
        db.close()

# Finalize the import of other controllers
# pylint: disable=unused-import
import wrapweb.api
import wrapweb.ui
<|endoftext|>


<commit_before>#!/usr/bin/env python
# encoding: utf-8

import os
import re
import sys
import tempfile
try:
    from git import Repo
except ImportError:
    print 'GitPython module missing, please install it.'
    sys.exit()
from shutil import copytree, move, rmtree, copy

class Template(object):

    is_git = False
    complete = False
    place_holders = {
        'PROJECT_NAME': 'project_name',
        'SETTINGS_DIR': 'template_settings_dir',
        'DB_NAME': 'db_name',
        'DB_USER': 'db_user',
        'DB_PASS': 'db_pass',
        'DJANGO_SECRET_KEY': 'django_secret_key'}

    def __init__(self, config):

        self.config = config
        self.working_dir = os.popen('pwd').read().split()[0]
        self.set_project_root()
        self.is_git()
        self.copy_template()

    def set_project_root(self):
        '''Set project root, based on working dir and project name.'''

        self.project_root = os.path.join(self.working_dir,
                                         self.config.project_name)

    def make_project_dir(self):
        '''Make the project director in current working directory.'''

        if not os.path.isdir(self.project_root):
            os.mkdir(self.project_root)
            if not os.path.isdir(self.project_root):
                self.config.cli_opts.error('Error creating project '\
                                           'directory')
        else:
            self.config.cli_opts.error('%s already exists' % (
                self.project_root))

# TODO: git stuff should live in its on class
    def is_git(self):
        '''Detect if the user wants to use a git repository.'''

        if self.config.template_path.startswith('git+'):
            self.is_git = True
            self.git_repo_path = self.config.template_path.replace('git+', '')
            self.config.template_path = tempfile.mkdtemp(suffix='skeletor')
            print 'Using git to clone template from %s' % self.git_repo_path
            self.git_clone()

    def git_clone(self):
        '''Clone git repository into tmp directory.'''

        try:
            repo = Repo.init(self.config.template_path)
            repo.create_remote('origin', self.git_repo_path)
            origin = repo.remotes.origin
            origin.fetch()
            origin.pull('master')
        except:
            self.config.cli_opts.error('Error cloning repository')
        else:
            rmtree(os.path.join(self.config.template_path, '.git'))

    def copy_template(self):
        '''Moves template_path into current working dir.'''

        if os.path.isdir(self.config.template_path):
            self.make_project_dir()
            for file in os.listdir(self.config.template_path):
                path = os.path.join(self.config.template_path, file)
                if os.path.isdir(path):
                    copytree(path, os.path.join(self.project_root, file))
                else:
                    copy(path, self.project_root)
            self.swap_placeholders()
        else:
            self.config.cli_opts.error('Unable to copy template, directory '\
                                       'does not exist')
        if self.is_git:
            rmtree(self.config.template_path)

    def rename(self, root, name, keep_ext=False):
        '''Rename a file or directory.'''

        e = re.compile(r'{{(.*?)}}')
        try:
            plain = e.findall(name)[0]
            if plain in self.place_holders:
                place_holder_val = getattr(self.config,
                                           self.place_holders[plain])
                origin = os.path.join(root, name)
                new_name = place_holder_val
                if keep_ext:
                    old_name, old_ext = os.path.splitext(name)
                    new_name = place_holder_val + old_ext
                new = os.path.join(root, new_name)
                move(origin, new)
        except IndexError:
            pass

    def rename_directories(self):
        '''Move directories with placeholder names.'''

        for root, dirs, files in os.walk(self.project_root):
            for d in dirs:
                self.rename(root, d)
        return False

    def rename_files(self):
        '''Move files with placeholder names.'''

        for root, dirs, files in os.walk(self.project_root):
            for f in files:
                self.rename(root, f, True)
        return False

    def replace_line(self, f, line, placeholder):
        '''Replace placeholder with value.'''

        attr = self.place_holders[placeholder]
        val = getattr(self.config, attr, None)
        if val:
            line = line.replace('{{%s}}' % placeholder, val)
            f.write(line)

    def swap_placeholders(self):
        '''Swap placeholders for real values.'''

        while self.rename_directories():
            continue

        while self.rename_files():
            continue

        for root, dirs, files in os.walk(self.project_root):
            for file in files:
                filepath = os.path.join(root, file)
                with open(filepath, 'r+') as f:
                    lines = f.readlines()
                    f.seek(0)
                    f.truncate()
                    for line in lines:
                        has_placeholder = False
                        for placeholder in self.place_holders:
                            if '{{%s}}' % placeholder in line:
                                has_placeholder = True
                                self.replace_line(f, line, placeholder)
                        if not has_placeholder:
                            f.write(line)
                    f.close()
<commit_msg>only replace part of name<commit_after>#!/usr/bin/env python
# encoding: utf-8

import os
import re
import sys
import tempfile
try:
    from git import Repo
except ImportError:
    print 'GitPython module missing, please install it.'
    sys.exit()
from shutil import copytree, move, rmtree, copy

class Template(object):

    is_git = False
    complete = False
    place_holders = {
        'PROJECT_NAME': 'project_name',
        'SETTINGS_DIR': 'template_settings_dir',
        'DB_NAME': 'db_name',
        'DB_USER': 'db_user',
        'DB_PASS': 'db_pass',
        'DJANGO_SECRET_KEY': 'django_secret_key'}

    def __init__(self, config):

        self.config = config
        self.working_dir = os.popen('pwd').read().split()[0]
        self.set_project_root()
        self.is_git()
        self.copy_template()

    def set_project_root(self):
        '''Set project root, based on working dir and project name.'''

        self.project_root = os.path.join(self.working_dir,
                                         self.config.project_name)

    def make_project_dir(self):
        '''Make the project director in current working directory.'''

        if not os.path.isdir(self.project_root):
            os.mkdir(self.project_root)
            if not os.path.isdir(self.project_root):
                self.config.cli_opts.error('Error creating project '\
                                           'directory')
        else:
            self.config.cli_opts.error('%s already exists' % (
                self.project_root))

# TODO: git stuff should live in its on class
    def is_git(self):
        '''Detect if the user wants to use a git repository.'''

        if self.config.template_path.startswith('git+'):
            self.is_git = True
            self.git_repo_path = self.config.template_path.replace('git+', '')
            self.config.template_path = tempfile.mkdtemp(suffix='skeletor')
            print 'Using git to clone template from %s' % self.git_repo_path
            self.git_clone()

    def git_clone(self):
        '''Clone git repository into tmp directory.'''

        try:
            repo = Repo.init(self.config.template_path)
            repo.create_remote('origin', self.git_repo_path)
            origin = repo.remotes.origin
            origin.fetch()
            origin.pull('master')
        except:
            self.config.cli_opts.error('Error cloning repository')
        else:
            rmtree(os.path.join(self.config.template_path, '.git'))

    def copy_template(self):
        '''Moves template_path into current working dir.'''

        if os.path.isdir(self.config.template_path):
            self.make_project_dir()
            for file in os.listdir(self.config.template_path):
                path = os.path.join(self.config.template_path, file)
                if os.path.isdir(path):
                    copytree(path, os.path.join(self.project_root, file))
                else:
                    copy(path, self.project_root)
            self.swap_placeholders()
        else:
            self.config.cli_opts.error('Unable to copy template, directory '\
                                       'does not exist')
        if self.is_git:
            rmtree(self.config.template_path)

    def rename(self, root, name):
        '''Rename a file or directory.'''

        e = re.compile(r'{{(.*?)}}')
        try:
            plain = e.findall(name)[0]
            if plain in self.place_holders:
                place_holder_val = getattr(self.config,
                                           self.place_holders[plain])
                origin = os.path.join(root, name)
                new_name = name.replace('{{%s}}' % plain, place_holder_val)
                new = os.path.join(root, new_name)
                move(origin, new)
        except IndexError:
            pass

    def rename_directories(self):
        '''Move directories with placeholder names.'''

        for root, dirs, files in os.walk(self.project_root):
            for d in dirs:
                self.rename(root, d)
        return False

    def rename_files(self):
        '''Move files with placeholder names.'''

        for root, dirs, files in os.walk(self.project_root):
            for f in files:
                self.rename(root, f, True)
        return False

    def replace_line(self, f, line, placeholder):
        '''Replace placeholder with value.'''

        attr = self.place_holders[placeholder]
        val = getattr(self.config, attr, None)
        if val:
            line = line.replace('{{%s}}' % placeholder, val)
            f.write(line)

    def swap_placeholders(self):
        '''Swap placeholders for real values.'''

        while self.rename_directories():
            continue

        while self.rename_files():
            continue

        for root, dirs, files in os.walk(self.project_root):
            for file in files:
                filepath = os.path.join(root, file)
                with open(filepath, 'r+') as f:
                    lines = f.readlines()
                    f.seek(0)
                    f.truncate()
                    for line in lines:
                        has_placeholder = False
                        for placeholder in self.place_holders:
                            if '{{%s}}' % placeholder in line:
                                has_placeholder = True
                                self.replace_line(f, line, placeholder)
                        if not has_placeholder:
                            f.write(line)
                    f.close()
<|endoftext|>


<commit_before>#ipc_lista1.15
#Professor: Jucimar Junior
#Any Mendes Carvalho - 1615310044
#
#
#
#
#
qHora = input("Quanto você ganha por hora: ")
hT = input("Quantas horas você trabalhou: ")

SalBruto = qHora

ir = (11/100.0 * salBruto)
inss = (8/100.0m* SalBruto)
sindicato = (5/100.0 * SalBruto)

vT = ir + sindicato
SalLiq = SalBruto - vT

print "------------------------"
print "Seu salário bruto e: ",SalBruto

print '------------------------"
print "Valor dos impostos"
print "-------------------------"
print "IR: ",ir
print "INSS: ",inss
print"--------------------------"
print""
<commit_msg>Update ipc_lista1.15.py<commit_after>#ipc_lista1.15
#Professor: Jucimar Junior
#Any Mendes Carvalho - 1615310044
#
#
#
#
#
qHora = input("Quanto você ganha por hora: ")
hT = input("Quantas horas você trabalhou: ")

SalBruto = qHora

ir = (11/100.0 * salBruto)
inss = (8/100.0m* SalBruto)
sindicato = (5/100.0 * SalBruto)

vT = ir + sindicato
SalLiq = SalBruto - vT

print "------------------------"
print "Seu salário bruto e: ",SalBruto

print '------------------------"
print "Valor dos impostos"
print "-------------------------"
print "IR: ",ir
print "INSS: ",inss
print"--------------------------"
print"Se salario liquido e: ",
<|endoftext|>


<commit_before>#ipc_lista1.16
#Professor: Jucimar Junior
#Any Mendes Carvalho
<commit_msg>Update ipc_lista1.16.py<commit_after>#ipc_lista1.16
#Professor: Jucimar Junior
#Any Mendes Carvalho - 1615310044
#
#
#
#
#
<|endoftext|>


<commit_before>#ipc_lista2.03
#Professor: Jucimar Junior
#Any Mendes Carvalho - 1615310044
#
#
#
#
#Faça
<commit_msg>Update ipc_lista2.03.py<commit_after>#ipc_lista2.03
#Professor: Jucimar Junior
#Any Mendes Carvalho - 1615310044
#
#
#
#

#Faça
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-

# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html

import scrapy

class SkoobItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    pass
<commit_msg>Definindo os itens a serem extraidos<commit_after># -*- coding: utf-8 -*-

# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html

import scrapy

class SkoobItem(scrapy.Item):
    title = scrapy.Field()
    link = scrapy.Field()
    author = scrapy.Field()
<|endoftext|>


<commit_before>from __future__ import print_function

import argparse
import logging
import sys

from datetime import timedelta
from subprocess import Popen
from time import time, sleep
import psutil

def red(text):
    RED = '\033[91m'
    END = '\033[0m'
    return RED + text + END

class Process(object):
    def __init__(self,pid=None,command=None):
        self.pid = pid
        if self.pid is None:
            self.process = Popen(command)
            self.start_time = time()
        else:
            self.process = psutil.Process(self.pid)
            self.start_time = self.process.create_time()
            command = self.process.cmdline()
        self.command = ' '.join(command)

    def is_running(self):
        if self.pid is None:
            return self.process.poll() is None
        else:
            return self.process.is_running()

class HowLong(object):
    def __init__(self):
        parser = argparse.ArgumentParser(description='Time a process')
        parser.add_argument('-i', type=float, nargs='?', metavar='interval',
                            help='the timer interval, defaults to 1 second')
        parser.add_argument('-c', metavar='command', type=str, nargs=1,
                            help='a valid command')
        parser.add_argument('-p', metavar='pid', type=int, nargs=1,
                            help='a valid process id to monitor - see \'ps aux\'')
        parser.add_argument('-f', metavar='file', type=str, nargs=1,
                            help='output to file insted of stdout')
        parser.add_argument('-l', metavar='log level', nargs=1,
                            choices=['ERROR', 'INFO', 'DEBUG'],
                            help='set log level to ERROR/INFO/DEBUG')
        parser.add_argument('command_args', metavar='cmd_args', type=str,
                            nargs=argparse.REMAINDER,
                            help='additional arguments for target command')
        parsed_args = parser.parse_args()

        self.timer_interval = parsed_args.i if parsed_args.i else 1

        command = parsed_args.c if parsed_args.c else None
        cmd_args = parsed_args.command_args if parsed_args.command_args else None
        assert command is not None or cmd_args is None, "Can't have no command but have command args, \
                             usage with command is: howlong [options] -c your_command your_options"
        if parsed_args.p:
            self.pid = int(parsed_args.p[0])
            self.command = None
            assert command is None, "can't have both -p and -c"
            assert self.pid in psutil.pids(), "argument p must be a valid pid, %d is not one" % pid
        else:
            assert command is not None, "you must use either -p or -c"
            self.pid = None
            cmd_args = [] if cmd_args is None else cmd_args
            self.command = command + cmd_args

        self.log_file = parsed_args.f[0] if parsed_args.f else None

        if parsed_args.l == ["ERROR"]:
            self.log_level = logging.ERROR
        elif parsed_args.l == ["DEBUG"]:
            self.log_level = logging.DEBUG
        else:
            self.log_level = logging.INFO

    def run(self):
        if self.log_file:
            logging.basicConfig(filename=self.log_file, level=self.log_level,
                                format='%(levelname)s:%(message)s')
        else:
            logging.basicConfig(level=self.log_level,
                                format='%(levelname)s:%(message)s')

        process = Process(pid=self.pid,command=self.command)
        readable_command = process.command
        start_time = process.start_time
        logging.debug("Running " + readable_command)
        while process.is_running():
            sleep(self.timer_interval)
            elapsed_time = (time() - start_time) * 1000
            logging.info(red(str(timedelta(milliseconds=elapsed_time))))
        logging.debug("Finished " + readable_command)

def howlong():
    HowLong().run()

if __name__ == "__main__": howlong()
<commit_msg>Colored text functionality<commit_after>from __future__ import print_function

import argparse
import logging
import sys

from datetime import timedelta
from subprocess import Popen
from time import time, sleep
import psutil
from termcolor import colored

def red(text):
    RED = '\033[91m'
    END = '\033[0m'
    return RED + text + END

class Process(object):
    def __init__(self,pid=None,command=None):
        self.pid = pid
        if self.pid is None:
            self.process = Popen(command)
            self.start_time = time()
        else:
            self.process = psutil.Process(self.pid)
            self.start_time = self.process.create_time()
            command = self.process.cmdline()
        self.command = ' '.join(command)

    def is_running(self):
        if self.pid is None:
            return self.process.poll() is None
        else:
            return self.process.is_running()

class HowLong(object):
    def __init__(self):
        parser = argparse.ArgumentParser(description='Time a process')
        parser.add_argument('-i', type=float, nargs='?', metavar='interval',
                            help='the timer interval, defaults to 1 second')
        parser.add_argument('-c', metavar='command', type=str, nargs=1,
                            help='a valid command')
        parser.add_argument('-p', metavar='pid', type=int, nargs=1,
                            help='a valid process id to monitor - see \'ps aux\'')
        parser.add_argument('-f', metavar='file', type=str, nargs=1,
                            help='output to file insted of stdout')
        parser.add_argument('-l', metavar='log level', nargs=1,
                            choices=['ERROR', 'INFO', 'DEBUG'],
                            help='set log level to ERROR/INFO/DEBUG')
        parser.add_argument('command_args', metavar='cmd_args', type=str,
                            nargs=argparse.REMAINDER,
                            help='additional arguments for target command')
        parsed_args = parser.parse_args()

        self.timer_interval = parsed_args.i if parsed_args.i else 1

        command = parsed_args.c if parsed_args.c else None
        cmd_args = parsed_args.command_args if parsed_args.command_args else None
        assert command is not None or cmd_args is None, "Can't have no command but have command args, \
                             usage with command is: howlong [options] -c your_command your_options"
        if parsed_args.p:
            self.pid = int(parsed_args.p[0])
            self.command = None
            assert command is None, "can't have both -p and -c"
            assert self.pid in psutil.pids(), "argument p must be a valid pid, %d is not one" % pid
        else:
            assert command is not None, "you must use either -p or -c"
            self.pid = None
            cmd_args = [] if cmd_args is None else cmd_args
            self.command = command + cmd_args

        self.log_file = parsed_args.f[0] if parsed_args.f else None

        if parsed_args.l == ["ERROR"]:
            self.log_level = logging.ERROR
        elif parsed_args.l == ["DEBUG"]:
            self.log_level = logging.DEBUG
        else:
            self.log_level = logging.INFO

    def run(self):
        if self.log_file:
            logging.basicConfig(filename=self.log_file, level=self.log_level,
                                format='%(levelname)s:%(message)s')
        else:
            logging.basicConfig(level=self.log_level,
                                format='%(levelname)s:%(message)s')

        process = Process(pid=self.pid,command=self.command)
        readable_command = process.command
        start_time = process.start_time
        logging.debug(colored("Running " + readable_command), 'green')
        while process.is_running():
            sleep(self.timer_interval)
            elapsed_time = (time() - start_time) * 1000
            logging.info(colored(str(timedelta(milliseconds=elapsed_time)), 'blue'))
        logging.debug(colored("Finished " + readable_command), 'red')

def howlong():
    HowLong().run()

if __name__ == "__main__": howlong()
<|endoftext|>


<commit_before>#
# Ana Beatriz Faria Frota - 1615310027
# Mateus Mota de Souza - 1615310016
# Matheus Henrique Araujo Batista - 1615310039
# Nahan Trindade Passos - 1615310021
# Victor Hugo Souza Correia - 1615310024
#

print ("Vamos saber se você foi aprovado! \nPrimeiramente...")
n1 = float(input("Insira sua primeira nota: "))
n2 = float(input("Insira sua segunda nota: "))
media = (n1+n2)/2

if 9>=media>=10:
    print (n1)
    print (n2)
    print (media)
    print ("Conceito A")
    print ("Aprovado")
elif 9>media>=7.5:
    print (n1)
    print (n2)
    print (media)
    print ("Conceito B")
    print ("Aprovado")
elif 7.5>media>=6.0:
    print (n1)
    print (n2)
    print (media)
    print ("Conceito C")
    print ("Aprovado")
elif 6.0>media>=4.0:
    print (n1)
    print (n2)
    print (media)
    print ("Conceito D")
    print ("Reprovado")
elif 4.0>media>0.0:
    print (n1)
    print (n2)
    print (media)
    print ("Conceito E")
    print ("Reprovado")
else:
    print ("Conceito E")
    print ("Reprovado")
<commit_msg>Delete ipc_lista2.14.py<commit_after><|endoftext|>


<commit_before>__version__ = "3.2.0b5"
<commit_msg>version 3.2.0b6<commit_after>__version__ = "3.2.0b6"
<|endoftext|>


<commit_before>version = '0.4.9'
<commit_msg>Version Bump<commit_after>version = '0.4.10'
<|endoftext|>


<commit_before><commit_msg>preserve file name on download<commit_after><|endoftext|>


<commit_before><commit_msg>No longer need sub-class release method<commit_after><|endoftext|>


<commit_before><commit_msg>Introduced the environment variable OQ_ENGINE_MODE<commit_after><|endoftext|>


<commit_before><commit_msg>Removed unused module<commit_after><|endoftext|>


<commit_before>import gettext

#: Version information (major, minor, revision[, 'dev']).
version_info = (1, 1, 5)
#: Version string 'major.minor.revision'.
version = __version__ = ".".join(map(str, version_info))

gettext.install('slogging')
<commit_msg>version bump to 1.1.6<commit_after>import gettext

#: Version information (major, minor, revision[, 'dev']).
version_info = (1, 1, 6)
#: Version string 'major.minor.revision'.
version = __version__ = ".".join(map(str, version_info))

gettext.install('slogging')
<|endoftext|>


<commit_before>from slumber import exceptions

_SERIALIZERS = {
    "json": True,
    "yaml": True,
}

try:
    import json
except ImportError:
    _SERIALIZERS["json"] = False

try:
    import yaml
except ImportError:
    _SERIALIZERS["yaml"] = False

class BaseSerializer(object):

    content_types = None
    key = None

    def get_content_type(self):
        if self.content_types is None:
            raise NotImplementedError()
        return self.content_types[0]

    def loads(self, data):
        raise NotImplementedError()

    def dumps(self, data):
        raise NotImplementedError()

class JsonSerializer(BaseSerializer):

    content_types = [
                        "application/json",
                        "application/x-javascript",
                        "text/javascript",
                        "text/x-javascript",
                        "text/x-json",
                    ]
    key = "json"

    def loads(self, data):
        return json.loads(data)

    def dumps(self, data):
        return json.dumps(data)

class YamlSerializer(BaseSerializer):

    content_types = ["text/yaml"]
    key = "yaml"

    def loads(self, data):
        return yaml.safe_load(data)

    def dumps(self, data):
        return yaml.dump(data)

class Serializer(object):

    def __init__(self, default=None, serializers=None):
        if default is None:
            default = "json" if _SERIALIZERS["json"] else "yaml"

        if serializers is None:
            serializers = [x() for x in [JsonSerializer, YamlSerializer] if _SERIALIZERS[x.key]]

        if not serializers:
            raise exceptions.SerializerNoAvailable("There are no Available Serializers.")

        self.serializers = {}

        for serializer in serializers:
            self.serializers[serializer.key] = serializer

        self.default = default

    def get_serializer(self, name=None, content_type=None):
        if name is None and content_type is None:
            return self.serializers[self.default]
        elif name is not None and content_type is None:
            if not name in self.serializers:
                raise exceptions.SerializerNotAvailable("%s is not an available serializer" % name)
            return self.serializers[name]
        else:
            for x in self.serializers.values():
                for ctype in x.content_types:
                    if content_type == ctype:
                        return x
            raise exceptions.SerializerNotAvailable("%s is not an available serializer" % content_type)

    def loads(self, data, format=None):
        s = self.get_serializer(format)
        return s.loads(data)

    def dumps(self, data, format=None):
        s = self.get_serializer(format)
        return s.dumps(data)

    def get_content_type(self, format=None):
        s = self.get_serializer(format)
        return s.get_content_type()
<commit_msg>Fix pep-8 E128<commit_after>from slumber import exceptions

_SERIALIZERS = {
    "json": True,
    "yaml": True,
}

try:
    import json
except ImportError:
    _SERIALIZERS["json"] = False

try:
    import yaml
except ImportError:
    _SERIALIZERS["yaml"] = False

class BaseSerializer(object):

    content_types = None
    key = None

    def get_content_type(self):
        if self.content_types is None:
            raise NotImplementedError()
        return self.content_types[0]

    def loads(self, data):
        raise NotImplementedError()

    def dumps(self, data):
        raise NotImplementedError()

class JsonSerializer(BaseSerializer):

    content_types = [
        "application/json",
        "application/x-javascript",
        "text/javascript",
        "text/x-javascript",
        "text/x-json",
    ]
    key = "json"

    def loads(self, data):
        return json.loads(data)

    def dumps(self, data):
        return json.dumps(data)

class YamlSerializer(BaseSerializer):

    content_types = ["text/yaml"]
    key = "yaml"

    def loads(self, data):
        return yaml.safe_load(data)

    def dumps(self, data):
        return yaml.dump(data)

class Serializer(object):

    def __init__(self, default=None, serializers=None):
        if default is None:
            default = "json" if _SERIALIZERS["json"] else "yaml"

        if serializers is None:
            serializers = [x() for x in [JsonSerializer, YamlSerializer] if _SERIALIZERS[x.key]]

        if not serializers:
            raise exceptions.SerializerNoAvailable("There are no Available Serializers.")

        self.serializers = {}

        for serializer in serializers:
            self.serializers[serializer.key] = serializer

        self.default = default

    def get_serializer(self, name=None, content_type=None):
        if name is None and content_type is None:
            return self.serializers[self.default]
        elif name is not None and content_type is None:
            if not name in self.serializers:
                raise exceptions.SerializerNotAvailable("%s is not an available serializer" % name)
            return self.serializers[name]
        else:
            for x in self.serializers.values():
                for ctype in x.content_types:
                    if content_type == ctype:
                        return x
            raise exceptions.SerializerNotAvailable("%s is not an available serializer" % content_type)

    def loads(self, data, format=None):
        s = self.get_serializer(format)
        return s.loads(data)

    def dumps(self, data, format=None):
        s = self.get_serializer(format)
        return s.dumps(data)

    def get_content_type(self, format=None):
        s = self.get_serializer(format)
        return s.get_content_type()
<|endoftext|>


<commit_before>import datetime

from django.db import models

from logicaldelete import managers

class Model(models.Model):
    """
    This base model provides date fields and functionality to enable logical
    delete functionality in derived models.
    """

    date_created = models.DateTimeField(default=datetime.datetime.now)
    date_modified = models.DateTimeField(default=datetime.datetime.now)
    date_removed = models.DateTimeField(null=True, blank=True)

    objects = managers.LogicalDeletedManager()

    def active(self):
        return self.date_removed == None
    active.boolean = True

    def delete(self):
        '''
        Soft delete all fk related objects that
        inherit from logicaldelete class
        '''

        # Fetch related models
        related_objs = [relation.get_accessor_name() for
                        relation in self._meta.get_all_related_objects()]

        for objs_model in related_objs:
            # Retrieve all related objects
            objs = getattr(self, objs_model).all()

            for obj in objs:
                # Checking if inherits from logicaldelete
                if not issubclass(obj.__class__, Model):
                    break
                obj.delete()

        # Soft delete the object
        self.date_removed = timezone.now()
        self.save()

    class Meta:
        abstract = True
<commit_msg>Timezone support<commit_after>from django.db import models

try:
    from django.utils import timezone
except ImportError:
    from datetime import datetime as timezonefrom logicaldelete import managers

class Model(models.Model):
    """
    This base model provides date fields and functionality to enable logical
    delete functionality in derived models.
    """

    date_created = models.DateTimeField(default=timezone.now)
    date_modified = models.DateTimeField(default=timezone.now)
    date_removed = models.DateTimeField(null=True, blank=True)

    objects = managers.LogicalDeletedManager()

    def active(self):
        return self.date_removed is None
    active.boolean = True

    def delete(self):
        '''
        Soft delete all fk related objects that
        inherit from logicaldelete class
        '''

        # Fetch related models
        related_objs = [relation.get_accessor_name() for
                        relation in self._meta.get_all_related_objects()]

        for objs_model in related_objs:
            # Retrieve all related objects
            objs = getattr(self, objs_model).all()

            for obj in objs:
                # Checking if inherits from logicaldelete
                if not issubclass(obj.__class__, Model):
                    break
                obj.delete()

        # Soft delete the object
        self.date_removed = timezone.now()
        self.save()

    class Meta:
        abstract = True
<|endoftext|>


<commit_before>#!/usr/bin/python -B
#
# (Use -B to suppress __pycache__/pyc/pyo creation.  Those files can break
# things, e.g. when I run a script as sudo and get root-owned files in my home
# directory.)
#

from __future__ import absolute_import, print_function, unicode_literals

import sys
import os

FEATURE_RATE = 0x20
FEATURE_DPI  = 0x8e
RATE_LIST = [("1000", 0), ("500", 1), ("250", 2), ("125", 3)]
DPI_LIST = [("400", 3), ("800", 4), ("1800", 5), ("3600", 6), ("3600_frozen", 7)]

def usage(err=0):
    print("usage: logitech-g400-config.py [show]")
    print("  Prints the current mouse settings")
    print("")
    print("usage: logitech-g400-config.py set [options]")
    print("  -rRATE")
    print("    RATE is in Hz and is one of: 125, 250, 500, or 1000.  The Windows driver")
    print("    defaults to 500 Hz.")
    print("  -dDPI")
    print("    DPI is one of: 400, 800, 1800, 3600, or 3600_frozen.  With 3600_frozen, the")
    print("    DPI+/DPI- buttons no longer change the DPI and instead are treated as")
    print("    any other ordinary mouse button.")
    print("")
    print("usage: logitech-g400-config.py trace")
    print("    Read mouse press/release interrupts from the Logitech-proprietary G400 USB")
    print("    interface.  This interface will report DPI+/DPI- presses/releases even with")
    print("    ordinary DPI settings.  End the tracing with Ctrl-C.")
    print("")
    sys.exit(err)

def open_device():
    global hid
    import hid

    info_good = []
    info_skip = []

    device_list = hid.enumerate(0x046d, 0xc245)
    for info in device_list:
        # The mouse should have two interfaces, #0 and #1.  We need
        # interface #1.  Linux uses the `interface_number` field.  macOS uses
        # an IOKit IOService path, which includes a string like
        # "/IOUSBHostInterface@0/".
        if b"/IOUSBHostInterface@0/" in info["path"] or info["interface_number"] == 0:
            info_skip.append(info)
        elif b"/IOUSBHostInterface@1/" in info["path"] or info["interface_number"] == 1:
            info_good.append(info)
        else:
            print("unexpected G400 USB device: " + info["path"])

    if len(info_good) == 1:
        return hid.Device(path=info_good[0]["path"])
    elif len(info_good) != len(info_skip):
        sys.exit("error: unexpected USB interfaces while querying for a G400 mouse")
    elif len(info_good) == 0:
        sys.exit("error: no G400 mouse attached")
    else:
        sys.exit("error: multiple G400 mice detected -- this script only supports one")

def set_var(dev, var, val):
    dev.send_feature_report(bytes(bytearray((var, val))))

def get_var(dev, var):
    return bytearray(dev.get_feature_report(var, 2))[1]

def map_pair_list(lst, val, reversed=False):
    for pair in lst:
        if val == pair[1 - (not reversed)]:
            return pair[1 - reversed]
    return None

def reject_cmd_subargs(subargs):
    for arg in subargs:
        if arg == "--help":
            usage(0)
        else:
            usage("error: unrecognized argument: " + arg)

def do_set_cmd(subargs):
    dev = open_device()
    for arg in subargs:
        rate = map_pair_list(RATE_LIST, arg[2:])
        dpi = map_pair_list(DPI_LIST, arg[2:])
        if arg.startswith("-r") and rate is not None:
            set_var(dev, FEATURE_RATE, rate)
        elif arg.startswith("-d") and dpi is not None:
            set_var(dev, FEATURE_DPI, dpi)
        elif arg == "--help":
            usage(0)
        else:
            usage("error: unrecognized argument: " + arg)

def do_trace_cmd():
    dev = open_device()
    while True:
        data = bytearray(dev.read(2, 1000))
        if len(data) == 0:
            continue
        if data[0] == 0x80 and len(data) == 2:
            buttonbits = bytearray(data)[1]
            buttons = [" %s" % i for i in range(8) if (buttonbits & (1 << i)) != 0]
            print("pressed:" + "".join(buttons))
        else:
            print("unknown:" + "".join([" %02x" % x for x in data]))

def do_show_cmd():
    dev = open_device()
    rate = get_var(dev, FEATURE_RATE)
    rate = map_pair_list(RATE_LIST, rate, True) or ("unknown(%s)" % rate)
    dpi = get_var(dev, FEATURE_DPI)
    dpi = map_pair_list(DPI_LIST, dpi, True) or ("unknown(%s)" % dpi)
    print("sampling_rate: %s" % rate)
    print("dpi_level: %s" % dpi)

def main():
    cmd = sys.argv[1] if len(sys.argv) >= 2 else None
    subargs = sys.argv[2:]
    if cmd == "set":
        do_set_cmd(subargs)
    elif cmd == "trace":
        reject_cmd_subargs(subargs)
        do_trace_cmd()
    elif cmd in [None, "show"]:
        reject_cmd_subargs(subargs)
        do_show_cmd()
    elif cmd == "--help":
        usage(0)
    else:
        usage("error: unrecognized command: " + cmd)

main()
<commit_msg>Don't start setting the rate/dpi until we've parsed all arguments<commit_after>#!/usr/bin/python -B
#
# (Use -B to suppress __pycache__/pyc/pyo creation.  Those files can break
# things, e.g. when I run a script as sudo and get root-owned files in my home
# directory.)
#

from __future__ import absolute_import, print_function, unicode_literals

import sys
import os

FEATURE_RATE = 0x20
FEATURE_DPI  = 0x8e
RATE_LIST = [("1000", 0), ("500", 1), ("250", 2), ("125", 3)]
DPI_LIST = [("400", 3), ("800", 4), ("1800", 5), ("3600", 6), ("3600_frozen", 7)]

def usage(err=0):
    print("usage: logitech-g400-config.py [show]")
    print("  Prints the current mouse settings")
    print("")
    print("usage: logitech-g400-config.py set [options]")
    print("  -rRATE")
    print("    RATE is in Hz and is one of: 125, 250, 500, or 1000.  The Windows driver")
    print("    defaults to 500 Hz.")
    print("  -dDPI")
    print("    DPI is one of: 400, 800, 1800, 3600, or 3600_frozen.  With 3600_frozen, the")
    print("    DPI+/DPI- buttons no longer change the DPI and instead are treated as")
    print("    any other ordinary mouse button.")
    print("")
    print("usage: logitech-g400-config.py trace")
    print("    Read mouse press/release interrupts from the Logitech-proprietary G400 USB")
    print("    interface.  This interface will report DPI+/DPI- presses/releases even with")
    print("    ordinary DPI settings.  End the tracing with Ctrl-C.")
    print("")
    sys.exit(err)

def open_device():
    global hid
    import hid

    info_good = []
    info_skip = []

    device_list = hid.enumerate(0x046d, 0xc245)
    for info in device_list:
        # The mouse should have two interfaces, #0 and #1.  We need
        # interface #1.  Linux uses the `interface_number` field.  macOS uses
        # an IOKit IOService path, which includes a string like
        # "/IOUSBHostInterface@0/".
        if b"/IOUSBHostInterface@0/" in info["path"] or info["interface_number"] == 0:
            info_skip.append(info)
        elif b"/IOUSBHostInterface@1/" in info["path"] or info["interface_number"] == 1:
            info_good.append(info)
        else:
            print("unexpected G400 USB device: " + info["path"])

    if len(info_good) == 1:
        return hid.Device(path=info_good[0]["path"])
    elif len(info_good) != len(info_skip):
        sys.exit("error: unexpected USB interfaces while querying for a G400 mouse")
    elif len(info_good) == 0:
        sys.exit("error: no G400 mouse attached")
    else:
        sys.exit("error: multiple G400 mice detected -- this script only supports one")

def set_var(dev, var, val):
    dev.send_feature_report(bytes(bytearray((var, val))))

def get_var(dev, var):
    return bytearray(dev.get_feature_report(var, 2))[1]

def map_pair_list(lst, val, reversed=False):
    for pair in lst:
        if val == pair[1 - (not reversed)]:
            return pair[1 - reversed]
    return None

def reject_cmd_subargs(subargs):
    for arg in subargs:
        if arg == "--help":
            usage(0)
        else:
            usage("error: unrecognized argument: " + arg)

def do_set_cmd(subargs):
    rate = None
    dpi = None
    for arg in subargs:
        arg_val = arg[2:]
        if arg.startswith("-r"):
            rate = map_pair_list(RATE_LIST, arg_val)
            if rate is None:
                usage("error: invalid RATE setting: " + arg_val)
        elif arg.startswith("-d"):
            dpi = map_pair_list(DPI_LIST, arg_val)
            if dpi is None:
                usage("error: invalid DPI setting: " + arg_val)
        elif arg == "--help":
            usage(0)
        else:
            usage("error: unrecognized argument: " + arg)
    dev = open_device()
    if rate is not None:
        set_var(dev, FEATURE_RATE, rate)
    if dpi is not None:
        set_var(dev, FEATURE_DPI, dpi)

def do_trace_cmd():
    dev = open_device()
    while True:
        data = bytearray(dev.read(2, 1000))
        if len(data) == 0:
            continue
        if data[0] == 0x80 and len(data) == 2:
            buttonbits = bytearray(data)[1]
            buttons = [" %s" % i for i in range(8) if (buttonbits & (1 << i)) != 0]
            print("pressed:" + "".join(buttons))
        else:
            print("unknown:" + "".join([" %02x" % x for x in data]))

def do_show_cmd():
    dev = open_device()
    rate = get_var(dev, FEATURE_RATE)
    rate = map_pair_list(RATE_LIST, rate, True) or ("unknown(%s)" % rate)
    dpi = get_var(dev, FEATURE_DPI)
    dpi = map_pair_list(DPI_LIST, dpi, True) or ("unknown(%s)" % dpi)
    print("sampling_rate: %s" % rate)
    print("dpi_level: %s" % dpi)

def main():
    cmd = sys.argv[1] if len(sys.argv) >= 2 else None
    subargs = sys.argv[2:]
    if cmd == "set":
        do_set_cmd(subargs)
    elif cmd == "trace":
        reject_cmd_subargs(subargs)
        do_trace_cmd()
    elif cmd in [None, "show"]:
        reject_cmd_subargs(subargs)
        do_show_cmd()
    elif cmd == "--help":
        usage(0)
    else:
        usage("error: unrecognized command: " + cmd)

main()
<|endoftext|>


<commit_before># Copyright (c) 2014 Rackspace
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
Initial M1 Solum CLI commands implemented (but not REST communications):
* app create --repo="repo_url" [--build=no] plan_name
* app delete plan_name
* app list
* assembly create [--assembly="assembly_name"] plan_name
* assembly delete assembly_name
* assembly list

Notes:
* This code is expected to be replaced by the OpenStack Client (OSC) when
    it has progressed a little bit farther as described at:
    https://wiki.openstack.org/wiki/Solum/CLI
* Internationalization will not be added in M1 since this is a prototype
"""

from __future__ import print_function

import argparse
import json
import sys

import six
import yaml

from solumclient.common import cli_utils
from solumclient.openstack.common import cliutils
from solumclient.openstack.common import strutils

class AppCommands(cli_utils.CommandsBase):
    """Application targets."""

    def create(self):
        """Create an application."""
        self.parser.add_argument('plan_file',
                                 help="Plan file")
        args = self.parser.parse_args()
        with open(args.plan_file) as definition_file:
            definition = definition_file.read()

        # Convert yaml to json until we add yaml support in API layer.
        try:
            data = yaml.load(definition)
        except yaml.YAMLError as exc:
            print("Error in plan file: %s", str(exc))
            sys.exit(1)

        json_data = json.dumps(data)
        plan = self.client.plans.create(json_data)

        fields = ['uuid', 'name', 'description', 'uri']
        data = dict([(f, getattr(plan, f, ''))
                     for f in fields])
        cliutils.print_dict(data, wrap=72)

    def delete(self):
        """Delete an application."""
        self.parser.add_argument('plan_uuid',
                                 help="Tenant/project-wide unique plan uuid")
        args = self.parser.parse_args()
        self.client.plans.delete(plan_id=args.plan_uuid)

    def list(self):
        """List all applications."""
        fields = ['uuid', 'name', 'description']
        response = self.client.plans.list()
        cliutils.print_list(response, fields)

class AssemblyCommands(cli_utils.CommandsBase):
    """Assembly targets."""

    def create(self):
        """Create an assembly."""
        self.parser.add_argument('plan_uri',
                                 help="Tenant/project-wide unique plan uri")
        self.parser.add_argument('--assembly',
                                 help="Assembly name")
        args = self.parser.parse_args()
        print("assembly create plan_uri=%s assembly=%s" % (
            args.plan_uri,
            args.assembly))
        assembly = self.client.assemblies.create(name=args.assembly,
                                                 plan_uri=args.plan_uri)
        fields = ['uuid', 'name', 'description', 'status']
        data = dict([(f, getattr(assembly, f, ''))
                     for f in fields])
        cliutils.print_dict(data, wrap=72)

    def delete(self):
        """Delete an assembly."""
        self.parser.add_argument('assembly_uuid',
                                 help="Assembly uuid")
        args = self.parser.parse_args()
        self.client.assemblies.delete(assembly_id=args.assembly_uuid)

    def list(self):
        """List all assemblies."""
        fields = ['uuid', 'name', 'description', 'status']
        response = self.client.assemblies.list()
        cliutils.print_list(response, fields)

    def get(self):
        """Show an assembly's resource."""
        self.parser.add_argument('assembly_uuid',
                                 help="Assembly uuid")
        args = self.parser.parse_args()
        print("assembly get assembly_uuid=%s" % (
            args.assembly_uuid))
        response = self.client.assemblies.get(assembly_id=args.assembly_uuid)
        fields = ['uuid', 'name', 'description', 'status']
        data = dict([(f, getattr(response, f, ''))
                     for f in fields])
        cliutils.print_dict(data, wrap=72)

def main():
    """Basically the entry point."""
    parser = argparse.ArgumentParser(conflict_handler='resolve')
    parser.the_error = parser.error
    parser.error = lambda m: None

    resources = {
        'app': AppCommands,
        'assembly': AssemblyCommands,
    }

    choices = resources.keys()

    parser.add_argument('resource', choices=choices,
                        help="Target noun to act upon")

    resource = None
    try:
        parsed, _ = parser.parse_known_args()
        resource = parsed.resource
    except Exception as se_except:
        parser.print_help()
        return se_except

    if resource in resources:
        try:
            resources[resource](parser)
        except Exception as e:
            print(strutils.safe_encode(six.text_type(e)), file=sys.stderr)
            sys.exit(1)

    else:
        cli_utils.show_help(resources)
        print("\n")
        parser.print_help()

if __name__ == '__main__':
    sys.exit(main())
<commit_msg>Remove unnecessary print statements from solum cmdline client<commit_after># Copyright (c) 2014 Rackspace
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
Initial M1 Solum CLI commands implemented (but not REST communications):
* app create --repo="repo_url" [--build=no] plan_name
* app delete plan_name
* app list
* assembly create [--assembly="assembly_name"] plan_name
* assembly delete assembly_name
* assembly list

Notes:
* This code is expected to be replaced by the OpenStack Client (OSC) when
    it has progressed a little bit farther as described at:
    https://wiki.openstack.org/wiki/Solum/CLI
* Internationalization will not be added in M1 since this is a prototype
"""

from __future__ import print_function

import argparse
import json
import sys

import six
import yaml

from solumclient.common import cli_utils
from solumclient.openstack.common import cliutils
from solumclient.openstack.common import strutils

class AppCommands(cli_utils.CommandsBase):
    """Application targets."""

    def create(self):
        """Create an application."""
        self.parser.add_argument('plan_file',
                                 help="Plan file")
        args = self.parser.parse_args()
        with open(args.plan_file) as definition_file:
            definition = definition_file.read()

        # Convert yaml to json until we add yaml support in API layer.
        try:
            data = yaml.load(definition)
        except yaml.YAMLError as exc:
            print("Error in plan file: %s", str(exc))
            sys.exit(1)

        json_data = json.dumps(data)
        plan = self.client.plans.create(json_data)

        fields = ['uuid', 'name', 'description', 'uri']
        data = dict([(f, getattr(plan, f, ''))
                     for f in fields])
        cliutils.print_dict(data, wrap=72)

    def delete(self):
        """Delete an application."""
        self.parser.add_argument('plan_uuid',
                                 help="Tenant/project-wide unique plan uuid")
        args = self.parser.parse_args()
        self.client.plans.delete(plan_id=args.plan_uuid)

    def list(self):
        """List all applications."""
        fields = ['uuid', 'name', 'description']
        response = self.client.plans.list()
        cliutils.print_list(response, fields)

class AssemblyCommands(cli_utils.CommandsBase):
    """Assembly targets."""

    def create(self):
        """Create an assembly."""
        self.parser.add_argument('plan_uri',
                                 help="Tenant/project-wide unique plan uri")
        self.parser.add_argument('--assembly',
                                 help="Assembly name")
        args = self.parser.parse_args()
        assembly = self.client.assemblies.create(name=args.assembly,
                                                 plan_uri=args.plan_uri)
        fields = ['uuid', 'name', 'description', 'status']
        data = dict([(f, getattr(assembly, f, ''))
                     for f in fields])
        cliutils.print_dict(data, wrap=72)

    def delete(self):
        """Delete an assembly."""
        self.parser.add_argument('assembly_uuid',
                                 help="Assembly uuid")
        args = self.parser.parse_args()
        self.client.assemblies.delete(assembly_id=args.assembly_uuid)

    def list(self):
        """List all assemblies."""
        fields = ['uuid', 'name', 'description', 'status']
        response = self.client.assemblies.list()
        cliutils.print_list(response, fields)

    def get(self):
        """Show an assembly's resource."""
        self.parser.add_argument('assembly_uuid',
                                 help="Assembly uuid")
        args = self.parser.parse_args()
        response = self.client.assemblies.get(assembly_id=args.assembly_uuid)
        fields = ['uuid', 'name', 'description', 'status']
        data = dict([(f, getattr(response, f, ''))
                     for f in fields])
        cliutils.print_dict(data, wrap=72)

def main():
    """Basically the entry point."""
    parser = argparse.ArgumentParser(conflict_handler='resolve')
    parser.the_error = parser.error
    parser.error = lambda m: None

    resources = {
        'app': AppCommands,
        'assembly': AssemblyCommands,
    }

    choices = resources.keys()

    parser.add_argument('resource', choices=choices,
                        help="Target noun to act upon")

    resource = None
    try:
        parsed, _ = parser.parse_known_args()
        resource = parsed.resource
    except Exception as se_except:
        parser.print_help()
        return se_except

    if resource in resources:
        try:
            resources[resource](parser)
        except Exception as e:
            print(strutils.safe_encode(six.text_type(e)), file=sys.stderr)
            sys.exit(1)

    else:
        cli_utils.show_help(resources)
        print("\n")
        parser.print_help()

if __name__ == '__main__':
    sys.exit(main())
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
"""
https://leetcode.com/problems/burst-balloons/description/

Given n balloons, indexed from 0 to n-1. Each balloon is painted with a number on it represented by array nums. You are asked to burst all the balloons. If the you burst balloon i you will get nums[left] * nums[i] * nums[right] coins. Here left and right are adjacent indices of i. After the burst, the left and right then becomes adjacent.

Find the maximum coins you can collect by bursting the balloons wisely.

Note:

You may imagine nums[-1] = nums[n] = 1. They are not real therefore you can not burst them.
0 ≤ n ≤ 500, 0 ≤ nums[i] ≤ 100
Example:

Input: [3,1,5,8]
Output: 167
Explanation: nums = [3,1,5,8] --> [3,5,8] -->   [3,8]   -->  [8]  --> []
             coins =  3*1*5      +  3*5*8    +  1*3*8      + 1*8*1   = 167
"""

import unittest

def toKey(nums):
    return ",".join([str(n) for n in nums])

class Node:

    def __init__(self, nums: list[int], key: str, val: int, parent=None):
        self.nums = nums
        self.length = len(nums)
        self.key = key
        self.val = val
        self.sub = 0
        self.parent = parent

class Solution:

    def maxOfThree(self, nums):
        return nums[0]*nums[1]*nums[2] + nums[0]*nums[-1] + max(nums[0], nums[-1])

    def maxCoins(self, nums):
        nums = list(filter(lambda num: num > 0, nums))
        if len(nums) == 0:
            return 0
        if len(nums) == 1:
            return nums[0]
        if len(nums) == 2:
            return nums[0]*nums[1] + max(nums)
        if len(nums) == 3:
            return self.maxOfThree(nums)

        root = Node(nums, toKey(nums), 0)
        visits = {root.key: root}
        stack = [root]

        while len(stack) != 0:
            cur = stack.pop()
            # print("cur:", cur.key)
            if cur.length == 3:
                # cur.val = nums[0]*nums[1]*nums[2]
                # cur.sub = nums[0]*nums[-1] + max(nums[0], nums[-1])
                cur.sub = self.maxOfThree(cur.nums)
                print(cur.key, "|", cur.sub, cur.val)
                while cur.parent != None and cur.val + cur.sub > visits[cur.parent.key].sub:
                    visits[cur.parent.key].sub = cur.val + cur.sub
                    cur = visits[cur.parent.key]
                continue

            for i in range(1, len(cur.nums)-1):
                rests = cur.nums[:i] + cur.nums[i+1:]
                val = cur.nums[i-1]*cur.nums[i]*cur.nums[i+1]
                key = toKey(rests)
                if key not in visits:
                    # print(i, cur.nums[i-1], cur.nums[i], cur.nums[i+1])
                    # print("key:", key, "val:", val)
                    node = Node(rests, key, val, cur)
                    visits[key] = node
                    stack.append(node)
                else:
                    node = visits[key]
                    # print(node.val)
                    if val > node.val:
                        node.val = val
                        # node.val = max(node.val, val)
                        node.parent = cur
                        # print("node.key", node.key, node.val, node.sub)
                        # print("cur.key", cur.key, cur.val, cur.sub)
                        # print("val", val)
                        # node
                        # cur.val = val

                        # cur.sub = max(cur.sub, val + visits[key].sub)

                        # cur.sub = max(cur.sub + cur.val, visits[key].sub)
                        # print("kkkkk", key, sub, val, visits[key].val, visits[key].sub)
                        while node.parent != None and node.val + node.sub > visits[node.parent.key].sub:
                            visits[node.parent.key].sub = node.val + node.sub
                            # print("node.parent.key", node.parent.key, visits[node.parent.key].val, visits[node.parent.key].sub)
                            node = visits[node.parent.key]
                    continue
        # print(visits)
        # for key, node in visits.items():
        #     print(f'[{key}]', "val:", node.val, "sub:", node.sub)
        return root.sub

class SolutionTestCase(unittest.TestCase):

    def setUp(self):
        self.solution = Solution()

    def test_01(self):
        nums = [10]
        expected = 10
        got = self.solution.maxCoins(nums)
        self.assertEqual(expected, got)

        nums = [3,8]
        expected = 3*8 + 8
        got = self.solution.maxCoins(nums)
        self.assertEqual(expected, got)

        nums = [3,10,3]
        expected = 90 + 9 + 3
        got = self.solution.maxCoins(nums)
        self.assertEqual(expected, got)

        nums = [3, 5, 8]
        expected = 152
        got = self.solution.maxCoins(nums)
        self.assertEqual(expected, got)

        nums = [1, 5, 8]
        expected = 56
        got = self.solution.maxCoins(nums)
        self.assertEqual(expected, got)

        nums = [1, 3, 8]
        expected = 40
        got = self.solution.maxCoins(nums)
        self.assertEqual(expected, got)

    def test_02(self):
        nums = [3,1,5,8]
        print("\n", nums)
        expected = 167
        got = self.solution.maxCoins(nums)
        self.assertEqual(expected, got)
        self.assertEqual(expected, self.solution.maxCoins([0,3,1,5,8]))
        self.assertEqual(expected, self.solution.maxCoins([3,0,1,5,8]))

        self.assertEqual(160, self.solution.maxCoins([1,3,5,8]))
        # [1,3,5,8] --> [1,3,8] --> [1,8] --> [8]
        #   3*5*8          24         8        8 = 160

        nums = [3,1,2,5,8]
        expected = 6 + 30 + 152
        got = self.solution.maxCoins([3,1,2,5,8])
        self.assertEqual(expected, got)

        nums = [1,2,5,8]
        print("qq", self.solution.maxCoins(nums))

        nums = [1,3,5,8]
        print("qq", self.solution.maxCoins(nums))

        nums = [1,3, 2,8]
        print("qq", self.solution.maxCoins(nums))

    def test_03(self):
        self.assertEqual(self.solution.maxCoins([1,3,2,5,8]), 190)
        self.assertEqual(self.solution.maxCoins([9,76,64,21]), 116718) # (102144 + 14574)
        self.assertEqual(self.solution.maxCoins([9,76,21]), 14574)
        self.assertEqual(self.solution.maxCoins([76,64,21,21]), 137332) # (64*76*21 + 35188)

    def test_04(self):
        nums = [9,76,97,60,5]
        print("\n", nums)
        # [9,76,97,60,5] val: 0 sub: 486114
        # [9,97,60,5] val: 66348 sub: 70767
        # [9,76,60,5] val: 442320 sub: 43794
        # [9,76,97,5] val: 29100 sub: 70767

        got = self.solution.maxCoins(nums)

        nums = [9,76,64,97,60,5]
        # [9,76,97,60,5] val: 471808(76*64*97) sub: 542575
        print("\n", nums)
        got = self.solution.maxCoins(nums)

    def test_05(self):
        nums = [9,76,64,21,97,60,5]
       # [9,76,64,97,60,5] val: 130368 sub: 1014383

        print("\n", nums)
        expected = 1088290
        got = self.solution.maxCoins(nums)
        self.assertEqual(expected, got)

    def test_06(self):
        nums = [35,16,83,87,84,59,48,41]
        expected = 1583373
        got = self.solution.maxCoins(nums)
        self.assertEqual(expected, got)

if __name__ == '__main__':
    unittest.main()
<commit_msg>wa: still<commit_after># -*- coding: utf-8 -*-
"""
https://leetcode.com/problems/burst-balloons/description/

Given n balloons, indexed from 0 to n-1. Each balloon is painted with a number on it represented by array nums. You are asked to burst all the balloons. If the you burst balloon i you will get nums[left] * nums[i] * nums[right] coins. Here left and right are adjacent indices of i. After the burst, the left and right then becomes adjacent.

Find the maximum coins you can collect by bursting the balloons wisely.

Note:

You may imagine nums[-1] = nums[n] = 1. They are not real therefore you can not burst them.
0 ≤ n ≤ 500, 0 ≤ nums[i] ≤ 100
Example:

Input: [3,1,5,8]
Output: 167
Explanation: nums = [3,1,5,8] --> [3,5,8] -->   [3,8]   -->  [8]  --> []
             coins =  3*1*5      +  3*5*8    +  1*3*8      + 1*8*1   = 167
"""

import unittest

def toKey(nums):
    return ",".join([str(n) for n in nums])

class Node:

    def __init__(self, nums: list[int], key: str, parent, val: int, sub: int):
        self.nums = nums
        self.length = len(nums)
        self.key = key
        self.val = val
        self.sub = sub
        self.parent = parent

class Solution:

    def maxOfThree(self, nums):
        return nums[0]*nums[1]*nums[2] + nums[0]*nums[-1] + max(nums[0], nums[-1])

    def maxCoins(self, nums):
        nums = list(filter(lambda num: num > 0, nums))
        if len(nums) == 0:
            return 0
        if len(nums) == 1:
            return nums[0]
        if len(nums) == 2:
            return nums[0]*nums[1] + max(nums)
        if len(nums) == 3:
            return self.maxOfThree(nums)

        root = Node(nums, toKey(nums), None, 0, 0)
        visits = {root.key: root}
        stack = [root]

        while len(stack) != 0:
            cur = stack.pop()

            if cur.length == 3:
                cur.sub = self.maxOfThree(cur.nums)
                while cur.parent != None and cur.val + cur.sub > visits[cur.parent.key].sub:
                    visits[cur.parent.key].sub = cur.val + cur.sub
                    cur = visits[cur.parent.key]
                continue

            for i in range(1, len(cur.nums)-1):
                rests = cur.nums[:i] + cur.nums[i+1:]
                val = cur.nums[i-1]*cur.nums[i]*cur.nums[i+1]
                key = toKey(rests)
                if key not in visits:
                    node = Node(rests, key, cur, val, 0)
                    visits[key] = node
                    stack.append(node)
                else:
                    node = Node(rests, key, cur, val, visits[key].sub)
                    while node.parent != None and node.val + node.sub > visits[node.parent.key].sub:
                        visits[node.parent.key].sub = node.val + node.sub
                        node = visits[node.parent.key]
                    continue

        for key, node in visits.items():
            print(f'[{key}]', "val:", node.val, "sub:", node.sub)
        return root.sub

class SolutionTestCase(unittest.TestCase):

    def setUp(self):
        self.solution = Solution()

    # def test_01(self):
    #     nums = [10]
    #     expected = 10
    #     got = self.solution.maxCoins(nums)
    #     self.assertEqual(expected, got)

    #     nums = [3,8]
    #     expected = 3*8 + 8
    #     got = self.solution.maxCoins(nums)
    #     self.assertEqual(expected, got)

    #     nums = [3,10,3]
    #     expected = 90 + 9 + 3
    #     got = self.solution.maxCoins(nums)
    #     self.assertEqual(expected, got)

    #     nums = [3, 5, 8]
    #     expected = 152
    #     got = self.solution.maxCoins(nums)
    #     self.assertEqual(expected, got)

    #     nums = [1, 5, 8]
    #     expected = 56
    #     got = self.solution.maxCoins(nums)
    #     self.assertEqual(expected, got)

    #     nums = [1, 3, 8]
    #     expected = 40
    #     got = self.solution.maxCoins(nums)
    #     self.assertEqual(expected, got)

    # def test_02(self):
    #     nums = [3,1,5,8]
    #     print("\n", nums)
    #     expected = 167
    #     got = self.solution.maxCoins(nums)
    #     self.assertEqual(expected, got)
    #     self.assertEqual(expected, self.solution.maxCoins([0,3,1,5,8]))
    #     self.assertEqual(expected, self.solution.maxCoins([3,0,1,5,8]))

    #     self.assertEqual(160, self.solution.maxCoins([1,3,5,8]))
    #     # [1,3,5,8] --> [1,3,8] --> [1,8] --> [8]
    #     #   3*5*8          24         8        8 = 160

    #     nums = [3,1,2,5,8]
    #     expected = 6 + 30 + 152
    #     got = self.solution.maxCoins([3,1,2,5,8])
    #     self.assertEqual(expected, got)

    #     nums = [1,2,5,8]
    #     print("qq", self.solution.maxCoins(nums))

    #     nums = [1,3,5,8]
    #     print("qq", self.solution.maxCoins(nums))

    #     nums = [1,3, 2,8]
    #     print("qq", self.solution.maxCoins(nums))

    # def test_03(self):
    #     self.assertEqual(self.solution.maxCoins([1,3,2,5,8]), 190)
    #     self.assertEqual(self.solution.maxCoins([9,76,64,21]), 116718) # (102144 + 14574)
    #     self.assertEqual(self.solution.maxCoins([9,76,21]), 14574)
    #     self.assertEqual(self.solution.maxCoins([76,64,21,21]), 137332) # (64*76*21 + 35188)

    # def test_04(self):
    #     nums = [9,76,97,60,5]
    #     print("\n", nums)
    #     # [9,76,97,60,5] val: 0 sub: 486114
    #     # [9,97,60,5] val: 66348 sub: 70767
    #     # [9,76,60,5] val: 442320 sub: 43794
    #     # [9,76,97,5] val: 29100 sub: 70767

    #     got = self.solution.maxCoins(nums)

    #     nums = [9,76,64,97,60,5]
    #     # [9,76,97,60,5] val: 471808(76*64*97) sub: 542575
    #     print("\n", nums)
    #     got = self.solution.maxCoins(nums)

    # def test_05(self):
    #     nums = [9,76,64,21,97,60,5]
    #     # [9,76,64,97,60,5] val: 130368 sub: 1014383

    #     print("\n", nums)
    #     expected = 1088290
    #     got = self.solution.maxCoins(nums)
    #     self.assertEqual(expected, got)

    # def test_06(self):
    #     nums = [35,16,83,87,84,59,48,41]
    #     expected = 1583373
    #     got = self.solution.maxCoins(nums)
    #     self.assertEqual(expected, got)

    def test_07(self):
        nums = [2,3,9,1]
        print("\n", nums)
        expected = 76
        got = self.solution.maxCoins(nums)
        self.assertEqual(expected, got)

        nums = [2,3,7,9,1]
        print("\n", nums)
        expected = 279
        got = self.solution.maxCoins(nums)
        self.assertEqual(expected, got)

if __name__ == '__main__':
    unittest.main()
<|endoftext|>


<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Main file for SolveBio CLI """
#from __future__ import print_function

import os
import sys
import argparse

import solvebio

from . import auth

class SolveArgumentParser(argparse.ArgumentParser):
    """Main parser for the SolveBio command line client"""
    HELP = {
        'login': 'Login and save credentials',
        'logout': 'Logout and delete saved credentials',
        'whoami': 'Show your SolveBio email address',
        'shell': 'Open the SolveBio Python shell',
        'test': 'Make sure the SolveBio API is working correctly',
        'version': '%(prog)s {}'.format(solvebio.version.VERSION),
        'api_host': 'Override the default SolveBio API host',
        'api_key': 'Manually provide a SolveBio API key'
    }

    def __init__(self, *args, **kwargs):
        super(SolveArgumentParser, self).__init__(*args, **kwargs)
        self._optionals.title = 'SolveBio Options'
        self.add_argument('--version', action='version',
                          version=self.HELP['version'])
        self.add_argument('--api-host', help=self.HELP['api_host'])
        self.add_argument('--api-key', help=self.HELP['api_key'])

    def _add_subcommands(self):
        """
            The _add_subcommands method must be separate from the __init__
            method, as infinite recursion will occur otherwise, due to the fact
            that the __init__ method itself will be called when instantiating
            a subparser, as we do below
        """
        subcmd_params = {
            'title': 'SolveBio Commands',
            'dest': 'subcommands'
        }
        subcmd = self.add_subparsers(
            **subcmd_params)  # pylint: disable=star-args
        login_parser = subcmd.add_parser('login', help=self.HELP['login'])
        login_parser.set_defaults(func=auth.login)
        logout_parser = subcmd.add_parser('logout', help=self.HELP['logout'])
        logout_parser.set_defaults(func=auth.logout)
        whoami_parser = subcmd.add_parser('whoami', help=self.HELP['whoami'])
        whoami_parser.set_defaults(func=auth.whoami)
        shell_parser = subcmd.add_parser('shell', help=self.HELP['shell'])
        shell_parser.set_defaults(func=launch_ipython_shell)
        shell_parser = subcmd.add_parser('test', help=self.HELP['test'])
        shell_parser.set_defaults(func=test_solve_api)

    def parse_args(self, args=None, namespace=None):
        """
            Try to parse the args first, and then add the subparsers. We want
            to do this so that we can check to see if there are any unknown
            args. We can assume that if, by this point, there are no unknown
            args, we can append shell to the unknown args as a default.
            However, to do this, we have to suppress stdout/stderr during the
            initial parsing, in case the user calls the help method (in which
            case we want to add the additional arguments and *then* call the
            help method. This is a hack to get around the fact that argparse
            doesn't allow default subcommands.
        """
        try:
            sys.stdout = sys.stderr = open(os.devnull, 'w')
            _, unknown_args = self.parse_known_args(args, namespace)
            if not unknown_args:
                args.insert(0, 'shell')
        except SystemExit:
            pass
        finally:
            sys.stdout.flush()
            sys.stderr.flush()
            sys.stdout, sys.stderr = sys.__stdout__, sys.__stderr__
        self._add_subcommands()
        return super(SolveArgumentParser, self).parse_args(args, namespace)

def test_solve_api(args):  # pylint: disable=unused-argument
    """ Test SolveBio API """
    DATASET = 'Clinvar/1.0.0/ClinVar'  # pylint: disable=invalid-name

    class TestFail(Exception):
        """ Custom Exception class for running basic tests """
        def __init__(self, *args, **kwargs):
            super(TestFail, self).__init__(*args, **kwargs)

    def run_and_verify(query_func, title='run a test', check_func=len):
        """ Function for running small tests with nice printing and checks """
        sys.stdout.write('Trying to {}...'.format(title))
        response = query_func()
        if not check_func(response):
            raise TestFail('Failed on {}'.format(DATASET))
        sys.stdout.write('\x1b[32mOK!\x1b[39m\n')
        return response

    creds = solvebio.credentials.get_credentials()
    if not creds:
        print('You must be logged in as a SolveBio user '
              'in order to run the test suite!')
    try:
        # try loading a dataset
        load_dataset = lambda: solvebio.Dataset.retrieve(DATASET)
        try:
            dataset = run_and_verify(load_dataset, 'load a dataset')
        except solvebio.errors.SolveError as exc:
            raise TestFail('Loading {} failed! ({})'.format(DATASET, exc))

        # run a basic query
        query = run_and_verify(dataset.query, 'run a basic query')

        # run a basic filter
        basic_filter = lambda: query.filter(clinical_significance='Pathogenic')
        run_and_verify(basic_filter, 'run a basic filter')

        # run a range filter
        range_filter = solvebio.RangeFilter(chromosome=1,
                                            start=100000,
                                            end=900000)
        run_and_verify(lambda: query.filter(range_filter),
                       'run a range filter')

    except TestFail as exc:
        print('\n\n\x1b[31mFAIL!\x1b[39m {}'.format(exc))

def launch_ipython_shell(args):  # pylint: disable=unused-argument
    """Open the SolveBio shell (IPython wrapper)"""
    try:
        from IPython.config.loader import Config
    except ImportError:
        print("The SolveBio Python shell requires IPython.\n"
              "To install, type: 'pip install ipython'")
        return

    try:
        # see if we're already inside IPython
        get_ipython  # pylint: disable=undefined-variable
    except NameError:
        cfg = Config()
        prompt_config = cfg.PromptManager
        prompt_config.in_template = '[SolveBio] In <\\#>: '
        prompt_config.in2_template = '   .\\D.: '
        prompt_config.out_template = 'Out<\\#>: '
        banner1 = 'SolveBio Python shell started.'
        exit_msg = 'Quitting SolveBio shell.'
    else:
        print("Running nested copies of IPython.")
        cfg = Config()
        banner1 = exit_msg = ''

    # First import the embeddable shell class
    try:
        from IPython.terminal.embed import InteractiveShellEmbed
    except ImportError:
        #pylint: disable=import-error,no-name-in-module
        from IPython.frontend.terminal.embed import InteractiveShellEmbed

    # Now create an instance of the embeddable shell. The first argument is a
    # string with options exactly as you would type them if you were starting
    # IPython at the system command line. Any parameters you want to define for
    # configuration can thus be specified here.
    InteractiveShellEmbed(config=cfg, banner1=banner1, exit_msg=exit_msg)()

def main(argv=sys.argv[1:]):
    """ Main entry point for SolveBio CLI """
    parser = SolveArgumentParser()
    args = parser.parse_args(argv)

    if args.api_host:
        solvebio.api_host = args.api_host
    if args.api_key:
        solvebio.api_key = args.api_key

    args.func(args)

if __name__ == '__main__':
    main()
<commit_msg>fix range query in tests<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Main file for SolveBio CLI """
#from __future__ import print_function

import os
import sys
import argparse

import solvebio

from . import auth

class SolveArgumentParser(argparse.ArgumentParser):
    """Main parser for the SolveBio command line client"""
    HELP = {
        'login': 'Login and save credentials',
        'logout': 'Logout and delete saved credentials',
        'whoami': 'Show your SolveBio email address',
        'shell': 'Open the SolveBio Python shell',
        'test': 'Make sure the SolveBio API is working correctly',
        'version': '%(prog)s {}'.format(solvebio.version.VERSION),
        'api_host': 'Override the default SolveBio API host',
        'api_key': 'Manually provide a SolveBio API key'
    }

    def __init__(self, *args, **kwargs):
        super(SolveArgumentParser, self).__init__(*args, **kwargs)
        self._optionals.title = 'SolveBio Options'
        self.add_argument('--version', action='version',
                          version=self.HELP['version'])
        self.add_argument('--api-host', help=self.HELP['api_host'])
        self.add_argument('--api-key', help=self.HELP['api_key'])

    def _add_subcommands(self):
        """
            The _add_subcommands method must be separate from the __init__
            method, as infinite recursion will occur otherwise, due to the fact
            that the __init__ method itself will be called when instantiating
            a subparser, as we do below
        """
        subcmd_params = {
            'title': 'SolveBio Commands',
            'dest': 'subcommands'
        }
        subcmd = self.add_subparsers(
            **subcmd_params)  # pylint: disable=star-args
        login_parser = subcmd.add_parser('login', help=self.HELP['login'])
        login_parser.set_defaults(func=auth.login)
        logout_parser = subcmd.add_parser('logout', help=self.HELP['logout'])
        logout_parser.set_defaults(func=auth.logout)
        whoami_parser = subcmd.add_parser('whoami', help=self.HELP['whoami'])
        whoami_parser.set_defaults(func=auth.whoami)
        shell_parser = subcmd.add_parser('shell', help=self.HELP['shell'])
        shell_parser.set_defaults(func=launch_ipython_shell)
        shell_parser = subcmd.add_parser('test', help=self.HELP['test'])
        shell_parser.set_defaults(func=test_solve_api)

    def parse_args(self, args=None, namespace=None):
        """
            Try to parse the args first, and then add the subparsers. We want
            to do this so that we can check to see if there are any unknown
            args. We can assume that if, by this point, there are no unknown
            args, we can append shell to the unknown args as a default.
            However, to do this, we have to suppress stdout/stderr during the
            initial parsing, in case the user calls the help method (in which
            case we want to add the additional arguments and *then* call the
            help method. This is a hack to get around the fact that argparse
            doesn't allow default subcommands.
        """
        try:
            sys.stdout = sys.stderr = open(os.devnull, 'w')
            _, unknown_args = self.parse_known_args(args, namespace)
            if not unknown_args:
                args.insert(0, 'shell')
        except SystemExit:
            pass
        finally:
            sys.stdout.flush()
            sys.stderr.flush()
            sys.stdout, sys.stderr = sys.__stdout__, sys.__stderr__
        self._add_subcommands()
        return super(SolveArgumentParser, self).parse_args(args, namespace)

def test_solve_api(args):  # pylint: disable=unused-argument
    """ Test SolveBio API """
    DATASET = 'ClinVar/2.0.0-1/Variants'  # pylint: disable=invalid-name

    class TestFail(Exception):
        """ Custom Exception class for running basic tests """
        def __init__(self, *args, **kwargs):
            super(TestFail, self).__init__(*args, **kwargs)

    def run_and_verify(query_func, title='run a test', check_func=len):
        """ Function for running small tests with nice printing and checks """
        sys.stdout.write('Trying to {}...'.format(title))
        response = query_func()
        if not check_func(response):
            raise TestFail('Failed on {}'.format(DATASET))
        sys.stdout.write('\x1b[32mOK!\x1b[39m\n')
        return response

    creds = solvebio.credentials.get_credentials()
    if not creds:
        print('You must be logged in as a SolveBio user '
              'in order to run the test suite!')
    try:
        # try loading a dataset
        load_dataset = lambda: solvebio.Dataset.retrieve(DATASET)
        try:
            dataset = run_and_verify(load_dataset, 'load a dataset')
        except solvebio.errors.SolveError as exc:
            raise TestFail('Loading {} failed! ({})'.format(DATASET, exc))

        # run a basic query
        query = run_and_verify(dataset.query, 'run a basic query')

        # run a basic filter
        basic_filter = lambda: query.filter(clinical_significance='Pathogenic')
        run_and_verify(basic_filter, 'run a basic filter')

        # run a range filter
        range_filter = solvebio.RangeFilter(build="hg19",
                                            chromosome=1,
                                            start=100000,
                                            end=900000)
        run_and_verify(lambda: query.filter(range_filter),
                       'run a range filter')

    except TestFail as exc:
        print('\n\n\x1b[31mFAIL!\x1b[39m {}'.format(exc))

def launch_ipython_shell(args):  # pylint: disable=unused-argument
    """Open the SolveBio shell (IPython wrapper)"""
    try:
        from IPython.config.loader import Config
    except ImportError:
        print("The SolveBio Python shell requires IPython.\n"
              "To install, type: 'pip install ipython'")
        return

    try:
        # see if we're already inside IPython
        get_ipython  # pylint: disable=undefined-variable
    except NameError:
        cfg = Config()
        prompt_config = cfg.PromptManager
        prompt_config.in_template = '[SolveBio] In <\\#>: '
        prompt_config.in2_template = '   .\\D.: '
        prompt_config.out_template = 'Out<\\#>: '
        banner1 = 'SolveBio Python shell started.'
        exit_msg = 'Quitting SolveBio shell.'
    else:
        print("Running nested copies of IPython.")
        cfg = Config()
        banner1 = exit_msg = ''

    # First import the embeddable shell class
    try:
        from IPython.terminal.embed import InteractiveShellEmbed
    except ImportError:
        #pylint: disable=import-error,no-name-in-module
        from IPython.frontend.terminal.embed import InteractiveShellEmbed

    # Now create an instance of the embeddable shell. The first argument is a
    # string with options exactly as you would type them if you were starting
    # IPython at the system command line. Any parameters you want to define for
    # configuration can thus be specified here.
    InteractiveShellEmbed(config=cfg, banner1=banner1, exit_msg=exit_msg)()

def main(argv=sys.argv[1:]):
    """ Main entry point for SolveBio CLI """
    parser = SolveArgumentParser()
    args = parser.parse_args(argv)

    if args.api_host:
        solvebio.api_host = args.api_host
    if args.api_key:
        solvebio.api_key = args.api_key

    args.func(args)

if __name__ == '__main__':
    main()
<|endoftext|>


<commit_before>'''
Used to generate variable data such as random strings and ids
'''
# Import python libs
import os
import time
import random
import struct
import binascii
import datetime

# create a standard epoch so all platforms will count ids from
# a standard epoch of jan 1 2014
STD_EPOCH = time.mktime(datetime.datetime(2014, 1, 1).timetuple()) * 1000000

def rand_hex_str(size):
    '''
    Return a random string of the passed size using hex encoding
    '''
    return binascii.hexlify(os.urandom(size/2))

def rand_raw_str(size):
    '''
    Return a raw byte string of the given size
    '''
    return os.urandom(size)

def gen_id():
    '''
    Return a revision based on timestamp
    '''
    r_time = time.time() * 1000000 - STD_EPOCH
    return struct.pack('>HQ', random.randint(0, 65535), r_time).encode('hex')
<commit_msg>Add random dict generator function<commit_after>'''
Used to generate variable data such as random strings and ids
'''
# Import python libs
import os
import time
import random
import struct
import binascii
import datetime

# create a standard epoch so all platforms will count ids from
# a standard epoch of jan 1 2014
STD_EPOCH = time.mktime(datetime.datetime(2014, 1, 1).timetuple()) * 1000000

def rand_hex_str(size):
    '''
    Return a random string of the passed size using hex encoding
    '''
    return binascii.hexlify(os.urandom(size/2))

def rand_raw_str(size):
    '''
    Return a raw byte string of the given size
    '''
    return os.urandom(size)

def gen_id():
    '''
    Return a revision based on timestamp
    '''
    r_time = time.time() * 1000000 - STD_EPOCH
    return struct.pack('>HQ', random.randint(0, 65535), r_time).encode('hex')

def rand_dict():
    '''
    Populate a dict with random data, types etc for testing
    '''
    deep = random.randint(0, 100)
    ret = {}
    top = ret
    for ind in range(deep):
        key = rand_hex_str(random.randint(0, 50))
        top[key] = {}
        top = top[key]
    return ret
<|endoftext|>


<commit_before>"""
This is pure python implementation of bubble sort algorithm

For doctests run following command:
python -m doctest -v bubble_sort.py
or
python3 -m doctest -v bubble_sort.py

For manual testing run:
python bubble_sort.py
"""
from __future__ import print_function

def bubble_sort(collection):
    """Pure implementation of bubble sort algorithm in Python

    :param collection: some mutable ordered collection with heterogeneous
    comparable items inside
    :return: the same collection ordered by ascending

    Examples:
    >>> bubble_sort([0, 5, 3, 2, 2])
    [0, 2, 2, 3, 5]

    >>> bubble_sort([])
    []

    >>> bubble_sort([-2, -5, -45])
    [-45, -5, -2]
    """
    length = len(collection)
    for i in range(length-1):
        for j in range(length-1):
            if collection[j] > collection[j+1]:
                collection[j], collection[j+1] = collection[j+1], collection[j]

    return collection

if __name__ == '__main__':
    import sys
    # For python 2.x and 3.x compatibility: 3.x has not raw_input builtin
    # otherwise 2.x's input builtin function is too "smart"
    if sys.version_info.major < 3:
        input_function = raw_input
    else:
        input_function = input

    user_input = input_function('Enter numbers separated by a comma:\n')
    unsorted = [int(item) for item in user_input.split(',')]
    print(bubble_sort(unsorted))
<commit_msg>Revert "Update bubble_sort.py"<commit_after>"""
This is pure python implementation of bubble sort algorithm

For doctests run following command:
python -m doctest -v bubble_sort.py
or
python3 -m doctest -v bubble_sort.py

For manual testing run:
python bubble_sort.py
"""
from __future__ import print_function

def bubble_sort(collection):
    """Pure implementation of bubble sort algorithm in Python

    :param collection: some mutable ordered collection with heterogeneous
    comparable items inside
    :return: the same collection ordered by ascending

    Examples:
    >>> bubble_sort([0, 5, 3, 2, 2])
    [0, 2, 2, 3, 5]

    >>> bubble_sort([])
    []

    >>> bubble_sort([-2, -5, -45])
    [-45, -5, -2]
    """
    length = len(collection)
    for i in range(length):
        for j in range(length-1):
            if collection[j] > collection[j+1]:
                collection[j], collection[j+1] = collection[j+1], collection[j]

    return collection

if __name__ == '__main__':
    import sys
    # For python 2.x and 3.x compatibility: 3.x has not raw_input builtin
    # otherwise 2.x's input builtin function is too "smart"
    if sys.version_info.major < 3:
        input_function = raw_input
    else:
        input_function = input

    user_input = input_function('Enter numbers separated by a comma:\n')
    unsorted = [int(item) for item in user_input.split(',')]
    print(bubble_sort(unsorted))
<|endoftext|>