<commit_before>#! /usr/bin/python3

import sys
import os
import threading
import decimal
import time
import json
import re
import requests
import collections
import logging
import binascii
from datetime import datetime
from dateutil.tz import tzlocal
import argparse
import configparser
import appdirs
import tarfile
import urllib.request
import shutil
import codecs

from counterpartylib.lib import log
logger = logging.getLogger(__name__)
log.set_up(logger)

D = decimal.Decimal

from counterpartylib import server
from counterpartylib.lib import config
from counterpartylib.lib.util import value_input, value_output

rpc_sessions = {}

class JsonDecimalEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o,  D):
            return str(o)
        return super(JsonDecimalEncoder, self).default(o)

json_dump = lambda x: json.dumps(x, sort_keys=True, indent=4, cls=JsonDecimalEncoder)
json_print = lambda x: print(json_dump(x))

class RPCError(Exception):
    pass
class AssetError(Exception):
    pass

def rpc(url, method, params=None, ssl_verify=False):
    headers = {'content-type': 'application/json'}
    payload = {
        "method": method,
        "params": params,
        "jsonrpc": "2.0",
        "id": 0,
    }

    if url not in rpc_sessions:
        rpc_session = requests.Session()
        rpc_sessions[url] = rpc_session
    else:
    	rpc_session = rpc_sessions[url]

    response = None
    TRIES = 12
    for i in range(TRIES):
        try:
            response = rpc_session.post(url + '/rpc/', data=json.dumps(payload), headers=headers, verify=ssl_verify)
            if i > 0:
                logger.debug('Successfully connected.')
            break
        except requests.exceptions.SSLError as e:
            raise e
        except requests.exceptions.ConnectionError:
            logger.debug('Could not connect to {}. (Try {}/{})'.format(url, i+1, TRIES))
            time.sleep(5)

    if response == None:
        raise RPCError('Cannot communicate with {}.'.format(url))
    elif response.status_code not in (200, 500):
        raise RPCError(str(response.status_code) + ' ' + response.reason + ' ' + response.text)

    # Return result, with error handling.
    response_json = response.json()
    if 'error' not in response_json.keys() or response_json['error'] == None:
        return response_json['result']
    else:
        raise RPCError('{}'.format(response_json['error']))

def api(method, params=None):
    return rpc(config.COUNTERPARTY_RPC, method, params=params, ssl_verify=config.COUNTERPARTY_RPC_SSL_VERIFY)

def is_divisible(asset):
    if asset in (config.BTC, config.XCP, 'leverage', 'value', 'fraction', 'price', 'odds'):
        return True
    else:
        sql = '''SELECT * FROM issuances WHERE (status = ? AND asset = ?)'''
        bindings = ['valid', asset]
        issuances = api('sql', {'query': sql, 'bindings': bindings})

        if not issuances: raise AssetError('No such asset: {}'.format(asset))
        return issuances[0]['divisible']

def value_in(quantity, asset, divisible=None):
    if divisible is None:
        divisible = is_divisible(asset)
    return value_input(quantity, asset, divisible)

def value_out(quantity, asset, divisible=None):
    if divisible is None:
        divisible = is_divisible(asset)
    return value_output(quantity, asset, divisible)

def bootstrap(testnet=False, overwrite=True, ask_confirmation=False):
    data_dir = appdirs.user_data_dir(appauthor=config.XCP_NAME, appname=config.APP_NAME, roaming=True)

    # Set Constants.
    if testnet:
        BOOTSTRAP_URL = 'https://s3.amazonaws.com/counterparty-bootstrap/counterpartyd-testnet-db.latest.tar.gz'
        TARBALL_FILENAME = 'counterpartyd-testnet-db.latest.tar.gz'
        DATABASE_FILENAME = 'counterpartyd.9.testnet.db'
        DATABASE_PATH = os.path.join(data_dir, '{}.testnet.db'.format(config.APP_NAME))
    else:
        BOOTSTRAP_URL = 'https://s3.amazonaws.com/counterparty-bootstrap/counterpartyd-db.latest.tar.gz'
        TARBALL_FILENAME = 'counterpartyd-db.latest.tar.gz'
        DATABASE_FILENAME = 'counterpartyd.9.db'
        DATABASE_PATH = os.path.join(data_dir, '{}.db'.format(config.APP_NAME))

    # Prepare Directory.
    if not os.path.exists(data_dir):
        os.makedirs(data_dir, mode=0o755)
    if not overwrite and os.path.exists(DATABASE_PATH):
        return

    # Define Progress Bar.
    def reporthook(blocknum, blocksize, totalsize):
        readsofar = blocknum * blocksize
        if totalsize > 0:
            percent = readsofar * 1e2 / totalsize
            s = "\r%5.1f%% %*d / %d" % (
                percent, len(str(totalsize)), readsofar, totalsize)
            sys.stderr.write(s)
            if readsofar >= totalsize: # near the end
                sys.stderr.write("\n")
        else: # total size is unknown
            sys.stderr.write("read %d\n" % (readsofar,))

    print('Downloading database from {}...'.format(BOOTSTRAP_URL))
    urllib.request.urlretrieve(BOOTSTRAP_URL, TARBALL_FILENAME, reporthook)

    print('Extracting...')
    with tarfile.open(TARBALL_FILENAME, 'r:gz') as tar_file:
        tar_file.extractall()

    print('Copying {} to {}...'.format(DATABASE_FILENAME, DATABASE_PATH))
    shutil.move(DATABASE_FILENAME, DATABASE_PATH)
    os.chmod(DATABASE_PATH, 0o660)

    # Clean files.
    os.remove(TARBALL_FILENAME)
    os.remove('checksums.txt')

# Set default values of command line arguments with config file
def add_config_arguments(arg_parser, config_args, default_config_file, config_file_arg_name='config_file'):
    cmd_args = arg_parser.parse_known_args()[0]

    config_file = getattr(cmd_args, config_file_arg_name, None)
    if not config_file:
        config_dir = appdirs.user_config_dir(appauthor=config.XCP_NAME, appname=config.APP_NAME, roaming=True)
        if not os.path.isdir(config_dir):
            os.makedirs(config_dir, mode=0o755)
        config_file = os.path.join(config_dir, default_config_file)

    # clean BOM
    BUFSIZE = 4096
    BOMLEN = len(codecs.BOM_UTF8)
    with codecs.open(config_file, 'r+b') as fp:
        chunk = fp.read(BUFSIZE)
        if chunk.startswith(codecs.BOM_UTF8):
            i = 0
            chunk = chunk[BOMLEN:]
            while chunk:
                fp.seek(i)
                fp.write(chunk)
                i += len(chunk)
                fp.seek(BOMLEN, os.SEEK_CUR)
                chunk = fp.read(BUFSIZE)
            fp.seek(-BOMLEN, os.SEEK_CUR)
            fp.truncate()

    logger.debug('Loading configuration file: `{}`'.format(config_file))
    configfile = configparser.ConfigParser()
    with codecs.open(config_file, 'r', encoding='utf8') as fp:
        configfile.readfp(fp)

    if not 'Default' in configfile:
        configfile['Default'] = {}

    # Initialize default values with the config file.
    for arg in config_args:
        key = arg[0][-1].replace('--', '')
        if 'action' in arg[1] and arg[1]['action'] == 'store_true' and key in configfile['Default']:
            arg[1]['default'] = configfile['Default'].getboolean(key)
        elif key in configfile['Default'] and configfile['Default'][key]:
            arg[1]['default'] = configfile['Default'][key]
        arg_parser.add_argument(*arg[0], **arg[1])

    return arg_parser

# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
<commit_msg>update the bootstrap routine to work (.9. filename part removed), and extract to the system tempdir instead of pwd<commit_after>#! /usr/bin/python3

import sys
import os
import threading
import decimal
import time
import json
import re
import requests
import collections
import logging
import binascii
from datetime import datetime
from dateutil.tz import tzlocal
import argparse
import configparser
import appdirs
import tarfile
import urllib.request
import shutil
import codecs
import tempfile

from counterpartylib.lib import log
logger = logging.getLogger(__name__)
log.set_up(logger)

D = decimal.Decimal

from counterpartylib import server
from counterpartylib.lib import config
from counterpartylib.lib.util import value_input, value_output

rpc_sessions = {}

class JsonDecimalEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o,  D):
            return str(o)
        return super(JsonDecimalEncoder, self).default(o)

json_dump = lambda x: json.dumps(x, sort_keys=True, indent=4, cls=JsonDecimalEncoder)
json_print = lambda x: print(json_dump(x))

class RPCError(Exception):
    pass
class AssetError(Exception):
    pass

def rpc(url, method, params=None, ssl_verify=False):
    headers = {'content-type': 'application/json'}
    payload = {
        "method": method,
        "params": params,
        "jsonrpc": "2.0",
        "id": 0,
    }

    if url not in rpc_sessions:
        rpc_session = requests.Session()
        rpc_sessions[url] = rpc_session
    else:
    	rpc_session = rpc_sessions[url]

    response = None
    TRIES = 12
    for i in range(TRIES):
        try:
            response = rpc_session.post(url + '/rpc/', data=json.dumps(payload), headers=headers, verify=ssl_verify)
            if i > 0:
                logger.debug('Successfully connected.')
            break
        except requests.exceptions.SSLError as e:
            raise e
        except requests.exceptions.ConnectionError:
            logger.debug('Could not connect to {}. (Try {}/{})'.format(url, i+1, TRIES))
            time.sleep(5)

    if response == None:
        raise RPCError('Cannot communicate with {}.'.format(url))
    elif response.status_code not in (200, 500):
        raise RPCError(str(response.status_code) + ' ' + response.reason + ' ' + response.text)

    # Return result, with error handling.
    response_json = response.json()
    if 'error' not in response_json.keys() or response_json['error'] == None:
        return response_json['result']
    else:
        raise RPCError('{}'.format(response_json['error']))

def api(method, params=None):
    return rpc(config.COUNTERPARTY_RPC, method, params=params, ssl_verify=config.COUNTERPARTY_RPC_SSL_VERIFY)

def is_divisible(asset):
    if asset in (config.BTC, config.XCP, 'leverage', 'value', 'fraction', 'price', 'odds'):
        return True
    else:
        sql = '''SELECT * FROM issuances WHERE (status = ? AND asset = ?)'''
        bindings = ['valid', asset]
        issuances = api('sql', {'query': sql, 'bindings': bindings})

        if not issuances: raise AssetError('No such asset: {}'.format(asset))
        return issuances[0]['divisible']

def value_in(quantity, asset, divisible=None):
    if divisible is None:
        divisible = is_divisible(asset)
    return value_input(quantity, asset, divisible)

def value_out(quantity, asset, divisible=None):
    if divisible is None:
        divisible = is_divisible(asset)
    return value_output(quantity, asset, divisible)

def bootstrap(testnet=False, overwrite=True, ask_confirmation=False):
    data_dir = appdirs.user_data_dir(appauthor=config.XCP_NAME, appname=config.APP_NAME, roaming=True)

    # Set Constants.
    if testnet:
        BOOTSTRAP_URL = 'https://s3.amazonaws.com/counterparty-bootstrap/counterpartyd-testnet-db.latest.tar.gz'
        TARBALL_PATH = os.path.join(tempfile.gettempdir(), 'counterpartyd-testnet-db.latest.tar.gz')
        DATABASE_PATH = os.path.join(data_dir, '{}.testnet.db'.format(config.APP_NAME))
    else:
        BOOTSTRAP_URL = 'https://s3.amazonaws.com/counterparty-bootstrap/counterpartyd-db.latest.tar.gz'
        TARBALL_PATH = os.path.join(tempfile.gettempdir(), 'counterpartyd-db.latest.tar.gz')
        DATABASE_PATH = os.path.join(data_dir, '{}.db'.format(config.APP_NAME))

    # Prepare Directory.
    if not os.path.exists(data_dir):
        os.makedirs(data_dir, mode=0o755)
    if not overwrite and os.path.exists(DATABASE_PATH):
        return

    # Define Progress Bar.
    def reporthook(blocknum, blocksize, totalsize):
        readsofar = blocknum * blocksize
        if totalsize > 0:
            percent = readsofar * 1e2 / totalsize
            s = "\r%5.1f%% %*d / %d" % (
                percent, len(str(totalsize)), readsofar, totalsize)
            sys.stderr.write(s)
            if readsofar >= totalsize: # near the end
                sys.stderr.write("\n")
        else: # total size is unknown
            sys.stderr.write("read %d\n" % (readsofar,))

    print('Downloading database from {}...'.format(BOOTSTRAP_URL))
    urllib.request.urlretrieve(BOOTSTRAP_URL, TARBALL_PATH, reporthook)

    print('Extracting to "%s"...' % data_dir)
    with tarfile.open(TARBALL_PATH, 'r:gz') as tar_file:
        tar_file.extractall(path=data_dir)

    assert os.path.exists(DATABASE_PATH)
    os.chmod(DATABASE_PATH, 0o660)

    print('Cleaning up...')
    os.remove(TARBALL_PATH)
    os.remove(os.path.join(data_dir, 'checksums.txt'))

# Set default values of command line arguments with config file
def add_config_arguments(arg_parser, config_args, default_config_file, config_file_arg_name='config_file'):
    cmd_args = arg_parser.parse_known_args()[0]

    config_file = getattr(cmd_args, config_file_arg_name, None)
    if not config_file:
        config_dir = appdirs.user_config_dir(appauthor=config.XCP_NAME, appname=config.APP_NAME, roaming=True)
        if not os.path.isdir(config_dir):
            os.makedirs(config_dir, mode=0o755)
        config_file = os.path.join(config_dir, default_config_file)

    # clean BOM
    BUFSIZE = 4096
    BOMLEN = len(codecs.BOM_UTF8)
    with codecs.open(config_file, 'r+b') as fp:
        chunk = fp.read(BUFSIZE)
        if chunk.startswith(codecs.BOM_UTF8):
            i = 0
            chunk = chunk[BOMLEN:]
            while chunk:
                fp.seek(i)
                fp.write(chunk)
                i += len(chunk)
                fp.seek(BOMLEN, os.SEEK_CUR)
                chunk = fp.read(BUFSIZE)
            fp.seek(-BOMLEN, os.SEEK_CUR)
            fp.truncate()

    logger.debug('Loading configuration file: `{}`'.format(config_file))
    configfile = configparser.ConfigParser()
    with codecs.open(config_file, 'r', encoding='utf8') as fp:
        configfile.readfp(fp)

    if not 'Default' in configfile:
        configfile['Default'] = {}

    # Initialize default values with the config file.
    for arg in config_args:
        key = arg[0][-1].replace('--', '')
        if 'action' in arg[1] and arg[1]['action'] == 'store_true' and key in configfile['Default']:
            arg[1]['default'] = configfile['Default'].getboolean(key)
        elif key in configfile['Default'] and configfile['Default'][key]:
            arg[1]['default'] = configfile['Default'][key]
        arg_parser.add_argument(*arg[0], **arg[1])

    return arg_parser

# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
<|endoftext|>


<commit_before>from conans.errors import ConanException, NotFoundException
from conans.model.conan_file import ConanFile
import inspect
import uuid
import imp
import os
from conans.util.files import load
from conans.paths import CONANFILE_TXT
from conans.util.config_parser import ConfigParser
from conans.model.options import OptionsValues
from conans.model.ref import ConanFileReference
from conans.model.settings import Settings

class ConanFileLoader(object):
    def __init__(self, output, runner, settings, options):
        '''
        param settings: Settings object, to assign to ConanFile at load time
        param options: OptionsValues, necessary so the base conanfile loads the options
                        to start propagation, and having them in order to call build()
        '''

        self._output = output
        self._runner = runner
        assert isinstance(settings, Settings)
        assert isinstance(options, OptionsValues)
        self._settings = settings
        self._options = options

    def _create_check_conan(self, conan_file, consumer):
        """ Check the integrity of a given conanfile
        """
        result = None
        for name, attr in conan_file.__dict__.iteritems():
            if "_" in name:
                continue
            if inspect.isclass(attr) and issubclass(attr, ConanFile) and attr != ConanFile:
                if result is None:
                    # Actual instantiation of ConanFile object
                    result = attr(self._output, self._runner, self._settings.copy())
                else:
                    raise ConanException("More than 1 conanfile in the file")

        if result is None:
            raise ConanException("No subclass of ConanFile")

        # check name and version were specified
        if not consumer:
            if not hasattr(result, "name") or not result.name:
                raise ConanException("conanfile didn't specify name")
            if not hasattr(result, "version") or not result.version:
                raise ConanException("conanfile didn't specify version")

        return result

    def load_conan(self, conan_file_path, consumer=False):
        """ loads a ConanFile object from the given file
        """
        # Check if precompiled exist, delete it
        if os.path.exists(conan_file_path + "c"):
            os.unlink(conan_file_path + "c")

        if not os.path.exists(conan_file_path):
            raise NotFoundException("%s not found!" % conan_file_path)

        # We have to generate a new name for each conans
        module_id = uuid.uuid1()
        try:
            loaded = imp.load_source("conan_conan%s" % module_id, conan_file_path)
        except Exception:
            import traceback
            trace = traceback.format_exc().split('\n')
            raise ConanException("Unable to load conanfile in %s\n%s" % (conan_file_path,
                                                                         '\n'.join(trace[3:])))
        try:
            result = self._create_check_conan(loaded, consumer)
            if consumer:
                result.options.initialize_upstream(self._options)
            return result
        except Exception as e:  # re-raise with file name
            raise ConanException("%s: %s" % (conan_file_path, str(e)))

    def load_conan_txt(self, conan_requirements_path):

        if not os.path.exists(conan_requirements_path):
            raise NotFoundException("%s not found!" % CONANFILE_TXT)

        conanfile = ConanFile(self._output, self._runner, self._settings.copy())

        parser = ConanFileTextLoader(load(conan_requirements_path))
        for requirement_text in parser.requirements:
            ConanFileReference.loads(requirement_text)  # Raise if invalid
            conanfile.requires.add(requirement_text)

        conanfile.generators = parser.generators

        options = OptionsValues.loads(parser.options)
        conanfile.options.values = options
        conanfile.options.initialize_upstream(self._options)

        # imports method
        conanfile.imports = ConanFileTextLoader.imports_method(conanfile,
                                                               parser.import_parameters)

        return conanfile

class ConanFileTextLoader(object):
    """Parse a plain requirements file"""

    def __init__(self, input_text):
        # Prefer composition over inheritance, the __getattr__ was breaking things
        self._config_parser = ConfigParser(input_text,  ["requires", "generators", "options",
                                                         "imports"])

    @property
    def requirements(self):
        """returns a list of requires
        EX:  "OpenCV/2.4.10@phil/stable"
        """
        return [r.strip() for r in self._config_parser.requires.splitlines()]

    @property
    def options(self):
        return self._config_parser.options

    @property
    def import_parameters(self):
        ret = []
        local_install_text = self._config_parser.imports
        for local_install_line in local_install_text.splitlines():
            invalid_line_msg = "Invalid imports line: %s" \
                               "\nEX: OpenCV/lib, * -> ./lib" % local_install_line
            try:
                if local_install_line.startswith("/") or local_install_line.startswith(".."):
                    raise ConanException("Import's paths can't begin with '/' or '..'")
                pair = local_install_line.split("->")
                source = pair[0].strip().split(',', 1)
                dest = pair[1].strip()
                src, pattern = source[0].strip(), source[1].strip()
                ret.append((pattern, dest, src))
            except ConanException as excp:
                raise ConanException("%s\n%s" % (invalid_line_msg, excp.message))
            except:
                raise ConanException(invalid_line_msg)
        return ret

    @property
    def generators(self):
        return self._config_parser.generators.splitlines()

    @staticmethod
    def imports_method(conan_file, parameters):
        def imports():
            for import_params in parameters:
                conan_file.copy(*import_params)
        return imports
<commit_msg>Add conanfile_directory to conan file when it is loaded so that it can be referenced later<commit_after>from conans.errors import ConanException, NotFoundException
from conans.model.conan_file import ConanFile
import inspect
import uuid
import imp
import os
from conans.util.files import load
from conans.paths import CONANFILE_TXT
from conans.util.config_parser import ConfigParser
from conans.model.options import OptionsValues
from conans.model.ref import ConanFileReference
from conans.model.settings import Settings

class ConanFileLoader(object):
    def __init__(self, output, runner, settings, options):
        '''
        param settings: Settings object, to assign to ConanFile at load time
        param options: OptionsValues, necessary so the base conanfile loads the options
                        to start propagation, and having them in order to call build()
        '''

        self._output = output
        self._runner = runner
        assert isinstance(settings, Settings)
        assert isinstance(options, OptionsValues)
        self._settings = settings
        self._options = options

    def _create_check_conan(self, conan_file, consumer):
        """ Check the integrity of a given conanfile
        """
        result = None
        for name, attr in conan_file.__dict__.iteritems():
            if "_" in name:
                continue
            if inspect.isclass(attr) and issubclass(attr, ConanFile) and attr != ConanFile:
                if result is None:
                    # Actual instantiation of ConanFile object
                    result = attr(self._output, self._runner, self._settings.copy())
                else:
                    raise ConanException("More than 1 conanfile in the file")

        if result is None:
            raise ConanException("No subclass of ConanFile")

        # check name and version were specified
        if not consumer:
            if not hasattr(result, "name") or not result.name:
                raise ConanException("conanfile didn't specify name")
            if not hasattr(result, "version") or not result.version:
                raise ConanException("conanfile didn't specify version")

        return result

    def load_conan(self, conan_file_path, consumer=False):
        """ loads a ConanFile object from the given file
        """
        # Check if precompiled exist, delete it
        if os.path.exists(conan_file_path + "c"):
            os.unlink(conan_file_path + "c")

        if not os.path.exists(conan_file_path):
            raise NotFoundException("%s not found!" % conan_file_path)

        # We have to generate a new name for each conans
        module_id = uuid.uuid1()
        try:
            loaded = imp.load_source("conan_conan%s" % module_id, conan_file_path)
        except Exception:
            import traceback
            trace = traceback.format_exc().split('\n')
            raise ConanException("Unable to load conanfile in %s\n%s" % (conan_file_path,
                                                                         '\n'.join(trace[3:])))
        try:
            result = self._create_check_conan(loaded, consumer)
            if consumer:
                result.options.initialize_upstream(self._options)
	    type(result).conanfile_directory = property(lambda self, _path=conan_file_path: os.path.dirname(_path))
            return result
        except Exception as e:  # re-raise with file name
            raise ConanException("%s: %s" % (conan_file_path, str(e)))

    def load_conan_txt(self, conan_requirements_path):

        if not os.path.exists(conan_requirements_path):
            raise NotFoundException("%s not found!" % CONANFILE_TXT)

        conanfile = ConanFile(self._output, self._runner, self._settings.copy())

        parser = ConanFileTextLoader(load(conan_requirements_path))
        for requirement_text in parser.requirements:
            ConanFileReference.loads(requirement_text)  # Raise if invalid
            conanfile.requires.add(requirement_text)

        conanfile.generators = parser.generators

        options = OptionsValues.loads(parser.options)
        conanfile.options.values = options
        conanfile.options.initialize_upstream(self._options)

        # imports method
        conanfile.imports = ConanFileTextLoader.imports_method(conanfile,
                                                               parser.import_parameters)

        return conanfile

class ConanFileTextLoader(object):
    """Parse a plain requirements file"""

    def __init__(self, input_text):
        # Prefer composition over inheritance, the __getattr__ was breaking things
        self._config_parser = ConfigParser(input_text,  ["requires", "generators", "options",
                                                         "imports"])

    @property
    def requirements(self):
        """returns a list of requires
        EX:  "OpenCV/2.4.10@phil/stable"
        """
        return [r.strip() for r in self._config_parser.requires.splitlines()]

    @property
    def options(self):
        return self._config_parser.options

    @property
    def import_parameters(self):
        ret = []
        local_install_text = self._config_parser.imports
        for local_install_line in local_install_text.splitlines():
            invalid_line_msg = "Invalid imports line: %s" \
                               "\nEX: OpenCV/lib, * -> ./lib" % local_install_line
            try:
                if local_install_line.startswith("/") or local_install_line.startswith(".."):
                    raise ConanException("Import's paths can't begin with '/' or '..'")
                pair = local_install_line.split("->")
                source = pair[0].strip().split(',', 1)
                dest = pair[1].strip()
                src, pattern = source[0].strip(), source[1].strip()
                ret.append((pattern, dest, src))
            except ConanException as excp:
                raise ConanException("%s\n%s" % (invalid_line_msg, excp.message))
            except:
                raise ConanException(invalid_line_msg)
        return ret

    @property
    def generators(self):
        return self._config_parser.generators.splitlines()

    @staticmethod
    def imports_method(conan_file, parameters):
        def imports():
            for import_params in parameters:
                conan_file.copy(*import_params)
        return imports
<|endoftext|>


<commit_before>"""Pylint plugin for ConanFile"""
import re

import astroid
from astroid import MANAGER
from pylint.checkers import BaseChecker
from pylint.interfaces import IRawChecker

def register(linter):
    """required method to auto register this checker"""
    linter.register_checker(ConanDeprecatedImportsChecker(linter))

def transform_conanfile(node):
    """Transform definition of ConanFile class so dynamic fields are visible to pylint"""

    str_class = astroid.builtin_lookup("str")
    info_class = MANAGER.ast_from_module_name("conans.model.info").lookup(
        "ConanInfo")
    build_requires_class = MANAGER.ast_from_module_name(
        "conans.client.graph.graph_manager").lookup("_RecipeBuildRequires")
    file_copier_class = MANAGER.ast_from_module_name(
        "conans.client.file_copier").lookup("FileCopier")
    file_importer_class = MANAGER.ast_from_module_name(
        "conans.client.importer").lookup("_FileImporter")
    python_requires_class = MANAGER.ast_from_module_name(
        "conans.client.graph.python_requires").lookup("PyRequires")

    dynamic_fields = {
        "conan_data": str_class,
        "build_requires": build_requires_class,
        "info_build": info_class,
        "info": info_class,
        "copy": file_copier_class,
        "copy_deps": file_importer_class,
        "python_requires": [str_class, python_requires_class],
        "recipe_folder": str_class,
    }

    for f, t in dynamic_fields.items():
        node.locals[f] = [t]

MANAGER.register_transform(
    astroid.ClassDef, transform_conanfile,
    lambda node: node.qname() == "conans.model.conan_file.ConanFile")

def _python_requires_member():
    return astroid.parse("""
        from conans.client.graph.python_requires import ConanPythonRequire
        python_requires = ConanPythonRequire()
        """)

astroid.register_module_extender(astroid.MANAGER, "conans", _python_requires_member)

class ConanDeprecatedImportsChecker(BaseChecker):
    """
    Check "from conans*" imports which disappears in Conan 2.x. Only "from conan*" is valid
    """

    __implements__ = IRawChecker

    deprecated_imports_pattern = re.compile(r"(from|import)\s+conans[\.|\s].*")
    name = "conan_deprecated_imports"
    msgs = {
        "E9000": (
            "Using deprecated imports from 'conans'",
            "conan1.x-deprecated-imports",
            (
                "Use imports from 'conan' instead of 'conans'"
                " because 'conan' will be the root package for Conan 2.x"
            )
        )
    }
    options = ()

    def process_module(self, node):
        """
        Processing the module's content that is accessible via node.stream() function
        """
        with node.stream() as stream:
            for (index, line) in enumerate(stream):
                if self.deprecated_imports_pattern.match(line.decode('utf-8')):
                    self.add_message("conan1.x-deprecated-imports", line=index)
<commit_msg>ConanDeprecatedImportsChecker: fix line numbers (#10822)<commit_after>"""Pylint plugin for ConanFile"""
import re

import astroid
from astroid import MANAGER
from pylint.checkers import BaseChecker
from pylint.interfaces import IRawChecker

def register(linter):
    """required method to auto register this checker"""
    linter.register_checker(ConanDeprecatedImportsChecker(linter))

def transform_conanfile(node):
    """Transform definition of ConanFile class so dynamic fields are visible to pylint"""

    str_class = astroid.builtin_lookup("str")
    info_class = MANAGER.ast_from_module_name("conans.model.info").lookup(
        "ConanInfo")
    build_requires_class = MANAGER.ast_from_module_name(
        "conans.client.graph.graph_manager").lookup("_RecipeBuildRequires")
    file_copier_class = MANAGER.ast_from_module_name(
        "conans.client.file_copier").lookup("FileCopier")
    file_importer_class = MANAGER.ast_from_module_name(
        "conans.client.importer").lookup("_FileImporter")
    python_requires_class = MANAGER.ast_from_module_name(
        "conans.client.graph.python_requires").lookup("PyRequires")

    dynamic_fields = {
        "conan_data": str_class,
        "build_requires": build_requires_class,
        "info_build": info_class,
        "info": info_class,
        "copy": file_copier_class,
        "copy_deps": file_importer_class,
        "python_requires": [str_class, python_requires_class],
        "recipe_folder": str_class,
    }

    for f, t in dynamic_fields.items():
        node.locals[f] = [t]

MANAGER.register_transform(
    astroid.ClassDef, transform_conanfile,
    lambda node: node.qname() == "conans.model.conan_file.ConanFile")

def _python_requires_member():
    return astroid.parse("""
        from conans.client.graph.python_requires import ConanPythonRequire
        python_requires = ConanPythonRequire()
        """)

astroid.register_module_extender(astroid.MANAGER, "conans", _python_requires_member)

class ConanDeprecatedImportsChecker(BaseChecker):
    """
    Check "from conans*" imports which disappears in Conan 2.x. Only "from conan*" is valid
    """

    __implements__ = IRawChecker

    deprecated_imports_pattern = re.compile(r"(from|import)\s+conans[\.|\s].*")
    name = "conan_deprecated_imports"
    msgs = {
        "E9000": (
            "Using deprecated imports from 'conans'",
            "conan1.x-deprecated-imports",
            (
                "Use imports from 'conan' instead of 'conans'"
                " because 'conan' will be the root package for Conan 2.x"
            )
        )
    }
    options = ()

    def process_module(self, node):
        """
        Processing the module's content that is accessible via node.stream() function
        """
        with node.stream() as stream:
            for (index, line) in enumerate(stream):
                if self.deprecated_imports_pattern.match(line.decode('utf-8')):
                    self.add_message("conan1.x-deprecated-imports", line=index + 1)
<|endoftext|>


<commit_before>#!/usr/bin/python
#
# Copyright (c) 2006 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.opensource.org/licenses/cpl.php.
#
# This program is distributed in the hope that it will be useful, but
# without any waranty; without even the implied warranty of merchantability
# or fitness for a particular purpose. See the Common Public License for
# full details.
#

import cmd
import sys
from conary import dbstore
import sqlerrors
import os

try:
    import readline
except ImportError:
    hasReadline = False
else:
    hasReadline = True

class DbSql(cmd.Cmd):
    _historyPath = os.path.expanduser('~/.dbsqlhistory')

    def __init__(self, db = None, driver = None, path = None):
        cmd.Cmd.__init__(self)
        self.prompt = 'dbsql> '
        self.doc_header = "Documented commands (type .help <topic>):"
        self.intro = 'dbstore sql shell.  type ".quit" to exit'
        if driver and path:
            self.db = dbstore.connect(path, driver=driver)
        elif db:
            self.db = db
        else:
            raise RuntimeError, 'driver and path OR db must be given'
        self.cu = self.db.cursor()

    def onecmd(self, cmd):
        # remove any trailing whitespace
        cmd = cmd.strip()

        if cmd.startswith('.'):
            cmd = cmd[1:]
            cmd, arg, line = self.parseline(cmd)
            try:
                func = getattr(self, 'do_' + cmd)
            except AttributeError:
                return self.default(line)
            return func(arg)

        if not cmd:
            return
        if ';' in cmd:
            onecmd, rest = cmd.split(';')
            self.onecmd(onecmd)
            self.onecmd(rest)
            return
        try:
            self.cu.execute(cmd)
        except sqlerrors.DatabaseError, e:
            print 'Error:', str(e.args[0])
        fields = None
        for row in self.cu:
            if not fields:
                fields = self.cu.fields()
                print '|'.join(fields)
            print '|'.join(repr(x) for x in row)

    def cmdloop(self):
        self.read_history()
        rc = cmd.Cmd.cmdloop(self)
        self.save_history()
        return rc

    def read_history(self):
        if hasReadline and self._historyPath:
            try:
                readline.read_history_file(self._historyPath)
            except:
                pass

    def save_history(self):
        if hasReadline and self._historyPath:
            readline.set_history_length(1000)
            try:
                readline.write_history_file(self._historyPath)
            except:
                pass

    def do_quit(self, arg):
        # ask to stop
        return True

    def help_quit(self):
        print """quit
quit the shell"""

    def help_help(self):
        print """quit
display help"""

def shell(db):
    'invokes a dbstore sql shell on an existing db connection'
    shell = DbSql(db)
    return shell.cmdloop()
<commit_msg>implement .headers [on/off], .show [tables/triggers/etc]; clean up exiting; fix autocompletion for functions<commit_after>#!/usr/bin/python
#
# Copyright (c) 2006 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.opensource.org/licenses/cpl.php.
#
# This program is distributed in the hope that it will be useful, but
# without any waranty; without even the implied warranty of merchantability
# or fitness for a particular purpose. See the Common Public License for
# full details.
#

import cmd
import sys
from conary import dbstore
import sqlerrors
import os

try:
    import readline
except ImportError:
    hasReadline = False
else:
    hasReadline = True

class DbSql(cmd.Cmd):
    _historyPath = os.path.expanduser('~/.dbsqlhistory')

    def __init__(self, db = None, driver = None, path = None):
        cmd.Cmd.__init__(self)
        self.prompt = 'dbsql> '
        self.doc_header = "Documented commands (type .help <topic>):"

        self.intro = """dbstore sql shell.
type ".quit" to exit, ".help" for help"""

        self.showHeaders = False

        if driver and path:
            self.db = dbstore.connect(path, driver=driver)
        elif db:
            self.db = db
        else:
            raise RuntimeError, 'driver and path OR db must be given'
        self.cu = self.db.cursor()

    def onecmd(self, cmd):
        # remove any trailing whitespace
        cmd = cmd.strip()

        if cmd.startswith('.'):
            cmd = cmd[1:]
            cmd, arg, line = self.parseline(cmd)
            try:
                func = getattr(self, 'do_' + cmd)
            except AttributeError:
                return self.default(line)
            return func(arg)

        if cmd == 'EOF':
            # on EOF, ask to stop
            print
            return True

        if not cmd:
            # no command, noop
            return False

        if ';' in cmd:
            # split up the command and execute each part
            for onecmd in cmd.split(';', 1):
                self.onecmd(onecmd)
            return False

        # execute the SQL command
        try:
            self.cu.execute(cmd)
        except sqlerrors.DatabaseError, e:
            print 'Error:', str(e.args[0])
            return False

        # print the results (if any)
        fields = None
        for row in self.cu:
            if self.showHeaders and not fields:
                fields = self.cu.fields()
                print '|'.join(fields)
            print '|'.join(str(x) for x in row)

        # reload the schema, in case there was a change
        self.db.loadSchema()

    def cmdloop(self):
        self.read_history()
        while 1:
            try:
                rc = cmd.Cmd.cmdloop(self)
            except KeyboardInterrupt:
                # let Ctrl+C just cancel input, like in a shell
                self.intro = None
                print
                continue
            break
        self.save_history()
        return rc

    def read_history(self):
        if hasReadline and self._historyPath:
            try:
                readline.read_history_file(self._historyPath)
            except:
                pass

    def save_history(self):
        if hasReadline and self._historyPath:
            readline.set_history_length(1000)
            try:
                readline.write_history_file(self._historyPath)
            except:
                pass

    def completenames(self, text, *ignored):
        # override completenames to append the . at the start
        if text.startswith('.'):
            text = text[1:]
        dotext = 'do_'+text
        return ['.' + a[3:] for a in self.get_names() if a.startswith(dotext)]

    def do_show(self, arg):
        schemaBits = ('tables', 'triggers', 'functions', 'sequences',
                      'triggers')
        if arg in schemaBits:
            d = self.db.__dict__[arg]
            print '\n'.join(sorted(d.keys()))
        else:
            print 'unknown argument', arg
        return False

    def help_show(self):
        print """show [tables/triggers/functions/sequences/triggers]
display database information"""

    def do_headers(self, arg):
        if arg in ('on', 'yes'):
            self.showHeaders = True
        elif arg in ('off', 'no'):
            self.showHeaders = False
        else:
            print 'unknown argument', arg
        return False

    def help_headers(self):
        print """headers [on/off]
turn the display of headers on or off"""

    do_head = do_headers
    help_head = do_head

    def do_quit(self, arg):
        # ask to stop
        return True

    def help_quit(self):
        print """quit
quit the shell"""

    def help_help(self):
        print """quit
display help"""

def shell(db):
    'invokes a dbstore sql shell on an existing db connection'
    shell = DbSql(db)
    return shell.cmdloop()
<|endoftext|>


<commit_before>from datetime import datetime, timedelta

from django import forms

from produto.models import Colecao
from .models import Familia

class LoteForm(forms.Form):
    lote = forms.CharField(
        label='Lote', max_length=9, min_length=9,
        widget=forms.TextInput(attrs={'type': 'number',
                               'autofocus': 'autofocus'}))

class OpForm(forms.Form):
    op = forms.CharField(
        label='OP',
        widget=forms.TextInput(attrs={'type': 'number',
                               'autofocus': 'autofocus'}))

class OsForm(forms.Form):
    os = forms.CharField(
        label='OS',
        widget=forms.TextInput(attrs={'type': 'number',
                               'autofocus': 'autofocus'}))

class AnPeriodoAlterForm(forms.Form):
    periodo_de = forms.CharField(
        label='Período: De',
        widget=forms.TextInput(attrs={'type': 'number',
                               'autofocus': 'autofocus'}))
    periodo_ate = forms.CharField(
        label='Até', required=False,
        widget=forms.TextInput(attrs={'type': 'number'}))

    alternativa = forms.CharField(
        label='Alternativa', required=False,
        widget=forms.TextInput(attrs={'type': 'number'}))

    def clean_periodo(self, periodo):
        try:
            i_periodo = int(float(periodo))
            if i_periodo < 0:
                periodo = None
        except ValueError:
            periodo = None
        return periodo

    def clean_periodo_de(self):
        return self.clean_periodo(self.cleaned_data['periodo_de'])

    def clean_periodo_ate(self):
        return self.clean_periodo(self.cleaned_data['periodo_ate'])

class AnDtCorteAlterForm(forms.Form):
    data_de = forms.DateField(
        label='Data do Corte/Gargalo: De',
        widget=forms.DateInput(attrs={'type': 'date',
                               'autofocus': 'autofocus'}))
    data_ate = forms.DateField(
        label='Até', required=False,
        widget=forms.DateInput(attrs={'type': 'date'}))

    alternativa = forms.CharField(
        label='Alternativa', required=False,
        widget=forms.TextInput(attrs={'type': 'number'}))

    # roteiro = forms.CharField(
    #     label='Roteiro', required=False,
    #     widget=forms.TextInput(attrs={'type': 'number'}))

    # tipo = forms.CharField(
    #     label='Tipo (MD, PG, PA)', required=False, widget=forms.TextInput)

    # def clean_tipo(self):
    #     tipo = self.cleaned_data['tipo'].upper()
    #     if tipo not in ('MD', 'PG', 'PA'):
    #         tipo = ''
    #     return tipo

class ResponsPorEstagioForm(forms.Form):
    estagio = forms.CharField(
        label='Estágio', max_length=2, required=False,
        widget=forms.TextInput(attrs={'type': 'number',
                               'autofocus': 'autofocus'}))
    usuario = forms.CharField(
        label='Usuário', max_length=20, required=False,
        widget=forms.TextInput(attrs={'type': 'string'}))
    CHOICES = [('e', 'Por estágio'),
               ('u', 'Por usuário')]
    ordem = forms.ChoiceField(
        choices=CHOICES, initial='e', widget=forms.RadioSelect())

    def clean_usuario(self):
        usuario = self.cleaned_data['usuario'].upper()
        data = self.data.copy()
        data['usuario'] = usuario
        self.data = data
        return usuario

class ImprimeLotesForm(forms.Form):
    op = forms.CharField(
        label='OP',
        widget=forms.TextInput(attrs={'type': 'number',
                               'autofocus': 'autofocus'}))
    tam = forms.CharField(
        label='Tamanho', required=False,
        widget=forms.TextInput(attrs={'type': 'string'}))
    cor = forms.CharField(
        label='Cor', required=False,
        widget=forms.TextInput(attrs={'type': 'string'}))
    order = forms.ChoiceField(
        label='Ordem',
        choices=[('t',  'Tamanho/Cor/OC'), ('o', 'OC'),
                 ('c', 'Cor/Tamanho/OC')])
    pula = forms.IntegerField(
        label='Pula quantos lotes', required=False,
        widget=forms.TextInput(attrs={'type': 'number'}))
    qtd_lotes = forms.IntegerField(
        label='Imprime quantos lotes', required=False,
        widget=forms.TextInput(attrs={'type': 'number'}))
    oc_inicial = forms.IntegerField(
        label='OC inicial', required=False,
        widget=forms.TextInput(attrs={'type': 'number'}))
    oc_final = forms.IntegerField(
        label='OC final', required=False,
        widget=forms.TextInput(attrs={'type': 'number'}))
    ultimo = forms.CharField(
        label='Último lote impresso', required=False,
        max_length=9, min_length=9,
        widget=forms.TextInput(attrs={'type': 'number'}))
    CHOICES = [('A', 'Etiqueta adesiva'),
               ('C', 'Cartela'),
               ('F', 'Cartela de fundo')]
    impresso = forms.ChoiceField(
        label='Impresso', choices=CHOICES, initial='A')
    obs1 = forms.CharField(
        label='Observação 1', required=False,
        widget=forms.TextInput(
            attrs={'type': 'string', 'style': 'width:20en'}))
    obs2 = forms.CharField(
        label='Observação 2', required=False,
        widget=forms.TextInput(
            attrs={'type': 'string', 'style': 'width:20en'}))

    def clean_tam(self):
        tam = self.cleaned_data['tam'].upper()
        data = self.data.copy()
        data['tam'] = tam
        self.data = data
        return tam

    def clean_cor(self):
        cor = self.cleaned_data['cor'].upper()
        data = self.data.copy()
        data['cor'] = cor
        self.data = data
        return cor

class ImprimePacote3LotesForm(forms.Form):
    op = forms.CharField(
        label='OP',
        widget=forms.TextInput(attrs={'type': 'number',
                               'autofocus': 'autofocus'}))
    tam = forms.CharField(
        label='Tamanho', required=False,
        widget=forms.TextInput(attrs={'type': 'string'}))
    cor = forms.CharField(
        label='Cor', required=False,
        widget=forms.TextInput(attrs={'type': 'string'}))
    ultimo = forms.CharField(
        label='Lote em última etiqueta de caixa impressa', required=False,
        max_length=9, min_length=9,
        widget=forms.TextInput(attrs={'type': 'number'}))
    ultima_cx = forms.CharField(
        label='Número da última caixa impressa', required=False,
        widget=forms.TextInput(attrs={'type': 'number'}))
    pula = forms.IntegerField(
        label='Pula quantos pacotes', required=False,
        widget=forms.TextInput(attrs={'type': 'number'}))
    qtd_lotes = forms.IntegerField(
        label='Imprime quantos pacotes', required=False,
        widget=forms.TextInput(attrs={'type': 'number'}))
    CHOICES = [('B', 'Etiqueta de caixa com barras de 3 lotes'),
               ('C', 'Etiqueta de caixa de lotes')]
    impresso = forms.ChoiceField(
        label='Impresso', choices=CHOICES, initial='B')
    obs1 = forms.CharField(
        label='Observação 1', required=False,
        widget=forms.TextInput(
            attrs={'type': 'string', 'style': 'width:20en'}))
    obs2 = forms.CharField(
        label='Observação 2', required=False,
        widget=forms.TextInput(
            attrs={'type': 'string', 'style': 'width:20en'}))

    def clean_tam(self):
        tam = self.cleaned_data['tam'].upper()
        data = self.data.copy()
        data['tam'] = tam
        self.data = data
        return tam

    def clean_cor(self):
        cor = self.cleaned_data['cor'].upper()
        data = self.data.copy()
        data['cor'] = cor
        self.data = data
        return cor

class OpPendenteForm(forms.Form):
    estagio = forms.CharField(
        label='Estágio', max_length=2, required=False,
        widget=forms.TextInput(attrs={'type': 'number',
                               'autofocus': 'autofocus'}))
    periodo_de = forms.CharField(
        label='Período: De', required=False,
        widget=forms.TextInput(attrs={'type': 'number'}))
    periodo_ate = forms.CharField(
        label='Até', required=False,
        widget=forms.TextInput(attrs={'type': 'number'}))

    data_de = forms.DateField(
        label='Data do Corte/Gargalo: De', required=False,
        widget=forms.DateInput(attrs={'type': 'date'}))
    data_ate = forms.DateField(
        label='Até', required=False,
        widget=forms.DateInput(attrs={'type': 'date'}))

    colecao = forms.ModelChoiceField(
        label='Coleção', required=False,
        queryset=Colecao.objects.exclude(colecao=0).order_by(
            'colecao'), empty_label="(Todas)")

    CHOICES = [('-', 'Ambas (2 e 4)'),
               ('2', '2 - Ordem cofecção gerada'),
               ('4', '4 - Ordens em produção')]
    situacao = forms.ChoiceField(
        label='Situação', choices=CHOICES, initial='0')

    def clean_periodo(self, periodo, default):
        try:
            i_periodo = int(float(periodo))
            if i_periodo < 0:
                periodo = default
        except ValueError:
            periodo = default
        return periodo

    def clean_periodo_de(self):
        return self.clean_periodo(self.cleaned_data['periodo_de'], 0)

    def clean_periodo_ate(self):
        return self.clean_periodo(self.cleaned_data['periodo_ate'], 9999)

    def clean_situacao(self):
        if self.cleaned_data['situacao'] == '-':
            return ''
        else:
            return self.cleaned_data['situacao']

class PedidoForm(forms.Form):
    pedido = forms.CharField(
        label='Pedido',
        widget=forms.TextInput(attrs={'type': 'number',
                               'autofocus': 'autofocus'}))

class ModeloTermicaForm(forms.ModelForm):
    gabarito = forms.CharField(
        label='Gabarito',
        widget=forms.Textarea(
            attrs={'max_length': 8192, 'rows': 20, 'cols': 79}))

class DistribuicaoForm(forms.Form):
    # estagio = forms.CharField(
    #     label='Estágio', max_length=2, required=False,
    #     widget=forms.TextInput(attrs={'type': 'number',
    #                            'autofocus': 'autofocus'}))
    data_de = forms.DateField(
        label='Data da distribuição: De',
        widget=forms.DateInput(attrs={'type': 'date'}))
    data_ate = forms.DateField(
        label='Até', required=False,
        widget=forms.DateInput(attrs={'type': 'date'}))
    familia = forms.ModelChoiceField(
        label='Família (tear)', required=False,
        queryset=Familia.objects.filter(
            divisao_producao__range=['3000', '3999']).order_by(
            'divisao_producao'), empty_label="(Todas)")

    # def clean_estagio(self):
    #     estagio = self.cleaned_data['estagio']
    #     if estagio == '':
    #         estagio = '22'
    #     data = self.data.copy()
    #     data['estagio'] = estagio
    #     self.data = data
    #     return estagio

class BuscaOpForm(forms.Form):
    ref = forms.CharField(
        label='Referência', required=False, min_length=5, max_length=5,
        widget=forms.TextInput(attrs={'type': 'string',
                               'autofocus': 'autofocus'}))

    def clean_ref(self):
        ref = self.cleaned_data['ref'].upper()
        data = self.data.copy()
        data['ref'] = ref
        self.data = data
        return ref

class ExpedicaoForm(forms.Form):
    embarque_de = forms.DateField(
        label='Data do embarque: De', required=False,
        widget=forms.DateInput(attrs={'type': 'date',
                               'autofocus': 'autofocus'}))
    embarque_ate = forms.DateField(
        label='Até', required=False,
        widget=forms.DateInput(attrs={'type': 'date'}))

    pedido_tussor = forms.CharField(
        label='Pedido na Tussor', required=False,
        widget=forms.TextInput(attrs={'type': 'number'}))

    pedido_cliente = forms.CharField(
        label='Pedido no cliente', required=False,
        widget=forms.TextInput(attrs={'type': 'number'}))

    cliente = forms.CharField(
        label='Cliente', required=False,
        help_text='Parte do nome ou início do CNPJ.',
        widget=forms.TextInput(attrs={'type': 'string'}))

    CHOICES = [('r', 'Por referência'),
               ('c', 'Por referência-cor-tamanho')]
    detalhe = forms.ChoiceField(
        label='Detalhe', choices=CHOICES, initial='r')

    def clean_cliente(self):
        cliente = self.cleaned_data['cliente'].upper()
        data = self.data.copy()
        data['cliente'] = cliente
        self.data = data
        return cliente

    def clean(self):
        clean_ef = super(ExpedicaoForm, self).clean()

        if not any(
            clean_ef.get(x, '')
            for x in (
                'embarque_de',
                'embarque_ate',
                'pedido_tussor',
                'pedido_cliente',
                'cliente',
            )
        ):
            list_msg = ['Ao menos um destes campos deve ser preenchido']
            self._errors['embarque_de'] = self.error_class(list_msg)
            self._errors['embarque_ate'] = self.error_class(list_msg)
            self._errors['pedido_tussor'] = self.error_class(list_msg)
            self._errors['pedido_cliente'] = self.error_class(list_msg)
            self._errors['cliente'] = self.error_class(list_msg)

        return clean_ef

class OpPerdaForm(forms.Form):
    data_de = forms.DateField(
        label='Data do Corte: De', required=False,
        help_text='Padrão: Hoje',
        widget=forms.DateInput(attrs={
            'type': 'date',
            'value': datetime.now().date()}))
    data_ate = forms.DateField(
        label='Até', required=False,
        help_text='Padrão: Período de um mês',
        widget=forms.DateInput(attrs={'type': 'date'}))

    CHOICES = [('r', 'Por referência'),
               ('c', 'Por referência-cor-tamanho')]
    detalhe = forms.ChoiceField(
        label='Detalhe', choices=CHOICES, initial='c')

    def clean_data_de(self):
        data_de = self.cleaned_data['data_de']
        if data_de is None:
            data_de = datetime.now().date()
            data = self.data.copy()
            data['data_de'] = data_de
            self.data = data
        return data_de

    def clean_data_ate(self):
        data_ate = self.cleaned_data['data_ate']
        if data_ate is None:
            data_ate = self.cleaned_data['data_de']
            data_ate = data_ate.replace(
                month=data_ate.month % 12 + 1)-timedelta(days=1)
            data = self.data.copy()
            data['data_ate'] = data_ate
            self.data = data
        return data_ate
<commit_msg>ImprimeLotesForm pede estagio para cartela de complemento<commit_after>from datetime import datetime, timedelta

from django import forms

from produto.models import Colecao
from .models import Familia

class LoteForm(forms.Form):
    lote = forms.CharField(
        label='Lote', max_length=9, min_length=9,
        widget=forms.TextInput(attrs={'type': 'number',
                               'autofocus': 'autofocus'}))

class OpForm(forms.Form):
    op = forms.CharField(
        label='OP',
        widget=forms.TextInput(attrs={'type': 'number',
                               'autofocus': 'autofocus'}))

class OsForm(forms.Form):
    os = forms.CharField(
        label='OS',
        widget=forms.TextInput(attrs={'type': 'number',
                               'autofocus': 'autofocus'}))

class AnPeriodoAlterForm(forms.Form):
    periodo_de = forms.CharField(
        label='Período: De',
        widget=forms.TextInput(attrs={'type': 'number',
                               'autofocus': 'autofocus'}))
    periodo_ate = forms.CharField(
        label='Até', required=False,
        widget=forms.TextInput(attrs={'type': 'number'}))

    alternativa = forms.CharField(
        label='Alternativa', required=False,
        widget=forms.TextInput(attrs={'type': 'number'}))

    def clean_periodo(self, periodo):
        try:
            i_periodo = int(float(periodo))
            if i_periodo < 0:
                periodo = None
        except ValueError:
            periodo = None
        return periodo

    def clean_periodo_de(self):
        return self.clean_periodo(self.cleaned_data['periodo_de'])

    def clean_periodo_ate(self):
        return self.clean_periodo(self.cleaned_data['periodo_ate'])

class AnDtCorteAlterForm(forms.Form):
    data_de = forms.DateField(
        label='Data do Corte/Gargalo: De',
        widget=forms.DateInput(attrs={'type': 'date',
                               'autofocus': 'autofocus'}))
    data_ate = forms.DateField(
        label='Até', required=False,
        widget=forms.DateInput(attrs={'type': 'date'}))

    alternativa = forms.CharField(
        label='Alternativa', required=False,
        widget=forms.TextInput(attrs={'type': 'number'}))

    # roteiro = forms.CharField(
    #     label='Roteiro', required=False,
    #     widget=forms.TextInput(attrs={'type': 'number'}))

    # tipo = forms.CharField(
    #     label='Tipo (MD, PG, PA)', required=False, widget=forms.TextInput)

    # def clean_tipo(self):
    #     tipo = self.cleaned_data['tipo'].upper()
    #     if tipo not in ('MD', 'PG', 'PA'):
    #         tipo = ''
    #     return tipo

class ResponsPorEstagioForm(forms.Form):
    estagio = forms.CharField(
        label='Estágio', max_length=2, required=False,
        widget=forms.TextInput(attrs={'type': 'number',
                               'autofocus': 'autofocus'}))
    usuario = forms.CharField(
        label='Usuário', max_length=20, required=False,
        widget=forms.TextInput(attrs={'type': 'string'}))
    CHOICES = [('e', 'Por estágio'),
               ('u', 'Por usuário')]
    ordem = forms.ChoiceField(
        choices=CHOICES, initial='e', widget=forms.RadioSelect())

    def clean_usuario(self):
        usuario = self.cleaned_data['usuario'].upper()
        data = self.data.copy()
        data['usuario'] = usuario
        self.data = data
        return usuario

class ImprimeLotesForm(forms.Form):
    op = forms.CharField(
        label='OP',
        widget=forms.TextInput(attrs={'type': 'number',
                               'autofocus': 'autofocus'}))
    estagio = forms.CharField(
        label='Estágio de quebra de lote', required=False,
        help_text='Só imprime cartela de lote com quantidade parcial nesse '
                  'estágio.',
        widget=forms.TextInput(attrs={'type': 'number',
                               'autofocus': 'autofocus'}))
    tam = forms.CharField(
        label='Tamanho', required=False,
        widget=forms.TextInput(attrs={'type': 'string'}))
    cor = forms.CharField(
        label='Cor', required=False,
        widget=forms.TextInput(attrs={'type': 'string'}))
    order = forms.ChoiceField(
        label='Ordem',
        choices=[('t',  'Tamanho/Cor/OC'), ('o', 'OC'),
                 ('c', 'Cor/Tamanho/OC')])
    pula = forms.IntegerField(
        label='Pula quantos lotes', required=False,
        widget=forms.TextInput(attrs={'type': 'number'}))
    qtd_lotes = forms.IntegerField(
        label='Imprime quantos lotes', required=False,
        widget=forms.TextInput(attrs={'type': 'number'}))
    oc_inicial = forms.IntegerField(
        label='OC inicial', required=False,
        widget=forms.TextInput(attrs={'type': 'number'}))
    oc_final = forms.IntegerField(
        label='OC final', required=False,
        widget=forms.TextInput(attrs={'type': 'number'}))
    ultimo = forms.CharField(
        label='Último lote impresso', required=False,
        max_length=9, min_length=9,
        widget=forms.TextInput(attrs={'type': 'number'}))
    CHOICES = [('A', 'Etiqueta adesiva'),
               ('C', 'Cartela'),
               ('F', 'Cartela de fundo')]
    impresso = forms.ChoiceField(
        label='Impresso', choices=CHOICES, initial='A')
    obs1 = forms.CharField(
        label='Observação 1', required=False,
        widget=forms.TextInput(
            attrs={'type': 'string', 'style': 'width:20en'}))
    obs2 = forms.CharField(
        label='Observação 2', required=False,
        widget=forms.TextInput(
            attrs={'type': 'string', 'style': 'width:20en'}))

    def clean_tam(self):
        tam = self.cleaned_data['tam'].upper()
        data = self.data.copy()
        data['tam'] = tam
        self.data = data
        return tam

    def clean_cor(self):
        cor = self.cleaned_data['cor'].upper()
        data = self.data.copy()
        data['cor'] = cor
        self.data = data
        return cor

class ImprimePacote3LotesForm(forms.Form):
    op = forms.CharField(
        label='OP',
        widget=forms.TextInput(attrs={'type': 'number',
                               'autofocus': 'autofocus'}))
    tam = forms.CharField(
        label='Tamanho', required=False,
        widget=forms.TextInput(attrs={'type': 'string'}))
    cor = forms.CharField(
        label='Cor', required=False,
        widget=forms.TextInput(attrs={'type': 'string'}))
    ultimo = forms.CharField(
        label='Lote em última etiqueta de caixa impressa', required=False,
        max_length=9, min_length=9,
        widget=forms.TextInput(attrs={'type': 'number'}))
    ultima_cx = forms.CharField(
        label='Número da última caixa impressa', required=False,
        widget=forms.TextInput(attrs={'type': 'number'}))
    pula = forms.IntegerField(
        label='Pula quantos pacotes', required=False,
        widget=forms.TextInput(attrs={'type': 'number'}))
    qtd_lotes = forms.IntegerField(
        label='Imprime quantos pacotes', required=False,
        widget=forms.TextInput(attrs={'type': 'number'}))
    CHOICES = [('B', 'Etiqueta de caixa com barras de 3 lotes'),
               ('C', 'Etiqueta de caixa de lotes')]
    impresso = forms.ChoiceField(
        label='Impresso', choices=CHOICES, initial='B')
    obs1 = forms.CharField(
        label='Observação 1', required=False,
        widget=forms.TextInput(
            attrs={'type': 'string', 'style': 'width:20en'}))
    obs2 = forms.CharField(
        label='Observação 2', required=False,
        widget=forms.TextInput(
            attrs={'type': 'string', 'style': 'width:20en'}))

    def clean_tam(self):
        tam = self.cleaned_data['tam'].upper()
        data = self.data.copy()
        data['tam'] = tam
        self.data = data
        return tam

    def clean_cor(self):
        cor = self.cleaned_data['cor'].upper()
        data = self.data.copy()
        data['cor'] = cor
        self.data = data
        return cor

class OpPendenteForm(forms.Form):
    estagio = forms.CharField(
        label='Estágio', max_length=2, required=False,
        widget=forms.TextInput(attrs={'type': 'number',
                               'autofocus': 'autofocus'}))
    periodo_de = forms.CharField(
        label='Período: De', required=False,
        widget=forms.TextInput(attrs={'type': 'number'}))
    periodo_ate = forms.CharField(
        label='Até', required=False,
        widget=forms.TextInput(attrs={'type': 'number'}))

    data_de = forms.DateField(
        label='Data do Corte/Gargalo: De', required=False,
        widget=forms.DateInput(attrs={'type': 'date'}))
    data_ate = forms.DateField(
        label='Até', required=False,
        widget=forms.DateInput(attrs={'type': 'date'}))

    colecao = forms.ModelChoiceField(
        label='Coleção', required=False,
        queryset=Colecao.objects.exclude(colecao=0).order_by(
            'colecao'), empty_label="(Todas)")

    CHOICES = [('-', 'Ambas (2 e 4)'),
               ('2', '2 - Ordem cofecção gerada'),
               ('4', '4 - Ordens em produção')]
    situacao = forms.ChoiceField(
        label='Situação', choices=CHOICES, initial='0')

    def clean_periodo(self, periodo, default):
        try:
            i_periodo = int(float(periodo))
            if i_periodo < 0:
                periodo = default
        except ValueError:
            periodo = default
        return periodo

    def clean_periodo_de(self):
        return self.clean_periodo(self.cleaned_data['periodo_de'], 0)

    def clean_periodo_ate(self):
        return self.clean_periodo(self.cleaned_data['periodo_ate'], 9999)

    def clean_situacao(self):
        if self.cleaned_data['situacao'] == '-':
            return ''
        else:
            return self.cleaned_data['situacao']

class PedidoForm(forms.Form):
    pedido = forms.CharField(
        label='Pedido',
        widget=forms.TextInput(attrs={'type': 'number',
                               'autofocus': 'autofocus'}))

class ModeloTermicaForm(forms.ModelForm):
    gabarito = forms.CharField(
        label='Gabarito',
        widget=forms.Textarea(
            attrs={'max_length': 8192, 'rows': 20, 'cols': 79}))

class DistribuicaoForm(forms.Form):
    # estagio = forms.CharField(
    #     label='Estágio', max_length=2, required=False,
    #     widget=forms.TextInput(attrs={'type': 'number',
    #                            'autofocus': 'autofocus'}))
    data_de = forms.DateField(
        label='Data da distribuição: De',
        widget=forms.DateInput(attrs={'type': 'date'}))
    data_ate = forms.DateField(
        label='Até', required=False,
        widget=forms.DateInput(attrs={'type': 'date'}))
    familia = forms.ModelChoiceField(
        label='Família (tear)', required=False,
        queryset=Familia.objects.filter(
            divisao_producao__range=['3000', '3999']).order_by(
            'divisao_producao'), empty_label="(Todas)")

    # def clean_estagio(self):
    #     estagio = self.cleaned_data['estagio']
    #     if estagio == '':
    #         estagio = '22'
    #     data = self.data.copy()
    #     data['estagio'] = estagio
    #     self.data = data
    #     return estagio

class BuscaOpForm(forms.Form):
    ref = forms.CharField(
        label='Referência', required=False, min_length=5, max_length=5,
        widget=forms.TextInput(attrs={'type': 'string',
                               'autofocus': 'autofocus'}))

    def clean_ref(self):
        ref = self.cleaned_data['ref'].upper()
        data = self.data.copy()
        data['ref'] = ref
        self.data = data
        return ref

class ExpedicaoForm(forms.Form):
    embarque_de = forms.DateField(
        label='Data do embarque: De', required=False,
        widget=forms.DateInput(attrs={'type': 'date',
                               'autofocus': 'autofocus'}))
    embarque_ate = forms.DateField(
        label='Até', required=False,
        widget=forms.DateInput(attrs={'type': 'date'}))

    pedido_tussor = forms.CharField(
        label='Pedido na Tussor', required=False,
        widget=forms.TextInput(attrs={'type': 'number'}))

    pedido_cliente = forms.CharField(
        label='Pedido no cliente', required=False,
        widget=forms.TextInput(attrs={'type': 'number'}))

    cliente = forms.CharField(
        label='Cliente', required=False,
        help_text='Parte do nome ou início do CNPJ.',
        widget=forms.TextInput(attrs={'type': 'string'}))

    CHOICES = [('r', 'Por referência'),
               ('c', 'Por referência-cor-tamanho')]
    detalhe = forms.ChoiceField(
        label='Detalhe', choices=CHOICES, initial='r')

    def clean_cliente(self):
        cliente = self.cleaned_data['cliente'].upper()
        data = self.data.copy()
        data['cliente'] = cliente
        self.data = data
        return cliente

    def clean(self):
        clean_ef = super(ExpedicaoForm, self).clean()

        if not any(
            clean_ef.get(x, '')
            for x in (
                'embarque_de',
                'embarque_ate',
                'pedido_tussor',
                'pedido_cliente',
                'cliente',
            )
        ):
            list_msg = ['Ao menos um destes campos deve ser preenchido']
            self._errors['embarque_de'] = self.error_class(list_msg)
            self._errors['embarque_ate'] = self.error_class(list_msg)
            self._errors['pedido_tussor'] = self.error_class(list_msg)
            self._errors['pedido_cliente'] = self.error_class(list_msg)
            self._errors['cliente'] = self.error_class(list_msg)

        return clean_ef

class OpPerdaForm(forms.Form):
    data_de = forms.DateField(
        label='Data do Corte: De', required=False,
        help_text='Padrão: Hoje',
        widget=forms.DateInput(attrs={
            'type': 'date',
            'value': datetime.now().date()}))
    data_ate = forms.DateField(
        label='Até', required=False,
        help_text='Padrão: Período de um mês',
        widget=forms.DateInput(attrs={'type': 'date'}))

    CHOICES = [('r', 'Por referência'),
               ('c', 'Por referência-cor-tamanho')]
    detalhe = forms.ChoiceField(
        label='Detalhe', choices=CHOICES, initial='c')

    def clean_data_de(self):
        data_de = self.cleaned_data['data_de']
        if data_de is None:
            data_de = datetime.now().date()
            data = self.data.copy()
            data['data_de'] = data_de
            self.data = data
        return data_de

    def clean_data_ate(self):
        data_ate = self.cleaned_data['data_ate']
        if data_ate is None:
            data_ate = self.cleaned_data['data_de']
            data_ate = data_ate.replace(
                month=data_ate.month % 12 + 1)-timedelta(days=1)
            data = self.data.copy()
            data['data_ate'] = data_ate
            self.data = data
        return data_ate
<|endoftext|>


<commit_before># coding=utf-8
from contracts import models
import remotesyc.models

__author__ = 'alex'

def float_number(value):
    converted = 0
    if isinstance(value, basestring):
        try:
            converted = float(value.replace(',', '.'))
        except ValueError:
            if value:
                raise
        except TypeError:
            converted = 0
    return converted

def load_spent_hours(contract, obj):
    return float_number(obj.get_field_value(contract.company.spent_hours_external))

def load_estimated_hours(contract, obj):
    return float_number(obj.get_field_value(contract.company.estimated_hours_external))

def calc_spent_hours(contract, querysets):
    """Total de horas restantes para todo o período"""
    hours = []
    for queryset in querysets:
        hours.append(sum([(float_number(ticket.get_field_value(contract.company.spent_hours_external)))
                          for ticket in queryset]))
    return sum(hours)

def calc_remainder_hours(contract, spent_hours):
    """Total de horas restantes para todo o período"""
    return contract.hours - spent_hours

def calc_spent_credits(contract, period, status=remotesyc.models.Ticket.STATUS.CLOSED):
    """Saldo de horas considerando o consumo dos meses anteriores ao período passado"""
    intervals = models.Period.objects.filter(contract=contract, dt_start__lt=period.dt_start)
    querysets = []
    for interval in intervals:
        queryset = remotesyc.models.Ticket.objects.filter(
            organization_id=contract.company.organization_external,
            updated_at__range=[interval.dt_start, interval.dt_end])

        if not status == remotesyc.models.Ticket.STATUS.ALL:
            queryset = queryset.filter(status=status)

        querysets.append(queryset)
    return (contract.average_hours * intervals.count()) - calc_spent_hours(contract, querysets)<commit_msg>Redução de código(usando funções existentes).<commit_after># coding=utf-8
from contracts import models
import remotesyc.models

__author__ = 'alex'

def float_number(value):
    converted = 0
    if isinstance(value, basestring):
        try:
            converted = float(value.replace(',', '.'))
        except ValueError:
            if value:
                raise
        except TypeError:
            converted = 0
    return converted

def load_spent_hours(contract, obj):
    return float_number(obj.get_field_value(contract.company.spent_hours_external))

def load_estimated_hours(contract, obj):
    return float_number(obj.get_field_value(contract.company.estimated_hours_external))

def calc_spent_hours(contract, querysets):
    """Total de horas restantes para todo o período"""
    hours = []
    for queryset in querysets:
        hours.append(sum([load_spent_hours(contract, ticket) for ticket in queryset]))
    return sum(hours)

def calc_remainder_hours(contract, spent_hours):
    """Total de horas restantes para todo o período"""
    return contract.hours - spent_hours

def calc_spent_credits(contract, period, status=remotesyc.models.Ticket.STATUS.CLOSED):
    """Saldo de horas considerando o consumo dos meses anteriores ao período passado"""
    intervals = models.Period.objects.filter(contract=contract, dt_start__lt=period.dt_start)
    querysets = []
    for interval in intervals:
        queryset = remotesyc.models.Ticket.objects.filter(
            organization_id=contract.company.organization_external,
            updated_at__range=[interval.dt_start, interval.dt_end])

        if not status == remotesyc.models.Ticket.STATUS.ALL:
            queryset = queryset.filter(status=status)

        querysets.append(queryset)
    return (contract.average_hours * intervals.count()) - calc_spent_hours(contract, querysets)<|endoftext|>


<commit_before>"""
This module provides some useful tools for ``vcs`` like annotate/diff html
output. It also includes some internal helpers.
"""
import time
import datetime

def makedate():
    lt = time.localtime()
    if lt[8] == 1 and time.daylight:
        tz = time.altzone
    else:
        tz = time.timezone
    return time.mktime(lt), tz

def date_fromtimestamp(unixts, tzoffset=0):
    """
    Makes a datetime objec out of unix timestamp with given timezone offset
    :param unixts:
    :param tzoffset:
    """
    return datetime.datetime(*time.gmtime(float(unixts) - tzoffset)[:6])

def safe_unicode(str):
    """
    safe unicode function. In case of UnicodeDecode error we try to return
    unicode with errors replace, if this failes we return unicode with
    string_escape decoding
    """

    try:
        u_str = unicode(str)
    except UnicodeDecodeError:
        try:
            u_str = unicode(str, 'utf-8', 'replace')
        except UnicodeDecodeError:
            # In case we have a decode error just represent as byte string
            u_str = unicode(str(str).encode('string_escape'))

    return u_str
<commit_msg>param should be not named as function name<commit_after>"""
This module provides some useful tools for ``vcs`` like annotate/diff html
output. It also includes some internal helpers.
"""
import time
import datetime

def makedate():
    lt = time.localtime()
    if lt[8] == 1 and time.daylight:
        tz = time.altzone
    else:
        tz = time.timezone
    return time.mktime(lt), tz

def date_fromtimestamp(unixts, tzoffset=0):
    """
    Makes a datetime objec out of unix timestamp with given timezone offset
    :param unixts:
    :param tzoffset:
    """
    return datetime.datetime(*time.gmtime(float(unixts) - tzoffset)[:6])

def safe_unicode(s):
    """
    safe unicode function. In case of UnicodeDecode error we try to return
    unicode with errors replace, if this fails we return unicode with
    string_escape decoding
    """

    try:
        u_str = unicode(s)
    except UnicodeDecodeError:
        try:
            u_str = unicode(s, 'utf-8', 'replace')
        except UnicodeDecodeError:
            # In case we have a decode error just represent as byte string
            u_str = unicode(str(s).encode('string_escape'))

    return u_str
<|endoftext|>


<commit_before>#!/usr/bin/env python3

# This script is part of earlyoom package.

# Send a GUI notification to all logged-in users.

# Written by https://github.com/hakavlad

# Why it was written:
#   https://github.com/rfjakob/earlyoom/issues/72

# Example:
#   ./notify_all_users.py -i dialog-warning earlyoom "Low memory! Killing process 2233 tail"

# Usage:
#   earlyoom -N notify_all_users.py

# Notification that should pop up:
#   earlyoom
#   Low memory! Killing process 2233 tail

from sys import argv
from os import listdir
from subprocess import Popen, TimeoutExpired

def rline1(path):
    """read 1st line from path."""
    with open(path) as f:
        for line in f:
            return line

def re_pid_environ(pid):
    """
    read environ of 1 process
    returns tuple with USER, DBUS, DISPLAY like follow:
    ('user', 'DISPLAY=:0',
     'DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus')
    returns None if these vars is not in /proc/[pid]/environ
    """
    try:
        env = str(rline1('/proc/' + pid + '/environ'))
        if display_env in env and dbus_env in env and user_env in env:
            env_list = env.split('\x00')

            # iterating over a list of process environment variables
            for i in env_list:
                if i.startswith(user_env):
                    user = i
                    if user == 'USER=root':
                        return None
                    continue

                if i.startswith(display_env):
                    display = i[:10]
                    continue

                if i.startswith(dbus_env):
                    dbus = i
                    continue

                if i.startswith('HOME='):
                    # exclude Display Manager's user
                    if i.startswith('HOME=/var'):
                        return None

            env = user.partition('USER=')[2], display, dbus
            return env

    except FileNotFoundError:
        return None
    except ProcessLookupError:
        return None

def root_notify_env():
    """return set(user, display, dbus)"""
    unsorted_envs_list = []
    # iterates over processes, find processes with suitable env
    for pid in listdir('/proc'):
        if pid[0].isdecimal() is False:
            continue
        one_env = re_pid_environ(pid)
        unsorted_envs_list.append(one_env)
    env = set(unsorted_envs_list)
    env.discard(None)

    # deduplicate dbus
    new_env = []
    end = []
    for i in env:
        key = i[0] + i[1]
        if key not in end:
            end.append(key)
            new_env.append(i)
        else:
            continue

    return new_env

help_message = '''Usage:
  {} [notify-send options] summary [body text]
Examples:
  {} mytitle mytext
  {} -i dialog-warning earlyoom "killing process X"'''.format(
    argv[0], argv[0], argv[0])

if len(argv) == 1:
    print(help_message)
    exit(1)

if len(argv) == 2:
    if argv[1] == '-h' or argv[1] == '--help':
        print(help_message)
        exit()

# This script should be executed with euid=0
try:
    rline1('/proc/1/environ')
except PermissionError:
    print('{}: PermissionError'.format(argv[0]))
    exit(1)

wait_time = 10

display_env = 'DISPLAY='
dbus_env = 'DBUS_SESSION_BUS_ADDRESS='
user_env = 'USER='

list_with_envs = root_notify_env()

# if somebody logged in with GUI
if len(list_with_envs) > 0:

    # iterating over logged-in users
    for i in list_with_envs:

        username, display_env, dbus_env = i[0], i[1], i[2]
        display_tuple = display_env.partition('=')
        dbus_tuple = dbus_env.partition('=')
        display_value = display_tuple[2]
        dbus_value = dbus_tuple[2]

        cmd = [
            'sudo', '-u', username,
            'env',
            'DISPLAY=' + display_value,
            'DBUS_SESSION_BUS_ADDRESS=' + dbus_value,
            'notify-send'
        ]

        cmd.extend(argv[1:])

        with Popen(cmd) as proc:
            try:
                proc.wait(timeout=wait_time)
            except TimeoutExpired:
                proc.kill()
                print('TimeoutExpired: notify user:' + username)
else:
    print('Nobody logged-in with GUI. Nothing to do.')
<commit_msg>Remove contrib/notify_all_users.py<commit_after><|endoftext|>


<commit_before>__author__ = 'mpetyx'

from celery import shared_task
from celery.utils.log import get_task_logger
from celery.schedules import crontab
import celery
logger = get_task_logger(__name__)
import datetime
from questionnaire.models import RunInfoHistory, Subject, RunInfo
from django.http import HttpResponse
from django.template import Context
from django.template.loader import render_to_string, get_template
from django.core.mail import EmailMessage
from datetime import date
import os
from datetime import timedelta
from .models import Campaign
from questionnaire.views import *
from django.contrib.sites.models import Site

current_site = Site.objects.all()[0].name

def generate_campaign_run( questionnaire_id, subject_id=None):

    qu = get_object_or_404(Questionnaire, id=questionnaire_id)
    qs = qu.questionsets()[0]

    if subject_id is not None:
        # su = get_object_or_404(Subject, email=subject_id)
        su = Subject.objects.get_or_create(email=subject_id)
        su = su[0]
        su.save()
    else:
        su = Subject.objects.filter(givenname='Anonymous', surname='User')[0:1]
        if su:
            su = su[0]
        else:
            su = Subject(givenname='Anonymous', surname='User')
            su.save()

    str_to_hash = "".join(map(lambda i: chr(random.randint(0, 255)), range(16)))
    str_to_hash += settings.SECRET_KEY
    key = md5(str_to_hash).hexdigest()

    run = RunInfo(subject=su, random=key, runid=key, questionset=qs)
    run.save()

    questionnaire_start.send(sender=None, runinfo=run, questionnaire=qu)

    return str(current_site)+"/q/%s/"%key

def retrieve_campaign_run( questionnaire_id, subject):

    qu = get_object_or_404(Questionnaire, id=questionnaire_id)
    qs = qu.questionsets()[0]

    if RunInfo.objects.filter(subject__email=subject, questionset=qs):
        run_key = RunInfo.objects.get(subject__email=subject, questionset=qs).runid

        return str(current_site)+"/q/%s/"%run_key
    else:
        return generate_campaign_run(questionnaire_id, subject)

@shared_task(ignore_result=True)
def send_email_alert(email, questionnaire):
    subject = "You should Complete your Questionaire!"
    to = [email]
    from_email = 'forgot_questionaires@apis.technology'

    ctx = {
        # 'user': str(user.first_name+ " "+user.last_name),
        # 'invoice_id': invoice_id,
        # 'amount' : amount,
        # 'overall_balance':balance,
        # 'billing_date':str(date.today())
        'questionnaire':str(questionnaire)
    }

    message = get_template('mails/questionaire.html').render(Context(ctx))
    msg = EmailMessage(subject, message, to=to, from_email=from_email)
    msg.content_subtype = 'html'
    msg.send()

    return True

@shared_task(ignore_result=True)
def send_email_campagin(email, qu):
    subject = "You should Complete your Questionaire!"
    to = [email]
    from_email = 'welcome_questionaires@apis.technology'

    ctx = {
        # 'user': str(user.first_name+ " "+user.last_name),
        # 'invoice_id': invoice_id,
        # 'amount' : amount,
        # 'overall_balance':balance,
        'qu':str(qu)
    }

    message = get_template('mails/welcome_questionaire.html').render(Context(ctx))
    msg = EmailMessage(subject, message, to=to, from_email=from_email)
    msg.content_subtype = 'html'
    msg.send()

    return True

@shared_task(ignore_result=True)
def start_campaign(emails):

    for email in emails:
        send_email_campagin.delay(email)

# @celery.decorators.periodic_task(run_every=crontab(day_of_month=[1,15]),ignore_result=True,name="task_check_who_filled_the_questionaire",)
@celery.decorators.periodic_task(run_every=timedelta(seconds=30),ignore_result=True,name="task_check_who_filled_the_questionaire",)
def check_who_filled_the_questionaire():
    for campaign in Campaign.objects.all():
        questionnaires = campaign.questionnaires.all()
        for questionnaire in questionnaires:
            emails = campaign.emails
            for email in emails:
                if not RunInfoHistory.objects.filter(subject__email=email,questionnaire=questionnaire):

                    send_email_alert.delay(email,retrieve_campaign_run(questionnaire.id,email))

# from email_campaigns.tasks import send_email
# send_email("mpetyx@me.com")
<commit_msg>changing mail encoding<commit_after>__author__ = 'mpetyx'

from celery import shared_task
from celery.utils.log import get_task_logger
from celery.schedules import crontab
import celery
logger = get_task_logger(__name__)
import datetime
from questionnaire.models import RunInfoHistory, Subject, RunInfo
from django.http import HttpResponse
from django.template import Context
from django.template.loader import render_to_string, get_template
from django.core.mail import EmailMessage
from datetime import date
import os
from datetime import timedelta
from .models import Campaign
from questionnaire.views import *
from django.contrib.sites.models import Site

current_site = Site.objects.all()[0].name

def generate_campaign_run( questionnaire_id, subject_id=None):

    qu = get_object_or_404(Questionnaire, id=questionnaire_id)
    qs = qu.questionsets()[0]

    if subject_id is not None:
        # su = get_object_or_404(Subject, email=subject_id)
        su = Subject.objects.get_or_create(email=subject_id)
        su = su[0]
        su.save()
    else:
        su = Subject.objects.filter(givenname='Anonymous', surname='User')[0:1]
        if su:
            su = su[0]
        else:
            su = Subject(givenname='Anonymous', surname='User')
            su.save()

    str_to_hash = "".join(map(lambda i: chr(random.randint(0, 255)), range(16)))
    str_to_hash += settings.SECRET_KEY
    key = md5(str_to_hash).hexdigest()

    run = RunInfo(subject=su, random=key, runid=key, questionset=qs)
    run.save()

    questionnaire_start.send(sender=None, runinfo=run, questionnaire=qu)

    return str(current_site)+"/q/%s/"%key

def retrieve_campaign_run( questionnaire_id, subject):

    qu = get_object_or_404(Questionnaire, id=questionnaire_id)
    qs = qu.questionsets()[0]

    if RunInfo.objects.filter(subject__email=subject, questionset=qs):
        run_key = RunInfo.objects.get(subject__email=subject, questionset=qs).runid

        return str(current_site)+"/q/%s/"%run_key
    else:
        return generate_campaign_run(questionnaire_id, subject)

@shared_task(ignore_result=True)
def send_email_alert(email, questionnaire):
    subject = "You should Complete your Questionaire!"
    to = [email]
    from_email = 'forgot_questionaires@apis.technology'

    ctx = {
        # 'user': str(user.first_name+ " "+user.last_name),
        # 'invoice_id': invoice_id,
        # 'amount' : amount,
        # 'overall_balance':balance,
        # 'billing_date':str(date.today())
        'questionnaire':str(questionnaire)
    }

    message = get_template('mails/questionaire.html').render(Context(ctx))
    msg = EmailMessage(subject, message, to=to, from_email=from_email)
    msg.content_subtype = 'text/html'
    msg.send()

    return True

@shared_task(ignore_result=True)
def send_email_campagin(email, qu):
    subject = "You should Complete your Questionaire!"
    to = [email]
    from_email = 'welcome_questionaires@apis.technology'

    ctx = {
        # 'user': str(user.first_name+ " "+user.last_name),
        # 'invoice_id': invoice_id,
        # 'amount' : amount,
        # 'overall_balance':balance,
        'qu':str(qu)
    }

    message = get_template('mails/welcome_questionaire.html').render(Context(ctx))
    msg = EmailMessage(subject, message, to=to, from_email=from_email)
    msg.content_subtype = 'html'
    msg.send()

    return True

@shared_task(ignore_result=True)
def start_campaign(emails):

    for email in emails:
        send_email_campagin.delay(email)

# @celery.decorators.periodic_task(run_every=crontab(day_of_month=[1,15]),ignore_result=True,name="task_check_who_filled_the_questionaire",)
@celery.decorators.periodic_task(run_every=timedelta(seconds=30),ignore_result=True,name="task_check_who_filled_the_questionaire",)
def check_who_filled_the_questionaire():
    for campaign in Campaign.objects.all():
        questionnaires = campaign.questionnaires.all()
        for questionnaire in questionnaires:
            emails = campaign.emails
            for email in emails:
                if not RunInfoHistory.objects.filter(subject__email=email,questionnaire=questionnaire):

                    send_email_alert.delay(email,retrieve_campaign_run(questionnaire.id,email))

# from email_campaigns.tasks import send_email
# send_email("mpetyx@me.com")
<|endoftext|>