code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
'''
The function aggreagtes all pre_stream, layout and post_stream and
components, and yields them one by one.
'''
# Yielding everything under pre_stream
for x in self._yield_all(self.pre_stream): yield x
# Yielding layout
for x in self._yield_all(self.la... | def _aggregate(self) | The function aggreagtes all pre_stream, layout and post_stream and
components, and yields them one by one. | 5.106057 | 3.150676 | 1.620623 |
if duration in ("0", "+0", "-0"):
return datetime.timedelta()
pattern = re.compile('([\d\.]+)([a-zµμ]+)')
total = 0
sign = -1 if duration[0] == '-' else 1
matches = pattern.findall(duration)
if not len(matches):
raise Exception("Invalid duration {}".format(duration))
... | def from_str(duration) | Parse a duration string to a datetime.timedelta | 2.947966 | 2.87287 | 1.02614 |
total_seconds = delta.total_seconds()
sign = "-" if total_seconds < 0 else ""
nanoseconds = abs(total_seconds * _second_size)
if total_seconds < 1:
result_str = _to_str_small(nanoseconds, extended)
else:
result_str = _to_str_large(nanoseconds, extended)
return "{}{}".form... | def to_str(delta, extended=False) | Format a datetime.timedelta to a duration string | 3.209027 | 3.25313 | 0.986443 |
try:
command = 'RENAME TABLE {0} TO {1}'.format(wrap(old_table), wrap(new_table))
except:
command = 'ALTER TABLE {0} RENAME {1}'.format(wrap(old_table), wrap(new_table))
self.execute(command)
self._printer('Renamed {0} to {1}'.format(wrap(old_table), wrap... | def rename(self, old_table, new_table) | Rename a table.
You must have ALTER and DROP privileges for the original table,
and CREATE and INSERT privileges for the new table. | 2.325771 | 2.417056 | 0.962233 |
statement = "CREATE DATABASE {0} DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci".format(wrap(name))
return self.execute(statement) | def create_database(self, name) | Create a new database. | 4.712768 | 4.398696 | 1.071401 |
# TODO: Issue occurs when bool values exist in data
# Remove if the table exists
if name in self.tables:
self.drop(name)
# Set headers list
if not columns:
columns = data[0]
# Validate data shape
for row in data:
asse... | def create_table(self, name, data, columns=None, add_pk=True) | Generate and execute a create table query by parsing a 2D dataset | 4.338584 | 4.268478 | 1.016424 |
''' Consulta o status do pagamento '''
url = u'{notification_url}{notification_code}?email={email}&token={token}'.format(
notification_url=self.notification_url,
notification_code=self.notification_code,
email=email,
token=token)
req = requ... | def _get_notification(self, email, token) | Consulta o status do pagamento | 3.926733 | 3.637775 | 1.079433 |
''' Lista dos items do pagamento
'''
if type(self.transaction['items']['item']) == list:
return self.transaction['items']['item']
else:
return [self.transaction['items']['item'],] | def items(self) | Lista dos items do pagamento | 5.767564 | 3.802273 | 1.516873 |
def create_single_poll(self, polls_question, polls_description=None):
path = {}
data = {}
params = {}
# REQUIRED - polls[question]
data["polls[question]"] = polls_question
# OPTIONAL - polls[description]
if polls_descriptio... | Create a single poll.
Create a new poll for the current user | null | null | null | |
host, port = address
err = None
for res in getaddrinfo(host, port, 0 if has_ipv6 else AF_INET, SOCK_STREAM):
af, socktype, proto, _canonname, sa = res
sock = None
try:
sock = socket(af, socktype, proto)
if timeout is not _GLOBAL_DEFAULT_TIMEOUT:
... | def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT, source_address=None) | Connect to *address* and return the socket object.
Convenience function. Connect to *address* (a 2-tuple ``(host,
port)``) and return the socket object. Passing the optional
*timeout* parameter will set the timeout on the socket instance
before attempting to connect. If no *timeout* is supplied, the... | 1.851356 | 1.954477 | 0.947239 |
if getattr(instance, "_index", True):
cls = instance.get_real_instance_class()
index = cls.search_objects.mapping.index
doc_type = cls.search_objects.mapping.doc_type
cls.search_objects.client.delete(index, doc_type, instance.id, ignore=[404]) | def content_deleted(sender, instance=None, **kwargs) | removes content from the ES index when deleted from DB | 4.209839 | 3.705557 | 1.136088 |
self.slug = slugify(self.name)[:50]
return super(Tag, self).save(*args, **kwargs) | def save(self, *args, **kwargs) | sets the `slug` values as the name
:param args: inline arguments (optional)
:param kwargs: keyword arguments (optional)
:return: `super.save()` | 3.627719 | 4.019337 | 0.902567 |
if self.slug is None or self.slug == "":
self.slug = slugify(self.name)
feature_type = super(FeatureType, self).save(*args, **kwargs)
if self.instant_article_is_dirty:
index_feature_type_content.delay(self.pk)
self._db_instant_article = self.instant_ar... | def save(self, *args, **kwargs) | sets the `slug` values as the name
:param args: inline arguments (optional)
:param kwargs: keyword arguments (optional)
:return: `super.save()` | 5.956812 | 6.047939 | 0.984933 |
# check if there is a valid thumbnail override
if self.thumbnail_override.id is not None:
return self.thumbnail_override
# otherwise, just try to grab the first image
first_image = self.first_image
if first_image is not None:
return first_image
... | def thumbnail(self) | Read-only attribute that provides the value of the thumbnail to display. | 6.2611 | 6.202799 | 1.009399 |
# loop through image fields and grab the first non-none one
for model_field in self._meta.fields:
if isinstance(model_field, ImageField):
if model_field.name is not 'thumbnail_override':
field_value = getattr(self, model_field.name)
... | def first_image(self) | Ready-only attribute that provides the value of the first non-none image that's
not the thumbnail override field. | 4.416122 | 3.048978 | 1.448394 |
try:
url = reverse("content-detail-view", kwargs={"pk": self.pk, "slug": self.slug})
except NoReverseMatch:
url = None
return url | def get_absolute_url(self) | produces a url to link directly to this instance, given the URL config
:return: `str` | 3.213792 | 3.596069 | 0.893696 |
if self.published:
now = timezone.now()
if now >= self.published:
return True
return False | def is_published(self) | determines if the content is/should be live
:return: `bool` | 3.924044 | 5.072 | 0.773668 |
tags = list(self.tags.all())
return sorted(
tags,
key=lambda tag: ((type(tag) != Tag) * 100000) + tag.count(),
reverse=True
) | def ordered_tags(self) | gets the related tags
:return: `list` of `Tag` instances | 4.601975 | 4.85861 | 0.947179 |
if not self.slug:
self.slug = slugify(self.build_slug())[:self._meta.get_field("slug").max_length]
if not self.is_indexed:
if kwargs is None:
kwargs = {}
kwargs["index"] = False
content = super(Content, self).save(*args, **kwargs)
... | def save(self, *args, **kwargs) | creates the slug, queues up for indexing and saves the instance
:param args: inline arguments (optional)
:param kwargs: keyword arguments
:return: `bulbs.content.Content` | 4.997084 | 4.610453 | 1.08386 |
# Elasticsearch v1.4 percolator range query does not support DateTime range queries
# (PercolateContext.nowInMillisImpl is not implemented). Once using
# v1.6+ we can instead compare "start_date/end_date" to python DateTime
now_epoch = datetime_to_epoch_seconds(timezone.now())
... | def percolate_special_coverage(self, max_size=10, sponsored_only=False) | gets list of active, sponsored special coverages containing this content via
Elasticsearch Percolator (see SpecialCoverage._save_percolator)
Sorting:
1) Manually added
2) Most recent start date | 5.287549 | 5.041684 | 1.048766 |
return self.create(
user=user,
content_type=ContentType.objects.get_for_model(content),
object_id=content.pk,
change_message=message
) | def log(self, user, content, message) | creates a new log record
:param user: user
:param content: content instance
:param message: change information | 2.990245 | 2.835483 | 1.05458 |
if not self.id: # this is a totally new instance, create uuid value
self.url_uuid = str(uuid.uuid4()).replace("-", "")
super(ObfuscatedUrlInfo, self).save(*args, **kwargs) | def save(self, *args, **kwargs) | sets uuid for url
:param args: inline arguments (optional)
:param kwargs: keyword arguments (optional)
:return: `super.save()` | 7.778442 | 7.475252 | 1.040559 |
path = "{0}/playlists".format(localdir)
if not os.path.exists(path):
os.makedirs(path)
filepath = "{0}/{1}".format(path, self.gen_filename())
playlist = open(filepath, "w")
for track in self.get_tracks():
playlist.write("{0}/{1}.mp3\n".format(
... | def write_playlist_file(self, localdir) | Check if playlist exists in local directory. | 2.799946 | 2.730748 | 1.02534 |
return filter(
lambda m: not m[0].startswith("__") and not inspect.isfunction(m[1]) and not inspect.ismethod(m[1]),
inspect.getmembers(self.__class__)
) | def getmembers(self) | :return: list of members as name, type tuples
:rtype: list | 2.526752 | 2.711575 | 0.931839 |
for attribute_name, type_instance in self.getmembers():
if isinstance(type_instance, DataType):
self._templates[attribute_name] = type_instance
value = None
if attribute_name in arguments:
value = arguments[attribute_name]... | def _create_instance_attributes(self, arguments) | Copies class level attribute templates and makes instance placeholders
This step is required for direct uses of Model classes. This creates a
copy of attribute_names ignores methods and private variables.
DataCollection types are deep copied to ignore memory reference conflicts.
DataTy... | 4.426129 | 3.83453 | 1.154282 |
_attribute_keys = list()
for attribute_name, type_instance in self.getmembers():
if isinstance(type_instance, DataType):
_attribute_keys.append(attribute_name)
return _attribute_keys | def get_attribute_keys(self) | Returns a list of managed attributes for the Model class
Implemented for use with data adapters, can be used to quickly make a list of the
attribute names in a prestans model | 4.862196 | 4.005858 | 1.213771 |
if self._required and (value is None or not isinstance(value, dict)):
raise exception.RequiredAttributeError()
if not self._required and not value:
return None
_model_instance = self.__class__()
rewrite_map = self.attribute_r... | def validate(self, value, attribute_filter=None, minified=False) | :param value: serializable input to validate
:type value: dict | None
:param attribute_filter:
:type: prestans.parser.AttributeFilter | None
:param minified: whether or not the input is minified
:type minified: bool
:return: the validated model
:rtype: Model | 3.149199 | 2.908394 | 1.082797 |
rewrite_map = dict()
token_rewrite_map = self.generate_attribute_token_rewrite_map()
for attribute_name, type_instance in self.getmembers():
if isinstance(type_instance, DataType):
attribute_tokens = attribute_name.split('_')
rewritten_att... | def attribute_rewrite_map(self) | Example: long_name -> a_b
:return: the rewrite map
:rtype: dict | 2.998815 | 2.956847 | 1.014194 |
from prestans.parser import AttributeFilter
from prestans.parser import AttributeFilterImmutable
from prestans.types import Array
model_dictionary = dict()
rewrite_map = self.attribute_rewrite_map()
# convert filter to immutable if it isn't already
if ... | def as_serializable(self, attribute_filter=None, minified=False) | Returns a dictionary with attributes and pure python representation of
the data instances. If an attribute filter is provided as_serializable
will respect the visibility.
The response is used by serializers to return data to client
:param attribute_filter:
:type attribute_filte... | 2.485231 | 2.370927 | 1.048211 |
def list_enrollments_courses(self, course_id, grading_period_id=None, include=None, role=None, sis_account_id=None, sis_course_id=None, sis_section_id=None, sis_user_id=None, state=None, type=None, user_id=None):
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_... | List enrollments.
Depending on the URL given, return either (1) all of the enrollments in
a course, (2) all of the enrollments in a section or (3) all of a user's
enrollments. This includes student, teacher, TA, and observer enrollments.
If a user has multiple enrollments... | null | null | null | |
def enroll_user_courses(self, course_id, enrollment_type, enrollment_user_id, enrollment_associated_user_id=None, enrollment_course_section_id=None, enrollment_enrollment_state=None, enrollment_limit_privileges_to_course_section=None, enrollment_notify=None, enrollment_role=None, enrollment_role_id=None, enrollment_sel... | Enroll a user.
Create a new user enrollment for a course or section. | null | null | null | |
def conclude_deactivate_or_delete_enrollment(self, id, course_id, task=None):
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
path["course_id"] = course_id
# REQUIRED - PATH - id
path["id"] = id
# O... | Conclude, deactivate, or delete an enrollment.
Conclude, deactivate, or delete an enrollment. If the +task+ argument isn't given, the enrollment
will be concluded. | null | null | null | |
filtered_interfaces = []
for interface in interfaces:
if interface.obj_type() == 'interface':
ixn_vlan = interface.get_object_by_type('vlan')
vlanEnable = is_true(ixn_vlan.get_attribute('vlanEnable'))
vlanCount = int(ixn_vlan.get_attribute('vlanCount'))
... | def filter_ints_based_on_vlan(interfaces, vlan, count=1) | Filter list of interfaces based on VLAN presence or absence criteria.
:param interfaces: list of interfaces to filter.
:param vlan: boolean indicating whether to filter interfaces with or without VLAN.
:param vlan: number of expected VLANs (note that when vlanEnable == False, vlanCount == 1)
:return: i... | 2.483982 | 2.24451 | 1.106693 |
attributes['enabled'] = True
if 'name' in self._data:
attributes['description'] = self._data['name']
obj_ref = self.api.add(self.obj_parent(), self.obj_type(), **attributes)
self.api.commit()
return self.api.remapIds(obj_ref) | def _create(self, **attributes) | Create new interface on IxNetwork.
Set enabled and description (==name).
:return: interface object reference. | 5.413452 | 4.659167 | 1.161893 |
column_names = list(column_names) if column_names else None
with self.connection.cursor() as cursor:
constraints = get_constraints(cursor, model._meta.db_table)
result = []
for name, infodict in constraints.items():
if column_names is None or column_names... | def _constraint_names(self, model, column_names=None, unique=None,
primary_key=None, index=None, foreign_key=None,
check=None) | Returns all constraint names matching the columns and conditions | 1.764973 | 1.740757 | 1.013911 |
return \
isinstance(self._element_template, Boolean) or \
isinstance(self._element_template, Float) or \
isinstance(self._element_template, Integer) or \
isinstance(self._element_template, String) | def is_scalar(self) | :return:
:rtype: bool | 3.734122 | 3.288035 | 1.13567 |
if not self._required and value is None:
return None
elif self._required and value is None:
raise exception.RequiredAttributeError()
_validated_value = self.__class__(
element_template=self._element_template,
min_length=self._min_length,... | def validate(self, value, attribute_filter=None, minified=False) | :param value:
:type value: list | None
:param attribute_filter:
:type attribute_filter: prestans.parser.AttributeFilter
:param minified:
:type minified: bool
:return: | 2.095173 | 2.101479 | 0.996999 |
@wraps(http_method_handler)
def secure_http_method_handler(self, *args, **kwargs):
if not self.__provider_config__.authentication:
_message = "Service available to authenticated users only, no auth context provider set in handler"
authentication_error = prestans.exception.... | def login_required(http_method_handler) | provides a decorator for RESTRequestHandler methods to check for authenticated users
RESTRequestHandler subclass must have a auth_context instance, refer to prestans.auth
for the parent class definition.
If decorator is used and no auth_context is provided the client will be denied access.
Handler wi... | 3.669507 | 3.177155 | 1.154966 |
def _role_required(http_method_handler):
@wraps(http_method_handler)
def secure_http_method_handler(self, *args, **kwargs):
# role name must be provided
if role_name is None:
_message = "Role name must be provided"
authorization_error =... | def role_required(role_name=None) | Authenticates a HTTP method handler based on a provided role
With a little help from Peter Cole's Blog
http://mrcoles.com/blog/3-decorator-examples-and-awesome-python/ | 3.000221 | 2.918112 | 1.028138 |
def _access_required(http_method_handler):
def secure_http_method_handler(self, *args, **kwargs):
# authentication context must be set
if not self.__provider_config__.authentication:
_message = "Service available to authenticated users only, no auth context pr... | def access_required(config=None) | Authenticates a HTTP method handler based on a custom set of arguments | 3.783108 | 3.695349 | 1.023748 |
output_dictionary = dict()
for key, value in iter(self._key_map.items()):
if isinstance(value, bool):
output_dictionary[key] = value
elif isinstance(value, self.__class__):
output_dictionary[key] = value.as_dict()
return output_d... | def as_dict(self) | turns attribute filter object into python dictionary | 3.398116 | 2.963475 | 1.146666 |
from autocmake.extract import extract_list
s = []
s.append("\n\ndef gen_cmake_command(options, arguments):")
s.append(' ')
s.append(" command = []")
for env in config['export']:
s.append(' command.append({0})'.format(env))
s.append(" command.append(arguments['--cm... | def gen_cmake_command(config) | Generate CMake command. | 2.677783 | 2.59618 | 1.031432 |
from autocmake.extract import extract_list
s = []
s.append('#!/usr/bin/env python')
s.append('\n{0}'.format(autogenerated_notice()))
s.append('\nimport os')
s.append('import sys')
s.append('assert sys.version_info >= (2, 6), \'Python >= 2.6 is required\'')
s.append("\nsys.path.ins... | def gen_setup(config, default_build_type, relative_path, setup_script_name) | Generate setup script. | 2.848559 | 2.823402 | 1.00891 |
import os
s = []
s.append(autogenerated_notice())
s.append('\n# set minimum cmake version')
s.append('cmake_minimum_required(VERSION {0} FATAL_ERROR)'.format(min_cmake_version))
s.append('\n# project name')
s.append('project({0} {1})'.format(project_name, project_language))
s.a... | def gen_cmakelists(project_name, project_language, min_cmake_version, default_build_type, relative_path, modules) | Generate CMakeLists.txt. | 3.031816 | 3.021958 | 1.003262 |
l = 0
for opt in options:
if len(opt[0]) > l:
l = len(opt[0])
s = []
for opt in options:
s.append(' {0}{1} {2}'.format(opt[0], ' ' * (l - len(opt[0])), opt[1]))
return '\n'.join(s) | def align_options(options) | Indents flags and aligns help texts. | 2.194583 | 2.048657 | 1.07123 |
rtn = ['Traceback (most recent call last):\n']
if limit is None or limit >= 0:
rtn.extend(traceback.format_tb(tback, limit))
else:
rtn.extend(traceback.format_list(traceback.extract_tb(tback)[limit:]))
rtn.extend(traceback.format_exception_only(etype, value))
return rtn | def format_exception(etype, value, tback, limit=None) | Python 2 compatible version of traceback.format_exception
Accepts negative limits like the Python 3 version | 2.143255 | 2.141261 | 1.000931 |
# If name is an entry point, try to parse it
epoint = None
if isinstance(name, EntryPoint):
epoint = name
name = epoint.module_name
if path is None:
try:
loader = pkgutil.get_loader(name)
except ImportError:
pass
else:
if... | def _import_module(name, path=None) | Args:
name(str):
* Full name of object
* name can also be an EntryPoint object, name and path will be determined dynamically
path(str): Module directory
Returns:
object: module object or advertised object for EntryPoint
Loads a module using importlib catching ex... | 3.365064 | 3.197253 | 1.052486 |
prefix = '%s.' % (package.__name__)
path = getattr(package, '__path__', None)
if path:
for submod in pkgutil.walk_packages(path, prefix=prefix):
_import_module(submod[1], submod[0].path) | def _recursive_import(package) | Args:
package(py:term:`package`): Package to walk
Import all modules from a package recursively | 4.265124 | 4.593081 | 0.928598 |
# Start with standard library
if self.library:
LOGGER.info('Loading plugins from standard library')
libmod = _import_module(self.library)
_recursive_import(libmod)
# Get entry points
if self.entry_point:
LOGGER.info('Loading plug... | def load_modules(self) | Locate and import modules from locations specified during initialization.
Locations include:
- Program's standard library (``library``)
- `Entry points <Entry point_>`_ (``entry_point``)
- Specified modules (``modules``)
- Specified paths (``paths``)
If ... | 3.174279 | 2.834949 | 1.119695 |
if not self.loaded:
self.load_modules()
# pylint: disable=protected-access
return get_plugins()[self.group]._filter(blacklist=self.blacklist, newest_only=True,
type_filter=self.type_filter) | def plugins(self) | Newest version of all plugins in the group filtered by ``blacklist``
Returns:
dict: Nested dictionary of plugins accessible through dot-notation.
Plugins are returned in a nested dictionary, but can also be accessed through dot-notion.
Just as when accessing an undefined dictionary... | 9.653489 | 6.870848 | 1.404992 |
if not self.loaded:
self.load_modules()
# pylint: disable=protected-access
return get_plugins()[self.group]._filter(blacklist=self.blacklist,
type_filter=self.type_filter) | def plugins_all(self) | All resulting versions of all plugins in the group filtered by ``blacklist``
Returns:
dict: Nested dictionary of plugins accessible through dot-notation.
Similar to :py:attr:`plugins`, but lowest level is a regular dictionary of
all unfiltered plugin versions for the given plugin t... | 8.310459 | 6.35046 | 1.308639 |
if not self.loaded:
self.load_modules()
# pylint: disable=protected-access
return get_plugins()[self.group]._filter(blacklist=self.blacklist,
newest_only=True,
type_filter=sel... | def get_plugin(self, plugin_type, name, version=None) | Args:
plugin_type(str): Parent type
name(str): Plugin name
version(str): Plugin version
Returns:
:py:class:`Plugin`: Plugin, or :py:data:`None` if plugin can't be found
Retrieve a specific plugin. ``blacklist`` and ``type_filter`` still apply.
I... | 6.124197 | 5.018936 | 1.220218 |
# Rows that exist in the table
existing_rows = self.select(table, columns)
# Rows that DO NOT exist in the table
unique = diff(existing_rows, values, y_only=True) # Get values that are not in existing_rows
# Keys that exist in the table
keys = self.get_primary... | def insert_uniques(self, table, columns, values) | Insert multiple rows into a table that do not already exist.
If the rows primary key already exists, the rows values will be updated.
If the rows primary key does not exists, a new row will be inserted | 2.996831 | 2.989358 | 1.0025 |
# TODO: Cant accept lists?
# Concatenate statement
cols, vals = get_col_val_str(columns)
statement = "INSERT INTO {0} ({1}) VALUES ({2})".format(wrap(table), cols, vals)
# Execute statement
if execute:
self._cursor.execute(statement, values)
... | def insert(self, table, columns, values, execute=True) | Insert a single row into a table. | 5.917468 | 5.790592 | 1.021911 |
# Make values a list of lists if it is a flat list
if not isinstance(values[0], (list, set, tuple)):
values = []
for v in values:
if v is not None and len(v) > 0:
values.append([v])
else:
values.appe... | def insert_many(self, table, columns, values, limit=MAX_ROWS_PER_QUERY, execute=True) | Insert multiple rows into a table.
If only one row is found, self.insert method will be used. | 3.441664 | 3.500069 | 0.983313 |
def list_quizzes_in_course(self, course_id, search_term=None):
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
path["course_id"] = course_id
# OPTIONAL - search_term
if search_term is not None:
pa... | List quizzes in a course.
Returns the list of Quizzes in this course. | null | null | null | |
def validate_quiz_access_code(self, id, course_id, access_code):
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
path["course_id"] = course_id
# REQUIRED - PATH - id
path["id"] = id
# REQUIRED - acc... | Validate quiz access code.
Accepts an access code and returns a boolean indicating whether that access code is correct | null | null | null | |
self.not_empty.acquire()
try:
if not block:
if not self._qsize():
raise Empty
elif timeout is None:
while not self._qsize():
self.not_empty.wait()
elif timeout < 0:
raise ... | def get(self, block=True, timeout=None) | Remove and return an item from the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until an item is available. If 'timeout' is
a positive number, it blocks at most 'timeout' seconds and raises
the Empty exception if no item was available w... | 1.918267 | 1.672009 | 1.147283 |
m = _load_case_module(case, config)
result = m.run(case, config)
summary[case] = _summarize_result(m, result)
_print_summary(m, case, summary)
if result['Type'] == 'Book':
for name, page in six.iteritems(result['Data']):
functions.create_page_from_template("validation.h... | def run_suite(case, config, summary) | Run the full suite of validation tests | 3.487181 | 3.426347 | 1.017755 |
distro_name = '{}/{}.tar.bz2'.format(conda.config.subdir, meta.dist())
try:
dist_info = cli.distribution(owner, meta.name(), meta.version(), distro_name)
except binstar_client.errors.NotFound:
dist_info = {}
return bool(dist_info) | def artifact_already_exists(cli, meta, owner) | Checks to see whether the built recipe (aka distribution) already
exists on the owner/user's binstar account. | 5.268654 | 4.508092 | 1.16871 |
gen_parser = self._subparsers_handle.add_parser(
name="gen",
help="generate client side model stubs, filters"
)
gen_parser.add_argument(
"-t",
"--template",
choices=['closure.model', 'closure.filter'],
default... | def _add_generate_sub_commands(self) | Sub commands for generating models for usage by clients.
Currently supports Google Closure. | 2.900176 | 2.756335 | 1.052186 |
if not os.path.isdir(self._args.output):
raise exception.Base("%s is not a writeable directory" % self._args.output)
if not os.path.isfile(self._args.models_definition):
if not self.check_package_exists(self._args.models_definition):
raise exception.Bas... | def _dispatch_gen(self) | Process the generate subset of commands. | 4.12161 | 3.941939 | 1.045579 |
# Retrieve all Or filters pertinent to the special coverage query.
should_filters = [
es_filter.Terms(pk=self.query.get("included_ids", [])),
es_filter.Terms(pk=self.query.get("pinned_ids", []))
]
should_filters += self.get_group_filters()
# Comp... | def search(self) | Return a search using the combined query of all associated special coverage objects. | 6.488183 | 5.572171 | 1.164391 |
group_filters = []
field_map = {
"feature-type": "feature_type.slug",
"tag": "tags.slug",
"content-type": "_type"
}
for group_set in self.query.get("groups", []):
for group in group_set:
group_filter = es_filter.Mat... | def get_group_filters(self) | Return es OR filters to include all special coverage group conditions. | 3.687954 | 3.261558 | 1.130734 |
if not self._query:
self._query.update({
"excluded_ids": [],
"included_ids": [],
"pinned_ids": [],
"groups": [],
})
for special_coverage in self._special_coverages:
# Access query at dict... | def query(self) | Group the self.special_coverages queries and memoize them. | 3.096936 | 2.489522 | 1.243988 |
def set_extensions_for_student_quiz_submissions(self, user_id, course_id, extend_from_end_at=None, extend_from_now=None, extra_attempts=None, extra_time=None, manually_unlocked=None):
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
path["c... | Set extensions for student quiz submissions.
<b>Responses</b>
* <b>200 OK</b> if the request was successful
* <b>403 Forbidden</b> if you are not allowed to extend quizzes for this course | null | null | null | |
rnftools.mishmash.Source.recode_sam_reads(
sam_fn=args.sam_fn,
fastq_rnf_fo=args.fq_fo,
fai_fo=args.fai_fo,
genome_id=args.genome_id,
number_of_read_tuples=10**9,
simulator_name=args.simulator_name,
allow_unmapped=args.allow_unmapped,
) | def sam2rnf(args) | Convert SAM to RNF-based FASTQ with respect to argparse parameters.
Args:
args (...): Arguments parsed by argparse | 6.789996 | 7.855474 | 0.864365 |
parser_sam2rnf = subparsers.add_parser(subcommand, help=help, description=description)
parser_sam2rnf.set_defaults(func=sam2rnf)
parser_sam2rnf.add_argument(
'-s', '--sam', type=str, metavar='file', dest='sam_fn', required=True,
help='Input SAM/BAM with true (expected) alignments of ... | def add_sam2rnf_parser(subparsers, subcommand, help, description, simulator_name=None) | Add another parser for a SAM2RNF-like command.
Args:
subparsers (subparsers): File name of the genome from which read tuples are created (FASTA file).
simulator_name (str): Name of the simulator used in comments. | 3.256715 | 3.415172 | 0.953602 |
affiliate = self.create(**kwargs)
self.api.affiliate_users.create(affiliate_id=affiliate.id, **user_params)
return affiliate | def create_with_user(self, user_params, **kwargs) | Creates an affiliate and corresponding affiliate user
:param user_params: kwargs for user creation
:param kwargs:
:return: affiliate instance | 3.801131 | 3.273389 | 1.161222 |
def list_roles(self, account_id, show_inherited=None, state=None):
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
path["account_id"] = account_id
# OPTIONAL - state
if state is not None:
self._v... | List roles.
List the roles available to an account. | null | null | null | |
def get_single_role(self, id, role_id, account_id, role=None):
path = {}
data = {}
params = {}
# REQUIRED - PATH - id
path["id"] = id
# REQUIRED - PATH - account_id
path["account_id"] = account_id
# REQUIRED - ro... | Get a single role.
Retrieve information about a single role | null | null | null | |
ss = Execute(sql_script, split_algo, prep_statements, dump_fails, self)
ss.execute(commands, ignored_commands=ignored_commands, execute_fails=execute_fails) | def execute_script(self, sql_script=None, commands=None, split_algo='sql_split', prep_statements=False,
dump_fails=True, execute_fails=True, ignored_commands=('DROP', 'UNLOCK', 'LOCK')) | Wrapper method for SQLScript class. | 4.103273 | 4.029899 | 1.018207 |
return Execute(sql_script, split_algo, prep_statements, dump_fails, self) | def script(self, sql_script, split_algo='sql_split', prep_statements=True, dump_fails=True) | Wrapper method providing access to the SQLScript class's methods and properties. | 4.7128 | 5.201875 | 0.905981 |
url = urljoin(self.base_url, self.auth_url)
params = {
'response_type': 'code',
'client_id': self.client_id,
'redirect_uri': self.redirect_url,
'scope': ' '.join(scope),
'state': state if state is not None else self._generate_state(),
... | def authorize_url(self, scope: list, state: str = None) -> tuple | Returns the URL to which the user can be redirected to authorize your application to access his/her account. It
will also return the state which can be used for CSRF protection. A state is generated if not passed to this
method.
Example:
>>> auth = OAuthAuthentication('https://examp... | 2.148947 | 2.168697 | 0.990893 |
url_data = parse_qs(redirect_url.split('?', 1)[1])
if 'error' in url_data:
logger.warning("Error received in OAuth authentication response: %s" % url_data.get('error'))
raise OAuthAuthentication.OAuthError(url_data['error'], url_data.get('error_description', None))
... | def obtain_token(self, redirect_url: str, state: str) -> str | Exchange the code that was obtained using `authorize_url` for an authorization token. The code is extracted
from the URL that redirected the user back to your site.
Example:
>>> auth = OAuthAuthentication('https://example.com/oauth/moneybird/', 'your_id', 'your_secret')
>>> auth... | 2.248348 | 2.280173 | 0.986043 |
state = str(uuid.uuid4()).replace('-', '')
logger.debug("Generated OAuth state: %s" % state)
return state | def _generate_state() -> str | Generates a new random string to be used as OAuth state.
:return: A randomly generated OAuth state. | 5.584224 | 4.200861 | 1.329305 |
# Collect list of type, length tuples
type_len_pairs = [ValueType(record).get_type_len for record in column_data]
# Retrieve frequency counts of each type
types_count = {t: type_len_pairs.count(t) for t in set([type_ for type_, len_, len_dec in type_len_pairs])}
# Most frequently occurring da... | def sql_column_type(column_data, prefer_varchar=False, prefer_int=False) | Retrieve the best fit data type for a column of a MySQL table.
Accepts a iterable of values ONLY for the column whose data type
is in question.
:param column_data: Iterable of values from a MySQL table column
:param prefer_varchar: Use type VARCHAR if valid
:param prefer_int: Use type INT if valid... | 2.877196 | 2.912488 | 0.987883 |
test_method = [
self.is_time,
self.is_date,
self.is_datetime,
self.is_decimal,
self.is_year,
self.is_tinyint,
self.is_smallint,
self.is_mediumint,
self.is_int,
self.is_bigint,
... | def get_sql(self) | Retrieve the data type for a data record. | 2.688136 | 2.381959 | 1.12854 |
# Check types and set type/len
self.get_sql()
return self.type, self.len, self.len_decimal | def get_type_len(self) | Retrieve the type and length for a data record. | 16.217009 | 16.800362 | 0.965277 |
def create_course_section(self, course_id, course_section_end_at=None, course_section_name=None, course_section_restrict_enrollments_to_section_dates=None, course_section_sis_section_id=None, course_section_start_at=None, enable_sis_reactivation=None):
path = {}
data = {}
params = {... | Create course section.
Creates a new section for this course. | null | null | null | |
def cross_list_section(self, id, new_course_id):
path = {}
data = {}
params = {}
# REQUIRED - PATH - id
path["id"] = id
# REQUIRED - PATH - new_course_id
path["new_course_id"] = new_course_id
self.logger.debug("P... | Cross-list a Section.
Move the Section to another course. The new course may be in a different account (department),
but must belong to the same root account (institution). | null | null | null | |
def edit_section(self, id, course_section_end_at=None, course_section_name=None, course_section_restrict_enrollments_to_section_dates=None, course_section_sis_section_id=None, course_section_start_at=None):
path = {}
data = {}
params = {}
# REQUIRED - PATH - id
... | Edit a section.
Modify an existing section. | null | null | null | |
# Get original config and change database key
config = self._config
config['database'] = db
if user:
config['user'] = user
self.database = db
# Close current database connection
self._disconnect()
# Reconnect to the new database
... | def change_db(self, db, user=None) | Change connect database. | 5.026827 | 4.744698 | 1.059462 |
self._cursor.execute(command)
self._commit()
return True | def execute(self, command) | Execute a single SQL query without returning a result. | 6.209014 | 5.396687 | 1.150523 |
attempts = 0
while attempts < max_attempts:
try:
# Execute statement
self._cursor.executemany(command, params)
self._commit()
return True
except Exception as e:
attempts += 1
... | def executemany(self, command, params=None, max_attempts=5) | Execute multiple SQL queries without returning a result. | 2.8366 | 2.833089 | 1.001239 |
if 'connection_timeout' not in self._config:
self._config['connection_timeout'] = 480
try:
self._cnx = connect(**config)
self._cursor = self._cnx.cursor()
self._printer('\tMySQL DB connection established with db', config['database'])
excep... | def _connect(self, config) | Establish a connection with a MySQL database. | 2.879484 | 2.699038 | 1.066856 |
if self._auto_reconnect:
attempts = 0
while attempts < max_attempts:
try:
# Execute statement
self._cursor.execute(statement)
fetch = self._cursor.fetchall()
rows = self._fetch_rows(f... | def _fetch(self, statement, commit, max_attempts=5) | Execute a SQL query and return a result.
Recursively disconnect and reconnect to the database
if an error occurs. | 2.06109 | 2.017146 | 1.021786 |
glEnable(GL_BLEND)
glEnable(GL_POINT_SMOOTH)
glShadeModel(GL_SMOOTH)# Enables Smooth Shading
glBlendFunc(GL_SRC_ALPHA,GL_ONE)#Type Of Blending To Perform
glHint(GL_PERSPECTIVE_CORRECTION_HINT,GL_NICEST);#Really Nice Perspective Calculations
glHint(GL_POINT_SMOOTH_HINT,GL_NICEST);#Really Nice Point Smoothing
gl... | def resize(widthWindow, heightWindow) | Initial settings for the OpenGL state machine, clear color, window size, etc | 2.652957 | 2.491983 | 1.064596 |
self.color = tuple(particle.color)[:3] | def set_bumper_color(self, particle, group, bumper, collision_point, collision_normal) | Set bumper color to the color of the particle that collided with it | 11.098062 | 10.607125 | 1.046284 |
if type(rabaClass) is types.StringType :
self._raba_namespace = namespace
self.con = stp.RabaConnection(self._raba_namespace)
self.rabaClass = self.con.getClass(rabaClass)
else :
self.rabaClass = rabaClass
self._raba_namespace = self.rabaClass._raba_namespace
self.con = stp.RabaConnection(self... | def reset(self, rabaClass, namespace = None) | rabaClass can either be a raba class of a string of a raba class name. In the latter case you must provide the namespace argument.
If it's a Raba Class the argument is ignored. If you fear cicular imports use strings | 3.325485 | 3.267317 | 1.017803 |
"add a new filter to the query"
dstF = {}
if len(lstFilters) > 0 :
if type(lstFilters[0]) is types.DictType :
dstF = lstFilters[0]
lstFilters = lstFilters[1:]
if len(dctFilters) > 0 :
dstF = dict(dstF, **dctFilters)
filts = {}
for k, v in dstF.iteritems() :
sk = k.split(' ')
if len(sk... | def addFilter(self, *lstFilters, **dctFilters) | add a new filter to the query | 2.972287 | 2.908355 | 1.021982 |
"Returns the query without performing it. If count, the query returned will be a SELECT COUNT() instead of a SELECT"
sqlFilters = []
sqlValues = []
# print self.filters
for f in self.filters :
filt = []
for k, vv in f.iteritems() :
if type(vv) is types.ListType or type(vv) is types.TupleType :
... | def getSQLQuery(self, count = False) | Returns the query without performing it. If count, the query returned will be a SELECT COUNT() instead of a SELECT | 3.734161 | 3.265744 | 1.143433 |
sql, sqlValues = self.getSQLQuery()
cur = self.con.execute('%s %s'% (sql, sqlTail), sqlValues)
for v in cur :
if not raw :
yield RabaPupa(self.rabaClass, v[0])
else :
yield v | def iterRun(self, sqlTail = '', raw = False) | Compile filters and run the query and returns an iterator. This much more efficient for large data sets but
you get the results one element at a time. One thing to keep in mind is that this function keeps the cursor open, that means that the sqlite databae is locked (no updates/inserts etc...) until all
the element... | 7.35841 | 5.183561 | 1.419566 |
sql, sqlValues = self.getSQLQuery()
cur = self.con.execute('%s %s'% (sql, sqlTail), sqlValues)
res = []
for v in cur :
if not raw :
res.append(RabaPupa(self.rabaClass, v[0]))
else :
return v
return res | def run(self, sqlTail = '', raw = False) | Compile filters and run the query and returns the entire result. You can use sqlTail to add things such as order by. If raw, returns the raw tuple data (not wrapped into a raba object) | 6.820302 | 5.109422 | 1.334848 |
"Compile filters and counts the number of results. You can use sqlTail to add things such as order by"
sql, sqlValues = self.getSQLQuery(count = True)
return int(self.con.execute('%s %s'% (sql, sqlTail), sqlValues).fetchone()[0]) | def count(self, sqlTail = '') | Compile filters and counts the number of results. You can use sqlTail to add things such as order by | 9.255057 | 4.521776 | 2.046775 |
sql = "SELECT %s.raba_id FROM %s WHERE %s" % (self.rabaClass.__name__, self.rabaClass.__name__, whereAndTail)
cur = self.con.execute(sql, params)
res = []
for v in cur :
if not raw :
res.append(RabaPupa(self.rabaClass, v[0]))
else :
return v
return res | def runWhere(self, whereAndTail, params = (), raw = False) | You get to write your own where + tail clauses. If raw, returns the raw tuple data (not wrapped into a raba object).If raw, returns the raw tuple data (not wrapped into a raba object) | 3.69646 | 3.017158 | 1.225146 |
tables = tables if tables else self.tables
for t in tables:
self._printer('\t{0}'.format(t))
for col in self.get_schema(t, True):
self._printer('\t\t{0:30} {1:15} {2:10} {3:10} {4:10} {5:10}'.format(*col)) | def show_schema(self, tables=None) | Print schema information. | 2.763202 | 2.545567 | 1.085496 |
# Retrieve schema in list form
schema = self.get_schema(table, with_headers=True)
# Pop headers from first item in list
headers = schema.pop(0)
# Create dictionary by zipping headers with each row
return {values[0]: dict(zip(headers, values[0:])) for values in ... | def get_schema_dict(self, table) | Retrieve the database schema in key, value pairs for easier
references and comparisons. | 6.614294 | 6.284975 | 1.052398 |
f = self.fetch('desc ' + wrap(table))
if not isinstance(f[0], list):
f = [f]
# Replace None with ''
schema = [['' if col is None else col for col in row] for row in f]
# If with_headers is True, insert headers to first row before returning
if with_h... | def get_schema(self, table, with_headers=False) | Retrieve the database schema for a particular table. | 3.837245 | 3.587573 | 1.069594 |
location = 'AFTER {0}'.format(after_col) if after_col else 'FIRST'
null_ = 'NULL' if null else 'NOT NULL'
comment = "COMMENT 'Column auto created by mysql-toolkit'"
pk = 'AUTO_INCREMENT PRIMARY KEY {0}'.format(comment) if primary_key else ''
query = 'ALTER TABLE {0} ADD ... | def add_column(self, table, name='ID', data_type='int(11)', after_col=None, null=False, primary_key=False) | Add a column to an existing table. | 3.717066 | 3.704463 | 1.003402 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.