<commit_before># postgres.py
# Copyright (C) 2005 Michael Bayer mike_mp@zzzcomputing.com
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

import sys, StringIO, string, types, re

import sqlalchemy.sql as sql
import sqlalchemy.engine as engine
import sqlalchemy.schema as schema
import sqlalchemy.ansisql as ansisql
import sqlalchemy.types as sqltypes
from sqlalchemy.ansisql import *
try:
    import psycopg2 as psycopg
except:
    try:
        import psycopg
    except:
        psycopg = None

class PGNumeric(sqltypes.Numeric):
    def get_col_spec(self):
        return "NUMERIC(%(precision)s, %(length)s)" % {'precision': self.precision, 'length' : self.length}
class PGInteger(sqltypes.Integer):
    def get_col_spec(self):
        return "INTEGER"
class PGDateTime(sqltypes.DateTime):
    def get_col_spec(self):
        return "TIMESTAMP"
class PGText(sqltypes.TEXT):
    def get_col_spec(self):
        return "TEXT"
class PGString(sqltypes.String):
    def get_col_spec(self):
        return "VARCHAR(%(length)s)" % {'length' : self.length}
class PGChar(sqltypes.CHAR):
    def get_col_spec(self):
        return "CHAR(%(length)s)" % {'length' : self.length}
class PGBinary(sqltypes.Binary):
    def get_col_spec(self):
        return "BYTEA"
class PGBoolean(sqltypes.Boolean):
    def get_col_spec(self):
        return "BOOLEAN"

colspecs = {
    sqltypes.Integer : PGInteger,
    sqltypes.Numeric : PGNumeric,
    sqltypes.DateTime : PGDateTime,
    sqltypes.String : PGString,
    sqltypes.Binary : PGBinary,
    sqltypes.Boolean : PGBoolean,
    sqltypes.TEXT : PGText,
    sqltypes.CHAR: PGChar,
}

ischema_names = {
    'integer' : PGInteger,
    'character varying' : PGString,
    'character' : PGChar,
    'text' : PGText,
    'numeric' : PGNumeric,
    'timestamp without time zone' : PGDateTime,
    'bytea' : PGBinary,
}

generic_engine = ansisql.engine()
gen_columns = schema.Table("columns", generic_engine,
    Column("table_schema", String),
    Column("table_name", String),
    Column("column_name", String),
    Column("is_nullable", Integer),
    Column("data_type", String),
    Column("ordinal_position", Integer),
    Column("character_maximum_length", Integer),
    Column("numeric_precision", Integer),
    Column("numeric_precision_radix", Integer),
    schema="information_schema")

gen_constraints = schema.Table("table_constraints", generic_engine,
    Column("table_schema", String),
    Column("table_name", String),
    Column("constraint_name", String),
    Column("constraint_type", String),
    schema="information_schema")

gen_column_constraints = schema.Table("constraint_column_usage", generic_engine,
    Column("table_schema", String),
    Column("table_name", String),
    Column("column_name", String),
    Column("constraint_name", String),
    schema="information_schema")

def engine(opts, **params):
    return PGSQLEngine(opts, **params)

class PGSQLEngine(ansisql.ANSISQLEngine):
    def __init__(self, opts, module = None, **params):
        if module is None:
            if psycopg is None:
                raise "Couldnt locate psycopg1 or psycopg2: specify postgres module argument"
            self.module = psycopg
        else:
            self.module = module
        self.opts = opts or {}
        ansisql.ANSISQLEngine.__init__(self, **params)

    def connect_args(self):
        return [[], self.opts]

    def type_descriptor(self, typeobj):
        return sqltypes.adapt_type(typeobj, colspecs)

    def last_inserted_ids(self):
        return self.context.last_inserted_ids

    def compiler(self, statement, bindparams, **kwargs):
        return PGCompiler(self, statement, bindparams, **kwargs)

    def schemagenerator(self, proxy, **params):
        return PGSchemaGenerator(proxy, **params)

    def schemadropper(self, proxy, **params):
        return PGSchemaDropper(proxy, **params)

    def reflecttable(self, table):
        raise "not implemented"

    def last_inserted_ids(self):
        # if we used sequences or already had all values for the last inserted row,
        # return that list
        if self.context.last_inserted_ids is not None:
            return self.context.last_inserted_ids

        # else we have to use lastrowid and select the most recently inserted row
        table = self.context.last_inserted_table
        if self.context.lastrowid is not None and table is not None and len(table.primary_keys):
            row = sql.select(table.primary_keys, table.rowid_column == self.context.lastrowid).execute().fetchone()
            return [v for v in row]
        else:
            return None

    def pre_exec(self, connection, cursor, statement, parameters, echo = None, compiled = None, **kwargs):
        if compiled is None: return
        if getattr(compiled, "isinsert", False):
            if isinstance(parameters, list):
                plist = parameters
            else:
                plist = [parameters]
            # inserts are usually one at a time.  but if we got a list of parameters,
            # it will calculate last_inserted_ids for just the last row in the list.
            # TODO: why not make last_inserted_ids a 2D array since we have to explicitly sequence
            # it or post-select anyway
            for param in plist:
                last_inserted_ids = []
                need_lastrowid=False
                for primary_key in compiled.statement.table.primary_keys:
                    if not param.has_key(primary_key.key) or param[primary_key.key] is None:
                        if primary_key.sequence is not None and not primary_key.sequence.optional:
                            if echo is True or self.echo:
                                self.log("select nextval('%s')" % primary_key.sequence.name)
                            cursor.execute("select nextval('%s')" % primary_key.sequence.name)
                            newid = cursor.fetchone()[0]
                            param[primary_key.key] = newid
                            last_inserted_ids.append(param[primary_key.key])
                        else:
                            need_lastrowid = True
                    else:
                        last_inserted_ids.append(param[primary_key.key])
                if need_lastrowid:
                    self.context.last_inserted_ids = None
                else:
                    self.context.last_inserted_ids = last_inserted_ids

    def _executemany(self, c, statement, parameters):
        """we need accurate rowcounts for updates, inserts and deletes.  psycopg2 is not nice enough
        to produce this correctly for an executemany, so we do our own executemany here."""
        rowcount = 0
        for param in parameters:
            c.execute(statement, param)
            rowcount += c.rowcount
        self.context.rowcount = rowcount

    def post_exec(self, connection, cursor, statement, parameters, echo = None, compiled = None, **kwargs):
        if compiled is None: return
        if getattr(compiled, "isinsert", False):
            table = compiled.statement.table
            self.context.last_inserted_table = table
            self.context.lastrowid = cursor.lastrowid

    def dbapi(self):
        return self.module

    def reflecttable(self, table):
        columns = gen_columns.toengine(table.engine)
        constraints = gen_constraints.toengine(table.engine)
        column_constraints = gen_column_constraints.toengine(table.engine)

        s = select([columns, constraints.c.constraint_type],
            columns.c.table_name==table.name,
            order_by=[columns.c.ordinal_position])

        s.append_from(sql.outerjoin(columns, column_constraints,
                              sql.and_(
                                      columns.c.table_name==column_constraints.c.table_name,
                                      columns.c.table_schema==column_constraints.c.table_schema,
                                      columns.c.column_name==column_constraints.c.column_name,
                                  )).outerjoin(constraints,
                                  sql.and_(
                                      column_constraints.c.table_schema==constraints.c.table_schema,
                                      column_constraints.c.constraint_name==constraints.c.constraint_name,
                                      constraints.c.constraint_type=='PRIMARY KEY'
                                  )))

        if table.schema is not None:
            s.append_whereclause(columns.c.table_schema==table.schema)
        else:
            current_schema = text("select current_schema()", table.engine).scalar()
            s.append_whereclause(columns.c.table_schema==current_schema)

        c = s.execute()
        while True:
            row = c.fetchone()
            if row is None:
                break
            #print "row! " + repr(row)
            (name, type, nullable, primary_key, charlen, numericprec, numericradix) = (
                row[columns.c.column_name],
                row[columns.c.data_type],
                not row[columns.c.is_nullable],
                row[constraints.c.constraint_type] is not None,
                row[columns.c.character_maximum_length],
                row[columns.c.numeric_precision],
                row[columns.c.numeric_precision_radix],
                )

            #match = re.match(r'(\w+)(\(.*?\))?', type)
            #coltype = match.group(1)
            #args = match.group(2)

            #print "coltype: " + repr(coltype) + " args: " + repr(args)
            coltype = ischema_names[type]
            table.append_item(schema.Column(name, coltype, primary_key = primary_key, nullable = nullable))
        return
        c = self.execute("PRAGMA foreign_key_list(" + table.name + ")", {})
        while True:
            row = c.fetchone()
            if row is None:
                break
            (tablename, localcol, remotecol) = (row[2], row[3], row[4])
            #print "row! " + repr(row)
            remotetable = Table(tablename, self, autoload = True)
            table.c[localcol].foreign_key = schema.ForeignKey(remotetable.c[remotecol])

class PGCompiler(ansisql.ANSICompiler):
    def bindparam_string(self, name):
        return "%(" + name + ")s"

    def visit_insert(self, insert):
        """inserts are required to have the primary keys be explicitly present.
         mapper will by default not put them in the insert statement to comply
         with autoincrement fields that require they not be present.  so,
         put them all in for columns where sequence usage is defined."""
        for c in insert.table.primary_keys:
            if c.sequence is not None and not c.sequence.optional:
                self.bindparams[c.key] = None
        return ansisql.ANSICompiler.visit_insert(self, insert)

class PGSchemaGenerator(ansisql.ANSISchemaGenerator):
    def get_column_specification(self, column):
        colspec = column.name
        if column.primary_key and isinstance(column.type, types.Integer) and (column.sequence is None or column.sequence.optional):
            colspec += " SERIAL"
        else:
            colspec += " " + column.type.get_col_spec()

        if not column.nullable:
            colspec += " NOT NULL"
        if column.primary_key:
            colspec += " PRIMARY KEY"
        if column.foreign_key:
            colspec += " REFERENCES %s(%s)" % (column.column.foreign_key.column.table.name, column.column.foreign_key.column.name)
        return colspec

    def visit_sequence(self, sequence):
        if not sequence.optional:
            self.append("CREATE SEQUENCE %s" % sequence.name)
            self.execute()

class PGSchemaDropper(ansisql.ANSISchemaDropper):
    def visit_sequence(self, sequence):
        if not sequence.optional:
            self.append("DROP SEQUENCE %s" % sequence.name)
            self.execute()
<commit_msg><commit_after># postgres.py
# Copyright (C) 2005 Michael Bayer mike_mp@zzzcomputing.com
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

import sys, StringIO, string, types, re

import sqlalchemy.sql as sql
import sqlalchemy.engine as engine
import sqlalchemy.schema as schema
import sqlalchemy.ansisql as ansisql
import sqlalchemy.types as sqltypes
from sqlalchemy.ansisql import *
try:
    import psycopg2 as psycopg
except:
    try:
        import psycopg
    except:
        psycopg = None

class PGNumeric(sqltypes.Numeric):
    def get_col_spec(self):
        return "NUMERIC(%(precision)s, %(length)s)" % {'precision': self.precision, 'length' : self.length}
class PGInteger(sqltypes.Integer):
    def get_col_spec(self):
        return "INTEGER"
class PGDateTime(sqltypes.DateTime):
    def get_col_spec(self):
        return "TIMESTAMP"
class PGText(sqltypes.TEXT):
    def get_col_spec(self):
        return "TEXT"
class PGString(sqltypes.String):
    def get_col_spec(self):
        return "VARCHAR(%(length)s)" % {'length' : self.length}
class PGChar(sqltypes.CHAR):
    def get_col_spec(self):
        return "CHAR(%(length)s)" % {'length' : self.length}
class PGBinary(sqltypes.Binary):
    def get_col_spec(self):
        return "BYTEA"
class PGBoolean(sqltypes.Boolean):
    def get_col_spec(self):
        return "BOOLEAN"

colspecs = {
    sqltypes.Integer : PGInteger,
    sqltypes.Numeric : PGNumeric,
    sqltypes.DateTime : PGDateTime,
    sqltypes.String : PGString,
    sqltypes.Binary : PGBinary,
    sqltypes.Boolean : PGBoolean,
    sqltypes.TEXT : PGText,
    sqltypes.CHAR: PGChar,
}

ischema_names = {
    'integer' : PGInteger,
    'character varying' : PGString,
    'character' : PGChar,
    'text' : PGText,
    'numeric' : PGNumeric,
    'timestamp without time zone' : PGDateTime,
    'bytea' : PGBinary,
}

generic_engine = ansisql.engine()
gen_columns = schema.Table("columns", generic_engine,
    Column("table_schema", String),
    Column("table_name", String),
    Column("column_name", String),
    Column("is_nullable", Integer),
    Column("data_type", String),
    Column("ordinal_position", Integer),
    Column("character_maximum_length", Integer),
    Column("numeric_precision", Integer),
    Column("numeric_scale", Integer),
    schema="information_schema")

gen_constraints = schema.Table("table_constraints", generic_engine,
    Column("table_schema", String),
    Column("table_name", String),
    Column("constraint_name", String),
    Column("constraint_type", String),
    schema="information_schema")

gen_column_constraints = schema.Table("constraint_column_usage", generic_engine,
    Column("table_schema", String),
    Column("table_name", String),
    Column("column_name", String),
    Column("constraint_name", String),
    schema="information_schema")

def engine(opts, **params):
    return PGSQLEngine(opts, **params)

class PGSQLEngine(ansisql.ANSISQLEngine):
    def __init__(self, opts, module = None, **params):
        if module is None:
            if psycopg is None:
                raise "Couldnt locate psycopg1 or psycopg2: specify postgres module argument"
            self.module = psycopg
        else:
            self.module = module
        self.opts = opts or {}
        ansisql.ANSISQLEngine.__init__(self, **params)

    def connect_args(self):
        return [[], self.opts]

    def type_descriptor(self, typeobj):
        return sqltypes.adapt_type(typeobj, colspecs)

    def last_inserted_ids(self):
        return self.context.last_inserted_ids

    def compiler(self, statement, bindparams, **kwargs):
        return PGCompiler(self, statement, bindparams, **kwargs)

    def schemagenerator(self, proxy, **params):
        return PGSchemaGenerator(proxy, **params)

    def schemadropper(self, proxy, **params):
        return PGSchemaDropper(proxy, **params)

    def reflecttable(self, table):
        raise "not implemented"

    def last_inserted_ids(self):
        # if we used sequences or already had all values for the last inserted row,
        # return that list
        if self.context.last_inserted_ids is not None:
            return self.context.last_inserted_ids

        # else we have to use lastrowid and select the most recently inserted row
        table = self.context.last_inserted_table
        if self.context.lastrowid is not None and table is not None and len(table.primary_keys):
            row = sql.select(table.primary_keys, table.rowid_column == self.context.lastrowid).execute().fetchone()
            return [v for v in row]
        else:
            return None

    def pre_exec(self, connection, cursor, statement, parameters, echo = None, compiled = None, **kwargs):
        if compiled is None: return
        if getattr(compiled, "isinsert", False):
            if isinstance(parameters, list):
                plist = parameters
            else:
                plist = [parameters]
            # inserts are usually one at a time.  but if we got a list of parameters,
            # it will calculate last_inserted_ids for just the last row in the list.
            # TODO: why not make last_inserted_ids a 2D array since we have to explicitly sequence
            # it or post-select anyway
            for param in plist:
                last_inserted_ids = []
                need_lastrowid=False
                for primary_key in compiled.statement.table.primary_keys:
                    if not param.has_key(primary_key.key) or param[primary_key.key] is None:
                        if primary_key.sequence is not None and not primary_key.sequence.optional:
                            if echo is True or self.echo:
                                self.log("select nextval('%s')" % primary_key.sequence.name)
                            cursor.execute("select nextval('%s')" % primary_key.sequence.name)
                            newid = cursor.fetchone()[0]
                            param[primary_key.key] = newid
                            last_inserted_ids.append(param[primary_key.key])
                        else:
                            need_lastrowid = True
                    else:
                        last_inserted_ids.append(param[primary_key.key])
                if need_lastrowid:
                    self.context.last_inserted_ids = None
                else:
                    self.context.last_inserted_ids = last_inserted_ids

    def _executemany(self, c, statement, parameters):
        """we need accurate rowcounts for updates, inserts and deletes.  psycopg2 is not nice enough
        to produce this correctly for an executemany, so we do our own executemany here."""
        rowcount = 0
        for param in parameters:
            c.execute(statement, param)
            rowcount += c.rowcount
        self.context.rowcount = rowcount

    def post_exec(self, connection, cursor, statement, parameters, echo = None, compiled = None, **kwargs):
        if compiled is None: return
        if getattr(compiled, "isinsert", False):
            table = compiled.statement.table
            self.context.last_inserted_table = table
            self.context.lastrowid = cursor.lastrowid

    def dbapi(self):
        return self.module

    def reflecttable(self, table):
        columns = gen_columns.toengine(table.engine)
        constraints = gen_constraints.toengine(table.engine)
        column_constraints = gen_column_constraints.toengine(table.engine)

        s = select([columns, constraints.c.constraint_type],
            columns.c.table_name==table.name,
            order_by=[columns.c.ordinal_position])

        s.append_from(sql.outerjoin(columns, column_constraints,
                              sql.and_(
                                      columns.c.table_name==column_constraints.c.table_name,
                                      columns.c.table_schema==column_constraints.c.table_schema,
                                      columns.c.column_name==column_constraints.c.column_name,
                                  )).outerjoin(constraints,
                                  sql.and_(
                                      column_constraints.c.table_schema==constraints.c.table_schema,
                                      column_constraints.c.constraint_name==constraints.c.constraint_name,
                                      constraints.c.constraint_type=='PRIMARY KEY'
                                  )))

        if table.schema is not None:
            s.append_whereclause(columns.c.table_schema==table.schema)
        else:
            current_schema = text("select current_schema()", table.engine).scalar()
            s.append_whereclause(columns.c.table_schema==current_schema)

        c = s.execute()
        while True:
            row = c.fetchone()
            if row is None:
                break
            #print "row! " + repr(row)
            (name, type, nullable, primary_key, charlen, numericprec, numericscale) = (
                row[columns.c.column_name],
                row[columns.c.data_type],
                not row[columns.c.is_nullable],
                row[constraints.c.constraint_type] is not None,
                row[columns.c.character_maximum_length],
                row[columns.c.numeric_precision],
                row[columns.c.numeric_scale],
                )

            #match = re.match(r'(\w+)(\(.*?\))?', type)
            #coltype = match.group(1)
            #args = match.group(2)

            #print "coltype: " + repr(coltype) + " args: " + repr(args)
            coltype = ischema_names[type]
            table.append_item(schema.Column(name, coltype, primary_key = primary_key, nullable = nullable))
        return
        c = self.execute("PRAGMA foreign_key_list(" + table.name + ")", {})
        while True:
            row = c.fetchone()
            if row is None:
                break
            (tablename, localcol, remotecol) = (row[2], row[3], row[4])
            #print "row! " + repr(row)
            remotetable = Table(tablename, self, autoload = True)
            table.c[localcol].foreign_key = schema.ForeignKey(remotetable.c[remotecol])

class PGCompiler(ansisql.ANSICompiler):
    def bindparam_string(self, name):
        return "%(" + name + ")s"

    def visit_insert(self, insert):
        """inserts are required to have the primary keys be explicitly present.
         mapper will by default not put them in the insert statement to comply
         with autoincrement fields that require they not be present.  so,
         put them all in for columns where sequence usage is defined."""
        for c in insert.table.primary_keys:
            if c.sequence is not None and not c.sequence.optional:
                self.bindparams[c.key] = None
        return ansisql.ANSICompiler.visit_insert(self, insert)

class PGSchemaGenerator(ansisql.ANSISchemaGenerator):
    def get_column_specification(self, column):
        colspec = column.name
        if column.primary_key and isinstance(column.type, types.Integer) and (column.sequence is None or column.sequence.optional):
            colspec += " SERIAL"
        else:
            colspec += " " + column.type.get_col_spec()

        if not column.nullable:
            colspec += " NOT NULL"
        if column.primary_key:
            colspec += " PRIMARY KEY"
        if column.foreign_key:
            colspec += " REFERENCES %s(%s)" % (column.column.foreign_key.column.table.name, column.column.foreign_key.column.name)
        return colspec

    def visit_sequence(self, sequence):
        if not sequence.optional:
            self.append("CREATE SEQUENCE %s" % sequence.name)
            self.execute()

class PGSchemaDropper(ansisql.ANSISchemaDropper):
    def visit_sequence(self, sequence):
        if not sequence.optional:
            self.append("DROP SEQUENCE %s" % sequence.name)
            self.execute()
<|endoftext|>


<commit_before>__version__ = 0.13

from TASSELpy.TASSELbridge import TASSELbridge
<commit_msg>Updated version<commit_after>__version__ = 0.14

from TASSELpy.TASSELbridge import TASSELbridge
<|endoftext|>


<commit_before># coding=utf-8
"""
parse config.json
"""

import json
import os

from .enums import LogLevel
from .exceptions.config import *
from .utils import listAttr, convertDictToObject, ConvertedObject

class Config:
    """
    represent config.json.
    You can access configures with

    Example:
    ```python
    config = Config()
    config.accounts.test_bot.ck
    ```
    """

    def __init__(self):
        if not os.path.isfile(Path.Config.value):
            raise NotFoundConfigError

        try:
            with open(Path.Config.value) as f:
                config = convertDictToObject(json.load(f))
        except json.JSONDecodeError:
            raise InvalidConfigSyntaxError

        if not hasattr(config, "accounts"):
            raise InsufficientAttributeError("accounts")

        for k in listAttr(config.accounts):
            v = getattr(config.accounts, k)
            if hasattr(v, "application") and hasattr(config, "application"):
                app = getattr(config.application, v.application)
                if not app:
                    raise InsufficientAttributeError("application")
                if not hasattr(app, "ck") or not hasattr(app, "cs"):
                    raise InsufficientAttributeError("accounts[x].ck or accounts[x].cs")

                v.ck, v.cs = app.ck, app.cs

            for attr in ["ck", "cs", "at", "ats", "id", "sn"]:
                if not hasattr(v, attr):
                    raise InsufficientAttributeError("accounts[x].{}".format(attr))
            setattr(config.accounts, k, v)

        if not hasattr(config, "mute"):
            config.mute = ConvertedObject()
        for attr in ["via", "user_id", "user_sn", "domain"]:
            hasattr(config.mute, attr) or setattr(config.mute, attr, [])

        # TODO: implement permissions

        if not hasattr(config, "log_level"):
            setattr(config, "log_level", LogLevel.Error)
        elif not hasattr(LogLevel, config.log_level.title()):
            config.log_level = LogLevel.Error
        else:
            config.log_level = getattr(LogLevel, config.log_level.title())

        [setattr(self, x, getattr(config, x)) for x in listAttr(config)]
<commit_msg>Add: directory config parsing<commit_after># coding=utf-8
"""
parse config.json
"""

import json
import os

from .enums import LogLevel
from .exceptions.config import *
from .utils import listAttr, convertDictToObject, ConvertedObject

class Config:
    """
    represent config.json.
    You can access configures with

    Example:
    ```python
    config = Config()
    config.accounts.test_bot.ck
    ```
    """
    application = {}
    account = {}
    mute = {}
    directory = {}
    log_level = None

    def __init__(self):
        if not os.path.isfile(configPath):
            raise NotFoundConfigError(f"{configPath} is not found.")

        try:
            with open(configPath) as f:
                config = convertDictToObject(json.load(f))
        except json.JSONDecodeError:
            raise InvalidConfigSyntaxError(f"{configPath} has invalid syntax.")

        if not hasattr(config, "accounts"):
            raise InsufficientAttributeError("accounts")

        for k in listAttr(config.accounts):
            v = getattr(config.accounts, k)
            if hasattr(v, "application") and hasattr(config, "application"):
                app = getattr(config.application, v.application)
                if not app:
                    raise InsufficientAttributeError("application")
                if not hasattr(app, "ck") or not hasattr(app, "cs"):
                    raise InsufficientAttributeError("accounts[x].ck or accounts[x].cs")
                v.ck, v.cs = app.ck, app.cs

            for attr in ["ck", "cs", "at", "ats", "id", "sn"]:
                if not hasattr(v, attr):
                    raise InsufficientAttributeError("accounts[x].{}".format(attr))
            setattr(config.accounts, k, v)

        if not hasattr(config, "mute"):
            config.mute = ConvertedObject()
        for attr in ["via", "user_id", "user_sn", "domain"]:
            hasattr(config.mute, attr) or setattr(config.mute, attr, [])

        if not hasattr(config, "directory"):
            config.directory = ConvertedObject()
        for attr in ["plugins", "logs", "tmp", "cache", "assets", "api"]:
            hasattr(config.directory, attr) or setattr(config.directory, attr, attr)

        if not hasattr(config, "log_level"):
            setattr(config, "log_level", LogLevel.Error)
        elif not hasattr(LogLevel, config.log_level.title()):
            config.log_level = LogLevel.Error
        else:
            config.log_level = getattr(LogLevel, config.log_level.title())

        [setattr(self, x, getattr(config, x)) for x in listAttr(config)]
<|endoftext|>


<commit_before>import asyncio
import datetime
import re

import discord
from discord.ext import commands

class TimeParser:
    def __init__(self, argument):
        compiled = re.compile(r'(?:(?P<hours>\d+)h)?(?:(?P<minutes>\d+)m)?(?:(?P<seconds>\d+)s)?')
        self.original = argument
        try:
            self.seconds = int(argument)
        except ValueError as e:
            match = compiled.match(argument)
            if match is None or not match.group(0):
                raise commands.BadArgument('Failed to parse time.') from e

            self.seconds = 0
            hours = match.group('hours')
            if hours is not None:
                self.seconds += int(hours) * 3600
            minutes = match.group('minutes')
            if minutes is not None:
                self.seconds += int(minutes) * 60
            seconds = match.group('seconds')
            if seconds is not None:
                self.seconds += int(seconds)

        if self.seconds < 0:
            raise commands.BadArgument("I don't do negative time.")

        if self.seconds > 604800:  # 7 days
            raise commands.BadArgument("That's a bit too far in the future for me.")

class Meta:
    def __init__(self, bot: commands.Bot):
        self.bot = bot

    @commands.command()
    async def uptime(self, ctx: commands.Context):
        """Tells you how long the bot has been up for"""

        now = datetime.datetime.utcnow()
        delta = now - self.bot.uptime
        hours, remainder = divmod(int(delta.total_seconds()), 3600)
        minutes, seconds = divmod(remainder, 60)
        days, hours = divmod(hours, 24)

        fmt = '{h}h {m}m {s}s'
        if days:
            fmt = '{d}d ' + fmt

        await ctx.send(content='Uptime: **{}**'.format(fmt.format(d=days, h=hours, m=minutes, s=seconds)))

    @commands.command(aliases=['reminder', 'remind'])
    async def timer(self, ctx: commands.Context, time: TimeParser, *, message=''):
        """Reminds you of something after a certain amount of time.
        The time can optionally be specified with units such as 'h'
        for hours, 'm' for minutes and 's' for seconds. If no unit
        is given then it is assumed to be seconds. You can also combine
        multiple units together, e.g. 2h4m10s.
        """

        author = ctx.message.author
        message = message.replace('@everyone', '@\u200beveryone').replace('@here', '@\u200bhere')

        if not message:
            reminder = "Okay {0.mention}, I'll remind you in {1.seconds} seconds."
            completed = 'Time is up {0.mention}! You asked to be reminded about something.'
        else:
            reminder = '''Okay {0.mention}, I'll remind you about "{2}" in {1.seconds} seconds.'''
            completed = 'Time is up {0.mention}! You asked to be reminded about "{1}".'

        await ctx.send(reminder.format(author, time, message))
        await asyncio.sleep(time.seconds)
        await ctx.send(completed.format(author, message))

    @commands.command()
    @commands.guild_only()
    async def userinfo(self, ctx: commands.Context, *, member: discord.Member = None):
        """Shows info about a member.
        This cannot be used in private messages. If you don't specify
        a member then the info returned will be yours.
        """
        channel = ctx.channel
        if member is None:
            member = ctx.author

        e = discord.Embed()

        roles = [role.name.replace('@', '@\u200b') for role in member.roles]

        e.set_author(name=str(member), icon_url=member.avatar_url or member.default_avatar_url)
        e.set_footer(text='Member since').timestamp = member.joined_at
        e.add_field(name='ID', value=member.id)
        e.add_field(name='Current Name', value=member.display_name)
        e.add_field(name='Created', value=member.created_at)
        e.add_field(name='Roles', value=', '.join(roles))
        e.colour = member.colour

        if member.avatar:
            e.set_image(url=member.avatar_url)

        await ctx.send(embed=e)

    @commands.command()
    async def cleanup(self, ctx: commands.Context, limit=100):
        """Deletes the bot's messages up to the most 100 recent messages."""

        if limit > 100:
            raise commands.BadArgument('Limit is too high!')

        def is_me(m):
            return m.author.id == self.bot.user.id

        deleted = await ctx.channel.purge(limit=limit, check=is_me)
        await ctx.send(f'Deleted {len(deleted)} message(s)', delete_after=5)

def setup(bot):
    bot.add_cog(Meta(bot))
<commit_msg>Improve timer code<commit_after>import asyncio
import datetime
import re

import discord
from discord.ext import commands

class TimeParser:
    def __init__(self, argument):
        compiled = re.compile(r'(?:(?P<hours>\d+)h)?(?:(?P<minutes>\d+)m)?(?:(?P<seconds>\d+)s)?')
        self.original = argument
        try:
            self.seconds = int(argument)
        except ValueError as e:
            match = compiled.match(argument)
            if match is None or not match.group(0):
                raise commands.BadArgument('Failed to parse time.') from e

            self.seconds = 0
            hours = match.group('hours')
            if hours is not None:
                self.seconds += int(hours) * 3600
            minutes = match.group('minutes')
            if minutes is not None:
                self.seconds += int(minutes) * 60
            seconds = match.group('seconds')
            if seconds is not None:
                self.seconds += int(seconds)

        if self.seconds < 0:
            raise commands.BadArgument("I don't do negative time.")

        if self.seconds > 7 * 60 * 60:  # 7 days
            raise commands.BadArgument("That's a bit too far in the future for me.")

class Meta:
    def __init__(self, bot: commands.Bot):
        self.bot = bot

    @commands.command()
    async def uptime(self, ctx: commands.Context):
        """Tells you how long the bot has been up for"""

        now = datetime.datetime.utcnow()
        delta = now - self.bot.uptime
        hours, remainder = divmod(int(delta.total_seconds()), 3600)
        minutes, seconds = divmod(remainder, 60)
        days, hours = divmod(hours, 24)

        fmt = '{h}h {m}m {s}s'
        if days:
            fmt = '{d}d ' + fmt

        await ctx.send(content='Uptime: **{}**'.format(fmt.format(d=days, h=hours, m=minutes, s=seconds)))

    @commands.command(aliases=['reminder', 'remind'])
    async def timer(self, ctx: commands.Context, time: TimeParser, *, message='something'):
        """Reminds you of something after a certain amount of time.
        The time can optionally be specified with units such as 'h'
        for hours, 'm' for minutes and 's' for seconds. If no unit
        is given then it is assumed to be seconds. You can also combine
        multiple units together, e.g. 2h4m10s.
        """

        author = ctx.message.author
        message = message.replace('@everyone', '@\u200beveryone').replace('@here', '@\u200bhere')

        reminder = '''Okay {0.mention}, I'll remind you about "{2}" in {1.seconds} seconds.'''
        completed = 'Time is up {0.mention}! You asked to be reminded about "{1}".'

        await ctx.send(reminder.format(author, time, message))
        await asyncio.sleep(time.seconds)
        await ctx.send(completed.format(author, message))

    @commands.command()
    @commands.guild_only()
    async def userinfo(self, ctx: commands.Context, *, member: discord.Member = None):
        """Shows info about a member.
        This cannot be used in private messages. If you don't specify
        a member then the info returned will be yours.
        """
        if member is None:
            member = ctx.author

        e = discord.Embed()

        roles = [role.name.replace('@', '@\u200b') for role in member.roles]

        e.set_author(name=str(member), icon_url=member.avatar_url or member.default_avatar_url)
        e.set_footer(text='Member since').timestamp = member.joined_at
        e.add_field(name='ID', value=member.id)
        e.add_field(name='Current Name', value=member.display_name)
        e.add_field(name='Created', value=member.created_at)
        e.add_field(name='Roles', value=', '.join(roles))
        e.colour = member.colour

        if member.avatar:
            e.set_image(url=member.avatar_url)

        await ctx.send(embed=e)

    @commands.command()
    async def cleanup(self, ctx: commands.Context, limit=100):
        """Deletes the bot's messages up to the most 100 recent messages."""

        if limit > 100:
            raise commands.BadArgument('Limit is too high!')

        def is_me(m):
            return m.author.id == self.bot.user.id

        deleted = await ctx.channel.purge(limit=limit, check=is_me)
        await ctx.send(f'Deleted {len(deleted)} message(s)', delete_after=5)

def setup(bot):
    bot.add_cog(Meta(bot))
<|endoftext|>


<commit_before>import logging
import json
import random
import re
import requests

logger = logging.getLogger(__name__)

def findIndexOfSequence(data, sequence, startIndex=0):
    index = startIndex
    for token in sequence:
        index = data.find(token, index)
        if index == -1:
            return -1
    return index + len(sequence[-1])

def emojiFilter(input):
    ret = input.replace("{", ":_")
    ret = ret.replace("}", "_:")
    lastpos = None
    while ret.rfind(":_", 0, lastpos) != -1:
        lastpos = ret.rfind(":_", 0, lastpos)
        start = lastpos + 2
        end = ret.rfind("_:")
        content = ret[start:end]
        content = content.lower() #TODO: this lowers too much!
        content = content.replace("/", "")
        ret = ret[:start] + content + ret[end:]
    return ret

def getCardValue(cardName, setCode):
    url = "http://www.mtggoldfish.com/widgets/autocard/%s [%s]" % (cardName, setCode)
    headers = {
        'Pragma': 'no-cache',
        'Accept-Encoding': 'gzip, deflate, sdch',
        'Accept-Language': 'en-US,en;q=0.8,de;q=0.6,sv;q=0.4',
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.36',
        'Accept': 'text/javascript, application/javascript, application/ecmascript, application/x-ecmascript, */*; q=0.01',
        'Referer': 'http://www.mtggoldfish.com/widgets/autocard/%s' % cardName,
        'X-Requested-With': 'XMLHttpRequest',
        'Connection': 'keep-alive',
        'Cache-Control': 'no-cache'
    }
    response = requests.get(url, headers=headers)
    index = findIndexOfSequence(response.content, ["tcgplayer", "btn-shop-price", "$"])
    endIndex = response.content.find("\\n", index)
    try:
        value = float(response.content[index + 2:endIndex].replace(",", ""))
    except ValueError:
        value = 0

    return value

def getCard(name):
    queryUrl = "http://api.deckbrew.com/mtg/cards?name=%s" % name
    r = requests.get(queryUrl)
    cards = r.json()

    if len(cards) < 1:
        return None

    card = None
    for element in cards:
        if element["name"].lower() == name.lower():
            card = element

    if card:
        mostRecent = card["editions"][0]
        card["value"] = getCardValue(card["name"], mostRecent["set_id"])
    return card

def getSeasons(dciNumber):
    # Returns to current and last season for that DCI number
    url = "http://www.wizards.com/Magic/PlaneswalkerPoints/JavaScript/GetPointsHistoryModal"
    headers = {
        'Pragma': 'no-cache',
        'Origin': 'http://www.wizards.com',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'en-US,en;q=0.8,de;q=0.6,sv;q=0.4',
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.36',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'Accept': '*/*',
        'Cache-Control': 'no-cache',
        'X-Requested-With': 'XMLHttpRequest',
        'Cookie': 'f5_cspm=1234; BIGipServerWWWPWPPOOL01=353569034.20480.0000; __utmt=1; BIGipServerWWWPool1=3792701706.20480.0000; PlaneswalkerPointsSettings=0=0&lastviewed=9212399887; __utma=75931667.1475261136.1456488297.1456488297.1456488297.1; __utmb=75931667.5.10.1456488297; __utmc=75931667; __utmz=75931667.1456488297.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)',
        'Connection': 'keep-alive',
        'Referer': 'http://www.wizards.com/Magic/PlaneswalkerPoints/%s' % dciNumber
    }
    data = {"Parameters": {"DCINumber": dciNumber, "SelectedType": "Yearly"}}
    response = requests.post(url, headers=headers, data=json.dumps(data))

    if response.status_code is 200:
        seasons = []

        responseData = json.loads(response.content)
        markup = responseData["ModalContent"]
        searchPosition = markup.find("SeasonRange")

        while searchPosition != -1:
            pointsvalue = "PointsValue\">"
            searchPosition = markup.find(pointsvalue, searchPosition)
            searchPosition += len(pointsvalue)
            endPosition = markup.find("
", searchPosition)
            if endPosition != -1:
                value = markup[searchPosition:endPosition]
                seasons.append(int(value))
            searchPosition = markup.find("SeasonRange", searchPosition)

        return {"currentSeason": seasons[0], "lastSeason": seasons[1]}
    else:
        return None

class Messenger(object):
    def __init__(self, slack_clients):
        self.clients = slack_clients

    def send_message(self, channel_id, msg):
        # in the case of Group and Private channels, RTM channel payload is a complex dictionary
        if isinstance(channel_id, dict):
            channel_id = channel_id['id']
        logger.debug('Sending msg: {} to channel: {}'.format(msg, channel_id))
        channel = self.clients.rtm.server.channels.find(channel_id)
        channel.send_message("{}".format(msg.encode('ascii', 'ignore')))

    def write_help_message(self, channel_id):
        bot_uid = self.clients.bot_user_id()
        txt = '{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}'.format(
            "I'm your friendly Slack bot written in Python.  I'll *_respond_* to the following commands:",
            "> `hi <@" + bot_uid + ">` - I'll respond with a randomized greeting mentioning your username. :wave:",
            "> `<@" + bot_uid + "> joke` - I'll tell you one of my finest jokes, with a typing pause for effect. :laughing:",
            "> `<@" + bot_uid + "> help` - I'll reply with this helpful text. :information_source:",
            "> `!card cardname` - I'll post a picture of the named card. :frame_with_picture:",
            "> `!price cardname` - I'll respond with the card's current market price. :moneybag:",
            "> `!oracle cardname` - I'll respond with the card's oracle text. :book:",
            "> `!pwp dcinumber` - I'll tell you a player's PWP score and bye eligibility. :trophy:")
        self.send_message(channel_id, txt)

    def write_greeting(self, channel_id, user_id):
        greetings = ['Hi', 'Hello', 'Nice to meet you', 'Howdy', 'Salutations']
        txt = '{}, <@{}>!'.format(random.choice(greetings), user_id)
        self.send_message(channel_id, txt)

    def write_prompt(self, channel_id):
        bot_uid = self.clients.bot_user_id()
        txt = "I'm sorry, I didn't quite understand... Can I help you? (e.g. `<@" + bot_uid + "> help`)"
        self.send_message(channel_id, txt)

    def write_joke(self, channel_id):
        with open('/src/bot/jokes.json', 'r') as infile:
            joke = random.choice(json.load(infile))
        self.send_message(channel_id, joke["setup"])
        self.clients.send_user_typing_pause(channel_id)
        self.send_message(channel_id, joke["punchline"])

    def write_error(self, channel_id, err_msg):
        txt = ":face_with_head_bandage: my maker didn't handle this error very well:\n>```{}```".format(err_msg)
        self.send_message(channel_id, txt)

    def write_card(self, channel_id, searchTerm):
        card = getCard(searchTerm)

        if card:
            mostRecentPrinting = card["editions"][0]
            txt = ""
            attachment = {
                "title": card["name"].replace("\"", "\\\""),
                "image_url": mostRecentPrinting["image_url"],
                "footer": "%s (%s)" % (mostRecentPrinting["set"], mostRecentPrinting["set_id"]),
            }
            self.clients.web.chat.post_message(channel_id, txt, attachments=[attachment], as_user='true')
        else:
            txt = 'Card not found.'
            self.send_message(channel_id, txt)

    def write_oracle(self, channel_id, searchTerm):
        card = getCard(searchTerm)

        if card:
            typeline = ""
            if "supertypes" in card:
                for supertype in card["supertypes"]:
                    typeline += supertype.capitalize() + " "
            if "types" in card:
                for cardtype in card["types"]:
                    typeline += cardtype.capitalize() + " "
                if "subtypes" in card:
                    typeline += "- "
            if "subtypes" in card:
                for subtype in card["subtypes"]:
                    typeline += subtype.capitalize() + " "
            txt = "*%s %s*\n%s\n%s" % (card["name"], card["cost"], typeline, card["text"].replace(u'\u2212', '-'))
            if "power" in card and "toughness" in card:
                txt += "\n*`%s/%s`*" % (card["power"], card["toughness"])
            if "loyalty" in card:
                txt += "\n*`%s`*" % card["loyalty"]
            txt = emojiFilter(txt)
        else:
            txt = 'Card not found.'
        self.send_message(channel_id, txt)

    def write_price(self, channel_id, searchTerm):
        card = getCard(searchTerm)

        if card:
            mostRecentPrinting = card["editions"][0]
            txt = "Unable to find price information for %s" % card["name"]
            if card["value"] > 0:
                txt = ("Current market price for most recent printing of %s (%s) - $%.1f" %
                       (card["name"], mostRecentPrinting["set"], card["value"]))
        else:
            txt = 'Card not found.'
        self.send_message(channel_id, txt)

    def write_pwp(self, channel_id, dciNumber):
        planeswalker = getSeasons(dciNumber)

        if planeswalker:
            txt = ("DCI# %s has %s points in the current season, and %s points last season.\nCurrently "
                   % (dciNumber, planeswalker["currentSeason"], planeswalker["lastSeason"]))

            if planeswalker["currentSeason"] >= 2250 or planeswalker["lastSeason"] >= 2250:
                txt += "eligible for 2 GP byes."
            elif planeswalker["currentSeason"] >= 1300 or planeswalker["lastSeason"] >= 1300:
                txt += "eligible for 1 GP bye."
            else:
                txt += "not eligible for GP byes."
        else:
            txt = "DCI# %s not found." % dciNumber
        self.send_message(channel_id, txt)
<commit_msg>Trying to remove overlower()-ing in emojiFilter()<commit_after>import logging
import json
import random
import re
import requests

logger = logging.getLogger(__name__)

def findIndexOfSequence(data, sequence, startIndex=0):
    index = startIndex
    for token in sequence:
        index = data.find(token, index)
        if index == -1:
            return -1
    return index + len(sequence[-1])

def emojiFilter(input):
    ret = input.replace("{", ":_")
    ret = ret.replace("}", "_:")
    lastpos = None
    while ret.rfind("_:", 0, lastpos) != -1:
        end = ret.rfind("_:", 0, lastpos)
        lastpos = ret.rfind(":_", 0, lastpos)
        start = lastpos + 2
        content = ret[start:end]
        content = content.lower()
        content = content.replace("/", "")
        ret = ret[:start] + content + ret[end:]
    return ret

def getCardValue(cardName, setCode):
    url = "http://www.mtggoldfish.com/widgets/autocard/%s [%s]" % (cardName, setCode)
    headers = {
        'Pragma': 'no-cache',
        'Accept-Encoding': 'gzip, deflate, sdch',
        'Accept-Language': 'en-US,en;q=0.8,de;q=0.6,sv;q=0.4',
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.36',
        'Accept': 'text/javascript, application/javascript, application/ecmascript, application/x-ecmascript, */*; q=0.01',
        'Referer': 'http://www.mtggoldfish.com/widgets/autocard/%s' % cardName,
        'X-Requested-With': 'XMLHttpRequest',
        'Connection': 'keep-alive',
        'Cache-Control': 'no-cache'
    }
    response = requests.get(url, headers=headers)
    index = findIndexOfSequence(response.content, ["tcgplayer", "btn-shop-price", "$"])
    endIndex = response.content.find("\\n", index)
    try:
        value = float(response.content[index + 2:endIndex].replace(",", ""))
    except ValueError:
        value = 0

    return value

def getCard(name):
    queryUrl = "http://api.deckbrew.com/mtg/cards?name=%s" % name
    r = requests.get(queryUrl)
    cards = r.json()

    if len(cards) < 1:
        return None

    card = None
    for element in cards:
        if element["name"].lower() == name.lower():
            card = element

    if card:
        mostRecent = card["editions"][0]
        card["value"] = getCardValue(card["name"], mostRecent["set_id"])
    return card

def getSeasons(dciNumber):
    # Returns to current and last season for that DCI number
    url = "http://www.wizards.com/Magic/PlaneswalkerPoints/JavaScript/GetPointsHistoryModal"
    headers = {
        'Pragma': 'no-cache',
        'Origin': 'http://www.wizards.com',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'en-US,en;q=0.8,de;q=0.6,sv;q=0.4',
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.36',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'Accept': '*/*',
        'Cache-Control': 'no-cache',
        'X-Requested-With': 'XMLHttpRequest',
        'Cookie': 'f5_cspm=1234; BIGipServerWWWPWPPOOL01=353569034.20480.0000; __utmt=1; BIGipServerWWWPool1=3792701706.20480.0000; PlaneswalkerPointsSettings=0=0&lastviewed=9212399887; __utma=75931667.1475261136.1456488297.1456488297.1456488297.1; __utmb=75931667.5.10.1456488297; __utmc=75931667; __utmz=75931667.1456488297.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)',
        'Connection': 'keep-alive',
        'Referer': 'http://www.wizards.com/Magic/PlaneswalkerPoints/%s' % dciNumber
    }
    data = {"Parameters": {"DCINumber": dciNumber, "SelectedType": "Yearly"}}
    response = requests.post(url, headers=headers, data=json.dumps(data))

    if response.status_code is 200:
        seasons = []

        responseData = json.loads(response.content)
        markup = responseData["ModalContent"]
        searchPosition = markup.find("SeasonRange")

        while searchPosition != -1:
            pointsvalue = "PointsValue\">"
            searchPosition = markup.find(pointsvalue, searchPosition)
            searchPosition += len(pointsvalue)
            endPosition = markup.find("
", searchPosition)
            if endPosition != -1:
                value = markup[searchPosition:endPosition]
                seasons.append(int(value))
            searchPosition = markup.find("SeasonRange", searchPosition)

        return {"currentSeason": seasons[0], "lastSeason": seasons[1]}
    else:
        return None

class Messenger(object):
    def __init__(self, slack_clients):
        self.clients = slack_clients

    def send_message(self, channel_id, msg):
        # in the case of Group and Private channels, RTM channel payload is a complex dictionary
        if isinstance(channel_id, dict):
            channel_id = channel_id['id']
        logger.debug('Sending msg: {} to channel: {}'.format(msg, channel_id))
        channel = self.clients.rtm.server.channels.find(channel_id)
        channel.send_message("{}".format(msg.encode('ascii', 'ignore')))

    def write_help_message(self, channel_id):
        bot_uid = self.clients.bot_user_id()
        txt = '{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}'.format(
            "I'm your friendly Slack bot written in Python.  I'll *_respond_* to the following commands:",
            "> `hi <@" + bot_uid + ">` - I'll respond with a randomized greeting mentioning your username. :wave:",
            "> `<@" + bot_uid + "> joke` - I'll tell you one of my finest jokes, with a typing pause for effect. :laughing:",
            "> `<@" + bot_uid + "> help` - I'll reply with this helpful text. :information_source:",
            "> `!card cardname` - I'll post a picture of the named card. :frame_with_picture:",
            "> `!price cardname` - I'll respond with the card's current market price. :moneybag:",
            "> `!oracle cardname` - I'll respond with the card's oracle text. :book:",
            "> `!pwp dcinumber` - I'll tell you a player's PWP score and bye eligibility. :trophy:")
        self.send_message(channel_id, txt)

    def write_greeting(self, channel_id, user_id):
        greetings = ['Hi', 'Hello', 'Nice to meet you', 'Howdy', 'Salutations']
        txt = '{}, <@{}>!'.format(random.choice(greetings), user_id)
        self.send_message(channel_id, txt)

    def write_prompt(self, channel_id):
        bot_uid = self.clients.bot_user_id()
        txt = "I'm sorry, I didn't quite understand... Can I help you? (e.g. `<@" + bot_uid + "> help`)"
        self.send_message(channel_id, txt)

    def write_joke(self, channel_id):
        with open('/src/bot/jokes.json', 'r') as infile:
            joke = random.choice(json.load(infile))
        self.send_message(channel_id, joke["setup"])
        self.clients.send_user_typing_pause(channel_id)
        self.send_message(channel_id, joke["punchline"])

    def write_error(self, channel_id, err_msg):
        txt = ":face_with_head_bandage: my maker didn't handle this error very well:\n>```{}```".format(err_msg)
        self.send_message(channel_id, txt)

    def write_card(self, channel_id, searchTerm):
        card = getCard(searchTerm)

        if card:
            mostRecentPrinting = card["editions"][0]
            txt = ""
            attachment = {
                "title": card["name"].replace("\"", "\\\""),
                "image_url": mostRecentPrinting["image_url"],
                "footer": "%s (%s)" % (mostRecentPrinting["set"], mostRecentPrinting["set_id"]),
            }
            self.clients.web.chat.post_message(channel_id, txt, attachments=[attachment], as_user='true')
        else:
            txt = 'Card not found.'
            self.send_message(channel_id, txt)

    def write_oracle(self, channel_id, searchTerm):
        card = getCard(searchTerm)

        if card:
            typeline = ""
            if "supertypes" in card:
                for supertype in card["supertypes"]:
                    typeline += supertype.capitalize() + " "
            if "types" in card:
                for cardtype in card["types"]:
                    typeline += cardtype.capitalize() + " "
                if "subtypes" in card:
                    typeline += "- "
            if "subtypes" in card:
                for subtype in card["subtypes"]:
                    typeline += subtype.capitalize() + " "
            txt = "*%s %s*\n%s\n%s" % (card["name"], card["cost"], typeline, card["text"].replace(u'\u2212', '-'))
            if "power" in card and "toughness" in card:
                txt += "\n*`%s/%s`*" % (card["power"], card["toughness"])
            if "loyalty" in card:
                txt += "\n*`%s`*" % card["loyalty"]
            txt = emojiFilter(txt)
        else:
            txt = 'Card not found.'
        self.send_message(channel_id, txt)

    def write_price(self, channel_id, searchTerm):
        card = getCard(searchTerm)

        if card:
            mostRecentPrinting = card["editions"][0]
            txt = "Unable to find price information for %s" % card["name"]
            if card["value"] > 0:
                txt = ("Current market price for most recent printing of %s (%s) - $%.1f" %
                       (card["name"], mostRecentPrinting["set"], card["value"]))
        else:
            txt = 'Card not found.'
        self.send_message(channel_id, txt)

    def write_pwp(self, channel_id, dciNumber):
        planeswalker = getSeasons(dciNumber)

        if planeswalker:
            txt = ("DCI# %s has %s points in the current season, and %s points last season.\nCurrently "
                   % (dciNumber, planeswalker["currentSeason"], planeswalker["lastSeason"]))

            if planeswalker["currentSeason"] >= 2250 or planeswalker["lastSeason"] >= 2250:
                txt += "eligible for 2 GP byes."
            elif planeswalker["currentSeason"] >= 1300 or planeswalker["lastSeason"] >= 1300:
                txt += "eligible for 1 GP bye."
            else:
                txt += "not eligible for GP byes."
        else:
            txt = "DCI# %s not found." % dciNumber
        self.send_message(channel_id, txt)
<|endoftext|>


<commit_before>"""Functions for checking files"""
import os
import stat

from botbot import problems
from botbot.checker import is_link

def is_fastq(path):
    """Check whether a given file is a fastq file."""
    if os.path.splitext(path)[1] == ".fastq":
        if not is_link(path):
            return 'PROB_FILE_IS_FASTQ'

def has_permission_issues(path):
    """Check whether a given path has bad permissons."""
    mode = os.stat(path).st_mode
    if stat.S_ISDIR(mode) and not stat.S_IXGRP(mode):
        return 'PROB_DIR_NOT_WRITABLE'
    else:
        if not bool(stat.S_IRGRP & mode):
            return 'PROB_FILE_NOT_GRPRD'

def sam_should_compress(path):
    """Check if a *.SAM file should be compressed or deleted"""
    name, ext = os.path.splitext(path)
    if ext == '.sam':
        if os.path.isfile('.'.join((name, 'bam'))):
            return 'PROB_SAM_AND_BAM_EXIST'
        else:
            return 'PROB_SAM_SHOULD_COMPRESS'
<commit_msg>Remove unused import<commit_after>"""Functions for checking files"""
import os
import stat

from botbot.checker import is_link

def is_fastq(path):
    """Check whether a given file is a fastq file."""
    if os.path.splitext(path)[1] == ".fastq":
        if not is_link(path):
            return 'PROB_FILE_IS_FASTQ'

def has_permission_issues(path):
    """Check whether a given path has bad permissons."""
    mode = os.stat(path).st_mode
    if stat.S_ISDIR(mode) and not stat.S_IXGRP(mode):
        return 'PROB_DIR_NOT_WRITABLE'
    else:
        if not bool(stat.S_IRGRP & mode):
            return 'PROB_FILE_NOT_GRPRD'

def sam_should_compress(path):
    """Check if a *.SAM file should be compressed or deleted"""
    name, ext = os.path.splitext(path)
    if ext == '.sam':
        if os.path.isfile('.'.join((name, 'bam'))):
            return 'PROB_SAM_AND_BAM_EXIST'
        else:
            return 'PROB_SAM_SHOULD_COMPRESS'
<|endoftext|>


<commit_before>#!/bin/env python
"""
Compute the mean square displacement (MSD) of atoms (see ids below)
from the sequential files in the arguments.
If several atom IDs are specified, an average MSD among those atoms are written.
Staggered measuring of MSD can be used for the statistical purpose.

Usage:
  msd.py [options] FILES [FILES...]

Options:
  -h, --help    Show this help message and exit.
  --id=ID       IDs of atoms whose paths are to be traced.
                0 for all atoms and positive for atom-IDs.
                Several IDs can be specified separated by comma.
                [default: 0,]
  -m, --measure MEASURE
                Num of measuring lane. In case of 1, it is identical to non-staggered measuring. [default: 1]
  -s, --shift SHIFT
                Shift of each staggered lane. [default: 20]
"""

import numpy as np
from docopt import docopt

from napsys import NAPSystem

def anint(x):
    if x >= 0.5:
        return 1.0
    elif x < -0.5:
        return -1.0
    else:
        return 0.0

def get_ids(nsys,ids):
    atom_ids = []
    if 0 in ids:  # all the atoms
        atom_ids = [ i for i in range(len(nsys)) ]
        return atom_ids
    else:
        atom_ids = [ids]
    return atom_ids

def get_msd(files,ids0,nmeasure,nshift):
    ids = ids0
    if 0 in ids0:
        nsys = NAPSystem(fname=files[0])
        ids = [ i for i in range(len(nsys.atoms))]
    p0= np.zeros((nmeasure,len(ids),3))
    pp= np.zeros((len(ids),3))
    msd= np.zeros((len(files),nmeasure,3))
    npbc= np.zeros((len(ids),3),dtype=int)
    hmat= np.zeros((3,3))
    for ifile in range(len(files)):
        fname= files[ifile]
        nsys= NAPSystem(fname=fname)
        hmat[0]= nsys.a1 *nsys.alc
        hmat[1]= nsys.a2 *nsys.alc
        hmat[2]= nsys.a3 *nsys.alc
        for ia,idi in enumerate(ids):
            #...human-readable ID to computer-oriented ID
            i= idi - 1
            ai= nsys.atoms[i]
            pi= ai.pos
            if ifile == 0:
                pp[ia,:]= pi[:]
            else:
                #...correct periodic motion
                dev= pi -pp[ia]
                if dev[0] > 0.5:
                    npbc[ia,0] += -1
                elif dev[0] < -0.5:
                    npbc[ia,0] += 1
                if dev[1] > 0.5:
                    npbc[ia,1] += -1
                elif dev[1] < -0.5:
                    npbc[ia,1] += 1
                if dev[2] > 0.5:
                    npbc[ia,2] += -1
                elif dev[2] < -0.5:
                    npbc[ia,2] += 1
                # print npbc
                #...store current position
                pp[ia,:]= pi[:]

            for nm in range(nmeasure):
                if ifile == nm*nshift:
                    p0[nm,ia,0]= pi[0] +float(npbc[ia,0])
                    p0[nm,ia,1]= pi[1] +float(npbc[ia,1])
                    p0[nm,ia,2]= pi[2] +float(npbc[ia,2])
                if nm*nshift < ifile:
                    #...normalized to absolute
                    dev[0]= pi[0] -p0[nm,ia,0] +float(npbc[ia,0])
                    dev[1]= pi[1] -p0[nm,ia,1] +float(npbc[ia,1])
                    dev[2]= pi[2] -p0[nm,ia,2] +float(npbc[ia,2])
                    dev= np.dot(hmat.T,dev)
                    msd[ifile-nm*nshift,nm,0] += dev[0]**2
                    msd[ifile-nm*nshift,nm,1] += dev[1]**2
                    msd[ifile-nm*nshift,nm,2] += dev[2]**2

    for ifile in range(len(files)):
        for nm in range(nmeasure):
            msd[ifile-nm*nshift,nm,0] /= len(ids)
            msd[ifile-nm*nshift,nm,1] /= len(ids)
            msd[ifile-nm*nshift,nm,2] /= len(ids)

    return msd

if __name__ == "__main__":

    args = docopt(__doc__)

    files = args['FILES']
    ids = args['--id']
    ids = [ int(i) for i in ids.split(',') ]
    nmeasure = int(args['--measure'])
    nshift = int(args['--shift'])

    #...compute sampling time-window from nmeasure and nshift
    ntwindow= len(files) -(nmeasure-1)*nshift
    if ntwindow <= 0:
        err=' [Error] ntwindow <= 0 !!!\n'\
              + '  Chech the parameters nmeasure and nshift, and input files.'
        raise ValueError(err)

    msd = get_msd(files,ids,nmeasure,nshift)

    #...make output data files
    outfname='out.msd'
    with open(outfname,'w') as f:
        for ifile in range(len(files)-(nmeasure-1)*nshift):
            if ifile == 0:
                f.write(' {:10d}'.format(ifile)
                        +' {:15.7f} {:15.7f}'.format(0.0,0.0)
                        +' {:15.7f} {:15.7f}\n'.format(0.0,0.0))
            else:
                dev= np.zeros((3,))
                for nm in range(nmeasure):
                    dev += msd[ifile,nm]
                dev /= nmeasure
                f.write(' {:10d}'.format(ifile)
                        +' {:15.7f}'.format((dev[0]+dev[1]+dev[2])/3)
                        +' {:15.7f}'.format(dev[0])
                        +' {:15.7f}'.format(dev[1])
                        +' {:15.7f}'.format(dev[2])
                        +' \n')
    print('Wrote a file: {0:s}'.format(outfname))
<commit_msg>a bug fixed in msd.py.<commit_after>#!/bin/env python
"""
Compute the mean square displacement (MSD) of atoms (see ids below)
from the sequential files in the arguments.
If several atom IDs are specified, an average MSD among those atoms are written.
Staggered measuring of MSD can be used for the statistical purpose.

Usage:
  msd.py [options] FILES [FILES...]

Options:
  -h, --help    Show this help message and exit.
  --id=ID       IDs of atoms whose paths are to be traced.
                0 for all atoms and positive for atom-IDs.
                Several IDs can be specified separated by comma.
                [default: 0,]
  -m, --measure MEASURE
                Num of measuring lane. In case of 1, it is identical to non-staggered measuring. [default: 1]
  -s, --shift SHIFT
                Shift of each staggered lane. [default: 20]
"""

import numpy as np
from docopt import docopt

from nappy.napsys import NAPSystem

def anint(x):
    if x >= 0.5:
        return 1.0
    elif x < -0.5:
        return -1.0
    else:
        return 0.0

def get_ids(nsys,ids):
    atom_ids = []
    if 0 in ids:  # all the atoms
        atom_ids = [ i for i in range(len(nsys)) ]
        return atom_ids
    else:
        atom_ids = [ids]
    return atom_ids

def get_msd(files,ids0,nmeasure,nshift):
    ids = ids0
    if 0 in ids0:
        nsys = NAPSystem(fname=files[0])
        ids = [ i for i in range(len(nsys.atoms))]
    p0= np.zeros((nmeasure,len(ids),3))
    pp= np.zeros((len(ids),3))
    msd= np.zeros((len(files),nmeasure,3))
    npbc= np.zeros((len(ids),3),dtype=int)
    hmat= np.zeros((3,3))
    for ifile in range(len(files)):
        fname= files[ifile]
        nsys= NAPSystem(fname=fname)
        hmat[0]= nsys.a1 *nsys.alc
        hmat[1]= nsys.a2 *nsys.alc
        hmat[2]= nsys.a3 *nsys.alc
        for ia,idi in enumerate(ids):
            #...human-readable ID to computer-oriented ID
            i= idi - 1
            ai= nsys.atoms[i]
            pi= ai.pos
            if ifile == 0:
                pp[ia,:]= pi[:]
            else:
                #...correct periodic motion
                dev= pi -pp[ia]
                if dev[0] > 0.5:
                    npbc[ia,0] += -1
                elif dev[0] < -0.5:
                    npbc[ia,0] += 1
                if dev[1] > 0.5:
                    npbc[ia,1] += -1
                elif dev[1] < -0.5:
                    npbc[ia,1] += 1
                if dev[2] > 0.5:
                    npbc[ia,2] += -1
                elif dev[2] < -0.5:
                    npbc[ia,2] += 1
                # print npbc
                #...store current position
                pp[ia,:]= pi[:]

            for nm in range(nmeasure):
                if ifile == nm*nshift:
                    p0[nm,ia,0]= pi[0] +float(npbc[ia,0])
                    p0[nm,ia,1]= pi[1] +float(npbc[ia,1])
                    p0[nm,ia,2]= pi[2] +float(npbc[ia,2])
                if nm*nshift < ifile:
                    #...normalized to absolute
                    dev[0]= pi[0] -p0[nm,ia,0] +float(npbc[ia,0])
                    dev[1]= pi[1] -p0[nm,ia,1] +float(npbc[ia,1])
                    dev[2]= pi[2] -p0[nm,ia,2] +float(npbc[ia,2])
                    dev= np.dot(hmat.T,dev)
                    msd[ifile-nm*nshift,nm,0] += dev[0]**2
                    msd[ifile-nm*nshift,nm,1] += dev[1]**2
                    msd[ifile-nm*nshift,nm,2] += dev[2]**2

    for ifile in range(len(files)):
        for nm in range(nmeasure):
            msd[ifile-nm*nshift,nm,0] /= len(ids)
            msd[ifile-nm*nshift,nm,1] /= len(ids)
            msd[ifile-nm*nshift,nm,2] /= len(ids)

    return msd

if __name__ == "__main__":

    args = docopt(__doc__)

    files = args['FILES']
    ids = args['--id']
    ids = [ int(i) for i in ids.split(',') ]
    nmeasure = int(args['--measure'])
    nshift = int(args['--shift'])

    #...compute sampling time-window from nmeasure and nshift
    ntwindow= len(files) -(nmeasure-1)*nshift
    if ntwindow <= 0:
        err=' [Error] ntwindow <= 0 !!!\n'\
              + '  Chech the parameters nmeasure and nshift, and input files.'
        raise ValueError(err)

    msd = get_msd(files,ids,nmeasure,nshift)

    #...make output data files
    outfname='out.msd'
    with open(outfname,'w') as f:
        for ifile in range(len(files)-(nmeasure-1)*nshift):
            if ifile == 0:
                f.write(' {:10d}'.format(ifile)
                        +' {:15.7f} {:15.7f}'.format(0.0,0.0)
                        +' {:15.7f} {:15.7f}\n'.format(0.0,0.0))
            else:
                dev= np.zeros((3,))
                for nm in range(nmeasure):
                    dev += msd[ifile,nm]
                dev /= nmeasure
                f.write(' {:10d}'.format(ifile)
                        +' {:15.7f}'.format((dev[0]+dev[1]+dev[2])/3)
                        +' {:15.7f}'.format(dev[0])
                        +' {:15.7f}'.format(dev[1])
                        +' {:15.7f}'.format(dev[2])
                        +' \n')
    print('Wrote a file: {0:s}'.format(outfname))
<|endoftext|>