repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
mrstephenneal/mysql-toolkit | mysql/toolkit/components/operations/export.py | insert_statement | def insert_statement(table, columns, values):
"""Generate an insert statement string for dumping to text file or MySQL execution."""
if not all(isinstance(r, (list, set, tuple)) for r in values):
values = [[r] for r in values]
rows = []
for row in values:
new_row = []
for col in row:
if col is None:
new_col = 'NULL'
elif isinstance(col, (int, float, Decimal)):
new_col = str(MySQLConverterBase().to_mysql(col))
else:
string = str(MySQLConverterBase().to_mysql(col))
if "'" in string:
new_col = '"' + string + '"'
else:
new_col = "'" + string + "'"
new_row.append(new_col)
rows.append(', '.join(new_row))
vals = '(' + '),\n\t('.join(rows) + ')'
statement = "INSERT INTO\n\t{0} ({1}) \nVALUES\n\t{2}".format(wrap(table), cols_str(columns), vals)
return statement | python | def insert_statement(table, columns, values):
"""Generate an insert statement string for dumping to text file or MySQL execution."""
if not all(isinstance(r, (list, set, tuple)) for r in values):
values = [[r] for r in values]
rows = []
for row in values:
new_row = []
for col in row:
if col is None:
new_col = 'NULL'
elif isinstance(col, (int, float, Decimal)):
new_col = str(MySQLConverterBase().to_mysql(col))
else:
string = str(MySQLConverterBase().to_mysql(col))
if "'" in string:
new_col = '"' + string + '"'
else:
new_col = "'" + string + "'"
new_row.append(new_col)
rows.append(', '.join(new_row))
vals = '(' + '),\n\t('.join(rows) + ')'
statement = "INSERT INTO\n\t{0} ({1}) \nVALUES\n\t{2}".format(wrap(table), cols_str(columns), vals)
return statement | [
"def",
"insert_statement",
"(",
"table",
",",
"columns",
",",
"values",
")",
":",
"if",
"not",
"all",
"(",
"isinstance",
"(",
"r",
",",
"(",
"list",
",",
"set",
",",
"tuple",
")",
")",
"for",
"r",
"in",
"values",
")",
":",
"values",
"=",
"[",
"["... | Generate an insert statement string for dumping to text file or MySQL execution. | [
"Generate",
"an",
"insert",
"statement",
"string",
"for",
"dumping",
"to",
"text",
"file",
"or",
"MySQL",
"execution",
"."
] | train | https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/operations/export.py#L11-L33 |
mrstephenneal/mysql-toolkit | mysql/toolkit/components/operations/export.py | Export.dump_table | def dump_table(self, table, drop_statement=True):
"""Export a table structure and data to SQL file for backup or later import."""
create_statement = self.get_table_definition(table)
data = self.select_all(table)
statements = ['\n', sql_file_comment(''),
sql_file_comment('Table structure and data dump for {0}'.format(table)), sql_file_comment('')]
if drop_statement:
statements.append('\nDROP TABLE IF EXISTS {0};'.format(wrap(table)))
statements.append('{0};\n'.format(create_statement))
if len(data) > 0:
statements.append('{0};'.format(insert_statement(table, self.get_columns(table), data)))
return '\n'.join(statements) | python | def dump_table(self, table, drop_statement=True):
"""Export a table structure and data to SQL file for backup or later import."""
create_statement = self.get_table_definition(table)
data = self.select_all(table)
statements = ['\n', sql_file_comment(''),
sql_file_comment('Table structure and data dump for {0}'.format(table)), sql_file_comment('')]
if drop_statement:
statements.append('\nDROP TABLE IF EXISTS {0};'.format(wrap(table)))
statements.append('{0};\n'.format(create_statement))
if len(data) > 0:
statements.append('{0};'.format(insert_statement(table, self.get_columns(table), data)))
return '\n'.join(statements) | [
"def",
"dump_table",
"(",
"self",
",",
"table",
",",
"drop_statement",
"=",
"True",
")",
":",
"create_statement",
"=",
"self",
".",
"get_table_definition",
"(",
"table",
")",
"data",
"=",
"self",
".",
"select_all",
"(",
"table",
")",
"statements",
"=",
"["... | Export a table structure and data to SQL file for backup or later import. | [
"Export",
"a",
"table",
"structure",
"and",
"data",
"to",
"SQL",
"file",
"for",
"backup",
"or",
"later",
"import",
"."
] | train | https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/operations/export.py#L42-L53 |
mrstephenneal/mysql-toolkit | mysql/toolkit/components/operations/export.py | Export.dump_database | def dump_database(self, file_path, database=None, tables=None):
"""
Export the table structure and data for tables in a database.
If not database is specified, it is assumed the currently connected database
is the source. If no tables are provided, all tables will be dumped.
"""
# Change database if needed
if database:
self.change_db(database)
# Set table
if not tables:
tables = self.tables
# Retrieve and join dump statements
statements = [self.dump_table(table) for table in tqdm(tables, total=len(tables), desc='Generating dump files')]
dump = 'SET FOREIGN_KEY_CHECKS=0;' + '\n'.join(statements) + '\nSET FOREIGN_KEY_CHECKS=1;'
# Write dump statements to sql file
file_path = file_path if file_path.endswith('.sql') else file_path + '.sql'
write_text(dump, file_path)
return file_path | python | def dump_database(self, file_path, database=None, tables=None):
"""
Export the table structure and data for tables in a database.
If not database is specified, it is assumed the currently connected database
is the source. If no tables are provided, all tables will be dumped.
"""
# Change database if needed
if database:
self.change_db(database)
# Set table
if not tables:
tables = self.tables
# Retrieve and join dump statements
statements = [self.dump_table(table) for table in tqdm(tables, total=len(tables), desc='Generating dump files')]
dump = 'SET FOREIGN_KEY_CHECKS=0;' + '\n'.join(statements) + '\nSET FOREIGN_KEY_CHECKS=1;'
# Write dump statements to sql file
file_path = file_path if file_path.endswith('.sql') else file_path + '.sql'
write_text(dump, file_path)
return file_path | [
"def",
"dump_database",
"(",
"self",
",",
"file_path",
",",
"database",
"=",
"None",
",",
"tables",
"=",
"None",
")",
":",
"# Change database if needed",
"if",
"database",
":",
"self",
".",
"change_db",
"(",
"database",
")",
"# Set table",
"if",
"not",
"tabl... | Export the table structure and data for tables in a database.
If not database is specified, it is assumed the currently connected database
is the source. If no tables are provided, all tables will be dumped. | [
"Export",
"the",
"table",
"structure",
"and",
"data",
"for",
"tables",
"in",
"a",
"database",
"."
] | train | https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/operations/export.py#L55-L77 |
Stranger6667/pyoffers | pyoffers/api.py | retry | def retry(method):
"""
Allows to retry method execution few times.
"""
def inner(self, *args, **kwargs):
attempt_number = 1
while attempt_number < self.retries:
try:
return method(self, *args, **kwargs)
except HasOffersException as exc:
if 'API usage exceeded rate limit' not in str(exc):
raise exc
self.logger.debug('Retrying due: %s', exc)
time.sleep(self.retry_timeout)
except requests.exceptions.ConnectionError:
# This happens when the session gets expired
self.logger.debug('Recreating session due to ConnectionError')
self._session = requests.Session()
attempt_number += 1
raise MaxRetriesExceeded
return inner | python | def retry(method):
"""
Allows to retry method execution few times.
"""
def inner(self, *args, **kwargs):
attempt_number = 1
while attempt_number < self.retries:
try:
return method(self, *args, **kwargs)
except HasOffersException as exc:
if 'API usage exceeded rate limit' not in str(exc):
raise exc
self.logger.debug('Retrying due: %s', exc)
time.sleep(self.retry_timeout)
except requests.exceptions.ConnectionError:
# This happens when the session gets expired
self.logger.debug('Recreating session due to ConnectionError')
self._session = requests.Session()
attempt_number += 1
raise MaxRetriesExceeded
return inner | [
"def",
"retry",
"(",
"method",
")",
":",
"def",
"inner",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"attempt_number",
"=",
"1",
"while",
"attempt_number",
"<",
"self",
".",
"retries",
":",
"try",
":",
"return",
"method",
"(",
... | Allows to retry method execution few times. | [
"Allows",
"to",
"retry",
"method",
"execution",
"few",
"times",
"."
] | train | https://github.com/Stranger6667/pyoffers/blob/9575d6cdc878096242268311a22cc5fdd4f64b37/pyoffers/api.py#L21-L43 |
Stranger6667/pyoffers | pyoffers/api.py | HasOffersAPI.setup_managers | def setup_managers(self):
"""
Allows to access manager by model name - it is convenient, because HasOffers returns model names in responses.
"""
self._managers = {}
for manager_class in MODEL_MANAGERS:
instance = manager_class(self)
if not instance.forbid_registration \
and not isinstance(instance, ApplicationManager) or instance.__class__ is ApplicationManager:
# Descendants of ``ApplicationManager`` shouldn't be present in API instance. They are controlled by
# Application controller. The manager itself, on the other hand, should.
setattr(self, instance.name, instance)
if instance.model:
self._managers[instance.model.__name__] = instance
if instance.model_aliases:
for alias in instance.model_aliases:
self._managers[alias] = instance | python | def setup_managers(self):
"""
Allows to access manager by model name - it is convenient, because HasOffers returns model names in responses.
"""
self._managers = {}
for manager_class in MODEL_MANAGERS:
instance = manager_class(self)
if not instance.forbid_registration \
and not isinstance(instance, ApplicationManager) or instance.__class__ is ApplicationManager:
# Descendants of ``ApplicationManager`` shouldn't be present in API instance. They are controlled by
# Application controller. The manager itself, on the other hand, should.
setattr(self, instance.name, instance)
if instance.model:
self._managers[instance.model.__name__] = instance
if instance.model_aliases:
for alias in instance.model_aliases:
self._managers[alias] = instance | [
"def",
"setup_managers",
"(",
"self",
")",
":",
"self",
".",
"_managers",
"=",
"{",
"}",
"for",
"manager_class",
"in",
"MODEL_MANAGERS",
":",
"instance",
"=",
"manager_class",
"(",
"self",
")",
"if",
"not",
"instance",
".",
"forbid_registration",
"and",
"not... | Allows to access manager by model name - it is convenient, because HasOffers returns model names in responses. | [
"Allows",
"to",
"access",
"manager",
"by",
"model",
"name",
"-",
"it",
"is",
"convenient",
"because",
"HasOffers",
"returns",
"model",
"names",
"in",
"responses",
"."
] | train | https://github.com/Stranger6667/pyoffers/blob/9575d6cdc878096242268311a22cc5fdd4f64b37/pyoffers/api.py#L63-L79 |
Stranger6667/pyoffers | pyoffers/api.py | HasOffersAPI._call | def _call(self, target, method, target_class=None, single_result=True, raw=False, files=None, **kwargs):
"""
Low-level call to HasOffers API.
:param target_class: type of resulting object/objects.
"""
if target_class is None:
target_class = target
params = prepare_query_params(
NetworkToken=self.network_token,
NetworkId=self.network_id,
Target=target,
Method=method,
**kwargs
)
kwargs = {'url': self.endpoint, 'params': params, 'verify': self.verify, 'method': 'GET'}
if files:
kwargs.update({'method': 'POST', 'files': files})
self.logger.debug('Request parameters: %s', params)
response = self.session.request(**kwargs)
self.logger.debug('Response [%s]: %s', response.status_code, response.text)
response.raise_for_status()
data = response.json(object_pairs_hook=OrderedDict)
return self.handle_response(data, target=target_class, single_result=single_result, raw=raw) | python | def _call(self, target, method, target_class=None, single_result=True, raw=False, files=None, **kwargs):
"""
Low-level call to HasOffers API.
:param target_class: type of resulting object/objects.
"""
if target_class is None:
target_class = target
params = prepare_query_params(
NetworkToken=self.network_token,
NetworkId=self.network_id,
Target=target,
Method=method,
**kwargs
)
kwargs = {'url': self.endpoint, 'params': params, 'verify': self.verify, 'method': 'GET'}
if files:
kwargs.update({'method': 'POST', 'files': files})
self.logger.debug('Request parameters: %s', params)
response = self.session.request(**kwargs)
self.logger.debug('Response [%s]: %s', response.status_code, response.text)
response.raise_for_status()
data = response.json(object_pairs_hook=OrderedDict)
return self.handle_response(data, target=target_class, single_result=single_result, raw=raw) | [
"def",
"_call",
"(",
"self",
",",
"target",
",",
"method",
",",
"target_class",
"=",
"None",
",",
"single_result",
"=",
"True",
",",
"raw",
"=",
"False",
",",
"files",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"target_class",
"is",
"None"... | Low-level call to HasOffers API.
:param target_class: type of resulting object/objects. | [
"Low",
"-",
"level",
"call",
"to",
"HasOffers",
"API",
".",
":",
"param",
"target_class",
":",
"type",
"of",
"resulting",
"object",
"/",
"objects",
"."
] | train | https://github.com/Stranger6667/pyoffers/blob/9575d6cdc878096242268311a22cc5fdd4f64b37/pyoffers/api.py#L94-L118 |
Stranger6667/pyoffers | pyoffers/api.py | HasOffersAPI.handle_response | def handle_response(self, content, target=None, single_result=True, raw=False):
"""
Parses response, checks it.
"""
response = content['response']
self.check_errors(response)
data = response.get('data')
if is_empty(data):
return data
elif is_paginated(data):
if 'count' in data and not data['count']:
# Response is paginated, but is empty
return data['data']
data = data['data']
if raw:
return data
return self.init_all_objects(data, target=target, single_result=single_result) | python | def handle_response(self, content, target=None, single_result=True, raw=False):
"""
Parses response, checks it.
"""
response = content['response']
self.check_errors(response)
data = response.get('data')
if is_empty(data):
return data
elif is_paginated(data):
if 'count' in data and not data['count']:
# Response is paginated, but is empty
return data['data']
data = data['data']
if raw:
return data
return self.init_all_objects(data, target=target, single_result=single_result) | [
"def",
"handle_response",
"(",
"self",
",",
"content",
",",
"target",
"=",
"None",
",",
"single_result",
"=",
"True",
",",
"raw",
"=",
"False",
")",
":",
"response",
"=",
"content",
"[",
"'response'",
"]",
"self",
".",
"check_errors",
"(",
"response",
")... | Parses response, checks it. | [
"Parses",
"response",
"checks",
"it",
"."
] | train | https://github.com/Stranger6667/pyoffers/blob/9575d6cdc878096242268311a22cc5fdd4f64b37/pyoffers/api.py#L120-L140 |
Stranger6667/pyoffers | pyoffers/api.py | HasOffersAPI.init_all_objects | def init_all_objects(self, data, target=None, single_result=True):
"""
Initializes model instances from given data.
Returns single instance if single_result=True.
"""
if single_result:
return self.init_target_object(target, data)
return list(self.expand_models(target, data)) | python | def init_all_objects(self, data, target=None, single_result=True):
"""
Initializes model instances from given data.
Returns single instance if single_result=True.
"""
if single_result:
return self.init_target_object(target, data)
return list(self.expand_models(target, data)) | [
"def",
"init_all_objects",
"(",
"self",
",",
"data",
",",
"target",
"=",
"None",
",",
"single_result",
"=",
"True",
")",
":",
"if",
"single_result",
":",
"return",
"self",
".",
"init_target_object",
"(",
"target",
",",
"data",
")",
"return",
"list",
"(",
... | Initializes model instances from given data.
Returns single instance if single_result=True. | [
"Initializes",
"model",
"instances",
"from",
"given",
"data",
".",
"Returns",
"single",
"instance",
"if",
"single_result",
"=",
"True",
"."
] | train | https://github.com/Stranger6667/pyoffers/blob/9575d6cdc878096242268311a22cc5fdd4f64b37/pyoffers/api.py#L147-L154 |
Stranger6667/pyoffers | pyoffers/api.py | HasOffersAPI.init_target_object | def init_target_object(self, target, data):
"""
Initializes target object and assign extra objects to target as attributes
"""
target_object = self.init_single_object(target, data.pop(target, data))
for key, item in data.items():
key_alias = MANAGER_ALIASES.get(key, key)
if item:
# Item is an OrderedDict with 4 possible structure patterns:
# - Just an OrderedDict with (key - value)'s
# - OrderedDict with single (key - OrderedDict)
# - OrderedDict with multiple (key - OrderedDict)'s
# - String (like CreativeCode model)
if isinstance(item, str):
children = item
else:
first_key = list(item.keys())[0]
if isinstance(item[first_key], OrderedDict):
instances = item.values()
if len(instances) > 1:
children = [self.init_single_object(key_alias, instance) for instance in instances]
else:
children = self.init_single_object(key_alias, list(instances)[0])
else:
children = self.init_single_object(key_alias, item)
setattr(target_object, key.lower(), children)
else:
setattr(target_object, key.lower(), None)
return target_object | python | def init_target_object(self, target, data):
"""
Initializes target object and assign extra objects to target as attributes
"""
target_object = self.init_single_object(target, data.pop(target, data))
for key, item in data.items():
key_alias = MANAGER_ALIASES.get(key, key)
if item:
# Item is an OrderedDict with 4 possible structure patterns:
# - Just an OrderedDict with (key - value)'s
# - OrderedDict with single (key - OrderedDict)
# - OrderedDict with multiple (key - OrderedDict)'s
# - String (like CreativeCode model)
if isinstance(item, str):
children = item
else:
first_key = list(item.keys())[0]
if isinstance(item[first_key], OrderedDict):
instances = item.values()
if len(instances) > 1:
children = [self.init_single_object(key_alias, instance) for instance in instances]
else:
children = self.init_single_object(key_alias, list(instances)[0])
else:
children = self.init_single_object(key_alias, item)
setattr(target_object, key.lower(), children)
else:
setattr(target_object, key.lower(), None)
return target_object | [
"def",
"init_target_object",
"(",
"self",
",",
"target",
",",
"data",
")",
":",
"target_object",
"=",
"self",
".",
"init_single_object",
"(",
"target",
",",
"data",
".",
"pop",
"(",
"target",
",",
"data",
")",
")",
"for",
"key",
",",
"item",
"in",
"dat... | Initializes target object and assign extra objects to target as attributes | [
"Initializes",
"target",
"object",
"and",
"assign",
"extra",
"objects",
"to",
"target",
"as",
"attributes"
] | train | https://github.com/Stranger6667/pyoffers/blob/9575d6cdc878096242268311a22cc5fdd4f64b37/pyoffers/api.py#L156-L184 |
Stranger6667/pyoffers | pyoffers/api.py | HasOffersAPI.expand_models | def expand_models(self, target, data):
"""
Generates all objects from given data.
"""
if isinstance(data, dict):
data = data.values()
for chunk in data:
if target in chunk:
yield self.init_target_object(target, chunk)
else:
for key, item in chunk.items():
yield self.init_single_object(key, item) | python | def expand_models(self, target, data):
"""
Generates all objects from given data.
"""
if isinstance(data, dict):
data = data.values()
for chunk in data:
if target in chunk:
yield self.init_target_object(target, chunk)
else:
for key, item in chunk.items():
yield self.init_single_object(key, item) | [
"def",
"expand_models",
"(",
"self",
",",
"target",
",",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"data",
"=",
"data",
".",
"values",
"(",
")",
"for",
"chunk",
"in",
"data",
":",
"if",
"target",
"in",
"chunk",
":",
... | Generates all objects from given data. | [
"Generates",
"all",
"objects",
"from",
"given",
"data",
"."
] | train | https://github.com/Stranger6667/pyoffers/blob/9575d6cdc878096242268311a22cc5fdd4f64b37/pyoffers/api.py#L190-L201 |
theonion/django-bulbs | bulbs/contributions/utils.py | merge_roles | def merge_roles(dominant_name, deprecated_name):
"""
Merges a deprecated role into a dominant role.
"""
dominant_qs = ContributorRole.objects.filter(name=dominant_name)
if not dominant_qs.exists() or dominant_qs.count() != 1:
return
dominant = dominant_qs.first()
deprecated_qs = ContributorRole.objects.filter(name=deprecated_name)
if not deprecated_qs.exists() or deprecated_qs.count() != 1:
return
deprecated = deprecated_qs.first()
# Update Rates
if not dominant.flat_rates.exists() and deprecated.flat_rates.exists():
flat_rate = deprecated.flat_rates.first()
flat_rate.role = dominant
flat_rate.save()
if not dominant.hourly_rates.exists() and deprecated.hourly_rates.exists():
hourly_rate = deprecated.hourly_rates.first()
hourly_rate.role = dominant
hourly_rate.save()
for ft_rate in deprecated.feature_type_rates.all():
dom_ft_rate = dominant.feature_type_rates.filter(feature_type=ft_rate.feature_type)
if dom_ft_rate.exists() and dom_ft_rate.first().rate == 0:
dom_ft_rate.first().delete()
if not dom_ft_rate.exists():
ft_rate.role = dominant
ft_rate.save()
# Update contributions
for contribution in deprecated.contribution_set.all():
contribution.role = dominant
contribution.save()
# Update overrides
for override in deprecated.overrides.all():
dom_override_qs = dominant.overrides.filter(contributor=override.contributor)
if not dom_override_qs.exists():
override.role = dominant
override.save()
else:
dom_override = dom_override_qs.first()
for flat_override in override.override_flatrate.all():
flat_override.profile = dom_override
flat_override.save()
for hourly_override in override.override_hourly.all():
hourly_override.profile = dom_override
hourly_override.save()
for feature_type_override in override.override_feature_type.all():
feature_type_override.profile = dom_override
feature_type_override.save() | python | def merge_roles(dominant_name, deprecated_name):
"""
Merges a deprecated role into a dominant role.
"""
dominant_qs = ContributorRole.objects.filter(name=dominant_name)
if not dominant_qs.exists() or dominant_qs.count() != 1:
return
dominant = dominant_qs.first()
deprecated_qs = ContributorRole.objects.filter(name=deprecated_name)
if not deprecated_qs.exists() or deprecated_qs.count() != 1:
return
deprecated = deprecated_qs.first()
# Update Rates
if not dominant.flat_rates.exists() and deprecated.flat_rates.exists():
flat_rate = deprecated.flat_rates.first()
flat_rate.role = dominant
flat_rate.save()
if not dominant.hourly_rates.exists() and deprecated.hourly_rates.exists():
hourly_rate = deprecated.hourly_rates.first()
hourly_rate.role = dominant
hourly_rate.save()
for ft_rate in deprecated.feature_type_rates.all():
dom_ft_rate = dominant.feature_type_rates.filter(feature_type=ft_rate.feature_type)
if dom_ft_rate.exists() and dom_ft_rate.first().rate == 0:
dom_ft_rate.first().delete()
if not dom_ft_rate.exists():
ft_rate.role = dominant
ft_rate.save()
# Update contributions
for contribution in deprecated.contribution_set.all():
contribution.role = dominant
contribution.save()
# Update overrides
for override in deprecated.overrides.all():
dom_override_qs = dominant.overrides.filter(contributor=override.contributor)
if not dom_override_qs.exists():
override.role = dominant
override.save()
else:
dom_override = dom_override_qs.first()
for flat_override in override.override_flatrate.all():
flat_override.profile = dom_override
flat_override.save()
for hourly_override in override.override_hourly.all():
hourly_override.profile = dom_override
hourly_override.save()
for feature_type_override in override.override_feature_type.all():
feature_type_override.profile = dom_override
feature_type_override.save() | [
"def",
"merge_roles",
"(",
"dominant_name",
",",
"deprecated_name",
")",
":",
"dominant_qs",
"=",
"ContributorRole",
".",
"objects",
".",
"filter",
"(",
"name",
"=",
"dominant_name",
")",
"if",
"not",
"dominant_qs",
".",
"exists",
"(",
")",
"or",
"dominant_qs"... | Merges a deprecated role into a dominant role. | [
"Merges",
"a",
"deprecated",
"role",
"into",
"a",
"dominant",
"role",
"."
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/contributions/utils.py#L7-L62 |
gdestuynder/simple_bugzilla | bugzilla.py | Bugzilla.quick_search | def quick_search(self, terms):
'''Wrapper for search_bugs, for simple string searches'''
assert type(terms) is str
p = [{'quicksearch': terms}]
return self.search_bugs(p) | python | def quick_search(self, terms):
'''Wrapper for search_bugs, for simple string searches'''
assert type(terms) is str
p = [{'quicksearch': terms}]
return self.search_bugs(p) | [
"def",
"quick_search",
"(",
"self",
",",
"terms",
")",
":",
"assert",
"type",
"(",
"terms",
")",
"is",
"str",
"p",
"=",
"[",
"{",
"'quicksearch'",
":",
"terms",
"}",
"]",
"return",
"self",
".",
"search_bugs",
"(",
"p",
")"
] | Wrapper for search_bugs, for simple string searches | [
"Wrapper",
"for",
"search_bugs",
"for",
"simple",
"string",
"searches"
] | train | https://github.com/gdestuynder/simple_bugzilla/blob/c69766a81fa7960a8f2b22287968fa4787f1bcfe/bugzilla.py#L35-L39 |
gdestuynder/simple_bugzilla | bugzilla.py | Bugzilla.search_bugs | def search_bugs(self, terms):
'''http://bugzilla.readthedocs.org/en/latest/api/core/v1/bug.html#search-bugs
terms = [{'product': 'Infrastructure & Operations'}, {'status': 'NEW'}]'''
params = ''
for i in terms:
k = i.popitem()
params = '{p}&{new}={value}'.format(p=params, new=quote_url(k[0]),
value=quote_url(k[1]))
return DotDict(self._get('bug', params=params)) | python | def search_bugs(self, terms):
'''http://bugzilla.readthedocs.org/en/latest/api/core/v1/bug.html#search-bugs
terms = [{'product': 'Infrastructure & Operations'}, {'status': 'NEW'}]'''
params = ''
for i in terms:
k = i.popitem()
params = '{p}&{new}={value}'.format(p=params, new=quote_url(k[0]),
value=quote_url(k[1]))
return DotDict(self._get('bug', params=params)) | [
"def",
"search_bugs",
"(",
"self",
",",
"terms",
")",
":",
"params",
"=",
"''",
"for",
"i",
"in",
"terms",
":",
"k",
"=",
"i",
".",
"popitem",
"(",
")",
"params",
"=",
"'{p}&{new}={value}'",
".",
"format",
"(",
"p",
"=",
"params",
",",
"new",
"=",
... | http://bugzilla.readthedocs.org/en/latest/api/core/v1/bug.html#search-bugs
terms = [{'product': 'Infrastructure & Operations'}, {'status': 'NEW'}] | [
"http",
":",
"//",
"bugzilla",
".",
"readthedocs",
".",
"org",
"/",
"en",
"/",
"latest",
"/",
"api",
"/",
"core",
"/",
"v1",
"/",
"bug",
".",
"html#search",
"-",
"bugs",
"terms",
"=",
"[",
"{",
"product",
":",
"Infrastructure",
"&",
"Operations",
"}"... | train | https://github.com/gdestuynder/simple_bugzilla/blob/c69766a81fa7960a8f2b22287968fa4787f1bcfe/bugzilla.py#L41-L49 |
gdestuynder/simple_bugzilla | bugzilla.py | Bugzilla.put_attachment | def put_attachment(self, attachmentid, attachment_update):
'''http://bugzilla.readthedocs.org/en/latest/api/core/v1/attachment.html#update-attachment'''
assert type(attachment_update) is DotDict
if (not 'ids' in attachment_update):
attachment_update.ids = [attachmentid]
return self._put('bug/attachment/{attachmentid}'.format(attachmentid=attachmentid),
json.dumps(attachment_update)) | python | def put_attachment(self, attachmentid, attachment_update):
'''http://bugzilla.readthedocs.org/en/latest/api/core/v1/attachment.html#update-attachment'''
assert type(attachment_update) is DotDict
if (not 'ids' in attachment_update):
attachment_update.ids = [attachmentid]
return self._put('bug/attachment/{attachmentid}'.format(attachmentid=attachmentid),
json.dumps(attachment_update)) | [
"def",
"put_attachment",
"(",
"self",
",",
"attachmentid",
",",
"attachment_update",
")",
":",
"assert",
"type",
"(",
"attachment_update",
")",
"is",
"DotDict",
"if",
"(",
"not",
"'ids'",
"in",
"attachment_update",
")",
":",
"attachment_update",
".",
"ids",
"=... | http://bugzilla.readthedocs.org/en/latest/api/core/v1/attachment.html#update-attachment | [
"http",
":",
"//",
"bugzilla",
".",
"readthedocs",
".",
"org",
"/",
"en",
"/",
"latest",
"/",
"api",
"/",
"core",
"/",
"v1",
"/",
"attachment",
".",
"html#update",
"-",
"attachment"
] | train | https://github.com/gdestuynder/simple_bugzilla/blob/c69766a81fa7960a8f2b22287968fa4787f1bcfe/bugzilla.py#L68-L75 |
gdestuynder/simple_bugzilla | bugzilla.py | Bugzilla.put_bug | def put_bug(self, bugid, bug_update):
'''http://bugzilla.readthedocs.org/en/latest/api/core/v1/bug.html#update-bug'''
assert type(bug_update) is DotDict
if (not 'ids' in bug_update):
bug_update.ids = [bugid]
return self._put('bug/{bugid}'.format(bugid=bugid),
json.dumps(bug_update)) | python | def put_bug(self, bugid, bug_update):
'''http://bugzilla.readthedocs.org/en/latest/api/core/v1/bug.html#update-bug'''
assert type(bug_update) is DotDict
if (not 'ids' in bug_update):
bug_update.ids = [bugid]
return self._put('bug/{bugid}'.format(bugid=bugid),
json.dumps(bug_update)) | [
"def",
"put_bug",
"(",
"self",
",",
"bugid",
",",
"bug_update",
")",
":",
"assert",
"type",
"(",
"bug_update",
")",
"is",
"DotDict",
"if",
"(",
"not",
"'ids'",
"in",
"bug_update",
")",
":",
"bug_update",
".",
"ids",
"=",
"[",
"bugid",
"]",
"return",
... | http://bugzilla.readthedocs.org/en/latest/api/core/v1/bug.html#update-bug | [
"http",
":",
"//",
"bugzilla",
".",
"readthedocs",
".",
"org",
"/",
"en",
"/",
"latest",
"/",
"api",
"/",
"core",
"/",
"v1",
"/",
"bug",
".",
"html#update",
"-",
"bug"
] | train | https://github.com/gdestuynder/simple_bugzilla/blob/c69766a81fa7960a8f2b22287968fa4787f1bcfe/bugzilla.py#L77-L84 |
gdestuynder/simple_bugzilla | bugzilla.py | Bugzilla.post_attachment | def post_attachment(self, bugid, attachment):
'''http://bugzilla.readthedocs.org/en/latest/api/core/v1/attachment.html#create-attachment'''
assert type(attachment) is DotDict
assert 'data' in attachment
assert 'file_name' in attachment
assert 'summary' in attachment
if (not 'content_type' in attachment): attachment.content_type = 'text/plain'
attachment.ids = bugid
attachment.data = base64.standard_b64encode(bytearray(attachment.data, 'ascii')).decode('ascii')
return self._post('bug/{bugid}/attachment'.format(bugid=bugid), json.dumps(attachment)) | python | def post_attachment(self, bugid, attachment):
'''http://bugzilla.readthedocs.org/en/latest/api/core/v1/attachment.html#create-attachment'''
assert type(attachment) is DotDict
assert 'data' in attachment
assert 'file_name' in attachment
assert 'summary' in attachment
if (not 'content_type' in attachment): attachment.content_type = 'text/plain'
attachment.ids = bugid
attachment.data = base64.standard_b64encode(bytearray(attachment.data, 'ascii')).decode('ascii')
return self._post('bug/{bugid}/attachment'.format(bugid=bugid), json.dumps(attachment)) | [
"def",
"post_attachment",
"(",
"self",
",",
"bugid",
",",
"attachment",
")",
":",
"assert",
"type",
"(",
"attachment",
")",
"is",
"DotDict",
"assert",
"'data'",
"in",
"attachment",
"assert",
"'file_name'",
"in",
"attachment",
"assert",
"'summary'",
"in",
"atta... | http://bugzilla.readthedocs.org/en/latest/api/core/v1/attachment.html#create-attachment | [
"http",
":",
"//",
"bugzilla",
".",
"readthedocs",
".",
"org",
"/",
"en",
"/",
"latest",
"/",
"api",
"/",
"core",
"/",
"v1",
"/",
"attachment",
".",
"html#create",
"-",
"attachment"
] | train | https://github.com/gdestuynder/simple_bugzilla/blob/c69766a81fa7960a8f2b22287968fa4787f1bcfe/bugzilla.py#L86-L96 |
gdestuynder/simple_bugzilla | bugzilla.py | Bugzilla.post_bug | def post_bug(self, bug):
'''http://bugzilla.readthedocs.org/en/latest/api/core/v1/bug.html#create-bug'''
assert type(bug) is DotDict
assert 'product' in bug
assert 'component' in bug
assert 'summary' in bug
if (not 'version' in bug): bug.version = 'other'
if (not 'op_sys' in bug): bug.op_sys = 'All'
if (not 'platform' in bug): bug.platform = 'All'
return self._post('bug', json.dumps(bug)) | python | def post_bug(self, bug):
'''http://bugzilla.readthedocs.org/en/latest/api/core/v1/bug.html#create-bug'''
assert type(bug) is DotDict
assert 'product' in bug
assert 'component' in bug
assert 'summary' in bug
if (not 'version' in bug): bug.version = 'other'
if (not 'op_sys' in bug): bug.op_sys = 'All'
if (not 'platform' in bug): bug.platform = 'All'
return self._post('bug', json.dumps(bug)) | [
"def",
"post_bug",
"(",
"self",
",",
"bug",
")",
":",
"assert",
"type",
"(",
"bug",
")",
"is",
"DotDict",
"assert",
"'product'",
"in",
"bug",
"assert",
"'component'",
"in",
"bug",
"assert",
"'summary'",
"in",
"bug",
"if",
"(",
"not",
"'version'",
"in",
... | http://bugzilla.readthedocs.org/en/latest/api/core/v1/bug.html#create-bug | [
"http",
":",
"//",
"bugzilla",
".",
"readthedocs",
".",
"org",
"/",
"en",
"/",
"latest",
"/",
"api",
"/",
"core",
"/",
"v1",
"/",
"bug",
".",
"html#create",
"-",
"bug"
] | train | https://github.com/gdestuynder/simple_bugzilla/blob/c69766a81fa7960a8f2b22287968fa4787f1bcfe/bugzilla.py#L98-L108 |
gdestuynder/simple_bugzilla | bugzilla.py | Bugzilla.post_comment | def post_comment(self, bugid, comment):
'''http://bugzilla.readthedocs.org/en/latest/api/core/v1/comment.html#create-comments'''
data = {'id': bugid, "comment": comment}
return self._post('bug/{bugid}/comment'.format(bugid=bugid), json.dumps(data)) | python | def post_comment(self, bugid, comment):
'''http://bugzilla.readthedocs.org/en/latest/api/core/v1/comment.html#create-comments'''
data = {'id': bugid, "comment": comment}
return self._post('bug/{bugid}/comment'.format(bugid=bugid), json.dumps(data)) | [
"def",
"post_comment",
"(",
"self",
",",
"bugid",
",",
"comment",
")",
":",
"data",
"=",
"{",
"'id'",
":",
"bugid",
",",
"\"comment\"",
":",
"comment",
"}",
"return",
"self",
".",
"_post",
"(",
"'bug/{bugid}/comment'",
".",
"format",
"(",
"bugid",
"=",
... | http://bugzilla.readthedocs.org/en/latest/api/core/v1/comment.html#create-comments | [
"http",
":",
"//",
"bugzilla",
".",
"readthedocs",
".",
"org",
"/",
"en",
"/",
"latest",
"/",
"api",
"/",
"core",
"/",
"v1",
"/",
"comment",
".",
"html#create",
"-",
"comments"
] | train | https://github.com/gdestuynder/simple_bugzilla/blob/c69766a81fa7960a8f2b22287968fa4787f1bcfe/bugzilla.py#L110-L113 |
gdestuynder/simple_bugzilla | bugzilla.py | Bugzilla._get | def _get(self, q, params=''):
'''Generic GET wrapper including the api_key'''
if (q[-1] == '/'): q = q[:-1]
headers = {'Content-Type': 'application/json'}
r = requests.get('{url}{q}?api_key={key}{params}'.format(url=self.url, q=q, key=self.api_key, params=params),
headers=headers)
ret = DotDict(r.json())
if (not r.ok or ('error' in ret and ret.error == True)):
raise Exception(r.url, r.reason, r.status_code, r.json())
return DotDict(r.json()) | python | def _get(self, q, params=''):
'''Generic GET wrapper including the api_key'''
if (q[-1] == '/'): q = q[:-1]
headers = {'Content-Type': 'application/json'}
r = requests.get('{url}{q}?api_key={key}{params}'.format(url=self.url, q=q, key=self.api_key, params=params),
headers=headers)
ret = DotDict(r.json())
if (not r.ok or ('error' in ret and ret.error == True)):
raise Exception(r.url, r.reason, r.status_code, r.json())
return DotDict(r.json()) | [
"def",
"_get",
"(",
"self",
",",
"q",
",",
"params",
"=",
"''",
")",
":",
"if",
"(",
"q",
"[",
"-",
"1",
"]",
"==",
"'/'",
")",
":",
"q",
"=",
"q",
"[",
":",
"-",
"1",
"]",
"headers",
"=",
"{",
"'Content-Type'",
":",
"'application/json'",
"}"... | Generic GET wrapper including the api_key | [
"Generic",
"GET",
"wrapper",
"including",
"the",
"api_key"
] | train | https://github.com/gdestuynder/simple_bugzilla/blob/c69766a81fa7960a8f2b22287968fa4787f1bcfe/bugzilla.py#L115-L124 |
gdestuynder/simple_bugzilla | bugzilla.py | Bugzilla._post | def _post(self, q, payload='', params=''):
'''Generic POST wrapper including the api_key'''
if (q[-1] == '/'): q = q[:-1]
headers = {'Content-Type': 'application/json'}
r = requests.post('{url}{q}?api_key={key}{params}'.format(url=self.url, q=q, key=self.api_key, params=params),
headers=headers, data=payload)
ret = DotDict(r.json())
if (not r.ok or ('error' in ret and ret.error == True)):
raise Exception(r.url, r.reason, r.status_code, r.json())
return DotDict(r.json()) | python | def _post(self, q, payload='', params=''):
'''Generic POST wrapper including the api_key'''
if (q[-1] == '/'): q = q[:-1]
headers = {'Content-Type': 'application/json'}
r = requests.post('{url}{q}?api_key={key}{params}'.format(url=self.url, q=q, key=self.api_key, params=params),
headers=headers, data=payload)
ret = DotDict(r.json())
if (not r.ok or ('error' in ret and ret.error == True)):
raise Exception(r.url, r.reason, r.status_code, r.json())
return DotDict(r.json()) | [
"def",
"_post",
"(",
"self",
",",
"q",
",",
"payload",
"=",
"''",
",",
"params",
"=",
"''",
")",
":",
"if",
"(",
"q",
"[",
"-",
"1",
"]",
"==",
"'/'",
")",
":",
"q",
"=",
"q",
"[",
":",
"-",
"1",
"]",
"headers",
"=",
"{",
"'Content-Type'",
... | Generic POST wrapper including the api_key | [
"Generic",
"POST",
"wrapper",
"including",
"the",
"api_key"
] | train | https://github.com/gdestuynder/simple_bugzilla/blob/c69766a81fa7960a8f2b22287968fa4787f1bcfe/bugzilla.py#L126-L135 |
lordmauve/lepton | examples/games/bonk/game.py | game_system.bind_objects | def bind_objects(self, *objects):
"""Bind one or more objects"""
self.control.bind_keys(objects)
self.objects += objects | python | def bind_objects(self, *objects):
"""Bind one or more objects"""
self.control.bind_keys(objects)
self.objects += objects | [
"def",
"bind_objects",
"(",
"self",
",",
"*",
"objects",
")",
":",
"self",
".",
"control",
".",
"bind_keys",
"(",
"objects",
")",
"self",
".",
"objects",
"+=",
"objects"
] | Bind one or more objects | [
"Bind",
"one",
"or",
"more",
"objects"
] | train | https://github.com/lordmauve/lepton/blob/bf03f2c20ea8c51ade632f692d0a21e520fbba7c/examples/games/bonk/game.py#L53-L56 |
lordmauve/lepton | examples/games/bonk/game.py | game_system.update | def update(self, time_delta):
"""Update all sprites in the system. time_delta is the
time since the last update (in arbitrary time units).
This method can be conveniently scheduled using the Pyglet
scheduler method: pyglet.clock.schedule_interval
"""
self.control.update(self, time_delta)
for object in self.objects:
object.update(time_delta)
# object.sprite.last_position = object.sprite.position
# object.sprite.last_velocity = object.sprite.velocity
# for group in self:
for controller in self.controllers:
controller(time_delta, self) | python | def update(self, time_delta):
"""Update all sprites in the system. time_delta is the
time since the last update (in arbitrary time units).
This method can be conveniently scheduled using the Pyglet
scheduler method: pyglet.clock.schedule_interval
"""
self.control.update(self, time_delta)
for object in self.objects:
object.update(time_delta)
# object.sprite.last_position = object.sprite.position
# object.sprite.last_velocity = object.sprite.velocity
# for group in self:
for controller in self.controllers:
controller(time_delta, self) | [
"def",
"update",
"(",
"self",
",",
"time_delta",
")",
":",
"self",
".",
"control",
".",
"update",
"(",
"self",
",",
"time_delta",
")",
"for",
"object",
"in",
"self",
".",
"objects",
":",
"object",
".",
"update",
"(",
"time_delta",
")",
"# object.sprite.l... | Update all sprites in the system. time_delta is the
time since the last update (in arbitrary time units).
This method can be conveniently scheduled using the Pyglet
scheduler method: pyglet.clock.schedule_interval | [
"Update",
"all",
"sprites",
"in",
"the",
"system",
".",
"time_delta",
"is",
"the",
"time",
"since",
"the",
"last",
"update",
"(",
"in",
"arbitrary",
"time",
"units",
")",
".",
"This",
"method",
"can",
"be",
"conveniently",
"scheduled",
"using",
"the",
"Pyg... | train | https://github.com/lordmauve/lepton/blob/bf03f2c20ea8c51ade632f692d0a21e520fbba7c/examples/games/bonk/game.py#L94-L109 |
lordmauve/lepton | examples/games/bonk/game.py | game_system.draw | def draw(self):
"""Draw all the sprites in the system using their renderers.
This method is convenient to call from you Pyglet window's
on_draw handler to redraw particles when needed.
"""
glPushAttrib(GL_ALL_ATTRIB_BITS)
self.draw_score()
for sprite in self:
sprite.draw()
glPopAttrib() | python | def draw(self):
"""Draw all the sprites in the system using their renderers.
This method is convenient to call from you Pyglet window's
on_draw handler to redraw particles when needed.
"""
glPushAttrib(GL_ALL_ATTRIB_BITS)
self.draw_score()
for sprite in self:
sprite.draw()
glPopAttrib() | [
"def",
"draw",
"(",
"self",
")",
":",
"glPushAttrib",
"(",
"GL_ALL_ATTRIB_BITS",
")",
"self",
".",
"draw_score",
"(",
")",
"for",
"sprite",
"in",
"self",
":",
"sprite",
".",
"draw",
"(",
")",
"glPopAttrib",
"(",
")"
] | Draw all the sprites in the system using their renderers.
This method is convenient to call from you Pyglet window's
on_draw handler to redraw particles when needed. | [
"Draw",
"all",
"the",
"sprites",
"in",
"the",
"system",
"using",
"their",
"renderers",
".",
"This",
"method",
"is",
"convenient",
"to",
"call",
"from",
"you",
"Pyglet",
"window",
"s",
"on_draw",
"handler",
"to",
"redraw",
"particles",
"when",
"needed",
"."
] | train | https://github.com/lordmauve/lepton/blob/bf03f2c20ea8c51ade632f692d0a21e520fbba7c/examples/games/bonk/game.py#L111-L121 |
lordmauve/lepton | examples/games/bonk/game.py | ball.reset_ball | def reset_ball(self, x, y):
"""reset ball to set location on the screen"""
self.sprite.position.x = x
self.sprite.position.y = y | python | def reset_ball(self, x, y):
"""reset ball to set location on the screen"""
self.sprite.position.x = x
self.sprite.position.y = y | [
"def",
"reset_ball",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"self",
".",
"sprite",
".",
"position",
".",
"x",
"=",
"x",
"self",
".",
"sprite",
".",
"position",
".",
"y",
"=",
"y"
] | reset ball to set location on the screen | [
"reset",
"ball",
"to",
"set",
"location",
"on",
"the",
"screen"
] | train | https://github.com/lordmauve/lepton/blob/bf03f2c20ea8c51ade632f692d0a21e520fbba7c/examples/games/bonk/game.py#L246-L249 |
lordmauve/lepton | examples/games/bonk/game.py | ball.update | def update(self, td):
"""Update state of ball"""
self.sprite.last_position = self.sprite.position
self.sprite.last_velocity = self.sprite.velocity
if self.particle_group != None:
self.update_particle_group(td) | python | def update(self, td):
"""Update state of ball"""
self.sprite.last_position = self.sprite.position
self.sprite.last_velocity = self.sprite.velocity
if self.particle_group != None:
self.update_particle_group(td) | [
"def",
"update",
"(",
"self",
",",
"td",
")",
":",
"self",
".",
"sprite",
".",
"last_position",
"=",
"self",
".",
"sprite",
".",
"position",
"self",
".",
"sprite",
".",
"last_velocity",
"=",
"self",
".",
"sprite",
".",
"velocity",
"if",
"self",
".",
... | Update state of ball | [
"Update",
"state",
"of",
"ball"
] | train | https://github.com/lordmauve/lepton/blob/bf03f2c20ea8c51ade632f692d0a21e520fbba7c/examples/games/bonk/game.py#L263-L268 |
lordmauve/lepton | examples/games/bonk/game.py | Box.generate | def generate(self):
"""Return a random point inside the box"""
x, y, z = self.point1
return (x + self.size_x * random(),
y + self.size_y * random(),
z + self.size_z * random()) | python | def generate(self):
"""Return a random point inside the box"""
x, y, z = self.point1
return (x + self.size_x * random(),
y + self.size_y * random(),
z + self.size_z * random()) | [
"def",
"generate",
"(",
"self",
")",
":",
"x",
",",
"y",
",",
"z",
"=",
"self",
".",
"point1",
"return",
"(",
"x",
"+",
"self",
".",
"size_x",
"*",
"random",
"(",
")",
",",
"y",
"+",
"self",
".",
"size_y",
"*",
"random",
"(",
")",
",",
"z",
... | Return a random point inside the box | [
"Return",
"a",
"random",
"point",
"inside",
"the",
"box"
] | train | https://github.com/lordmauve/lepton/blob/bf03f2c20ea8c51ade632f692d0a21e520fbba7c/examples/games/bonk/game.py#L475-L480 |
lordmauve/lepton | examples/games/bonk/game.py | Box.intersect | def intersect(self, start_point, end_point):
"""Intersect the line segment with the box return the first
intersection point and normal vector pointing into space from
the box side intersected.
If the line does not intersect, or lies completely in one side
of the box return (None, None)
"""
sx, sy, sz = start_point
ex, ey, ez = end_point
p1x, p1y, p1z = self.point1
p2x, p2y, p2z = self.point2
start_inside = start_point in self
end_inside = end_point in self
if start_inside != end_inside:
if (end_inside and sy > p2y) or (start_inside and ey >= p2y) and (ey != sy):
# Test for itersection with bottom face
t = (sy - p2y) / (ey - sy)
ix = (ex - sx) * t + sx
iy = p2y
iz = (ez - sz) * t + sz
if p1x <= ix <= p2x and p1z <= iz <= p2z:
return (ix, iy, iz), (0.0, (sy > p2y) * 2.0 - 1.0, 0.0)
if (end_inside and sx < p1x) or (start_inside and ex <= p1x) and (ex != sx):
# Test for itersection with left face
t = (sx - p1x) / (ex - sx)
ix = p1x
iy = (ey - sy) * t + sy
iz = (ez - sz) * t + sz
if p1y <= iy <= p2y and p1z <= iz <= p2z:
return (ix, iy, iz), ((sx > p1x) * 2.0 - 1.0, 0.0, 0.0)
if (end_inside and sy < p1y) or (start_inside and ey <= p1y) and (ey != sy):
# Test for itersection with top face
t = (sy - p1y) / (ey - sy)
ix = (ex - sx) * t + sx
iy = p1y
iz = (ez - sz) * t + sz
if p1x <= ix <= p2x and p1z <= iz <= p2z:
return (ix, iy, iz), (0.0, (sy > p1y) * 2.0 - 1.0, 0.0)
if (end_inside and sx > p2x) or (start_inside and ex >= p2x) and (ex != sx):
# Test for itersection with right face
t = (sx - p2x) / (ex - sx)
ix = p2x
iy = (ey - sy) * t + sy
iz = (ez - sz) * t + sz
if p1y <= iy <= p2y and p1z <= iz <= p2z:
return (ix, iy, iz), ((sx > p2x) * 2.0 - 1.0, 0.0, 0.0)
if (end_inside and sz > p2z) or (start_inside and ez >= p2z) and (ez != sz):
# Test for itersection with far face
t = (sz - p2z) / (ez - sz)
ix = (ex - sx) * t + sx
iy = (ey - sy) * t + sy
iz = p2z
if p1y <= iy <= p2y and p1x <= ix <= p2x:
return (ix, iy, iz), (0.0, 0.0, (sz > p2z) * 2.0 - 1.0)
if (end_inside and sz < p1z) or (start_inside and ez <= p1z) and (ez != sz):
# Test for itersection with near face
t = (sz - p1z) / (ez - sz)
ix = (ex - sx) * t + sx
iy = (ey - sy) * t + sy
iz = p1z
if p1y <= iy <= p2y and p1x <= ix <= p2x:
return (ix, iy, iz), (0.0, 0.0, (sz > p1z) * 2.0 - 1.0)
return None, None | python | def intersect(self, start_point, end_point):
"""Intersect the line segment with the box return the first
intersection point and normal vector pointing into space from
the box side intersected.
If the line does not intersect, or lies completely in one side
of the box return (None, None)
"""
sx, sy, sz = start_point
ex, ey, ez = end_point
p1x, p1y, p1z = self.point1
p2x, p2y, p2z = self.point2
start_inside = start_point in self
end_inside = end_point in self
if start_inside != end_inside:
if (end_inside and sy > p2y) or (start_inside and ey >= p2y) and (ey != sy):
# Test for itersection with bottom face
t = (sy - p2y) / (ey - sy)
ix = (ex - sx) * t + sx
iy = p2y
iz = (ez - sz) * t + sz
if p1x <= ix <= p2x and p1z <= iz <= p2z:
return (ix, iy, iz), (0.0, (sy > p2y) * 2.0 - 1.0, 0.0)
if (end_inside and sx < p1x) or (start_inside and ex <= p1x) and (ex != sx):
# Test for itersection with left face
t = (sx - p1x) / (ex - sx)
ix = p1x
iy = (ey - sy) * t + sy
iz = (ez - sz) * t + sz
if p1y <= iy <= p2y and p1z <= iz <= p2z:
return (ix, iy, iz), ((sx > p1x) * 2.0 - 1.0, 0.0, 0.0)
if (end_inside and sy < p1y) or (start_inside and ey <= p1y) and (ey != sy):
# Test for itersection with top face
t = (sy - p1y) / (ey - sy)
ix = (ex - sx) * t + sx
iy = p1y
iz = (ez - sz) * t + sz
if p1x <= ix <= p2x and p1z <= iz <= p2z:
return (ix, iy, iz), (0.0, (sy > p1y) * 2.0 - 1.0, 0.0)
if (end_inside and sx > p2x) or (start_inside and ex >= p2x) and (ex != sx):
# Test for itersection with right face
t = (sx - p2x) / (ex - sx)
ix = p2x
iy = (ey - sy) * t + sy
iz = (ez - sz) * t + sz
if p1y <= iy <= p2y and p1z <= iz <= p2z:
return (ix, iy, iz), ((sx > p2x) * 2.0 - 1.0, 0.0, 0.0)
if (end_inside and sz > p2z) or (start_inside and ez >= p2z) and (ez != sz):
# Test for itersection with far face
t = (sz - p2z) / (ez - sz)
ix = (ex - sx) * t + sx
iy = (ey - sy) * t + sy
iz = p2z
if p1y <= iy <= p2y and p1x <= ix <= p2x:
return (ix, iy, iz), (0.0, 0.0, (sz > p2z) * 2.0 - 1.0)
if (end_inside and sz < p1z) or (start_inside and ez <= p1z) and (ez != sz):
# Test for itersection with near face
t = (sz - p1z) / (ez - sz)
ix = (ex - sx) * t + sx
iy = (ey - sy) * t + sy
iz = p1z
if p1y <= iy <= p2y and p1x <= ix <= p2x:
return (ix, iy, iz), (0.0, 0.0, (sz > p1z) * 2.0 - 1.0)
return None, None | [
"def",
"intersect",
"(",
"self",
",",
"start_point",
",",
"end_point",
")",
":",
"sx",
",",
"sy",
",",
"sz",
"=",
"start_point",
"ex",
",",
"ey",
",",
"ez",
"=",
"end_point",
"p1x",
",",
"p1y",
",",
"p1z",
"=",
"self",
".",
"point1",
"p2x",
",",
... | Intersect the line segment with the box return the first
intersection point and normal vector pointing into space from
the box side intersected.
If the line does not intersect, or lies completely in one side
of the box return (None, None) | [
"Intersect",
"the",
"line",
"segment",
"with",
"the",
"box",
"return",
"the",
"first",
"intersection",
"point",
"and",
"normal",
"vector",
"pointing",
"into",
"space",
"from",
"the",
"box",
"side",
"intersected",
".",
"If",
"the",
"line",
"does",
"not",
"int... | train | https://github.com/lordmauve/lepton/blob/bf03f2c20ea8c51ade632f692d0a21e520fbba7c/examples/games/bonk/game.py#L505-L568 |
theonion/django-bulbs | bulbs/content/custom_search.py | custom_search_model | def custom_search_model(model, query, preview=False, published=False,
id_field="id", sort_pinned=True, field_map={}):
"""Filter a model with the given filter.
`field_map` translates incoming field names to the appropriate ES names.
"""
if preview:
func = preview_filter_from_query
else:
func = filter_from_query
f = func(query, id_field=id_field, field_map=field_map)
# filter by published
if published:
if f:
f &= Range(published={"lte": timezone.now()})
else:
f = Range(published={"lte": timezone.now()})
qs = model.search_objects.search(published=False)
if f:
qs = qs.filter(f)
# possibly include a text query
if query.get("query"):
qs = qs.query("match", _all=query["query"])
# set up pinned ids
pinned_ids = query.get("pinned_ids")
if pinned_ids and sort_pinned:
pinned_query = es_query.FunctionScore(
boost_mode="multiply",
functions=[{
"filter": Terms(id=pinned_ids),
"weight": 2
}]
)
qs = qs.query(pinned_query)
qs = qs.sort("_score", "-published")
else:
qs = qs.sort("-published")
return qs | python | def custom_search_model(model, query, preview=False, published=False,
id_field="id", sort_pinned=True, field_map={}):
"""Filter a model with the given filter.
`field_map` translates incoming field names to the appropriate ES names.
"""
if preview:
func = preview_filter_from_query
else:
func = filter_from_query
f = func(query, id_field=id_field, field_map=field_map)
# filter by published
if published:
if f:
f &= Range(published={"lte": timezone.now()})
else:
f = Range(published={"lte": timezone.now()})
qs = model.search_objects.search(published=False)
if f:
qs = qs.filter(f)
# possibly include a text query
if query.get("query"):
qs = qs.query("match", _all=query["query"])
# set up pinned ids
pinned_ids = query.get("pinned_ids")
if pinned_ids and sort_pinned:
pinned_query = es_query.FunctionScore(
boost_mode="multiply",
functions=[{
"filter": Terms(id=pinned_ids),
"weight": 2
}]
)
qs = qs.query(pinned_query)
qs = qs.sort("_score", "-published")
else:
qs = qs.sort("-published")
return qs | [
"def",
"custom_search_model",
"(",
"model",
",",
"query",
",",
"preview",
"=",
"False",
",",
"published",
"=",
"False",
",",
"id_field",
"=",
"\"id\"",
",",
"sort_pinned",
"=",
"True",
",",
"field_map",
"=",
"{",
"}",
")",
":",
"if",
"preview",
":",
"f... | Filter a model with the given filter.
`field_map` translates incoming field names to the appropriate ES names. | [
"Filter",
"a",
"model",
"with",
"the",
"given",
"filter",
"."
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/content/custom_search.py#L41-L82 |
theonion/django-bulbs | bulbs/content/custom_search.py | preview_filter_from_query | def preview_filter_from_query(query, id_field="id", field_map={}):
"""This filter includes the "excluded_ids" so they still show up in the editor."""
f = groups_filter_from_query(query, field_map=field_map)
# NOTE: we don't exclude the excluded ids here so they show up in the editor
# include these, please
included_ids = query.get("included_ids")
if included_ids:
if f:
f |= Terms(pk=included_ids)
else:
f = Terms(pk=included_ids)
return f | python | def preview_filter_from_query(query, id_field="id", field_map={}):
"""This filter includes the "excluded_ids" so they still show up in the editor."""
f = groups_filter_from_query(query, field_map=field_map)
# NOTE: we don't exclude the excluded ids here so they show up in the editor
# include these, please
included_ids = query.get("included_ids")
if included_ids:
if f:
f |= Terms(pk=included_ids)
else:
f = Terms(pk=included_ids)
return f | [
"def",
"preview_filter_from_query",
"(",
"query",
",",
"id_field",
"=",
"\"id\"",
",",
"field_map",
"=",
"{",
"}",
")",
":",
"f",
"=",
"groups_filter_from_query",
"(",
"query",
",",
"field_map",
"=",
"field_map",
")",
"# NOTE: we don't exclude the excluded ids here ... | This filter includes the "excluded_ids" so they still show up in the editor. | [
"This",
"filter",
"includes",
"the",
"excluded_ids",
"so",
"they",
"still",
"show",
"up",
"in",
"the",
"editor",
"."
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/content/custom_search.py#L85-L96 |
theonion/django-bulbs | bulbs/content/custom_search.py | filter_from_query | def filter_from_query(query, id_field="id", field_map={}):
"""This returns a filter which actually filters out everything, unlike the
preview filter which includes excluded_ids for UI purposes.
"""
f = groups_filter_from_query(query, field_map=field_map)
excluded_ids = query.get("excluded_ids")
included_ids = query.get("included_ids")
if included_ids: # include these, please
if f is None:
f = Terms(pk=included_ids)
else:
f |= Terms(pk=included_ids)
if excluded_ids: # exclude these
if f is None:
f = MatchAll()
f &= ~Terms(pk=excluded_ids)
return f | python | def filter_from_query(query, id_field="id", field_map={}):
"""This returns a filter which actually filters out everything, unlike the
preview filter which includes excluded_ids for UI purposes.
"""
f = groups_filter_from_query(query, field_map=field_map)
excluded_ids = query.get("excluded_ids")
included_ids = query.get("included_ids")
if included_ids: # include these, please
if f is None:
f = Terms(pk=included_ids)
else:
f |= Terms(pk=included_ids)
if excluded_ids: # exclude these
if f is None:
f = MatchAll()
f &= ~Terms(pk=excluded_ids)
return f | [
"def",
"filter_from_query",
"(",
"query",
",",
"id_field",
"=",
"\"id\"",
",",
"field_map",
"=",
"{",
"}",
")",
":",
"f",
"=",
"groups_filter_from_query",
"(",
"query",
",",
"field_map",
"=",
"field_map",
")",
"excluded_ids",
"=",
"query",
".",
"get",
"(",... | This returns a filter which actually filters out everything, unlike the
preview filter which includes excluded_ids for UI purposes. | [
"This",
"returns",
"a",
"filter",
"which",
"actually",
"filters",
"out",
"everything",
"unlike",
"the",
"preview",
"filter",
"which",
"includes",
"excluded_ids",
"for",
"UI",
"purposes",
"."
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/content/custom_search.py#L99-L118 |
theonion/django-bulbs | bulbs/content/custom_search.py | get_condition_filter | def get_condition_filter(condition, field_map={}):
"""
Return the appropriate filter for a given group condition.
# TODO: integrate this into groups_filter_from_query function.
"""
field_name = condition.get("field")
field_name = field_map.get(field_name, field_name)
operation = condition["type"]
values = condition["values"]
condition_filter = MatchAll()
if values:
values = [v["value"] for v in values]
if operation == "all":
for value in values:
if "." in field_name:
path = field_name.split(".")[0]
condition_filter &= Nested(path=path, filter=Term(**{field_name: value}))
else:
condition_filter &= Term(**{field_name: value})
elif operation == "any":
if "." in field_name:
path = field_name.split(".")[0]
condition_filter &= Nested(path=path, filter=Terms(**{field_name: values}))
else:
condition_filter &= Terms(**{field_name: values})
elif operation == "none":
if "." in field_name:
path = field_name.split(".")[0]
condition_filter &= ~Nested(path=path, filter=Terms(**{field_name: values}))
else:
condition_filter &= ~Terms(**{field_name: values})
else:
raise ValueError(
"""ES conditions must be one of the following values: ['all', 'any', 'none']"""
)
return condition_filter | python | def get_condition_filter(condition, field_map={}):
"""
Return the appropriate filter for a given group condition.
# TODO: integrate this into groups_filter_from_query function.
"""
field_name = condition.get("field")
field_name = field_map.get(field_name, field_name)
operation = condition["type"]
values = condition["values"]
condition_filter = MatchAll()
if values:
values = [v["value"] for v in values]
if operation == "all":
for value in values:
if "." in field_name:
path = field_name.split(".")[0]
condition_filter &= Nested(path=path, filter=Term(**{field_name: value}))
else:
condition_filter &= Term(**{field_name: value})
elif operation == "any":
if "." in field_name:
path = field_name.split(".")[0]
condition_filter &= Nested(path=path, filter=Terms(**{field_name: values}))
else:
condition_filter &= Terms(**{field_name: values})
elif operation == "none":
if "." in field_name:
path = field_name.split(".")[0]
condition_filter &= ~Nested(path=path, filter=Terms(**{field_name: values}))
else:
condition_filter &= ~Terms(**{field_name: values})
else:
raise ValueError(
"""ES conditions must be one of the following values: ['all', 'any', 'none']"""
)
return condition_filter | [
"def",
"get_condition_filter",
"(",
"condition",
",",
"field_map",
"=",
"{",
"}",
")",
":",
"field_name",
"=",
"condition",
".",
"get",
"(",
"\"field\"",
")",
"field_name",
"=",
"field_map",
".",
"get",
"(",
"field_name",
",",
"field_name",
")",
"operation",... | Return the appropriate filter for a given group condition.
# TODO: integrate this into groups_filter_from_query function. | [
"Return",
"the",
"appropriate",
"filter",
"for",
"a",
"given",
"group",
"condition",
"."
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/content/custom_search.py#L121-L159 |
theonion/django-bulbs | bulbs/content/custom_search.py | groups_filter_from_query | def groups_filter_from_query(query, field_map={}):
"""Creates an F object for the groups of a search query."""
f = None
# filter groups
for group in query.get("groups", []):
group_f = MatchAll()
for condition in group.get("conditions", []):
field_name = condition["field"]
field_name = field_map.get(field_name, field_name)
operation = condition["type"]
values = condition["values"]
if values:
values = [v["value"] for v in values]
if operation == "all":
# NOTE: is there a better way to express this?
for value in values:
if "." in field_name:
path = field_name.split(".")[0]
group_f &= Nested(path=path, filter=Term(**{field_name: value}))
else:
group_f &= Term(**{field_name: value})
elif operation == "any":
if "." in field_name:
path = field_name.split(".")[0]
group_f &= Nested(path=path, filter=Terms(**{field_name: values}))
else:
group_f &= Terms(**{field_name: values})
elif operation == "none":
if "." in field_name:
path = field_name.split(".")[0]
group_f &= ~Nested(path=path, filter=Terms(**{field_name: values}))
else:
group_f &= ~Terms(**{field_name: values})
date_range = group.get("time")
if date_range:
group_f &= date_range_filter(date_range)
if f:
f |= group_f
else:
f = group_f
return f | python | def groups_filter_from_query(query, field_map={}):
"""Creates an F object for the groups of a search query."""
f = None
# filter groups
for group in query.get("groups", []):
group_f = MatchAll()
for condition in group.get("conditions", []):
field_name = condition["field"]
field_name = field_map.get(field_name, field_name)
operation = condition["type"]
values = condition["values"]
if values:
values = [v["value"] for v in values]
if operation == "all":
# NOTE: is there a better way to express this?
for value in values:
if "." in field_name:
path = field_name.split(".")[0]
group_f &= Nested(path=path, filter=Term(**{field_name: value}))
else:
group_f &= Term(**{field_name: value})
elif operation == "any":
if "." in field_name:
path = field_name.split(".")[0]
group_f &= Nested(path=path, filter=Terms(**{field_name: values}))
else:
group_f &= Terms(**{field_name: values})
elif operation == "none":
if "." in field_name:
path = field_name.split(".")[0]
group_f &= ~Nested(path=path, filter=Terms(**{field_name: values}))
else:
group_f &= ~Terms(**{field_name: values})
date_range = group.get("time")
if date_range:
group_f &= date_range_filter(date_range)
if f:
f |= group_f
else:
f = group_f
return f | [
"def",
"groups_filter_from_query",
"(",
"query",
",",
"field_map",
"=",
"{",
"}",
")",
":",
"f",
"=",
"None",
"# filter groups",
"for",
"group",
"in",
"query",
".",
"get",
"(",
"\"groups\"",
",",
"[",
"]",
")",
":",
"group_f",
"=",
"MatchAll",
"(",
")"... | Creates an F object for the groups of a search query. | [
"Creates",
"an",
"F",
"object",
"for",
"the",
"groups",
"of",
"a",
"search",
"query",
"."
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/content/custom_search.py#L162-L203 |
theonion/django-bulbs | bulbs/content/custom_search.py | date_range_filter | def date_range_filter(range_name):
"""Create a filter from a named date range."""
filter_days = list(filter(
lambda time: time["label"] == range_name,
settings.CUSTOM_SEARCH_TIME_PERIODS))
num_days = filter_days[0]["days"] if len(filter_days) else None
if num_days:
dt = timedelta(num_days)
start_time = timezone.now() - dt
return Range(published={"gte": start_time})
return MatchAll() | python | def date_range_filter(range_name):
"""Create a filter from a named date range."""
filter_days = list(filter(
lambda time: time["label"] == range_name,
settings.CUSTOM_SEARCH_TIME_PERIODS))
num_days = filter_days[0]["days"] if len(filter_days) else None
if num_days:
dt = timedelta(num_days)
start_time = timezone.now() - dt
return Range(published={"gte": start_time})
return MatchAll() | [
"def",
"date_range_filter",
"(",
"range_name",
")",
":",
"filter_days",
"=",
"list",
"(",
"filter",
"(",
"lambda",
"time",
":",
"time",
"[",
"\"label\"",
"]",
"==",
"range_name",
",",
"settings",
".",
"CUSTOM_SEARCH_TIME_PERIODS",
")",
")",
"num_days",
"=",
... | Create a filter from a named date range. | [
"Create",
"a",
"filter",
"from",
"a",
"named",
"date",
"range",
"."
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/content/custom_search.py#L206-L218 |
arcturial/clickatell-python | clickatell/rest/__init__.py | Rest.request | def request(self, action, data={}, headers={}, method='GET'):
"""
Append the REST headers to every request
"""
headers = {
"Authorization": "Bearer " + self.token,
"Content-Type": "application/json",
"X-Version": "1",
"Accept": "application/json"
}
return Transport.request(self, action, data, headers, method) | python | def request(self, action, data={}, headers={}, method='GET'):
"""
Append the REST headers to every request
"""
headers = {
"Authorization": "Bearer " + self.token,
"Content-Type": "application/json",
"X-Version": "1",
"Accept": "application/json"
}
return Transport.request(self, action, data, headers, method) | [
"def",
"request",
"(",
"self",
",",
"action",
",",
"data",
"=",
"{",
"}",
",",
"headers",
"=",
"{",
"}",
",",
"method",
"=",
"'GET'",
")",
":",
"headers",
"=",
"{",
"\"Authorization\"",
":",
"\"Bearer \"",
"+",
"self",
".",
"token",
",",
"\"Content-T... | Append the REST headers to every request | [
"Append",
"the",
"REST",
"headers",
"to",
"every",
"request"
] | train | https://github.com/arcturial/clickatell-python/blob/4a554c28edaf2e5d0d9e81b4c9415241bfd61d00/clickatell/rest/__init__.py#L18-L29 |
arcturial/clickatell-python | clickatell/rest/__init__.py | Rest.sendMessage | def sendMessage(self, to, message, extra={}):
"""
If the 'to' parameter is a single entry, we will parse it into a list.
We will merge default values into the request data and the extra parameters
provided by the user.
"""
to = to if isinstance(to, list) else [to]
to = [str(num) for num in to]
data = {'to': to, 'text': message}
data = self.merge(data, {'callback': 7, 'mo': 1}, extra)
content = self.parseRest(self.request('rest/message', data, {}, 'POST'));
result = []
# Messages in the REST response will contain errors on the message entry itself.
for entry in content['message']:
entry = self.merge({'apiMessageId': False, 'to': data['to'][0], 'error': False, 'errorCode': False}, entry)
result.append({
'id': entry['apiMessageId'].encode('utf-8'),
'destination': entry['to'].encode('utf-8'),
'error': entry['error']['description'].encode('utf-8') if entry['error'] != False else False,
'errorCode': entry['error']['code'].encode('utf-8') if entry['error'] != False else False
});
return result | python | def sendMessage(self, to, message, extra={}):
"""
If the 'to' parameter is a single entry, we will parse it into a list.
We will merge default values into the request data and the extra parameters
provided by the user.
"""
to = to if isinstance(to, list) else [to]
to = [str(num) for num in to]
data = {'to': to, 'text': message}
data = self.merge(data, {'callback': 7, 'mo': 1}, extra)
content = self.parseRest(self.request('rest/message', data, {}, 'POST'));
result = []
# Messages in the REST response will contain errors on the message entry itself.
for entry in content['message']:
entry = self.merge({'apiMessageId': False, 'to': data['to'][0], 'error': False, 'errorCode': False}, entry)
result.append({
'id': entry['apiMessageId'].encode('utf-8'),
'destination': entry['to'].encode('utf-8'),
'error': entry['error']['description'].encode('utf-8') if entry['error'] != False else False,
'errorCode': entry['error']['code'].encode('utf-8') if entry['error'] != False else False
});
return result | [
"def",
"sendMessage",
"(",
"self",
",",
"to",
",",
"message",
",",
"extra",
"=",
"{",
"}",
")",
":",
"to",
"=",
"to",
"if",
"isinstance",
"(",
"to",
",",
"list",
")",
"else",
"[",
"to",
"]",
"to",
"=",
"[",
"str",
"(",
"num",
")",
"for",
"num... | If the 'to' parameter is a single entry, we will parse it into a list.
We will merge default values into the request data and the extra parameters
provided by the user. | [
"If",
"the",
"to",
"parameter",
"is",
"a",
"single",
"entry",
"we",
"will",
"parse",
"it",
"into",
"a",
"list",
".",
"We",
"will",
"merge",
"default",
"values",
"into",
"the",
"request",
"data",
"and",
"the",
"extra",
"parameters",
"provided",
"by",
"the... | train | https://github.com/arcturial/clickatell-python/blob/4a554c28edaf2e5d0d9e81b4c9415241bfd61d00/clickatell/rest/__init__.py#L31-L55 |
arcturial/clickatell-python | clickatell/rest/__init__.py | Rest.stopMessage | def stopMessage(self, apiMsgId):
"""
See parent method for documentation
"""
content = self.parseRest(self.request('rest/message/' + apiMsgId, {}, {}, 'DELETE'))
return {
'id': content['apiMessageId'].encode('utf-8'),
'status': content['messageStatus'].encode('utf-8'),
'description': self.getStatus(content['messageStatus'])
} | python | def stopMessage(self, apiMsgId):
"""
See parent method for documentation
"""
content = self.parseRest(self.request('rest/message/' + apiMsgId, {}, {}, 'DELETE'))
return {
'id': content['apiMessageId'].encode('utf-8'),
'status': content['messageStatus'].encode('utf-8'),
'description': self.getStatus(content['messageStatus'])
} | [
"def",
"stopMessage",
"(",
"self",
",",
"apiMsgId",
")",
":",
"content",
"=",
"self",
".",
"parseRest",
"(",
"self",
".",
"request",
"(",
"'rest/message/'",
"+",
"apiMsgId",
",",
"{",
"}",
",",
"{",
"}",
",",
"'DELETE'",
")",
")",
"return",
"{",
"'id... | See parent method for documentation | [
"See",
"parent",
"method",
"for",
"documentation"
] | train | https://github.com/arcturial/clickatell-python/blob/4a554c28edaf2e5d0d9e81b4c9415241bfd61d00/clickatell/rest/__init__.py#L64-L74 |
arcturial/clickatell-python | clickatell/rest/__init__.py | Rest.getMessageCharge | def getMessageCharge(self, apiMsgId):
"""
See parent method for documentation
"""
content = self.parseRest(self.request('rest/message/' + apiMsgId))
return {
'id': apiMsgId,
'status': content['messageStatus'].encode('utf-8'),
'description': self.getStatus(content['messageStatus']),
'charge': float(content['charge'])
} | python | def getMessageCharge(self, apiMsgId):
"""
See parent method for documentation
"""
content = self.parseRest(self.request('rest/message/' + apiMsgId))
return {
'id': apiMsgId,
'status': content['messageStatus'].encode('utf-8'),
'description': self.getStatus(content['messageStatus']),
'charge': float(content['charge'])
} | [
"def",
"getMessageCharge",
"(",
"self",
",",
"apiMsgId",
")",
":",
"content",
"=",
"self",
".",
"parseRest",
"(",
"self",
".",
"request",
"(",
"'rest/message/'",
"+",
"apiMsgId",
")",
")",
"return",
"{",
"'id'",
":",
"apiMsgId",
",",
"'status'",
":",
"co... | See parent method for documentation | [
"See",
"parent",
"method",
"for",
"documentation"
] | train | https://github.com/arcturial/clickatell-python/blob/4a554c28edaf2e5d0d9e81b4c9415241bfd61d00/clickatell/rest/__init__.py#L82-L93 |
arcturial/clickatell-python | clickatell/rest/__init__.py | Rest.routeCoverage | def routeCoverage(self, msisdn):
"""
If the route coverage lookup encounters an error, we will treat it as "not covered".
"""
content = self.parseRest(self.request('rest/coverage/' + str(msisdn)))
return {
'routable': content['routable'],
'destination': content['destination'].encode('utf-8'),
'charge': float(content['minimumCharge'])
} | python | def routeCoverage(self, msisdn):
"""
If the route coverage lookup encounters an error, we will treat it as "not covered".
"""
content = self.parseRest(self.request('rest/coverage/' + str(msisdn)))
return {
'routable': content['routable'],
'destination': content['destination'].encode('utf-8'),
'charge': float(content['minimumCharge'])
} | [
"def",
"routeCoverage",
"(",
"self",
",",
"msisdn",
")",
":",
"content",
"=",
"self",
".",
"parseRest",
"(",
"self",
".",
"request",
"(",
"'rest/coverage/'",
"+",
"str",
"(",
"msisdn",
")",
")",
")",
"return",
"{",
"'routable'",
":",
"content",
"[",
"'... | If the route coverage lookup encounters an error, we will treat it as "not covered". | [
"If",
"the",
"route",
"coverage",
"lookup",
"encounters",
"an",
"error",
"we",
"will",
"treat",
"it",
"as",
"not",
"covered",
"."
] | train | https://github.com/arcturial/clickatell-python/blob/4a554c28edaf2e5d0d9e81b4c9415241bfd61d00/clickatell/rest/__init__.py#L95-L105 |
PGower/PyCanvas | pycanvas/apis/admins.py | AdminsAPI.make_account_admin | def make_account_admin(self, user_id, account_id, role=None, role_id=None, send_confirmation=None):
"""
Make an account admin.
Flag an existing user as an admin within the account.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
"""ID"""
path["account_id"] = account_id
# REQUIRED - user_id
"""The id of the user to promote."""
data["user_id"] = user_id
# OPTIONAL - role
"""(deprecated)
The user's admin relationship with the account will be created with the
given role. Defaults to 'AccountAdmin'."""
if role is not None:
data["role"] = role
# OPTIONAL - role_id
"""The user's admin relationship with the account will be created with the
given role. Defaults to the built-in role for 'AccountAdmin'."""
if role_id is not None:
data["role_id"] = role_id
# OPTIONAL - send_confirmation
"""Send a notification email to
the new admin if true. Default is true."""
if send_confirmation is not None:
data["send_confirmation"] = send_confirmation
self.logger.debug("POST /api/v1/accounts/{account_id}/admins with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/accounts/{account_id}/admins".format(**path), data=data, params=params, single_item=True) | python | def make_account_admin(self, user_id, account_id, role=None, role_id=None, send_confirmation=None):
"""
Make an account admin.
Flag an existing user as an admin within the account.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
"""ID"""
path["account_id"] = account_id
# REQUIRED - user_id
"""The id of the user to promote."""
data["user_id"] = user_id
# OPTIONAL - role
"""(deprecated)
The user's admin relationship with the account will be created with the
given role. Defaults to 'AccountAdmin'."""
if role is not None:
data["role"] = role
# OPTIONAL - role_id
"""The user's admin relationship with the account will be created with the
given role. Defaults to the built-in role for 'AccountAdmin'."""
if role_id is not None:
data["role_id"] = role_id
# OPTIONAL - send_confirmation
"""Send a notification email to
the new admin if true. Default is true."""
if send_confirmation is not None:
data["send_confirmation"] = send_confirmation
self.logger.debug("POST /api/v1/accounts/{account_id}/admins with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/accounts/{account_id}/admins".format(**path), data=data, params=params, single_item=True) | [
"def",
"make_account_admin",
"(",
"self",
",",
"user_id",
",",
"account_id",
",",
"role",
"=",
"None",
",",
"role_id",
"=",
"None",
",",
"send_confirmation",
"=",
"None",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}"... | Make an account admin.
Flag an existing user as an admin within the account. | [
"Make",
"an",
"account",
"admin",
".",
"Flag",
"an",
"existing",
"user",
"as",
"an",
"admin",
"within",
"the",
"account",
"."
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/admins.py#L19-L57 |
PGower/PyCanvas | pycanvas/apis/admins.py | AdminsAPI.list_account_admins | def list_account_admins(self, account_id, user_id=None):
"""
List account admins.
List the admins in the account
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
"""ID"""
path["account_id"] = account_id
# OPTIONAL - user_id
"""Scope the results to those with user IDs equal to any of the IDs specified here."""
if user_id is not None:
params["user_id"] = user_id
self.logger.debug("GET /api/v1/accounts/{account_id}/admins with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/accounts/{account_id}/admins".format(**path), data=data, params=params, all_pages=True) | python | def list_account_admins(self, account_id, user_id=None):
"""
List account admins.
List the admins in the account
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
"""ID"""
path["account_id"] = account_id
# OPTIONAL - user_id
"""Scope the results to those with user IDs equal to any of the IDs specified here."""
if user_id is not None:
params["user_id"] = user_id
self.logger.debug("GET /api/v1/accounts/{account_id}/admins with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/accounts/{account_id}/admins".format(**path), data=data, params=params, all_pages=True) | [
"def",
"list_account_admins",
"(",
"self",
",",
"account_id",
",",
"user_id",
"=",
"None",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - account_id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
"\"account_id\"",
"... | List account admins.
List the admins in the account | [
"List",
"account",
"admins",
".",
"List",
"the",
"admins",
"in",
"the",
"account"
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/admins.py#L93-L113 |
solute/python-tint | tint/registry.py | _hex_to_rgb | def _hex_to_rgb(hex_code):
"""
>>> _hex_to_rgb("007fff")
(0, 127, 255)
"""
if len(hex_code) != 6:
raise ValueError(hex_code + " is not a string of length 6, cannot convert to rgb.")
return tuple(map(ord, hex_code.decode("hex"))) | python | def _hex_to_rgb(hex_code):
"""
>>> _hex_to_rgb("007fff")
(0, 127, 255)
"""
if len(hex_code) != 6:
raise ValueError(hex_code + " is not a string of length 6, cannot convert to rgb.")
return tuple(map(ord, hex_code.decode("hex"))) | [
"def",
"_hex_to_rgb",
"(",
"hex_code",
")",
":",
"if",
"len",
"(",
"hex_code",
")",
"!=",
"6",
":",
"raise",
"ValueError",
"(",
"hex_code",
"+",
"\" is not a string of length 6, cannot convert to rgb.\"",
")",
"return",
"tuple",
"(",
"map",
"(",
"ord",
",",
"h... | >>> _hex_to_rgb("007fff")
(0, 127, 255) | [
">>>",
"_hex_to_rgb",
"(",
"007fff",
")",
"(",
"0",
"127",
"255",
")"
] | train | https://github.com/solute/python-tint/blob/a09e44147b9fe81a67892901960f5b8350821c95/tint/registry.py#L44-L51 |
solute/python-tint | tint/registry.py | TintRegistry.add_colors_from_file | def add_colors_from_file(self, system, f_or_filename):
"""Add color definition to a given color system.
You may pass either a file-like object or a filename string pointing
to a color definition csv file. Each line in that input file should
look like this::
café au lait,a67b5b
i.e. a color name and a sRGB hex code, separated by by comma (``,``). Note that
this is standard excel-style csv format without headers.
You may add to already existing color system. Previously existing color
definitions of the same (normalized) name will be overwritten,
regardless of the color system.
Args:
system (string): The color system the colors should be added to
(e.g. ``"en"``).
color_definitions (filename, or file-like object): Either
a filename, or a file-like object pointing to a color definition
csv file (excel style).
"""
if hasattr(f_or_filename, "read"):
colors = (row for row in csv.reader(f_or_filename) if row)
else:
with open(f_or_filename, "rb") as f:
colors = [row for row in csv.reader(f) if row]
self.add_colors(system, colors) | python | def add_colors_from_file(self, system, f_or_filename):
"""Add color definition to a given color system.
You may pass either a file-like object or a filename string pointing
to a color definition csv file. Each line in that input file should
look like this::
café au lait,a67b5b
i.e. a color name and a sRGB hex code, separated by by comma (``,``). Note that
this is standard excel-style csv format without headers.
You may add to already existing color system. Previously existing color
definitions of the same (normalized) name will be overwritten,
regardless of the color system.
Args:
system (string): The color system the colors should be added to
(e.g. ``"en"``).
color_definitions (filename, or file-like object): Either
a filename, or a file-like object pointing to a color definition
csv file (excel style).
"""
if hasattr(f_or_filename, "read"):
colors = (row for row in csv.reader(f_or_filename) if row)
else:
with open(f_or_filename, "rb") as f:
colors = [row for row in csv.reader(f) if row]
self.add_colors(system, colors) | [
"def",
"add_colors_from_file",
"(",
"self",
",",
"system",
",",
"f_or_filename",
")",
":",
"if",
"hasattr",
"(",
"f_or_filename",
",",
"\"read\"",
")",
":",
"colors",
"=",
"(",
"row",
"for",
"row",
"in",
"csv",
".",
"reader",
"(",
"f_or_filename",
")",
"... | Add color definition to a given color system.
You may pass either a file-like object or a filename string pointing
to a color definition csv file. Each line in that input file should
look like this::
café au lait,a67b5b
i.e. a color name and a sRGB hex code, separated by by comma (``,``). Note that
this is standard excel-style csv format without headers.
You may add to already existing color system. Previously existing color
definitions of the same (normalized) name will be overwritten,
regardless of the color system.
Args:
system (string): The color system the colors should be added to
(e.g. ``"en"``).
color_definitions (filename, or file-like object): Either
a filename, or a file-like object pointing to a color definition
csv file (excel style). | [
"Add",
"color",
"definition",
"to",
"a",
"given",
"color",
"system",
"."
] | train | https://github.com/solute/python-tint/blob/a09e44147b9fe81a67892901960f5b8350821c95/tint/registry.py#L90-L120 |
solute/python-tint | tint/registry.py | TintRegistry.add_colors | def add_colors(self, system, colors):
"""Add color definition to a given color system.
You may add to already existing color system. Previously existing color
definitions of the same (normalized) name will be overwritten,
regardless of the color system.
Args:
system (string): The color system the colors should be added to
(e.g. ``"en"``).
color_definitions (iterable of tuples): Color name / sRGB value pairs
(e.g. ``[("white", "ffffff"), ("red", "ff0000")]``)
Examples:
>>> color_definitions = {"greenish": "336633", "blueish": "334466"}
>>> tint_registry = TintRegistry()
>>> tint_registry.add_colors("vague", color_definitions.iteritems())
"""
if system not in self._colors_by_system_hex:
self._colors_by_system_hex[system] = {}
self._colors_by_system_lab[system] = []
for color_name, hex_code in colors:
hex_code = hex_code.lower().strip().strip("#")
color_name = color_name.lower().strip()
if not isinstance(color_name, unicode):
color_name = unicode(color_name, "utf-8")
self._colors_by_system_hex[system][hex_code] = color_name
self._colors_by_system_lab[system].append((_hex_to_lab(hex_code), color_name))
self._hex_by_color[_normalize(color_name)] = hex_code | python | def add_colors(self, system, colors):
"""Add color definition to a given color system.
You may add to already existing color system. Previously existing color
definitions of the same (normalized) name will be overwritten,
regardless of the color system.
Args:
system (string): The color system the colors should be added to
(e.g. ``"en"``).
color_definitions (iterable of tuples): Color name / sRGB value pairs
(e.g. ``[("white", "ffffff"), ("red", "ff0000")]``)
Examples:
>>> color_definitions = {"greenish": "336633", "blueish": "334466"}
>>> tint_registry = TintRegistry()
>>> tint_registry.add_colors("vague", color_definitions.iteritems())
"""
if system not in self._colors_by_system_hex:
self._colors_by_system_hex[system] = {}
self._colors_by_system_lab[system] = []
for color_name, hex_code in colors:
hex_code = hex_code.lower().strip().strip("#")
color_name = color_name.lower().strip()
if not isinstance(color_name, unicode):
color_name = unicode(color_name, "utf-8")
self._colors_by_system_hex[system][hex_code] = color_name
self._colors_by_system_lab[system].append((_hex_to_lab(hex_code), color_name))
self._hex_by_color[_normalize(color_name)] = hex_code | [
"def",
"add_colors",
"(",
"self",
",",
"system",
",",
"colors",
")",
":",
"if",
"system",
"not",
"in",
"self",
".",
"_colors_by_system_hex",
":",
"self",
".",
"_colors_by_system_hex",
"[",
"system",
"]",
"=",
"{",
"}",
"self",
".",
"_colors_by_system_lab",
... | Add color definition to a given color system.
You may add to already existing color system. Previously existing color
definitions of the same (normalized) name will be overwritten,
regardless of the color system.
Args:
system (string): The color system the colors should be added to
(e.g. ``"en"``).
color_definitions (iterable of tuples): Color name / sRGB value pairs
(e.g. ``[("white", "ffffff"), ("red", "ff0000")]``)
Examples:
>>> color_definitions = {"greenish": "336633", "blueish": "334466"}
>>> tint_registry = TintRegistry()
>>> tint_registry.add_colors("vague", color_definitions.iteritems()) | [
"Add",
"color",
"definition",
"to",
"a",
"given",
"color",
"system",
"."
] | train | https://github.com/solute/python-tint/blob/a09e44147b9fe81a67892901960f5b8350821c95/tint/registry.py#L122-L154 |
solute/python-tint | tint/registry.py | TintRegistry.match_name | def match_name(self, in_string, fuzzy=False):
"""Match a color to a sRGB value.
The matching will be based purely on the input string and the color names in the
registry. If there's no direct hit, a fuzzy matching algorithm is applied. This method
will never fail to return a sRGB value, but depending on the score, it might or might
not be a sensible result – as a rule of thumb, any score less then 90 indicates that
there's a lot of guessing going on. It's the callers responsibility to judge if the return
value should be trusted.
In normalization terms, this method implements "normalize an arbitrary color name
to a sRGB value".
Args:
in_string (string): The input string containing something resembling
a color name.
fuzzy (bool, optional): Try fuzzy matching if no exact match was found.
Defaults to ``False``.
Returns:
A named tuple with the members `hex_code` and `score`.
Raises:
ValueError: If ``fuzzy`` is ``False`` and no match is found
Examples:
>>> tint_registry = TintRegistry()
>>> tint_registry.match_name("rather white", fuzzy=True)
MatchResult(hex_code=u'ffffff', score=95)
"""
in_string = _normalize(in_string)
if in_string in self._hex_by_color:
return MatchResult(self._hex_by_color[in_string], 100)
if not fuzzy:
raise ValueError("No match for %r found." % in_string)
# We want the standard scorer *plus* the set scorer, because colors are often
# (but not always) related by sub-strings
color_names = self._hex_by_color.keys()
set_match = dict(fuzzywuzzy.process.extract(
in_string,
color_names,
scorer=fuzzywuzzy.fuzz.token_set_ratio
))
standard_match = dict(fuzzywuzzy.process.extract(in_string, color_names))
# This would be much easier with a collections.Counter, but alas! it's a 2.7 feature.
key_union = set(set_match) | set(standard_match)
counter = ((n, set_match.get(n, 0) + standard_match.get(n, 0)) for n in key_union)
color_name, score = sorted(counter, key=operator.itemgetter(1))[-1]
return MatchResult(self._hex_by_color[color_name], score / 2) | python | def match_name(self, in_string, fuzzy=False):
"""Match a color to a sRGB value.
The matching will be based purely on the input string and the color names in the
registry. If there's no direct hit, a fuzzy matching algorithm is applied. This method
will never fail to return a sRGB value, but depending on the score, it might or might
not be a sensible result – as a rule of thumb, any score less then 90 indicates that
there's a lot of guessing going on. It's the callers responsibility to judge if the return
value should be trusted.
In normalization terms, this method implements "normalize an arbitrary color name
to a sRGB value".
Args:
in_string (string): The input string containing something resembling
a color name.
fuzzy (bool, optional): Try fuzzy matching if no exact match was found.
Defaults to ``False``.
Returns:
A named tuple with the members `hex_code` and `score`.
Raises:
ValueError: If ``fuzzy`` is ``False`` and no match is found
Examples:
>>> tint_registry = TintRegistry()
>>> tint_registry.match_name("rather white", fuzzy=True)
MatchResult(hex_code=u'ffffff', score=95)
"""
in_string = _normalize(in_string)
if in_string in self._hex_by_color:
return MatchResult(self._hex_by_color[in_string], 100)
if not fuzzy:
raise ValueError("No match for %r found." % in_string)
# We want the standard scorer *plus* the set scorer, because colors are often
# (but not always) related by sub-strings
color_names = self._hex_by_color.keys()
set_match = dict(fuzzywuzzy.process.extract(
in_string,
color_names,
scorer=fuzzywuzzy.fuzz.token_set_ratio
))
standard_match = dict(fuzzywuzzy.process.extract(in_string, color_names))
# This would be much easier with a collections.Counter, but alas! it's a 2.7 feature.
key_union = set(set_match) | set(standard_match)
counter = ((n, set_match.get(n, 0) + standard_match.get(n, 0)) for n in key_union)
color_name, score = sorted(counter, key=operator.itemgetter(1))[-1]
return MatchResult(self._hex_by_color[color_name], score / 2) | [
"def",
"match_name",
"(",
"self",
",",
"in_string",
",",
"fuzzy",
"=",
"False",
")",
":",
"in_string",
"=",
"_normalize",
"(",
"in_string",
")",
"if",
"in_string",
"in",
"self",
".",
"_hex_by_color",
":",
"return",
"MatchResult",
"(",
"self",
".",
"_hex_by... | Match a color to a sRGB value.
The matching will be based purely on the input string and the color names in the
registry. If there's no direct hit, a fuzzy matching algorithm is applied. This method
will never fail to return a sRGB value, but depending on the score, it might or might
not be a sensible result – as a rule of thumb, any score less then 90 indicates that
there's a lot of guessing going on. It's the callers responsibility to judge if the return
value should be trusted.
In normalization terms, this method implements "normalize an arbitrary color name
to a sRGB value".
Args:
in_string (string): The input string containing something resembling
a color name.
fuzzy (bool, optional): Try fuzzy matching if no exact match was found.
Defaults to ``False``.
Returns:
A named tuple with the members `hex_code` and `score`.
Raises:
ValueError: If ``fuzzy`` is ``False`` and no match is found
Examples:
>>> tint_registry = TintRegistry()
>>> tint_registry.match_name("rather white", fuzzy=True)
MatchResult(hex_code=u'ffffff', score=95) | [
"Match",
"a",
"color",
"to",
"a",
"sRGB",
"value",
"."
] | train | https://github.com/solute/python-tint/blob/a09e44147b9fe81a67892901960f5b8350821c95/tint/registry.py#L156-L209 |
solute/python-tint | tint/registry.py | TintRegistry.find_nearest | def find_nearest(self, hex_code, system, filter_set=None):
"""Find a color name that's most similar to a given sRGB hex code.
In normalization terms, this method implements "normalize an arbitrary sRGB value
to a well-defined color name".
Args:
system (string): The color system. Currently, `"en"`` is the only default
system.
filter_set (iterable of string, optional): Limits the output choices
to fewer color names. The names (e.g. ``["black", "white"]``) must be
present in the given system.
If omitted, all color names of the system are considered. Defaults to None.
Returns:
A named tuple with the members `color_name` and `distance`.
Raises:
ValueError: If argument `system` is not a registered color system.
Examples:
>>> tint_registry = TintRegistry()
>>> tint_registry.find_nearest("54e6e4", system="en")
FindResult(color_name=u'bright turquoise', distance=3.730288645055483)
>>> tint_registry.find_nearest("54e6e4", "en", filter_set=("white", "black"))
FindResult(color_name=u'white', distance=25.709952192116894)
"""
if system not in self._colors_by_system_hex:
raise ValueError(
"%r is not a registered color system. Try one of %r"
% (system, self._colors_by_system_hex.keys())
)
hex_code = hex_code.lower().strip()
# Try direct hit (fast path)
if hex_code in self._colors_by_system_hex[system]:
color_name = self._colors_by_system_hex[system][hex_code]
if filter_set is None or color_name in filter_set:
return FindResult(color_name, 0)
# No direct hit, assemble list of lab_color/color_name pairs
colors = self._colors_by_system_lab[system]
if filter_set is not None:
colors = (pair for pair in colors if pair[1] in set(filter_set))
# find minimal distance
lab_color = _hex_to_lab(hex_code)
min_distance = sys.float_info.max
min_color_name = None
for current_lab_color, current_color_name in colors:
distance = colormath.color_diff.delta_e_cie2000(lab_color, current_lab_color)
if distance < min_distance:
min_distance = distance
min_color_name = current_color_name
return FindResult(min_color_name, min_distance) | python | def find_nearest(self, hex_code, system, filter_set=None):
"""Find a color name that's most similar to a given sRGB hex code.
In normalization terms, this method implements "normalize an arbitrary sRGB value
to a well-defined color name".
Args:
system (string): The color system. Currently, `"en"`` is the only default
system.
filter_set (iterable of string, optional): Limits the output choices
to fewer color names. The names (e.g. ``["black", "white"]``) must be
present in the given system.
If omitted, all color names of the system are considered. Defaults to None.
Returns:
A named tuple with the members `color_name` and `distance`.
Raises:
ValueError: If argument `system` is not a registered color system.
Examples:
>>> tint_registry = TintRegistry()
>>> tint_registry.find_nearest("54e6e4", system="en")
FindResult(color_name=u'bright turquoise', distance=3.730288645055483)
>>> tint_registry.find_nearest("54e6e4", "en", filter_set=("white", "black"))
FindResult(color_name=u'white', distance=25.709952192116894)
"""
if system not in self._colors_by_system_hex:
raise ValueError(
"%r is not a registered color system. Try one of %r"
% (system, self._colors_by_system_hex.keys())
)
hex_code = hex_code.lower().strip()
# Try direct hit (fast path)
if hex_code in self._colors_by_system_hex[system]:
color_name = self._colors_by_system_hex[system][hex_code]
if filter_set is None or color_name in filter_set:
return FindResult(color_name, 0)
# No direct hit, assemble list of lab_color/color_name pairs
colors = self._colors_by_system_lab[system]
if filter_set is not None:
colors = (pair for pair in colors if pair[1] in set(filter_set))
# find minimal distance
lab_color = _hex_to_lab(hex_code)
min_distance = sys.float_info.max
min_color_name = None
for current_lab_color, current_color_name in colors:
distance = colormath.color_diff.delta_e_cie2000(lab_color, current_lab_color)
if distance < min_distance:
min_distance = distance
min_color_name = current_color_name
return FindResult(min_color_name, min_distance) | [
"def",
"find_nearest",
"(",
"self",
",",
"hex_code",
",",
"system",
",",
"filter_set",
"=",
"None",
")",
":",
"if",
"system",
"not",
"in",
"self",
".",
"_colors_by_system_hex",
":",
"raise",
"ValueError",
"(",
"\"%r is not a registered color system. Try one of %r\""... | Find a color name that's most similar to a given sRGB hex code.
In normalization terms, this method implements "normalize an arbitrary sRGB value
to a well-defined color name".
Args:
system (string): The color system. Currently, `"en"`` is the only default
system.
filter_set (iterable of string, optional): Limits the output choices
to fewer color names. The names (e.g. ``["black", "white"]``) must be
present in the given system.
If omitted, all color names of the system are considered. Defaults to None.
Returns:
A named tuple with the members `color_name` and `distance`.
Raises:
ValueError: If argument `system` is not a registered color system.
Examples:
>>> tint_registry = TintRegistry()
>>> tint_registry.find_nearest("54e6e4", system="en")
FindResult(color_name=u'bright turquoise', distance=3.730288645055483)
>>> tint_registry.find_nearest("54e6e4", "en", filter_set=("white", "black"))
FindResult(color_name=u'white', distance=25.709952192116894) | [
"Find",
"a",
"color",
"name",
"that",
"s",
"most",
"similar",
"to",
"a",
"given",
"sRGB",
"hex",
"code",
"."
] | train | https://github.com/solute/python-tint/blob/a09e44147b9fe81a67892901960f5b8350821c95/tint/registry.py#L211-L268 |
usingnamespace/pyramid_authsanity | src/pyramid_authsanity/sources.py | SessionAuthSourceInitializer | def SessionAuthSourceInitializer(
value_key='sanity.'
):
""" An authentication source that uses the current session """
value_key = value_key + 'value'
@implementer(IAuthSourceService)
class SessionAuthSource(object):
vary = []
def __init__(self, context, request):
self.request = request
self.session = request.session
self.cur_val = None
def get_value(self):
if self.cur_val is None:
self.cur_val = self.session.get(value_key, [None, None])
return self.cur_val
def headers_remember(self, value):
if self.cur_val is None:
self.cur_val = self.session.get(value_key, [None, None])
self.session[value_key] = value
return []
def headers_forget(self):
if self.cur_val is None:
self.cur_val = self.session.get(value_key, [None, None])
if value_key in self.session:
del self.session[value_key]
return []
return SessionAuthSource | python | def SessionAuthSourceInitializer(
value_key='sanity.'
):
""" An authentication source that uses the current session """
value_key = value_key + 'value'
@implementer(IAuthSourceService)
class SessionAuthSource(object):
vary = []
def __init__(self, context, request):
self.request = request
self.session = request.session
self.cur_val = None
def get_value(self):
if self.cur_val is None:
self.cur_val = self.session.get(value_key, [None, None])
return self.cur_val
def headers_remember(self, value):
if self.cur_val is None:
self.cur_val = self.session.get(value_key, [None, None])
self.session[value_key] = value
return []
def headers_forget(self):
if self.cur_val is None:
self.cur_val = self.session.get(value_key, [None, None])
if value_key in self.session:
del self.session[value_key]
return []
return SessionAuthSource | [
"def",
"SessionAuthSourceInitializer",
"(",
"value_key",
"=",
"'sanity.'",
")",
":",
"value_key",
"=",
"value_key",
"+",
"'value'",
"@",
"implementer",
"(",
"IAuthSourceService",
")",
"class",
"SessionAuthSource",
"(",
"object",
")",
":",
"vary",
"=",
"[",
"]",
... | An authentication source that uses the current session | [
"An",
"authentication",
"source",
"that",
"uses",
"the",
"current",
"session"
] | train | https://github.com/usingnamespace/pyramid_authsanity/blob/2a5de20f5e2be88b38eb8332e7a45ff2f8aa049d/src/pyramid_authsanity/sources.py#L16-L53 |
usingnamespace/pyramid_authsanity | src/pyramid_authsanity/sources.py | CookieAuthSourceInitializer | def CookieAuthSourceInitializer(
secret,
cookie_name='auth',
secure=False,
max_age=None,
httponly=False,
path="/",
domains=None,
debug=False,
hashalg='sha512',
):
""" An authentication source that uses a unique cookie. """
@implementer(IAuthSourceService)
class CookieAuthSource(object):
vary = ['Cookie']
def __init__(self, context, request):
self.domains = domains
if self.domains is None:
self.domains = []
self.domains.append(request.domain)
self.cookie = SignedCookieProfile(
secret,
'authsanity',
cookie_name,
secure=secure,
max_age=max_age,
httponly=httponly,
path=path,
domains=domains,
hashalg=hashalg,
)
# Bind the cookie to the current request
self.cookie = self.cookie.bind(request)
def get_value(self):
val = self.cookie.get_value()
if val is None:
return [None, None]
return val
def headers_remember(self, value):
return self.cookie.get_headers(value, domains=self.domains)
def headers_forget(self):
return self.cookie.get_headers(None, max_age=0)
return CookieAuthSource | python | def CookieAuthSourceInitializer(
secret,
cookie_name='auth',
secure=False,
max_age=None,
httponly=False,
path="/",
domains=None,
debug=False,
hashalg='sha512',
):
""" An authentication source that uses a unique cookie. """
@implementer(IAuthSourceService)
class CookieAuthSource(object):
vary = ['Cookie']
def __init__(self, context, request):
self.domains = domains
if self.domains is None:
self.domains = []
self.domains.append(request.domain)
self.cookie = SignedCookieProfile(
secret,
'authsanity',
cookie_name,
secure=secure,
max_age=max_age,
httponly=httponly,
path=path,
domains=domains,
hashalg=hashalg,
)
# Bind the cookie to the current request
self.cookie = self.cookie.bind(request)
def get_value(self):
val = self.cookie.get_value()
if val is None:
return [None, None]
return val
def headers_remember(self, value):
return self.cookie.get_headers(value, domains=self.domains)
def headers_forget(self):
return self.cookie.get_headers(None, max_age=0)
return CookieAuthSource | [
"def",
"CookieAuthSourceInitializer",
"(",
"secret",
",",
"cookie_name",
"=",
"'auth'",
",",
"secure",
"=",
"False",
",",
"max_age",
"=",
"None",
",",
"httponly",
"=",
"False",
",",
"path",
"=",
"\"/\"",
",",
"domains",
"=",
"None",
",",
"debug",
"=",
"F... | An authentication source that uses a unique cookie. | [
"An",
"authentication",
"source",
"that",
"uses",
"a",
"unique",
"cookie",
"."
] | train | https://github.com/usingnamespace/pyramid_authsanity/blob/2a5de20f5e2be88b38eb8332e7a45ff2f8aa049d/src/pyramid_authsanity/sources.py#L56-L108 |
usingnamespace/pyramid_authsanity | src/pyramid_authsanity/sources.py | HeaderAuthSourceInitializer | def HeaderAuthSourceInitializer(
secret,
salt='sanity.header.'
):
""" An authentication source that uses the Authorization header. """
@implementer(IAuthSourceService)
class HeaderAuthSource(object):
vary = ['Authorization']
def __init__(self, context, request):
self.request = request
self.cur_val = None
serializer = JSONSerializer()
self.serializer = SignedSerializer(
secret,
salt,
serializer=serializer,
)
def _get_authorization(self):
try:
type, token = self.request.authorization
return self.serializer.loads(token)
except Exception:
return None
def _create_authorization(self, value):
try:
return self.serializer.dumps(value)
except Exception:
return ''
def get_value(self):
if self.cur_val is None:
self.cur_val = self._get_authorization() or [None, None]
return self.cur_val
def headers_remember(self, value):
if self.cur_val is None:
self.cur_val = None
token = self._create_authorization(value)
auth_info = native_(b'Bearer ' + token, 'latin-1', 'strict')
return [('Authorization', auth_info)]
def headers_forget(self):
if self.cur_val is None:
self.cur_val = None
return []
return HeaderAuthSource | python | def HeaderAuthSourceInitializer(
secret,
salt='sanity.header.'
):
""" An authentication source that uses the Authorization header. """
@implementer(IAuthSourceService)
class HeaderAuthSource(object):
vary = ['Authorization']
def __init__(self, context, request):
self.request = request
self.cur_val = None
serializer = JSONSerializer()
self.serializer = SignedSerializer(
secret,
salt,
serializer=serializer,
)
def _get_authorization(self):
try:
type, token = self.request.authorization
return self.serializer.loads(token)
except Exception:
return None
def _create_authorization(self, value):
try:
return self.serializer.dumps(value)
except Exception:
return ''
def get_value(self):
if self.cur_val is None:
self.cur_val = self._get_authorization() or [None, None]
return self.cur_val
def headers_remember(self, value):
if self.cur_val is None:
self.cur_val = None
token = self._create_authorization(value)
auth_info = native_(b'Bearer ' + token, 'latin-1', 'strict')
return [('Authorization', auth_info)]
def headers_forget(self):
if self.cur_val is None:
self.cur_val = None
return []
return HeaderAuthSource | [
"def",
"HeaderAuthSourceInitializer",
"(",
"secret",
",",
"salt",
"=",
"'sanity.header.'",
")",
":",
"@",
"implementer",
"(",
"IAuthSourceService",
")",
"class",
"HeaderAuthSource",
"(",
"object",
")",
":",
"vary",
"=",
"[",
"'Authorization'",
"]",
"def",
"__ini... | An authentication source that uses the Authorization header. | [
"An",
"authentication",
"source",
"that",
"uses",
"the",
"Authorization",
"header",
"."
] | train | https://github.com/usingnamespace/pyramid_authsanity/blob/2a5de20f5e2be88b38eb8332e7a45ff2f8aa049d/src/pyramid_authsanity/sources.py#L111-L166 |
klen/muffin-rest | muffin_rest/peewee.py | PWFilter.apply | def apply(self, collection, ops, resource=None, **kwargs):
"""Filter given collection."""
mfield = self.mfield or resource.meta.model._meta.fields.get(self.field.attribute)
if mfield:
collection = collection.where(*[op(mfield, val) for op, val in ops])
return collection | python | def apply(self, collection, ops, resource=None, **kwargs):
"""Filter given collection."""
mfield = self.mfield or resource.meta.model._meta.fields.get(self.field.attribute)
if mfield:
collection = collection.where(*[op(mfield, val) for op, val in ops])
return collection | [
"def",
"apply",
"(",
"self",
",",
"collection",
",",
"ops",
",",
"resource",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"mfield",
"=",
"self",
".",
"mfield",
"or",
"resource",
".",
"meta",
".",
"model",
".",
"_meta",
".",
"fields",
".",
"get",... | Filter given collection. | [
"Filter",
"given",
"collection",
"."
] | train | https://github.com/klen/muffin-rest/blob/1d85bdd3b72a89eaeab8c4086926260a960408aa/muffin_rest/peewee.py#L32-L37 |
klen/muffin-rest | muffin_rest/peewee.py | PWRESTHandler.get_one | def get_one(self, request, **kwargs):
"""Load a resource."""
resource = request.match_info.get(self.name)
if not resource:
return None
try:
return self.collection.where(self.meta.model_pk == resource).get()
except Exception:
raise RESTNotFound(reason='Resource not found.') | python | def get_one(self, request, **kwargs):
"""Load a resource."""
resource = request.match_info.get(self.name)
if not resource:
return None
try:
return self.collection.where(self.meta.model_pk == resource).get()
except Exception:
raise RESTNotFound(reason='Resource not found.') | [
"def",
"get_one",
"(",
"self",
",",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"resource",
"=",
"request",
".",
"match_info",
".",
"get",
"(",
"self",
".",
"name",
")",
"if",
"not",
"resource",
":",
"return",
"None",
"try",
":",
"return",
"self",
... | Load a resource. | [
"Load",
"a",
"resource",
"."
] | train | https://github.com/klen/muffin-rest/blob/1d85bdd3b72a89eaeab8c4086926260a960408aa/muffin_rest/peewee.py#L95-L104 |
klen/muffin-rest | muffin_rest/peewee.py | PWRESTHandler.sort | def sort(self, *sorting, **kwargs):
"""Sort resources."""
sorting_ = []
for name, desc in sorting:
field = self.meta.model._meta.fields.get(name)
if field is None:
continue
if desc:
field = field.desc()
sorting_.append(field)
if sorting_:
return self.collection.order_by(*sorting_)
return self.collection | python | def sort(self, *sorting, **kwargs):
"""Sort resources."""
sorting_ = []
for name, desc in sorting:
field = self.meta.model._meta.fields.get(name)
if field is None:
continue
if desc:
field = field.desc()
sorting_.append(field)
if sorting_:
return self.collection.order_by(*sorting_)
return self.collection | [
"def",
"sort",
"(",
"self",
",",
"*",
"sorting",
",",
"*",
"*",
"kwargs",
")",
":",
"sorting_",
"=",
"[",
"]",
"for",
"name",
",",
"desc",
"in",
"sorting",
":",
"field",
"=",
"self",
".",
"meta",
".",
"model",
".",
"_meta",
".",
"fields",
".",
... | Sort resources. | [
"Sort",
"resources",
"."
] | train | https://github.com/klen/muffin-rest/blob/1d85bdd3b72a89eaeab8c4086926260a960408aa/muffin_rest/peewee.py#L106-L118 |
klen/muffin-rest | muffin_rest/peewee.py | PWRESTHandler.paginate | def paginate(self, request, offset=0, limit=None):
"""Paginate queryset."""
return self.collection.offset(offset).limit(limit), self.collection.count() | python | def paginate(self, request, offset=0, limit=None):
"""Paginate queryset."""
return self.collection.offset(offset).limit(limit), self.collection.count() | [
"def",
"paginate",
"(",
"self",
",",
"request",
",",
"offset",
"=",
"0",
",",
"limit",
"=",
"None",
")",
":",
"return",
"self",
".",
"collection",
".",
"offset",
"(",
"offset",
")",
".",
"limit",
"(",
"limit",
")",
",",
"self",
".",
"collection",
"... | Paginate queryset. | [
"Paginate",
"queryset",
"."
] | train | https://github.com/klen/muffin-rest/blob/1d85bdd3b72a89eaeab8c4086926260a960408aa/muffin_rest/peewee.py#L120-L122 |
klen/muffin-rest | muffin_rest/peewee.py | PWRESTHandler.save | def save(self, request, resource=None, **kwargs):
"""Create a resource."""
resources = resource if isinstance(resource, list) else [resource]
for obj in resources:
obj.save()
return resource | python | def save(self, request, resource=None, **kwargs):
"""Create a resource."""
resources = resource if isinstance(resource, list) else [resource]
for obj in resources:
obj.save()
return resource | [
"def",
"save",
"(",
"self",
",",
"request",
",",
"resource",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"resources",
"=",
"resource",
"if",
"isinstance",
"(",
"resource",
",",
"list",
")",
"else",
"[",
"resource",
"]",
"for",
"obj",
"in",
"resou... | Create a resource. | [
"Create",
"a",
"resource",
"."
] | train | https://github.com/klen/muffin-rest/blob/1d85bdd3b72a89eaeab8c4086926260a960408aa/muffin_rest/peewee.py#L128-L133 |
klen/muffin-rest | muffin_rest/peewee.py | PWRESTHandler.delete | async def delete(self, request, resource=None, **kwargs):
"""Delete a resource.
Supports batch delete.
"""
if resource:
resources = [resource]
else:
data = await self.parse(request)
if data:
resources = list(self.collection.where(self.meta.model_pk << data))
if not resources:
raise RESTNotFound(reason='Resource not found')
for resource in resources:
resource.delete_instance() | python | async def delete(self, request, resource=None, **kwargs):
"""Delete a resource.
Supports batch delete.
"""
if resource:
resources = [resource]
else:
data = await self.parse(request)
if data:
resources = list(self.collection.where(self.meta.model_pk << data))
if not resources:
raise RESTNotFound(reason='Resource not found')
for resource in resources:
resource.delete_instance() | [
"async",
"def",
"delete",
"(",
"self",
",",
"request",
",",
"resource",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"resource",
":",
"resources",
"=",
"[",
"resource",
"]",
"else",
":",
"data",
"=",
"await",
"self",
".",
"parse",
"(",
"re... | Delete a resource.
Supports batch delete. | [
"Delete",
"a",
"resource",
"."
] | train | https://github.com/klen/muffin-rest/blob/1d85bdd3b72a89eaeab8c4086926260a960408aa/muffin_rest/peewee.py#L135-L151 |
PGower/PyCanvas | pycanvas/apis/accounts.py | AccountsAPI.get_sub_accounts_of_account | def get_sub_accounts_of_account(self, account_id, recursive=None):
"""
Get the sub-accounts of an account.
List accounts that are sub-accounts of the given account.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
"""ID"""
path["account_id"] = account_id
# OPTIONAL - recursive
"""If true, the entire account tree underneath
this account will be returned (though still paginated). If false, only
direct sub-accounts of this account will be returned. Defaults to false."""
if recursive is not None:
params["recursive"] = recursive
self.logger.debug("GET /api/v1/accounts/{account_id}/sub_accounts with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/accounts/{account_id}/sub_accounts".format(**path), data=data, params=params, all_pages=True) | python | def get_sub_accounts_of_account(self, account_id, recursive=None):
"""
Get the sub-accounts of an account.
List accounts that are sub-accounts of the given account.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
"""ID"""
path["account_id"] = account_id
# OPTIONAL - recursive
"""If true, the entire account tree underneath
this account will be returned (though still paginated). If false, only
direct sub-accounts of this account will be returned. Defaults to false."""
if recursive is not None:
params["recursive"] = recursive
self.logger.debug("GET /api/v1/accounts/{account_id}/sub_accounts with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/accounts/{account_id}/sub_accounts".format(**path), data=data, params=params, all_pages=True) | [
"def",
"get_sub_accounts_of_account",
"(",
"self",
",",
"account_id",
",",
"recursive",
"=",
"None",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - account_id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
"\"account_... | Get the sub-accounts of an account.
List accounts that are sub-accounts of the given account. | [
"Get",
"the",
"sub",
"-",
"accounts",
"of",
"an",
"account",
".",
"List",
"accounts",
"that",
"are",
"sub",
"-",
"accounts",
"of",
"the",
"given",
"account",
"."
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/accounts.py#L77-L99 |
PGower/PyCanvas | pycanvas/apis/accounts.py | AccountsAPI.list_active_courses_in_account | def list_active_courses_in_account(self, account_id, by_subaccounts=None, by_teachers=None, completed=None, enrollment_term_id=None, enrollment_type=None, hide_enrollmentless_courses=None, include=None, published=None, search_term=None, state=None, with_enrollments=None):
"""
List active courses in an account.
Retrieve the list of courses in this account.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
"""ID"""
path["account_id"] = account_id
# OPTIONAL - with_enrollments
"""If true, include only courses with at least one enrollment. If false,
include only courses with no enrollments. If not present, do not filter
on course enrollment status."""
if with_enrollments is not None:
params["with_enrollments"] = with_enrollments
# OPTIONAL - enrollment_type
"""If set, only return courses that have at least one user enrolled in
in the course with one of the specified enrollment types."""
if enrollment_type is not None:
self._validate_enum(enrollment_type, ["teacher", "student", "ta", "observer", "designer"])
params["enrollment_type"] = enrollment_type
# OPTIONAL - published
"""If true, include only published courses. If false, exclude published
courses. If not present, do not filter on published status."""
if published is not None:
params["published"] = published
# OPTIONAL - completed
"""If true, include only completed courses (these may be in state
'completed', or their enrollment term may have ended). If false, exclude
completed courses. If not present, do not filter on completed status."""
if completed is not None:
params["completed"] = completed
# OPTIONAL - by_teachers
"""List of User IDs of teachers; if supplied, include only courses taught by
one of the referenced users."""
if by_teachers is not None:
params["by_teachers"] = by_teachers
# OPTIONAL - by_subaccounts
"""List of Account IDs; if supplied, include only courses associated with one
of the referenced subaccounts."""
if by_subaccounts is not None:
params["by_subaccounts"] = by_subaccounts
# OPTIONAL - hide_enrollmentless_courses
"""If present, only return courses that have at least one enrollment.
Equivalent to 'with_enrollments=true'; retained for compatibility."""
if hide_enrollmentless_courses is not None:
params["hide_enrollmentless_courses"] = hide_enrollmentless_courses
# OPTIONAL - state
"""If set, only return courses that are in the given state(s). By default,
all states but "deleted" are returned."""
if state is not None:
self._validate_enum(state, ["created", "claimed", "available", "completed", "deleted", "all"])
params["state"] = state
# OPTIONAL - enrollment_term_id
"""If set, only includes courses from the specified term."""
if enrollment_term_id is not None:
params["enrollment_term_id"] = enrollment_term_id
# OPTIONAL - search_term
"""The partial course name, code, or full ID to match and return in the results list. Must be at least 3 characters."""
if search_term is not None:
params["search_term"] = search_term
# OPTIONAL - include
"""- All explanations can be seen in the {api:CoursesController#index Course API index documentation}
- "sections", "needs_grading_count" and "total_scores" are not valid options at the account level"""
if include is not None:
self._validate_enum(include, ["syllabus_body", "term", "course_progress", "storage_quota_used_mb", "total_students", "teachers"])
params["include"] = include
self.logger.debug("GET /api/v1/accounts/{account_id}/courses with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/accounts/{account_id}/courses".format(**path), data=data, params=params, all_pages=True) | python | def list_active_courses_in_account(self, account_id, by_subaccounts=None, by_teachers=None, completed=None, enrollment_term_id=None, enrollment_type=None, hide_enrollmentless_courses=None, include=None, published=None, search_term=None, state=None, with_enrollments=None):
"""
List active courses in an account.
Retrieve the list of courses in this account.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
"""ID"""
path["account_id"] = account_id
# OPTIONAL - with_enrollments
"""If true, include only courses with at least one enrollment. If false,
include only courses with no enrollments. If not present, do not filter
on course enrollment status."""
if with_enrollments is not None:
params["with_enrollments"] = with_enrollments
# OPTIONAL - enrollment_type
"""If set, only return courses that have at least one user enrolled in
in the course with one of the specified enrollment types."""
if enrollment_type is not None:
self._validate_enum(enrollment_type, ["teacher", "student", "ta", "observer", "designer"])
params["enrollment_type"] = enrollment_type
# OPTIONAL - published
"""If true, include only published courses. If false, exclude published
courses. If not present, do not filter on published status."""
if published is not None:
params["published"] = published
# OPTIONAL - completed
"""If true, include only completed courses (these may be in state
'completed', or their enrollment term may have ended). If false, exclude
completed courses. If not present, do not filter on completed status."""
if completed is not None:
params["completed"] = completed
# OPTIONAL - by_teachers
"""List of User IDs of teachers; if supplied, include only courses taught by
one of the referenced users."""
if by_teachers is not None:
params["by_teachers"] = by_teachers
# OPTIONAL - by_subaccounts
"""List of Account IDs; if supplied, include only courses associated with one
of the referenced subaccounts."""
if by_subaccounts is not None:
params["by_subaccounts"] = by_subaccounts
# OPTIONAL - hide_enrollmentless_courses
"""If present, only return courses that have at least one enrollment.
Equivalent to 'with_enrollments=true'; retained for compatibility."""
if hide_enrollmentless_courses is not None:
params["hide_enrollmentless_courses"] = hide_enrollmentless_courses
# OPTIONAL - state
"""If set, only return courses that are in the given state(s). By default,
all states but "deleted" are returned."""
if state is not None:
self._validate_enum(state, ["created", "claimed", "available", "completed", "deleted", "all"])
params["state"] = state
# OPTIONAL - enrollment_term_id
"""If set, only includes courses from the specified term."""
if enrollment_term_id is not None:
params["enrollment_term_id"] = enrollment_term_id
# OPTIONAL - search_term
"""The partial course name, code, or full ID to match and return in the results list. Must be at least 3 characters."""
if search_term is not None:
params["search_term"] = search_term
# OPTIONAL - include
"""- All explanations can be seen in the {api:CoursesController#index Course API index documentation}
- "sections", "needs_grading_count" and "total_scores" are not valid options at the account level"""
if include is not None:
self._validate_enum(include, ["syllabus_body", "term", "course_progress", "storage_quota_used_mb", "total_students", "teachers"])
params["include"] = include
self.logger.debug("GET /api/v1/accounts/{account_id}/courses with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/accounts/{account_id}/courses".format(**path), data=data, params=params, all_pages=True) | [
"def",
"list_active_courses_in_account",
"(",
"self",
",",
"account_id",
",",
"by_subaccounts",
"=",
"None",
",",
"by_teachers",
"=",
"None",
",",
"completed",
"=",
"None",
",",
"enrollment_term_id",
"=",
"None",
",",
"enrollment_type",
"=",
"None",
",",
"hide_e... | List active courses in an account.
Retrieve the list of courses in this account. | [
"List",
"active",
"courses",
"in",
"an",
"account",
".",
"Retrieve",
"the",
"list",
"of",
"courses",
"in",
"this",
"account",
"."
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/accounts.py#L101-L185 |
PGower/PyCanvas | pycanvas/apis/accounts.py | AccountsAPI.update_account | def update_account(self, id, account_default_group_storage_quota_mb=None, account_default_storage_quota_mb=None, account_default_time_zone=None, account_default_user_storage_quota_mb=None, account_name=None, account_services=None, account_settings_lock_all_announcements_locked=None, account_settings_lock_all_announcements_value=None, account_settings_restrict_student_future_listing_locked=None, account_settings_restrict_student_future_listing_value=None, account_settings_restrict_student_future_view_locked=None, account_settings_restrict_student_future_view_value=None, account_settings_restrict_student_past_view_locked=None, account_settings_restrict_student_past_view_value=None):
"""
Update an account.
Update an existing account.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - id
"""ID"""
path["id"] = id
# OPTIONAL - account[name]
"""Updates the account name"""
if account_name is not None:
data["account[name]"] = account_name
# OPTIONAL - account[default_time_zone]
"""The default time zone of the account. Allowed time zones are
{http://www.iana.org/time-zones IANA time zones} or friendlier
{http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html Ruby on Rails time zones}."""
if account_default_time_zone is not None:
data["account[default_time_zone]"] = account_default_time_zone
# OPTIONAL - account[default_storage_quota_mb]
"""The default course storage quota to be used, if not otherwise specified."""
if account_default_storage_quota_mb is not None:
data["account[default_storage_quota_mb]"] = account_default_storage_quota_mb
# OPTIONAL - account[default_user_storage_quota_mb]
"""The default user storage quota to be used, if not otherwise specified."""
if account_default_user_storage_quota_mb is not None:
data["account[default_user_storage_quota_mb]"] = account_default_user_storage_quota_mb
# OPTIONAL - account[default_group_storage_quota_mb]
"""The default group storage quota to be used, if not otherwise specified."""
if account_default_group_storage_quota_mb is not None:
data["account[default_group_storage_quota_mb]"] = account_default_group_storage_quota_mb
# OPTIONAL - account[settings][restrict_student_past_view][value]
"""Restrict students from viewing courses after end date"""
if account_settings_restrict_student_past_view_value is not None:
data["account[settings][restrict_student_past_view][value]"] = account_settings_restrict_student_past_view_value
# OPTIONAL - account[settings][restrict_student_past_view][locked]
"""Lock this setting for sub-accounts and courses"""
if account_settings_restrict_student_past_view_locked is not None:
data["account[settings][restrict_student_past_view][locked]"] = account_settings_restrict_student_past_view_locked
# OPTIONAL - account[settings][restrict_student_future_view][value]
"""Restrict students from viewing courses before start date"""
if account_settings_restrict_student_future_view_value is not None:
data["account[settings][restrict_student_future_view][value]"] = account_settings_restrict_student_future_view_value
# OPTIONAL - account[settings][restrict_student_future_view][locked]
"""Lock this setting for sub-accounts and courses"""
if account_settings_restrict_student_future_view_locked is not None:
data["account[settings][restrict_student_future_view][locked]"] = account_settings_restrict_student_future_view_locked
# OPTIONAL - account[settings][lock_all_announcements][value]
"""Disable comments on announcements"""
if account_settings_lock_all_announcements_value is not None:
data["account[settings][lock_all_announcements][value]"] = account_settings_lock_all_announcements_value
# OPTIONAL - account[settings][lock_all_announcements][locked]
"""Lock this setting for sub-accounts and courses"""
if account_settings_lock_all_announcements_locked is not None:
data["account[settings][lock_all_announcements][locked]"] = account_settings_lock_all_announcements_locked
# OPTIONAL - account[settings][restrict_student_future_listing][value]
"""Restrict students from viewing future enrollments in course list"""
if account_settings_restrict_student_future_listing_value is not None:
data["account[settings][restrict_student_future_listing][value]"] = account_settings_restrict_student_future_listing_value
# OPTIONAL - account[settings][restrict_student_future_listing][locked]
"""Lock this setting for sub-accounts and courses"""
if account_settings_restrict_student_future_listing_locked is not None:
data["account[settings][restrict_student_future_listing][locked]"] = account_settings_restrict_student_future_listing_locked
# OPTIONAL - account[services]
"""Give this a set of keys and boolean values to enable or disable services matching the keys"""
if account_services is not None:
data["account[services]"] = account_services
self.logger.debug("PUT /api/v1/accounts/{id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("PUT", "/api/v1/accounts/{id}".format(**path), data=data, params=params, single_item=True) | python | def update_account(self, id, account_default_group_storage_quota_mb=None, account_default_storage_quota_mb=None, account_default_time_zone=None, account_default_user_storage_quota_mb=None, account_name=None, account_services=None, account_settings_lock_all_announcements_locked=None, account_settings_lock_all_announcements_value=None, account_settings_restrict_student_future_listing_locked=None, account_settings_restrict_student_future_listing_value=None, account_settings_restrict_student_future_view_locked=None, account_settings_restrict_student_future_view_value=None, account_settings_restrict_student_past_view_locked=None, account_settings_restrict_student_past_view_value=None):
"""
Update an account.
Update an existing account.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - id
"""ID"""
path["id"] = id
# OPTIONAL - account[name]
"""Updates the account name"""
if account_name is not None:
data["account[name]"] = account_name
# OPTIONAL - account[default_time_zone]
"""The default time zone of the account. Allowed time zones are
{http://www.iana.org/time-zones IANA time zones} or friendlier
{http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html Ruby on Rails time zones}."""
if account_default_time_zone is not None:
data["account[default_time_zone]"] = account_default_time_zone
# OPTIONAL - account[default_storage_quota_mb]
"""The default course storage quota to be used, if not otherwise specified."""
if account_default_storage_quota_mb is not None:
data["account[default_storage_quota_mb]"] = account_default_storage_quota_mb
# OPTIONAL - account[default_user_storage_quota_mb]
"""The default user storage quota to be used, if not otherwise specified."""
if account_default_user_storage_quota_mb is not None:
data["account[default_user_storage_quota_mb]"] = account_default_user_storage_quota_mb
# OPTIONAL - account[default_group_storage_quota_mb]
"""The default group storage quota to be used, if not otherwise specified."""
if account_default_group_storage_quota_mb is not None:
data["account[default_group_storage_quota_mb]"] = account_default_group_storage_quota_mb
# OPTIONAL - account[settings][restrict_student_past_view][value]
"""Restrict students from viewing courses after end date"""
if account_settings_restrict_student_past_view_value is not None:
data["account[settings][restrict_student_past_view][value]"] = account_settings_restrict_student_past_view_value
# OPTIONAL - account[settings][restrict_student_past_view][locked]
"""Lock this setting for sub-accounts and courses"""
if account_settings_restrict_student_past_view_locked is not None:
data["account[settings][restrict_student_past_view][locked]"] = account_settings_restrict_student_past_view_locked
# OPTIONAL - account[settings][restrict_student_future_view][value]
"""Restrict students from viewing courses before start date"""
if account_settings_restrict_student_future_view_value is not None:
data["account[settings][restrict_student_future_view][value]"] = account_settings_restrict_student_future_view_value
# OPTIONAL - account[settings][restrict_student_future_view][locked]
"""Lock this setting for sub-accounts and courses"""
if account_settings_restrict_student_future_view_locked is not None:
data["account[settings][restrict_student_future_view][locked]"] = account_settings_restrict_student_future_view_locked
# OPTIONAL - account[settings][lock_all_announcements][value]
"""Disable comments on announcements"""
if account_settings_lock_all_announcements_value is not None:
data["account[settings][lock_all_announcements][value]"] = account_settings_lock_all_announcements_value
# OPTIONAL - account[settings][lock_all_announcements][locked]
"""Lock this setting for sub-accounts and courses"""
if account_settings_lock_all_announcements_locked is not None:
data["account[settings][lock_all_announcements][locked]"] = account_settings_lock_all_announcements_locked
# OPTIONAL - account[settings][restrict_student_future_listing][value]
"""Restrict students from viewing future enrollments in course list"""
if account_settings_restrict_student_future_listing_value is not None:
data["account[settings][restrict_student_future_listing][value]"] = account_settings_restrict_student_future_listing_value
# OPTIONAL - account[settings][restrict_student_future_listing][locked]
"""Lock this setting for sub-accounts and courses"""
if account_settings_restrict_student_future_listing_locked is not None:
data["account[settings][restrict_student_future_listing][locked]"] = account_settings_restrict_student_future_listing_locked
# OPTIONAL - account[services]
"""Give this a set of keys and boolean values to enable or disable services matching the keys"""
if account_services is not None:
data["account[services]"] = account_services
self.logger.debug("PUT /api/v1/accounts/{id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("PUT", "/api/v1/accounts/{id}".format(**path), data=data, params=params, single_item=True) | [
"def",
"update_account",
"(",
"self",
",",
"id",
",",
"account_default_group_storage_quota_mb",
"=",
"None",
",",
"account_default_storage_quota_mb",
"=",
"None",
",",
"account_default_time_zone",
"=",
"None",
",",
"account_default_user_storage_quota_mb",
"=",
"None",
","... | Update an account.
Update an existing account. | [
"Update",
"an",
"account",
".",
"Update",
"an",
"existing",
"account",
"."
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/accounts.py#L187-L274 |
PGower/PyCanvas | pycanvas/apis/accounts.py | AccountsAPI.create_new_sub_account | def create_new_sub_account(self, account_id, account_name, account_default_group_storage_quota_mb=None, account_default_storage_quota_mb=None, account_default_user_storage_quota_mb=None, account_sis_account_id=None):
"""
Create a new sub-account.
Add a new sub-account to a given account.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
"""ID"""
path["account_id"] = account_id
# REQUIRED - account[name]
"""The name of the new sub-account."""
data["account[name]"] = account_name
# OPTIONAL - account[sis_account_id]
"""The account's identifier in the Student Information System."""
if account_sis_account_id is not None:
data["account[sis_account_id]"] = account_sis_account_id
# OPTIONAL - account[default_storage_quota_mb]
"""The default course storage quota to be used, if not otherwise specified."""
if account_default_storage_quota_mb is not None:
data["account[default_storage_quota_mb]"] = account_default_storage_quota_mb
# OPTIONAL - account[default_user_storage_quota_mb]
"""The default user storage quota to be used, if not otherwise specified."""
if account_default_user_storage_quota_mb is not None:
data["account[default_user_storage_quota_mb]"] = account_default_user_storage_quota_mb
# OPTIONAL - account[default_group_storage_quota_mb]
"""The default group storage quota to be used, if not otherwise specified."""
if account_default_group_storage_quota_mb is not None:
data["account[default_group_storage_quota_mb]"] = account_default_group_storage_quota_mb
self.logger.debug("POST /api/v1/accounts/{account_id}/sub_accounts with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/accounts/{account_id}/sub_accounts".format(**path), data=data, params=params, single_item=True) | python | def create_new_sub_account(self, account_id, account_name, account_default_group_storage_quota_mb=None, account_default_storage_quota_mb=None, account_default_user_storage_quota_mb=None, account_sis_account_id=None):
"""
Create a new sub-account.
Add a new sub-account to a given account.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
"""ID"""
path["account_id"] = account_id
# REQUIRED - account[name]
"""The name of the new sub-account."""
data["account[name]"] = account_name
# OPTIONAL - account[sis_account_id]
"""The account's identifier in the Student Information System."""
if account_sis_account_id is not None:
data["account[sis_account_id]"] = account_sis_account_id
# OPTIONAL - account[default_storage_quota_mb]
"""The default course storage quota to be used, if not otherwise specified."""
if account_default_storage_quota_mb is not None:
data["account[default_storage_quota_mb]"] = account_default_storage_quota_mb
# OPTIONAL - account[default_user_storage_quota_mb]
"""The default user storage quota to be used, if not otherwise specified."""
if account_default_user_storage_quota_mb is not None:
data["account[default_user_storage_quota_mb]"] = account_default_user_storage_quota_mb
# OPTIONAL - account[default_group_storage_quota_mb]
"""The default group storage quota to be used, if not otherwise specified."""
if account_default_group_storage_quota_mb is not None:
data["account[default_group_storage_quota_mb]"] = account_default_group_storage_quota_mb
self.logger.debug("POST /api/v1/accounts/{account_id}/sub_accounts with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/accounts/{account_id}/sub_accounts".format(**path), data=data, params=params, single_item=True) | [
"def",
"create_new_sub_account",
"(",
"self",
",",
"account_id",
",",
"account_name",
",",
"account_default_group_storage_quota_mb",
"=",
"None",
",",
"account_default_storage_quota_mb",
"=",
"None",
",",
"account_default_user_storage_quota_mb",
"=",
"None",
",",
"account_s... | Create a new sub-account.
Add a new sub-account to a given account. | [
"Create",
"a",
"new",
"sub",
"-",
"account",
".",
"Add",
"a",
"new",
"sub",
"-",
"account",
"to",
"a",
"given",
"account",
"."
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/accounts.py#L303-L342 |
mrstephenneal/mysql-toolkit | mysql/toolkit/components/manipulate/__init__.py | Delete.delete | def delete(self, table, where=None):
"""Delete existing rows from a table."""
if where:
where_key, where_val = where
query = "DELETE FROM {0} WHERE {1}='{2}'".format(wrap(table), where_key, where_val)
else:
query = 'DELETE FROM {0}'.format(wrap(table))
self.execute(query)
return True | python | def delete(self, table, where=None):
"""Delete existing rows from a table."""
if where:
where_key, where_val = where
query = "DELETE FROM {0} WHERE {1}='{2}'".format(wrap(table), where_key, where_val)
else:
query = 'DELETE FROM {0}'.format(wrap(table))
self.execute(query)
return True | [
"def",
"delete",
"(",
"self",
",",
"table",
",",
"where",
"=",
"None",
")",
":",
"if",
"where",
":",
"where_key",
",",
"where_val",
"=",
"where",
"query",
"=",
"\"DELETE FROM {0} WHERE {1}='{2}'\"",
".",
"format",
"(",
"wrap",
"(",
"table",
")",
",",
"wh... | Delete existing rows from a table. | [
"Delete",
"existing",
"rows",
"from",
"a",
"table",
"."
] | train | https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/manipulate/__init__.py#L8-L16 |
bioasp/caspo | caspo/visualize.py | coloured_network | def coloured_network(network, setup, filename):
"""
Plots a coloured (hyper-)graph to a dot file
Parameters
----------
network : object
An object implementing a method `__plot__` which must return the `networkx.MultiDiGraph`_ instance to be coloured.
Typically, it will be an instance of either :class:`caspo.core.graph.Graph`, :class:`caspo.core.logicalnetwork.LogicalNetwork`
or :class:`caspo.core.logicalnetwork.LogicalNetworkList`
setup : :class:`caspo.core.setup.Setup`
Experimental setup to be coloured in the network
.. _networkx.MultiDiGraph: https://networkx.readthedocs.io/en/stable/reference/classes.multidigraph.html#networkx.MultiDiGraph
"""
NODES_ATTR = {
'DEFAULT': {'color': 'black', 'fillcolor': 'white', 'style': 'filled, bold', 'fontname': 'Helvetica', 'fontsize': 18, 'shape': 'ellipse'},
'STIMULI': {'color': 'olivedrab3', 'fillcolor': 'olivedrab3'},
'INHIBITOR': {'color': 'orangered', 'fillcolor': 'orangered'},
'READOUT': {'color': 'lightblue', 'fillcolor': 'lightblue'},
'INHOUT': {'color': 'orangered', 'fillcolor': 'SkyBlue2', 'style': 'filled, bold, diagonals'},
'GATE' : {'fillcolor': 'black', 'fixedsize': True, 'width': 0.2, 'height': 0.2, 'label': '.'}
}
EDGES_ATTR = {
'DEFAULT': {'dir': 'forward', 'penwidth': 2.5},
1 : {'color': 'forestgreen', 'arrowhead': 'normal'},
-1 : {'color': 'red', 'arrowhead': 'tee'}
}
graph = network.__plot__()
for node in graph.nodes():
_type = 'DEFAULT'
for attr, value in NODES_ATTR[_type].items():
graph.node[node][attr] = value
if 'gate' in graph.node[node]:
_type = 'GATE'
elif node in setup.stimuli:
_type = 'STIMULI'
elif node in setup.readouts and node in setup.inhibitors:
_type = 'INHOUT'
elif node in setup.readouts:
_type = 'READOUT'
elif node in setup.inhibitors:
_type = 'INHIBITOR'
if _type != 'DEFAULT':
for attr, value in NODES_ATTR[_type].items():
graph.node[node][attr] = value
for source, target in graph.edges():
for k in graph.edge[source][target]:
for attr, value in EDGES_ATTR['DEFAULT'].items():
graph.edge[source][target][k][attr] = value
for attr, value in EDGES_ATTR[graph.edge[source][target][k]['sign']].items():
graph.edge[source][target][k][attr] = value
if 'weight' in graph.edge[source][target][k]:
graph.edge[source][target][k]['penwidth'] = 5 * graph.edge[source][target][k]['weight']
write_dot(graph, filename) | python | def coloured_network(network, setup, filename):
"""
Plots a coloured (hyper-)graph to a dot file
Parameters
----------
network : object
An object implementing a method `__plot__` which must return the `networkx.MultiDiGraph`_ instance to be coloured.
Typically, it will be an instance of either :class:`caspo.core.graph.Graph`, :class:`caspo.core.logicalnetwork.LogicalNetwork`
or :class:`caspo.core.logicalnetwork.LogicalNetworkList`
setup : :class:`caspo.core.setup.Setup`
Experimental setup to be coloured in the network
.. _networkx.MultiDiGraph: https://networkx.readthedocs.io/en/stable/reference/classes.multidigraph.html#networkx.MultiDiGraph
"""
NODES_ATTR = {
'DEFAULT': {'color': 'black', 'fillcolor': 'white', 'style': 'filled, bold', 'fontname': 'Helvetica', 'fontsize': 18, 'shape': 'ellipse'},
'STIMULI': {'color': 'olivedrab3', 'fillcolor': 'olivedrab3'},
'INHIBITOR': {'color': 'orangered', 'fillcolor': 'orangered'},
'READOUT': {'color': 'lightblue', 'fillcolor': 'lightblue'},
'INHOUT': {'color': 'orangered', 'fillcolor': 'SkyBlue2', 'style': 'filled, bold, diagonals'},
'GATE' : {'fillcolor': 'black', 'fixedsize': True, 'width': 0.2, 'height': 0.2, 'label': '.'}
}
EDGES_ATTR = {
'DEFAULT': {'dir': 'forward', 'penwidth': 2.5},
1 : {'color': 'forestgreen', 'arrowhead': 'normal'},
-1 : {'color': 'red', 'arrowhead': 'tee'}
}
graph = network.__plot__()
for node in graph.nodes():
_type = 'DEFAULT'
for attr, value in NODES_ATTR[_type].items():
graph.node[node][attr] = value
if 'gate' in graph.node[node]:
_type = 'GATE'
elif node in setup.stimuli:
_type = 'STIMULI'
elif node in setup.readouts and node in setup.inhibitors:
_type = 'INHOUT'
elif node in setup.readouts:
_type = 'READOUT'
elif node in setup.inhibitors:
_type = 'INHIBITOR'
if _type != 'DEFAULT':
for attr, value in NODES_ATTR[_type].items():
graph.node[node][attr] = value
for source, target in graph.edges():
for k in graph.edge[source][target]:
for attr, value in EDGES_ATTR['DEFAULT'].items():
graph.edge[source][target][k][attr] = value
for attr, value in EDGES_ATTR[graph.edge[source][target][k]['sign']].items():
graph.edge[source][target][k][attr] = value
if 'weight' in graph.edge[source][target][k]:
graph.edge[source][target][k]['penwidth'] = 5 * graph.edge[source][target][k]['weight']
write_dot(graph, filename) | [
"def",
"coloured_network",
"(",
"network",
",",
"setup",
",",
"filename",
")",
":",
"NODES_ATTR",
"=",
"{",
"'DEFAULT'",
":",
"{",
"'color'",
":",
"'black'",
",",
"'fillcolor'",
":",
"'white'",
",",
"'style'",
":",
"'filled, bold'",
",",
"'fontname'",
":",
... | Plots a coloured (hyper-)graph to a dot file
Parameters
----------
network : object
An object implementing a method `__plot__` which must return the `networkx.MultiDiGraph`_ instance to be coloured.
Typically, it will be an instance of either :class:`caspo.core.graph.Graph`, :class:`caspo.core.logicalnetwork.LogicalNetwork`
or :class:`caspo.core.logicalnetwork.LogicalNetworkList`
setup : :class:`caspo.core.setup.Setup`
Experimental setup to be coloured in the network
.. _networkx.MultiDiGraph: https://networkx.readthedocs.io/en/stable/reference/classes.multidigraph.html#networkx.MultiDiGraph | [
"Plots",
"a",
"coloured",
"(",
"hyper",
"-",
")",
"graph",
"to",
"a",
"dot",
"file"
] | train | https://github.com/bioasp/caspo/blob/a68d1eace75b9b08f23633d1fb5ce6134403959e/caspo/visualize.py#L26-L91 |
bioasp/caspo | caspo/visualize.py | networks_distribution | def networks_distribution(df, filepath=None):
"""
Generates two alternative plots describing the distribution of
variables `mse` and `size`. It is intended to be used over a list
of logical networks.
Parameters
----------
df: `pandas.DataFrame`_
DataFrame with columns `mse` and `size`
filepath: str
Absolute path to a folder where to write the plots
Returns
-------
tuple
Generated plots
.. _pandas.DataFrame: http://pandas.pydata.org/pandas-docs/stable/dsintro.html#dataframe
"""
df.mse = df.mse.map(lambda f: "%.4f" % f)
g = sns.JointGrid(x="mse", y="size", data=df)
g.plot_joint(sns.violinplot, scale='count')
g.ax_joint.set_yticks(range(df['size'].min(), df['size'].max() + 1))
g.ax_joint.set_yticklabels(range(df['size'].min(), df['size'].max() + 1))
for tick in g.ax_joint.get_xticklabels():
tick.set_rotation(90)
g.ax_joint.set_xlabel("MSE")
g.ax_joint.set_ylabel("Size")
for i, t in enumerate(g.ax_joint.get_xticklabels()):
c = df[df['mse'] == t.get_text()].shape[0]
g.ax_marg_x.annotate(c, xy=(i, 0.5), va="center", ha="center", size=20, rotation=90)
for i, t in enumerate(g.ax_joint.get_yticklabels()):
s = int(t.get_text())
c = df[df['size'] == s].shape[0]
g.ax_marg_y.annotate(c, xy=(0.5, s), va="center", ha="center", size=20)
if filepath:
g.savefig(os.path.join(filepath, 'networks-distribution.pdf'))
plt.figure()
counts = df[["size", "mse"]].reset_index(level=0).groupby(["size", "mse"], as_index=False).count()
cp = counts.pivot("size", "mse", "index").sort_index()
ax = sns.heatmap(cp, annot=True, fmt=".0f", linewidths=.5)
ax.set_xlabel("MSE")
ax.set_ylabel("Size")
if filepath:
plt.savefig(os.path.join(filepath, 'networks-heatmap.pdf'))
return g, ax | python | def networks_distribution(df, filepath=None):
"""
Generates two alternative plots describing the distribution of
variables `mse` and `size`. It is intended to be used over a list
of logical networks.
Parameters
----------
df: `pandas.DataFrame`_
DataFrame with columns `mse` and `size`
filepath: str
Absolute path to a folder where to write the plots
Returns
-------
tuple
Generated plots
.. _pandas.DataFrame: http://pandas.pydata.org/pandas-docs/stable/dsintro.html#dataframe
"""
df.mse = df.mse.map(lambda f: "%.4f" % f)
g = sns.JointGrid(x="mse", y="size", data=df)
g.plot_joint(sns.violinplot, scale='count')
g.ax_joint.set_yticks(range(df['size'].min(), df['size'].max() + 1))
g.ax_joint.set_yticklabels(range(df['size'].min(), df['size'].max() + 1))
for tick in g.ax_joint.get_xticklabels():
tick.set_rotation(90)
g.ax_joint.set_xlabel("MSE")
g.ax_joint.set_ylabel("Size")
for i, t in enumerate(g.ax_joint.get_xticklabels()):
c = df[df['mse'] == t.get_text()].shape[0]
g.ax_marg_x.annotate(c, xy=(i, 0.5), va="center", ha="center", size=20, rotation=90)
for i, t in enumerate(g.ax_joint.get_yticklabels()):
s = int(t.get_text())
c = df[df['size'] == s].shape[0]
g.ax_marg_y.annotate(c, xy=(0.5, s), va="center", ha="center", size=20)
if filepath:
g.savefig(os.path.join(filepath, 'networks-distribution.pdf'))
plt.figure()
counts = df[["size", "mse"]].reset_index(level=0).groupby(["size", "mse"], as_index=False).count()
cp = counts.pivot("size", "mse", "index").sort_index()
ax = sns.heatmap(cp, annot=True, fmt=".0f", linewidths=.5)
ax.set_xlabel("MSE")
ax.set_ylabel("Size")
if filepath:
plt.savefig(os.path.join(filepath, 'networks-heatmap.pdf'))
return g, ax | [
"def",
"networks_distribution",
"(",
"df",
",",
"filepath",
"=",
"None",
")",
":",
"df",
".",
"mse",
"=",
"df",
".",
"mse",
".",
"map",
"(",
"lambda",
"f",
":",
"\"%.4f\"",
"%",
"f",
")",
"g",
"=",
"sns",
".",
"JointGrid",
"(",
"x",
"=",
"\"mse\"... | Generates two alternative plots describing the distribution of
variables `mse` and `size`. It is intended to be used over a list
of logical networks.
Parameters
----------
df: `pandas.DataFrame`_
DataFrame with columns `mse` and `size`
filepath: str
Absolute path to a folder where to write the plots
Returns
-------
tuple
Generated plots
.. _pandas.DataFrame: http://pandas.pydata.org/pandas-docs/stable/dsintro.html#dataframe | [
"Generates",
"two",
"alternative",
"plots",
"describing",
"the",
"distribution",
"of",
"variables",
"mse",
"and",
"size",
".",
"It",
"is",
"intended",
"to",
"be",
"used",
"over",
"a",
"list",
"of",
"logical",
"networks",
"."
] | train | https://github.com/bioasp/caspo/blob/a68d1eace75b9b08f23633d1fb5ce6134403959e/caspo/visualize.py#L94-L156 |
bioasp/caspo | caspo/visualize.py | mappings_frequency | def mappings_frequency(df, filepath=None):
"""
Plots the frequency of logical conjunction mappings
Parameters
----------
df: `pandas.DataFrame`_
DataFrame with columns `frequency` and `mapping`
filepath: str
Absolute path to a folder where to write the plot
Returns
-------
plot
Generated plot
.. _pandas.DataFrame: http://pandas.pydata.org/pandas-docs/stable/dsintro.html#dataframe
"""
df = df.sort_values('frequency')
df['conf'] = df.frequency.map(lambda f: 0 if f < 0.2 else 1 if f < 0.8 else 2)
g = sns.factorplot(x="mapping", y="frequency", data=df, aspect=3, hue='conf', legend=False)
for tick in g.ax.get_xticklabels():
tick.set_rotation(90)
g.ax.set_ylim([-.05, 1.05])
g.ax.set_xlabel("Logical mapping")
g.ax.set_ylabel("Frequency")
if filepath:
g.savefig(os.path.join(filepath, 'mappings-frequency.pdf'))
return g | python | def mappings_frequency(df, filepath=None):
"""
Plots the frequency of logical conjunction mappings
Parameters
----------
df: `pandas.DataFrame`_
DataFrame with columns `frequency` and `mapping`
filepath: str
Absolute path to a folder where to write the plot
Returns
-------
plot
Generated plot
.. _pandas.DataFrame: http://pandas.pydata.org/pandas-docs/stable/dsintro.html#dataframe
"""
df = df.sort_values('frequency')
df['conf'] = df.frequency.map(lambda f: 0 if f < 0.2 else 1 if f < 0.8 else 2)
g = sns.factorplot(x="mapping", y="frequency", data=df, aspect=3, hue='conf', legend=False)
for tick in g.ax.get_xticklabels():
tick.set_rotation(90)
g.ax.set_ylim([-.05, 1.05])
g.ax.set_xlabel("Logical mapping")
g.ax.set_ylabel("Frequency")
if filepath:
g.savefig(os.path.join(filepath, 'mappings-frequency.pdf'))
return g | [
"def",
"mappings_frequency",
"(",
"df",
",",
"filepath",
"=",
"None",
")",
":",
"df",
"=",
"df",
".",
"sort_values",
"(",
"'frequency'",
")",
"df",
"[",
"'conf'",
"]",
"=",
"df",
".",
"frequency",
".",
"map",
"(",
"lambda",
"f",
":",
"0",
"if",
"f"... | Plots the frequency of logical conjunction mappings
Parameters
----------
df: `pandas.DataFrame`_
DataFrame with columns `frequency` and `mapping`
filepath: str
Absolute path to a folder where to write the plot
Returns
-------
plot
Generated plot
.. _pandas.DataFrame: http://pandas.pydata.org/pandas-docs/stable/dsintro.html#dataframe | [
"Plots",
"the",
"frequency",
"of",
"logical",
"conjunction",
"mappings"
] | train | https://github.com/bioasp/caspo/blob/a68d1eace75b9b08f23633d1fb5ce6134403959e/caspo/visualize.py#L158-L195 |
bioasp/caspo | caspo/visualize.py | behaviors_distribution | def behaviors_distribution(df, filepath=None):
"""
Plots the distribution of logical networks across input-output behaviors.
Optionally, input-output behaviors can be grouped by MSE.
Parameters
----------
df: `pandas.DataFrame`_
DataFrame with columns `networks` and optionally `mse`
filepath: str
Absolute path to a folder where to write the plot
Returns
-------
plot
Generated plot
.. _pandas.DataFrame: http://pandas.pydata.org/pandas-docs/stable/dsintro.html#dataframe
"""
cols = ["networks", "index"]
rcols = ["Logical networks", "Input-Output behaviors"]
sort_cols = ["networks"]
if "mse" in df.columns:
cols.append("mse")
rcols.append("MSE")
sort_cols = ["mse"] + sort_cols
df.mse = df.mse.map(lambda f: "%.4f" % f)
df = df.sort_values(sort_cols).reset_index(drop=True).reset_index(level=0)[cols]
df.columns = rcols
if "MSE" in df.columns:
g = sns.factorplot(x='Input-Output behaviors', y='Logical networks', hue='MSE', data=df, aspect=3, kind='bar', legend_out=False)
else:
g = sns.factorplot(x='Input-Output behaviors', y='Logical networks', data=df, aspect=3, kind='bar', legend_out=False)
g.ax.set_xticks([])
if filepath:
g.savefig(os.path.join(filepath, 'behaviors-distribution.pdf'))
return g | python | def behaviors_distribution(df, filepath=None):
"""
Plots the distribution of logical networks across input-output behaviors.
Optionally, input-output behaviors can be grouped by MSE.
Parameters
----------
df: `pandas.DataFrame`_
DataFrame with columns `networks` and optionally `mse`
filepath: str
Absolute path to a folder where to write the plot
Returns
-------
plot
Generated plot
.. _pandas.DataFrame: http://pandas.pydata.org/pandas-docs/stable/dsintro.html#dataframe
"""
cols = ["networks", "index"]
rcols = ["Logical networks", "Input-Output behaviors"]
sort_cols = ["networks"]
if "mse" in df.columns:
cols.append("mse")
rcols.append("MSE")
sort_cols = ["mse"] + sort_cols
df.mse = df.mse.map(lambda f: "%.4f" % f)
df = df.sort_values(sort_cols).reset_index(drop=True).reset_index(level=0)[cols]
df.columns = rcols
if "MSE" in df.columns:
g = sns.factorplot(x='Input-Output behaviors', y='Logical networks', hue='MSE', data=df, aspect=3, kind='bar', legend_out=False)
else:
g = sns.factorplot(x='Input-Output behaviors', y='Logical networks', data=df, aspect=3, kind='bar', legend_out=False)
g.ax.set_xticks([])
if filepath:
g.savefig(os.path.join(filepath, 'behaviors-distribution.pdf'))
return g | [
"def",
"behaviors_distribution",
"(",
"df",
",",
"filepath",
"=",
"None",
")",
":",
"cols",
"=",
"[",
"\"networks\"",
",",
"\"index\"",
"]",
"rcols",
"=",
"[",
"\"Logical networks\"",
",",
"\"Input-Output behaviors\"",
"]",
"sort_cols",
"=",
"[",
"\"networks\"",... | Plots the distribution of logical networks across input-output behaviors.
Optionally, input-output behaviors can be grouped by MSE.
Parameters
----------
df: `pandas.DataFrame`_
DataFrame with columns `networks` and optionally `mse`
filepath: str
Absolute path to a folder where to write the plot
Returns
-------
plot
Generated plot
.. _pandas.DataFrame: http://pandas.pydata.org/pandas-docs/stable/dsintro.html#dataframe | [
"Plots",
"the",
"distribution",
"of",
"logical",
"networks",
"across",
"input",
"-",
"output",
"behaviors",
".",
"Optionally",
"input",
"-",
"output",
"behaviors",
"can",
"be",
"grouped",
"by",
"MSE",
"."
] | train | https://github.com/bioasp/caspo/blob/a68d1eace75b9b08f23633d1fb5ce6134403959e/caspo/visualize.py#L197-L242 |
bioasp/caspo | caspo/visualize.py | experimental_designs | def experimental_designs(df, filepath=None):
"""
For each experimental design it plot all the corresponding
experimental conditions in a different plot
Parameters
----------
df: `pandas.DataFrame`_
DataFrame with columns `id` and starting with `TR:`
filepath: str
Absolute path to a folder where to write the plot
Returns
-------
list
Generated plots
.. _pandas.DataFrame: http://pandas.pydata.org/pandas-docs/stable/dsintro.html#dataframe
"""
axes = []
bw = matplotlib.colors.ListedColormap(['white', 'black'])
cols = df.columns
for i, dd in df.groupby("id"):
cues = dd.drop([c for c in cols if not c.startswith("TR:")] + ["id"], axis=1).reset_index(drop=True)
cues.columns = [c[3:] for c in cues.columns]
plt.figure(figsize=(max((len(cues.columns)-1) * .5, 4), max(len(cues)*0.6, 2.5)))
ax = sns.heatmap(cues, linewidths=.5, cbar=False, cmap=bw, linecolor='gray')
_ = [t.set_color('r') if t.get_text().endswith('i') else t.set_color('g') for t in ax.xaxis.get_ticklabels()]
ax.set_xlabel("Stimuli (green) and Inhibitors (red)")
ax.set_ylabel("Experimental condition")
plt.tight_layout()
axes.append(ax)
if filepath:
plt.savefig(os.path.join(filepath, 'design-%s.pdf' % i))
return axes | python | def experimental_designs(df, filepath=None):
"""
For each experimental design it plot all the corresponding
experimental conditions in a different plot
Parameters
----------
df: `pandas.DataFrame`_
DataFrame with columns `id` and starting with `TR:`
filepath: str
Absolute path to a folder where to write the plot
Returns
-------
list
Generated plots
.. _pandas.DataFrame: http://pandas.pydata.org/pandas-docs/stable/dsintro.html#dataframe
"""
axes = []
bw = matplotlib.colors.ListedColormap(['white', 'black'])
cols = df.columns
for i, dd in df.groupby("id"):
cues = dd.drop([c for c in cols if not c.startswith("TR:")] + ["id"], axis=1).reset_index(drop=True)
cues.columns = [c[3:] for c in cues.columns]
plt.figure(figsize=(max((len(cues.columns)-1) * .5, 4), max(len(cues)*0.6, 2.5)))
ax = sns.heatmap(cues, linewidths=.5, cbar=False, cmap=bw, linecolor='gray')
_ = [t.set_color('r') if t.get_text().endswith('i') else t.set_color('g') for t in ax.xaxis.get_ticklabels()]
ax.set_xlabel("Stimuli (green) and Inhibitors (red)")
ax.set_ylabel("Experimental condition")
plt.tight_layout()
axes.append(ax)
if filepath:
plt.savefig(os.path.join(filepath, 'design-%s.pdf' % i))
return axes | [
"def",
"experimental_designs",
"(",
"df",
",",
"filepath",
"=",
"None",
")",
":",
"axes",
"=",
"[",
"]",
"bw",
"=",
"matplotlib",
".",
"colors",
".",
"ListedColormap",
"(",
"[",
"'white'",
",",
"'black'",
"]",
")",
"cols",
"=",
"df",
".",
"columns",
... | For each experimental design it plot all the corresponding
experimental conditions in a different plot
Parameters
----------
df: `pandas.DataFrame`_
DataFrame with columns `id` and starting with `TR:`
filepath: str
Absolute path to a folder where to write the plot
Returns
-------
list
Generated plots
.. _pandas.DataFrame: http://pandas.pydata.org/pandas-docs/stable/dsintro.html#dataframe | [
"For",
"each",
"experimental",
"design",
"it",
"plot",
"all",
"the",
"corresponding",
"experimental",
"conditions",
"in",
"a",
"different",
"plot"
] | train | https://github.com/bioasp/caspo/blob/a68d1eace75b9b08f23633d1fb5ce6134403959e/caspo/visualize.py#L244-L288 |
bioasp/caspo | caspo/visualize.py | differences_distribution | def differences_distribution(df, filepath=None):
"""
For each experimental design it plot all the corresponding
generated differences in different plots
Parameters
----------
df: `pandas.DataFrame`_
DataFrame with columns `id`, `pairs`, and starting with `DIF:`
filepath: str
Absolute path to a folder where to write the plots
Returns
-------
list
Generated plots
.. _pandas.DataFrame: http://pandas.pydata.org/pandas-docs/stable/dsintro.html#dataframe
"""
axes = []
cols = df.columns
for i, dd in df.groupby("id"):
palette = sns.color_palette("Set1", len(dd))
plt.figure()
readouts = dd.drop([c for c in cols if not c.startswith("DIF:")] + ["id"], axis=1).reset_index(drop=True)
readouts.columns = [c[4:] for c in readouts.columns]
ax1 = readouts.T.plot(kind='bar', stacked=True, color=palette)
ax1.set_xlabel("Readout")
ax1.set_ylabel("Pairwise differences")
plt.tight_layout()
if filepath:
plt.savefig(os.path.join(filepath, 'design-%s-readouts.pdf' % i))
plt.figure()
behaviors = dd[["pairs"]].reset_index(drop=True)
ax2 = behaviors.plot.bar(color=palette, legend=False)
ax2.set_xlabel("Experimental condition")
ax2.set_ylabel("Pairs of input-output behaviors")
plt.tight_layout()
if filepath:
plt.savefig(os.path.join(filepath, 'design-%s-behaviors.pdf' % i))
axes.append((ax1, ax2))
return axes | python | def differences_distribution(df, filepath=None):
"""
For each experimental design it plot all the corresponding
generated differences in different plots
Parameters
----------
df: `pandas.DataFrame`_
DataFrame with columns `id`, `pairs`, and starting with `DIF:`
filepath: str
Absolute path to a folder where to write the plots
Returns
-------
list
Generated plots
.. _pandas.DataFrame: http://pandas.pydata.org/pandas-docs/stable/dsintro.html#dataframe
"""
axes = []
cols = df.columns
for i, dd in df.groupby("id"):
palette = sns.color_palette("Set1", len(dd))
plt.figure()
readouts = dd.drop([c for c in cols if not c.startswith("DIF:")] + ["id"], axis=1).reset_index(drop=True)
readouts.columns = [c[4:] for c in readouts.columns]
ax1 = readouts.T.plot(kind='bar', stacked=True, color=palette)
ax1.set_xlabel("Readout")
ax1.set_ylabel("Pairwise differences")
plt.tight_layout()
if filepath:
plt.savefig(os.path.join(filepath, 'design-%s-readouts.pdf' % i))
plt.figure()
behaviors = dd[["pairs"]].reset_index(drop=True)
ax2 = behaviors.plot.bar(color=palette, legend=False)
ax2.set_xlabel("Experimental condition")
ax2.set_ylabel("Pairs of input-output behaviors")
plt.tight_layout()
if filepath:
plt.savefig(os.path.join(filepath, 'design-%s-behaviors.pdf' % i))
axes.append((ax1, ax2))
return axes | [
"def",
"differences_distribution",
"(",
"df",
",",
"filepath",
"=",
"None",
")",
":",
"axes",
"=",
"[",
"]",
"cols",
"=",
"df",
".",
"columns",
"for",
"i",
",",
"dd",
"in",
"df",
".",
"groupby",
"(",
"\"id\"",
")",
":",
"palette",
"=",
"sns",
".",
... | For each experimental design it plot all the corresponding
generated differences in different plots
Parameters
----------
df: `pandas.DataFrame`_
DataFrame with columns `id`, `pairs`, and starting with `DIF:`
filepath: str
Absolute path to a folder where to write the plots
Returns
-------
list
Generated plots
.. _pandas.DataFrame: http://pandas.pydata.org/pandas-docs/stable/dsintro.html#dataframe | [
"For",
"each",
"experimental",
"design",
"it",
"plot",
"all",
"the",
"corresponding",
"generated",
"differences",
"in",
"different",
"plots"
] | train | https://github.com/bioasp/caspo/blob/a68d1eace75b9b08f23633d1fb5ce6134403959e/caspo/visualize.py#L290-L344 |
bioasp/caspo | caspo/visualize.py | predictions_variance | def predictions_variance(df, filepath=None):
"""
Plots the mean variance prediction for each readout
Parameters
----------
df: `pandas.DataFrame`_
DataFrame with columns starting with `VAR:`
filepath: str
Absolute path to a folder where to write the plots
Returns
-------
plot
Generated plot
.. _pandas.DataFrame: http://pandas.pydata.org/pandas-docs/stable/dsintro.html#dataframe
"""
df = df.filter(regex="^VAR:")
by_readout = df.mean(axis=0).reset_index(level=0)
by_readout.columns = ['Readout', 'Prediction variance (mean)']
by_readout['Readout'] = by_readout.Readout.map(lambda n: n[4:])
g1 = sns.factorplot(x='Readout', y='Prediction variance (mean)', data=by_readout, kind='bar', aspect=2)
for tick in g1.ax.get_xticklabels():
tick.set_rotation(90)
if filepath:
g1.savefig(os.path.join(filepath, 'predictions-variance.pdf'))
return g1 | python | def predictions_variance(df, filepath=None):
"""
Plots the mean variance prediction for each readout
Parameters
----------
df: `pandas.DataFrame`_
DataFrame with columns starting with `VAR:`
filepath: str
Absolute path to a folder where to write the plots
Returns
-------
plot
Generated plot
.. _pandas.DataFrame: http://pandas.pydata.org/pandas-docs/stable/dsintro.html#dataframe
"""
df = df.filter(regex="^VAR:")
by_readout = df.mean(axis=0).reset_index(level=0)
by_readout.columns = ['Readout', 'Prediction variance (mean)']
by_readout['Readout'] = by_readout.Readout.map(lambda n: n[4:])
g1 = sns.factorplot(x='Readout', y='Prediction variance (mean)', data=by_readout, kind='bar', aspect=2)
for tick in g1.ax.get_xticklabels():
tick.set_rotation(90)
if filepath:
g1.savefig(os.path.join(filepath, 'predictions-variance.pdf'))
return g1 | [
"def",
"predictions_variance",
"(",
"df",
",",
"filepath",
"=",
"None",
")",
":",
"df",
"=",
"df",
".",
"filter",
"(",
"regex",
"=",
"\"^VAR:\"",
")",
"by_readout",
"=",
"df",
".",
"mean",
"(",
"axis",
"=",
"0",
")",
".",
"reset_index",
"(",
"level",... | Plots the mean variance prediction for each readout
Parameters
----------
df: `pandas.DataFrame`_
DataFrame with columns starting with `VAR:`
filepath: str
Absolute path to a folder where to write the plots
Returns
-------
plot
Generated plot
.. _pandas.DataFrame: http://pandas.pydata.org/pandas-docs/stable/dsintro.html#dataframe | [
"Plots",
"the",
"mean",
"variance",
"prediction",
"for",
"each",
"readout"
] | train | https://github.com/bioasp/caspo/blob/a68d1eace75b9b08f23633d1fb5ce6134403959e/caspo/visualize.py#L346-L383 |
bioasp/caspo | caspo/visualize.py | intervention_strategies | def intervention_strategies(df, filepath=None):
"""
Plots all intervention strategies
Parameters
----------
df: `pandas.DataFrame`_
DataFrame with columns starting with `TR:`
filepath: str
Absolute path to a folder where to write the plot
Returns
-------
plot
Generated plot
.. _pandas.DataFrame: http://pandas.pydata.org/pandas-docs/stable/dsintro.html#dataframe
"""
logger = logging.getLogger("caspo")
LIMIT = 50
if len(df) > LIMIT:
msg = "Too many intervention strategies to visualize. A sample of %s strategies will be considered." % LIMIT
logger.warning(msg)
df = df.sample(LIMIT)
values = np.unique(df.values.flatten())
if len(values) == 3:
rwg = matplotlib.colors.ListedColormap(['red', 'white', 'green'])
elif 1 in values:
rwg = matplotlib.colors.ListedColormap(['white', 'green'])
else:
rwg = matplotlib.colors.ListedColormap(['red', 'white'])
plt.figure(figsize=(max((len(df.columns)-1) * .5, 4), max(len(df)*0.6, 2.5)))
df.columns = [c[3:] for c in df.columns]
ax = sns.heatmap(df, linewidths=.5, cbar=False, cmap=rwg, linecolor='gray')
ax.set_xlabel("Species")
ax.set_ylabel("Intervention strategy")
for tick in ax.get_xticklabels():
tick.set_rotation(90)
plt.tight_layout()
if filepath:
plt.savefig(os.path.join(filepath, 'strategies.pdf'))
return ax | python | def intervention_strategies(df, filepath=None):
"""
Plots all intervention strategies
Parameters
----------
df: `pandas.DataFrame`_
DataFrame with columns starting with `TR:`
filepath: str
Absolute path to a folder where to write the plot
Returns
-------
plot
Generated plot
.. _pandas.DataFrame: http://pandas.pydata.org/pandas-docs/stable/dsintro.html#dataframe
"""
logger = logging.getLogger("caspo")
LIMIT = 50
if len(df) > LIMIT:
msg = "Too many intervention strategies to visualize. A sample of %s strategies will be considered." % LIMIT
logger.warning(msg)
df = df.sample(LIMIT)
values = np.unique(df.values.flatten())
if len(values) == 3:
rwg = matplotlib.colors.ListedColormap(['red', 'white', 'green'])
elif 1 in values:
rwg = matplotlib.colors.ListedColormap(['white', 'green'])
else:
rwg = matplotlib.colors.ListedColormap(['red', 'white'])
plt.figure(figsize=(max((len(df.columns)-1) * .5, 4), max(len(df)*0.6, 2.5)))
df.columns = [c[3:] for c in df.columns]
ax = sns.heatmap(df, linewidths=.5, cbar=False, cmap=rwg, linecolor='gray')
ax.set_xlabel("Species")
ax.set_ylabel("Intervention strategy")
for tick in ax.get_xticklabels():
tick.set_rotation(90)
plt.tight_layout()
if filepath:
plt.savefig(os.path.join(filepath, 'strategies.pdf'))
return ax | [
"def",
"intervention_strategies",
"(",
"df",
",",
"filepath",
"=",
"None",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"\"caspo\"",
")",
"LIMIT",
"=",
"50",
"if",
"len",
"(",
"df",
")",
">",
"LIMIT",
":",
"msg",
"=",
"\"Too many interventi... | Plots all intervention strategies
Parameters
----------
df: `pandas.DataFrame`_
DataFrame with columns starting with `TR:`
filepath: str
Absolute path to a folder where to write the plot
Returns
-------
plot
Generated plot
.. _pandas.DataFrame: http://pandas.pydata.org/pandas-docs/stable/dsintro.html#dataframe | [
"Plots",
"all",
"intervention",
"strategies"
] | train | https://github.com/bioasp/caspo/blob/a68d1eace75b9b08f23633d1fb5ce6134403959e/caspo/visualize.py#L386-L439 |
bioasp/caspo | caspo/visualize.py | interventions_frequency | def interventions_frequency(df, filepath=None):
"""
Plots the frequency of occurrence for each intervention
Parameters
----------
df: `pandas.DataFrame`_
DataFrame with columns `frequency` and `intervention`
filepath: str
Absolute path to a folder where to write the plot
Returns
-------
plot
Generated plot
.. _pandas.DataFrame: http://pandas.pydata.org/pandas-docs/stable/dsintro.html#dataframe
"""
df = df.sort_values('frequency')
df['conf'] = df.frequency.map(lambda f: 0 if f < 0.2 else 1 if f < 0.8 else 2)
g = sns.factorplot(x="intervention", y="frequency", data=df, aspect=3, hue='conf', legend=False)
for tick in g.ax.get_xticklabels():
tick.set_rotation(90)
_ = [t.set_color('r') if t.get_text().endswith('-1') else t.set_color('g') for t in g.ax.xaxis.get_ticklabels()]
g.ax.set_ylim([-.05, 1.05])
g.ax.set_xlabel("Intervention")
g.ax.set_ylabel("Frequency")
if filepath:
g.savefig(os.path.join(filepath, 'interventions-frequency.pdf'))
return g | python | def interventions_frequency(df, filepath=None):
"""
Plots the frequency of occurrence for each intervention
Parameters
----------
df: `pandas.DataFrame`_
DataFrame with columns `frequency` and `intervention`
filepath: str
Absolute path to a folder where to write the plot
Returns
-------
plot
Generated plot
.. _pandas.DataFrame: http://pandas.pydata.org/pandas-docs/stable/dsintro.html#dataframe
"""
df = df.sort_values('frequency')
df['conf'] = df.frequency.map(lambda f: 0 if f < 0.2 else 1 if f < 0.8 else 2)
g = sns.factorplot(x="intervention", y="frequency", data=df, aspect=3, hue='conf', legend=False)
for tick in g.ax.get_xticklabels():
tick.set_rotation(90)
_ = [t.set_color('r') if t.get_text().endswith('-1') else t.set_color('g') for t in g.ax.xaxis.get_ticklabels()]
g.ax.set_ylim([-.05, 1.05])
g.ax.set_xlabel("Intervention")
g.ax.set_ylabel("Frequency")
if filepath:
g.savefig(os.path.join(filepath, 'interventions-frequency.pdf'))
return g | [
"def",
"interventions_frequency",
"(",
"df",
",",
"filepath",
"=",
"None",
")",
":",
"df",
"=",
"df",
".",
"sort_values",
"(",
"'frequency'",
")",
"df",
"[",
"'conf'",
"]",
"=",
"df",
".",
"frequency",
".",
"map",
"(",
"lambda",
"f",
":",
"0",
"if",
... | Plots the frequency of occurrence for each intervention
Parameters
----------
df: `pandas.DataFrame`_
DataFrame with columns `frequency` and `intervention`
filepath: str
Absolute path to a folder where to write the plot
Returns
-------
plot
Generated plot
.. _pandas.DataFrame: http://pandas.pydata.org/pandas-docs/stable/dsintro.html#dataframe | [
"Plots",
"the",
"frequency",
"of",
"occurrence",
"for",
"each",
"intervention"
] | train | https://github.com/bioasp/caspo/blob/a68d1eace75b9b08f23633d1fb5ce6134403959e/caspo/visualize.py#L441-L480 |
karel-brinda/rnftools | rnftools/lavender/Report.py | Report.add_graph | def add_graph(
self,
y,
x_label=None,
y_label="",
title="",
x_run=None,
y_run=None,
svg_size_px=None,
key_position="bottom right",
):
"""
Add a new graph to the overlap report.
Args:
y (str): Value plotted on y-axis.
x_label (str): Label on x-axis.
y_label (str): Label on y-axis.
title (str): Title of the plot.
x_run ((float,float)): x-range.
y_run ((int,int)): y-rang.
svg_size_px ((int,int): Size of SVG image in pixels.
key_position (str): GnuPlot position of the legend.
"""
if x_run is None:
x_run = self.default_x_run
if y_run is None:
y_run = self.default_y_run
if svg_size_px is None:
svg_size_px = self.default_svg_size_px
for panel in self.panels:
x_run = self._load_x_run(x_run)
y_run = self._load_y_run(y_run)
svg_size_px = self._load_svg_size_px(svg_size_px)
panel.add_graph(
y=y,
x_run=x_run,
y_run=y_run,
svg_size_px=svg_size_px,
y_label=y_label,
x_label=x_label if x_label is not None else self.default_x_label,
title=title,
key_position=key_position,
) | python | def add_graph(
self,
y,
x_label=None,
y_label="",
title="",
x_run=None,
y_run=None,
svg_size_px=None,
key_position="bottom right",
):
"""
Add a new graph to the overlap report.
Args:
y (str): Value plotted on y-axis.
x_label (str): Label on x-axis.
y_label (str): Label on y-axis.
title (str): Title of the plot.
x_run ((float,float)): x-range.
y_run ((int,int)): y-rang.
svg_size_px ((int,int): Size of SVG image in pixels.
key_position (str): GnuPlot position of the legend.
"""
if x_run is None:
x_run = self.default_x_run
if y_run is None:
y_run = self.default_y_run
if svg_size_px is None:
svg_size_px = self.default_svg_size_px
for panel in self.panels:
x_run = self._load_x_run(x_run)
y_run = self._load_y_run(y_run)
svg_size_px = self._load_svg_size_px(svg_size_px)
panel.add_graph(
y=y,
x_run=x_run,
y_run=y_run,
svg_size_px=svg_size_px,
y_label=y_label,
x_label=x_label if x_label is not None else self.default_x_label,
title=title,
key_position=key_position,
) | [
"def",
"add_graph",
"(",
"self",
",",
"y",
",",
"x_label",
"=",
"None",
",",
"y_label",
"=",
"\"\"",
",",
"title",
"=",
"\"\"",
",",
"x_run",
"=",
"None",
",",
"y_run",
"=",
"None",
",",
"svg_size_px",
"=",
"None",
",",
"key_position",
"=",
"\"bottom... | Add a new graph to the overlap report.
Args:
y (str): Value plotted on y-axis.
x_label (str): Label on x-axis.
y_label (str): Label on y-axis.
title (str): Title of the plot.
x_run ((float,float)): x-range.
y_run ((int,int)): y-rang.
svg_size_px ((int,int): Size of SVG image in pixels.
key_position (str): GnuPlot position of the legend. | [
"Add",
"a",
"new",
"graph",
"to",
"the",
"overlap",
"report",
"."
] | train | https://github.com/karel-brinda/rnftools/blob/25510798606fbc803a622a1abfcecf06d00d47a9/rnftools/lavender/Report.py#L174-L219 |
karel-brinda/rnftools | rnftools/lavender/Report.py | Report.clean | def clean(self):
"""Remove all temporary files."""
rnftools.utils.shell('rm -fR "{}" "{}"'.format(self.report_dir, self._html_fn)) | python | def clean(self):
"""Remove all temporary files."""
rnftools.utils.shell('rm -fR "{}" "{}"'.format(self.report_dir, self._html_fn)) | [
"def",
"clean",
"(",
"self",
")",
":",
"rnftools",
".",
"utils",
".",
"shell",
"(",
"'rm -fR \"{}\" \"{}\"'",
".",
"format",
"(",
"self",
".",
"report_dir",
",",
"self",
".",
"_html_fn",
")",
")"
] | Remove all temporary files. | [
"Remove",
"all",
"temporary",
"files",
"."
] | train | https://github.com/karel-brinda/rnftools/blob/25510798606fbc803a622a1abfcecf06d00d47a9/rnftools/lavender/Report.py#L226-L229 |
karel-brinda/rnftools | rnftools/lavender/Report.py | Report.create_html | def create_html(self):
"""Create HTML report."""
html_table = ""
columns = [panel.get_html_column() for panel in self.panels]
trs = len(columns[0])
html_table += os.linesep.join(
[
"<tr>{}</tr>".format("".join(["<td>{}</td>".format(columns[col][row]) for col in range(len(columns))]))
for row in range(trs)
]
)
with open(self._html_fn, "w+") as f:
css_src = textwrap.dedent(
"""\
.main_table {border-collapse:collapse;margin-top:15px;}
td {border: solid #aaaaff 1px;padding:4px;vertical-alignment:top;}
colgroup, thead {border: solid black 2px;padding 2px;}
.configuration {font-size:85%;}
.configuration, .configuration * {margin:0;padding:0;}
.formats {text-align:center;margin:20px 0px;}
img {min-width:640px}
"""
)
html_src = """<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>{title}</title>
<style type="text/css">
{css}
</style>
</head>
<body>
<h1>{title}</h1>
<strong>{description}</strong>
<table class="main_table">
{html_table}
</table>
</body>
""".format(
html_table=html_table,
css=css_src,
title=self.title,
description=self.description,
)
tidy_html_src = bs4.BeautifulSoup(html_src).prettify()
f.write(tidy_html_src) | python | def create_html(self):
"""Create HTML report."""
html_table = ""
columns = [panel.get_html_column() for panel in self.panels]
trs = len(columns[0])
html_table += os.linesep.join(
[
"<tr>{}</tr>".format("".join(["<td>{}</td>".format(columns[col][row]) for col in range(len(columns))]))
for row in range(trs)
]
)
with open(self._html_fn, "w+") as f:
css_src = textwrap.dedent(
"""\
.main_table {border-collapse:collapse;margin-top:15px;}
td {border: solid #aaaaff 1px;padding:4px;vertical-alignment:top;}
colgroup, thead {border: solid black 2px;padding 2px;}
.configuration {font-size:85%;}
.configuration, .configuration * {margin:0;padding:0;}
.formats {text-align:center;margin:20px 0px;}
img {min-width:640px}
"""
)
html_src = """<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>{title}</title>
<style type="text/css">
{css}
</style>
</head>
<body>
<h1>{title}</h1>
<strong>{description}</strong>
<table class="main_table">
{html_table}
</table>
</body>
""".format(
html_table=html_table,
css=css_src,
title=self.title,
description=self.description,
)
tidy_html_src = bs4.BeautifulSoup(html_src).prettify()
f.write(tidy_html_src) | [
"def",
"create_html",
"(",
"self",
")",
":",
"html_table",
"=",
"\"\"",
"columns",
"=",
"[",
"panel",
".",
"get_html_column",
"(",
")",
"for",
"panel",
"in",
"self",
".",
"panels",
"]",
"trs",
"=",
"len",
"(",
"columns",
"[",
"0",
"]",
")",
"html_tab... | Create HTML report. | [
"Create",
"HTML",
"report",
"."
] | train | https://github.com/karel-brinda/rnftools/blob/25510798606fbc803a622a1abfcecf06d00d47a9/rnftools/lavender/Report.py#L247-L299 |
TurboGears/backlash | backlash/tbtools.py | get_current_traceback | def get_current_traceback(show_hidden_frames=False, skip=0, context=None, exc_info=None):
"""Get the current exception info as `Traceback` object. Per default
calling this method will reraise system exceptions such as generator exit,
system exit or others. This behavior can be disabled by passing `False`
to the function as first parameter.
"""
if exc_info is None:
exc_info = sys.exc_info()
exc_type, exc_value, tb = exc_info
for x in range(skip):
if tb.tb_next is None:
break
tb = tb.tb_next
tb = Traceback(exc_type, exc_value, tb, context=context)
if not show_hidden_frames:
tb.filter_hidden_frames()
return tb | python | def get_current_traceback(show_hidden_frames=False, skip=0, context=None, exc_info=None):
"""Get the current exception info as `Traceback` object. Per default
calling this method will reraise system exceptions such as generator exit,
system exit or others. This behavior can be disabled by passing `False`
to the function as first parameter.
"""
if exc_info is None:
exc_info = sys.exc_info()
exc_type, exc_value, tb = exc_info
for x in range(skip):
if tb.tb_next is None:
break
tb = tb.tb_next
tb = Traceback(exc_type, exc_value, tb, context=context)
if not show_hidden_frames:
tb.filter_hidden_frames()
return tb | [
"def",
"get_current_traceback",
"(",
"show_hidden_frames",
"=",
"False",
",",
"skip",
"=",
"0",
",",
"context",
"=",
"None",
",",
"exc_info",
"=",
"None",
")",
":",
"if",
"exc_info",
"is",
"None",
":",
"exc_info",
"=",
"sys",
".",
"exc_info",
"(",
")",
... | Get the current exception info as `Traceback` object. Per default
calling this method will reraise system exceptions such as generator exit,
system exit or others. This behavior can be disabled by passing `False`
to the function as first parameter. | [
"Get",
"the",
"current",
"exception",
"info",
"as",
"Traceback",
"object",
".",
"Per",
"default",
"calling",
"this",
"method",
"will",
"reraise",
"system",
"exceptions",
"such",
"as",
"generator",
"exit",
"system",
"exit",
"or",
"others",
".",
"This",
"behavio... | train | https://github.com/TurboGears/backlash/blob/b8c73a6c8a203843f5a52c43b858ae5907fb2a4f/backlash/tbtools.py#L145-L162 |
TurboGears/backlash | backlash/tbtools.py | Traceback.log | def log(self, logfile=None):
"""Log the ASCII traceback into a file object."""
if logfile is None:
logfile = sys.stderr
tb = self.plaintext.rstrip() + '\n'
file_mode = getattr(logfile, 'mode', None)
if file_mode is not None:
if 'b' in file_mode:
tb = tb.encode('utf-8')
logfile.write(tb) | python | def log(self, logfile=None):
"""Log the ASCII traceback into a file object."""
if logfile is None:
logfile = sys.stderr
tb = self.plaintext.rstrip() + '\n'
file_mode = getattr(logfile, 'mode', None)
if file_mode is not None:
if 'b' in file_mode:
tb = tb.encode('utf-8')
logfile.write(tb) | [
"def",
"log",
"(",
"self",
",",
"logfile",
"=",
"None",
")",
":",
"if",
"logfile",
"is",
"None",
":",
"logfile",
"=",
"sys",
".",
"stderr",
"tb",
"=",
"self",
".",
"plaintext",
".",
"rstrip",
"(",
")",
"+",
"'\\n'",
"file_mode",
"=",
"getattr",
"("... | Log the ASCII traceback into a file object. | [
"Log",
"the",
"ASCII",
"traceback",
"into",
"a",
"file",
"object",
"."
] | train | https://github.com/TurboGears/backlash/blob/b8c73a6c8a203843f5a52c43b858ae5907fb2a4f/backlash/tbtools.py#L262-L272 |
TurboGears/backlash | backlash/tbtools.py | Traceback.paste | def paste(self):
"""Create a paste and return the paste id."""
data = json.dumps({
'description': 'Backlash Internal Server Error',
'public': False,
'files': {
'traceback.txt': {
'content': self.plaintext
}
}
}).encode('utf-8')
rv = urlopen('https://api.github.com/gists', data=data)
resp = json.loads(rv.read().decode('utf-8'))
rv.close()
return {
'url': resp['html_url'],
'id': resp['id']
} | python | def paste(self):
"""Create a paste and return the paste id."""
data = json.dumps({
'description': 'Backlash Internal Server Error',
'public': False,
'files': {
'traceback.txt': {
'content': self.plaintext
}
}
}).encode('utf-8')
rv = urlopen('https://api.github.com/gists', data=data)
resp = json.loads(rv.read().decode('utf-8'))
rv.close()
return {
'url': resp['html_url'],
'id': resp['id']
} | [
"def",
"paste",
"(",
"self",
")",
":",
"data",
"=",
"json",
".",
"dumps",
"(",
"{",
"'description'",
":",
"'Backlash Internal Server Error'",
",",
"'public'",
":",
"False",
",",
"'files'",
":",
"{",
"'traceback.txt'",
":",
"{",
"'content'",
":",
"self",
".... | Create a paste and return the paste id. | [
"Create",
"a",
"paste",
"and",
"return",
"the",
"paste",
"id",
"."
] | train | https://github.com/TurboGears/backlash/blob/b8c73a6c8a203843f5a52c43b858ae5907fb2a4f/backlash/tbtools.py#L274-L292 |
TurboGears/backlash | backlash/tbtools.py | Traceback.render_summary | def render_summary(self, include_title=True):
"""Render the traceback for the interactive console."""
title = ''
description = ''
frames = []
classes = ['traceback']
if not self.frames:
classes.append('noframe-traceback')
if include_title:
if self.is_syntax_error:
title = text_('Syntax Error')
else:
title = text_('Traceback <em>(most recent call last)</em>:')
for frame in self.frames:
frames.append(text_('<li%s>%s') % (
frame.info and text_(' title="%s"') % escape(frame.info) or text_(''),
frame.render()
))
if self.is_syntax_error:
description_wrapper = text_('<pre class=syntaxerror>%s</pre>')
else:
description_wrapper = text_('<blockquote>%s</blockquote>')
return SUMMARY_HTML % {
'classes': text_(' '.join(classes)),
'title': title and text_('<h3>%s</h3>' % title) or text_(''),
'frames': text_('\n'.join(frames)),
'description': description_wrapper % escape(self.exception)
} | python | def render_summary(self, include_title=True):
"""Render the traceback for the interactive console."""
title = ''
description = ''
frames = []
classes = ['traceback']
if not self.frames:
classes.append('noframe-traceback')
if include_title:
if self.is_syntax_error:
title = text_('Syntax Error')
else:
title = text_('Traceback <em>(most recent call last)</em>:')
for frame in self.frames:
frames.append(text_('<li%s>%s') % (
frame.info and text_(' title="%s"') % escape(frame.info) or text_(''),
frame.render()
))
if self.is_syntax_error:
description_wrapper = text_('<pre class=syntaxerror>%s</pre>')
else:
description_wrapper = text_('<blockquote>%s</blockquote>')
return SUMMARY_HTML % {
'classes': text_(' '.join(classes)),
'title': title and text_('<h3>%s</h3>' % title) or text_(''),
'frames': text_('\n'.join(frames)),
'description': description_wrapper % escape(self.exception)
} | [
"def",
"render_summary",
"(",
"self",
",",
"include_title",
"=",
"True",
")",
":",
"title",
"=",
"''",
"description",
"=",
"''",
"frames",
"=",
"[",
"]",
"classes",
"=",
"[",
"'traceback'",
"]",
"if",
"not",
"self",
".",
"frames",
":",
"classes",
".",
... | Render the traceback for the interactive console. | [
"Render",
"the",
"traceback",
"for",
"the",
"interactive",
"console",
"."
] | train | https://github.com/TurboGears/backlash/blob/b8c73a6c8a203843f5a52c43b858ae5907fb2a4f/backlash/tbtools.py#L294-L325 |
TurboGears/backlash | backlash/tbtools.py | Traceback.generate_plaintext_traceback | def generate_plaintext_traceback(self):
"""Like the plaintext attribute but returns a generator"""
yield text_('Traceback (most recent call last):')
for frame in self.frames:
yield text_(' File "%s", line %s, in %s' % (
frame.filename,
frame.lineno,
frame.function_name
))
yield text_(' ' + frame.current_line.strip())
yield text_(self.exception) | python | def generate_plaintext_traceback(self):
"""Like the plaintext attribute but returns a generator"""
yield text_('Traceback (most recent call last):')
for frame in self.frames:
yield text_(' File "%s", line %s, in %s' % (
frame.filename,
frame.lineno,
frame.function_name
))
yield text_(' ' + frame.current_line.strip())
yield text_(self.exception) | [
"def",
"generate_plaintext_traceback",
"(",
"self",
")",
":",
"yield",
"text_",
"(",
"'Traceback (most recent call last):'",
")",
"for",
"frame",
"in",
"self",
".",
"frames",
":",
"yield",
"text_",
"(",
"' File \"%s\", line %s, in %s'",
"%",
"(",
"frame",
".",
"f... | Like the plaintext attribute but returns a generator | [
"Like",
"the",
"plaintext",
"attribute",
"but",
"returns",
"a",
"generator"
] | train | https://github.com/TurboGears/backlash/blob/b8c73a6c8a203843f5a52c43b858ae5907fb2a4f/backlash/tbtools.py#L343-L353 |
TurboGears/backlash | backlash/tbtools.py | Frame.render_source | def render_source(self):
"""Render the sourcecode."""
return SOURCE_TABLE_HTML % text_('\n'.join(line.render() for line in
self.get_annotated_lines())) | python | def render_source(self):
"""Render the sourcecode."""
return SOURCE_TABLE_HTML % text_('\n'.join(line.render() for line in
self.get_annotated_lines())) | [
"def",
"render_source",
"(",
"self",
")",
":",
"return",
"SOURCE_TABLE_HTML",
"%",
"text_",
"(",
"'\\n'",
".",
"join",
"(",
"line",
".",
"render",
"(",
")",
"for",
"line",
"in",
"self",
".",
"get_annotated_lines",
"(",
")",
")",
")"
] | Render the sourcecode. | [
"Render",
"the",
"sourcecode",
"."
] | train | https://github.com/TurboGears/backlash/blob/b8c73a6c8a203843f5a52c43b858ae5907fb2a4f/backlash/tbtools.py#L451-L454 |
karel-brinda/rnftools | rnftools/mishmash/DwgSim.py | DwgSim.recode_dwgsim_reads | def recode_dwgsim_reads(
dwgsim_prefix,
fastq_rnf_fo,
fai_fo,
genome_id,
estimate_unknown_values,
number_of_read_tuples=10**9,
):
"""Convert DwgSim FASTQ file to RNF FASTQ file.
Args:
dwgsim_prefix (str): DwgSim prefix of the simulation (see its commandline parameters).
fastq_rnf_fo (file): File object of RNF FASTQ.
fai_fo (file): File object for FAI file of the reference genome.
genome_id (int): RNF genome ID to be used.
estimate_unknown_values (bool): Estimate unknown values (right coordinate of each end).
number_of_read_tuples (int): Estimate of number of simulated read tuples (to set width).
"""
dwgsim_pattern = re.compile(
'@(.*)_([0-9]+)_([0-9]+)_([01])_([01])_([01])_([01])_([0-9]+):([0-9]+):([0-9]+)_([0-9]+):([0-9]+):([0-9]+)_(([0-9abcdef])+)'
)
###
# DWGSIM read name format
#
# 1) contig name (chromsome name)
# 2) start end 1 (one-based)
# 3) start end 2 (one-based)
# 4) strand end 1 (0 - forward, 1 - reverse)
# 5) strand end 2 (0 - forward, 1 - reverse)
# 6) random read end 1 (0 - from the mutated reference, 1 - random)
# 7) random read end 2 (0 - from the mutated reference, 1 - random)
# 8) number of sequencing errors end 1 (color errors for colorspace)
# 9) number of SNPs end 1
# 10) number of indels end 1
# 11) number of sequencing errors end 2 (color errors for colorspace)
# 12) number of SNPs end 2
# 13) number of indels end 2
# 14) read number (unique within a given contig/chromosome)
###
fai_index = rnftools.utils.FaIdx(fai_fo=fai_fo)
read_tuple_id_width = len(format(number_of_read_tuples, 'x'))
# parsing FQ file
read_tuple_id = 0
last_read_tuple_name = None
old_fq = "{}.bfast.fastq".format(dwgsim_prefix)
fq_creator = rnftools.rnfformat.FqCreator(
fastq_fo=fastq_rnf_fo,
read_tuple_id_width=read_tuple_id_width,
genome_id_width=2,
chr_id_width=fai_index.chr_id_width,
coor_width=fai_index.coor_width,
info_reads_in_tuple=True,
info_simulator="dwgsim",
)
i = 0
with open(old_fq, "r+") as f1:
for line in f1:
if i % 4 == 0:
read_tuple_name = line[1:].strip()
if read_tuple_name != last_read_tuple_name:
new_tuple = True
if last_read_tuple_name is not None:
read_tuple_id += 1
else:
new_tuple = False
last_read_tuple_name = read_tuple_name
m = dwgsim_pattern.search(line)
if m is None:
rnftools.utils.error(
"Read tuple '{}' was not created by DwgSim.".format(line[1:]),
program="RNFtools",
subprogram="MIShmash",
exception=ValueError,
)
contig_name = m.group(1)
start_1 = int(m.group(2))
start_2 = int(m.group(3))
direction_1 = "F" if int(m.group(4)) == 0 else "R"
direction_2 = "F" if int(m.group(5)) == 0 else "R"
# random_1 = bool(m.group(6))
# random_2 = bool(m.group(7))
# seq_err_1 = int(m.group(8))
# snp_1 = int(m.group(9))
# indels_1 = int(m.group(10))
# seq_err_2 = int(m.group(11))
# snp_2 = int(m.group(12))
# indels_2 = int(m.group(13))
# read_tuple_id_dwg = int(m.group(14), 16)
chr_id = fai_index.dict_chr_ids[contig_name] if fai_index.dict_chr_ids != {} else "0"
elif i % 4 == 1:
bases = line.strip()
if new_tuple:
segment = rnftools.rnfformat.Segment(
genome_id=genome_id,
chr_id=chr_id,
direction=direction_1,
left=start_1,
right=start_1 + len(bases) - 1 if estimate_unknown_values else 0,
)
else:
segment = rnftools.rnfformat.Segment(
genome_id=genome_id,
chr_id=chr_id,
direction=direction_2,
left=start_2,
right=start_2 + len(bases) - 1 if estimate_unknown_values else 0,
)
elif i % 4 == 2:
pass
elif i % 4 == 3:
qualities = line.strip()
fq_creator.add_read(
read_tuple_id=read_tuple_id,
bases=bases,
qualities=qualities,
segments=[segment],
)
i += 1
fq_creator.flush_read_tuple() | python | def recode_dwgsim_reads(
dwgsim_prefix,
fastq_rnf_fo,
fai_fo,
genome_id,
estimate_unknown_values,
number_of_read_tuples=10**9,
):
"""Convert DwgSim FASTQ file to RNF FASTQ file.
Args:
dwgsim_prefix (str): DwgSim prefix of the simulation (see its commandline parameters).
fastq_rnf_fo (file): File object of RNF FASTQ.
fai_fo (file): File object for FAI file of the reference genome.
genome_id (int): RNF genome ID to be used.
estimate_unknown_values (bool): Estimate unknown values (right coordinate of each end).
number_of_read_tuples (int): Estimate of number of simulated read tuples (to set width).
"""
dwgsim_pattern = re.compile(
'@(.*)_([0-9]+)_([0-9]+)_([01])_([01])_([01])_([01])_([0-9]+):([0-9]+):([0-9]+)_([0-9]+):([0-9]+):([0-9]+)_(([0-9abcdef])+)'
)
###
# DWGSIM read name format
#
# 1) contig name (chromsome name)
# 2) start end 1 (one-based)
# 3) start end 2 (one-based)
# 4) strand end 1 (0 - forward, 1 - reverse)
# 5) strand end 2 (0 - forward, 1 - reverse)
# 6) random read end 1 (0 - from the mutated reference, 1 - random)
# 7) random read end 2 (0 - from the mutated reference, 1 - random)
# 8) number of sequencing errors end 1 (color errors for colorspace)
# 9) number of SNPs end 1
# 10) number of indels end 1
# 11) number of sequencing errors end 2 (color errors for colorspace)
# 12) number of SNPs end 2
# 13) number of indels end 2
# 14) read number (unique within a given contig/chromosome)
###
fai_index = rnftools.utils.FaIdx(fai_fo=fai_fo)
read_tuple_id_width = len(format(number_of_read_tuples, 'x'))
# parsing FQ file
read_tuple_id = 0
last_read_tuple_name = None
old_fq = "{}.bfast.fastq".format(dwgsim_prefix)
fq_creator = rnftools.rnfformat.FqCreator(
fastq_fo=fastq_rnf_fo,
read_tuple_id_width=read_tuple_id_width,
genome_id_width=2,
chr_id_width=fai_index.chr_id_width,
coor_width=fai_index.coor_width,
info_reads_in_tuple=True,
info_simulator="dwgsim",
)
i = 0
with open(old_fq, "r+") as f1:
for line in f1:
if i % 4 == 0:
read_tuple_name = line[1:].strip()
if read_tuple_name != last_read_tuple_name:
new_tuple = True
if last_read_tuple_name is not None:
read_tuple_id += 1
else:
new_tuple = False
last_read_tuple_name = read_tuple_name
m = dwgsim_pattern.search(line)
if m is None:
rnftools.utils.error(
"Read tuple '{}' was not created by DwgSim.".format(line[1:]),
program="RNFtools",
subprogram="MIShmash",
exception=ValueError,
)
contig_name = m.group(1)
start_1 = int(m.group(2))
start_2 = int(m.group(3))
direction_1 = "F" if int(m.group(4)) == 0 else "R"
direction_2 = "F" if int(m.group(5)) == 0 else "R"
# random_1 = bool(m.group(6))
# random_2 = bool(m.group(7))
# seq_err_1 = int(m.group(8))
# snp_1 = int(m.group(9))
# indels_1 = int(m.group(10))
# seq_err_2 = int(m.group(11))
# snp_2 = int(m.group(12))
# indels_2 = int(m.group(13))
# read_tuple_id_dwg = int(m.group(14), 16)
chr_id = fai_index.dict_chr_ids[contig_name] if fai_index.dict_chr_ids != {} else "0"
elif i % 4 == 1:
bases = line.strip()
if new_tuple:
segment = rnftools.rnfformat.Segment(
genome_id=genome_id,
chr_id=chr_id,
direction=direction_1,
left=start_1,
right=start_1 + len(bases) - 1 if estimate_unknown_values else 0,
)
else:
segment = rnftools.rnfformat.Segment(
genome_id=genome_id,
chr_id=chr_id,
direction=direction_2,
left=start_2,
right=start_2 + len(bases) - 1 if estimate_unknown_values else 0,
)
elif i % 4 == 2:
pass
elif i % 4 == 3:
qualities = line.strip()
fq_creator.add_read(
read_tuple_id=read_tuple_id,
bases=bases,
qualities=qualities,
segments=[segment],
)
i += 1
fq_creator.flush_read_tuple() | [
"def",
"recode_dwgsim_reads",
"(",
"dwgsim_prefix",
",",
"fastq_rnf_fo",
",",
"fai_fo",
",",
"genome_id",
",",
"estimate_unknown_values",
",",
"number_of_read_tuples",
"=",
"10",
"**",
"9",
",",
")",
":",
"dwgsim_pattern",
"=",
"re",
".",
"compile",
"(",
"'@(.*)... | Convert DwgSim FASTQ file to RNF FASTQ file.
Args:
dwgsim_prefix (str): DwgSim prefix of the simulation (see its commandline parameters).
fastq_rnf_fo (file): File object of RNF FASTQ.
fai_fo (file): File object for FAI file of the reference genome.
genome_id (int): RNF genome ID to be used.
estimate_unknown_values (bool): Estimate unknown values (right coordinate of each end).
number_of_read_tuples (int): Estimate of number of simulated read tuples (to set width). | [
"Convert",
"DwgSim",
"FASTQ",
"file",
"to",
"RNF",
"FASTQ",
"file",
"."
] | train | https://github.com/karel-brinda/rnftools/blob/25510798606fbc803a622a1abfcecf06d00d47a9/rnftools/mishmash/DwgSim.py#L218-L354 |
saghul/evergreen | evergreen/tasks.py | sleep | def sleep(seconds=0):
"""Yield control to another eligible coroutine until at least *seconds* have
elapsed.
*seconds* may be specified as an integer, or a float if fractional seconds
are desired.
"""
loop = evergreen.current.loop
current = Fiber.current()
assert loop.task is not current
timer = loop.call_later(seconds, current.switch)
try:
loop.switch()
finally:
timer.cancel() | python | def sleep(seconds=0):
"""Yield control to another eligible coroutine until at least *seconds* have
elapsed.
*seconds* may be specified as an integer, or a float if fractional seconds
are desired.
"""
loop = evergreen.current.loop
current = Fiber.current()
assert loop.task is not current
timer = loop.call_later(seconds, current.switch)
try:
loop.switch()
finally:
timer.cancel() | [
"def",
"sleep",
"(",
"seconds",
"=",
"0",
")",
":",
"loop",
"=",
"evergreen",
".",
"current",
".",
"loop",
"current",
"=",
"Fiber",
".",
"current",
"(",
")",
"assert",
"loop",
".",
"task",
"is",
"not",
"current",
"timer",
"=",
"loop",
".",
"call_late... | Yield control to another eligible coroutine until at least *seconds* have
elapsed.
*seconds* may be specified as an integer, or a float if fractional seconds
are desired. | [
"Yield",
"control",
"to",
"another",
"eligible",
"coroutine",
"until",
"at",
"least",
"*",
"seconds",
"*",
"have",
"elapsed",
"."
] | train | https://github.com/saghul/evergreen/blob/22f22f45892f397c23c3e09e6ea1ad4c00b3add8/evergreen/tasks.py#L16-L30 |
saghul/evergreen | evergreen/tasks.py | spawn | def spawn(func, *args, **kwargs):
"""Create a task to run ``func(*args, **kwargs)``. Returns a
:class:`Task` objec.
Execution control returns immediately to the caller; the created task
is merely scheduled to be run at the next available opportunity.
Use :func:`spawn_later` to arrange for tasks to be spawned
after a finite delay.
"""
t = Task(target=func, args=args, kwargs=kwargs)
t.start()
return t | python | def spawn(func, *args, **kwargs):
"""Create a task to run ``func(*args, **kwargs)``. Returns a
:class:`Task` objec.
Execution control returns immediately to the caller; the created task
is merely scheduled to be run at the next available opportunity.
Use :func:`spawn_later` to arrange for tasks to be spawned
after a finite delay.
"""
t = Task(target=func, args=args, kwargs=kwargs)
t.start()
return t | [
"def",
"spawn",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"t",
"=",
"Task",
"(",
"target",
"=",
"func",
",",
"args",
"=",
"args",
",",
"kwargs",
"=",
"kwargs",
")",
"t",
".",
"start",
"(",
")",
"return",
"t"
] | Create a task to run ``func(*args, **kwargs)``. Returns a
:class:`Task` objec.
Execution control returns immediately to the caller; the created task
is merely scheduled to be run at the next available opportunity.
Use :func:`spawn_later` to arrange for tasks to be spawned
after a finite delay. | [
"Create",
"a",
"task",
"to",
"run",
"func",
"(",
"*",
"args",
"**",
"kwargs",
")",
".",
"Returns",
"a",
":",
"class",
":",
"Task",
"objec",
"."
] | train | https://github.com/saghul/evergreen/blob/22f22f45892f397c23c3e09e6ea1ad4c00b3add8/evergreen/tasks.py#L33-L44 |
saghul/evergreen | evergreen/tasks.py | task | def task(func):
"""Decorator to run the decorated function as a Task
"""
def task_wrapper(*args, **kwargs):
return spawn(func, *args, **kwargs)
return task_wrapper | python | def task(func):
"""Decorator to run the decorated function as a Task
"""
def task_wrapper(*args, **kwargs):
return spawn(func, *args, **kwargs)
return task_wrapper | [
"def",
"task",
"(",
"func",
")",
":",
"def",
"task_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"spawn",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"task_wrapper"
] | Decorator to run the decorated function as a Task | [
"Decorator",
"to",
"run",
"the",
"decorated",
"function",
"as",
"a",
"Task"
] | train | https://github.com/saghul/evergreen/blob/22f22f45892f397c23c3e09e6ea1ad4c00b3add8/evergreen/tasks.py#L47-L52 |
saghul/evergreen | evergreen/tasks.py | Task.join | def join(self, timeout=None):
"""Wait for this Task to end. If a timeout is given, after the time expires the function
will return anyway."""
if not self._started:
raise RuntimeError('cannot join task before it is started')
return self._exit_event.wait(timeout) | python | def join(self, timeout=None):
"""Wait for this Task to end. If a timeout is given, after the time expires the function
will return anyway."""
if not self._started:
raise RuntimeError('cannot join task before it is started')
return self._exit_event.wait(timeout) | [
"def",
"join",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"_started",
":",
"raise",
"RuntimeError",
"(",
"'cannot join task before it is started'",
")",
"return",
"self",
".",
"_exit_event",
".",
"wait",
"(",
"timeout",
")"... | Wait for this Task to end. If a timeout is given, after the time expires the function
will return anyway. | [
"Wait",
"for",
"this",
"Task",
"to",
"end",
".",
"If",
"a",
"timeout",
"is",
"given",
"after",
"the",
"time",
"expires",
"the",
"function",
"will",
"return",
"anyway",
"."
] | train | https://github.com/saghul/evergreen/blob/22f22f45892f397c23c3e09e6ea1ad4c00b3add8/evergreen/tasks.py#L89-L94 |
saghul/evergreen | evergreen/tasks.py | Task.kill | def kill(self, typ=TaskExit, value=None, tb=None):
"""Terminates the current task by raising an exception into it.
Whatever that task might be doing; be it waiting for I/O or another
primitive, it sees an exception as soon as it yields control.
By default, this exception is TaskExit, but a specific exception
may be specified.
"""
if not self.is_alive():
return
if not value:
value = typ()
if not self._running:
# task hasn't started yet and therefore throw won't work
def just_raise():
six.reraise(typ, value, tb)
self.run = just_raise
return
evergreen.current.loop.call_soon(self.throw, typ, value, tb) | python | def kill(self, typ=TaskExit, value=None, tb=None):
"""Terminates the current task by raising an exception into it.
Whatever that task might be doing; be it waiting for I/O or another
primitive, it sees an exception as soon as it yields control.
By default, this exception is TaskExit, but a specific exception
may be specified.
"""
if not self.is_alive():
return
if not value:
value = typ()
if not self._running:
# task hasn't started yet and therefore throw won't work
def just_raise():
six.reraise(typ, value, tb)
self.run = just_raise
return
evergreen.current.loop.call_soon(self.throw, typ, value, tb) | [
"def",
"kill",
"(",
"self",
",",
"typ",
"=",
"TaskExit",
",",
"value",
"=",
"None",
",",
"tb",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"is_alive",
"(",
")",
":",
"return",
"if",
"not",
"value",
":",
"value",
"=",
"typ",
"(",
")",
"if",... | Terminates the current task by raising an exception into it.
Whatever that task might be doing; be it waiting for I/O or another
primitive, it sees an exception as soon as it yields control.
By default, this exception is TaskExit, but a specific exception
may be specified. | [
"Terminates",
"the",
"current",
"task",
"by",
"raising",
"an",
"exception",
"into",
"it",
".",
"Whatever",
"that",
"task",
"might",
"be",
"doing",
";",
"be",
"it",
"waiting",
"for",
"I",
"/",
"O",
"or",
"another",
"primitive",
"it",
"sees",
"an",
"except... | train | https://github.com/saghul/evergreen/blob/22f22f45892f397c23c3e09e6ea1ad4c00b3add8/evergreen/tasks.py#L96-L114 |
bioasp/caspo | caspo/core/logicalnetwork.py | LogicalNetworkList.from_csv | def from_csv(cls, filename):
"""
Creates a list of logical networks from a CSV file.
Columns that cannot be parsed as a :class:`caspo.core.mapping.Mapping` are ignored
except for a column named `networks` which (if present) is interpreted as the number
of logical networks having the same input-output behavior.
Parameters
----------
filename : str
Absolute path to CSV file
Returns
-------
caspo.core.logicalnetwork.LogicalNetworkList
Created object instance
"""
df = pd.read_csv(filename)
edges = set()
mappings = []
cols = []
for m in df.columns:
try:
ct = Mapping.from_str(m)
mappings.append(ct)
cols.append(m)
for source, sign in ct.clause:
edges.add((source, ct.target, sign))
except ValueError:
#current column isn't a mapping
pass
graph = Graph.from_tuples(edges)
hypergraph = HyperGraph.from_graph(graph)
hypergraph.mappings = mappings
if 'networks' in df.columns:
nnet = df['networks'].values.astype(int)
else:
nnet = None
return cls(hypergraph, matrix=df[cols].values, networks=nnet) | python | def from_csv(cls, filename):
"""
Creates a list of logical networks from a CSV file.
Columns that cannot be parsed as a :class:`caspo.core.mapping.Mapping` are ignored
except for a column named `networks` which (if present) is interpreted as the number
of logical networks having the same input-output behavior.
Parameters
----------
filename : str
Absolute path to CSV file
Returns
-------
caspo.core.logicalnetwork.LogicalNetworkList
Created object instance
"""
df = pd.read_csv(filename)
edges = set()
mappings = []
cols = []
for m in df.columns:
try:
ct = Mapping.from_str(m)
mappings.append(ct)
cols.append(m)
for source, sign in ct.clause:
edges.add((source, ct.target, sign))
except ValueError:
#current column isn't a mapping
pass
graph = Graph.from_tuples(edges)
hypergraph = HyperGraph.from_graph(graph)
hypergraph.mappings = mappings
if 'networks' in df.columns:
nnet = df['networks'].values.astype(int)
else:
nnet = None
return cls(hypergraph, matrix=df[cols].values, networks=nnet) | [
"def",
"from_csv",
"(",
"cls",
",",
"filename",
")",
":",
"df",
"=",
"pd",
".",
"read_csv",
"(",
"filename",
")",
"edges",
"=",
"set",
"(",
")",
"mappings",
"=",
"[",
"]",
"cols",
"=",
"[",
"]",
"for",
"m",
"in",
"df",
".",
"columns",
":",
"try... | Creates a list of logical networks from a CSV file.
Columns that cannot be parsed as a :class:`caspo.core.mapping.Mapping` are ignored
except for a column named `networks` which (if present) is interpreted as the number
of logical networks having the same input-output behavior.
Parameters
----------
filename : str
Absolute path to CSV file
Returns
-------
caspo.core.logicalnetwork.LogicalNetworkList
Created object instance | [
"Creates",
"a",
"list",
"of",
"logical",
"networks",
"from",
"a",
"CSV",
"file",
".",
"Columns",
"that",
"cannot",
"be",
"parsed",
"as",
"a",
":",
"class",
":",
"caspo",
".",
"core",
".",
"mapping",
".",
"Mapping",
"are",
"ignored",
"except",
"for",
"a... | train | https://github.com/bioasp/caspo/blob/a68d1eace75b9b08f23633d1fb5ce6134403959e/caspo/core/logicalnetwork.py#L80-L122 |
bioasp/caspo | caspo/core/logicalnetwork.py | LogicalNetworkList.from_hypergraph | def from_hypergraph(cls, hypergraph, networks=None):
"""
Creates a list of logical networks from a given hypergraph and an
optional list of :class:`caspo.core.logicalnetwork.LogicalNetwork` object instances
Parameters
----------
hypegraph : :class:`caspo.core.hypergraph.HyperGraph`
Underlying hypergraph for this logical network list
networks : Optional[list]
List of :class:`caspo.core.logicalnetwork.LogicalNetwork` object instances
Returns
-------
caspo.core.logicalnetwork.LogicalNetworkList
Created object instance
"""
matrix = None
nnet = None
if networks:
matrix = np.array([networks[0].to_array(hypergraph.mappings)])
nnet = [networks[0].networks]
for network in networks[1:]:
matrix = np.append(matrix, [network.to_array(hypergraph.mappings)], axis=0)
nnet.append(network.networks)
return cls(hypergraph, matrix, nnet) | python | def from_hypergraph(cls, hypergraph, networks=None):
"""
Creates a list of logical networks from a given hypergraph and an
optional list of :class:`caspo.core.logicalnetwork.LogicalNetwork` object instances
Parameters
----------
hypegraph : :class:`caspo.core.hypergraph.HyperGraph`
Underlying hypergraph for this logical network list
networks : Optional[list]
List of :class:`caspo.core.logicalnetwork.LogicalNetwork` object instances
Returns
-------
caspo.core.logicalnetwork.LogicalNetworkList
Created object instance
"""
matrix = None
nnet = None
if networks:
matrix = np.array([networks[0].to_array(hypergraph.mappings)])
nnet = [networks[0].networks]
for network in networks[1:]:
matrix = np.append(matrix, [network.to_array(hypergraph.mappings)], axis=0)
nnet.append(network.networks)
return cls(hypergraph, matrix, nnet) | [
"def",
"from_hypergraph",
"(",
"cls",
",",
"hypergraph",
",",
"networks",
"=",
"None",
")",
":",
"matrix",
"=",
"None",
"nnet",
"=",
"None",
"if",
"networks",
":",
"matrix",
"=",
"np",
".",
"array",
"(",
"[",
"networks",
"[",
"0",
"]",
".",
"to_array... | Creates a list of logical networks from a given hypergraph and an
optional list of :class:`caspo.core.logicalnetwork.LogicalNetwork` object instances
Parameters
----------
hypegraph : :class:`caspo.core.hypergraph.HyperGraph`
Underlying hypergraph for this logical network list
networks : Optional[list]
List of :class:`caspo.core.logicalnetwork.LogicalNetwork` object instances
Returns
-------
caspo.core.logicalnetwork.LogicalNetworkList
Created object instance | [
"Creates",
"a",
"list",
"of",
"logical",
"networks",
"from",
"a",
"given",
"hypergraph",
"and",
"an",
"optional",
"list",
"of",
":",
"class",
":",
"caspo",
".",
"core",
".",
"logicalnetwork",
".",
"LogicalNetwork",
"object",
"instances"
] | train | https://github.com/bioasp/caspo/blob/a68d1eace75b9b08f23633d1fb5ce6134403959e/caspo/core/logicalnetwork.py#L125-L152 |
bioasp/caspo | caspo/core/logicalnetwork.py | LogicalNetworkList.mappings | def mappings(self):
"""
:class:`caspo.core.mapping.MappingList`: the list of mappings present in at least one logical network in this list
"""
return self.hg.mappings[np.unique(np.where(self.__matrix == 1)[1])] | python | def mappings(self):
"""
:class:`caspo.core.mapping.MappingList`: the list of mappings present in at least one logical network in this list
"""
return self.hg.mappings[np.unique(np.where(self.__matrix == 1)[1])] | [
"def",
"mappings",
"(",
"self",
")",
":",
"return",
"self",
".",
"hg",
".",
"mappings",
"[",
"np",
".",
"unique",
"(",
"np",
".",
"where",
"(",
"self",
".",
"__matrix",
"==",
"1",
")",
"[",
"1",
"]",
")",
"]"
] | :class:`caspo.core.mapping.MappingList`: the list of mappings present in at least one logical network in this list | [
":",
"class",
":",
"caspo",
".",
"core",
".",
"mapping",
".",
"MappingList",
":",
"the",
"list",
"of",
"mappings",
"present",
"in",
"at",
"least",
"one",
"logical",
"network",
"in",
"this",
"list"
] | train | https://github.com/bioasp/caspo/blob/a68d1eace75b9b08f23633d1fb5ce6134403959e/caspo/core/logicalnetwork.py#L161-L165 |
bioasp/caspo | caspo/core/logicalnetwork.py | LogicalNetworkList.reset | def reset(self):
"""
Drop all networks in the list
"""
self.__matrix = np.array([])
self.__networks = np.array([]) | python | def reset(self):
"""
Drop all networks in the list
"""
self.__matrix = np.array([])
self.__networks = np.array([]) | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"__matrix",
"=",
"np",
".",
"array",
"(",
"[",
"]",
")",
"self",
".",
"__networks",
"=",
"np",
".",
"array",
"(",
"[",
"]",
")"
] | Drop all networks in the list | [
"Drop",
"all",
"networks",
"in",
"the",
"list"
] | train | https://github.com/bioasp/caspo/blob/a68d1eace75b9b08f23633d1fb5ce6134403959e/caspo/core/logicalnetwork.py#L167-L172 |
bioasp/caspo | caspo/core/logicalnetwork.py | LogicalNetworkList.split | def split(self, indices):
"""
Splits logical networks according to given indices
Parameters
----------
indices : list
1-D array of sorted integers, the entries indicate where the array is split
Returns
-------
list
List of :class:`caspo.core.logicalnetwork.LogicalNetworkList` object instances
.. seealso:: `numpy.split <http://docs.scipy.org/doc/numpy/reference/generated/numpy.split.html#numpy-split>`_
"""
return [LogicalNetworkList(self.hg, part) for part in np.split(self.__matrix, indices)] | python | def split(self, indices):
"""
Splits logical networks according to given indices
Parameters
----------
indices : list
1-D array of sorted integers, the entries indicate where the array is split
Returns
-------
list
List of :class:`caspo.core.logicalnetwork.LogicalNetworkList` object instances
.. seealso:: `numpy.split <http://docs.scipy.org/doc/numpy/reference/generated/numpy.split.html#numpy-split>`_
"""
return [LogicalNetworkList(self.hg, part) for part in np.split(self.__matrix, indices)] | [
"def",
"split",
"(",
"self",
",",
"indices",
")",
":",
"return",
"[",
"LogicalNetworkList",
"(",
"self",
".",
"hg",
",",
"part",
")",
"for",
"part",
"in",
"np",
".",
"split",
"(",
"self",
".",
"__matrix",
",",
"indices",
")",
"]"
] | Splits logical networks according to given indices
Parameters
----------
indices : list
1-D array of sorted integers, the entries indicate where the array is split
Returns
-------
list
List of :class:`caspo.core.logicalnetwork.LogicalNetworkList` object instances
.. seealso:: `numpy.split <http://docs.scipy.org/doc/numpy/reference/generated/numpy.split.html#numpy-split>`_ | [
"Splits",
"logical",
"networks",
"according",
"to",
"given",
"indices"
] | train | https://github.com/bioasp/caspo/blob/a68d1eace75b9b08f23633d1fb5ce6134403959e/caspo/core/logicalnetwork.py#L174-L191 |
bioasp/caspo | caspo/core/logicalnetwork.py | LogicalNetworkList.concat | def concat(self, other):
"""
Returns the concatenation with another :class:`caspo.core.logicalnetwork.LogicalNetworkList` object instance.
It is assumed (not checked) that both have the same underlying hypergraph.
Parameters
----------
other : :class:`caspo.core.logicalnetwork.LogicalNetworkList`
The list to concatenate
Returns
-------
caspo.core.logicalnetwork.LogicalNetworkList
If other is empty returns self, if self is empty returns other, otherwise a new
:class:`caspo.core.LogicalNetworkList` is created by concatenating self and other.
"""
if len(other) == 0:
return self
elif len(self) == 0:
return other
else:
return LogicalNetworkList(self.hg, np.append(self.__matrix, other.__matrix, axis=0), np.concatenate([self.__networks, other.__networks])) | python | def concat(self, other):
"""
Returns the concatenation with another :class:`caspo.core.logicalnetwork.LogicalNetworkList` object instance.
It is assumed (not checked) that both have the same underlying hypergraph.
Parameters
----------
other : :class:`caspo.core.logicalnetwork.LogicalNetworkList`
The list to concatenate
Returns
-------
caspo.core.logicalnetwork.LogicalNetworkList
If other is empty returns self, if self is empty returns other, otherwise a new
:class:`caspo.core.LogicalNetworkList` is created by concatenating self and other.
"""
if len(other) == 0:
return self
elif len(self) == 0:
return other
else:
return LogicalNetworkList(self.hg, np.append(self.__matrix, other.__matrix, axis=0), np.concatenate([self.__networks, other.__networks])) | [
"def",
"concat",
"(",
"self",
",",
"other",
")",
":",
"if",
"len",
"(",
"other",
")",
"==",
"0",
":",
"return",
"self",
"elif",
"len",
"(",
"self",
")",
"==",
"0",
":",
"return",
"other",
"else",
":",
"return",
"LogicalNetworkList",
"(",
"self",
".... | Returns the concatenation with another :class:`caspo.core.logicalnetwork.LogicalNetworkList` object instance.
It is assumed (not checked) that both have the same underlying hypergraph.
Parameters
----------
other : :class:`caspo.core.logicalnetwork.LogicalNetworkList`
The list to concatenate
Returns
-------
caspo.core.logicalnetwork.LogicalNetworkList
If other is empty returns self, if self is empty returns other, otherwise a new
:class:`caspo.core.LogicalNetworkList` is created by concatenating self and other. | [
"Returns",
"the",
"concatenation",
"with",
"another",
":",
"class",
":",
"caspo",
".",
"core",
".",
"logicalnetwork",
".",
"LogicalNetworkList",
"object",
"instance",
".",
"It",
"is",
"assumed",
"(",
"not",
"checked",
")",
"that",
"both",
"have",
"the",
"sam... | train | https://github.com/bioasp/caspo/blob/a68d1eace75b9b08f23633d1fb5ce6134403959e/caspo/core/logicalnetwork.py#L193-L214 |
bioasp/caspo | caspo/core/logicalnetwork.py | LogicalNetworkList.append | def append(self, network):
"""
Append a :class:`caspo.core.logicalnetwork.LogicalNetwork` to the list
Parameters
----------
network : :class:`caspo.core.logicalnetwork.LogicalNetwork`
The network to append
"""
arr = network.to_array(self.hg.mappings)
if len(self.__matrix):
self.__matrix = np.append(self.__matrix, [arr], axis=0)
self.__networks = np.append(self.__networks, network.networks)
else:
self.__matrix = np.array([arr])
self.__networks = np.array([network.networks]) | python | def append(self, network):
"""
Append a :class:`caspo.core.logicalnetwork.LogicalNetwork` to the list
Parameters
----------
network : :class:`caspo.core.logicalnetwork.LogicalNetwork`
The network to append
"""
arr = network.to_array(self.hg.mappings)
if len(self.__matrix):
self.__matrix = np.append(self.__matrix, [arr], axis=0)
self.__networks = np.append(self.__networks, network.networks)
else:
self.__matrix = np.array([arr])
self.__networks = np.array([network.networks]) | [
"def",
"append",
"(",
"self",
",",
"network",
")",
":",
"arr",
"=",
"network",
".",
"to_array",
"(",
"self",
".",
"hg",
".",
"mappings",
")",
"if",
"len",
"(",
"self",
".",
"__matrix",
")",
":",
"self",
".",
"__matrix",
"=",
"np",
".",
"append",
... | Append a :class:`caspo.core.logicalnetwork.LogicalNetwork` to the list
Parameters
----------
network : :class:`caspo.core.logicalnetwork.LogicalNetwork`
The network to append | [
"Append",
"a",
":",
"class",
":",
"caspo",
".",
"core",
".",
"logicalnetwork",
".",
"LogicalNetwork",
"to",
"the",
"list"
] | train | https://github.com/bioasp/caspo/blob/a68d1eace75b9b08f23633d1fb5ce6134403959e/caspo/core/logicalnetwork.py#L216-L231 |
bioasp/caspo | caspo/core/logicalnetwork.py | LogicalNetworkList.to_funset | def to_funset(self):
"""
Converts the list of logical networks to a set of `gringo.Fun`_ instances
Returns
-------
set
Representation of all networks as a set of `gringo.Fun`_ instances
.. _gringo.Fun: http://potassco.sourceforge.net/gringo.html#Fun
"""
fs = set((gringo.Fun("variable", [var]) for var in self.hg.nodes))
formulas = set()
for network in self:
formulas = formulas.union(it.imap(lambda (_, f): f, network.formulas_iter()))
formulas = pd.Series(list(formulas))
for i, network in enumerate(self):
for v, f in network.formulas_iter():
fs.add(gringo.Fun("formula", [i, v, formulas[formulas == f].index[0]]))
for formula_idx, formula in formulas.iteritems():
for clause in formula:
clause_idx = self.hg.clauses_idx[clause]
fs.add(gringo.Fun("dnf", [formula_idx, clause_idx]))
for variable, sign in clause:
fs.add(gringo.Fun("clause", [clause_idx, variable, sign]))
return fs | python | def to_funset(self):
"""
Converts the list of logical networks to a set of `gringo.Fun`_ instances
Returns
-------
set
Representation of all networks as a set of `gringo.Fun`_ instances
.. _gringo.Fun: http://potassco.sourceforge.net/gringo.html#Fun
"""
fs = set((gringo.Fun("variable", [var]) for var in self.hg.nodes))
formulas = set()
for network in self:
formulas = formulas.union(it.imap(lambda (_, f): f, network.formulas_iter()))
formulas = pd.Series(list(formulas))
for i, network in enumerate(self):
for v, f in network.formulas_iter():
fs.add(gringo.Fun("formula", [i, v, formulas[formulas == f].index[0]]))
for formula_idx, formula in formulas.iteritems():
for clause in formula:
clause_idx = self.hg.clauses_idx[clause]
fs.add(gringo.Fun("dnf", [formula_idx, clause_idx]))
for variable, sign in clause:
fs.add(gringo.Fun("clause", [clause_idx, variable, sign]))
return fs | [
"def",
"to_funset",
"(",
"self",
")",
":",
"fs",
"=",
"set",
"(",
"(",
"gringo",
".",
"Fun",
"(",
"\"variable\"",
",",
"[",
"var",
"]",
")",
"for",
"var",
"in",
"self",
".",
"hg",
".",
"nodes",
")",
")",
"formulas",
"=",
"set",
"(",
")",
"for",... | Converts the list of logical networks to a set of `gringo.Fun`_ instances
Returns
-------
set
Representation of all networks as a set of `gringo.Fun`_ instances
.. _gringo.Fun: http://potassco.sourceforge.net/gringo.html#Fun | [
"Converts",
"the",
"list",
"of",
"logical",
"networks",
"to",
"a",
"set",
"of",
"gringo",
".",
"Fun",
"_",
"instances"
] | train | https://github.com/bioasp/caspo/blob/a68d1eace75b9b08f23633d1fb5ce6134403959e/caspo/core/logicalnetwork.py#L277-L308 |
bioasp/caspo | caspo/core/logicalnetwork.py | LogicalNetworkList.to_dataframe | def to_dataframe(self, networks=False, dataset=None, size=False, n_jobs=-1):
"""
Converts the list of logical networks to a `pandas.DataFrame`_ object instance
Parameters
----------
networks : boolean
If True, a column with number of networks having the same behavior is included in the DataFrame
dataset: Optional[:class:`caspo.core.dataset.Dataset`]
If not None, a column with the MSE with respect to the given dataset is included in the DataFrame
size: boolean
If True, a column with the size of each logical network is included in the DataFrame
n_jobs : int
Number of jobs to run in parallel. Default to -1 (all cores available)
Returns
-------
`pandas.DataFrame`_
DataFrame representation of the list of logical networks.
.. _pandas.DataFrame: http://pandas.pydata.org/pandas-docs/stable/dsintro.html#dataframe
"""
length = len(self)
df = pd.DataFrame(self.__matrix, columns=map(str, self.hg.mappings))
if networks:
df = pd.concat([df, pd.DataFrame({'networks': self.__networks})], axis=1)
if dataset is not None:
clampings = dataset.clampings
readouts = dataset.readouts.columns
observations = dataset.readouts.values
pos = ~np.isnan(observations)
mse = Parallel(n_jobs=n_jobs)(delayed(__parallel_mse__)(n, clampings, readouts, observations[pos], pos) for n in self)
df = pd.concat([df, pd.DataFrame({'mse': mse})], axis=1)
if size:
df = pd.concat([df, pd.DataFrame({'size': np.fromiter((n.size for n in self), int, length)})], axis=1)
return df | python | def to_dataframe(self, networks=False, dataset=None, size=False, n_jobs=-1):
"""
Converts the list of logical networks to a `pandas.DataFrame`_ object instance
Parameters
----------
networks : boolean
If True, a column with number of networks having the same behavior is included in the DataFrame
dataset: Optional[:class:`caspo.core.dataset.Dataset`]
If not None, a column with the MSE with respect to the given dataset is included in the DataFrame
size: boolean
If True, a column with the size of each logical network is included in the DataFrame
n_jobs : int
Number of jobs to run in parallel. Default to -1 (all cores available)
Returns
-------
`pandas.DataFrame`_
DataFrame representation of the list of logical networks.
.. _pandas.DataFrame: http://pandas.pydata.org/pandas-docs/stable/dsintro.html#dataframe
"""
length = len(self)
df = pd.DataFrame(self.__matrix, columns=map(str, self.hg.mappings))
if networks:
df = pd.concat([df, pd.DataFrame({'networks': self.__networks})], axis=1)
if dataset is not None:
clampings = dataset.clampings
readouts = dataset.readouts.columns
observations = dataset.readouts.values
pos = ~np.isnan(observations)
mse = Parallel(n_jobs=n_jobs)(delayed(__parallel_mse__)(n, clampings, readouts, observations[pos], pos) for n in self)
df = pd.concat([df, pd.DataFrame({'mse': mse})], axis=1)
if size:
df = pd.concat([df, pd.DataFrame({'size': np.fromiter((n.size for n in self), int, length)})], axis=1)
return df | [
"def",
"to_dataframe",
"(",
"self",
",",
"networks",
"=",
"False",
",",
"dataset",
"=",
"None",
",",
"size",
"=",
"False",
",",
"n_jobs",
"=",
"-",
"1",
")",
":",
"length",
"=",
"len",
"(",
"self",
")",
"df",
"=",
"pd",
".",
"DataFrame",
"(",
"se... | Converts the list of logical networks to a `pandas.DataFrame`_ object instance
Parameters
----------
networks : boolean
If True, a column with number of networks having the same behavior is included in the DataFrame
dataset: Optional[:class:`caspo.core.dataset.Dataset`]
If not None, a column with the MSE with respect to the given dataset is included in the DataFrame
size: boolean
If True, a column with the size of each logical network is included in the DataFrame
n_jobs : int
Number of jobs to run in parallel. Default to -1 (all cores available)
Returns
-------
`pandas.DataFrame`_
DataFrame representation of the list of logical networks.
.. _pandas.DataFrame: http://pandas.pydata.org/pandas-docs/stable/dsintro.html#dataframe | [
"Converts",
"the",
"list",
"of",
"logical",
"networks",
"to",
"a",
"pandas",
".",
"DataFrame",
"_",
"object",
"instance"
] | train | https://github.com/bioasp/caspo/blob/a68d1eace75b9b08f23633d1fb5ce6134403959e/caspo/core/logicalnetwork.py#L310-L354 |
bioasp/caspo | caspo/core/logicalnetwork.py | LogicalNetworkList.to_csv | def to_csv(self, filename, networks=False, dataset=None, size=False, n_jobs=-1):
"""
Writes the list of logical networks to a CSV file
Parameters
----------
filename : str
Absolute path where to write the CSV file
networks : boolean
If True, a column with number of networks having the same behavior is included in the file
dataset: Optional[:class:`caspo.core.dataset.Dataset`]
If not None, a column with the MSE with respect to the given dataset is included
size: boolean
If True, a column with the size of each logical network is included
n_jobs : int
Number of jobs to run in parallel. Default to -1 (all cores available)
"""
self.to_dataframe(networks, dataset, size, n_jobs).to_csv(filename, index=False) | python | def to_csv(self, filename, networks=False, dataset=None, size=False, n_jobs=-1):
"""
Writes the list of logical networks to a CSV file
Parameters
----------
filename : str
Absolute path where to write the CSV file
networks : boolean
If True, a column with number of networks having the same behavior is included in the file
dataset: Optional[:class:`caspo.core.dataset.Dataset`]
If not None, a column with the MSE with respect to the given dataset is included
size: boolean
If True, a column with the size of each logical network is included
n_jobs : int
Number of jobs to run in parallel. Default to -1 (all cores available)
"""
self.to_dataframe(networks, dataset, size, n_jobs).to_csv(filename, index=False) | [
"def",
"to_csv",
"(",
"self",
",",
"filename",
",",
"networks",
"=",
"False",
",",
"dataset",
"=",
"None",
",",
"size",
"=",
"False",
",",
"n_jobs",
"=",
"-",
"1",
")",
":",
"self",
".",
"to_dataframe",
"(",
"networks",
",",
"dataset",
",",
"size",
... | Writes the list of logical networks to a CSV file
Parameters
----------
filename : str
Absolute path where to write the CSV file
networks : boolean
If True, a column with number of networks having the same behavior is included in the file
dataset: Optional[:class:`caspo.core.dataset.Dataset`]
If not None, a column with the MSE with respect to the given dataset is included
size: boolean
If True, a column with the size of each logical network is included
n_jobs : int
Number of jobs to run in parallel. Default to -1 (all cores available) | [
"Writes",
"the",
"list",
"of",
"logical",
"networks",
"to",
"a",
"CSV",
"file"
] | train | https://github.com/bioasp/caspo/blob/a68d1eace75b9b08f23633d1fb5ce6134403959e/caspo/core/logicalnetwork.py#L356-L378 |
bioasp/caspo | caspo/core/logicalnetwork.py | LogicalNetworkList.frequencies_iter | def frequencies_iter(self):
"""
Iterates over all non-zero frequencies of logical conjunction mappings in this list
Yields
------
tuple[caspo.core.mapping.Mapping, float]
The next pair (mapping,frequency)
"""
f = self.__matrix.mean(axis=0)
for i, m in self.mappings.iteritems():
yield m, f[i] | python | def frequencies_iter(self):
"""
Iterates over all non-zero frequencies of logical conjunction mappings in this list
Yields
------
tuple[caspo.core.mapping.Mapping, float]
The next pair (mapping,frequency)
"""
f = self.__matrix.mean(axis=0)
for i, m in self.mappings.iteritems():
yield m, f[i] | [
"def",
"frequencies_iter",
"(",
"self",
")",
":",
"f",
"=",
"self",
".",
"__matrix",
".",
"mean",
"(",
"axis",
"=",
"0",
")",
"for",
"i",
",",
"m",
"in",
"self",
".",
"mappings",
".",
"iteritems",
"(",
")",
":",
"yield",
"m",
",",
"f",
"[",
"i"... | Iterates over all non-zero frequencies of logical conjunction mappings in this list
Yields
------
tuple[caspo.core.mapping.Mapping, float]
The next pair (mapping,frequency) | [
"Iterates",
"over",
"all",
"non",
"-",
"zero",
"frequencies",
"of",
"logical",
"conjunction",
"mappings",
"in",
"this",
"list"
] | train | https://github.com/bioasp/caspo/blob/a68d1eace75b9b08f23633d1fb5ce6134403959e/caspo/core/logicalnetwork.py#L380-L391 |
bioasp/caspo | caspo/core/logicalnetwork.py | LogicalNetworkList.frequency | def frequency(self, mapping):
"""
Returns frequency of a given :class:`caspo.core.mapping.Mapping`
Parameters
----------
mapping : :class:`caspo.core.mapping.Mapping`
A logical conjuntion mapping
Returns
-------
float
Frequency of the given mapping over all logical networks
Raises
------
ValueError
If the given mapping is not found in the mappings of the underlying hypergraph of this list
"""
return self.__matrix[:, self.hg.mappings[mapping]].mean() | python | def frequency(self, mapping):
"""
Returns frequency of a given :class:`caspo.core.mapping.Mapping`
Parameters
----------
mapping : :class:`caspo.core.mapping.Mapping`
A logical conjuntion mapping
Returns
-------
float
Frequency of the given mapping over all logical networks
Raises
------
ValueError
If the given mapping is not found in the mappings of the underlying hypergraph of this list
"""
return self.__matrix[:, self.hg.mappings[mapping]].mean() | [
"def",
"frequency",
"(",
"self",
",",
"mapping",
")",
":",
"return",
"self",
".",
"__matrix",
"[",
":",
",",
"self",
".",
"hg",
".",
"mappings",
"[",
"mapping",
"]",
"]",
".",
"mean",
"(",
")"
] | Returns frequency of a given :class:`caspo.core.mapping.Mapping`
Parameters
----------
mapping : :class:`caspo.core.mapping.Mapping`
A logical conjuntion mapping
Returns
-------
float
Frequency of the given mapping over all logical networks
Raises
------
ValueError
If the given mapping is not found in the mappings of the underlying hypergraph of this list | [
"Returns",
"frequency",
"of",
"a",
"given",
":",
"class",
":",
"caspo",
".",
"core",
".",
"mapping",
".",
"Mapping"
] | train | https://github.com/bioasp/caspo/blob/a68d1eace75b9b08f23633d1fb5ce6134403959e/caspo/core/logicalnetwork.py#L393-L412 |
bioasp/caspo | caspo/core/logicalnetwork.py | LogicalNetworkList.combinatorics | def combinatorics(self):
"""
Returns mutually exclusive/inclusive mappings
Returns
-------
(dict,dict)
A tuple of 2 dictionaries.
For each mapping key, the first dict has as value the set of mutually exclusive mappings while
the second dict has as value the set of mutually inclusive mappings.
"""
f = self.__matrix.mean(axis=0)
candidates = np.where((f < 1) & (f > 0))[0]
exclusive, inclusive = defaultdict(set), defaultdict(set)
for i, j in it.combinations(candidates, 2):
xor = np.logical_xor(self.__matrix[:, i], self.__matrix[:, j])
if xor.all():
exclusive[self.hg.mappings[i]].add(self.hg.mappings[j])
exclusive[self.hg.mappings[j]].add(self.hg.mappings[i])
if (~xor).all():
inclusive[self.hg.mappings[i]].add(self.hg.mappings[j])
inclusive[self.hg.mappings[j]].add(self.hg.mappings[i])
return exclusive, inclusive | python | def combinatorics(self):
"""
Returns mutually exclusive/inclusive mappings
Returns
-------
(dict,dict)
A tuple of 2 dictionaries.
For each mapping key, the first dict has as value the set of mutually exclusive mappings while
the second dict has as value the set of mutually inclusive mappings.
"""
f = self.__matrix.mean(axis=0)
candidates = np.where((f < 1) & (f > 0))[0]
exclusive, inclusive = defaultdict(set), defaultdict(set)
for i, j in it.combinations(candidates, 2):
xor = np.logical_xor(self.__matrix[:, i], self.__matrix[:, j])
if xor.all():
exclusive[self.hg.mappings[i]].add(self.hg.mappings[j])
exclusive[self.hg.mappings[j]].add(self.hg.mappings[i])
if (~xor).all():
inclusive[self.hg.mappings[i]].add(self.hg.mappings[j])
inclusive[self.hg.mappings[j]].add(self.hg.mappings[i])
return exclusive, inclusive | [
"def",
"combinatorics",
"(",
"self",
")",
":",
"f",
"=",
"self",
".",
"__matrix",
".",
"mean",
"(",
"axis",
"=",
"0",
")",
"candidates",
"=",
"np",
".",
"where",
"(",
"(",
"f",
"<",
"1",
")",
"&",
"(",
"f",
">",
"0",
")",
")",
"[",
"0",
"]"... | Returns mutually exclusive/inclusive mappings
Returns
-------
(dict,dict)
A tuple of 2 dictionaries.
For each mapping key, the first dict has as value the set of mutually exclusive mappings while
the second dict has as value the set of mutually inclusive mappings. | [
"Returns",
"mutually",
"exclusive",
"/",
"inclusive",
"mappings"
] | train | https://github.com/bioasp/caspo/blob/a68d1eace75b9b08f23633d1fb5ce6134403959e/caspo/core/logicalnetwork.py#L414-L438 |
bioasp/caspo | caspo/core/logicalnetwork.py | LogicalNetworkList.predictions | def predictions(self, setup, n_jobs=-1):
"""
Returns a `pandas.DataFrame`_ with the weighted average predictions and variance of all readouts for each possible
clampings in the given experimental setup.
For each logical network the weight corresponds to the number of networks having the same behavior.
Parameters
----------
setup : :class:`caspo.core.setup.Setup`
Experimental setup
n_jobs : int
Number of jobs to run in parallel. Default to -1 (all cores available)
Returns
-------
`pandas.DataFrame`_
DataFrame with the weighted average predictions and variance of all readouts for each possible clamping
.. _pandas.DataFrame: http://pandas.pydata.org/pandas-docs/stable/dsintro.html#dataframe
.. seealso:: `Wikipedia: Weighted sample variance <https://en.wikipedia.org/wiki/Weighted_arithmetic_mean#Weighted_sample_variance>`_
"""
stimuli, inhibitors, readouts = setup.stimuli, setup.inhibitors, setup.readouts
nc = len(setup.cues())
predictions = np.zeros((len(self), 2**nc, len(setup)))
predictions[:, :, :] = Parallel(n_jobs=n_jobs)(delayed(__parallel_predictions__)(n, list(setup.clampings_iter(setup.cues())), readouts, stimuli, inhibitors) for n in self)
avg = np.average(predictions[:, :, nc:], axis=0, weights=self.__networks)
var = np.average((predictions[:, :, nc:]-avg)**2, axis=0, weights=self.__networks)
rcues = ["TR:%s" % c for c in setup.cues(True)]
cols = np.concatenate([rcues, ["AVG:%s" % r for r in readouts], ["VAR:%s" % r for r in readouts]])
#use the first network predictions to extract all clampings
df = pd.DataFrame(np.concatenate([predictions[0, :, :nc], avg, var], axis=1), columns=cols)
df[rcues] = df[rcues].astype(int)
return df | python | def predictions(self, setup, n_jobs=-1):
"""
Returns a `pandas.DataFrame`_ with the weighted average predictions and variance of all readouts for each possible
clampings in the given experimental setup.
For each logical network the weight corresponds to the number of networks having the same behavior.
Parameters
----------
setup : :class:`caspo.core.setup.Setup`
Experimental setup
n_jobs : int
Number of jobs to run in parallel. Default to -1 (all cores available)
Returns
-------
`pandas.DataFrame`_
DataFrame with the weighted average predictions and variance of all readouts for each possible clamping
.. _pandas.DataFrame: http://pandas.pydata.org/pandas-docs/stable/dsintro.html#dataframe
.. seealso:: `Wikipedia: Weighted sample variance <https://en.wikipedia.org/wiki/Weighted_arithmetic_mean#Weighted_sample_variance>`_
"""
stimuli, inhibitors, readouts = setup.stimuli, setup.inhibitors, setup.readouts
nc = len(setup.cues())
predictions = np.zeros((len(self), 2**nc, len(setup)))
predictions[:, :, :] = Parallel(n_jobs=n_jobs)(delayed(__parallel_predictions__)(n, list(setup.clampings_iter(setup.cues())), readouts, stimuli, inhibitors) for n in self)
avg = np.average(predictions[:, :, nc:], axis=0, weights=self.__networks)
var = np.average((predictions[:, :, nc:]-avg)**2, axis=0, weights=self.__networks)
rcues = ["TR:%s" % c for c in setup.cues(True)]
cols = np.concatenate([rcues, ["AVG:%s" % r for r in readouts], ["VAR:%s" % r for r in readouts]])
#use the first network predictions to extract all clampings
df = pd.DataFrame(np.concatenate([predictions[0, :, :nc], avg, var], axis=1), columns=cols)
df[rcues] = df[rcues].astype(int)
return df | [
"def",
"predictions",
"(",
"self",
",",
"setup",
",",
"n_jobs",
"=",
"-",
"1",
")",
":",
"stimuli",
",",
"inhibitors",
",",
"readouts",
"=",
"setup",
".",
"stimuli",
",",
"setup",
".",
"inhibitors",
",",
"setup",
".",
"readouts",
"nc",
"=",
"len",
"(... | Returns a `pandas.DataFrame`_ with the weighted average predictions and variance of all readouts for each possible
clampings in the given experimental setup.
For each logical network the weight corresponds to the number of networks having the same behavior.
Parameters
----------
setup : :class:`caspo.core.setup.Setup`
Experimental setup
n_jobs : int
Number of jobs to run in parallel. Default to -1 (all cores available)
Returns
-------
`pandas.DataFrame`_
DataFrame with the weighted average predictions and variance of all readouts for each possible clamping
.. _pandas.DataFrame: http://pandas.pydata.org/pandas-docs/stable/dsintro.html#dataframe
.. seealso:: `Wikipedia: Weighted sample variance <https://en.wikipedia.org/wiki/Weighted_arithmetic_mean#Weighted_sample_variance>`_ | [
"Returns",
"a",
"pandas",
".",
"DataFrame",
"_",
"with",
"the",
"weighted",
"average",
"predictions",
"and",
"variance",
"of",
"all",
"readouts",
"for",
"each",
"possible",
"clampings",
"in",
"the",
"given",
"experimental",
"setup",
".",
"For",
"each",
"logica... | train | https://github.com/bioasp/caspo/blob/a68d1eace75b9b08f23633d1fb5ce6134403959e/caspo/core/logicalnetwork.py#L440-L479 |
bioasp/caspo | caspo/core/logicalnetwork.py | LogicalNetworkList.weighted_mse | def weighted_mse(self, dataset, n_jobs=-1):
"""
Returns the weighted MSE over all logical networks with respect to the given :class:`caspo.core.dataset.Dataset` object instance.
For each logical network the weight corresponds to the number of networks having the same behavior.
Parameters
----------
dataset: :class:`caspo.core.dataset.Dataset`
Dataset to compute MSE
n_jobs : int
Number of jobs to run in parallel. Default to -1 (all cores available)
Returns
-------
float
Weighted MSE
"""
predictions = np.zeros((len(self), len(dataset.clampings), len(dataset.setup.readouts)))
predictions[:, :, :] = Parallel(n_jobs=n_jobs)(delayed(__parallel_predictions__)(n, dataset.clampings, dataset.setup.readouts) for n in self)
for i, _ in enumerate(self):
predictions[i, :, :] *= self.__networks[i]
readouts = dataset.readouts.values
pos = ~np.isnan(readouts)
return mean_squared_error(readouts[pos], (np.sum(predictions, axis=0) / np.sum(self.__networks))[pos]) | python | def weighted_mse(self, dataset, n_jobs=-1):
"""
Returns the weighted MSE over all logical networks with respect to the given :class:`caspo.core.dataset.Dataset` object instance.
For each logical network the weight corresponds to the number of networks having the same behavior.
Parameters
----------
dataset: :class:`caspo.core.dataset.Dataset`
Dataset to compute MSE
n_jobs : int
Number of jobs to run in parallel. Default to -1 (all cores available)
Returns
-------
float
Weighted MSE
"""
predictions = np.zeros((len(self), len(dataset.clampings), len(dataset.setup.readouts)))
predictions[:, :, :] = Parallel(n_jobs=n_jobs)(delayed(__parallel_predictions__)(n, dataset.clampings, dataset.setup.readouts) for n in self)
for i, _ in enumerate(self):
predictions[i, :, :] *= self.__networks[i]
readouts = dataset.readouts.values
pos = ~np.isnan(readouts)
return mean_squared_error(readouts[pos], (np.sum(predictions, axis=0) / np.sum(self.__networks))[pos]) | [
"def",
"weighted_mse",
"(",
"self",
",",
"dataset",
",",
"n_jobs",
"=",
"-",
"1",
")",
":",
"predictions",
"=",
"np",
".",
"zeros",
"(",
"(",
"len",
"(",
"self",
")",
",",
"len",
"(",
"dataset",
".",
"clampings",
")",
",",
"len",
"(",
"dataset",
... | Returns the weighted MSE over all logical networks with respect to the given :class:`caspo.core.dataset.Dataset` object instance.
For each logical network the weight corresponds to the number of networks having the same behavior.
Parameters
----------
dataset: :class:`caspo.core.dataset.Dataset`
Dataset to compute MSE
n_jobs : int
Number of jobs to run in parallel. Default to -1 (all cores available)
Returns
-------
float
Weighted MSE | [
"Returns",
"the",
"weighted",
"MSE",
"over",
"all",
"logical",
"networks",
"with",
"respect",
"to",
"the",
"given",
":",
"class",
":",
"caspo",
".",
"core",
".",
"dataset",
".",
"Dataset",
"object",
"instance",
".",
"For",
"each",
"logical",
"network",
"th... | train | https://github.com/bioasp/caspo/blob/a68d1eace75b9b08f23633d1fb5ce6134403959e/caspo/core/logicalnetwork.py#L481-L507 |
bioasp/caspo | caspo/core/logicalnetwork.py | LogicalNetwork.from_hypertuples | def from_hypertuples(cls, hg, tuples):
"""
Creates a logical network from an iterable of integer tuples matching mappings in the given
:class:`caspo.core.hypergraph.HyperGraph`
Parameters
----------
hg : :class:`caspo.core.hypergraph.HyperGraph`
Underlying hypergraph
tuples : (int,int)
tuples matching mappings in the given hypergraph
Returns
-------
caspo.core.logicalnetwork.LogicalNetwork
Created object instance
"""
return cls([(hg.clauses[j], hg.variable(i)) for i, j in tuples], networks=1) | python | def from_hypertuples(cls, hg, tuples):
"""
Creates a logical network from an iterable of integer tuples matching mappings in the given
:class:`caspo.core.hypergraph.HyperGraph`
Parameters
----------
hg : :class:`caspo.core.hypergraph.HyperGraph`
Underlying hypergraph
tuples : (int,int)
tuples matching mappings in the given hypergraph
Returns
-------
caspo.core.logicalnetwork.LogicalNetwork
Created object instance
"""
return cls([(hg.clauses[j], hg.variable(i)) for i, j in tuples], networks=1) | [
"def",
"from_hypertuples",
"(",
"cls",
",",
"hg",
",",
"tuples",
")",
":",
"return",
"cls",
"(",
"[",
"(",
"hg",
".",
"clauses",
"[",
"j",
"]",
",",
"hg",
".",
"variable",
"(",
"i",
")",
")",
"for",
"i",
",",
"j",
"in",
"tuples",
"]",
",",
"n... | Creates a logical network from an iterable of integer tuples matching mappings in the given
:class:`caspo.core.hypergraph.HyperGraph`
Parameters
----------
hg : :class:`caspo.core.hypergraph.HyperGraph`
Underlying hypergraph
tuples : (int,int)
tuples matching mappings in the given hypergraph
Returns
-------
caspo.core.logicalnetwork.LogicalNetwork
Created object instance | [
"Creates",
"a",
"logical",
"network",
"from",
"an",
"iterable",
"of",
"integer",
"tuples",
"matching",
"mappings",
"in",
"the",
"given",
":",
"class",
":",
"caspo",
".",
"core",
".",
"hypergraph",
".",
"HyperGraph"
] | train | https://github.com/bioasp/caspo/blob/a68d1eace75b9b08f23633d1fb5ce6134403959e/caspo/core/logicalnetwork.py#L557-L575 |
bioasp/caspo | caspo/core/logicalnetwork.py | LogicalNetwork.to_graph | def to_graph(self):
"""
Converts the logical network to its underlying interaction graph
Returns
-------
caspo.core.graph.Graph
The underlying interaction graph
"""
edges = set()
for clause, target in self.edges_iter():
for source, signature in clause:
edges.add((source, target, signature))
return Graph.from_tuples(edges) | python | def to_graph(self):
"""
Converts the logical network to its underlying interaction graph
Returns
-------
caspo.core.graph.Graph
The underlying interaction graph
"""
edges = set()
for clause, target in self.edges_iter():
for source, signature in clause:
edges.add((source, target, signature))
return Graph.from_tuples(edges) | [
"def",
"to_graph",
"(",
"self",
")",
":",
"edges",
"=",
"set",
"(",
")",
"for",
"clause",
",",
"target",
"in",
"self",
".",
"edges_iter",
"(",
")",
":",
"for",
"source",
",",
"signature",
"in",
"clause",
":",
"edges",
".",
"add",
"(",
"(",
"source"... | Converts the logical network to its underlying interaction graph
Returns
-------
caspo.core.graph.Graph
The underlying interaction graph | [
"Converts",
"the",
"logical",
"network",
"to",
"its",
"underlying",
"interaction",
"graph"
] | train | https://github.com/bioasp/caspo/blob/a68d1eace75b9b08f23633d1fb5ce6134403959e/caspo/core/logicalnetwork.py#L581-L595 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.