id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
27,100
chaoss/grimoirelab-sortinghat
sortinghat/cmd/init.py
Init.__load_countries
def __load_countries(self, db): """Load the list of countries""" try: countries = self.__read_countries_file() except IOError as e: raise LoadError(str(e)) try: with db.connect() as session: for country in countries: session.add(country) except Exception as e: raise LoadError(str(e))
python
def __load_countries(self, db): try: countries = self.__read_countries_file() except IOError as e: raise LoadError(str(e)) try: with db.connect() as session: for country in countries: session.add(country) except Exception as e: raise LoadError(str(e))
[ "def", "__load_countries", "(", "self", ",", "db", ")", ":", "try", ":", "countries", "=", "self", ".", "__read_countries_file", "(", ")", "except", "IOError", "as", "e", ":", "raise", "LoadError", "(", "str", "(", "e", ")", ")", "try", ":", "with", ...
Load the list of countries
[ "Load", "the", "list", "of", "countries" ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/init.py#L118-L131
27,101
chaoss/grimoirelab-sortinghat
sortinghat/cmd/init.py
Init.__read_countries_file
def __read_countries_file(self): """Read countries from a CSV file""" import csv import pkg_resources filename = pkg_resources.resource_filename('sortinghat', 'data/countries.csv') with open(filename, 'r') as f: reader = csv.DictReader(f, fieldnames=['name', 'code', 'alpha3']) countries = [Country(**c) for c in reader] return countries
python
def __read_countries_file(self): import csv import pkg_resources filename = pkg_resources.resource_filename('sortinghat', 'data/countries.csv') with open(filename, 'r') as f: reader = csv.DictReader(f, fieldnames=['name', 'code', 'alpha3']) countries = [Country(**c) for c in reader] return countries
[ "def", "__read_countries_file", "(", "self", ")", ":", "import", "csv", "import", "pkg_resources", "filename", "=", "pkg_resources", ".", "resource_filename", "(", "'sortinghat'", ",", "'data/countries.csv'", ")", "with", "open", "(", "filename", ",", "'r'", ")", ...
Read countries from a CSV file
[ "Read", "countries", "from", "a", "CSV", "file" ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/init.py#L133-L144
27,102
chaoss/grimoirelab-sortinghat
sortinghat/cmd/remove.py
Remove.run
def run(self, *args): """Remove unique identities or identities from the registry. By default, it removes the unique identity identified by <identifier>. To remove an identity, set <identity> parameter. """ params = self.parser.parse_args(args) identifier = params.identifier identity = params.identity code = self.remove(identifier, identity) return code
python
def run(self, *args): params = self.parser.parse_args(args) identifier = params.identifier identity = params.identity code = self.remove(identifier, identity) return code
[ "def", "run", "(", "self", ",", "*", "args", ")", ":", "params", "=", "self", ".", "parser", ".", "parse_args", "(", "args", ")", "identifier", "=", "params", ".", "identifier", "identity", "=", "params", ".", "identity", "code", "=", "self", ".", "r...
Remove unique identities or identities from the registry. By default, it removes the unique identity identified by <identifier>. To remove an identity, set <identity> parameter.
[ "Remove", "unique", "identities", "or", "identities", "from", "the", "registry", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/remove.py#L71-L84
27,103
chaoss/grimoirelab-sortinghat
sortinghat/utils.py
merge_date_ranges
def merge_date_ranges(dates): """Merge date ranges. Generator that merges ovelaped data ranges. Default init and end dates (1900-01-01 and 2100-01-01) are considered range limits and will be removed when a set of ranges overlap. For example: * [(1900-01-01, 2010-01-01), (2008-01-01, 2100-01-01)] --> (2008-01-01, 2010-01-01) * [(1900-01-01, 2010-01-01), (2008-01-01, 2010-01-01), (2010-01-02, 2100-01-01)] --> (2008-01-01, 2010-01-01),(2010-01-02, 2100-01-01) * [(1900-01-01, 2010-01-01), (2010-01-02, 2100-01-01)] --> (1900-01-01, 2010-01-01), (2010-01-02, 2100-01-01) The condition MIN_PERIOD_DATE <= dt <= MAX_PERIOD_DATE must be true for each date. Otherwise, the generator will raise a ValueError exception. This code is based on samplebias' answer to StackOverflow's question "Merging a list of time-range tuples that have overlapping time-ranges" (http://stackoverflow.com/questions/5679638). :param dates: sequence of date ranges where each range is a (st_date, en_date) tuple :raises ValueError: when a value of the data range is out of bounds """ if not dates: return sorted_dates = sorted([sorted(t) for t in dates]) saved = list(sorted_dates[0]) for st, en in sorted_dates: if st < MIN_PERIOD_DATE or st > MAX_PERIOD_DATE: raise ValueError("start date %s is out of bounds" % str(st)) if en < MIN_PERIOD_DATE or en > MAX_PERIOD_DATE: raise ValueError("end date %s is out of bounds" % str(en)) if st <= saved[1]: if saved[0] == MIN_PERIOD_DATE: saved[0] = st if MAX_PERIOD_DATE in (en, saved[1]): saved[1] = min(saved[1], en) else: saved[1] = max(saved[1], en) else: yield tuple(saved) saved[0] = st saved[1] = en yield tuple(saved)
python
def merge_date_ranges(dates): if not dates: return sorted_dates = sorted([sorted(t) for t in dates]) saved = list(sorted_dates[0]) for st, en in sorted_dates: if st < MIN_PERIOD_DATE or st > MAX_PERIOD_DATE: raise ValueError("start date %s is out of bounds" % str(st)) if en < MIN_PERIOD_DATE or en > MAX_PERIOD_DATE: raise ValueError("end date %s is out of bounds" % str(en)) if st <= saved[1]: if saved[0] == MIN_PERIOD_DATE: saved[0] = st if MAX_PERIOD_DATE in (en, saved[1]): saved[1] = min(saved[1], en) else: saved[1] = max(saved[1], en) else: yield tuple(saved) saved[0] = st saved[1] = en yield tuple(saved)
[ "def", "merge_date_ranges", "(", "dates", ")", ":", "if", "not", "dates", ":", "return", "sorted_dates", "=", "sorted", "(", "[", "sorted", "(", "t", ")", "for", "t", "in", "dates", "]", ")", "saved", "=", "list", "(", "sorted_dates", "[", "0", "]", ...
Merge date ranges. Generator that merges ovelaped data ranges. Default init and end dates (1900-01-01 and 2100-01-01) are considered range limits and will be removed when a set of ranges overlap. For example: * [(1900-01-01, 2010-01-01), (2008-01-01, 2100-01-01)] --> (2008-01-01, 2010-01-01) * [(1900-01-01, 2010-01-01), (2008-01-01, 2010-01-01), (2010-01-02, 2100-01-01)] --> (2008-01-01, 2010-01-01),(2010-01-02, 2100-01-01) * [(1900-01-01, 2010-01-01), (2010-01-02, 2100-01-01)] --> (1900-01-01, 2010-01-01), (2010-01-02, 2100-01-01) The condition MIN_PERIOD_DATE <= dt <= MAX_PERIOD_DATE must be true for each date. Otherwise, the generator will raise a ValueError exception. This code is based on samplebias' answer to StackOverflow's question "Merging a list of time-range tuples that have overlapping time-ranges" (http://stackoverflow.com/questions/5679638). :param dates: sequence of date ranges where each range is a (st_date, en_date) tuple :raises ValueError: when a value of the data range is out of bounds
[ "Merge", "date", "ranges", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/utils.py#L33-L84
27,104
chaoss/grimoirelab-sortinghat
sortinghat/utils.py
uuid
def uuid(source, email=None, name=None, username=None): """Get the UUID related to the identity data. Based on the input data, the function will return the UUID associated to an identity. On this version, the UUID will be the SHA1 of "source:email:name:username" string. This string is case insensitive, which means same values for the input parameters in upper or lower case will produce the same UUID. The value of 'name' will converted to its unaccent form which means same values with accent or unnacent chars (i.e 'ö and o') will generate the same UUID. For instance, these combinations will produce the same UUID: ('scm', 'jsmith@example.com', 'John Smith', 'jsmith'), ('scm', 'jsmith@example,com', 'Jöhn Smith', 'jsmith'), ('scm', 'jsmith@example.com', 'John Smith', 'JSMITH'), ('scm', 'jsmith@example.com', 'john Smith', 'jsmith') :param source: data source :param email: email of the identity :param name: full name of the identity :param username: user name used by the identity :returns: a universal unique identifier for Sorting Hat :raises ValueError: when source is None or empty; each one of the parameters is None; parameters are empty. """ if source is None: raise ValueError("source cannot be None") if source == '': raise ValueError("source cannot be an empty string") if not (email or name or username): raise ValueError("identity data cannot be None or empty") s = ':'.join((to_unicode(source), to_unicode(email), to_unicode(name, unaccent=True), to_unicode(username))).lower() sha1 = hashlib.sha1(s.encode('UTF-8', errors="surrogateescape")) uuid_ = sha1.hexdigest() return uuid_
python
def uuid(source, email=None, name=None, username=None): if source is None: raise ValueError("source cannot be None") if source == '': raise ValueError("source cannot be an empty string") if not (email or name or username): raise ValueError("identity data cannot be None or empty") s = ':'.join((to_unicode(source), to_unicode(email), to_unicode(name, unaccent=True), to_unicode(username))).lower() sha1 = hashlib.sha1(s.encode('UTF-8', errors="surrogateescape")) uuid_ = sha1.hexdigest() return uuid_
[ "def", "uuid", "(", "source", ",", "email", "=", "None", ",", "name", "=", "None", ",", "username", "=", "None", ")", ":", "if", "source", "is", "None", ":", "raise", "ValueError", "(", "\"source cannot be None\"", ")", "if", "source", "==", "''", ":",...
Get the UUID related to the identity data. Based on the input data, the function will return the UUID associated to an identity. On this version, the UUID will be the SHA1 of "source:email:name:username" string. This string is case insensitive, which means same values for the input parameters in upper or lower case will produce the same UUID. The value of 'name' will converted to its unaccent form which means same values with accent or unnacent chars (i.e 'ö and o') will generate the same UUID. For instance, these combinations will produce the same UUID: ('scm', 'jsmith@example.com', 'John Smith', 'jsmith'), ('scm', 'jsmith@example,com', 'Jöhn Smith', 'jsmith'), ('scm', 'jsmith@example.com', 'John Smith', 'JSMITH'), ('scm', 'jsmith@example.com', 'john Smith', 'jsmith') :param source: data source :param email: email of the identity :param name: full name of the identity :param username: user name used by the identity :returns: a universal unique identifier for Sorting Hat :raises ValueError: when source is None or empty; each one of the parameters is None; parameters are empty.
[ "Get", "the", "UUID", "related", "to", "the", "identity", "data", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/utils.py#L122-L167
27,105
chaoss/grimoirelab-sortinghat
sortinghat/db/database.py
create_database_engine
def create_database_engine(user, password, database, host, port): """Create a database engine""" driver = 'mysql+pymysql' url = URL(driver, user, password, host, port, database, query={'charset': 'utf8mb4'}) return create_engine(url, poolclass=QueuePool, pool_size=25, pool_pre_ping=True, echo=False)
python
def create_database_engine(user, password, database, host, port): driver = 'mysql+pymysql' url = URL(driver, user, password, host, port, database, query={'charset': 'utf8mb4'}) return create_engine(url, poolclass=QueuePool, pool_size=25, pool_pre_ping=True, echo=False)
[ "def", "create_database_engine", "(", "user", ",", "password", ",", "database", ",", "host", ",", "port", ")", ":", "driver", "=", "'mysql+pymysql'", "url", "=", "URL", "(", "driver", ",", "user", ",", "password", ",", "host", ",", "port", ",", "database...
Create a database engine
[ "Create", "a", "database", "engine" ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/db/database.py#L170-L178
27,106
chaoss/grimoirelab-sortinghat
sortinghat/db/database.py
create_database_session
def create_database_session(engine): """Connect to the database""" try: Session = sessionmaker(bind=engine) return Session() except OperationalError as e: raise DatabaseError(error=e.orig.args[1], code=e.orig.args[0])
python
def create_database_session(engine): try: Session = sessionmaker(bind=engine) return Session() except OperationalError as e: raise DatabaseError(error=e.orig.args[1], code=e.orig.args[0])
[ "def", "create_database_session", "(", "engine", ")", ":", "try", ":", "Session", "=", "sessionmaker", "(", "bind", "=", "engine", ")", "return", "Session", "(", ")", "except", "OperationalError", "as", "e", ":", "raise", "DatabaseError", "(", "error", "=", ...
Connect to the database
[ "Connect", "to", "the", "database" ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/db/database.py#L181-L188
27,107
chaoss/grimoirelab-sortinghat
sortinghat/db/database.py
close_database_session
def close_database_session(session): """Close connection with the database""" try: session.close() except OperationalError as e: raise DatabaseError(error=e.orig.args[1], code=e.orig.args[0])
python
def close_database_session(session): try: session.close() except OperationalError as e: raise DatabaseError(error=e.orig.args[1], code=e.orig.args[0])
[ "def", "close_database_session", "(", "session", ")", ":", "try", ":", "session", ".", "close", "(", ")", "except", "OperationalError", "as", "e", ":", "raise", "DatabaseError", "(", "error", "=", "e", ".", "orig", ".", "args", "[", "1", "]", ",", "cod...
Close connection with the database
[ "Close", "connection", "with", "the", "database" ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/db/database.py#L191-L197
27,108
chaoss/grimoirelab-sortinghat
sortinghat/db/database.py
reflect_table
def reflect_table(engine, klass): """Inspect and reflect objects""" try: meta = MetaData() meta.reflect(bind=engine) except OperationalError as e: raise DatabaseError(error=e.orig.args[1], code=e.orig.args[0]) # Try to reflect from any of the supported tables table = None for tb in klass.tables(): if tb in meta.tables: table = meta.tables[tb] break if table is None: raise DatabaseError(error="Invalid schema. Table not found", code="-1") # Map table schema into klass mapper(klass, table, column_prefix=klass.column_prefix()) return table
python
def reflect_table(engine, klass): try: meta = MetaData() meta.reflect(bind=engine) except OperationalError as e: raise DatabaseError(error=e.orig.args[1], code=e.orig.args[0]) # Try to reflect from any of the supported tables table = None for tb in klass.tables(): if tb in meta.tables: table = meta.tables[tb] break if table is None: raise DatabaseError(error="Invalid schema. Table not found", code="-1") # Map table schema into klass mapper(klass, table, column_prefix=klass.column_prefix()) return table
[ "def", "reflect_table", "(", "engine", ",", "klass", ")", ":", "try", ":", "meta", "=", "MetaData", "(", ")", "meta", ".", "reflect", "(", "bind", "=", "engine", ")", "except", "OperationalError", "as", "e", ":", "raise", "DatabaseError", "(", "error", ...
Inspect and reflect objects
[ "Inspect", "and", "reflect", "objects" ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/db/database.py#L200-L225
27,109
chaoss/grimoirelab-sortinghat
sortinghat/db/database.py
find_model_by_table_name
def find_model_by_table_name(name): """Find a model reference by its table name""" for model in ModelBase._decl_class_registry.values(): if hasattr(model, '__table__') and model.__table__.fullname == name: return model return None
python
def find_model_by_table_name(name): for model in ModelBase._decl_class_registry.values(): if hasattr(model, '__table__') and model.__table__.fullname == name: return model return None
[ "def", "find_model_by_table_name", "(", "name", ")", ":", "for", "model", "in", "ModelBase", ".", "_decl_class_registry", ".", "values", "(", ")", ":", "if", "hasattr", "(", "model", ",", "'__table__'", ")", "and", "model", ".", "__table__", ".", "fullname",...
Find a model reference by its table name
[ "Find", "a", "model", "reference", "by", "its", "table", "name" ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/db/database.py#L228-L234
27,110
chaoss/grimoirelab-sortinghat
sortinghat/db/database.py
Database.handle_database_error
def handle_database_error(cls, session, exception): """Rollback changes made and handle any type of error raised by the DBMS.""" session.rollback() if isinstance(exception, IntegrityError): cls.handle_integrity_error(exception) elif isinstance(exception, FlushError): cls.handle_flush_error(exception) else: raise exception
python
def handle_database_error(cls, session, exception): session.rollback() if isinstance(exception, IntegrityError): cls.handle_integrity_error(exception) elif isinstance(exception, FlushError): cls.handle_flush_error(exception) else: raise exception
[ "def", "handle_database_error", "(", "cls", ",", "session", ",", "exception", ")", ":", "session", ".", "rollback", "(", ")", "if", "isinstance", "(", "exception", ",", "IntegrityError", ")", ":", "cls", ".", "handle_integrity_error", "(", "exception", ")", ...
Rollback changes made and handle any type of error raised by the DBMS.
[ "Rollback", "changes", "made", "and", "handle", "any", "type", "of", "error", "raised", "by", "the", "DBMS", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/db/database.py#L113-L123
27,111
chaoss/grimoirelab-sortinghat
sortinghat/db/database.py
Database.handle_integrity_error
def handle_integrity_error(cls, exception): """Handle integrity error exceptions.""" m = re.match(cls.MYSQL_INSERT_ERROR_REGEX, exception.statement) if not m: raise exception model = find_model_by_table_name(m.group('table')) if not model: raise exception m = re.match(cls.MYSQL_DUPLICATE_ENTRY_ERROR_REGEX, exception.orig.args[1]) if not m: raise exception entity = model.__name__ eid = m.group('value') raise AlreadyExistsError(entity=entity, eid=eid)
python
def handle_integrity_error(cls, exception): m = re.match(cls.MYSQL_INSERT_ERROR_REGEX, exception.statement) if not m: raise exception model = find_model_by_table_name(m.group('table')) if not model: raise exception m = re.match(cls.MYSQL_DUPLICATE_ENTRY_ERROR_REGEX, exception.orig.args[1]) if not m: raise exception entity = model.__name__ eid = m.group('value') raise AlreadyExistsError(entity=entity, eid=eid)
[ "def", "handle_integrity_error", "(", "cls", ",", "exception", ")", ":", "m", "=", "re", ".", "match", "(", "cls", ".", "MYSQL_INSERT_ERROR_REGEX", ",", "exception", ".", "statement", ")", "if", "not", "m", ":", "raise", "exception", "model", "=", "find_mo...
Handle integrity error exceptions.
[ "Handle", "integrity", "error", "exceptions", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/db/database.py#L126-L149
27,112
chaoss/grimoirelab-sortinghat
sortinghat/db/database.py
Database.handle_flush_error
def handle_flush_error(cls, exception): """Handle flush error exceptions.""" trace = exception.args[0] m = re.match(cls.MYSQL_FLUSH_ERROR_REGEX, trace) if not m: raise exception entity = m.group('entity') eid = m.group('eid') raise AlreadyExistsError(entity=entity, eid=eid)
python
def handle_flush_error(cls, exception): trace = exception.args[0] m = re.match(cls.MYSQL_FLUSH_ERROR_REGEX, trace) if not m: raise exception entity = m.group('entity') eid = m.group('eid') raise AlreadyExistsError(entity=entity, eid=eid)
[ "def", "handle_flush_error", "(", "cls", ",", "exception", ")", ":", "trace", "=", "exception", ".", "args", "[", "0", "]", "m", "=", "re", ".", "match", "(", "cls", ".", "MYSQL_FLUSH_ERROR_REGEX", ",", "trace", ")", "if", "not", "m", ":", "raise", "...
Handle flush error exceptions.
[ "Handle", "flush", "error", "exceptions", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/db/database.py#L152-L164
27,113
chaoss/grimoirelab-sortinghat
sortinghat/cmd/affiliate.py
Affiliate.run
def run(self, *args): """Affiliate unique identities to organizations.""" self.parser.parse_args(args) code = self.affiliate() return code
python
def run(self, *args): self.parser.parse_args(args) code = self.affiliate() return code
[ "def", "run", "(", "self", ",", "*", "args", ")", ":", "self", ".", "parser", ".", "parse_args", "(", "args", ")", "code", "=", "self", ".", "affiliate", "(", ")", "return", "code" ]
Affiliate unique identities to organizations.
[ "Affiliate", "unique", "identities", "to", "organizations", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/affiliate.py#L62-L69
27,114
chaoss/grimoirelab-sortinghat
sortinghat/cmd/affiliate.py
Affiliate.affiliate
def affiliate(self): """Affiliate unique identities. This method enrolls unique identities to organizations using email addresses and top/sub domains data. Only new enrollments will be created. """ try: uidentities = api.unique_identities(self.db) for uid in uidentities: uid.identities.sort(key=lambda x: x.id) for identity in uid.identities: # Only check email address to find new affiliations if not identity.email: continue if not EMAIL_ADDRESS_PATTERN.match(identity.email): continue domain = identity.email.split('@')[-1] try: doms = api.domains(self.db, domain=domain, top=True) except NotFoundError as e: continue if len(doms) > 1: doms.sort(key=lambda d: len(d.domain), reverse=True) msg = "multiple top domains for %s sub-domain. Domain %s selected." msg = msg % (domain, doms[0].domain) self.warning(msg) organization = doms[0].organization.name # Check enrollments to avoid insert affiliation twice enrollments = api.enrollments(self.db, uid.uuid, organization) if enrollments: continue api.add_enrollment(self.db, uid.uuid, organization) self.display('affiliate.tmpl', id=uid.uuid, email=identity.email, organization=organization) except (NotFoundError, InvalidValueError) as e: self.error(str(e)) return e.code return CMD_SUCCESS
python
def affiliate(self): try: uidentities = api.unique_identities(self.db) for uid in uidentities: uid.identities.sort(key=lambda x: x.id) for identity in uid.identities: # Only check email address to find new affiliations if not identity.email: continue if not EMAIL_ADDRESS_PATTERN.match(identity.email): continue domain = identity.email.split('@')[-1] try: doms = api.domains(self.db, domain=domain, top=True) except NotFoundError as e: continue if len(doms) > 1: doms.sort(key=lambda d: len(d.domain), reverse=True) msg = "multiple top domains for %s sub-domain. Domain %s selected." msg = msg % (domain, doms[0].domain) self.warning(msg) organization = doms[0].organization.name # Check enrollments to avoid insert affiliation twice enrollments = api.enrollments(self.db, uid.uuid, organization) if enrollments: continue api.add_enrollment(self.db, uid.uuid, organization) self.display('affiliate.tmpl', id=uid.uuid, email=identity.email, organization=organization) except (NotFoundError, InvalidValueError) as e: self.error(str(e)) return e.code return CMD_SUCCESS
[ "def", "affiliate", "(", "self", ")", ":", "try", ":", "uidentities", "=", "api", ".", "unique_identities", "(", "self", ".", "db", ")", "for", "uid", "in", "uidentities", ":", "uid", ".", "identities", ".", "sort", "(", "key", "=", "lambda", "x", ":...
Affiliate unique identities. This method enrolls unique identities to organizations using email addresses and top/sub domains data. Only new enrollments will be created.
[ "Affiliate", "unique", "identities", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/affiliate.py#L71-L121
27,115
chaoss/grimoirelab-sortinghat
sortinghat/cmd/countries.py
Countries.run
def run(self, *args): """Show information about countries.""" params = self.parser.parse_args(args) ct = params.code_or_term if ct and len(ct) < 2: self.error('Code country or term must have 2 or more characters length') return CODE_INVALID_FORMAT_ERROR code = ct if ct and len(ct) == 2 else None term = ct if ct and len(ct) > 2 else None try: countries = api.countries(self.db, code=code, term=term) self.display('countries.tmpl', countries=countries) except (NotFoundError, InvalidValueError) as e: self.error(str(e)) return e.code return CMD_SUCCESS
python
def run(self, *args): params = self.parser.parse_args(args) ct = params.code_or_term if ct and len(ct) < 2: self.error('Code country or term must have 2 or more characters length') return CODE_INVALID_FORMAT_ERROR code = ct if ct and len(ct) == 2 else None term = ct if ct and len(ct) > 2 else None try: countries = api.countries(self.db, code=code, term=term) self.display('countries.tmpl', countries=countries) except (NotFoundError, InvalidValueError) as e: self.error(str(e)) return e.code return CMD_SUCCESS
[ "def", "run", "(", "self", ",", "*", "args", ")", ":", "params", "=", "self", ".", "parser", ".", "parse_args", "(", "args", ")", "ct", "=", "params", ".", "code_or_term", "if", "ct", "and", "len", "(", "ct", ")", "<", "2", ":", "self", ".", "e...
Show information about countries.
[ "Show", "information", "about", "countries", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/countries.py#L64-L85
27,116
rigetti/rpcq
rpcq/_client.py
Client._call_async
async def _call_async(self, method_name: str, *args, **kwargs): """ Sends a request to the socket and then wait for the reply. To deal with multiple, asynchronous requests we do not expect that the receive reply task scheduled from this call is the one that receives this call's reply and instead rely on Events to signal across multiple _async_call/_recv_reply tasks. """ request = utils.rpc_request(method_name, *args, **kwargs) _log.debug("Sending request: %s", request) # setup an event to notify us when the reply is received (potentially by a task scheduled by # another call to _async_call). we do this before we send the request to catch the case # where the reply comes back before we re-enter this thread self._events[request.id] = asyncio.Event() # schedule a task to receive the reply to ensure we have a task to receive the reply asyncio.ensure_future(self._recv_reply()) await self._async_socket.send_multipart([to_msgpack(request)]) await self._events[request.id].wait() reply = self._replies.pop(request.id) if isinstance(reply, RPCError): raise utils.RPCError(reply.error) else: return reply.result
python
async def _call_async(self, method_name: str, *args, **kwargs): request = utils.rpc_request(method_name, *args, **kwargs) _log.debug("Sending request: %s", request) # setup an event to notify us when the reply is received (potentially by a task scheduled by # another call to _async_call). we do this before we send the request to catch the case # where the reply comes back before we re-enter this thread self._events[request.id] = asyncio.Event() # schedule a task to receive the reply to ensure we have a task to receive the reply asyncio.ensure_future(self._recv_reply()) await self._async_socket.send_multipart([to_msgpack(request)]) await self._events[request.id].wait() reply = self._replies.pop(request.id) if isinstance(reply, RPCError): raise utils.RPCError(reply.error) else: return reply.result
[ "async", "def", "_call_async", "(", "self", ",", "method_name", ":", "str", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "request", "=", "utils", ".", "rpc_request", "(", "method_name", ",", "*", "args", ",", "*", "*", "kwargs", ")", "_log", ...
Sends a request to the socket and then wait for the reply. To deal with multiple, asynchronous requests we do not expect that the receive reply task scheduled from this call is the one that receives this call's reply and instead rely on Events to signal across multiple _async_call/_recv_reply tasks.
[ "Sends", "a", "request", "to", "the", "socket", "and", "then", "wait", "for", "the", "reply", "." ]
9091e3541c4419d7ab882bb32a8b86aa85cedb6f
https://github.com/rigetti/rpcq/blob/9091e3541c4419d7ab882bb32a8b86aa85cedb6f/rpcq/_client.py#L97-L123
27,117
rigetti/rpcq
rpcq/_client.py
Client._recv_reply
async def _recv_reply(self): """ Helper task to recieve a reply store the result and trigger the associated event. """ raw_reply, = await self._async_socket.recv_multipart() reply = from_msgpack(raw_reply) _log.debug("Received reply: %s", reply) self._replies[reply.id] = reply self._events.pop(reply.id).set()
python
async def _recv_reply(self): raw_reply, = await self._async_socket.recv_multipart() reply = from_msgpack(raw_reply) _log.debug("Received reply: %s", reply) self._replies[reply.id] = reply self._events.pop(reply.id).set()
[ "async", "def", "_recv_reply", "(", "self", ")", ":", "raw_reply", ",", "=", "await", "self", ".", "_async_socket", ".", "recv_multipart", "(", ")", "reply", "=", "from_msgpack", "(", "raw_reply", ")", "_log", ".", "debug", "(", "\"Received reply: %s\"", ","...
Helper task to recieve a reply store the result and trigger the associated event.
[ "Helper", "task", "to", "recieve", "a", "reply", "store", "the", "result", "and", "trigger", "the", "associated", "event", "." ]
9091e3541c4419d7ab882bb32a8b86aa85cedb6f
https://github.com/rigetti/rpcq/blob/9091e3541c4419d7ab882bb32a8b86aa85cedb6f/rpcq/_client.py#L125-L133
27,118
rigetti/rpcq
rpcq/_client.py
Client.call
def call(self, method_name: str, *args, rpc_timeout: float = None, **kwargs): """ Send JSON RPC request to a backend socket and receive reply Note that this uses the default event loop to run in a blocking manner. If you would rather run in an async fashion or provide your own event loop then use .async_call instead :param method_name: Method name :param args: Args that will be passed to the remote function :param float rpc_timeout: Timeout in seconds for Server response, set to None to disable the timeout :param kwargs: Keyword args that will be passed to the remote function """ request = utils.rpc_request(method_name, *args, **kwargs) _log.debug("Sending request: %s", request) self._socket.send_multipart([to_msgpack(request)]) # if an rpc_timeout override is not specified, use the one set in the Client attributes if rpc_timeout is None: rpc_timeout = self.rpc_timeout start_time = time.time() while True: # Need to keep track of timeout manually in case this loop runs more than once. We subtract off already # elapsed time from the timeout. The call to max is to make sure we don't send a negative value # which would throw an error. timeout = max((start_time + rpc_timeout - time.time()) * 1000, 0) if rpc_timeout is not None else None if self._socket.poll(timeout) == 0: raise TimeoutError(f"Timeout on client {self.endpoint}, method name {method_name}, class info: {self}") raw_reply, = self._socket.recv_multipart() reply = from_msgpack(raw_reply) _log.debug("Received reply: %s", reply) # there's a possibility that the socket will have some leftover replies from a previous # request on it if that .call() was cancelled or timed out. Therefore, we need to discard replies that # don't match the request just like in the call_async case. if reply.id == request.id: break else: _log.debug('Discarding reply: %s', reply) for warning in reply.warnings: warn(f"{warning.kind}: {warning.body}") if isinstance(reply, RPCError): raise utils.RPCError(reply.error) else: return reply.result
python
def call(self, method_name: str, *args, rpc_timeout: float = None, **kwargs): request = utils.rpc_request(method_name, *args, **kwargs) _log.debug("Sending request: %s", request) self._socket.send_multipart([to_msgpack(request)]) # if an rpc_timeout override is not specified, use the one set in the Client attributes if rpc_timeout is None: rpc_timeout = self.rpc_timeout start_time = time.time() while True: # Need to keep track of timeout manually in case this loop runs more than once. We subtract off already # elapsed time from the timeout. The call to max is to make sure we don't send a negative value # which would throw an error. timeout = max((start_time + rpc_timeout - time.time()) * 1000, 0) if rpc_timeout is not None else None if self._socket.poll(timeout) == 0: raise TimeoutError(f"Timeout on client {self.endpoint}, method name {method_name}, class info: {self}") raw_reply, = self._socket.recv_multipart() reply = from_msgpack(raw_reply) _log.debug("Received reply: %s", reply) # there's a possibility that the socket will have some leftover replies from a previous # request on it if that .call() was cancelled or timed out. Therefore, we need to discard replies that # don't match the request just like in the call_async case. if reply.id == request.id: break else: _log.debug('Discarding reply: %s', reply) for warning in reply.warnings: warn(f"{warning.kind}: {warning.body}") if isinstance(reply, RPCError): raise utils.RPCError(reply.error) else: return reply.result
[ "def", "call", "(", "self", ",", "method_name", ":", "str", ",", "*", "args", ",", "rpc_timeout", ":", "float", "=", "None", ",", "*", "*", "kwargs", ")", ":", "request", "=", "utils", ".", "rpc_request", "(", "method_name", ",", "*", "args", ",", ...
Send JSON RPC request to a backend socket and receive reply Note that this uses the default event loop to run in a blocking manner. If you would rather run in an async fashion or provide your own event loop then use .async_call instead :param method_name: Method name :param args: Args that will be passed to the remote function :param float rpc_timeout: Timeout in seconds for Server response, set to None to disable the timeout :param kwargs: Keyword args that will be passed to the remote function
[ "Send", "JSON", "RPC", "request", "to", "a", "backend", "socket", "and", "receive", "reply", "Note", "that", "this", "uses", "the", "default", "event", "loop", "to", "run", "in", "a", "blocking", "manner", ".", "If", "you", "would", "rather", "run", "in"...
9091e3541c4419d7ab882bb32a8b86aa85cedb6f
https://github.com/rigetti/rpcq/blob/9091e3541c4419d7ab882bb32a8b86aa85cedb6f/rpcq/_client.py#L135-L182
27,119
rigetti/rpcq
rpcq/_client.py
Client.close
def close(self): """ Close the sockets """ self._socket.close() if self._async_socket_cache: self._async_socket_cache.close() self._async_socket_cache = None
python
def close(self): self._socket.close() if self._async_socket_cache: self._async_socket_cache.close() self._async_socket_cache = None
[ "def", "close", "(", "self", ")", ":", "self", ".", "_socket", ".", "close", "(", ")", "if", "self", ".", "_async_socket_cache", ":", "self", ".", "_async_socket_cache", ".", "close", "(", ")", "self", ".", "_async_socket_cache", "=", "None" ]
Close the sockets
[ "Close", "the", "sockets" ]
9091e3541c4419d7ab882bb32a8b86aa85cedb6f
https://github.com/rigetti/rpcq/blob/9091e3541c4419d7ab882bb32a8b86aa85cedb6f/rpcq/_client.py#L184-L191
27,120
rigetti/rpcq
rpcq/_client.py
Client._connect_to_socket
def _connect_to_socket(self, context: zmq.Context, endpoint: str): """ Connect to a DEALER socket at endpoint and turn off lingering. :param context: ZMQ Context to use (potentially async) :param endpoint: Endpoint :return: Connected socket """ socket = context.socket(zmq.DEALER) socket.connect(endpoint) socket.setsockopt(zmq.LINGER, 0) _log.debug("Client connected to endpoint %s", self.endpoint) return socket
python
def _connect_to_socket(self, context: zmq.Context, endpoint: str): socket = context.socket(zmq.DEALER) socket.connect(endpoint) socket.setsockopt(zmq.LINGER, 0) _log.debug("Client connected to endpoint %s", self.endpoint) return socket
[ "def", "_connect_to_socket", "(", "self", ",", "context", ":", "zmq", ".", "Context", ",", "endpoint", ":", "str", ")", ":", "socket", "=", "context", ".", "socket", "(", "zmq", ".", "DEALER", ")", "socket", ".", "connect", "(", "endpoint", ")", "socke...
Connect to a DEALER socket at endpoint and turn off lingering. :param context: ZMQ Context to use (potentially async) :param endpoint: Endpoint :return: Connected socket
[ "Connect", "to", "a", "DEALER", "socket", "at", "endpoint", "and", "turn", "off", "lingering", "." ]
9091e3541c4419d7ab882bb32a8b86aa85cedb6f
https://github.com/rigetti/rpcq/blob/9091e3541c4419d7ab882bb32a8b86aa85cedb6f/rpcq/_client.py#L193-L205
27,121
rigetti/rpcq
rpcq/_client.py
Client._async_socket
def _async_socket(self): """ Creates a new async socket if one doesn't already exist for this Client """ if not self._async_socket_cache: self._async_socket_cache = self._connect_to_socket(zmq.asyncio.Context(), self.endpoint) return self._async_socket_cache
python
def _async_socket(self): if not self._async_socket_cache: self._async_socket_cache = self._connect_to_socket(zmq.asyncio.Context(), self.endpoint) return self._async_socket_cache
[ "def", "_async_socket", "(", "self", ")", ":", "if", "not", "self", ".", "_async_socket_cache", ":", "self", ".", "_async_socket_cache", "=", "self", ".", "_connect_to_socket", "(", "zmq", ".", "asyncio", ".", "Context", "(", ")", ",", "self", ".", "endpoi...
Creates a new async socket if one doesn't already exist for this Client
[ "Creates", "a", "new", "async", "socket", "if", "one", "doesn", "t", "already", "exist", "for", "this", "Client" ]
9091e3541c4419d7ab882bb32a8b86aa85cedb6f
https://github.com/rigetti/rpcq/blob/9091e3541c4419d7ab882bb32a8b86aa85cedb6f/rpcq/_client.py#L208-L215
27,122
rigetti/rpcq
rpcq/_server.py
Server.run
def run(self, endpoint: str, loop: AbstractEventLoop = None): """ Run server main task. :param endpoint: Socket endpoint to listen to, e.g. "tcp://*:1234" :param loop: Event loop to run server in (alternatively just use run_async method) """ if not loop: loop = asyncio.get_event_loop() try: loop.run_until_complete(self.run_async(endpoint)) except KeyboardInterrupt: self._shutdown()
python
def run(self, endpoint: str, loop: AbstractEventLoop = None): if not loop: loop = asyncio.get_event_loop() try: loop.run_until_complete(self.run_async(endpoint)) except KeyboardInterrupt: self._shutdown()
[ "def", "run", "(", "self", ",", "endpoint", ":", "str", ",", "loop", ":", "AbstractEventLoop", "=", "None", ")", ":", "if", "not", "loop", ":", "loop", "=", "asyncio", ".", "get_event_loop", "(", ")", "try", ":", "loop", ".", "run_until_complete", "(",...
Run server main task. :param endpoint: Socket endpoint to listen to, e.g. "tcp://*:1234" :param loop: Event loop to run server in (alternatively just use run_async method)
[ "Run", "server", "main", "task", "." ]
9091e3541c4419d7ab882bb32a8b86aa85cedb6f
https://github.com/rigetti/rpcq/blob/9091e3541c4419d7ab882bb32a8b86aa85cedb6f/rpcq/_server.py#L132-L145
27,123
rigetti/rpcq
rpcq/_server.py
Server._shutdown
def _shutdown(self): """ Shut down the server. """ for exit_handler in self._exit_handlers: exit_handler() if self._socket: self._socket.close() self._socket = None
python
def _shutdown(self): for exit_handler in self._exit_handlers: exit_handler() if self._socket: self._socket.close() self._socket = None
[ "def", "_shutdown", "(", "self", ")", ":", "for", "exit_handler", "in", "self", ".", "_exit_handlers", ":", "exit_handler", "(", ")", "if", "self", ".", "_socket", ":", "self", ".", "_socket", ".", "close", "(", ")", "self", ".", "_socket", "=", "None"...
Shut down the server.
[ "Shut", "down", "the", "server", "." ]
9091e3541c4419d7ab882bb32a8b86aa85cedb6f
https://github.com/rigetti/rpcq/blob/9091e3541c4419d7ab882bb32a8b86aa85cedb6f/rpcq/_server.py#L153-L162
27,124
rigetti/rpcq
rpcq/_server.py
Server._connect
def _connect(self, endpoint: str): """ Connect the server to an endpoint. Creates a ZMQ ROUTER socket for the given endpoint. :param endpoint: Socket endpoint, e.g. "tcp://*:1234" """ if self._socket: raise RuntimeError('Cannot run multiple Servers on the same socket') context = zmq.asyncio.Context() self._socket = context.socket(zmq.ROUTER) self._socket.bind(endpoint) _log.info("Starting server, listening on endpoint {}".format(endpoint))
python
def _connect(self, endpoint: str): if self._socket: raise RuntimeError('Cannot run multiple Servers on the same socket') context = zmq.asyncio.Context() self._socket = context.socket(zmq.ROUTER) self._socket.bind(endpoint) _log.info("Starting server, listening on endpoint {}".format(endpoint))
[ "def", "_connect", "(", "self", ",", "endpoint", ":", "str", ")", ":", "if", "self", ".", "_socket", ":", "raise", "RuntimeError", "(", "'Cannot run multiple Servers on the same socket'", ")", "context", "=", "zmq", ".", "asyncio", ".", "Context", "(", ")", ...
Connect the server to an endpoint. Creates a ZMQ ROUTER socket for the given endpoint. :param endpoint: Socket endpoint, e.g. "tcp://*:1234"
[ "Connect", "the", "server", "to", "an", "endpoint", ".", "Creates", "a", "ZMQ", "ROUTER", "socket", "for", "the", "given", "endpoint", "." ]
9091e3541c4419d7ab882bb32a8b86aa85cedb6f
https://github.com/rigetti/rpcq/blob/9091e3541c4419d7ab882bb32a8b86aa85cedb6f/rpcq/_server.py#L164-L177
27,125
rigetti/rpcq
rpcq/_server.py
Server._process_request
async def _process_request(self, identity: bytes, empty_frame: list, request: RPCRequest): """ Executes the method specified in a JSON RPC request and then sends the reply to the socket. :param identity: Client identity provided by ZeroMQ :param empty_frame: Either an empty list or a single null frame depending on the client type :param request: JSON RPC request """ try: _log.debug("Client %s sent request: %s", identity, request) start_time = datetime.now() reply = await self.rpc_spec.run_handler(request) if self.announce_timing: _log.info("Request {} for {} lasted {} seconds".format( request.id, request.method, (datetime.now() - start_time).total_seconds())) _log.debug("Sending client %s reply: %s", identity, reply) await self._socket.send_multipart([identity, *empty_frame, to_msgpack(reply)]) except Exception as e: if self.serialize_exceptions: _log.exception('Exception thrown in _process_request') else: raise e
python
async def _process_request(self, identity: bytes, empty_frame: list, request: RPCRequest): try: _log.debug("Client %s sent request: %s", identity, request) start_time = datetime.now() reply = await self.rpc_spec.run_handler(request) if self.announce_timing: _log.info("Request {} for {} lasted {} seconds".format( request.id, request.method, (datetime.now() - start_time).total_seconds())) _log.debug("Sending client %s reply: %s", identity, reply) await self._socket.send_multipart([identity, *empty_frame, to_msgpack(reply)]) except Exception as e: if self.serialize_exceptions: _log.exception('Exception thrown in _process_request') else: raise e
[ "async", "def", "_process_request", "(", "self", ",", "identity", ":", "bytes", ",", "empty_frame", ":", "list", ",", "request", ":", "RPCRequest", ")", ":", "try", ":", "_log", ".", "debug", "(", "\"Client %s sent request: %s\"", ",", "identity", ",", "requ...
Executes the method specified in a JSON RPC request and then sends the reply to the socket. :param identity: Client identity provided by ZeroMQ :param empty_frame: Either an empty list or a single null frame depending on the client type :param request: JSON RPC request
[ "Executes", "the", "method", "specified", "in", "a", "JSON", "RPC", "request", "and", "then", "sends", "the", "reply", "to", "the", "socket", "." ]
9091e3541c4419d7ab882bb32a8b86aa85cedb6f
https://github.com/rigetti/rpcq/blob/9091e3541c4419d7ab882bb32a8b86aa85cedb6f/rpcq/_server.py#L179-L201
27,126
rigetti/rpcq
rpcq/_spec.py
RPCSpec.add_handler
def add_handler(self, f): """ Adds the function f to a dictionary of JSON RPC methods. :param callable f: Method to be exposed :return: """ if f.__name__.startswith('rpc_'): raise ValueError("Server method names cannot start with rpc_.") self._json_rpc_methods[f.__name__] = f return f
python
def add_handler(self, f): if f.__name__.startswith('rpc_'): raise ValueError("Server method names cannot start with rpc_.") self._json_rpc_methods[f.__name__] = f return f
[ "def", "add_handler", "(", "self", ",", "f", ")", ":", "if", "f", ".", "__name__", ".", "startswith", "(", "'rpc_'", ")", ":", "raise", "ValueError", "(", "\"Server method names cannot start with rpc_.\"", ")", "self", ".", "_json_rpc_methods", "[", "f", ".", ...
Adds the function f to a dictionary of JSON RPC methods. :param callable f: Method to be exposed :return:
[ "Adds", "the", "function", "f", "to", "a", "dictionary", "of", "JSON", "RPC", "methods", "." ]
9091e3541c4419d7ab882bb32a8b86aa85cedb6f
https://github.com/rigetti/rpcq/blob/9091e3541c4419d7ab882bb32a8b86aa85cedb6f/rpcq/_spec.py#L74-L84
27,127
rigetti/rpcq
rpcq/_spec.py
RPCSpec.get_handler
def get_handler(self, request): """ Get callable from JSON RPC request :param RPCRequest request: JSON RPC request :return: Method :rtype: callable """ try: f = self._json_rpc_methods[request.method] except (AttributeError, KeyError): # pragma no coverage raise RPCMethodError("Received invalid method '{}'".format(request.method)) return f
python
def get_handler(self, request): try: f = self._json_rpc_methods[request.method] except (AttributeError, KeyError): # pragma no coverage raise RPCMethodError("Received invalid method '{}'".format(request.method)) return f
[ "def", "get_handler", "(", "self", ",", "request", ")", ":", "try", ":", "f", "=", "self", ".", "_json_rpc_methods", "[", "request", ".", "method", "]", "except", "(", "AttributeError", ",", "KeyError", ")", ":", "# pragma no coverage", "raise", "RPCMethodEr...
Get callable from JSON RPC request :param RPCRequest request: JSON RPC request :return: Method :rtype: callable
[ "Get", "callable", "from", "JSON", "RPC", "request" ]
9091e3541c4419d7ab882bb32a8b86aa85cedb6f
https://github.com/rigetti/rpcq/blob/9091e3541c4419d7ab882bb32a8b86aa85cedb6f/rpcq/_spec.py#L86-L100
27,128
rigetti/rpcq
rpcq/_spec.py
RPCSpec.run_handler
async def run_handler(self, request: RPCRequest) -> Union[RPCReply, RPCError]: """ Process a JSON RPC request :param RPCRequest request: JSON RPC request :return: JSON RPC reply """ with catch_warnings(record=True) as warnings: try: rpc_handler = self.get_handler(request) except RPCMethodError as e: return rpc_error(request.id, str(e), warnings=warnings) try: # Run RPC and get result args, kwargs = get_input(request.params) result = rpc_handler(*args, **kwargs) if asyncio.iscoroutine(result): result = await result except Exception as e: if self.serialize_exceptions: _traceback = traceback.format_exc() _log.error(_traceback) if self.provide_tracebacks: return rpc_error(request.id, "{}\n{}".format(str(e), _traceback), warnings=warnings) else: return rpc_error(request.id, str(e), warnings=warnings) else: raise e return rpc_reply(request.id, result, warnings=warnings)
python
async def run_handler(self, request: RPCRequest) -> Union[RPCReply, RPCError]: with catch_warnings(record=True) as warnings: try: rpc_handler = self.get_handler(request) except RPCMethodError as e: return rpc_error(request.id, str(e), warnings=warnings) try: # Run RPC and get result args, kwargs = get_input(request.params) result = rpc_handler(*args, **kwargs) if asyncio.iscoroutine(result): result = await result except Exception as e: if self.serialize_exceptions: _traceback = traceback.format_exc() _log.error(_traceback) if self.provide_tracebacks: return rpc_error(request.id, "{}\n{}".format(str(e), _traceback), warnings=warnings) else: return rpc_error(request.id, str(e), warnings=warnings) else: raise e return rpc_reply(request.id, result, warnings=warnings)
[ "async", "def", "run_handler", "(", "self", ",", "request", ":", "RPCRequest", ")", "->", "Union", "[", "RPCReply", ",", "RPCError", "]", ":", "with", "catch_warnings", "(", "record", "=", "True", ")", "as", "warnings", ":", "try", ":", "rpc_handler", "=...
Process a JSON RPC request :param RPCRequest request: JSON RPC request :return: JSON RPC reply
[ "Process", "a", "JSON", "RPC", "request" ]
9091e3541c4419d7ab882bb32a8b86aa85cedb6f
https://github.com/rigetti/rpcq/blob/9091e3541c4419d7ab882bb32a8b86aa85cedb6f/rpcq/_spec.py#L102-L135
27,129
rigetti/rpcq
rpcq/_utils.py
rpc_request
def rpc_request(method_name: str, *args, **kwargs) -> rpcq.messages.RPCRequest: """ Create RPC request :param method_name: Method name :param args: Positional arguments :param kwargs: Keyword arguments :return: JSON RPC formatted dict """ if args: kwargs['*args'] = args return rpcq.messages.RPCRequest( jsonrpc='2.0', id=str(uuid.uuid4()), method=method_name, params=kwargs )
python
def rpc_request(method_name: str, *args, **kwargs) -> rpcq.messages.RPCRequest: if args: kwargs['*args'] = args return rpcq.messages.RPCRequest( jsonrpc='2.0', id=str(uuid.uuid4()), method=method_name, params=kwargs )
[ "def", "rpc_request", "(", "method_name", ":", "str", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "rpcq", ".", "messages", ".", "RPCRequest", ":", "if", "args", ":", "kwargs", "[", "'*args'", "]", "=", "args", "return", "rpcq", ".", "messag...
Create RPC request :param method_name: Method name :param args: Positional arguments :param kwargs: Keyword arguments :return: JSON RPC formatted dict
[ "Create", "RPC", "request" ]
9091e3541c4419d7ab882bb32a8b86aa85cedb6f
https://github.com/rigetti/rpcq/blob/9091e3541c4419d7ab882bb32a8b86aa85cedb6f/rpcq/_utils.py#L28-L45
27,130
rigetti/rpcq
rpcq/_utils.py
rpc_reply
def rpc_reply(id: Union[str, int], result: Optional[object], warnings: Optional[List[Warning]] = None) -> rpcq.messages.RPCReply: """ Create RPC reply :param str|int id: Request ID :param result: Result :param warnings: List of warnings to attach to the message :return: JSON RPC formatted dict """ warnings = warnings or [] return rpcq.messages.RPCReply( jsonrpc='2.0', id=id, result=result, warnings=[rpc_warning(warning) for warning in warnings] )
python
def rpc_reply(id: Union[str, int], result: Optional[object], warnings: Optional[List[Warning]] = None) -> rpcq.messages.RPCReply: warnings = warnings or [] return rpcq.messages.RPCReply( jsonrpc='2.0', id=id, result=result, warnings=[rpc_warning(warning) for warning in warnings] )
[ "def", "rpc_reply", "(", "id", ":", "Union", "[", "str", ",", "int", "]", ",", "result", ":", "Optional", "[", "object", "]", ",", "warnings", ":", "Optional", "[", "List", "[", "Warning", "]", "]", "=", "None", ")", "->", "rpcq", ".", "messages", ...
Create RPC reply :param str|int id: Request ID :param result: Result :param warnings: List of warnings to attach to the message :return: JSON RPC formatted dict
[ "Create", "RPC", "reply" ]
9091e3541c4419d7ab882bb32a8b86aa85cedb6f
https://github.com/rigetti/rpcq/blob/9091e3541c4419d7ab882bb32a8b86aa85cedb6f/rpcq/_utils.py#L48-L65
27,131
rigetti/rpcq
rpcq/_utils.py
rpc_error
def rpc_error(id: Union[str, int], error_msg: str, warnings: List[Any] = []) -> rpcq.messages.RPCError: """ Create RPC error :param id: Request ID :param error_msg: Error message :param warning: List of warnings to attach to the message :return: JSON RPC formatted dict """ return rpcq.messages.RPCError( jsonrpc='2.0', id=id, error=error_msg, warnings=[rpc_warning(warning) for warning in warnings])
python
def rpc_error(id: Union[str, int], error_msg: str, warnings: List[Any] = []) -> rpcq.messages.RPCError: return rpcq.messages.RPCError( jsonrpc='2.0', id=id, error=error_msg, warnings=[rpc_warning(warning) for warning in warnings])
[ "def", "rpc_error", "(", "id", ":", "Union", "[", "str", ",", "int", "]", ",", "error_msg", ":", "str", ",", "warnings", ":", "List", "[", "Any", "]", "=", "[", "]", ")", "->", "rpcq", ".", "messages", ".", "RPCError", ":", "return", "rpcq", ".",...
Create RPC error :param id: Request ID :param error_msg: Error message :param warning: List of warnings to attach to the message :return: JSON RPC formatted dict
[ "Create", "RPC", "error" ]
9091e3541c4419d7ab882bb32a8b86aa85cedb6f
https://github.com/rigetti/rpcq/blob/9091e3541c4419d7ab882bb32a8b86aa85cedb6f/rpcq/_utils.py#L68-L82
27,132
rigetti/rpcq
rpcq/_utils.py
get_input
def get_input(params: Union[dict, list]) -> Tuple[list, dict]: """ Get positional or keyword arguments from JSON RPC params :param params: Parameters passed through JSON RPC :return: args, kwargs """ # Backwards compatibility for old clients that send params as a list if isinstance(params, list): args = params kwargs = {} elif isinstance(params, dict): args = params.pop('*args', []) kwargs = params else: # pragma no coverage raise TypeError( 'Unknown type {} of params, must be list or dict'.format(type(params))) return args, kwargs
python
def get_input(params: Union[dict, list]) -> Tuple[list, dict]: # Backwards compatibility for old clients that send params as a list if isinstance(params, list): args = params kwargs = {} elif isinstance(params, dict): args = params.pop('*args', []) kwargs = params else: # pragma no coverage raise TypeError( 'Unknown type {} of params, must be list or dict'.format(type(params))) return args, kwargs
[ "def", "get_input", "(", "params", ":", "Union", "[", "dict", ",", "list", "]", ")", "->", "Tuple", "[", "list", ",", "dict", "]", ":", "# Backwards compatibility for old clients that send params as a list", "if", "isinstance", "(", "params", ",", "list", ")", ...
Get positional or keyword arguments from JSON RPC params :param params: Parameters passed through JSON RPC :return: args, kwargs
[ "Get", "positional", "or", "keyword", "arguments", "from", "JSON", "RPC", "params" ]
9091e3541c4419d7ab882bb32a8b86aa85cedb6f
https://github.com/rigetti/rpcq/blob/9091e3541c4419d7ab882bb32a8b86aa85cedb6f/rpcq/_utils.py#L85-L103
27,133
rigetti/rpcq
rpcq/_base.py
repr_value
def repr_value(value): """ Represent a value in human readable form. For long list's this truncates the printed representation. :param value: The value to represent. :return: A string representation. :rtype: basestring """ if isinstance(value, list) and len(value) > REPR_LIST_TRUNCATION: return "[{},...]".format(", ".join(map(repr, value[:REPR_LIST_TRUNCATION]))) else: return repr(value)
python
def repr_value(value): if isinstance(value, list) and len(value) > REPR_LIST_TRUNCATION: return "[{},...]".format(", ".join(map(repr, value[:REPR_LIST_TRUNCATION]))) else: return repr(value)
[ "def", "repr_value", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "list", ")", "and", "len", "(", "value", ")", ">", "REPR_LIST_TRUNCATION", ":", "return", "\"[{},...]\"", ".", "format", "(", "\", \"", ".", "join", "(", "map", "(", "r...
Represent a value in human readable form. For long list's this truncates the printed representation. :param value: The value to represent. :return: A string representation. :rtype: basestring
[ "Represent", "a", "value", "in", "human", "readable", "form", ".", "For", "long", "list", "s", "this", "truncates", "the", "printed", "representation", "." ]
9091e3541c4419d7ab882bb32a8b86aa85cedb6f
https://github.com/rigetti/rpcq/blob/9091e3541c4419d7ab882bb32a8b86aa85cedb6f/rpcq/_base.py#L28-L40
27,134
klen/graphite-beacon
graphite_beacon/alerts.py
AlertFabric.get
def get(cls, reactor, source='graphite', **options): """Get Alert Class by source.""" acls = cls.alerts[source] return acls(reactor, **options)
python
def get(cls, reactor, source='graphite', **options): acls = cls.alerts[source] return acls(reactor, **options)
[ "def", "get", "(", "cls", ",", "reactor", ",", "source", "=", "'graphite'", ",", "*", "*", "options", ")", ":", "acls", "=", "cls", ".", "alerts", "[", "source", "]", "return", "acls", "(", "reactor", ",", "*", "*", "options", ")" ]
Get Alert Class by source.
[ "Get", "Alert", "Class", "by", "source", "." ]
c1f071e9f557693bc90f6acbc314994985dc3b77
https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/alerts.py#L52-L55
27,135
klen/graphite-beacon
graphite_beacon/alerts.py
BaseAlert.convert
def convert(self, value): """Convert self value.""" try: return convert_to_format(value, self._format) except (ValueError, TypeError): return value
python
def convert(self, value): try: return convert_to_format(value, self._format) except (ValueError, TypeError): return value
[ "def", "convert", "(", "self", ",", "value", ")", ":", "try", ":", "return", "convert_to_format", "(", "value", ",", "self", ".", "_format", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "return", "value" ]
Convert self value.
[ "Convert", "self", "value", "." ]
c1f071e9f557693bc90f6acbc314994985dc3b77
https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/alerts.py#L144-L149
27,136
klen/graphite-beacon
graphite_beacon/alerts.py
BaseAlert.check
def check(self, records): """Check current value.""" for value, target in records: LOGGER.info("%s [%s]: %s", self.name, target, value) if value is None: self.notify(self.no_data, value, target) continue for rule in self.rules: if self.evaluate_rule(rule, value, target): self.notify(rule['level'], value, target, rule=rule) break else: self.notify('normal', value, target, rule=rule) self.history[target].append(value)
python
def check(self, records): for value, target in records: LOGGER.info("%s [%s]: %s", self.name, target, value) if value is None: self.notify(self.no_data, value, target) continue for rule in self.rules: if self.evaluate_rule(rule, value, target): self.notify(rule['level'], value, target, rule=rule) break else: self.notify('normal', value, target, rule=rule) self.history[target].append(value)
[ "def", "check", "(", "self", ",", "records", ")", ":", "for", "value", ",", "target", "in", "records", ":", "LOGGER", ".", "info", "(", "\"%s [%s]: %s\"", ",", "self", ".", "name", ",", "target", ",", "value", ")", "if", "value", "is", "None", ":", ...
Check current value.
[ "Check", "current", "value", "." ]
c1f071e9f557693bc90f6acbc314994985dc3b77
https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/alerts.py#L168-L182
27,137
klen/graphite-beacon
graphite_beacon/alerts.py
BaseAlert.evaluate_rule
def evaluate_rule(self, rule, value, target): """Calculate the value.""" def evaluate(expr): if expr in LOGICAL_OPERATORS.values(): return expr rvalue = self.get_value_for_expr(expr, target) if rvalue is None: return False # ignore this result return expr['op'](value, rvalue) evaluated = [evaluate(expr) for expr in rule['exprs']] while len(evaluated) > 1: lhs, logical_op, rhs = (evaluated.pop(0) for _ in range(3)) evaluated.insert(0, logical_op(lhs, rhs)) return evaluated[0]
python
def evaluate_rule(self, rule, value, target): def evaluate(expr): if expr in LOGICAL_OPERATORS.values(): return expr rvalue = self.get_value_for_expr(expr, target) if rvalue is None: return False # ignore this result return expr['op'](value, rvalue) evaluated = [evaluate(expr) for expr in rule['exprs']] while len(evaluated) > 1: lhs, logical_op, rhs = (evaluated.pop(0) for _ in range(3)) evaluated.insert(0, logical_op(lhs, rhs)) return evaluated[0]
[ "def", "evaluate_rule", "(", "self", ",", "rule", ",", "value", ",", "target", ")", ":", "def", "evaluate", "(", "expr", ")", ":", "if", "expr", "in", "LOGICAL_OPERATORS", ".", "values", "(", ")", ":", "return", "expr", "rvalue", "=", "self", ".", "g...
Calculate the value.
[ "Calculate", "the", "value", "." ]
c1f071e9f557693bc90f6acbc314994985dc3b77
https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/alerts.py#L184-L199
27,138
klen/graphite-beacon
graphite_beacon/alerts.py
BaseAlert.get_value_for_expr
def get_value_for_expr(self, expr, target): """I have no idea.""" if expr in LOGICAL_OPERATORS.values(): return None rvalue = expr['value'] if rvalue == HISTORICAL: history = self.history[target] if len(history) < self.history_size: return None rvalue = sum(history) / float(len(history)) rvalue = expr['mod'](rvalue) return rvalue
python
def get_value_for_expr(self, expr, target): if expr in LOGICAL_OPERATORS.values(): return None rvalue = expr['value'] if rvalue == HISTORICAL: history = self.history[target] if len(history) < self.history_size: return None rvalue = sum(history) / float(len(history)) rvalue = expr['mod'](rvalue) return rvalue
[ "def", "get_value_for_expr", "(", "self", ",", "expr", ",", "target", ")", ":", "if", "expr", "in", "LOGICAL_OPERATORS", ".", "values", "(", ")", ":", "return", "None", "rvalue", "=", "expr", "[", "'value'", "]", "if", "rvalue", "==", "HISTORICAL", ":", ...
I have no idea.
[ "I", "have", "no", "idea", "." ]
c1f071e9f557693bc90f6acbc314994985dc3b77
https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/alerts.py#L201-L213
27,139
klen/graphite-beacon
graphite_beacon/alerts.py
BaseAlert.notify
def notify(self, level, value, target=None, ntype=None, rule=None): """Notify main reactor about event.""" # Did we see the event before? if target in self.state and level == self.state[target]: return False # Do we see the event first time? if target not in self.state and level == 'normal' \ and not self.reactor.options['send_initial']: return False self.state[target] = level return self.reactor.notify(level, self, value, target=target, ntype=ntype, rule=rule)
python
def notify(self, level, value, target=None, ntype=None, rule=None): # Did we see the event before? if target in self.state and level == self.state[target]: return False # Do we see the event first time? if target not in self.state and level == 'normal' \ and not self.reactor.options['send_initial']: return False self.state[target] = level return self.reactor.notify(level, self, value, target=target, ntype=ntype, rule=rule)
[ "def", "notify", "(", "self", ",", "level", ",", "value", ",", "target", "=", "None", ",", "ntype", "=", "None", ",", "rule", "=", "None", ")", ":", "# Did we see the event before?", "if", "target", "in", "self", ".", "state", "and", "level", "==", "se...
Notify main reactor about event.
[ "Notify", "main", "reactor", "about", "event", "." ]
c1f071e9f557693bc90f6acbc314994985dc3b77
https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/alerts.py#L215-L227
27,140
klen/graphite-beacon
graphite_beacon/alerts.py
GraphiteAlert.load
def load(self): """Load data from Graphite.""" LOGGER.debug('%s: start checking: %s', self.name, self.query) if self.waiting: self.notify('warning', 'Process takes too much time', target='waiting', ntype='common') else: self.waiting = True try: response = yield self.client.fetch(self.url, auth_username=self.auth_username, auth_password=self.auth_password, request_timeout=self.request_timeout, connect_timeout=self.connect_timeout, validate_cert=self.validate_cert) records = ( GraphiteRecord(line, self.default_nan_value, self.ignore_nan) for line in response.buffer) data = [ (None if record.empty else getattr(record, self.method), record.target) for record in records] if len(data) == 0: raise ValueError('No data') self.check(data) self.notify('normal', 'Metrics are loaded', target='loading', ntype='common') except Exception as e: self.notify( self.loading_error, 'Loading error: %s' % e, target='loading', ntype='common') self.waiting = False
python
def load(self): LOGGER.debug('%s: start checking: %s', self.name, self.query) if self.waiting: self.notify('warning', 'Process takes too much time', target='waiting', ntype='common') else: self.waiting = True try: response = yield self.client.fetch(self.url, auth_username=self.auth_username, auth_password=self.auth_password, request_timeout=self.request_timeout, connect_timeout=self.connect_timeout, validate_cert=self.validate_cert) records = ( GraphiteRecord(line, self.default_nan_value, self.ignore_nan) for line in response.buffer) data = [ (None if record.empty else getattr(record, self.method), record.target) for record in records] if len(data) == 0: raise ValueError('No data') self.check(data) self.notify('normal', 'Metrics are loaded', target='loading', ntype='common') except Exception as e: self.notify( self.loading_error, 'Loading error: %s' % e, target='loading', ntype='common') self.waiting = False
[ "def", "load", "(", "self", ")", ":", "LOGGER", ".", "debug", "(", "'%s: start checking: %s'", ",", "self", ".", "name", ",", "self", ".", "query", ")", "if", "self", ".", "waiting", ":", "self", ".", "notify", "(", "'warning'", ",", "'Process takes too ...
Load data from Graphite.
[ "Load", "data", "from", "Graphite", "." ]
c1f071e9f557693bc90f6acbc314994985dc3b77
https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/alerts.py#L259-L285
27,141
klen/graphite-beacon
graphite_beacon/alerts.py
GraphiteAlert.get_graph_url
def get_graph_url(self, target, graphite_url=None): """Get Graphite URL.""" return self._graphite_url(target, graphite_url=graphite_url, raw_data=False)
python
def get_graph_url(self, target, graphite_url=None): return self._graphite_url(target, graphite_url=graphite_url, raw_data=False)
[ "def", "get_graph_url", "(", "self", ",", "target", ",", "graphite_url", "=", "None", ")", ":", "return", "self", ".", "_graphite_url", "(", "target", ",", "graphite_url", "=", "graphite_url", ",", "raw_data", "=", "False", ")" ]
Get Graphite URL.
[ "Get", "Graphite", "URL", "." ]
c1f071e9f557693bc90f6acbc314994985dc3b77
https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/alerts.py#L287-L289
27,142
klen/graphite-beacon
graphite_beacon/alerts.py
GraphiteAlert._graphite_url
def _graphite_url(self, query, raw_data=False, graphite_url=None): """Build Graphite URL.""" query = escape.url_escape(query) graphite_url = graphite_url or self.reactor.options.get('public_graphite_url') url = "{base}/render/?target={query}&from=-{from_time}&until=-{until}".format( base=graphite_url, query=query, from_time=self.from_time.as_graphite(), until=self.until.as_graphite(), ) if raw_data: url = "{}&format=raw".format(url) return url
python
def _graphite_url(self, query, raw_data=False, graphite_url=None): query = escape.url_escape(query) graphite_url = graphite_url or self.reactor.options.get('public_graphite_url') url = "{base}/render/?target={query}&from=-{from_time}&until=-{until}".format( base=graphite_url, query=query, from_time=self.from_time.as_graphite(), until=self.until.as_graphite(), ) if raw_data: url = "{}&format=raw".format(url) return url
[ "def", "_graphite_url", "(", "self", ",", "query", ",", "raw_data", "=", "False", ",", "graphite_url", "=", "None", ")", ":", "query", "=", "escape", ".", "url_escape", "(", "query", ")", "graphite_url", "=", "graphite_url", "or", "self", ".", "reactor", ...
Build Graphite URL.
[ "Build", "Graphite", "URL", "." ]
c1f071e9f557693bc90f6acbc314994985dc3b77
https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/alerts.py#L291-L303
27,143
klen/graphite-beacon
graphite_beacon/alerts.py
URLAlert.load
def load(self): """Load URL.""" LOGGER.debug('%s: start checking: %s', self.name, self.query) if self.waiting: self.notify('warning', 'Process takes too much time', target='waiting', ntype='common') else: self.waiting = True try: response = yield self.client.fetch( self.query, method=self.options.get('method', 'GET'), request_timeout=self.request_timeout, connect_timeout=self.connect_timeout, validate_cert=self.options.get('validate_cert', True)) self.check([(self.get_data(response), self.query)]) self.notify('normal', 'Metrics are loaded', target='loading', ntype='common') except Exception as e: self.notify('critical', str(e), target='loading', ntype='common') self.waiting = False
python
def load(self): LOGGER.debug('%s: start checking: %s', self.name, self.query) if self.waiting: self.notify('warning', 'Process takes too much time', target='waiting', ntype='common') else: self.waiting = True try: response = yield self.client.fetch( self.query, method=self.options.get('method', 'GET'), request_timeout=self.request_timeout, connect_timeout=self.connect_timeout, validate_cert=self.options.get('validate_cert', True)) self.check([(self.get_data(response), self.query)]) self.notify('normal', 'Metrics are loaded', target='loading', ntype='common') except Exception as e: self.notify('critical', str(e), target='loading', ntype='common') self.waiting = False
[ "def", "load", "(", "self", ")", ":", "LOGGER", ".", "debug", "(", "'%s: start checking: %s'", ",", "self", ".", "name", ",", "self", ".", "query", ")", "if", "self", ".", "waiting", ":", "self", ".", "notify", "(", "'warning'", ",", "'Process takes too ...
Load URL.
[ "Load", "URL", "." ]
c1f071e9f557693bc90f6acbc314994985dc3b77
https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/alerts.py#L318-L337
27,144
klen/graphite-beacon
graphite_beacon/core.py
_get_loader
def _get_loader(config): """Determine which config file type and loader to use based on a filename. :param config str: filename to config file :return: a tuple of the loader type and callable to load :rtype: (str, Callable) """ if config.endswith('.yml') or config.endswith('.yaml'): if not yaml: LOGGER.error("pyyaml must be installed to use the YAML loader") # TODO: stop reactor if running return None, None return 'yaml', yaml.load else: return 'json', json.loads
python
def _get_loader(config): if config.endswith('.yml') or config.endswith('.yaml'): if not yaml: LOGGER.error("pyyaml must be installed to use the YAML loader") # TODO: stop reactor if running return None, None return 'yaml', yaml.load else: return 'json', json.loads
[ "def", "_get_loader", "(", "config", ")", ":", "if", "config", ".", "endswith", "(", "'.yml'", ")", "or", "config", ".", "endswith", "(", "'.yaml'", ")", ":", "if", "not", "yaml", ":", "LOGGER", ".", "error", "(", "\"pyyaml must be installed to use the YAML ...
Determine which config file type and loader to use based on a filename. :param config str: filename to config file :return: a tuple of the loader type and callable to load :rtype: (str, Callable)
[ "Determine", "which", "config", "file", "type", "and", "loader", "to", "use", "based", "on", "a", "filename", "." ]
c1f071e9f557693bc90f6acbc314994985dc3b77
https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/core.py#L185-L199
27,145
klen/graphite-beacon
graphite_beacon/core.py
Reactor.start
def start(self, start_loop=True): """Start all the things. :param start_loop bool: whether to start the ioloop. should be False if the IOLoop is managed externally """ self.start_alerts() if self.options.get('pidfile'): with open(self.options.get('pidfile'), 'w') as fpid: fpid.write(str(os.getpid())) self.callback.start() LOGGER.info('Reactor starts') if start_loop: self.loop.start()
python
def start(self, start_loop=True): self.start_alerts() if self.options.get('pidfile'): with open(self.options.get('pidfile'), 'w') as fpid: fpid.write(str(os.getpid())) self.callback.start() LOGGER.info('Reactor starts') if start_loop: self.loop.start()
[ "def", "start", "(", "self", ",", "start_loop", "=", "True", ")", ":", "self", ".", "start_alerts", "(", ")", "if", "self", ".", "options", ".", "get", "(", "'pidfile'", ")", ":", "with", "open", "(", "self", ".", "options", ".", "get", "(", "'pidf...
Start all the things. :param start_loop bool: whether to start the ioloop. should be False if the IOLoop is managed externally
[ "Start", "all", "the", "things", "." ]
c1f071e9f557693bc90f6acbc314994985dc3b77
https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/core.py#L148-L162
27,146
klen/graphite-beacon
graphite_beacon/core.py
Reactor.notify
def notify(self, level, alert, value, target=None, ntype=None, rule=None): """ Provide the event to the handlers. """ LOGGER.info('Notify %s:%s:%s:%s', level, alert, value, target or "") if ntype is None: ntype = alert.source for handler in self.handlers.get(level, []): handler.notify(level, alert, value, target=target, ntype=ntype, rule=rule)
python
def notify(self, level, alert, value, target=None, ntype=None, rule=None): LOGGER.info('Notify %s:%s:%s:%s', level, alert, value, target or "") if ntype is None: ntype = alert.source for handler in self.handlers.get(level, []): handler.notify(level, alert, value, target=target, ntype=ntype, rule=rule)
[ "def", "notify", "(", "self", ",", "level", ",", "alert", ",", "value", ",", "target", "=", "None", ",", "ntype", "=", "None", ",", "rule", "=", "None", ")", ":", "LOGGER", ".", "info", "(", "'Notify %s:%s:%s:%s'", ",", "level", ",", "alert", ",", ...
Provide the event to the handlers.
[ "Provide", "the", "event", "to", "the", "handlers", "." ]
c1f071e9f557693bc90f6acbc314994985dc3b77
https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/core.py#L173-L182
27,147
klen/graphite-beacon
graphite_beacon/handlers/telegram.py
write_to_file
def write_to_file(chats, chatfile): """called every time chats are modified""" with open(chatfile, 'w') as handler: handler.write('\n'.join((str(id_) for id_ in chats)))
python
def write_to_file(chats, chatfile): with open(chatfile, 'w') as handler: handler.write('\n'.join((str(id_) for id_ in chats)))
[ "def", "write_to_file", "(", "chats", ",", "chatfile", ")", ":", "with", "open", "(", "chatfile", ",", "'w'", ")", "as", "handler", ":", "handler", ".", "write", "(", "'\\n'", ".", "join", "(", "(", "str", "(", "id_", ")", "for", "id_", "in", "chat...
called every time chats are modified
[ "called", "every", "time", "chats", "are", "modified" ]
c1f071e9f557693bc90f6acbc314994985dc3b77
https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/handlers/telegram.py#L174-L177
27,148
klen/graphite-beacon
graphite_beacon/handlers/telegram.py
get_chatlist
def get_chatlist(chatfile): """Try reading ids of saved chats from file. If we fail, return empty set""" if not chatfile: return set() try: with open(chatfile) as file_contents: return set(int(chat) for chat in file_contents) except (OSError, IOError) as exc: LOGGER.error('could not load saved chats:\n%s', exc) return set()
python
def get_chatlist(chatfile): if not chatfile: return set() try: with open(chatfile) as file_contents: return set(int(chat) for chat in file_contents) except (OSError, IOError) as exc: LOGGER.error('could not load saved chats:\n%s', exc) return set()
[ "def", "get_chatlist", "(", "chatfile", ")", ":", "if", "not", "chatfile", ":", "return", "set", "(", ")", "try", ":", "with", "open", "(", "chatfile", ")", "as", "file_contents", ":", "return", "set", "(", "int", "(", "chat", ")", "for", "chat", "in...
Try reading ids of saved chats from file. If we fail, return empty set
[ "Try", "reading", "ids", "of", "saved", "chats", "from", "file", ".", "If", "we", "fail", "return", "empty", "set" ]
c1f071e9f557693bc90f6acbc314994985dc3b77
https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/handlers/telegram.py#L180-L190
27,149
klen/graphite-beacon
graphite_beacon/handlers/telegram.py
get_data
def get_data(upd, bot_ident): """Parse telegram update.""" update_content = json.loads(upd.decode()) result = update_content['result'] data = (get_fields(update, bot_ident) for update in result) return (dt for dt in data if dt is not None)
python
def get_data(upd, bot_ident): update_content = json.loads(upd.decode()) result = update_content['result'] data = (get_fields(update, bot_ident) for update in result) return (dt for dt in data if dt is not None)
[ "def", "get_data", "(", "upd", ",", "bot_ident", ")", ":", "update_content", "=", "json", ".", "loads", "(", "upd", ".", "decode", "(", ")", ")", "result", "=", "update_content", "[", "'result'", "]", "data", "=", "(", "get_fields", "(", "update", ",",...
Parse telegram update.
[ "Parse", "telegram", "update", "." ]
c1f071e9f557693bc90f6acbc314994985dc3b77
https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/handlers/telegram.py#L193-L199
27,150
klen/graphite-beacon
graphite_beacon/handlers/telegram.py
get_fields
def get_fields(upd, bot_ident): """In telegram api, not every update has message field, and not every message has update field. We skip those cases. Rest of fields are mandatory. We also skip if text is not a valid command to handler. """ msg = upd.get('message', {}) text = msg.get('text') if not text: return chat_id = msg['chat']['id'] command = filter_commands(text, chat_id, bot_ident) if not command: return return (upd['update_id'], chat_id, msg['message_id'], command)
python
def get_fields(upd, bot_ident): msg = upd.get('message', {}) text = msg.get('text') if not text: return chat_id = msg['chat']['id'] command = filter_commands(text, chat_id, bot_ident) if not command: return return (upd['update_id'], chat_id, msg['message_id'], command)
[ "def", "get_fields", "(", "upd", ",", "bot_ident", ")", ":", "msg", "=", "upd", ".", "get", "(", "'message'", ",", "{", "}", ")", "text", "=", "msg", ".", "get", "(", "'text'", ")", "if", "not", "text", ":", "return", "chat_id", "=", "msg", "[", ...
In telegram api, not every update has message field, and not every message has update field. We skip those cases. Rest of fields are mandatory. We also skip if text is not a valid command to handler.
[ "In", "telegram", "api", "not", "every", "update", "has", "message", "field", "and", "not", "every", "message", "has", "update", "field", ".", "We", "skip", "those", "cases", ".", "Rest", "of", "fields", "are", "mandatory", ".", "We", "also", "skip", "if...
c1f071e9f557693bc90f6acbc314994985dc3b77
https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/handlers/telegram.py#L202-L216
27,151
klen/graphite-beacon
graphite_beacon/handlers/telegram.py
TelegramHandler._listen_commands
def _listen_commands(self): """Monitor new updates and send them further to self._respond_commands, where bot actions are decided. """ self._last_update = None update_body = {'timeout': 2} while True: latest = self._last_update # increase offset to filter out older updates update_body.update({'offset': latest + 1} if latest else {}) update_resp = self.client.get_updates(update_body) update_resp.add_done_callback(self._respond_commands) yield gen.sleep(5)
python
def _listen_commands(self): self._last_update = None update_body = {'timeout': 2} while True: latest = self._last_update # increase offset to filter out older updates update_body.update({'offset': latest + 1} if latest else {}) update_resp = self.client.get_updates(update_body) update_resp.add_done_callback(self._respond_commands) yield gen.sleep(5)
[ "def", "_listen_commands", "(", "self", ")", ":", "self", ".", "_last_update", "=", "None", "update_body", "=", "{", "'timeout'", ":", "2", "}", "while", "True", ":", "latest", "=", "self", ".", "_last_update", "# increase offset to filter out older updates", "u...
Monitor new updates and send them further to self._respond_commands, where bot actions are decided.
[ "Monitor", "new", "updates", "and", "send", "them", "further", "to", "self", ".", "_respond_commands", "where", "bot", "actions", "are", "decided", "." ]
c1f071e9f557693bc90f6acbc314994985dc3b77
https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/handlers/telegram.py#L70-L85
27,152
klen/graphite-beacon
graphite_beacon/handlers/telegram.py
TelegramHandler._respond_commands
def _respond_commands(self, update_response): """Extract commands to bot from update and act accordingly. For description of commands, see HELP_MESSAGE variable on top of this module. """ chatfile = self.chatfile chats = self.chats exc, upd = update_response.exception(), update_response.result().body if exc: LOGGER.error(str(exc)) if not upd: return data = get_data(upd, self.bot_ident) for update_id, chat_id, message_id, command in data: self._last_update = update_id chat_is_known = chat_id in chats chats_changed = False reply_text = None if command == '/activate': if chat_is_known: reply_text = 'This chat is already activated.' else: LOGGER.debug( 'Adding chat [%s] to notify list.', chat_id) reply_text = 'Activated.' chats.add(chat_id) chats_changed = True elif command == '/deactivate': if chat_is_known: LOGGER.debug( 'Deleting chat [%s] from notify list.', chat_id) reply_text = 'Deactivated.' chats.remove(chat_id) chats_changed = True if chats_changed and chatfile: write_to_file(chats, chatfile) elif command == '/help': reply_text = HELP_MESSAGE else: LOGGER.warning('Could not parse command: ' 'bot ident is wrong or missing') if reply_text: yield self.client.send_message({ 'chat_id': chat_id, 'reply_to_message_id': message_id, 'text': reply_text, 'parse_mode': 'Markdown', })
python
def _respond_commands(self, update_response): chatfile = self.chatfile chats = self.chats exc, upd = update_response.exception(), update_response.result().body if exc: LOGGER.error(str(exc)) if not upd: return data = get_data(upd, self.bot_ident) for update_id, chat_id, message_id, command in data: self._last_update = update_id chat_is_known = chat_id in chats chats_changed = False reply_text = None if command == '/activate': if chat_is_known: reply_text = 'This chat is already activated.' else: LOGGER.debug( 'Adding chat [%s] to notify list.', chat_id) reply_text = 'Activated.' chats.add(chat_id) chats_changed = True elif command == '/deactivate': if chat_is_known: LOGGER.debug( 'Deleting chat [%s] from notify list.', chat_id) reply_text = 'Deactivated.' chats.remove(chat_id) chats_changed = True if chats_changed and chatfile: write_to_file(chats, chatfile) elif command == '/help': reply_text = HELP_MESSAGE else: LOGGER.warning('Could not parse command: ' 'bot ident is wrong or missing') if reply_text: yield self.client.send_message({ 'chat_id': chat_id, 'reply_to_message_id': message_id, 'text': reply_text, 'parse_mode': 'Markdown', })
[ "def", "_respond_commands", "(", "self", ",", "update_response", ")", ":", "chatfile", "=", "self", ".", "chatfile", "chats", "=", "self", ".", "chats", "exc", ",", "upd", "=", "update_response", ".", "exception", "(", ")", ",", "update_response", ".", "re...
Extract commands to bot from update and act accordingly. For description of commands, see HELP_MESSAGE variable on top of this module.
[ "Extract", "commands", "to", "bot", "from", "update", "and", "act", "accordingly", ".", "For", "description", "of", "commands", "see", "HELP_MESSAGE", "variable", "on", "top", "of", "this", "module", "." ]
c1f071e9f557693bc90f6acbc314994985dc3b77
https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/handlers/telegram.py#L88-L144
27,153
klen/graphite-beacon
graphite_beacon/handlers/telegram.py
TelegramHandler.notify
def notify(self, level, *args, **kwargs): """Sends alerts to telegram chats. This method is called from top level module. Do not rename it. """ LOGGER.debug('Handler (%s) %s', self.name, level) notify_text = self.get_message(level, *args, **kwargs) for chat in self.chats.copy(): data = {"chat_id": chat, "text": notify_text} yield self.client.send_message(data)
python
def notify(self, level, *args, **kwargs): LOGGER.debug('Handler (%s) %s', self.name, level) notify_text = self.get_message(level, *args, **kwargs) for chat in self.chats.copy(): data = {"chat_id": chat, "text": notify_text} yield self.client.send_message(data)
[ "def", "notify", "(", "self", ",", "level", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "LOGGER", ".", "debug", "(", "'Handler (%s) %s'", ",", "self", ".", "name", ",", "level", ")", "notify_text", "=", "self", ".", "get_message", "(", "leve...
Sends alerts to telegram chats. This method is called from top level module. Do not rename it.
[ "Sends", "alerts", "to", "telegram", "chats", ".", "This", "method", "is", "called", "from", "top", "level", "module", ".", "Do", "not", "rename", "it", "." ]
c1f071e9f557693bc90f6acbc314994985dc3b77
https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/handlers/telegram.py#L147-L158
27,154
klen/graphite-beacon
graphite_beacon/handlers/telegram.py
TelegramHandler.get_message
def get_message(self, level, alert, value, **kwargs): """Standart alert message. Same format across all graphite-beacon handlers. """ target, ntype = kwargs.get('target'), kwargs.get('ntype') msg_type = 'telegram' if ntype == 'graphite' else 'short' tmpl = TEMPLATES[ntype][msg_type] generated = tmpl.generate( level=level, reactor=self.reactor, alert=alert, value=value, target=target,) return generated.decode().strip()
python
def get_message(self, level, alert, value, **kwargs): target, ntype = kwargs.get('target'), kwargs.get('ntype') msg_type = 'telegram' if ntype == 'graphite' else 'short' tmpl = TEMPLATES[ntype][msg_type] generated = tmpl.generate( level=level, reactor=self.reactor, alert=alert, value=value, target=target,) return generated.decode().strip()
[ "def", "get_message", "(", "self", ",", "level", ",", "alert", ",", "value", ",", "*", "*", "kwargs", ")", ":", "target", ",", "ntype", "=", "kwargs", ".", "get", "(", "'target'", ")", ",", "kwargs", ".", "get", "(", "'ntype'", ")", "msg_type", "="...
Standart alert message. Same format across all graphite-beacon handlers.
[ "Standart", "alert", "message", ".", "Same", "format", "across", "all", "graphite", "-", "beacon", "handlers", "." ]
c1f071e9f557693bc90f6acbc314994985dc3b77
https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/handlers/telegram.py#L160-L171
27,155
klen/graphite-beacon
graphite_beacon/handlers/telegram.py
CustomClient.fetchmaker
def fetchmaker(self, telegram_api_method): """Receives api method as string and returns wrapper around AsyncHTTPClient's fetch method """ fetch = self.client.fetch request = self.url(telegram_api_method) def _fetcher(body, method='POST', headers=None): """Uses fetch method of tornado http client.""" body = json.dumps(body) if not headers: headers = {} headers.update({'Content-Type': 'application/json'}) return fetch( request=request, body=body, method=method, headers=headers) return _fetcher
python
def fetchmaker(self, telegram_api_method): fetch = self.client.fetch request = self.url(telegram_api_method) def _fetcher(body, method='POST', headers=None): """Uses fetch method of tornado http client.""" body = json.dumps(body) if not headers: headers = {} headers.update({'Content-Type': 'application/json'}) return fetch( request=request, body=body, method=method, headers=headers) return _fetcher
[ "def", "fetchmaker", "(", "self", ",", "telegram_api_method", ")", ":", "fetch", "=", "self", ".", "client", ".", "fetch", "request", "=", "self", ".", "url", "(", "telegram_api_method", ")", "def", "_fetcher", "(", "body", ",", "method", "=", "'POST'", ...
Receives api method as string and returns wrapper around AsyncHTTPClient's fetch method
[ "Receives", "api", "method", "as", "string", "and", "returns", "wrapper", "around", "AsyncHTTPClient", "s", "fetch", "method" ]
c1f071e9f557693bc90f6acbc314994985dc3b77
https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/handlers/telegram.py#L259-L275
27,156
klen/graphite-beacon
graphite_beacon/units.py
TimeUnit._normalize_value_ms
def _normalize_value_ms(cls, value): """Normalize a value in ms to the largest unit possible without decimal places. Note that this ignores fractions of a second and always returns a value _at least_ in seconds. :return: the normalized value and unit name :rtype: Tuple[Union[int, float], str] """ value = round(value / 1000) * 1000 # Ignore fractions of second sorted_units = sorted(cls.UNITS_IN_MILLISECONDS.items(), key=lambda x: x[1], reverse=True) for unit, unit_in_ms in sorted_units: unit_value = value / unit_in_ms if unit_value.is_integer(): return int(unit_value), unit return value, MILLISECOND
python
def _normalize_value_ms(cls, value): value = round(value / 1000) * 1000 # Ignore fractions of second sorted_units = sorted(cls.UNITS_IN_MILLISECONDS.items(), key=lambda x: x[1], reverse=True) for unit, unit_in_ms in sorted_units: unit_value = value / unit_in_ms if unit_value.is_integer(): return int(unit_value), unit return value, MILLISECOND
[ "def", "_normalize_value_ms", "(", "cls", ",", "value", ")", ":", "value", "=", "round", "(", "value", "/", "1000", ")", "*", "1000", "# Ignore fractions of second", "sorted_units", "=", "sorted", "(", "cls", ".", "UNITS_IN_MILLISECONDS", ".", "items", "(", ...
Normalize a value in ms to the largest unit possible without decimal places. Note that this ignores fractions of a second and always returns a value _at least_ in seconds. :return: the normalized value and unit name :rtype: Tuple[Union[int, float], str]
[ "Normalize", "a", "value", "in", "ms", "to", "the", "largest", "unit", "possible", "without", "decimal", "places", "." ]
c1f071e9f557693bc90f6acbc314994985dc3b77
https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/units.py#L101-L118
27,157
klen/graphite-beacon
graphite_beacon/units.py
TimeUnit._normalize_unit
def _normalize_unit(cls, unit): """Resolve a unit to its real name if it's an alias. :param unit str: the unit to normalize :return: the normalized unit, or None one isn't found :rtype: Union[None, str] """ if unit in cls.UNITS_IN_SECONDS: return unit return cls.UNIT_ALIASES_REVERSE.get(unit, None)
python
def _normalize_unit(cls, unit): if unit in cls.UNITS_IN_SECONDS: return unit return cls.UNIT_ALIASES_REVERSE.get(unit, None)
[ "def", "_normalize_unit", "(", "cls", ",", "unit", ")", ":", "if", "unit", "in", "cls", ".", "UNITS_IN_SECONDS", ":", "return", "unit", "return", "cls", ".", "UNIT_ALIASES_REVERSE", ".", "get", "(", "unit", ",", "None", ")" ]
Resolve a unit to its real name if it's an alias. :param unit str: the unit to normalize :return: the normalized unit, or None one isn't found :rtype: Union[None, str]
[ "Resolve", "a", "unit", "to", "its", "real", "name", "if", "it", "s", "an", "alias", "." ]
c1f071e9f557693bc90f6acbc314994985dc3b77
https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/units.py#L121-L130
27,158
klen/graphite-beacon
graphite_beacon/units.py
TimeUnit.convert
def convert(cls, value, from_unit, to_unit): """Convert a value from one time unit to another. :return: the numeric value converted to the desired unit :rtype: float """ value_ms = value * cls.UNITS_IN_MILLISECONDS[from_unit] return value_ms / cls.UNITS_IN_MILLISECONDS[to_unit]
python
def convert(cls, value, from_unit, to_unit): value_ms = value * cls.UNITS_IN_MILLISECONDS[from_unit] return value_ms / cls.UNITS_IN_MILLISECONDS[to_unit]
[ "def", "convert", "(", "cls", ",", "value", ",", "from_unit", ",", "to_unit", ")", ":", "value_ms", "=", "value", "*", "cls", ".", "UNITS_IN_MILLISECONDS", "[", "from_unit", "]", "return", "value_ms", "/", "cls", ".", "UNITS_IN_MILLISECONDS", "[", "to_unit",...
Convert a value from one time unit to another. :return: the numeric value converted to the desired unit :rtype: float
[ "Convert", "a", "value", "from", "one", "time", "unit", "to", "another", "." ]
c1f071e9f557693bc90f6acbc314994985dc3b77
https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/units.py#L148-L155
27,159
klen/graphite-beacon
graphite_beacon/handlers/smtp.py
SMTPHandler.init_handler
def init_handler(self): """ Check self options. """ assert self.options.get('host') and self.options.get('port'), "Invalid options" assert self.options.get('to'), 'Recipients list is empty. SMTP disabled.' if not isinstance(self.options['to'], (list, tuple)): self.options['to'] = [self.options['to']]
python
def init_handler(self): assert self.options.get('host') and self.options.get('port'), "Invalid options" assert self.options.get('to'), 'Recipients list is empty. SMTP disabled.' if not isinstance(self.options['to'], (list, tuple)): self.options['to'] = [self.options['to']]
[ "def", "init_handler", "(", "self", ")", ":", "assert", "self", ".", "options", ".", "get", "(", "'host'", ")", "and", "self", ".", "options", ".", "get", "(", "'port'", ")", ",", "\"Invalid options\"", "assert", "self", ".", "options", ".", "get", "("...
Check self options.
[ "Check", "self", "options", "." ]
c1f071e9f557693bc90f6acbc314994985dc3b77
https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/handlers/smtp.py#L28-L33
27,160
alexprengere/FormalSystems
formalsystems/formalsystems.py
iterator_mix
def iterator_mix(*iterators): """ Iterating over list of iterators. Bit like zip, but zip stops after the shortest iterator is empty, abd here we go one until all iterators are empty. """ while True: one_left = False for it in iterators: try: yield it.next() except StopIteration: pass else: one_left = True if not one_left: break
python
def iterator_mix(*iterators): while True: one_left = False for it in iterators: try: yield it.next() except StopIteration: pass else: one_left = True if not one_left: break
[ "def", "iterator_mix", "(", "*", "iterators", ")", ":", "while", "True", ":", "one_left", "=", "False", "for", "it", "in", "iterators", ":", "try", ":", "yield", "it", ".", "next", "(", ")", "except", "StopIteration", ":", "pass", "else", ":", "one_lef...
Iterating over list of iterators. Bit like zip, but zip stops after the shortest iterator is empty, abd here we go one until all iterators are empty.
[ "Iterating", "over", "list", "of", "iterators", ".", "Bit", "like", "zip", "but", "zip", "stops", "after", "the", "shortest", "iterator", "is", "empty", "abd", "here", "we", "go", "one", "until", "all", "iterators", "are", "empty", "." ]
e46d9cc6f8dc076e9dc86f6f8511fc6f3aa95f6e
https://github.com/alexprengere/FormalSystems/blob/e46d9cc6f8dc076e9dc86f6f8511fc6f3aa95f6e/formalsystems/formalsystems.py#L309-L328
27,161
grantmcconnaughey/Lintly
lintly/parsers.py
BaseLintParser._normalize_path
def _normalize_path(self, path): """ Normalizes a file path so that it returns a path relative to the root repo directory. """ norm_path = os.path.normpath(path) return os.path.relpath(norm_path, start=self._get_working_dir())
python
def _normalize_path(self, path): norm_path = os.path.normpath(path) return os.path.relpath(norm_path, start=self._get_working_dir())
[ "def", "_normalize_path", "(", "self", ",", "path", ")", ":", "norm_path", "=", "os", ".", "path", ".", "normpath", "(", "path", ")", "return", "os", ".", "path", ".", "relpath", "(", "norm_path", ",", "start", "=", "self", ".", "_get_working_dir", "("...
Normalizes a file path so that it returns a path relative to the root repo directory.
[ "Normalizes", "a", "file", "path", "so", "that", "it", "returns", "a", "path", "relative", "to", "the", "root", "repo", "directory", "." ]
73c1ee36740ac5bb2a32d3f24fca2a27f4d4e466
https://github.com/grantmcconnaughey/Lintly/blob/73c1ee36740ac5bb2a32d3f24fca2a27f4d4e466/lintly/parsers.py#L21-L26
27,162
grantmcconnaughey/Lintly
lintly/backends/github.py
translate_github_exception
def translate_github_exception(func): """ Decorator to catch GitHub-specific exceptions and raise them as GitClientError exceptions. """ @functools.wraps(func) def _wrapper(*args, **kwargs): try: return func(*args, **kwargs) except UnknownObjectException as e: logger.exception('GitHub API 404 Exception') raise NotFoundError(str(e)) except GithubException as e: logger.exception('GitHub API Exception') raise GitClientError(str(e)) return _wrapper
python
def translate_github_exception(func): @functools.wraps(func) def _wrapper(*args, **kwargs): try: return func(*args, **kwargs) except UnknownObjectException as e: logger.exception('GitHub API 404 Exception') raise NotFoundError(str(e)) except GithubException as e: logger.exception('GitHub API Exception') raise GitClientError(str(e)) return _wrapper
[ "def", "translate_github_exception", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "_wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "func", "(", "*", "args", ",", "*", "*", "kw...
Decorator to catch GitHub-specific exceptions and raise them as GitClientError exceptions.
[ "Decorator", "to", "catch", "GitHub", "-", "specific", "exceptions", "and", "raise", "them", "as", "GitClientError", "exceptions", "." ]
73c1ee36740ac5bb2a32d3f24fca2a27f4d4e466
https://github.com/grantmcconnaughey/Lintly/blob/73c1ee36740ac5bb2a32d3f24fca2a27f4d4e466/lintly/backends/github.py#L29-L45
27,163
grantmcconnaughey/Lintly
lintly/builds.py
LintlyBuild.violations
def violations(self): """ Returns either the diff violations or all violations depending on configuration. """ return self._all_violations if self.config.fail_on == FAIL_ON_ANY else self._diff_violations
python
def violations(self): return self._all_violations if self.config.fail_on == FAIL_ON_ANY else self._diff_violations
[ "def", "violations", "(", "self", ")", ":", "return", "self", ".", "_all_violations", "if", "self", ".", "config", ".", "fail_on", "==", "FAIL_ON_ANY", "else", "self", ".", "_diff_violations" ]
Returns either the diff violations or all violations depending on configuration.
[ "Returns", "either", "the", "diff", "violations", "or", "all", "violations", "depending", "on", "configuration", "." ]
73c1ee36740ac5bb2a32d3f24fca2a27f4d4e466
https://github.com/grantmcconnaughey/Lintly/blob/73c1ee36740ac5bb2a32d3f24fca2a27f4d4e466/lintly/builds.py#L35-L39
27,164
grantmcconnaughey/Lintly
lintly/builds.py
LintlyBuild.execute
def execute(self): """ Executes a new build on a project. """ if not self.config.pr: raise NotPullRequestException logger.debug('Using the following configuration:') for name, value in self.config.as_dict().items(): logger.debug(' - {}={}'.format(name, repr(value))) logger.info('Running Lintly against PR #{} for repo {}'.format(self.config.pr, self.project)) parser = PARSERS.get(self.config.format) self._all_violations = parser.parse_violations(self.linter_output) logger.info('Lintly found violations in {} files'.format(len(self._all_violations))) diff = self.get_pr_diff() patch = self.get_pr_patch(diff) self._diff_violations = self.find_diff_violations(patch) logger.info('Lintly found diff violations in {} files'.format(len(self._diff_violations))) self.post_pr_comment(patch) self.post_commit_status()
python
def execute(self): if not self.config.pr: raise NotPullRequestException logger.debug('Using the following configuration:') for name, value in self.config.as_dict().items(): logger.debug(' - {}={}'.format(name, repr(value))) logger.info('Running Lintly against PR #{} for repo {}'.format(self.config.pr, self.project)) parser = PARSERS.get(self.config.format) self._all_violations = parser.parse_violations(self.linter_output) logger.info('Lintly found violations in {} files'.format(len(self._all_violations))) diff = self.get_pr_diff() patch = self.get_pr_patch(diff) self._diff_violations = self.find_diff_violations(patch) logger.info('Lintly found diff violations in {} files'.format(len(self._diff_violations))) self.post_pr_comment(patch) self.post_commit_status()
[ "def", "execute", "(", "self", ")", ":", "if", "not", "self", ".", "config", ".", "pr", ":", "raise", "NotPullRequestException", "logger", ".", "debug", "(", "'Using the following configuration:'", ")", "for", "name", ",", "value", "in", "self", ".", "config...
Executes a new build on a project.
[ "Executes", "a", "new", "build", "on", "a", "project", "." ]
73c1ee36740ac5bb2a32d3f24fca2a27f4d4e466
https://github.com/grantmcconnaughey/Lintly/blob/73c1ee36740ac5bb2a32d3f24fca2a27f4d4e466/lintly/builds.py#L51-L74
27,165
grantmcconnaughey/Lintly
lintly/builds.py
LintlyBuild.find_diff_violations
def find_diff_violations(self, patch): """ Uses the diff for this build to find changed lines that also have violations. """ violations = collections.defaultdict(list) for line in patch.changed_lines: file_violations = self._all_violations.get(line['file_name']) if not file_violations: continue line_violations = [v for v in file_violations if v.line == line['line_number']] for v in line_violations: violations[line['file_name']].append(v) return violations
python
def find_diff_violations(self, patch): violations = collections.defaultdict(list) for line in patch.changed_lines: file_violations = self._all_violations.get(line['file_name']) if not file_violations: continue line_violations = [v for v in file_violations if v.line == line['line_number']] for v in line_violations: violations[line['file_name']].append(v) return violations
[ "def", "find_diff_violations", "(", "self", ",", "patch", ")", ":", "violations", "=", "collections", ".", "defaultdict", "(", "list", ")", "for", "line", "in", "patch", ".", "changed_lines", ":", "file_violations", "=", "self", ".", "_all_violations", ".", ...
Uses the diff for this build to find changed lines that also have violations.
[ "Uses", "the", "diff", "for", "this", "build", "to", "find", "changed", "lines", "that", "also", "have", "violations", "." ]
73c1ee36740ac5bb2a32d3f24fca2a27f4d4e466
https://github.com/grantmcconnaughey/Lintly/blob/73c1ee36740ac5bb2a32d3f24fca2a27f4d4e466/lintly/builds.py#L82-L97
27,166
grantmcconnaughey/Lintly
lintly/builds.py
LintlyBuild.post_pr_comment
def post_pr_comment(self, patch): """ Posts a comment to the GitHub PR if the diff results have issues. """ if self.has_violations: post_pr_comment = True # Attempt to post a PR review. If posting the PR review fails because the bot account # does not have permission to review the PR then simply revert to posting a regular PR # comment. try: logger.info('Deleting old PR review comments') self.git_client.delete_pull_request_review_comments(self.config.pr) logger.info('Creating PR review') self.git_client.create_pull_request_review(self.config.pr, patch, self._diff_violations) post_pr_comment = False except GitClientError as e: # TODO: Make `create_pull_request_review` raise an `UnauthorizedError` # so that we don't have to check for a specific message in the exception if 'Viewer does not have permission to review this pull request' in str(e): logger.warning("Could not post PR review (the account didn't have permission)") pass else: raise if post_pr_comment: logger.info('Deleting old PR comment') self.git_client.delete_pull_request_comments(self.config.pr) logger.info('Creating PR comment') comment = build_pr_comment(self.config, self.violations) self.git_client.create_pull_request_comment(self.config.pr, comment)
python
def post_pr_comment(self, patch): if self.has_violations: post_pr_comment = True # Attempt to post a PR review. If posting the PR review fails because the bot account # does not have permission to review the PR then simply revert to posting a regular PR # comment. try: logger.info('Deleting old PR review comments') self.git_client.delete_pull_request_review_comments(self.config.pr) logger.info('Creating PR review') self.git_client.create_pull_request_review(self.config.pr, patch, self._diff_violations) post_pr_comment = False except GitClientError as e: # TODO: Make `create_pull_request_review` raise an `UnauthorizedError` # so that we don't have to check for a specific message in the exception if 'Viewer does not have permission to review this pull request' in str(e): logger.warning("Could not post PR review (the account didn't have permission)") pass else: raise if post_pr_comment: logger.info('Deleting old PR comment') self.git_client.delete_pull_request_comments(self.config.pr) logger.info('Creating PR comment') comment = build_pr_comment(self.config, self.violations) self.git_client.create_pull_request_comment(self.config.pr, comment)
[ "def", "post_pr_comment", "(", "self", ",", "patch", ")", ":", "if", "self", ".", "has_violations", ":", "post_pr_comment", "=", "True", "# Attempt to post a PR review. If posting the PR review fails because the bot account", "# does not have permission to review the PR then simply...
Posts a comment to the GitHub PR if the diff results have issues.
[ "Posts", "a", "comment", "to", "the", "GitHub", "PR", "if", "the", "diff", "results", "have", "issues", "." ]
73c1ee36740ac5bb2a32d3f24fca2a27f4d4e466
https://github.com/grantmcconnaughey/Lintly/blob/73c1ee36740ac5bb2a32d3f24fca2a27f4d4e466/lintly/builds.py#L99-L131
27,167
grantmcconnaughey/Lintly
lintly/builds.py
LintlyBuild.post_commit_status
def post_commit_status(self): """ Posts results to a commit status in GitHub if this build is for a pull request. """ if self.violations: plural = '' if self.introduced_issues_count == 1 else 's' description = 'Pull Request introduced {} linting violation{}'.format( self.introduced_issues_count, plural) self._post_status('failure', description) else: self._post_status('success', 'Linting detected no new issues.')
python
def post_commit_status(self): if self.violations: plural = '' if self.introduced_issues_count == 1 else 's' description = 'Pull Request introduced {} linting violation{}'.format( self.introduced_issues_count, plural) self._post_status('failure', description) else: self._post_status('success', 'Linting detected no new issues.')
[ "def", "post_commit_status", "(", "self", ")", ":", "if", "self", ".", "violations", ":", "plural", "=", "''", "if", "self", ".", "introduced_issues_count", "==", "1", "else", "'s'", "description", "=", "'Pull Request introduced {} linting violation{}'", ".", "for...
Posts results to a commit status in GitHub if this build is for a pull request.
[ "Posts", "results", "to", "a", "commit", "status", "in", "GitHub", "if", "this", "build", "is", "for", "a", "pull", "request", "." ]
73c1ee36740ac5bb2a32d3f24fca2a27f4d4e466
https://github.com/grantmcconnaughey/Lintly/blob/73c1ee36740ac5bb2a32d3f24fca2a27f4d4e466/lintly/builds.py#L133-L143
27,168
alexprengere/FormalSystems
formalsystems/leplparsing.py
reg_to_lex
def reg_to_lex(conditions, wildcards): """Transform a regular expression into a LEPL object. Replace the wildcards in the conditions by LEPL elements, like xM will be replaced by Any() & 'M'. In case of multiple same wildcards (like xMx), aliases are created to allow the regexp to compile, like Any() > 'x_0' & 'M' & Any() > 'x_1', and we chech that the matched values for all aliases like x_0, x_1 are the same. """ aliases = defaultdict(set) n_conds = [] # All conditions for i, _ in enumerate(conditions): n_cond = [] for char in conditions[i]: if char in wildcards: alias = '%s_%s' % (char, len(aliases[char])) aliases[char].add(alias) n_cond.append(make_token(alias, reg=wildcards[char])) else: n_cond.append(~Literal(char)) n_cond.append(Eos()) n_conds.append(reduce(operator.and_, n_cond) > make_dict) return tuple(n_conds), aliases
python
def reg_to_lex(conditions, wildcards): aliases = defaultdict(set) n_conds = [] # All conditions for i, _ in enumerate(conditions): n_cond = [] for char in conditions[i]: if char in wildcards: alias = '%s_%s' % (char, len(aliases[char])) aliases[char].add(alias) n_cond.append(make_token(alias, reg=wildcards[char])) else: n_cond.append(~Literal(char)) n_cond.append(Eos()) n_conds.append(reduce(operator.and_, n_cond) > make_dict) return tuple(n_conds), aliases
[ "def", "reg_to_lex", "(", "conditions", ",", "wildcards", ")", ":", "aliases", "=", "defaultdict", "(", "set", ")", "n_conds", "=", "[", "]", "# All conditions", "for", "i", ",", "_", "in", "enumerate", "(", "conditions", ")", ":", "n_cond", "=", "[", ...
Transform a regular expression into a LEPL object. Replace the wildcards in the conditions by LEPL elements, like xM will be replaced by Any() & 'M'. In case of multiple same wildcards (like xMx), aliases are created to allow the regexp to compile, like Any() > 'x_0' & 'M' & Any() > 'x_1', and we chech that the matched values for all aliases like x_0, x_1 are the same.
[ "Transform", "a", "regular", "expression", "into", "a", "LEPL", "object", "." ]
e46d9cc6f8dc076e9dc86f6f8511fc6f3aa95f6e
https://github.com/alexprengere/FormalSystems/blob/e46d9cc6f8dc076e9dc86f6f8511fc6f3aa95f6e/formalsystems/leplparsing.py#L11-L39
27,169
grantmcconnaughey/Lintly
lintly/cli.py
main
def main(**options): """Slurp up linter output and send it to a GitHub PR review.""" configure_logging(log_all=options.get('log')) stdin_stream = click.get_text_stream('stdin') stdin_text = stdin_stream.read() click.echo(stdin_text) ci = find_ci_provider() config = Config(options, ci=ci) build = LintlyBuild(config, stdin_text) try: build.execute() except NotPullRequestException: logger.info('Not a PR. Lintly is exiting.') sys.exit(0) # Exit with the number of files that have violations sys.exit(len(build.violations))
python
def main(**options): configure_logging(log_all=options.get('log')) stdin_stream = click.get_text_stream('stdin') stdin_text = stdin_stream.read() click.echo(stdin_text) ci = find_ci_provider() config = Config(options, ci=ci) build = LintlyBuild(config, stdin_text) try: build.execute() except NotPullRequestException: logger.info('Not a PR. Lintly is exiting.') sys.exit(0) # Exit with the number of files that have violations sys.exit(len(build.violations))
[ "def", "main", "(", "*", "*", "options", ")", ":", "configure_logging", "(", "log_all", "=", "options", ".", "get", "(", "'log'", ")", ")", "stdin_stream", "=", "click", ".", "get_text_stream", "(", "'stdin'", ")", "stdin_text", "=", "stdin_stream", ".", ...
Slurp up linter output and send it to a GitHub PR review.
[ "Slurp", "up", "linter", "output", "and", "send", "it", "to", "a", "GitHub", "PR", "review", "." ]
73c1ee36740ac5bb2a32d3f24fca2a27f4d4e466
https://github.com/grantmcconnaughey/Lintly/blob/73c1ee36740ac5bb2a32d3f24fca2a27f4d4e466/lintly/cli.py#L53-L73
27,170
grantmcconnaughey/Lintly
lintly/backends/gitlab.py
translate_gitlab_exception
def translate_gitlab_exception(func): """ Decorator to catch GitLab-specific exceptions and raise them as GitClientError exceptions. """ @functools.wraps(func) def _wrapper(*args, **kwargs): try: return func(*args, **kwargs) except gitlab.GitlabError as e: status_to_exception = { 401: UnauthorizedError, 404: NotFoundError, } exc_class = status_to_exception.get(e.response_code, GitClientError) raise exc_class(str(e), status_code=e.response_code) return _wrapper
python
def translate_gitlab_exception(func): @functools.wraps(func) def _wrapper(*args, **kwargs): try: return func(*args, **kwargs) except gitlab.GitlabError as e: status_to_exception = { 401: UnauthorizedError, 404: NotFoundError, } exc_class = status_to_exception.get(e.response_code, GitClientError) raise exc_class(str(e), status_code=e.response_code) return _wrapper
[ "def", "translate_gitlab_exception", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "_wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "func", "(", "*", "args", ",", "*", "*", "kw...
Decorator to catch GitLab-specific exceptions and raise them as GitClientError exceptions.
[ "Decorator", "to", "catch", "GitLab", "-", "specific", "exceptions", "and", "raise", "them", "as", "GitClientError", "exceptions", "." ]
73c1ee36740ac5bb2a32d3f24fca2a27f4d4e466
https://github.com/grantmcconnaughey/Lintly/blob/73c1ee36740ac5bb2a32d3f24fca2a27f4d4e466/lintly/backends/gitlab.py#L29-L47
27,171
ARMmbed/icetea
icetea_lib/Plugin/plugins/LocalAllocator/LocalAllocator.py
init_process_dut
def init_process_dut(contextlist, conf, index, args): """ Initialize process type Dut as DutProcess or DutConsole. """ if "subtype" in conf and conf["subtype"]: if conf["subtype"] != "console": msg = "Unrecognized process subtype: {}" contextlist.logger.error(msg.format(conf["subtype"])) raise ResourceInitError("Unrecognized process subtype: {}") # This is a specialized 'console' process config = None if "application" in conf: config = conf["application"] contextlist.logger.debug("Starting a remote console") dut = DutConsole(name="D%d" % index, conf=config, params=args) dut.index = index else: binary = conf["application"]['bin'] app_config = conf["application"] init_cli_cmds = app_config.get("init_cli_cmds", None) post_cli_cmds = app_config.get("post_cli_cmds", None) contextlist.logger.debug("Starting process '%s'" % binary) dut = DutProcess(name="D%d" % index, config=conf, params=args) dut.index = index dut.command = binary if args.valgrind: dut.use_valgrind(args.valgrind_tool, not args.valgrind_text, args.valgrind_console, args.valgrind_track_origins, args.valgrind_extra_params) if args.gdb == index: dut.use_gdb() contextlist.logger.info("GDB is activated for node %i" % index) if args.gdbs == index: dut.use_gdbs(True, args.gdbs_port) contextlist.logger.info("GDBserver is activated for node %i" % index) if args.vgdb == index: dut.use_vgdb() contextlist.logger.info("VGDB is activated for node %i" % index) if args.nobuf: dut.no_std_buf() if init_cli_cmds is not None: dut.set_init_cli_cmds(init_cli_cmds) if post_cli_cmds is not None: dut.set_post_cli_cmds(post_cli_cmds) contextlist.duts.append(dut) contextlist.dutinformations.append(dut.get_info())
python
def init_process_dut(contextlist, conf, index, args): if "subtype" in conf and conf["subtype"]: if conf["subtype"] != "console": msg = "Unrecognized process subtype: {}" contextlist.logger.error(msg.format(conf["subtype"])) raise ResourceInitError("Unrecognized process subtype: {}") # This is a specialized 'console' process config = None if "application" in conf: config = conf["application"] contextlist.logger.debug("Starting a remote console") dut = DutConsole(name="D%d" % index, conf=config, params=args) dut.index = index else: binary = conf["application"]['bin'] app_config = conf["application"] init_cli_cmds = app_config.get("init_cli_cmds", None) post_cli_cmds = app_config.get("post_cli_cmds", None) contextlist.logger.debug("Starting process '%s'" % binary) dut = DutProcess(name="D%d" % index, config=conf, params=args) dut.index = index dut.command = binary if args.valgrind: dut.use_valgrind(args.valgrind_tool, not args.valgrind_text, args.valgrind_console, args.valgrind_track_origins, args.valgrind_extra_params) if args.gdb == index: dut.use_gdb() contextlist.logger.info("GDB is activated for node %i" % index) if args.gdbs == index: dut.use_gdbs(True, args.gdbs_port) contextlist.logger.info("GDBserver is activated for node %i" % index) if args.vgdb == index: dut.use_vgdb() contextlist.logger.info("VGDB is activated for node %i" % index) if args.nobuf: dut.no_std_buf() if init_cli_cmds is not None: dut.set_init_cli_cmds(init_cli_cmds) if post_cli_cmds is not None: dut.set_post_cli_cmds(post_cli_cmds) contextlist.duts.append(dut) contextlist.dutinformations.append(dut.get_info())
[ "def", "init_process_dut", "(", "contextlist", ",", "conf", ",", "index", ",", "args", ")", ":", "if", "\"subtype\"", "in", "conf", "and", "conf", "[", "\"subtype\"", "]", ":", "if", "conf", "[", "\"subtype\"", "]", "!=", "\"console\"", ":", "msg", "=", ...
Initialize process type Dut as DutProcess or DutConsole.
[ "Initialize", "process", "type", "Dut", "as", "DutProcess", "or", "DutConsole", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/plugins/LocalAllocator/LocalAllocator.py#L140-L189
27,172
ARMmbed/icetea
icetea_lib/Plugin/plugins/LocalAllocator/LocalAllocator.py
LocalAllocator.allocate
def allocate(self, dut_configuration_list, args=None): """ Allocates resources from available local devices. :param dut_configuration_list: List of ResourceRequirements objects :param args: Not used :return: AllocationContextList with allocated resources """ dut_config_list = dut_configuration_list.get_dut_configuration() # if we need one or more local hardware duts let's search attached # devices using DutDetection if not isinstance(dut_config_list, list): raise AllocationError("Invalid dut configuration format!") if next((item for item in dut_config_list if item.get("type") == "hardware"), False): self._available_devices = DutDetection().get_available_devices() if len(self._available_devices) < len(dut_config_list): raise AllocationError("Required amount of devices not available.") # Enumerate all required DUT's try: for dut_config in dut_config_list: if not self.can_allocate(dut_config.get_requirements()): raise AllocationError("Resource type is not supported") self._allocate(dut_config) except AllocationError: # Locally allocated don't need to be released any way for # now, so just re-raise the error raise alloc_list = AllocationContextList() res_id = None for conf in dut_config_list: if conf.get("type") == "mbed": res_id = conf.get("allocated").get("target_id") context = AllocationContext(resource_id=res_id, alloc_data=conf) alloc_list.append(context) alloc_list.set_dut_init_function("serial", init_generic_serial_dut) alloc_list.set_dut_init_function("process", init_process_dut) alloc_list.set_dut_init_function("mbed", init_mbed_dut) return alloc_list
python
def allocate(self, dut_configuration_list, args=None): dut_config_list = dut_configuration_list.get_dut_configuration() # if we need one or more local hardware duts let's search attached # devices using DutDetection if not isinstance(dut_config_list, list): raise AllocationError("Invalid dut configuration format!") if next((item for item in dut_config_list if item.get("type") == "hardware"), False): self._available_devices = DutDetection().get_available_devices() if len(self._available_devices) < len(dut_config_list): raise AllocationError("Required amount of devices not available.") # Enumerate all required DUT's try: for dut_config in dut_config_list: if not self.can_allocate(dut_config.get_requirements()): raise AllocationError("Resource type is not supported") self._allocate(dut_config) except AllocationError: # Locally allocated don't need to be released any way for # now, so just re-raise the error raise alloc_list = AllocationContextList() res_id = None for conf in dut_config_list: if conf.get("type") == "mbed": res_id = conf.get("allocated").get("target_id") context = AllocationContext(resource_id=res_id, alloc_data=conf) alloc_list.append(context) alloc_list.set_dut_init_function("serial", init_generic_serial_dut) alloc_list.set_dut_init_function("process", init_process_dut) alloc_list.set_dut_init_function("mbed", init_mbed_dut) return alloc_list
[ "def", "allocate", "(", "self", ",", "dut_configuration_list", ",", "args", "=", "None", ")", ":", "dut_config_list", "=", "dut_configuration_list", ".", "get_dut_configuration", "(", ")", "# if we need one or more local hardware duts let's search attached", "# devices using ...
Allocates resources from available local devices. :param dut_configuration_list: List of ResourceRequirements objects :param args: Not used :return: AllocationContextList with allocated resources
[ "Allocates", "resources", "from", "available", "local", "devices", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/plugins/LocalAllocator/LocalAllocator.py#L225-L266
27,173
ARMmbed/icetea
icetea_lib/Plugin/plugins/LocalAllocator/LocalAllocator.py
LocalAllocator._allocate
def _allocate(self, dut_configuration): # pylint: disable=too-many-branches """ Internal allocation function. Allocates a single resource based on dut_configuration. :param dut_configuration: ResourceRequirements object which describes a required resource :return: True :raises: AllocationError if suitable resource was not found or if the platform was not allowed to be used. """ if dut_configuration["type"] == "hardware": dut_configuration.set("type", "mbed") if dut_configuration["type"] == "mbed": if not self._available_devices: raise AllocationError("No available devices to allocate from") dut_reqs = dut_configuration.get_requirements() platforms = None if 'allowed_platforms' not in dut_reqs else dut_reqs[ 'allowed_platforms'] platform_name = None if 'platform_name' not in dut_reqs else dut_reqs[ "platform_name"] if platform_name is None and platforms: platform_name = platforms[0] if platform_name and platforms: if platform_name not in platforms: raise AllocationError("Platform name not in allowed platforms.") # Enumerate through all available devices for dev in self._available_devices: if platform_name and dev["platform_name"] != platform_name: self.logger.debug("Skipping device %s because of mismatching platform. " "Required %s but device was %s", dev['target_id'], platform_name, dev['platform_name']) continue if dev['state'] == 'allocated': self.logger.debug("Skipping device %s because it was " "already allocated", dev['target_id']) continue if DutDetection.is_port_usable(dev['serial_port']): dev['state'] = "allocated" dut_reqs['allocated'] = dev self.logger.info("Allocated device %s", dev['target_id']) return True else: self.logger.info("Could not open serial port (%s) of " "allocated device %s", dev['serial_port'], dev['target_id']) # Didn't find a matching device to allocate so allocation failed raise AllocationError("No suitable local device available") elif dut_configuration["type"] == "serial": dut_reqs = dut_configuration.get_requirements() if not dut_reqs.get("serial_port"): raise AllocationError("Serial port not defined for requirement {}".format(dut_reqs)) if not DutDetection.is_port_usable(dut_reqs['serial_port']): raise AllocationError("Serial port {} not usable".format(dut_reqs['serial_port'])) # Successful allocation, return True return True
python
def _allocate(self, dut_configuration): # pylint: disable=too-many-branches if dut_configuration["type"] == "hardware": dut_configuration.set("type", "mbed") if dut_configuration["type"] == "mbed": if not self._available_devices: raise AllocationError("No available devices to allocate from") dut_reqs = dut_configuration.get_requirements() platforms = None if 'allowed_platforms' not in dut_reqs else dut_reqs[ 'allowed_platforms'] platform_name = None if 'platform_name' not in dut_reqs else dut_reqs[ "platform_name"] if platform_name is None and platforms: platform_name = platforms[0] if platform_name and platforms: if platform_name not in platforms: raise AllocationError("Platform name not in allowed platforms.") # Enumerate through all available devices for dev in self._available_devices: if platform_name and dev["platform_name"] != platform_name: self.logger.debug("Skipping device %s because of mismatching platform. " "Required %s but device was %s", dev['target_id'], platform_name, dev['platform_name']) continue if dev['state'] == 'allocated': self.logger.debug("Skipping device %s because it was " "already allocated", dev['target_id']) continue if DutDetection.is_port_usable(dev['serial_port']): dev['state'] = "allocated" dut_reqs['allocated'] = dev self.logger.info("Allocated device %s", dev['target_id']) return True else: self.logger.info("Could not open serial port (%s) of " "allocated device %s", dev['serial_port'], dev['target_id']) # Didn't find a matching device to allocate so allocation failed raise AllocationError("No suitable local device available") elif dut_configuration["type"] == "serial": dut_reqs = dut_configuration.get_requirements() if not dut_reqs.get("serial_port"): raise AllocationError("Serial port not defined for requirement {}".format(dut_reqs)) if not DutDetection.is_port_usable(dut_reqs['serial_port']): raise AllocationError("Serial port {} not usable".format(dut_reqs['serial_port'])) # Successful allocation, return True return True
[ "def", "_allocate", "(", "self", ",", "dut_configuration", ")", ":", "# pylint: disable=too-many-branches", "if", "dut_configuration", "[", "\"type\"", "]", "==", "\"hardware\"", ":", "dut_configuration", ".", "set", "(", "\"type\"", ",", "\"mbed\"", ")", "if", "d...
Internal allocation function. Allocates a single resource based on dut_configuration. :param dut_configuration: ResourceRequirements object which describes a required resource :return: True :raises: AllocationError if suitable resource was not found or if the platform was not allowed to be used.
[ "Internal", "allocation", "function", ".", "Allocates", "a", "single", "resource", "based", "on", "dut_configuration", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/plugins/LocalAllocator/LocalAllocator.py#L277-L331
27,174
ARMmbed/icetea
icetea_lib/Plugin/PluginManager.py
PluginManager.register_tc_plugins
def register_tc_plugins(self, plugin_name, plugin_class): """ Loads a plugin as a dictionary and attaches needed parts to correct areas for testing parts. :param plugin_name: Name of the plugins :param plugin_class: PluginBase :return: Nothing """ if plugin_name in self.registered_plugins: raise PluginException("Plugin {} already registered! Duplicate " "plugins?".format(plugin_name)) self.logger.debug("Registering plugin %s", plugin_name) plugin_class.init(bench=self.bench) if plugin_class.get_bench_api() is not None: register_func = self.plugin_types[PluginTypes.BENCH] register_func(plugin_name, plugin_class) if plugin_class.get_parsers() is not None: register_func = self.plugin_types[PluginTypes.PARSER] register_func(plugin_name, plugin_class) if plugin_class.get_external_services() is not None: register_func = self.plugin_types[PluginTypes.EXTSERVICE] register_func(plugin_name, plugin_class) self.registered_plugins.append(plugin_name)
python
def register_tc_plugins(self, plugin_name, plugin_class): if plugin_name in self.registered_plugins: raise PluginException("Plugin {} already registered! Duplicate " "plugins?".format(plugin_name)) self.logger.debug("Registering plugin %s", plugin_name) plugin_class.init(bench=self.bench) if plugin_class.get_bench_api() is not None: register_func = self.plugin_types[PluginTypes.BENCH] register_func(plugin_name, plugin_class) if plugin_class.get_parsers() is not None: register_func = self.plugin_types[PluginTypes.PARSER] register_func(plugin_name, plugin_class) if plugin_class.get_external_services() is not None: register_func = self.plugin_types[PluginTypes.EXTSERVICE] register_func(plugin_name, plugin_class) self.registered_plugins.append(plugin_name)
[ "def", "register_tc_plugins", "(", "self", ",", "plugin_name", ",", "plugin_class", ")", ":", "if", "plugin_name", "in", "self", ".", "registered_plugins", ":", "raise", "PluginException", "(", "\"Plugin {} already registered! Duplicate \"", "\"plugins?\"", ".", "format...
Loads a plugin as a dictionary and attaches needed parts to correct areas for testing parts. :param plugin_name: Name of the plugins :param plugin_class: PluginBase :return: Nothing
[ "Loads", "a", "plugin", "as", "a", "dictionary", "and", "attaches", "needed", "parts", "to", "correct", "areas", "for", "testing", "parts", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/PluginManager.py#L64-L88
27,175
ARMmbed/icetea
icetea_lib/Plugin/PluginManager.py
PluginManager.register_run_plugins
def register_run_plugins(self, plugin_name, plugin_class): """ Loads a plugin as a dictionary and attaches needed parts to correct Icetea run global parts. :param plugin_name: Name of the plugins :param plugin_class: PluginBase :return: Nothing """ if plugin_name in self.registered_plugins: raise PluginException("Plugin {} already registered! " "Duplicate plugins?".format(plugin_name)) self.logger.debug("Registering plugin %s", plugin_name) if plugin_class.get_allocators(): register_func = self.plugin_types[PluginTypes.ALLOCATOR] register_func(plugin_name, plugin_class) self.registered_plugins.append(plugin_name)
python
def register_run_plugins(self, plugin_name, plugin_class): if plugin_name in self.registered_plugins: raise PluginException("Plugin {} already registered! " "Duplicate plugins?".format(plugin_name)) self.logger.debug("Registering plugin %s", plugin_name) if plugin_class.get_allocators(): register_func = self.plugin_types[PluginTypes.ALLOCATOR] register_func(plugin_name, plugin_class) self.registered_plugins.append(plugin_name)
[ "def", "register_run_plugins", "(", "self", ",", "plugin_name", ",", "plugin_class", ")", ":", "if", "plugin_name", "in", "self", ".", "registered_plugins", ":", "raise", "PluginException", "(", "\"Plugin {} already registered! \"", "\"Duplicate plugins?\"", ".", "forma...
Loads a plugin as a dictionary and attaches needed parts to correct Icetea run global parts. :param plugin_name: Name of the plugins :param plugin_class: PluginBase :return: Nothing
[ "Loads", "a", "plugin", "as", "a", "dictionary", "and", "attaches", "needed", "parts", "to", "correct", "Icetea", "run", "global", "parts", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/PluginManager.py#L90-L106
27,176
ARMmbed/icetea
icetea_lib/Plugin/PluginManager.py
PluginManager.load_default_tc_plugins
def load_default_tc_plugins(self): """ Load default test case level plugins from icetea_lib.Plugin.plugins.default_plugins. :return: Nothing """ for plugin_name, plugin_class in default_plugins.items(): if issubclass(plugin_class, PluginBase): try: self.register_tc_plugins(plugin_name, plugin_class()) except PluginException as error: self.logger.debug(error) continue
python
def load_default_tc_plugins(self): for plugin_name, plugin_class in default_plugins.items(): if issubclass(plugin_class, PluginBase): try: self.register_tc_plugins(plugin_name, plugin_class()) except PluginException as error: self.logger.debug(error) continue
[ "def", "load_default_tc_plugins", "(", "self", ")", ":", "for", "plugin_name", ",", "plugin_class", "in", "default_plugins", ".", "items", "(", ")", ":", "if", "issubclass", "(", "plugin_class", ",", "PluginBase", ")", ":", "try", ":", "self", ".", "register...
Load default test case level plugins from icetea_lib.Plugin.plugins.default_plugins. :return: Nothing
[ "Load", "default", "test", "case", "level", "plugins", "from", "icetea_lib", ".", "Plugin", ".", "plugins", ".", "default_plugins", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/PluginManager.py#L119-L131
27,177
ARMmbed/icetea
icetea_lib/Plugin/PluginManager.py
PluginManager.load_custom_tc_plugins
def load_custom_tc_plugins(self, plugin_path=None): """ Load custom test case level plugins from plugin_path. :param plugin_path: Path to file, which contains the imports and mapping for plugins. :return: None if plugin_path is None or False or something equivalent to those. """ if not plugin_path: return directory = os.path.dirname(plugin_path) sys.path.append(directory) modulename = os.path.split(plugin_path)[1] # Strip of file extension. if "." in modulename: modulename = modulename[:modulename.rindex(".")] try: module = importlib.import_module(modulename) except ImportError: raise PluginException("Unable to import custom plugin information from {}.".format( plugin_path)) for plugin_name, plugin_class in module.plugins_to_load.items(): if issubclass(plugin_class, PluginBase): try: self.register_tc_plugins(plugin_name, plugin_class()) except PluginException as error: self.logger.debug(error) continue
python
def load_custom_tc_plugins(self, plugin_path=None): if not plugin_path: return directory = os.path.dirname(plugin_path) sys.path.append(directory) modulename = os.path.split(plugin_path)[1] # Strip of file extension. if "." in modulename: modulename = modulename[:modulename.rindex(".")] try: module = importlib.import_module(modulename) except ImportError: raise PluginException("Unable to import custom plugin information from {}.".format( plugin_path)) for plugin_name, plugin_class in module.plugins_to_load.items(): if issubclass(plugin_class, PluginBase): try: self.register_tc_plugins(plugin_name, plugin_class()) except PluginException as error: self.logger.debug(error) continue
[ "def", "load_custom_tc_plugins", "(", "self", ",", "plugin_path", "=", "None", ")", ":", "if", "not", "plugin_path", ":", "return", "directory", "=", "os", ".", "path", ".", "dirname", "(", "plugin_path", ")", "sys", ".", "path", ".", "append", "(", "dir...
Load custom test case level plugins from plugin_path. :param plugin_path: Path to file, which contains the imports and mapping for plugins. :return: None if plugin_path is None or False or something equivalent to those.
[ "Load", "custom", "test", "case", "level", "plugins", "from", "plugin_path", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/PluginManager.py#L133-L159
27,178
ARMmbed/icetea
icetea_lib/Plugin/PluginManager.py
PluginManager.load_default_run_plugins
def load_default_run_plugins(self): """ Load default run level plugins from icetea_lib.Plugin.plugins.default_plugins. :return: Nothing """ for plugin_name, plugin_class in default_plugins.items(): if issubclass(plugin_class, RunPluginBase): try: self.register_run_plugins(plugin_name, plugin_class()) except PluginException as error: self.logger.debug(error) continue
python
def load_default_run_plugins(self): for plugin_name, plugin_class in default_plugins.items(): if issubclass(plugin_class, RunPluginBase): try: self.register_run_plugins(plugin_name, plugin_class()) except PluginException as error: self.logger.debug(error) continue
[ "def", "load_default_run_plugins", "(", "self", ")", ":", "for", "plugin_name", ",", "plugin_class", "in", "default_plugins", ".", "items", "(", ")", ":", "if", "issubclass", "(", "plugin_class", ",", "RunPluginBase", ")", ":", "try", ":", "self", ".", "regi...
Load default run level plugins from icetea_lib.Plugin.plugins.default_plugins. :return: Nothing
[ "Load", "default", "run", "level", "plugins", "from", "icetea_lib", ".", "Plugin", ".", "plugins", ".", "default_plugins", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/PluginManager.py#L161-L173
27,179
ARMmbed/icetea
icetea_lib/Plugin/PluginManager.py
PluginManager.start_external_service
def start_external_service(self, service_name, conf=None): """ Start external service service_name with configuration conf. :param service_name: Name of service to start :param conf: :return: nothing """ if service_name in self._external_services: ser = self._external_services[service_name] service = ser(service_name, conf=conf, bench=self.bench) try: service.start() except PluginException: self.logger.exception("Starting service %s caused an exception!", service_name) raise PluginException("Failed to start external service {}".format(service_name)) self._started_services.append(service) setattr(self.bench, service_name, service) else: self.logger.warning("Service %s not found. Check your plugins.", service_name)
python
def start_external_service(self, service_name, conf=None): if service_name in self._external_services: ser = self._external_services[service_name] service = ser(service_name, conf=conf, bench=self.bench) try: service.start() except PluginException: self.logger.exception("Starting service %s caused an exception!", service_name) raise PluginException("Failed to start external service {}".format(service_name)) self._started_services.append(service) setattr(self.bench, service_name, service) else: self.logger.warning("Service %s not found. Check your plugins.", service_name)
[ "def", "start_external_service", "(", "self", ",", "service_name", ",", "conf", "=", "None", ")", ":", "if", "service_name", "in", "self", ".", "_external_services", ":", "ser", "=", "self", ".", "_external_services", "[", "service_name", "]", "service", "=", ...
Start external service service_name with configuration conf. :param service_name: Name of service to start :param conf: :return: nothing
[ "Start", "external", "service", "service_name", "with", "configuration", "conf", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/PluginManager.py#L203-L222
27,180
ARMmbed/icetea
icetea_lib/Plugin/PluginManager.py
PluginManager.stop_external_services
def stop_external_services(self): """ Stop all external services. :return: Nothing """ for service in self._started_services: self.logger.debug("Stopping application %s", service.name) try: service.stop() except PluginException: self.logger.exception("Stopping external service %s caused and exception!", service.name) self._started_services = []
python
def stop_external_services(self): for service in self._started_services: self.logger.debug("Stopping application %s", service.name) try: service.stop() except PluginException: self.logger.exception("Stopping external service %s caused and exception!", service.name) self._started_services = []
[ "def", "stop_external_services", "(", "self", ")", ":", "for", "service", "in", "self", ".", "_started_services", ":", "self", ".", "logger", ".", "debug", "(", "\"Stopping application %s\"", ",", "service", ".", "name", ")", "try", ":", "service", ".", "sto...
Stop all external services. :return: Nothing
[ "Stop", "all", "external", "services", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/PluginManager.py#L224-L237
27,181
ARMmbed/icetea
icetea_lib/Plugin/PluginManager.py
PluginManager._register_bench_extension
def _register_bench_extension(self, plugin_name, plugin_instance): """ Register a bench extension. :param plugin_name: Plugin name :param plugin_instance: PluginBase :return: Nothing """ for attr in plugin_instance.get_bench_api().keys(): if hasattr(self.bench, attr): raise PluginException("Attribute {} already exists in bench! Unable to add " "plugin {}.".format(attr, plugin_name)) setattr(self.bench, attr, plugin_instance.get_bench_api().get(attr))
python
def _register_bench_extension(self, plugin_name, plugin_instance): for attr in plugin_instance.get_bench_api().keys(): if hasattr(self.bench, attr): raise PluginException("Attribute {} already exists in bench! Unable to add " "plugin {}.".format(attr, plugin_name)) setattr(self.bench, attr, plugin_instance.get_bench_api().get(attr))
[ "def", "_register_bench_extension", "(", "self", ",", "plugin_name", ",", "plugin_instance", ")", ":", "for", "attr", "in", "plugin_instance", ".", "get_bench_api", "(", ")", ".", "keys", "(", ")", ":", "if", "hasattr", "(", "self", ".", "bench", ",", "att...
Register a bench extension. :param plugin_name: Plugin name :param plugin_instance: PluginBase :return: Nothing
[ "Register", "a", "bench", "extension", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/PluginManager.py#L239-L251
27,182
ARMmbed/icetea
icetea_lib/Plugin/PluginManager.py
PluginManager._register_dataparser
def _register_dataparser(self, plugin_name, plugin_instance): """ Register a parser. :param plugin_name: Parser name :param plugin_instance: PluginBase :return: Nothing """ for parser in plugin_instance.get_parsers().keys(): if self.responseparser.has_parser(parser): raise PluginException("Parser {} already registered to parsers! Unable to " "add parsers from {}.".format(parser, plugin_name)) self.responseparser.add_parser(parser, plugin_instance.get_parsers().get(parser))
python
def _register_dataparser(self, plugin_name, plugin_instance): for parser in plugin_instance.get_parsers().keys(): if self.responseparser.has_parser(parser): raise PluginException("Parser {} already registered to parsers! Unable to " "add parsers from {}.".format(parser, plugin_name)) self.responseparser.add_parser(parser, plugin_instance.get_parsers().get(parser))
[ "def", "_register_dataparser", "(", "self", ",", "plugin_name", ",", "plugin_instance", ")", ":", "for", "parser", "in", "plugin_instance", ".", "get_parsers", "(", ")", ".", "keys", "(", ")", ":", "if", "self", ".", "responseparser", ".", "has_parser", "(",...
Register a parser. :param plugin_name: Parser name :param plugin_instance: PluginBase :return: Nothing
[ "Register", "a", "parser", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/PluginManager.py#L253-L265
27,183
ARMmbed/icetea
icetea_lib/Plugin/PluginManager.py
PluginManager._register_external_service
def _register_external_service(self, plugin_name, plugin_instance): """ Register an external service. :param plugin_name: Service name :param plugin_instance: PluginBase :return: """ for attr in plugin_instance.get_external_services().keys(): if attr in self._external_services: raise PluginException("External service with name {} already exists! Unable to add " "services from plugin {}.".format(attr, plugin_name)) self._external_services[attr] = plugin_instance.get_external_services().get(attr)
python
def _register_external_service(self, plugin_name, plugin_instance): for attr in plugin_instance.get_external_services().keys(): if attr in self._external_services: raise PluginException("External service with name {} already exists! Unable to add " "services from plugin {}.".format(attr, plugin_name)) self._external_services[attr] = plugin_instance.get_external_services().get(attr)
[ "def", "_register_external_service", "(", "self", ",", "plugin_name", ",", "plugin_instance", ")", ":", "for", "attr", "in", "plugin_instance", ".", "get_external_services", "(", ")", ".", "keys", "(", ")", ":", "if", "attr", "in", "self", ".", "_external_serv...
Register an external service. :param plugin_name: Service name :param plugin_instance: PluginBase :return:
[ "Register", "an", "external", "service", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/PluginManager.py#L267-L279
27,184
ARMmbed/icetea
icetea_lib/Plugin/PluginManager.py
PluginManager._register_allocator
def _register_allocator(self, plugin_name, plugin_instance): """ Register an allocator. :param plugin_name: Allocator name :param plugin_instance: RunPluginBase :return: """ for allocator in plugin_instance.get_allocators().keys(): if allocator in self._allocators: raise PluginException("Allocator with name {} already exists! unable to add " "allocators from plugin {}".format(allocator, plugin_name)) self._allocators[allocator] = plugin_instance.get_allocators().get(allocator)
python
def _register_allocator(self, plugin_name, plugin_instance): for allocator in plugin_instance.get_allocators().keys(): if allocator in self._allocators: raise PluginException("Allocator with name {} already exists! unable to add " "allocators from plugin {}".format(allocator, plugin_name)) self._allocators[allocator] = plugin_instance.get_allocators().get(allocator)
[ "def", "_register_allocator", "(", "self", ",", "plugin_name", ",", "plugin_instance", ")", ":", "for", "allocator", "in", "plugin_instance", ".", "get_allocators", "(", ")", ".", "keys", "(", ")", ":", "if", "allocator", "in", "self", ".", "_allocators", ":...
Register an allocator. :param plugin_name: Allocator name :param plugin_instance: RunPluginBase :return:
[ "Register", "an", "allocator", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/PluginManager.py#L281-L293
27,185
ARMmbed/icetea
examples/sample_cloud.py
create
def create(host, port, result_converter=None, testcase_converter=None, args=None): """ Function which is called by Icetea to create an instance of the cloud client. This function must exists. This function myust not return None. Either return an instance of Client or raise. """ return SampleClient(host, port, result_converter, testcase_converter, args)
python
def create(host, port, result_converter=None, testcase_converter=None, args=None): return SampleClient(host, port, result_converter, testcase_converter, args)
[ "def", "create", "(", "host", ",", "port", ",", "result_converter", "=", "None", ",", "testcase_converter", "=", "None", ",", "args", "=", "None", ")", ":", "return", "SampleClient", "(", "host", ",", "port", ",", "result_converter", ",", "testcase_converter...
Function which is called by Icetea to create an instance of the cloud client. This function must exists. This function myust not return None. Either return an instance of Client or raise.
[ "Function", "which", "is", "called", "by", "Icetea", "to", "create", "an", "instance", "of", "the", "cloud", "client", ".", "This", "function", "must", "exists", ".", "This", "function", "myust", "not", "return", "None", ".", "Either", "return", "an", "ins...
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/examples/sample_cloud.py#L24-L30
27,186
ARMmbed/icetea
examples/sample_cloud.py
SampleClient.send_results
def send_results(self, result): """ Upload a result object to server. If resultConverter has been provided, use it to convert result object to format accepted by the server. If needed, use testcase_converter to convert tc metadata in result to suitable format. returns new result entry as a dictionary or None. """ if self.result_converter: print(self.result_converter(result)) else: print(result)
python
def send_results(self, result): if self.result_converter: print(self.result_converter(result)) else: print(result)
[ "def", "send_results", "(", "self", ",", "result", ")", ":", "if", "self", ".", "result_converter", ":", "print", "(", "self", ".", "result_converter", "(", "result", ")", ")", "else", ":", "print", "(", "result", ")" ]
Upload a result object to server. If resultConverter has been provided, use it to convert result object to format accepted by the server. If needed, use testcase_converter to convert tc metadata in result to suitable format. returns new result entry as a dictionary or None.
[ "Upload", "a", "result", "object", "to", "server", ".", "If", "resultConverter", "has", "been", "provided", "use", "it", "to", "convert", "result", "object", "to", "format", "accepted", "by", "the", "server", ".", "If", "needed", "use", "testcase_converter", ...
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/examples/sample_cloud.py#L93-L105
27,187
ARMmbed/icetea
icetea_lib/Plugin/plugins/HttpApi.py
HttpApiPlugin.get_tc_api
def get_tc_api(self, host, headers=None, cert=None, logger=None): ''' Gets HttpApi wrapped into a neat little package that raises TestStepFail if expected status code is not returned by the server. Default setting for expected status code is 200. Set expected to None when calling methods to ignore the expected status code parameter or set raiseException = False to disable raising the exception. ''' if logger is None and self.logger: logger = self.logger return Api(host, headers, cert, logger)
python
def get_tc_api(self, host, headers=None, cert=None, logger=None): ''' Gets HttpApi wrapped into a neat little package that raises TestStepFail if expected status code is not returned by the server. Default setting for expected status code is 200. Set expected to None when calling methods to ignore the expected status code parameter or set raiseException = False to disable raising the exception. ''' if logger is None and self.logger: logger = self.logger return Api(host, headers, cert, logger)
[ "def", "get_tc_api", "(", "self", ",", "host", ",", "headers", "=", "None", ",", "cert", "=", "None", ",", "logger", "=", "None", ")", ":", "if", "logger", "is", "None", "and", "self", ".", "logger", ":", "logger", "=", "self", ".", "logger", "retu...
Gets HttpApi wrapped into a neat little package that raises TestStepFail if expected status code is not returned by the server. Default setting for expected status code is 200. Set expected to None when calling methods to ignore the expected status code parameter or set raiseException = False to disable raising the exception.
[ "Gets", "HttpApi", "wrapped", "into", "a", "neat", "little", "package", "that", "raises", "TestStepFail", "if", "expected", "status", "code", "is", "not", "returned", "by", "the", "server", ".", "Default", "setting", "for", "expected", "status", "code", "is", ...
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/plugins/HttpApi.py#L43-L53
27,188
ARMmbed/icetea
icetea_lib/Plugin/plugins/HttpApi.py
Api._raise_fail
def _raise_fail(self, response, expected): """ Raise a TestStepFail with neatly formatted error message """ try: if self.logger: self.logger.error("Status code " "{} != {}. \n\n " "Payload: {}".format(response.status_code, expected, response.content)) raise TestStepFail("Status code {} != {}.".format(response.status_code, expected)) except TestStepFail: raise except: # pylint: disable=bare-except if self.logger: self.logger.error("Status code " "{} != {}. \n\n " "Payload: {}".format(response.status_code, expected, "Unable to parse payload")) raise TestStepFail("Status code {} != {}.".format(response.status_code, expected))
python
def _raise_fail(self, response, expected): try: if self.logger: self.logger.error("Status code " "{} != {}. \n\n " "Payload: {}".format(response.status_code, expected, response.content)) raise TestStepFail("Status code {} != {}.".format(response.status_code, expected)) except TestStepFail: raise except: # pylint: disable=bare-except if self.logger: self.logger.error("Status code " "{} != {}. \n\n " "Payload: {}".format(response.status_code, expected, "Unable to parse payload")) raise TestStepFail("Status code {} != {}.".format(response.status_code, expected))
[ "def", "_raise_fail", "(", "self", ",", "response", ",", "expected", ")", ":", "try", ":", "if", "self", ".", "logger", ":", "self", ".", "logger", ".", "error", "(", "\"Status code \"", "\"{} != {}. \\n\\n \"", "\"Payload: {}\"", ".", "format", "(", "respon...
Raise a TestStepFail with neatly formatted error message
[ "Raise", "a", "TestStepFail", "with", "neatly", "formatted", "error", "message" ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/plugins/HttpApi.py#L63-L84
27,189
ARMmbed/icetea
icetea_lib/Reports/ReportJunit.py
ReportJunit.generate
def generate(self, *args, **kwargs): """ Implementation for generate method from ReportBase. Generates the xml and saves the report in Junit xml format. :param args: 1 argument, filename is used. :param kwargs: Not used :return: Nothing """ xmlstr = str(self) filename = args[0] with open(filename, 'w') as fil: fil.write(xmlstr) with open(self.get_latest_filename('junit.xml'), "w") as latest_report: latest_report.write(xmlstr)
python
def generate(self, *args, **kwargs): xmlstr = str(self) filename = args[0] with open(filename, 'w') as fil: fil.write(xmlstr) with open(self.get_latest_filename('junit.xml'), "w") as latest_report: latest_report.write(xmlstr)
[ "def", "generate", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "xmlstr", "=", "str", "(", "self", ")", "filename", "=", "args", "[", "0", "]", "with", "open", "(", "filename", ",", "'w'", ")", "as", "fil", ":", "fil", ".",...
Implementation for generate method from ReportBase. Generates the xml and saves the report in Junit xml format. :param args: 1 argument, filename is used. :param kwargs: Not used :return: Nothing
[ "Implementation", "for", "generate", "method", "from", "ReportBase", ".", "Generates", "the", "xml", "and", "saves", "the", "report", "in", "Junit", "xml", "format", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Reports/ReportJunit.py#L71-L86
27,190
ARMmbed/icetea
icetea_lib/Reports/ReportJunit.py
ReportJunit.__generate
def __generate(results): """ Static method which generates the Junit xml string from results :param results: Results as ResultList object. :return: Junit xml format string. """ doc, tag, text = Doc().tagtext() # Counters for testsuite tag info count = 0 fails = 0 errors = 0 skips = 0 for result in results: # Loop through all results and count the ones that were not later retried. if result.passed() is False: if result.retries_left > 0: # This will appear in the list again, move on continue count += 1 if result.passed(): # Passed, no need to increment anything else continue elif result.skipped(): skips += 1 elif result.was_inconclusive(): errors += 1 else: fails += 1 with tag('testsuite', tests=str(count), failures=str(fails), errors=str(errors), skipped=str(skips)): for result in results: if result.passed() is False and result.retries_left > 0: continue class_name = result.get_tc_name() models = result.get_dut_models() if models: class_name = class_name + "." + models name = result.get_toolchain() with tag('testcase', classname=class_name, name=name, time=result.get_duration(seconds=True)): if result.stdout: with tag('system-out'): text(result.stdout) if result.passed(): continue elif result.skipped(): with tag('skipped'): text(result.skip_reason) elif result.was_inconclusive(): with tag('error', message=hex_escape_str(result.fail_reason)): text(result.stderr) else: with tag('failure', message=hex_escape_str(result.fail_reason)): text(result.stderr) return indent( doc.getvalue(), indentation=' '*4 )
python
def __generate(results): doc, tag, text = Doc().tagtext() # Counters for testsuite tag info count = 0 fails = 0 errors = 0 skips = 0 for result in results: # Loop through all results and count the ones that were not later retried. if result.passed() is False: if result.retries_left > 0: # This will appear in the list again, move on continue count += 1 if result.passed(): # Passed, no need to increment anything else continue elif result.skipped(): skips += 1 elif result.was_inconclusive(): errors += 1 else: fails += 1 with tag('testsuite', tests=str(count), failures=str(fails), errors=str(errors), skipped=str(skips)): for result in results: if result.passed() is False and result.retries_left > 0: continue class_name = result.get_tc_name() models = result.get_dut_models() if models: class_name = class_name + "." + models name = result.get_toolchain() with tag('testcase', classname=class_name, name=name, time=result.get_duration(seconds=True)): if result.stdout: with tag('system-out'): text(result.stdout) if result.passed(): continue elif result.skipped(): with tag('skipped'): text(result.skip_reason) elif result.was_inconclusive(): with tag('error', message=hex_escape_str(result.fail_reason)): text(result.stderr) else: with tag('failure', message=hex_escape_str(result.fail_reason)): text(result.stderr) return indent( doc.getvalue(), indentation=' '*4 )
[ "def", "__generate", "(", "results", ")", ":", "doc", ",", "tag", ",", "text", "=", "Doc", "(", ")", ".", "tagtext", "(", ")", "# Counters for testsuite tag info", "count", "=", "0", "fails", "=", "0", "errors", "=", "0", "skips", "=", "0", "for", "r...
Static method which generates the Junit xml string from results :param results: Results as ResultList object. :return: Junit xml format string.
[ "Static", "method", "which", "generates", "the", "Junit", "xml", "string", "from", "results" ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Reports/ReportJunit.py#L106-L170
27,191
ARMmbed/icetea
icetea_lib/AllocationContext.py
AllocationContextList.open_dut_connections
def open_dut_connections(self): """ Opens connections to Duts. Starts Dut read threads. :return: Nothing :raises DutConnectionError: if problems were encountered while opening dut connection. """ for dut in self.duts: try: dut.start_dut_thread() if hasattr(dut, "command"): dut.open_dut(dut.command) else: dut.open_dut() except DutConnectionError: self.logger.exception("Failed when opening dut connection") dut.close_dut(False) dut.close_connection() dut = None raise
python
def open_dut_connections(self): for dut in self.duts: try: dut.start_dut_thread() if hasattr(dut, "command"): dut.open_dut(dut.command) else: dut.open_dut() except DutConnectionError: self.logger.exception("Failed when opening dut connection") dut.close_dut(False) dut.close_connection() dut = None raise
[ "def", "open_dut_connections", "(", "self", ")", ":", "for", "dut", "in", "self", ".", "duts", ":", "try", ":", "dut", ".", "start_dut_thread", "(", ")", "if", "hasattr", "(", "dut", ",", "\"command\"", ")", ":", "dut", ".", "open_dut", "(", "dut", "...
Opens connections to Duts. Starts Dut read threads. :return: Nothing :raises DutConnectionError: if problems were encountered while opening dut connection.
[ "Opens", "connections", "to", "Duts", ".", "Starts", "Dut", "read", "threads", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/AllocationContext.py#L352-L371
27,192
ARMmbed/icetea
icetea_lib/AllocationContext.py
AllocationContextList.check_flashing_need
def check_flashing_need(self, execution_type, build_id, force): """ Check if flashing of local device is required. :param execution_type: Should be 'hardware' :param build_id: Build id, usually file name :param force: Forceflash flag :return: Boolean """ binary_file_name = AllocationContextList.get_build(build_id) if binary_file_name: if execution_type == 'hardware' and os.path.isfile(binary_file_name): if not force: #@todo: Make a better check for binary compatibility extension_split = os.path.splitext(binary_file_name) extension = extension_split[-1].lower() if extension != '.bin' and extension != '.hex': self.logger.debug("File ('%s') is not supported to flash, skip it" %( build_id)) return False return True return True else: raise ResourceInitError("Given binary %s does not exist" % build_id) else: raise ResourceInitError("Given binary %s does not exist" % build_id)
python
def check_flashing_need(self, execution_type, build_id, force): binary_file_name = AllocationContextList.get_build(build_id) if binary_file_name: if execution_type == 'hardware' and os.path.isfile(binary_file_name): if not force: #@todo: Make a better check for binary compatibility extension_split = os.path.splitext(binary_file_name) extension = extension_split[-1].lower() if extension != '.bin' and extension != '.hex': self.logger.debug("File ('%s') is not supported to flash, skip it" %( build_id)) return False return True return True else: raise ResourceInitError("Given binary %s does not exist" % build_id) else: raise ResourceInitError("Given binary %s does not exist" % build_id)
[ "def", "check_flashing_need", "(", "self", ",", "execution_type", ",", "build_id", ",", "force", ")", ":", "binary_file_name", "=", "AllocationContextList", ".", "get_build", "(", "build_id", ")", "if", "binary_file_name", ":", "if", "execution_type", "==", "'hard...
Check if flashing of local device is required. :param execution_type: Should be 'hardware' :param build_id: Build id, usually file name :param force: Forceflash flag :return: Boolean
[ "Check", "if", "flashing", "of", "local", "device", "is", "required", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/AllocationContext.py#L373-L398
27,193
ARMmbed/icetea
icetea_lib/LogManager.py
remove_handlers
def remove_handlers(logger): # TODO: Issue related to placeholder logger objects appearing in some rare cases. Check below # required as a workaround """ Remove handlers from logger. :param logger: Logger whose handlers to remove """ if hasattr(logger, "handlers"): for handler in logger.handlers[::-1]: try: if isinstance(handler, logging.FileHandler): handler.close() logger.removeHandler(handler) except: # pylint: disable=bare-except import traceback traceback.print_exc() break
python
def remove_handlers(logger): # TODO: Issue related to placeholder logger objects appearing in some rare cases. Check below # required as a workaround if hasattr(logger, "handlers"): for handler in logger.handlers[::-1]: try: if isinstance(handler, logging.FileHandler): handler.close() logger.removeHandler(handler) except: # pylint: disable=bare-except import traceback traceback.print_exc() break
[ "def", "remove_handlers", "(", "logger", ")", ":", "# TODO: Issue related to placeholder logger objects appearing in some rare cases. Check below", "# required as a workaround", "if", "hasattr", "(", "logger", ",", "\"handlers\"", ")", ":", "for", "handler", "in", "logger", "...
Remove handlers from logger. :param logger: Logger whose handlers to remove
[ "Remove", "handlers", "from", "logger", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/LogManager.py#L184-L201
27,194
ARMmbed/icetea
icetea_lib/LogManager.py
get_base_logfilename
def get_base_logfilename(logname): """ Return filename for a logfile, filename will contain the actual path + filename :param logname: Name of the log including the extension, should describe what it contains (eg. "device_serial_port.log") """ logdir = get_base_dir() fname = os.path.join(logdir, logname) GLOBAL_LOGFILES.append(fname) return fname
python
def get_base_logfilename(logname): logdir = get_base_dir() fname = os.path.join(logdir, logname) GLOBAL_LOGFILES.append(fname) return fname
[ "def", "get_base_logfilename", "(", "logname", ")", ":", "logdir", "=", "get_base_dir", "(", ")", "fname", "=", "os", ".", "path", ".", "join", "(", "logdir", ",", "logname", ")", "GLOBAL_LOGFILES", ".", "append", "(", "fname", ")", "return", "fname" ]
Return filename for a logfile, filename will contain the actual path + filename :param logname: Name of the log including the extension, should describe what it contains (eg. "device_serial_port.log")
[ "Return", "filename", "for", "a", "logfile", "filename", "will", "contain", "the", "actual", "path", "+", "filename" ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/LogManager.py#L236-L246
27,195
ARMmbed/icetea
icetea_lib/LogManager.py
get_file_logger
def get_file_logger(name, formatter=None): """ Return a file logger that will log into a file located in the testcase log directory. Anything logged with a file logger won't be visible in the console or any other logger. :param name: Name of the logger, eg. the module name :param formatter: Formatter to use """ if name is None or name == "": raise ValueError("Can't make a logger without name") logger = logging.getLogger(name) remove_handlers(logger) logger.setLevel(logging.INFO) if formatter is None: config = LOGGING_CONFIG.get(name, {}).get("file", DEFAULT_LOGGING_CONFIG.get("file")) formatter = BenchFormatter(config.get("level", "DEBUG"), config.get("dateformat")) func = get_testcase_logfilename(name + ".log") handler = _get_filehandler_with_formatter(func, formatter) logger.addHandler(handler) return logger
python
def get_file_logger(name, formatter=None): if name is None or name == "": raise ValueError("Can't make a logger without name") logger = logging.getLogger(name) remove_handlers(logger) logger.setLevel(logging.INFO) if formatter is None: config = LOGGING_CONFIG.get(name, {}).get("file", DEFAULT_LOGGING_CONFIG.get("file")) formatter = BenchFormatter(config.get("level", "DEBUG"), config.get("dateformat")) func = get_testcase_logfilename(name + ".log") handler = _get_filehandler_with_formatter(func, formatter) logger.addHandler(handler) return logger
[ "def", "get_file_logger", "(", "name", ",", "formatter", "=", "None", ")", ":", "if", "name", "is", "None", "or", "name", "==", "\"\"", ":", "raise", "ValueError", "(", "\"Can't make a logger without name\"", ")", "logger", "=", "logging", ".", "getLogger", ...
Return a file logger that will log into a file located in the testcase log directory. Anything logged with a file logger won't be visible in the console or any other logger. :param name: Name of the logger, eg. the module name :param formatter: Formatter to use
[ "Return", "a", "file", "logger", "that", "will", "log", "into", "a", "file", "located", "in", "the", "testcase", "log", "directory", ".", "Anything", "logged", "with", "a", "file", "logger", "won", "t", "be", "visible", "in", "the", "console", "or", "any...
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/LogManager.py#L256-L278
27,196
ARMmbed/icetea
icetea_lib/LogManager.py
_check_existing_logger
def _check_existing_logger(loggername, short_name): """ Check if logger with name loggername exists. :param loggername: Name of logger. :param short_name: Shortened name for the logger. :return: Logger or None """ if loggername in LOGGERS: # Check if short_name matches the existing one, if not update it if isinstance(LOGGERS[loggername], BenchLoggerAdapter): if ("source" not in LOGGERS[loggername].extra or LOGGERS[loggername].extra["source"] != short_name): LOGGERS[loggername].extra["source"] = short_name return LOGGERS[loggername] return None
python
def _check_existing_logger(loggername, short_name): if loggername in LOGGERS: # Check if short_name matches the existing one, if not update it if isinstance(LOGGERS[loggername], BenchLoggerAdapter): if ("source" not in LOGGERS[loggername].extra or LOGGERS[loggername].extra["source"] != short_name): LOGGERS[loggername].extra["source"] = short_name return LOGGERS[loggername] return None
[ "def", "_check_existing_logger", "(", "loggername", ",", "short_name", ")", ":", "if", "loggername", "in", "LOGGERS", ":", "# Check if short_name matches the existing one, if not update it", "if", "isinstance", "(", "LOGGERS", "[", "loggername", "]", ",", "BenchLoggerAdap...
Check if logger with name loggername exists. :param loggername: Name of logger. :param short_name: Shortened name for the logger. :return: Logger or None
[ "Check", "if", "logger", "with", "name", "loggername", "exists", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/LogManager.py#L281-L296
27,197
ARMmbed/icetea
icetea_lib/LogManager.py
_add_filehandler
def _add_filehandler(logger, logpath, formatter=None, name="Bench"): """ Adds a FileHandler to logger. :param logger: Logger. :param logpath: Path to file. :param formatter: Formatter to be used :param name: Name for logger :return: Logger """ formatter = formatter if formatter else BenchFormatterWithType(loggername=name) handler = _get_filehandler_with_formatter(logpath, formatter) config = LOGGING_CONFIG.get(name, {}).get("file", DEFAULT_LOGGING_CONFIG.get("file")) handler.setLevel(getattr(logging, config.get("level", "DEBUG"))) logger.addHandler(handler) return logger
python
def _add_filehandler(logger, logpath, formatter=None, name="Bench"): formatter = formatter if formatter else BenchFormatterWithType(loggername=name) handler = _get_filehandler_with_formatter(logpath, formatter) config = LOGGING_CONFIG.get(name, {}).get("file", DEFAULT_LOGGING_CONFIG.get("file")) handler.setLevel(getattr(logging, config.get("level", "DEBUG"))) logger.addHandler(handler) return logger
[ "def", "_add_filehandler", "(", "logger", ",", "logpath", ",", "formatter", "=", "None", ",", "name", "=", "\"Bench\"", ")", ":", "formatter", "=", "formatter", "if", "formatter", "else", "BenchFormatterWithType", "(", "loggername", "=", "name", ")", "handler"...
Adds a FileHandler to logger. :param logger: Logger. :param logpath: Path to file. :param formatter: Formatter to be used :param name: Name for logger :return: Logger
[ "Adds", "a", "FileHandler", "to", "logger", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/LogManager.py#L299-L314
27,198
ARMmbed/icetea
icetea_lib/LogManager.py
_get_basic_logger
def _get_basic_logger(loggername, log_to_file, logpath): """ Get a logger with our basic configuration done. :param loggername: Name of logger. :param log_to_file: Boolean, True if this logger should write a file. :return: Logger """ logger = logging.getLogger(loggername) logger.propagate = False remove_handlers(logger) logger.setLevel(logging.DEBUG) logger_config = LOGGING_CONFIG.get(loggername, DEFAULT_LOGGING_CONFIG) if TRUNCATE_LOG or logger_config.get("truncate_logs").get("truncate"): cfilter = ContextFilter() trunc_logs = logger_config.get("truncate_logs") # pylint: disable=invalid-name cfilter.MAXIMUM_LENGTH = trunc_logs.get("max_len", DEFAULT_LOGGING_CONFIG.get( "truncate_logs").get("max_len")) cfilter.REVEAL_LENGTH = trunc_logs.get("reveal_len", DEFAULT_LOGGING_CONFIG.get( "truncate_logs").get("reveal_len")) logger.addFilter(cfilter) # Filehandler for logger if log_to_file: _add_filehandler(logger, logpath, name=loggername) return logger
python
def _get_basic_logger(loggername, log_to_file, logpath): logger = logging.getLogger(loggername) logger.propagate = False remove_handlers(logger) logger.setLevel(logging.DEBUG) logger_config = LOGGING_CONFIG.get(loggername, DEFAULT_LOGGING_CONFIG) if TRUNCATE_LOG or logger_config.get("truncate_logs").get("truncate"): cfilter = ContextFilter() trunc_logs = logger_config.get("truncate_logs") # pylint: disable=invalid-name cfilter.MAXIMUM_LENGTH = trunc_logs.get("max_len", DEFAULT_LOGGING_CONFIG.get( "truncate_logs").get("max_len")) cfilter.REVEAL_LENGTH = trunc_logs.get("reveal_len", DEFAULT_LOGGING_CONFIG.get( "truncate_logs").get("reveal_len")) logger.addFilter(cfilter) # Filehandler for logger if log_to_file: _add_filehandler(logger, logpath, name=loggername) return logger
[ "def", "_get_basic_logger", "(", "loggername", ",", "log_to_file", ",", "logpath", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "loggername", ")", "logger", ".", "propagate", "=", "False", "remove_handlers", "(", "logger", ")", "logger", ".", "...
Get a logger with our basic configuration done. :param loggername: Name of logger. :param log_to_file: Boolean, True if this logger should write a file. :return: Logger
[ "Get", "a", "logger", "with", "our", "basic", "configuration", "done", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/LogManager.py#L317-L346
27,199
ARMmbed/icetea
icetea_lib/LogManager.py
get_resourceprovider_logger
def get_resourceprovider_logger(name=None, short_name=" ", log_to_file=True): """ Get a logger for ResourceProvider and it's components, such as Allocators. :param name: Name for logger :param short_name: Shorthand name for the logger :param log_to_file: Boolean, True if logger should log to a file as well. :return: Logger """ global LOGGERS loggername = name logger = _check_existing_logger(loggername, short_name) if logger is not None: return logger logger_config = LOGGING_CONFIG.get(name, DEFAULT_LOGGING_CONFIG) logger = _get_basic_logger(loggername, log_to_file, get_base_logfilename(loggername + ".log")) cbh = logging.StreamHandler() cbh.formatter = BenchFormatterWithType(COLOR_ON) if VERBOSE_LEVEL > 0 and not SILENT_ON: cbh.setLevel(logging.DEBUG) elif SILENT_ON: cbh.setLevel(logging.WARN) else: cbh.setLevel(getattr(logging, logger_config.get("level"))) logger.addHandler(cbh) LOGGERS[loggername] = BenchLoggerAdapter(logger, {"source": short_name}) return LOGGERS[loggername]
python
def get_resourceprovider_logger(name=None, short_name=" ", log_to_file=True): global LOGGERS loggername = name logger = _check_existing_logger(loggername, short_name) if logger is not None: return logger logger_config = LOGGING_CONFIG.get(name, DEFAULT_LOGGING_CONFIG) logger = _get_basic_logger(loggername, log_to_file, get_base_logfilename(loggername + ".log")) cbh = logging.StreamHandler() cbh.formatter = BenchFormatterWithType(COLOR_ON) if VERBOSE_LEVEL > 0 and not SILENT_ON: cbh.setLevel(logging.DEBUG) elif SILENT_ON: cbh.setLevel(logging.WARN) else: cbh.setLevel(getattr(logging, logger_config.get("level"))) logger.addHandler(cbh) LOGGERS[loggername] = BenchLoggerAdapter(logger, {"source": short_name}) return LOGGERS[loggername]
[ "def", "get_resourceprovider_logger", "(", "name", "=", "None", ",", "short_name", "=", "\" \"", ",", "log_to_file", "=", "True", ")", ":", "global", "LOGGERS", "loggername", "=", "name", "logger", "=", "_check_existing_logger", "(", "loggername", ",", "short_na...
Get a logger for ResourceProvider and it's components, such as Allocators. :param name: Name for logger :param short_name: Shorthand name for the logger :param log_to_file: Boolean, True if logger should log to a file as well. :return: Logger
[ "Get", "a", "logger", "for", "ResourceProvider", "and", "it", "s", "components", "such", "as", "Allocators", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/LogManager.py#L349-L379