code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
def create_quiz_report(self, quiz_id, course_id, quiz_report_report_type, include=None, quiz_report_includes_all_versions=None):
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
path["course_id"] = course_id
# REQUIRED - PATH - q... | Create a quiz report.
Create and return a new report for this quiz. If a previously
generated report matches the arguments and is still current (i.e.
there have been no new submissions), it will be returned.
*Responses*
* <code>400 Bad Request</code> if... | null | null | null | |
s = cues or list(self.stimuli + self.inhibitors)
clampings = it.chain.from_iterable(it.combinations(s, r) for r in xrange(len(s) + 1))
literals_tpl = {}
for stimulus in self.stimuli:
literals_tpl[stimulus] = -1
for c in clampings:
literals = lit... | def clampings_iter(self, cues=None) | Iterates over all possible clampings of this experimental setup
Parameters
----------
cues : Optional[iterable]
If given, restricts clampings over given species names
Yields
------
caspo.core.clamping.Clamping
The next clamping with respect to t... | 3.874284 | 4.102745 | 0.944315 |
fs = set((gringo.Fun('stimulus', [str(var)]) for var in self.stimuli))
fs = fs.union((gringo.Fun('inhibitor', [str(var)]) for var in self.inhibitors))
fs = fs.union((gringo.Fun('readout', [str(var)]) for var in self.readouts))
return fs | def to_funset(self) | Converts the experimental setup to a set of `gringo.Fun`_ object instances
Returns
-------
set
The set of `gringo.Fun`_ object instances
.. _gringo.Fun: http://potassco.sourceforge.net/gringo.html#Fun | 4.082036 | 3.641694 | 1.120917 |
with open(filename) as fp:
raw = json.load(fp)
return cls(raw['stimuli'], raw['inhibitors'], raw['readouts']) | def from_json(cls, filename) | Creates an experimental setup from a JSON file
Parameters
----------
filename : str
Absolute path to JSON file
Returns
-------
caspo.core.setup.Setup
Created object instance | 5.808452 | 7.699378 | 0.754405 |
with open(filename, 'w') as fp:
json.dump(dict(stimuli=self.stimuli, inhibitors=self.inhibitors, readouts=self.readouts), fp) | def to_json(self, filename) | Writes the experimental setup to a JSON file
Parameters
----------
filename : str
Absolute path where to write the JSON file | 3.799156 | 3.927477 | 0.967327 |
cues = self.stimuli + self.inhibitors
active_cues = set()
active_readouts = set()
for clause, var in networks.mappings:
active_cues = active_cues.union((l for (l, s) in clause if l in cues))
if var in self.readouts:
active_readouts.add(var... | def filter(self, networks) | Returns a new experimental setup restricted to species present in the given list of networks
Parameters
----------
networks : :class:`caspo.core.logicalnetwork.LogicalNetworkList`
List of logical networks
Returns
-------
caspo.core.setup.Setup
Th... | 4.853193 | 4.761289 | 1.019302 |
if rename_inhibitors:
return self.stimuli + [i+'i' for i in self.inhibitors]
else:
return self.stimuli + self.inhibitors | def cues(self, rename_inhibitors=False) | Returns stimuli and inhibitors species of this experimental setup
Parameters
----------
rename_inhibitors : boolean
If True, rename inhibitors with an ending 'i' as in MIDAS files.
Returns
-------
list
List of species names in order: first stimul... | 3.216393 | 2.796536 | 1.150135 |
def list_external_tools_courses(self, course_id, include_parents=None, search_term=None, selectable=None):
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
path["course_id"] = course_id
# OPTIONAL - search_term
... | List external tools.
Returns the paginated list of external tools for the current context.
See the get request docs for a single tool for a list of properties on an external tool. | null | null | null | |
def list_external_tools_accounts(self, account_id, include_parents=None, search_term=None, selectable=None):
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
path["account_id"] = account_id
# OPTIONAL - search_term
... | List external tools.
Returns the paginated list of external tools for the current context.
See the get request docs for a single tool for a list of properties on an external tool. | null | null | null | |
def list_external_tools_groups(self, group_id, include_parents=None, search_term=None, selectable=None):
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
path["group_id"] = group_id
# OPTIONAL - search_term
if s... | List external tools.
Returns the paginated list of external tools for the current context.
See the get request docs for a single tool for a list of properties on an external tool. | null | null | null | |
def get_sessionless_launch_url_for_external_tool_courses(self, course_id, assignment_id=None, id=None, launch_type=None, module_item_id=None, url=None):
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
path["course_id"] = course_id
... | Get a sessionless launch url for an external tool.
Returns a sessionless launch url for an external tool.
NOTE: Either the id or url must be provided unless launch_type is assessment or module_item. | null | null | null | |
def get_single_external_tool_courses(self, course_id, external_tool_id):
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
path["course_id"] = course_id
# REQUIRED - PATH - external_tool_id
path["external_tool_i... | Get a single external tool.
Returns the specified external tool. | null | null | null | |
def get_single_external_tool_accounts(self, account_id, external_tool_id):
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
path["account_id"] = account_id
# REQUIRED - PATH - external_tool_id
path["external_t... | Get a single external tool.
Returns the specified external tool. | null | null | null | |
self._find_lte(key)
node = self._create_node(key, value)
self._insert(node) | def insert(self, key, value) | Insert a key-value pair in the list.
The pair is inserted at the correct location so that the list remains
sorted on *key*. If a pair with the same key is already in the list,
then the pair is appended after all other pairs with that key. | 5.552253 | 7.454895 | 0.74478 |
self._find_lt(key)
node = self._path[0][2]
if node is self._tail or key < node[0]:
node = self._create_node(key, value)
self._insert(node)
else:
node[1] = value | def replace(self, key, value) | Replace the value of the first key-value pair with key *key*.
If the key was not found, the pair is inserted. | 4.988698 | 5.576513 | 0.894591 |
for i in range(self.maxlevel):
self._head[2+i] = self._tail
self._tail[-1] = 0
self._level = 1 | def clear(self) | Remove all key-value pairs. | 7.465348 | 7.191763 | 1.038041 |
if start is None:
node = self._head[2]
else:
self._find_lt(start)
node = self._path[0][2]
while node is not self._tail and (stop is None or node[0] < stop):
yield (node[0], node[1])
node = node[2] | def items(self, start=None, stop=None) | Return an iterator yielding pairs.
If *start* is specified, iteration starts at the first pair with a key
that is larger than or equal to *start*. If not specified, iteration
starts at the first pair in the list.
If *stop* is specified, iteration stops at the last pair that is
... | 3.772584 | 3.582913 | 1.052938 |
return (item[0] for item in self.items(start, stop)) | def keys(self, start=None, stop=None) | Like :meth:`items` but returns only the keys. | 5.984254 | 4.081138 | 1.46632 |
return (item[1] for item in self.items(start, stop)) | def values(self, start=None, stop=None) | Like :meth:`items` but returns only the values. | 5.862771 | 3.71896 | 1.576454 |
node = self._head[2]
if node is self._tail:
raise KeyError('list is empty')
self._find_lt(node[0])
self._remove(node)
return (node[0], node[1]) | def popitem(self) | Removes the first key-value pair and return it.
This method raises a ``KeyError`` if the list is empty. | 4.396262 | 4.690456 | 0.937278 |
self._find_lt(key)
node = self._path[0][2]
if node is self._tail or key < node[0]:
return default
return node[1] | def search(self, key, default=None) | Find the first key-value pair with key *key* and return its value.
If the key was not found, return *default*. If no default was provided,
return ``None``. This method never raises a ``KeyError``. | 6.914218 | 8.101002 | 0.853502 |
self._find_lt(key)
node = self._path[0][2]
if node is self._tail or key < node[0]:
raise KeyError('{!r} is not in list'.format(key))
self._remove(node) | def remove(self, key) | Remove the first key-value pair with key *key*.
If the key was not found, a ``KeyError`` is raised. | 5.927008 | 6.267569 | 0.945663 |
self._find_lt(key)
node = self._path[0][2]
if node is self._tail or key < node[0]:
if default is self.UNSET:
raise KeyError('key {!r} not in list')
return default
self._remove(node)
return node[1] | def pop(self, key, default=UNSET) | Remove the first key-value pair with key *key*.
If a pair was removed, return its value. Otherwise if *default* was
provided, return *default*. Otherwise a ``KeyError`` is raised. | 5.536253 | 5.895541 | 0.939058 |
self._find_lt(key)
node = self._path[0][2]
if node is self._tail or key < node[0]:
if default is self.UNSET:
raise KeyError('key {!r} not in list'.format(key))
return default
return self._distance[0] | def index(self, key, default=UNSET) | Find the first key-value pair with key *key* and return its position.
If the key is not found, return *default*. If default was not provided,
raise a ``KeyError`` | 6.067332 | 7.01154 | 0.865335 |
count = 0
pos = self.index(key, -1)
if pos == -1:
return count
count += 1
for i in range(pos+1, len(self)):
if self[i][0] != key:
break
count += 1
return count | def count(self, key) | Return the number of pairs with key *key*. | 2.522712 | 2.388594 | 1.056149 |
def update_tab_for_course(self, tab_id, course_id, hidden=None, position=None):
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
path["course_id"] = course_id
# REQUIRED - PATH - tab_id
path["tab_id"] = tab_id
... | Update a tab for a course.
Home and Settings tabs are not manageable, and can't be hidden or moved
Returns a tab object | null | null | null | |
# Determine if a row per query limit should be set
num_rows = self.count_rows(table)
if num_rows > limit:
return self._select_batched(table, '*', num_rows, limit, execute=execute)
else:
return self.select(table, '*', execute=execute) | def select_all(self, table, limit=MAX_ROWS_PER_QUERY, execute=True) | Query all rows and columns from a table. | 4.54001 | 4.626463 | 0.981313 |
return self.select(table, cols, execute, select_type='SELECT DISTINCT') | def select_distinct(self, table, cols='*', execute=True) | Query distinct values from a table. | 7.325654 | 7.449538 | 0.98337 |
# Validate query type
select_type = select_type.upper()
assert select_type in SELECT_QUERY_TYPES
# Concatenate statement
statement = '{0} {1} FROM {2}'.format(select_type, join_cols(cols), wrap(table))
if not execute:
# Return command
ret... | def select(self, table, cols, execute=True, select_type='SELECT', return_type=list) | Query every row and only certain columns from a table. | 5.090658 | 5.061673 | 1.005726 |
# Check if cols is a list of tuples
if isinstance(cols[0], tuple):
cols = join_cols(['{0}.{1}'.format(tbl, col) for tbl, col in cols])
else:
cols = join_cols(['{0}.{1}'.format(table1, col) for col in cols])
# Validate join_type and table2_col
joi... | def select_join(self, table1, table2, cols, table1_col, table2_col=None, join_type=None) | Left join all rows and columns from two tables where a common value is shared.
:param table1: Name of table #1
:param table2: Name of table #2
:param cols: List of columns or column tuples
String or flat list: Assumes column(s) are from table #1 if not specified
List of ... | 2.444599 | 2.384312 | 1.025285 |
return self.fetch(self._select_limit_statement(table, cols, offset, limit)) | def select_limit(self, table, cols='*', offset=0, limit=MAX_ROWS_PER_QUERY) | Run a select query with an offset and limit parameter. | 5.099705 | 4.604245 | 1.107609 |
# Unpack WHERE clause dictionary into tuple
if isinstance(where, (list, set)):
# Multiple WHERE clause's (separate with AND)
clauses = [self._where_clause(clause) for clause in where]
where_statement = ' AND '.join(clauses)
else:
where_sta... | def select_where(self, table, cols, where, return_type=list) | Query certain rows from a table where a particular value is found.
cols parameter can be passed as a iterable (list, set, tuple) or a string if
only querying a single column. where parameter can be passed as a two or three
part tuple. If only two parts are passed the assumed operator is equal... | 4.525812 | 4.556211 | 0.993328 |
# Unpack WHERE clause dictionary into tuple
min_val, max_val = between
# Concatenate full statement and execute
statement = "SELECT {0} FROM {1} WHERE {2} BETWEEN {3} AND {4}".format(join_cols(cols), wrap(table), where_col,
... | def select_where_between(self, table, cols, where_col, between) | Query rows from a table where a columns value is found between two values.
:param table: Name of the table
:param cols: List, tuple or set of columns or string with single column name
:param where_col: Column to check values against
:param between: Tuple with min and max values for comp... | 5.142088 | 5.473421 | 0.939465 |
# Retrieve search pattern
pattern = self._like_pattern(start, end, anywhere, index, length)
# Concatenate full statement and execute
statement = "SELECT {0} FROM {1} WHERE {2} LIKE '{3}'".format(join_cols(cols), wrap(table), where_col, pattern)
return self.fetch(stateme... | def select_where_like(self, table, cols, where_col, start=None, end=None, anywhere=None,
index=(None, None), length=None) | Query rows from a table where a specific pattern is found in a column.
MySQL syntax assumptions:
(%) The percent sign represents zero, one, or multiple characters.
(_) The underscore represents a single character.
:param table: Name of the table
:param cols: List, tuple... | 4.600767 | 5.529637 | 0.83202 |
assert isinstance(where, tuple)
if len(where) == 3:
where_col, operator, where_val = where
else:
where_col, where_val = where
operator = '='
assert operator in SELECT_WHERE_OPERATORS
# Concatenate WHERE clause (ex: **first_name='John'... | def _where_clause(where) | Unpack a where clause tuple and concatenate a MySQL WHERE statement.
:param where: 2 or 3 part tuple containing a where_column and a where_value (optional operator)
:return: WHERE clause statement | 4.663581 | 4.184918 | 1.114378 |
if return_type is dict:
# Pack each row into a dictionary
cols = self.get_columns(table) if cols is '*' else cols
if len(values) > 0 and isinstance(values[0], (set, list, tuple)):
return [dict(zip(cols, row)) for row in values]
else:
... | def _return_rows(self, table, cols, values, return_type) | Return fetched rows in the desired type. | 2.973949 | 2.945115 | 1.009791 |
# Execute select queries in small batches to avoid connection timeout
commands, offset = [], 0
while num_rows > 0:
# Use number of rows as limit if num_rows < limit
_limit = min(limit, num_rows)
# Execute select_limit query
commands.appen... | def _select_batched(self, table, cols, num_rows, limit, queries_per_batch=3, execute=True) | Run select queries in small batches and return joined resutls. | 4.429809 | 4.154799 | 1.066191 |
return 'SELECT {0} FROM {1} LIMIT {2}, {3}'.format(join_cols(cols), wrap(table), offset, limit) | def _select_limit_statement(table, cols='*', offset=0, limit=MAX_ROWS_PER_QUERY) | Concatenate a select with offset and limit statement. | 4.266833 | 3.773739 | 1.130664 |
# Unpack index tuple
index_num, index_char = index
index = None
# Start, end, anywhere
if all(i for i in [start, end, anywhere]) and not any(i for i in [index, length]):
return '{start}%{anywhere}%{end}'.format(start=start, end=end, anywhere=anywhere)
... | def _like_pattern(start, end, anywhere, index, length) | Create a LIKE pattern to use as a search parameter for a WHERE clause.
:param start: Value to be found at the start
:param end: Value to be found at the end
:param anywhere: Value to be found anywhere
:param index: Value to be found at a certain index
:param length: Minimum char... | 1.638716 | 1.630542 | 1.005013 |
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)):
... | def insert_statement(table, columns, values) | Generate an insert statement string for dumping to text file or MySQL execution. | 2.641924 | 2.615041 | 1.01028 |
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:
stateme... | def dump_table(self, table, drop_statement=True) | Export a table structure and data to SQL file for backup or later import. | 3.45384 | 3.216617 | 1.073749 |
# 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=... | 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. | 3.327515 | 3.445856 | 0.965657 |
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):
... | def retry(method) | Allows to retry method execution few times. | 3.901646 | 3.745376 | 1.041723 |
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 o... | def setup_managers(self) | Allows to access manager by model name - it is convenient, because HasOffers returns model names in responses. | 6.051507 | 5.542526 | 1.091832 |
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.endpoi... | 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. | 2.705993 | 2.781745 | 0.972768 |
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
... | def handle_response(self, content, target=None, single_result=True, raw=False) | Parses response, checks it. | 4.046242 | 3.933409 | 1.028686 |
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) | Initializes model instances from given data.
Returns single instance if single_result=True. | 5.523448 | 6.070431 | 0.909894 |
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 OrderedDic... | def init_target_object(self, target, data) | Initializes target object and assign extra objects to target as attributes | 3.575025 | 3.490294 | 1.024276 |
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, it... | def expand_models(self, target, data) | Generates all objects from given data. | 3.92899 | 3.651207 | 1.07608 |
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() != ... | def merge_roles(dominant_name, deprecated_name) | Merges a deprecated role into a dominant role. | 1.741526 | 1.726371 | 1.008778 |
'''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) | Wrapper for search_bugs, for simple string searches | 12.013271 | 5.549576 | 2.164719 |
'''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]),
... | def search_bugs(self, terms) | http://bugzilla.readthedocs.org/en/latest/api/core/v1/bug.html#search-bugs
terms = [{'product': 'Infrastructure & Operations'}, {'status': 'NEW'}] | 6.792458 | 3.526614 | 1.926056 |
'''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(attachm... | def put_attachment(self, attachmentid, attachment_update) | http://bugzilla.readthedocs.org/en/latest/api/core/v1/attachment.html#update-attachment | 5.064839 | 3.458805 | 1.464332 |
'''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) | http://bugzilla.readthedocs.org/en/latest/api/core/v1/bug.html#update-bug | 4.641221 | 3.262553 | 1.422573 |
'''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.c... | def post_attachment(self, bugid, attachment) | http://bugzilla.readthedocs.org/en/latest/api/core/v1/attachment.html#create-attachment | 3.867673 | 3.10762 | 1.244577 |
'''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_... | def post_bug(self, bug) | http://bugzilla.readthedocs.org/en/latest/api/core/v1/bug.html#create-bug | 3.804046 | 2.928806 | 1.298838 |
'''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) | http://bugzilla.readthedocs.org/en/latest/api/core/v1/comment.html#create-comments | 4.449083 | 2.572614 | 1.729402 |
'''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 ... | def _get(self, q, params='') | Generic GET wrapper including the api_key | 3.31102 | 2.847201 | 1.162904 |
'''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=paylo... | def _post(self, q, payload='', params='') | Generic POST wrapper including the api_key | 3.184164 | 2.756136 | 1.1553 |
def bind_objects(self, *objects):
self.control.bind_keys(objects)
self.objects += objects | Bind one or more objects | null | null | null | |
def update(self, time_delta):
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 grou... | 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 | null | null | null | |
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. | null | null | null | |
def reset_ball(self, x, y):
self.sprite.position.x = x
self.sprite.position.y = y | reset ball to set location on the screen | null | null | null | |
def update(self, td):
self.sprite.last_position = self.sprite.position
self.sprite.last_velocity = self.sprite.velocity
if self.particle_group != None:
self.update_particle_group(td) | Update state of ball | null | null | null | |
def generate(self):
x, y, z = self.point1
return (x + self.size_x * random(),
y + self.size_y * random(),
z + self.size_z * random()) | Return a random point inside the box | null | null | null | |
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(pub... | 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. | 3.442727 | 3.498811 | 0.983971 |
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:
... | 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. | 6.198174 | 4.747101 | 1.305675 |
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)
... | 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. | 3.564691 | 3.251481 | 1.096328 |
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 ... | 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. | 1.86171 | 1.83429 | 1.014949 |
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"]
... | def groups_filter_from_query(query, field_map={}) | Creates an F object for the groups of a search query. | 1.97334 | 1.91397 | 1.031019 |
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(publis... | def date_range_filter(range_name) | Create a filter from a named date range. | 5.91308 | 5.407823 | 1.093431 |
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') | Append the REST headers to every request | 2.834487 | 2.662851 | 1.064456 |
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 = []
# M... | 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. | 4.657619 | 4.368221 | 1.066251 |
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) | See parent method for documentation | 6.126574 | 5.882596 | 1.041475 |
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) | See parent method for documentation | 4.950398 | 4.718781 | 1.049084 |
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) | If the route coverage lookup encounters an error, we will treat it as "not covered". | 7.205974 | 6.790424 | 1.061196 |
def make_account_admin(self, user_id, account_id, role=None, role_id=None, send_confirmation=None):
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
path["account_id"] = account_id
# REQUIRED - user_id
data["u... | Make an account admin.
Flag an existing user as an admin within the account. | null | null | null | |
def list_account_admins(self, account_id, user_id=None):
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
path["account_id"] = account_id
# OPTIONAL - user_id
if user_id is not None:
params["user_... | List account admins.
List the admins in the account | null | null | null | |
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) | >>> _hex_to_rgb("007fff")
(0, 127, 255) | 3.66668 | 3.554848 | 1.031459 |
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) | 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 b... | 2.234404 | 2.551302 | 0.87579 |
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... | 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 ad... | 2.416555 | 2.552562 | 0.946717 |
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, becaus... | 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
no... | 3.992861 | 3.984432 | 1.002116 |
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)
... | 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.
... | 2.53492 | 2.384943 | 1.062885 |
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)... | def SessionAuthSourceInitializer(
value_key='sanity.'
) | An authentication source that uses the current session | 2.191741 | 2.195742 | 0.998178 |
@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)
... | 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. | 2.971456 | 3.088649 | 0.962057 |
@implementer(IAuthSourceService)
class HeaderAuthSource(object):
vary = ['Authorization']
def __init__(self, context, request):
self.request = request
self.cur_val = None
serializer = JSONSerializer()
self.serializer = SignedSerializer(
... | def HeaderAuthSourceInitializer(
secret,
salt='sanity.header.'
) | An authentication source that uses the Authorization header. | 2.9297 | 2.968383 | 0.986968 |
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) | Filter given collection. | 6.184408 | 5.809132 | 1.064601 |
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) | Load a resource. | 7.206155 | 6.731634 | 1.070491 |
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.co... | def sort(self, *sorting, **kwargs) | Sort resources. | 3.012135 | 2.790005 | 1.079616 |
return self.collection.offset(offset).limit(limit), self.collection.count() | def paginate(self, request, offset=0, limit=None) | Paginate queryset. | 6.747485 | 6.059368 | 1.113563 |
resources = resource if isinstance(resource, list) else [resource]
for obj in resources:
obj.save()
return resource | def save(self, request, resource=None, **kwargs) | Create a resource. | 3.957487 | 3.452198 | 1.146367 |
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')
... | async def delete(self, request, resource=None, **kwargs) | Delete a resource.
Supports batch delete. | 5.847957 | 5.808352 | 1.006819 |
def get_sub_accounts_of_account(self, account_id, recursive=None):
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
path["account_id"] = account_id
# OPTIONAL - recursive
if recursive is not None:
... | Get the sub-accounts of an account.
List accounts that are sub-accounts of the given account. | null | null | null | |
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):
path = {}
data = {}... | List active courses in an account.
Retrieve the list of courses in this account. | null | null | null | |
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):
path = {}
data = {}
params = {}
# REQUIRED - PATH - acc... | Create a new sub-account.
Add a new sub-account to a given account. | null | null | null | |
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) | Delete existing rows from a table. | 2.695671 | 2.589698 | 1.040921 |
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'},
... | 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.c... | 2.392583 | 2.299061 | 1.040678 |
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 ... | 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 w... | 2.101232 | 2.090044 | 1.005353 |
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... | 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.... | 2.671921 | 2.520197 | 1.060203 |
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_... | 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 ... | 3.125601 | 2.564482 | 1.218804 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.