repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
gamechanger/avro_codec | avro_codec/__init__.py | AvroCodec.dumps | def dumps(self, obj):
"""
Serializes obj to an avro-format byte array and returns it.
"""
out = BytesIO()
try:
self.dump(obj, out)
return out.getvalue()
finally:
out.close() | python | def dumps(self, obj):
"""
Serializes obj to an avro-format byte array and returns it.
"""
out = BytesIO()
try:
self.dump(obj, out)
return out.getvalue()
finally:
out.close() | [
"def",
"dumps",
"(",
"self",
",",
"obj",
")",
":",
"out",
"=",
"BytesIO",
"(",
")",
"try",
":",
"self",
".",
"dump",
"(",
"obj",
",",
"out",
")",
"return",
"out",
".",
"getvalue",
"(",
")",
"finally",
":",
"out",
".",
"close",
"(",
")"
] | Serializes obj to an avro-format byte array and returns it. | [
"Serializes",
"obj",
"to",
"an",
"avro",
"-",
"format",
"byte",
"array",
"and",
"returns",
"it",
"."
] | 57468bee8972a26b31b16a3437b3eeaa5ace2af6 | https://github.com/gamechanger/avro_codec/blob/57468bee8972a26b31b16a3437b3eeaa5ace2af6/avro_codec/__init__.py#L23-L32 | train |
gamechanger/avro_codec | avro_codec/__init__.py | AvroCodec.loads | def loads(self, data):
"""
Deserializes the given byte array into an object and returns it.
"""
st = BytesIO(data)
try:
return self.load(st)
finally:
st.close() | python | def loads(self, data):
"""
Deserializes the given byte array into an object and returns it.
"""
st = BytesIO(data)
try:
return self.load(st)
finally:
st.close() | [
"def",
"loads",
"(",
"self",
",",
"data",
")",
":",
"st",
"=",
"BytesIO",
"(",
"data",
")",
"try",
":",
"return",
"self",
".",
"load",
"(",
"st",
")",
"finally",
":",
"st",
".",
"close",
"(",
")"
] | Deserializes the given byte array into an object and returns it. | [
"Deserializes",
"the",
"given",
"byte",
"array",
"into",
"an",
"object",
"and",
"returns",
"it",
"."
] | 57468bee8972a26b31b16a3437b3eeaa5ace2af6 | https://github.com/gamechanger/avro_codec/blob/57468bee8972a26b31b16a3437b3eeaa5ace2af6/avro_codec/__init__.py#L41-L49 | train |
inveniosoftware/invenio-pidrelations | invenio_pidrelations/models.py | PIDRelation.create | def create(cls, parent, child, relation_type, index=None):
"""Create a PID relation for given parent and child."""
try:
with db.session.begin_nested():
obj = cls(parent_id=parent.id,
child_id=child.id,
relation_type=relation... | python | def create(cls, parent, child, relation_type, index=None):
"""Create a PID relation for given parent and child."""
try:
with db.session.begin_nested():
obj = cls(parent_id=parent.id,
child_id=child.id,
relation_type=relation... | [
"def",
"create",
"(",
"cls",
",",
"parent",
",",
"child",
",",
"relation_type",
",",
"index",
"=",
"None",
")",
":",
"try",
":",
"with",
"db",
".",
"session",
".",
"begin_nested",
"(",
")",
":",
"obj",
"=",
"cls",
"(",
"parent_id",
"=",
"parent",
"... | Create a PID relation for given parent and child. | [
"Create",
"a",
"PID",
"relation",
"for",
"given",
"parent",
"and",
"child",
"."
] | a49f3725cf595b663c5b04814280b231f88bc333 | https://github.com/inveniosoftware/invenio-pidrelations/blob/a49f3725cf595b663c5b04814280b231f88bc333/invenio_pidrelations/models.py#L106-L122 | train |
inveniosoftware/invenio-pidrelations | invenio_pidrelations/models.py | PIDRelation.relation_exists | def relation_exists(self, parent, child, relation_type):
"""Determine if given relation already exists."""
return PIDRelation.query.filter_by(
child_pid_id=child.id,
parent_pid_id=parent.id,
relation_type=relation_type).count() > 0 | python | def relation_exists(self, parent, child, relation_type):
"""Determine if given relation already exists."""
return PIDRelation.query.filter_by(
child_pid_id=child.id,
parent_pid_id=parent.id,
relation_type=relation_type).count() > 0 | [
"def",
"relation_exists",
"(",
"self",
",",
"parent",
",",
"child",
",",
"relation_type",
")",
":",
"return",
"PIDRelation",
".",
"query",
".",
"filter_by",
"(",
"child_pid_id",
"=",
"child",
".",
"id",
",",
"parent_pid_id",
"=",
"parent",
".",
"id",
",",
... | Determine if given relation already exists. | [
"Determine",
"if",
"given",
"relation",
"already",
"exists",
"."
] | a49f3725cf595b663c5b04814280b231f88bc333 | https://github.com/inveniosoftware/invenio-pidrelations/blob/a49f3725cf595b663c5b04814280b231f88bc333/invenio_pidrelations/models.py#L125-L130 | train |
Kortemme-Lab/klab | klab/fs/stats.py | df | def df(unit = 'GB'):
'''A wrapper for the df shell command.'''
details = {}
headers = ['Filesystem', 'Type', 'Size', 'Used', 'Available', 'Capacity', 'MountedOn']
n = len(headers)
unit = df_conversions[unit]
p = subprocess.Popen(args = ['df', '-TP'], stdout = subprocess.PIPE) # -P prevents line... | python | def df(unit = 'GB'):
'''A wrapper for the df shell command.'''
details = {}
headers = ['Filesystem', 'Type', 'Size', 'Used', 'Available', 'Capacity', 'MountedOn']
n = len(headers)
unit = df_conversions[unit]
p = subprocess.Popen(args = ['df', '-TP'], stdout = subprocess.PIPE) # -P prevents line... | [
"def",
"df",
"(",
"unit",
"=",
"'GB'",
")",
":",
"details",
"=",
"{",
"}",
"headers",
"=",
"[",
"'Filesystem'",
",",
"'Type'",
",",
"'Size'",
",",
"'Used'",
",",
"'Available'",
",",
"'Capacity'",
",",
"'MountedOn'",
"]",
"n",
"=",
"len",
"(",
"header... | A wrapper for the df shell command. | [
"A",
"wrapper",
"for",
"the",
"df",
"shell",
"command",
"."
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/fs/stats.py#L26-L69 | train |
joe513/django-cool-pagination | django_cool_paginator/templatetags/paginator_tags.py | url_replace | def url_replace(context, field, value):
"""
To avoid GET params losing
:param context: context_obj
:param field: str
:param value: str
:return: dict-like object
"""
query_string = context['request'].GET.copy()
query_string[field] = value
return query_string.urlencode() | python | def url_replace(context, field, value):
"""
To avoid GET params losing
:param context: context_obj
:param field: str
:param value: str
:return: dict-like object
"""
query_string = context['request'].GET.copy()
query_string[field] = value
return query_string.urlencode() | [
"def",
"url_replace",
"(",
"context",
",",
"field",
",",
"value",
")",
":",
"query_string",
"=",
"context",
"[",
"'request'",
"]",
".",
"GET",
".",
"copy",
"(",
")",
"query_string",
"[",
"field",
"]",
"=",
"value",
"return",
"query_string",
".",
"urlenco... | To avoid GET params losing
:param context: context_obj
:param field: str
:param value: str
:return: dict-like object | [
"To",
"avoid",
"GET",
"params",
"losing"
] | ed75a151a016aef0f5216fdb1e3610597872a3ef | https://github.com/joe513/django-cool-pagination/blob/ed75a151a016aef0f5216fdb1e3610597872a3ef/django_cool_paginator/templatetags/paginator_tags.py#L57-L70 | train |
joe513/django-cool-pagination | django_cool_paginator/templatetags/paginator_tags.py | ellipsis_or_number | def ellipsis_or_number(context, paginator, current_page):
"""
To avoid display a long pagination bar
:param context: template context
:param paginator: paginator_obj
:param current_page: int
:return: str or None
"""
# Checks is it first page
chosen_page = int(context['request'].GET... | python | def ellipsis_or_number(context, paginator, current_page):
"""
To avoid display a long pagination bar
:param context: template context
:param paginator: paginator_obj
:param current_page: int
:return: str or None
"""
# Checks is it first page
chosen_page = int(context['request'].GET... | [
"def",
"ellipsis_or_number",
"(",
"context",
",",
"paginator",
",",
"current_page",
")",
":",
"chosen_page",
"=",
"int",
"(",
"context",
"[",
"'request'",
"]",
".",
"GET",
"[",
"'page'",
"]",
")",
"if",
"'page'",
"in",
"context",
"[",
"'request'",
"]",
"... | To avoid display a long pagination bar
:param context: template context
:param paginator: paginator_obj
:param current_page: int
:return: str or None | [
"To",
"avoid",
"display",
"a",
"long",
"pagination",
"bar"
] | ed75a151a016aef0f5216fdb1e3610597872a3ef | https://github.com/joe513/django-cool-pagination/blob/ed75a151a016aef0f5216fdb1e3610597872a3ef/django_cool_paginator/templatetags/paginator_tags.py#L75-L93 | train |
adaptive-learning/proso-apps | proso_tasks/models.py | create_items | def create_items(sender, instance, **kwargs):
"""
When one of the defined objects is created, initialize also its item.
"""
if instance.item_id is None and instance.item is None:
item = Item()
if hasattr(instance, 'active'):
item.active = getattr(instance, 'active')
i... | python | def create_items(sender, instance, **kwargs):
"""
When one of the defined objects is created, initialize also its item.
"""
if instance.item_id is None and instance.item is None:
item = Item()
if hasattr(instance, 'active'):
item.active = getattr(instance, 'active')
i... | [
"def",
"create_items",
"(",
"sender",
",",
"instance",
",",
"**",
"kwargs",
")",
":",
"if",
"instance",
".",
"item_id",
"is",
"None",
"and",
"instance",
".",
"item",
"is",
"None",
":",
"item",
"=",
"Item",
"(",
")",
"if",
"hasattr",
"(",
"instance",
... | When one of the defined objects is created, initialize also its item. | [
"When",
"one",
"of",
"the",
"defined",
"objects",
"is",
"created",
"initialize",
"also",
"its",
"item",
"."
] | 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_tasks/models.py#L196-L205 | train |
adaptive-learning/proso-apps | proso_tasks/models.py | add_parent | def add_parent(sender, instance, **kwargs):
"""
When a task instance is created, create also an item relation.
"""
if not kwargs['created']:
return
for att in ['task', 'context']:
parent = getattr(instance, att).item_id
child = instance.item_id
ItemRelation.objects.ge... | python | def add_parent(sender, instance, **kwargs):
"""
When a task instance is created, create also an item relation.
"""
if not kwargs['created']:
return
for att in ['task', 'context']:
parent = getattr(instance, att).item_id
child = instance.item_id
ItemRelation.objects.ge... | [
"def",
"add_parent",
"(",
"sender",
",",
"instance",
",",
"**",
"kwargs",
")",
":",
"if",
"not",
"kwargs",
"[",
"'created'",
"]",
":",
"return",
"for",
"att",
"in",
"[",
"'task'",
",",
"'context'",
"]",
":",
"parent",
"=",
"getattr",
"(",
"instance",
... | When a task instance is created, create also an item relation. | [
"When",
"a",
"task",
"instance",
"is",
"created",
"create",
"also",
"an",
"item",
"relation",
"."
] | 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_tasks/models.py#L221-L234 | train |
adaptive-learning/proso-apps | proso_tasks/models.py | change_parent | def change_parent(sender, instance, **kwargs):
"""
When the given task instance has changed. Look at task and context and change
the corresponding item relation.
"""
if instance.id is None:
return
if len({'task', 'task_id'} & set(instance.changed_fields)) != 0:
diff = instance.di... | python | def change_parent(sender, instance, **kwargs):
"""
When the given task instance has changed. Look at task and context and change
the corresponding item relation.
"""
if instance.id is None:
return
if len({'task', 'task_id'} & set(instance.changed_fields)) != 0:
diff = instance.di... | [
"def",
"change_parent",
"(",
"sender",
",",
"instance",
",",
"**",
"kwargs",
")",
":",
"if",
"instance",
".",
"id",
"is",
"None",
":",
"return",
"if",
"len",
"(",
"{",
"'task'",
",",
"'task_id'",
"}",
"&",
"set",
"(",
"instance",
".",
"changed_fields",... | When the given task instance has changed. Look at task and context and change
the corresponding item relation. | [
"When",
"the",
"given",
"task",
"instance",
"has",
"changed",
".",
"Look",
"at",
"task",
"and",
"context",
"and",
"change",
"the",
"corresponding",
"item",
"relation",
"."
] | 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_tasks/models.py#L239-L259 | train |
adaptive-learning/proso-apps | proso_tasks/models.py | delete_parent | def delete_parent(sender, instance, **kwargs):
"""
When the given task instance is deleted, delete also the corresponding item
relations.
"""
ItemRelation.objects.filter(child_id=instance.item_id).delete() | python | def delete_parent(sender, instance, **kwargs):
"""
When the given task instance is deleted, delete also the corresponding item
relations.
"""
ItemRelation.objects.filter(child_id=instance.item_id).delete() | [
"def",
"delete_parent",
"(",
"sender",
",",
"instance",
",",
"**",
"kwargs",
")",
":",
"ItemRelation",
".",
"objects",
".",
"filter",
"(",
"child_id",
"=",
"instance",
".",
"item_id",
")",
".",
"delete",
"(",
")"
] | When the given task instance is deleted, delete also the corresponding item
relations. | [
"When",
"the",
"given",
"task",
"instance",
"is",
"deleted",
"delete",
"also",
"the",
"corresponding",
"item",
"relations",
"."
] | 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_tasks/models.py#L264-L269 | train |
Kortemme-Lab/klab | klab/bio/smallmolecule.py | Molecule.align_to_other | def align_to_other(self, other, mapping, self_root_pair, other_root_pair = None):
'''
root atoms are atom which all other unmapped atoms will be mapped off of
'''
if other_root_pair == None:
other_root_pair = self_root_pair
assert( len(self_root_pair) == len(other_ro... | python | def align_to_other(self, other, mapping, self_root_pair, other_root_pair = None):
'''
root atoms are atom which all other unmapped atoms will be mapped off of
'''
if other_root_pair == None:
other_root_pair = self_root_pair
assert( len(self_root_pair) == len(other_ro... | [
"def",
"align_to_other",
"(",
"self",
",",
"other",
",",
"mapping",
",",
"self_root_pair",
",",
"other_root_pair",
"=",
"None",
")",
":",
"if",
"other_root_pair",
"==",
"None",
":",
"other_root_pair",
"=",
"self_root_pair",
"assert",
"(",
"len",
"(",
"self_roo... | root atoms are atom which all other unmapped atoms will be mapped off of | [
"root",
"atoms",
"are",
"atom",
"which",
"all",
"other",
"unmapped",
"atoms",
"will",
"be",
"mapped",
"off",
"of"
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/smallmolecule.py#L110-L145 | train |
systori/bericht | bericht/html/parser.py | pumper | def pumper(html_generator):
"""
Pulls HTML from source generator,
feeds it to the parser and yields
DOM elements.
"""
source = html_generator()
parser = etree.HTMLPullParser(
events=('start', 'end'),
remove_comments=True
)
while True:
for element in parser.rea... | python | def pumper(html_generator):
"""
Pulls HTML from source generator,
feeds it to the parser and yields
DOM elements.
"""
source = html_generator()
parser = etree.HTMLPullParser(
events=('start', 'end'),
remove_comments=True
)
while True:
for element in parser.rea... | [
"def",
"pumper",
"(",
"html_generator",
")",
":",
"source",
"=",
"html_generator",
"(",
")",
"parser",
"=",
"etree",
".",
"HTMLPullParser",
"(",
"events",
"=",
"(",
"'start'",
",",
"'end'",
")",
",",
"remove_comments",
"=",
"True",
")",
"while",
"True",
... | Pulls HTML from source generator,
feeds it to the parser and yields
DOM elements. | [
"Pulls",
"HTML",
"from",
"source",
"generator",
"feeds",
"it",
"to",
"the",
"parser",
"and",
"yields",
"DOM",
"elements",
"."
] | e2b835784926fca86f94f06d0415ca2e4f2d4cb1 | https://github.com/systori/bericht/blob/e2b835784926fca86f94f06d0415ca2e4f2d4cb1/bericht/html/parser.py#L8-L29 | train |
Kortemme-Lab/klab | klab/general/date_ext.py | date_to_long_form_string | def date_to_long_form_string(dt, locale_ = 'en_US.utf8'):
'''dt should be a datetime.date object.'''
if locale_:
old_locale = locale.getlocale()
locale.setlocale(locale.LC_ALL, locale_)
v = dt.strftime("%A %B %d %Y")
if locale_:
locale.setlocale(locale.LC_ALL, old_locale)
ret... | python | def date_to_long_form_string(dt, locale_ = 'en_US.utf8'):
'''dt should be a datetime.date object.'''
if locale_:
old_locale = locale.getlocale()
locale.setlocale(locale.LC_ALL, locale_)
v = dt.strftime("%A %B %d %Y")
if locale_:
locale.setlocale(locale.LC_ALL, old_locale)
ret... | [
"def",
"date_to_long_form_string",
"(",
"dt",
",",
"locale_",
"=",
"'en_US.utf8'",
")",
":",
"if",
"locale_",
":",
"old_locale",
"=",
"locale",
".",
"getlocale",
"(",
")",
"locale",
".",
"setlocale",
"(",
"locale",
".",
"LC_ALL",
",",
"locale_",
")",
"v",
... | dt should be a datetime.date object. | [
"dt",
"should",
"be",
"a",
"datetime",
".",
"date",
"object",
"."
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/general/date_ext.py#L14-L22 | train |
Kortemme-Lab/klab | klab/bio/cache.py | BioCache.static_get_pdb_object | def static_get_pdb_object(pdb_id, bio_cache = None, cache_dir = None):
'''This method does not necessarily use a BioCache but it seems to fit here.'''
pdb_id = pdb_id.upper()
if bio_cache:
return bio_cache.get_pdb_object(pdb_id)
if cache_dir:
# Check to see whet... | python | def static_get_pdb_object(pdb_id, bio_cache = None, cache_dir = None):
'''This method does not necessarily use a BioCache but it seems to fit here.'''
pdb_id = pdb_id.upper()
if bio_cache:
return bio_cache.get_pdb_object(pdb_id)
if cache_dir:
# Check to see whet... | [
"def",
"static_get_pdb_object",
"(",
"pdb_id",
",",
"bio_cache",
"=",
"None",
",",
"cache_dir",
"=",
"None",
")",
":",
"pdb_id",
"=",
"pdb_id",
".",
"upper",
"(",
")",
"if",
"bio_cache",
":",
"return",
"bio_cache",
".",
"get_pdb_object",
"(",
"pdb_id",
")"... | This method does not necessarily use a BioCache but it seems to fit here. | [
"This",
"method",
"does",
"not",
"necessarily",
"use",
"a",
"BioCache",
"but",
"it",
"seems",
"to",
"fit",
"here",
"."
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/cache.py#L336-L353 | train |
cozy/python_cozy_management | cozy_management/migration.py | rebuild_app | def rebuild_app(app_name, quiet=False, force=True, without_exec=False,
restart=False):
'''
Rebuild cozy apps with deletion of npm directory & new npm build
'''
user = 'cozy-{app_name}'.format(app_name=app_name)
home = '{prefix}/{app_name}'.format(prefix=PREFIX, app_name=app_name)... | python | def rebuild_app(app_name, quiet=False, force=True, without_exec=False,
restart=False):
'''
Rebuild cozy apps with deletion of npm directory & new npm build
'''
user = 'cozy-{app_name}'.format(app_name=app_name)
home = '{prefix}/{app_name}'.format(prefix=PREFIX, app_name=app_name)... | [
"def",
"rebuild_app",
"(",
"app_name",
",",
"quiet",
"=",
"False",
",",
"force",
"=",
"True",
",",
"without_exec",
"=",
"False",
",",
"restart",
"=",
"False",
")",
":",
"user",
"=",
"'cozy-{app_name}'",
".",
"format",
"(",
"app_name",
"=",
"app_name",
")... | Rebuild cozy apps with deletion of npm directory & new npm build | [
"Rebuild",
"cozy",
"apps",
"with",
"deletion",
"of",
"npm",
"directory",
"&",
"new",
"npm",
"build"
] | 820cea58458ae3e067fa8cc2da38edbda4681dac | https://github.com/cozy/python_cozy_management/blob/820cea58458ae3e067fa8cc2da38edbda4681dac/cozy_management/migration.py#L14-L46 | train |
cozy/python_cozy_management | cozy_management/migration.py | rebuild_all_apps | def rebuild_all_apps(force=True, restart=False):
'''
Get all cozy apps & rebuild npm repository
'''
cozy_apps = monitor.status(only_cozy=True)
for app in cozy_apps.keys():
rebuild_app(app, force=force, restart=restart) | python | def rebuild_all_apps(force=True, restart=False):
'''
Get all cozy apps & rebuild npm repository
'''
cozy_apps = monitor.status(only_cozy=True)
for app in cozy_apps.keys():
rebuild_app(app, force=force, restart=restart) | [
"def",
"rebuild_all_apps",
"(",
"force",
"=",
"True",
",",
"restart",
"=",
"False",
")",
":",
"cozy_apps",
"=",
"monitor",
".",
"status",
"(",
"only_cozy",
"=",
"True",
")",
"for",
"app",
"in",
"cozy_apps",
".",
"keys",
"(",
")",
":",
"rebuild_app",
"(... | Get all cozy apps & rebuild npm repository | [
"Get",
"all",
"cozy",
"apps",
"&",
"rebuild",
"npm",
"repository"
] | 820cea58458ae3e067fa8cc2da38edbda4681dac | https://github.com/cozy/python_cozy_management/blob/820cea58458ae3e067fa8cc2da38edbda4681dac/cozy_management/migration.py#L49-L55 | train |
cozy/python_cozy_management | cozy_management/migration.py | restart_stopped_apps | def restart_stopped_apps():
'''
Restart all apps in stopped state
'''
cozy_apps = monitor.status(only_cozy=True)
for app in cozy_apps.keys():
state = cozy_apps[app]
if state == 'up':
next
elif state == 'down':
print 'Start {}'.format(app)
... | python | def restart_stopped_apps():
'''
Restart all apps in stopped state
'''
cozy_apps = monitor.status(only_cozy=True)
for app in cozy_apps.keys():
state = cozy_apps[app]
if state == 'up':
next
elif state == 'down':
print 'Start {}'.format(app)
... | [
"def",
"restart_stopped_apps",
"(",
")",
":",
"cozy_apps",
"=",
"monitor",
".",
"status",
"(",
"only_cozy",
"=",
"True",
")",
"for",
"app",
"in",
"cozy_apps",
".",
"keys",
"(",
")",
":",
"state",
"=",
"cozy_apps",
"[",
"app",
"]",
"if",
"state",
"==",
... | Restart all apps in stopped state | [
"Restart",
"all",
"apps",
"in",
"stopped",
"state"
] | 820cea58458ae3e067fa8cc2da38edbda4681dac | https://github.com/cozy/python_cozy_management/blob/820cea58458ae3e067fa8cc2da38edbda4681dac/cozy_management/migration.py#L58-L70 | train |
cozy/python_cozy_management | cozy_management/migration.py | migrate_2_node4 | def migrate_2_node4():
'''
Migrate existing cozy to node4
'''
helpers.cmd_exec('npm install -g cozy-monitor cozy-controller',
show_output=True)
helpers.cmd_exec('update-cozy-stack', show_output=True)
helpers.cmd_exec('update-all', show_output=True)
helpers.cmd_exec('... | python | def migrate_2_node4():
'''
Migrate existing cozy to node4
'''
helpers.cmd_exec('npm install -g cozy-monitor cozy-controller',
show_output=True)
helpers.cmd_exec('update-cozy-stack', show_output=True)
helpers.cmd_exec('update-all', show_output=True)
helpers.cmd_exec('... | [
"def",
"migrate_2_node4",
"(",
")",
":",
"helpers",
".",
"cmd_exec",
"(",
"'npm install -g cozy-monitor cozy-controller'",
",",
"show_output",
"=",
"True",
")",
"helpers",
".",
"cmd_exec",
"(",
"'update-cozy-stack'",
",",
"show_output",
"=",
"True",
")",
"helpers",
... | Migrate existing cozy to node4 | [
"Migrate",
"existing",
"cozy",
"to",
"node4"
] | 820cea58458ae3e067fa8cc2da38edbda4681dac | https://github.com/cozy/python_cozy_management/blob/820cea58458ae3e067fa8cc2da38edbda4681dac/cozy_management/migration.py#L73-L106 | train |
cozy/python_cozy_management | cozy_management/migration.py | install_requirements | def install_requirements():
'''
Install cozy requirements
'''
helpers.cmd_exec(
'echo "cozy cozy/nodejs_apt_list text " | debconf-set-selections',
show_output=True)
helpers.cmd_exec('apt-get install -y cozy-apt-node-list', show_output=True)
helpers.cmd_exec('apt-get update', ... | python | def install_requirements():
'''
Install cozy requirements
'''
helpers.cmd_exec(
'echo "cozy cozy/nodejs_apt_list text " | debconf-set-selections',
show_output=True)
helpers.cmd_exec('apt-get install -y cozy-apt-node-list', show_output=True)
helpers.cmd_exec('apt-get update', ... | [
"def",
"install_requirements",
"(",
")",
":",
"helpers",
".",
"cmd_exec",
"(",
"'echo \"cozy cozy/nodejs_apt_list text \" | debconf-set-selections'",
",",
"show_output",
"=",
"True",
")",
"helpers",
".",
"cmd_exec",
"(",
"'apt-get install -y cozy-apt-node-list'",
",",
"show... | Install cozy requirements | [
"Install",
"cozy",
"requirements"
] | 820cea58458ae3e067fa8cc2da38edbda4681dac | https://github.com/cozy/python_cozy_management/blob/820cea58458ae3e067fa8cc2da38edbda4681dac/cozy_management/migration.py#L109-L123 | train |
trendels/rhino | rhino/ext/session.py | SessionObject.add_message | def add_message(self, text, type=None):
"""Add a message with an optional type."""
key = self._msg_key
self.setdefault(key, [])
self[key].append(message(type, text))
self.save() | python | def add_message(self, text, type=None):
"""Add a message with an optional type."""
key = self._msg_key
self.setdefault(key, [])
self[key].append(message(type, text))
self.save() | [
"def",
"add_message",
"(",
"self",
",",
"text",
",",
"type",
"=",
"None",
")",
":",
"key",
"=",
"self",
".",
"_msg_key",
"self",
".",
"setdefault",
"(",
"key",
",",
"[",
"]",
")",
"self",
"[",
"key",
"]",
".",
"append",
"(",
"message",
"(",
"type... | Add a message with an optional type. | [
"Add",
"a",
"message",
"with",
"an",
"optional",
"type",
"."
] | f1f0ef21b6080a2bd130b38b5bef163074c94aed | https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/ext/session.py#L43-L48 | train |
trendels/rhino | rhino/ext/session.py | SessionObject.pop_messages | def pop_messages(self, type=None):
"""Retrieve stored messages and remove them from the session.
Return all messages with a specific type, or all messages when `type`
is None. Messages are returned in the order they were added. All
messages returned in this way are removed from the sess... | python | def pop_messages(self, type=None):
"""Retrieve stored messages and remove them from the session.
Return all messages with a specific type, or all messages when `type`
is None. Messages are returned in the order they were added. All
messages returned in this way are removed from the sess... | [
"def",
"pop_messages",
"(",
"self",
",",
"type",
"=",
"None",
")",
":",
"key",
"=",
"self",
".",
"_msg_key",
"messages",
"=",
"[",
"]",
"if",
"type",
"is",
"None",
":",
"messages",
"=",
"self",
".",
"pop",
"(",
"key",
",",
"[",
"]",
")",
"else",
... | Retrieve stored messages and remove them from the session.
Return all messages with a specific type, or all messages when `type`
is None. Messages are returned in the order they were added. All
messages returned in this way are removed from the session and will not
be returned in subseq... | [
"Retrieve",
"stored",
"messages",
"and",
"remove",
"them",
"from",
"the",
"session",
"."
] | f1f0ef21b6080a2bd130b38b5bef163074c94aed | https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/ext/session.py#L50-L78 | train |
assamite/creamas | creamas/vote.py | vote_random | def vote_random(candidates, votes, n_winners):
"""Select random winners from the candidates.
This voting method bypasses the given votes completely.
:param candidates: All candidates in the vote
:param votes: Votes from the agents
:param int n_winners: The number of vote winners
"""
rcands... | python | def vote_random(candidates, votes, n_winners):
"""Select random winners from the candidates.
This voting method bypasses the given votes completely.
:param candidates: All candidates in the vote
:param votes: Votes from the agents
:param int n_winners: The number of vote winners
"""
rcands... | [
"def",
"vote_random",
"(",
"candidates",
",",
"votes",
",",
"n_winners",
")",
":",
"rcands",
"=",
"list",
"(",
"candidates",
")",
"shuffle",
"(",
"rcands",
")",
"rcands",
"=",
"rcands",
"[",
":",
"min",
"(",
"n_winners",
",",
"len",
"(",
"rcands",
")",... | Select random winners from the candidates.
This voting method bypasses the given votes completely.
:param candidates: All candidates in the vote
:param votes: Votes from the agents
:param int n_winners: The number of vote winners | [
"Select",
"random",
"winners",
"from",
"the",
"candidates",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/vote.py#L439-L452 | train |
assamite/creamas | creamas/vote.py | vote_least_worst | def vote_least_worst(candidates, votes, n_winners):
"""Select "least worst" artifact as the winner of the vote.
Least worst artifact is the artifact with the best worst evaluation, i.e.
its worst evaluation is the best among all of the artifacts.
Ties are resolved randomly.
:param candidates: All... | python | def vote_least_worst(candidates, votes, n_winners):
"""Select "least worst" artifact as the winner of the vote.
Least worst artifact is the artifact with the best worst evaluation, i.e.
its worst evaluation is the best among all of the artifacts.
Ties are resolved randomly.
:param candidates: All... | [
"def",
"vote_least_worst",
"(",
"candidates",
",",
"votes",
",",
"n_winners",
")",
":",
"worsts",
"=",
"{",
"str",
"(",
"c",
")",
":",
"100000000.0",
"for",
"c",
"in",
"candidates",
"}",
"for",
"v",
"in",
"votes",
":",
"for",
"e",
"in",
"v",
":",
"... | Select "least worst" artifact as the winner of the vote.
Least worst artifact is the artifact with the best worst evaluation, i.e.
its worst evaluation is the best among all of the artifacts.
Ties are resolved randomly.
:param candidates: All candidates in the vote
:param votes: Votes from the ag... | [
"Select",
"least",
"worst",
"artifact",
"as",
"the",
"winner",
"of",
"the",
"vote",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/vote.py#L455-L479 | train |
assamite/creamas | creamas/vote.py | vote_best | def vote_best(candidates, votes, n_winners):
"""Select the artifact with the single best evaluation as the winner of
the vote.
Ties are resolved randomly.
:param candidates: All candidates in the vote
:param votes: Votes from the agents
:param int n_winners: The number of vote winners
"""
... | python | def vote_best(candidates, votes, n_winners):
"""Select the artifact with the single best evaluation as the winner of
the vote.
Ties are resolved randomly.
:param candidates: All candidates in the vote
:param votes: Votes from the agents
:param int n_winners: The number of vote winners
"""
... | [
"def",
"vote_best",
"(",
"candidates",
",",
"votes",
",",
"n_winners",
")",
":",
"best",
"=",
"[",
"votes",
"[",
"0",
"]",
"[",
"0",
"]",
"]",
"for",
"v",
"in",
"votes",
"[",
"1",
":",
"]",
":",
"if",
"v",
"[",
"0",
"]",
"[",
"1",
"]",
">",... | Select the artifact with the single best evaluation as the winner of
the vote.
Ties are resolved randomly.
:param candidates: All candidates in the vote
:param votes: Votes from the agents
:param int n_winners: The number of vote winners | [
"Select",
"the",
"artifact",
"with",
"the",
"single",
"best",
"evaluation",
"as",
"the",
"winner",
"of",
"the",
"vote",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/vote.py#L482-L496 | train |
assamite/creamas | creamas/vote.py | _remove_zeros | def _remove_zeros(votes, fpl, cl, ranking):
"""Remove zeros in IRV voting.
"""
for v in votes:
for r in v:
if r not in fpl:
v.remove(r)
for c in cl:
if c not in fpl:
if c not in ranking:
ranking.append((c, 0)) | python | def _remove_zeros(votes, fpl, cl, ranking):
"""Remove zeros in IRV voting.
"""
for v in votes:
for r in v:
if r not in fpl:
v.remove(r)
for c in cl:
if c not in fpl:
if c not in ranking:
ranking.append((c, 0)) | [
"def",
"_remove_zeros",
"(",
"votes",
",",
"fpl",
",",
"cl",
",",
"ranking",
")",
":",
"for",
"v",
"in",
"votes",
":",
"for",
"r",
"in",
"v",
":",
"if",
"r",
"not",
"in",
"fpl",
":",
"v",
".",
"remove",
"(",
"r",
")",
"for",
"c",
"in",
"cl",
... | Remove zeros in IRV voting. | [
"Remove",
"zeros",
"in",
"IRV",
"voting",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/vote.py#L499-L509 | train |
assamite/creamas | creamas/vote.py | _remove_last | def _remove_last(votes, fpl, cl, ranking):
"""Remove last candidate in IRV voting.
"""
for v in votes:
for r in v:
if r == fpl[-1]:
v.remove(r)
for c in cl:
if c == fpl[-1]:
if c not in ranking:
ranking.append((c, len(ranking) + 1)) | python | def _remove_last(votes, fpl, cl, ranking):
"""Remove last candidate in IRV voting.
"""
for v in votes:
for r in v:
if r == fpl[-1]:
v.remove(r)
for c in cl:
if c == fpl[-1]:
if c not in ranking:
ranking.append((c, len(ranking) + 1)) | [
"def",
"_remove_last",
"(",
"votes",
",",
"fpl",
",",
"cl",
",",
"ranking",
")",
":",
"for",
"v",
"in",
"votes",
":",
"for",
"r",
"in",
"v",
":",
"if",
"r",
"==",
"fpl",
"[",
"-",
"1",
"]",
":",
"v",
".",
"remove",
"(",
"r",
")",
"for",
"c"... | Remove last candidate in IRV voting. | [
"Remove",
"last",
"candidate",
"in",
"IRV",
"voting",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/vote.py#L512-L522 | train |
assamite/creamas | creamas/vote.py | vote_IRV | def vote_IRV(candidates, votes, n_winners):
"""Perform IRV voting based on votes.
Ties are resolved randomly.
:param candidates: All candidates in the vote
:param votes: Votes from the agents
:param int n_winners: The number of vote winners
"""
# TODO: Check what is wrong in here.
vote... | python | def vote_IRV(candidates, votes, n_winners):
"""Perform IRV voting based on votes.
Ties are resolved randomly.
:param candidates: All candidates in the vote
:param votes: Votes from the agents
:param int n_winners: The number of vote winners
"""
# TODO: Check what is wrong in here.
vote... | [
"def",
"vote_IRV",
"(",
"candidates",
",",
"votes",
",",
"n_winners",
")",
":",
"votes",
"=",
"[",
"[",
"e",
"[",
"0",
"]",
"for",
"e",
"in",
"v",
"]",
"for",
"v",
"in",
"votes",
"]",
"f",
"=",
"lambda",
"x",
":",
"Counter",
"(",
"e",
"[",
"0... | Perform IRV voting based on votes.
Ties are resolved randomly.
:param candidates: All candidates in the vote
:param votes: Votes from the agents
:param int n_winners: The number of vote winners | [
"Perform",
"IRV",
"voting",
"based",
"on",
"votes",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/vote.py#L525-L551 | train |
assamite/creamas | creamas/vote.py | vote_mean | def vote_mean(candidates, votes, n_winners):
"""Perform mean voting based on votes.
Mean voting computes the mean preference for each of the artifact
candidates from the votes and sorts the candidates in the mean preference
order.
Ties are resolved randomly.
:param candidates: All candidates ... | python | def vote_mean(candidates, votes, n_winners):
"""Perform mean voting based on votes.
Mean voting computes the mean preference for each of the artifact
candidates from the votes and sorts the candidates in the mean preference
order.
Ties are resolved randomly.
:param candidates: All candidates ... | [
"def",
"vote_mean",
"(",
"candidates",
",",
"votes",
",",
"n_winners",
")",
":",
"sums",
"=",
"{",
"str",
"(",
"candidate",
")",
":",
"[",
"]",
"for",
"candidate",
"in",
"candidates",
"}",
"for",
"vote",
"in",
"votes",
":",
"for",
"v",
"in",
"vote",
... | Perform mean voting based on votes.
Mean voting computes the mean preference for each of the artifact
candidates from the votes and sorts the candidates in the mean preference
order.
Ties are resolved randomly.
:param candidates: All candidates in the vote
:param votes: Votes from the agents
... | [
"Perform",
"mean",
"voting",
"based",
"on",
"votes",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/vote.py#L554-L581 | train |
assamite/creamas | creamas/vote.py | VoteAgent.vote | def vote(self, candidates):
"""Rank artifact candidates.
The voting is needed for the agents living in societies using
social decision making. The function should return a sorted list
of (candidate, evaluation)-tuples. Depending on the social choice
function used, the evaluation... | python | def vote(self, candidates):
"""Rank artifact candidates.
The voting is needed for the agents living in societies using
social decision making. The function should return a sorted list
of (candidate, evaluation)-tuples. Depending on the social choice
function used, the evaluation... | [
"def",
"vote",
"(",
"self",
",",
"candidates",
")",
":",
"ranks",
"=",
"[",
"(",
"c",
",",
"self",
".",
"evaluate",
"(",
"c",
")",
"[",
"0",
"]",
")",
"for",
"c",
"in",
"candidates",
"]",
"ranks",
".",
"sort",
"(",
"key",
"=",
"operator",
".",
... | Rank artifact candidates.
The voting is needed for the agents living in societies using
social decision making. The function should return a sorted list
of (candidate, evaluation)-tuples. Depending on the social choice
function used, the evaluation might be omitted from the actual decis... | [
"Rank",
"artifact",
"candidates",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/vote.py#L75-L97 | train |
assamite/creamas | creamas/vote.py | VoteEnvironment.add_candidate | def add_candidate(self, artifact):
"""Add candidate artifact to the list of current candidates.
"""
self.candidates.append(artifact)
self._log(logging.DEBUG, "CANDIDATES appended:'{}'"
.format(artifact)) | python | def add_candidate(self, artifact):
"""Add candidate artifact to the list of current candidates.
"""
self.candidates.append(artifact)
self._log(logging.DEBUG, "CANDIDATES appended:'{}'"
.format(artifact)) | [
"def",
"add_candidate",
"(",
"self",
",",
"artifact",
")",
":",
"self",
".",
"candidates",
".",
"append",
"(",
"artifact",
")",
"self",
".",
"_log",
"(",
"logging",
".",
"DEBUG",
",",
"\"CANDIDATES appended:'{}'\"",
".",
"format",
"(",
"artifact",
")",
")"... | Add candidate artifact to the list of current candidates. | [
"Add",
"candidate",
"artifact",
"to",
"the",
"list",
"of",
"current",
"candidates",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/vote.py#L129-L134 | train |
assamite/creamas | creamas/vote.py | VoteEnvironment.validate_candidates | def validate_candidates(self, candidates):
"""Validate the candidate artifacts with the agents in the environment.
In larger societies this method might be costly, as it calls each
agents' :meth:`validate`.
:returns:
A list of candidates that are validated by all agents in ... | python | def validate_candidates(self, candidates):
"""Validate the candidate artifacts with the agents in the environment.
In larger societies this method might be costly, as it calls each
agents' :meth:`validate`.
:returns:
A list of candidates that are validated by all agents in ... | [
"def",
"validate_candidates",
"(",
"self",
",",
"candidates",
")",
":",
"valid_candidates",
"=",
"set",
"(",
"candidates",
")",
"for",
"a",
"in",
"self",
".",
"get_agents",
"(",
"addr",
"=",
"False",
")",
":",
"vc",
"=",
"set",
"(",
"a",
".",
"validate... | Validate the candidate artifacts with the agents in the environment.
In larger societies this method might be costly, as it calls each
agents' :meth:`validate`.
:returns:
A list of candidates that are validated by all agents in the
environment. | [
"Validate",
"the",
"candidate",
"artifacts",
"with",
"the",
"agents",
"in",
"the",
"environment",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/vote.py#L136-L151 | train |
assamite/creamas | creamas/vote.py | VoteEnvironment.gather_votes | def gather_votes(self, candidates):
"""Gather votes for the given candidates from the agents in the
environment.
Returned votes are anonymous, i.e. they cannot be tracked to any
individual agent afterwards.
:returns:
A list of votes. Each vote is a list of ``(artifa... | python | def gather_votes(self, candidates):
"""Gather votes for the given candidates from the agents in the
environment.
Returned votes are anonymous, i.e. they cannot be tracked to any
individual agent afterwards.
:returns:
A list of votes. Each vote is a list of ``(artifa... | [
"def",
"gather_votes",
"(",
"self",
",",
"candidates",
")",
":",
"votes",
"=",
"[",
"]",
"for",
"a",
"in",
"self",
".",
"get_agents",
"(",
"addr",
"=",
"False",
")",
":",
"vote",
"=",
"a",
".",
"vote",
"(",
"candidates",
")",
"votes",
".",
"append"... | Gather votes for the given candidates from the agents in the
environment.
Returned votes are anonymous, i.e. they cannot be tracked to any
individual agent afterwards.
:returns:
A list of votes. Each vote is a list of ``(artifact, preference)``
-tuples sorted in... | [
"Gather",
"votes",
"for",
"the",
"given",
"candidates",
"from",
"the",
"agents",
"in",
"the",
"environment",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/vote.py#L153-L168 | train |
assamite/creamas | creamas/vote.py | VoteOrganizer.get_managers | def get_managers(self):
"""Get managers for the slave environments.
"""
if self._single_env:
return None
if not hasattr(self, '_managers'):
self._managers = self.env.get_slave_managers()
return self._managers | python | def get_managers(self):
"""Get managers for the slave environments.
"""
if self._single_env:
return None
if not hasattr(self, '_managers'):
self._managers = self.env.get_slave_managers()
return self._managers | [
"def",
"get_managers",
"(",
"self",
")",
":",
"if",
"self",
".",
"_single_env",
":",
"return",
"None",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_managers'",
")",
":",
"self",
".",
"_managers",
"=",
"self",
".",
"env",
".",
"get_slave_managers",
"(",
... | Get managers for the slave environments. | [
"Get",
"managers",
"for",
"the",
"slave",
"environments",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/vote.py#L265-L272 | train |
assamite/creamas | creamas/vote.py | VoteOrganizer.gather_votes | def gather_votes(self):
"""Gather votes from all the underlying slave environments for the
current list of candidates.
The votes are stored in :attr:`votes`, overriding any previous votes.
"""
async def slave_task(addr, candidates):
r_manager = await self.env.connect... | python | def gather_votes(self):
"""Gather votes from all the underlying slave environments for the
current list of candidates.
The votes are stored in :attr:`votes`, overriding any previous votes.
"""
async def slave_task(addr, candidates):
r_manager = await self.env.connect... | [
"def",
"gather_votes",
"(",
"self",
")",
":",
"async",
"def",
"slave_task",
"(",
"addr",
",",
"candidates",
")",
":",
"r_manager",
"=",
"await",
"self",
".",
"env",
".",
"connect",
"(",
"addr",
")",
"return",
"await",
"r_manager",
".",
"gather_votes",
"(... | Gather votes from all the underlying slave environments for the
current list of candidates.
The votes are stored in :attr:`votes`, overriding any previous votes. | [
"Gather",
"votes",
"from",
"all",
"the",
"underlying",
"slave",
"environments",
"for",
"the",
"current",
"list",
"of",
"candidates",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/vote.py#L274-L297 | train |
assamite/creamas | creamas/vote.py | VoteOrganizer.gather_candidates | def gather_candidates(self):
"""Gather candidates from the slave environments.
The candidates are stored in :attr:`candidates`, overriding any
previous candidates.
"""
async def slave_task(addr):
r_manager = await self.env.connect(addr)
return await r_man... | python | def gather_candidates(self):
"""Gather candidates from the slave environments.
The candidates are stored in :attr:`candidates`, overriding any
previous candidates.
"""
async def slave_task(addr):
r_manager = await self.env.connect(addr)
return await r_man... | [
"def",
"gather_candidates",
"(",
"self",
")",
":",
"async",
"def",
"slave_task",
"(",
"addr",
")",
":",
"r_manager",
"=",
"await",
"self",
".",
"env",
".",
"connect",
"(",
"addr",
")",
"return",
"await",
"r_manager",
".",
"get_candidates",
"(",
")",
"if"... | Gather candidates from the slave environments.
The candidates are stored in :attr:`candidates`, overriding any
previous candidates. | [
"Gather",
"candidates",
"from",
"the",
"slave",
"environments",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/vote.py#L299-L314 | train |
assamite/creamas | creamas/vote.py | VoteOrganizer.clear_candidates | def clear_candidates(self, clear_env=True):
"""Clear the current candidates.
:param bool clear_env:
If ``True``, clears also environment's (or its underlying slave
environments') candidates.
"""
async def slave_task(addr):
r_manager = await self.env.c... | python | def clear_candidates(self, clear_env=True):
"""Clear the current candidates.
:param bool clear_env:
If ``True``, clears also environment's (or its underlying slave
environments') candidates.
"""
async def slave_task(addr):
r_manager = await self.env.c... | [
"def",
"clear_candidates",
"(",
"self",
",",
"clear_env",
"=",
"True",
")",
":",
"async",
"def",
"slave_task",
"(",
"addr",
")",
":",
"r_manager",
"=",
"await",
"self",
".",
"env",
".",
"connect",
"(",
"addr",
")",
"return",
"await",
"r_manager",
".",
... | Clear the current candidates.
:param bool clear_env:
If ``True``, clears also environment's (or its underlying slave
environments') candidates. | [
"Clear",
"the",
"current",
"candidates",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/vote.py#L316-L333 | train |
assamite/creamas | creamas/vote.py | VoteOrganizer.validate_candidates | def validate_candidates(self):
"""Validate current candidates.
This method validates the current candidate list in all the agents
in the environment (or underlying slave environments) and replaces
the current :attr:`candidates` with the list of validated candidates.
The artifac... | python | def validate_candidates(self):
"""Validate current candidates.
This method validates the current candidate list in all the agents
in the environment (or underlying slave environments) and replaces
the current :attr:`candidates` with the list of validated candidates.
The artifac... | [
"def",
"validate_candidates",
"(",
"self",
")",
":",
"async",
"def",
"slave_task",
"(",
"addr",
",",
"candidates",
")",
":",
"r_manager",
"=",
"await",
"self",
".",
"env",
".",
"connect",
"(",
"addr",
")",
"return",
"await",
"r_manager",
".",
"validate_can... | Validate current candidates.
This method validates the current candidate list in all the agents
in the environment (or underlying slave environments) and replaces
the current :attr:`candidates` with the list of validated candidates.
The artifact candidates must be hashable and have a :... | [
"Validate",
"current",
"candidates",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/vote.py#L335-L366 | train |
assamite/creamas | creamas/vote.py | VoteOrganizer.gather_and_vote | def gather_and_vote(self, voting_method, validate=False, winners=1,
**kwargs):
"""Convenience function to gathering candidates and votes and
performing voting using them.
Additional ``**kwargs`` are passed down to voting method.
:param voting_method:
... | python | def gather_and_vote(self, voting_method, validate=False, winners=1,
**kwargs):
"""Convenience function to gathering candidates and votes and
performing voting using them.
Additional ``**kwargs`` are passed down to voting method.
:param voting_method:
... | [
"def",
"gather_and_vote",
"(",
"self",
",",
"voting_method",
",",
"validate",
"=",
"False",
",",
"winners",
"=",
"1",
",",
"**",
"kwargs",
")",
":",
"self",
".",
"gather_candidates",
"(",
")",
"if",
"validate",
":",
"self",
".",
"validate_candidates",
"(",... | Convenience function to gathering candidates and votes and
performing voting using them.
Additional ``**kwargs`` are passed down to voting method.
:param voting_method:
The voting method to use, see
:meth:`~creamas.vote.VoteOrganizer.compute_results` for details.
... | [
"Convenience",
"function",
"to",
"gathering",
"candidates",
"and",
"votes",
"and",
"performing",
"voting",
"using",
"them",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/vote.py#L368-L389 | train |
TheGhouls/oct | oct/utilities/run_device.py | start_device | def start_device(name, frontend, backend):
"""Start specified device
:param str name: name of the device, MUST match one of ['forwarder', 'streamer']
:param int frontend: frontend bind port for device
:param int backend: backend bind port for device
"""
device = getattr(devices, name)
devic... | python | def start_device(name, frontend, backend):
"""Start specified device
:param str name: name of the device, MUST match one of ['forwarder', 'streamer']
:param int frontend: frontend bind port for device
:param int backend: backend bind port for device
"""
device = getattr(devices, name)
devic... | [
"def",
"start_device",
"(",
"name",
",",
"frontend",
",",
"backend",
")",
":",
"device",
"=",
"getattr",
"(",
"devices",
",",
"name",
")",
"device",
"(",
"frontend",
",",
"backend",
")"
] | Start specified device
:param str name: name of the device, MUST match one of ['forwarder', 'streamer']
:param int frontend: frontend bind port for device
:param int backend: backend bind port for device | [
"Start",
"specified",
"device"
] | 7e9bddeb3b8495a26442b1c86744e9fb187fe88f | https://github.com/TheGhouls/oct/blob/7e9bddeb3b8495a26442b1c86744e9fb187fe88f/oct/utilities/run_device.py#L8-L16 | train |
TheGhouls/oct | oct/core/turrets_manager.py | TurretsManager.start | def start(self, transaction_context=None):
"""Publish start message to all turrets
"""
transaction_context = transaction_context or {}
context_cmd = {'command': 'set_transaction_context',
'msg': transaction_context}
self.publish(context_cmd)
self.pu... | python | def start(self, transaction_context=None):
"""Publish start message to all turrets
"""
transaction_context = transaction_context or {}
context_cmd = {'command': 'set_transaction_context',
'msg': transaction_context}
self.publish(context_cmd)
self.pu... | [
"def",
"start",
"(",
"self",
",",
"transaction_context",
"=",
"None",
")",
":",
"transaction_context",
"=",
"transaction_context",
"or",
"{",
"}",
"context_cmd",
"=",
"{",
"'command'",
":",
"'set_transaction_context'",
",",
"'msg'",
":",
"transaction_context",
"}"... | Publish start message to all turrets | [
"Publish",
"start",
"message",
"to",
"all",
"turrets"
] | 7e9bddeb3b8495a26442b1c86744e9fb187fe88f | https://github.com/TheGhouls/oct/blob/7e9bddeb3b8495a26442b1c86744e9fb187fe88f/oct/core/turrets_manager.py#L32-L39 | train |
TheGhouls/oct | oct/core/turrets_manager.py | TurretsManager.process_message | def process_message(self, message, is_started=False):
"""Process incomming message from turret
:param dict message: incomming message
:param bool is_started: test started indicator
"""
if not self.master:
return False
if 'status' not in message:
... | python | def process_message(self, message, is_started=False):
"""Process incomming message from turret
:param dict message: incomming message
:param bool is_started: test started indicator
"""
if not self.master:
return False
if 'status' not in message:
... | [
"def",
"process_message",
"(",
"self",
",",
"message",
",",
"is_started",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"master",
":",
"return",
"False",
"if",
"'status'",
"not",
"in",
"message",
":",
"return",
"False",
"message",
"[",
"'name'",
"]",... | Process incomming message from turret
:param dict message: incomming message
:param bool is_started: test started indicator | [
"Process",
"incomming",
"message",
"from",
"turret"
] | 7e9bddeb3b8495a26442b1c86744e9fb187fe88f | https://github.com/TheGhouls/oct/blob/7e9bddeb3b8495a26442b1c86744e9fb187fe88f/oct/core/turrets_manager.py#L51-L66 | train |
TheGhouls/oct | oct/core/turrets_manager.py | TurretsManager.add | def add(self, turret_data, is_started=False):
"""Add a turret object to current turrets configuration
:param dict turret_data: the data of the turret to add
:param bool is_started: tell if test are already runing
"""
if turret_data.get('uuid') in self.turrets:
return... | python | def add(self, turret_data, is_started=False):
"""Add a turret object to current turrets configuration
:param dict turret_data: the data of the turret to add
:param bool is_started: tell if test are already runing
"""
if turret_data.get('uuid') in self.turrets:
return... | [
"def",
"add",
"(",
"self",
",",
"turret_data",
",",
"is_started",
"=",
"False",
")",
":",
"if",
"turret_data",
".",
"get",
"(",
"'uuid'",
")",
"in",
"self",
".",
"turrets",
":",
"return",
"False",
"turret",
"=",
"Turret",
"(",
"**",
"turret_data",
")",... | Add a turret object to current turrets configuration
:param dict turret_data: the data of the turret to add
:param bool is_started: tell if test are already runing | [
"Add",
"a",
"turret",
"object",
"to",
"current",
"turrets",
"configuration"
] | 7e9bddeb3b8495a26442b1c86744e9fb187fe88f | https://github.com/TheGhouls/oct/blob/7e9bddeb3b8495a26442b1c86744e9fb187fe88f/oct/core/turrets_manager.py#L68-L84 | train |
TheGhouls/oct | oct/core/turrets_manager.py | TurretsManager.update | def update(self, turret_data):
"""Update a given turret
:param dict turret_data: the data of the turret to update
"""
if turret_data.get('uuid') not in self.turrets:
return False
turret = self.turrets[turret_data.get('uuid')]
turret.update(**turret_data)
... | python | def update(self, turret_data):
"""Update a given turret
:param dict turret_data: the data of the turret to update
"""
if turret_data.get('uuid') not in self.turrets:
return False
turret = self.turrets[turret_data.get('uuid')]
turret.update(**turret_data)
... | [
"def",
"update",
"(",
"self",
",",
"turret_data",
")",
":",
"if",
"turret_data",
".",
"get",
"(",
"'uuid'",
")",
"not",
"in",
"self",
".",
"turrets",
":",
"return",
"False",
"turret",
"=",
"self",
".",
"turrets",
"[",
"turret_data",
".",
"get",
"(",
... | Update a given turret
:param dict turret_data: the data of the turret to update | [
"Update",
"a",
"given",
"turret"
] | 7e9bddeb3b8495a26442b1c86744e9fb187fe88f | https://github.com/TheGhouls/oct/blob/7e9bddeb3b8495a26442b1c86744e9fb187fe88f/oct/core/turrets_manager.py#L86-L96 | train |
TheGhouls/oct | oct/core/turrets_manager.py | TurretsManager.publish | def publish(self, message, channel=None):
"""Publish a message for all turrets
:param dict message: message to send to turrets
:pram str channel: channel to send message, default to empty string
"""
if not self.master:
return
channel = channel or ''
d... | python | def publish(self, message, channel=None):
"""Publish a message for all turrets
:param dict message: message to send to turrets
:pram str channel: channel to send message, default to empty string
"""
if not self.master:
return
channel = channel or ''
d... | [
"def",
"publish",
"(",
"self",
",",
"message",
",",
"channel",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"master",
":",
"return",
"channel",
"=",
"channel",
"or",
"''",
"data",
"=",
"json",
".",
"dumps",
"(",
"message",
")",
"self",
".",
"pu... | Publish a message for all turrets
:param dict message: message to send to turrets
:pram str channel: channel to send message, default to empty string | [
"Publish",
"a",
"message",
"for",
"all",
"turrets"
] | 7e9bddeb3b8495a26442b1c86744e9fb187fe88f | https://github.com/TheGhouls/oct/blob/7e9bddeb3b8495a26442b1c86744e9fb187fe88f/oct/core/turrets_manager.py#L106-L116 | train |
berkeley-cocosci/Wallace | wallace/recruiters.py | PsiTurkRecruiter.open_recruitment | def open_recruitment(self, n=1):
"""Open recruitment for the first HIT, unless it's already open."""
from psiturk.amt_services import MTurkServices, RDSServices
from psiturk.psiturk_shell import PsiturkNetworkShell
from psiturk.psiturk_org_services import PsiturkOrgServices
psit... | python | def open_recruitment(self, n=1):
"""Open recruitment for the first HIT, unless it's already open."""
from psiturk.amt_services import MTurkServices, RDSServices
from psiturk.psiturk_shell import PsiturkNetworkShell
from psiturk.psiturk_org_services import PsiturkOrgServices
psit... | [
"def",
"open_recruitment",
"(",
"self",
",",
"n",
"=",
"1",
")",
":",
"from",
"psiturk",
".",
"amt_services",
"import",
"MTurkServices",
",",
"RDSServices",
"from",
"psiturk",
".",
"psiturk_shell",
"import",
"PsiturkNetworkShell",
"from",
"psiturk",
".",
"psitur... | Open recruitment for the first HIT, unless it's already open. | [
"Open",
"recruitment",
"for",
"the",
"first",
"HIT",
"unless",
"it",
"s",
"already",
"open",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/recruiters.py#L102-L150 | train |
berkeley-cocosci/Wallace | wallace/recruiters.py | PsiTurkRecruiter.approve_hit | def approve_hit(self, assignment_id):
"""Approve the HIT."""
from psiturk.amt_services import MTurkServices
self.amt_services = MTurkServices(
self.aws_access_key_id,
self.aws_secret_access_key,
self.config.getboolean(
'Shell Parameters', 'lau... | python | def approve_hit(self, assignment_id):
"""Approve the HIT."""
from psiturk.amt_services import MTurkServices
self.amt_services = MTurkServices(
self.aws_access_key_id,
self.aws_secret_access_key,
self.config.getboolean(
'Shell Parameters', 'lau... | [
"def",
"approve_hit",
"(",
"self",
",",
"assignment_id",
")",
":",
"from",
"psiturk",
".",
"amt_services",
"import",
"MTurkServices",
"self",
".",
"amt_services",
"=",
"MTurkServices",
"(",
"self",
".",
"aws_access_key_id",
",",
"self",
".",
"aws_secret_access_key... | Approve the HIT. | [
"Approve",
"the",
"HIT",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/recruiters.py#L196-L205 | train |
berkeley-cocosci/Wallace | wallace/recruiters.py | PsiTurkRecruiter.reward_bonus | def reward_bonus(self, assignment_id, amount, reason):
"""Reward the Turker with a bonus."""
from psiturk.amt_services import MTurkServices
self.amt_services = MTurkServices(
self.aws_access_key_id,
self.aws_secret_access_key,
self.config.getboolean(
... | python | def reward_bonus(self, assignment_id, amount, reason):
"""Reward the Turker with a bonus."""
from psiturk.amt_services import MTurkServices
self.amt_services = MTurkServices(
self.aws_access_key_id,
self.aws_secret_access_key,
self.config.getboolean(
... | [
"def",
"reward_bonus",
"(",
"self",
",",
"assignment_id",
",",
"amount",
",",
"reason",
")",
":",
"from",
"psiturk",
".",
"amt_services",
"import",
"MTurkServices",
"self",
".",
"amt_services",
"=",
"MTurkServices",
"(",
"self",
".",
"aws_access_key_id",
",",
... | Reward the Turker with a bonus. | [
"Reward",
"the",
"Turker",
"with",
"a",
"bonus",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/recruiters.py#L207-L216 | train |
MacHu-GWU/sqlalchemy_mate-project | sqlalchemy_mate/orm/extended_declarative_base.py | ExtendedBase.keys | def keys(cls):
"""
return list of all declared columns.
:rtype: List[str]
"""
if cls._cache_keys is None:
cls._cache_keys = [c.name for c in cls.__table__._columns]
return cls._cache_keys | python | def keys(cls):
"""
return list of all declared columns.
:rtype: List[str]
"""
if cls._cache_keys is None:
cls._cache_keys = [c.name for c in cls.__table__._columns]
return cls._cache_keys | [
"def",
"keys",
"(",
"cls",
")",
":",
"if",
"cls",
".",
"_cache_keys",
"is",
"None",
":",
"cls",
".",
"_cache_keys",
"=",
"[",
"c",
".",
"name",
"for",
"c",
"in",
"cls",
".",
"__table__",
".",
"_columns",
"]",
"return",
"cls",
".",
"_cache_keys"
] | return list of all declared columns.
:rtype: List[str] | [
"return",
"list",
"of",
"all",
"declared",
"columns",
"."
] | 946754744c8870f083fd7b4339fca15d1d6128b2 | https://github.com/MacHu-GWU/sqlalchemy_mate-project/blob/946754744c8870f083fd7b4339fca15d1d6128b2/sqlalchemy_mate/orm/extended_declarative_base.py#L134-L142 | train |
MacHu-GWU/sqlalchemy_mate-project | sqlalchemy_mate/orm/extended_declarative_base.py | ExtendedBase.random | def random(cls, engine_or_session, limit=5):
"""
Return random ORM instance.
:type engine_or_session: Union[Engine, Session]
:type limit: int
:rtype: List[ExtendedBase]
"""
ses, auto_close = ensure_session(engine_or_session)
result = ses.query(cls).order... | python | def random(cls, engine_or_session, limit=5):
"""
Return random ORM instance.
:type engine_or_session: Union[Engine, Session]
:type limit: int
:rtype: List[ExtendedBase]
"""
ses, auto_close = ensure_session(engine_or_session)
result = ses.query(cls).order... | [
"def",
"random",
"(",
"cls",
",",
"engine_or_session",
",",
"limit",
"=",
"5",
")",
":",
"ses",
",",
"auto_close",
"=",
"ensure_session",
"(",
"engine_or_session",
")",
"result",
"=",
"ses",
".",
"query",
"(",
"cls",
")",
".",
"order_by",
"(",
"func",
... | Return random ORM instance.
:type engine_or_session: Union[Engine, Session]
:type limit: int
:rtype: List[ExtendedBase] | [
"Return",
"random",
"ORM",
"instance",
"."
] | 946754744c8870f083fd7b4339fca15d1d6128b2 | https://github.com/MacHu-GWU/sqlalchemy_mate-project/blob/946754744c8870f083fd7b4339fca15d1d6128b2/sqlalchemy_mate/orm/extended_declarative_base.py#L413-L426 | train |
RedKrieg/pysparklines | sparkline/sparkline.py | main | def main():
u"""Reads from command line args or stdin and prints a sparkline from the
data. Requires at least 2 data points as input.
"""
import argparse
from pkg_resources import require
parser = argparse.ArgumentParser(description=main.__doc__)
parser.add_argument(
"data",
... | python | def main():
u"""Reads from command line args or stdin and prints a sparkline from the
data. Requires at least 2 data points as input.
"""
import argparse
from pkg_resources import require
parser = argparse.ArgumentParser(description=main.__doc__)
parser.add_argument(
"data",
... | [
"def",
"main",
"(",
")",
":",
"u",
"import",
"argparse",
"from",
"pkg_resources",
"import",
"require",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"main",
".",
"__doc__",
")",
"parser",
".",
"add_argument",
"(",
"\"data\"",
","... | u"""Reads from command line args or stdin and prints a sparkline from the
data. Requires at least 2 data points as input. | [
"u",
"Reads",
"from",
"command",
"line",
"args",
"or",
"stdin",
"and",
"prints",
"a",
"sparkline",
"from",
"the",
"data",
".",
"Requires",
"at",
"least",
"2",
"data",
"points",
"as",
"input",
"."
] | 7efdc98f841a0003e138a93c4e27cd71a64e7062 | https://github.com/RedKrieg/pysparklines/blob/7efdc98f841a0003e138a93c4e27cd71a64e7062/sparkline/sparkline.py#L57-L97 | train |
clement-alexandre/TotemBionet | totembionet/src/discrete_model/multiplex.py | Multiplex.is_active | def is_active(self, state: 'State') -> bool:
""" Return True if the multiplex is active in the given state, false otherwise. """
# Remove the genes which does not contribute to the multiplex
sub_state = state.sub_state_by_gene_name(*self.expression.variables)
# If this state is not in th... | python | def is_active(self, state: 'State') -> bool:
""" Return True if the multiplex is active in the given state, false otherwise. """
# Remove the genes which does not contribute to the multiplex
sub_state = state.sub_state_by_gene_name(*self.expression.variables)
# If this state is not in th... | [
"def",
"is_active",
"(",
"self",
",",
"state",
":",
"'State'",
")",
"->",
"bool",
":",
"sub_state",
"=",
"state",
".",
"sub_state_by_gene_name",
"(",
"*",
"self",
".",
"expression",
".",
"variables",
")",
"if",
"sub_state",
"not",
"in",
"self",
".",
"_is... | Return True if the multiplex is active in the given state, false otherwise. | [
"Return",
"True",
"if",
"the",
"multiplex",
"is",
"active",
"in",
"the",
"given",
"state",
"false",
"otherwise",
"."
] | f37a2f9358c1ce49f21c4a868b904da5dcd4614f | https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/discrete_model/multiplex.py#L21-L30 | train |
aacanakin/glim | glim/core.py | Registry.get | def get(self, key):
"""
Function deeply gets the key with "." notation
Args
----
key (string): A key with the "." notation.
Returns
-------
reg (unknown type): Returns a dict or a primitive
type.
"""
try:
layer... | python | def get(self, key):
"""
Function deeply gets the key with "." notation
Args
----
key (string): A key with the "." notation.
Returns
-------
reg (unknown type): Returns a dict or a primitive
type.
"""
try:
layer... | [
"def",
"get",
"(",
"self",
",",
"key",
")",
":",
"try",
":",
"layers",
"=",
"key",
".",
"split",
"(",
"'.'",
")",
"value",
"=",
"self",
".",
"registrar",
"for",
"key",
"in",
"layers",
":",
"value",
"=",
"value",
"[",
"key",
"]",
"return",
"value"... | Function deeply gets the key with "." notation
Args
----
key (string): A key with the "." notation.
Returns
-------
reg (unknown type): Returns a dict or a primitive
type. | [
"Function",
"deeply",
"gets",
"the",
"key",
"with",
".",
"notation"
] | 71a20ac149a1292c0d6c1dc7414985ea51854f7a | https://github.com/aacanakin/glim/blob/71a20ac149a1292c0d6c1dc7414985ea51854f7a/glim/core.py#L34-L54 | train |
aacanakin/glim | glim/core.py | Registry.set | def set(self, key, value):
"""
Function deeply sets the key with "." notation
Args
----
key (string): A key with the "." notation.
value (unknown type): A dict or a primitive type.
"""
target = self.registrar
for element in key.split('.')[:-1]... | python | def set(self, key, value):
"""
Function deeply sets the key with "." notation
Args
----
key (string): A key with the "." notation.
value (unknown type): A dict or a primitive type.
"""
target = self.registrar
for element in key.split('.')[:-1]... | [
"def",
"set",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"target",
"=",
"self",
".",
"registrar",
"for",
"element",
"in",
"key",
".",
"split",
"(",
"'.'",
")",
"[",
":",
"-",
"1",
"]",
":",
"target",
"=",
"target",
".",
"setdefault",
"(",
... | Function deeply sets the key with "." notation
Args
----
key (string): A key with the "." notation.
value (unknown type): A dict or a primitive type. | [
"Function",
"deeply",
"sets",
"the",
"key",
"with",
".",
"notation"
] | 71a20ac149a1292c0d6c1dc7414985ea51854f7a | https://github.com/aacanakin/glim/blob/71a20ac149a1292c0d6c1dc7414985ea51854f7a/glim/core.py#L56-L68 | train |
aacanakin/glim | glim/core.py | Facade.boot | def boot(cls, *args, **kwargs):
"""
Function creates the instance of accessor with dynamic
positional & keyword arguments.
Args
----
args (positional arguments): the positional arguments
that are passed to the class of accessor.
kwargs (keyword ar... | python | def boot(cls, *args, **kwargs):
"""
Function creates the instance of accessor with dynamic
positional & keyword arguments.
Args
----
args (positional arguments): the positional arguments
that are passed to the class of accessor.
kwargs (keyword ar... | [
"def",
"boot",
"(",
"cls",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"if",
"cls",
".",
"accessor",
"is",
"not",
"None",
":",
"if",
"cls",
".",
"instance",
"is",
"None",
":",
"cls",
".",
"instance",
"=",
"cls",
".",
"accessor",
"(",
"*",
... | Function creates the instance of accessor with dynamic
positional & keyword arguments.
Args
----
args (positional arguments): the positional arguments
that are passed to the class of accessor.
kwargs (keyword arguments): the keyword arguments
that are... | [
"Function",
"creates",
"the",
"instance",
"of",
"accessor",
"with",
"dynamic",
"positional",
"&",
"keyword",
"arguments",
"."
] | 71a20ac149a1292c0d6c1dc7414985ea51854f7a | https://github.com/aacanakin/glim/blob/71a20ac149a1292c0d6c1dc7414985ea51854f7a/glim/core.py#L150-L164 | train |
aacanakin/glim | glim/core.py | Facade.register | def register(cls, config={}):
"""
This function is basically a shortcut of boot for accessors
that have only the config dict argument.
Args
----
config (dict): the configuration dictionary
"""
if cls.accessor is not None:
if cls.instance is ... | python | def register(cls, config={}):
"""
This function is basically a shortcut of boot for accessors
that have only the config dict argument.
Args
----
config (dict): the configuration dictionary
"""
if cls.accessor is not None:
if cls.instance is ... | [
"def",
"register",
"(",
"cls",
",",
"config",
"=",
"{",
"}",
")",
":",
"if",
"cls",
".",
"accessor",
"is",
"not",
"None",
":",
"if",
"cls",
".",
"instance",
"is",
"None",
":",
"cls",
".",
"instance",
"=",
"cls",
".",
"accessor",
"(",
"config",
")... | This function is basically a shortcut of boot for accessors
that have only the config dict argument.
Args
----
config (dict): the configuration dictionary | [
"This",
"function",
"is",
"basically",
"a",
"shortcut",
"of",
"boot",
"for",
"accessors",
"that",
"have",
"only",
"the",
"config",
"dict",
"argument",
"."
] | 71a20ac149a1292c0d6c1dc7414985ea51854f7a | https://github.com/aacanakin/glim/blob/71a20ac149a1292c0d6c1dc7414985ea51854f7a/glim/core.py#L167-L178 | train |
Kortemme-Lab/klab | klab/bio/complexes.py | ProteinProteinComplex.get_complex | def get_complex(self):
'''Returns the record for the complex definition to be used for database storage.'''
d = dict(
LName = self.lname,
LShortName = self.lshortname,
LHTMLName = self.lhtmlname,
RName = self.rname,
RShortName = self.rshortname... | python | def get_complex(self):
'''Returns the record for the complex definition to be used for database storage.'''
d = dict(
LName = self.lname,
LShortName = self.lshortname,
LHTMLName = self.lhtmlname,
RName = self.rname,
RShortName = self.rshortname... | [
"def",
"get_complex",
"(",
"self",
")",
":",
"d",
"=",
"dict",
"(",
"LName",
"=",
"self",
".",
"lname",
",",
"LShortName",
"=",
"self",
".",
"lshortname",
",",
"LHTMLName",
"=",
"self",
".",
"lhtmlname",
",",
"RName",
"=",
"self",
".",
"rname",
",",
... | Returns the record for the complex definition to be used for database storage. | [
"Returns",
"the",
"record",
"for",
"the",
"complex",
"definition",
"to",
"be",
"used",
"for",
"database",
"storage",
"."
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/complexes.py#L143-L162 | train |
Kortemme-Lab/klab | klab/bio/complexes.py | ProteinProteinComplex.get_pdb_sets | def get_pdb_sets(self):
'''Return a record to be used for database storage. This only makes sense if self.id is set. See usage example
above.'''
assert(self.id != None)
data = []
for pdb_set in self.pdb_sets:
pdb_set_record = dict(
PPComplexID = ... | python | def get_pdb_sets(self):
'''Return a record to be used for database storage. This only makes sense if self.id is set. See usage example
above.'''
assert(self.id != None)
data = []
for pdb_set in self.pdb_sets:
pdb_set_record = dict(
PPComplexID = ... | [
"def",
"get_pdb_sets",
"(",
"self",
")",
":",
"assert",
"(",
"self",
".",
"id",
"!=",
"None",
")",
"data",
"=",
"[",
"]",
"for",
"pdb_set",
"in",
"self",
".",
"pdb_sets",
":",
"pdb_set_record",
"=",
"dict",
"(",
"PPComplexID",
"=",
"self",
".",
"id",... | Return a record to be used for database storage. This only makes sense if self.id is set. See usage example
above. | [
"Return",
"a",
"record",
"to",
"be",
"used",
"for",
"database",
"storage",
".",
"This",
"only",
"makes",
"sense",
"if",
"self",
".",
"id",
"is",
"set",
".",
"See",
"usage",
"example",
"above",
"."
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/complexes.py#L166-L196 | train |
Kortemme-Lab/klab | klab/parsers/xml.py | parse_singular_float | def parse_singular_float(t, tag_name):
'''Parses the sole floating point value with name tag_name in tag t. Heavy-handed with the asserts.'''
pos = t.getElementsByTagName(tag_name)
assert(len(pos) == 1)
pos = pos[0]
assert(len(pos.childNodes) == 1)
return float(pos.childNodes[0].data) | python | def parse_singular_float(t, tag_name):
'''Parses the sole floating point value with name tag_name in tag t. Heavy-handed with the asserts.'''
pos = t.getElementsByTagName(tag_name)
assert(len(pos) == 1)
pos = pos[0]
assert(len(pos.childNodes) == 1)
return float(pos.childNodes[0].data) | [
"def",
"parse_singular_float",
"(",
"t",
",",
"tag_name",
")",
":",
"pos",
"=",
"t",
".",
"getElementsByTagName",
"(",
"tag_name",
")",
"assert",
"(",
"len",
"(",
"pos",
")",
"==",
"1",
")",
"pos",
"=",
"pos",
"[",
"0",
"]",
"assert",
"(",
"len",
"... | Parses the sole floating point value with name tag_name in tag t. Heavy-handed with the asserts. | [
"Parses",
"the",
"sole",
"floating",
"point",
"value",
"with",
"name",
"tag_name",
"in",
"tag",
"t",
".",
"Heavy",
"-",
"handed",
"with",
"the",
"asserts",
"."
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/parsers/xml.py#L14-L20 | train |
Kortemme-Lab/klab | klab/parsers/xml.py | parse_singular_int | def parse_singular_int(t, tag_name):
'''Parses the sole integer value with name tag_name in tag t. Heavy-handed with the asserts.'''
pos = t.getElementsByTagName(tag_name)
assert(len(pos) == 1)
pos = pos[0]
assert(len(pos.childNodes) == 1)
v = pos.childNodes[0].data
assert(v.isdigit()) # no ... | python | def parse_singular_int(t, tag_name):
'''Parses the sole integer value with name tag_name in tag t. Heavy-handed with the asserts.'''
pos = t.getElementsByTagName(tag_name)
assert(len(pos) == 1)
pos = pos[0]
assert(len(pos.childNodes) == 1)
v = pos.childNodes[0].data
assert(v.isdigit()) # no ... | [
"def",
"parse_singular_int",
"(",
"t",
",",
"tag_name",
")",
":",
"pos",
"=",
"t",
".",
"getElementsByTagName",
"(",
"tag_name",
")",
"assert",
"(",
"len",
"(",
"pos",
")",
"==",
"1",
")",
"pos",
"=",
"pos",
"[",
"0",
"]",
"assert",
"(",
"len",
"("... | Parses the sole integer value with name tag_name in tag t. Heavy-handed with the asserts. | [
"Parses",
"the",
"sole",
"integer",
"value",
"with",
"name",
"tag_name",
"in",
"tag",
"t",
".",
"Heavy",
"-",
"handed",
"with",
"the",
"asserts",
"."
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/parsers/xml.py#L22-L30 | train |
Kortemme-Lab/klab | klab/parsers/xml.py | parse_singular_alphabetic_character | def parse_singular_alphabetic_character(t, tag_name):
'''Parses the sole alphabetic character value with name tag_name in tag t. Heavy-handed with the asserts.'''
pos = t.getElementsByTagName(tag_name)
assert(len(pos) == 1)
pos = pos[0]
assert(len(pos.childNodes) == 1)
v = pos.childNodes[0].data... | python | def parse_singular_alphabetic_character(t, tag_name):
'''Parses the sole alphabetic character value with name tag_name in tag t. Heavy-handed with the asserts.'''
pos = t.getElementsByTagName(tag_name)
assert(len(pos) == 1)
pos = pos[0]
assert(len(pos.childNodes) == 1)
v = pos.childNodes[0].data... | [
"def",
"parse_singular_alphabetic_character",
"(",
"t",
",",
"tag_name",
")",
":",
"pos",
"=",
"t",
".",
"getElementsByTagName",
"(",
"tag_name",
")",
"assert",
"(",
"len",
"(",
"pos",
")",
"==",
"1",
")",
"pos",
"=",
"pos",
"[",
"0",
"]",
"assert",
"(... | Parses the sole alphabetic character value with name tag_name in tag t. Heavy-handed with the asserts. | [
"Parses",
"the",
"sole",
"alphabetic",
"character",
"value",
"with",
"name",
"tag_name",
"in",
"tag",
"t",
".",
"Heavy",
"-",
"handed",
"with",
"the",
"asserts",
"."
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/parsers/xml.py#L32-L40 | train |
Kortemme-Lab/klab | klab/parsers/xml.py | parse_singular_string | def parse_singular_string(t, tag_name):
'''Parses the sole string value with name tag_name in tag t. Heavy-handed with the asserts.'''
pos = t.getElementsByTagName(tag_name)
assert(len(pos) == 1)
pos = pos[0]
assert(len(pos.childNodes) == 1)
return pos.childNodes[0].data | python | def parse_singular_string(t, tag_name):
'''Parses the sole string value with name tag_name in tag t. Heavy-handed with the asserts.'''
pos = t.getElementsByTagName(tag_name)
assert(len(pos) == 1)
pos = pos[0]
assert(len(pos.childNodes) == 1)
return pos.childNodes[0].data | [
"def",
"parse_singular_string",
"(",
"t",
",",
"tag_name",
")",
":",
"pos",
"=",
"t",
".",
"getElementsByTagName",
"(",
"tag_name",
")",
"assert",
"(",
"len",
"(",
"pos",
")",
"==",
"1",
")",
"pos",
"=",
"pos",
"[",
"0",
"]",
"assert",
"(",
"len",
... | Parses the sole string value with name tag_name in tag t. Heavy-handed with the asserts. | [
"Parses",
"the",
"sole",
"string",
"value",
"with",
"name",
"tag_name",
"in",
"tag",
"t",
".",
"Heavy",
"-",
"handed",
"with",
"the",
"asserts",
"."
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/parsers/xml.py#L42-L48 | train |
CodersOfTheNight/oshino | oshino/util.py | timer | def timer():
"""
Timer used for calculate time elapsed
"""
if sys.platform == "win32":
default_timer = time.clock
else:
default_timer = time.time
return default_timer() | python | def timer():
"""
Timer used for calculate time elapsed
"""
if sys.platform == "win32":
default_timer = time.clock
else:
default_timer = time.time
return default_timer() | [
"def",
"timer",
"(",
")",
":",
"if",
"sys",
".",
"platform",
"==",
"\"win32\"",
":",
"default_timer",
"=",
"time",
".",
"clock",
"else",
":",
"default_timer",
"=",
"time",
".",
"time",
"return",
"default_timer",
"(",
")"
] | Timer used for calculate time elapsed | [
"Timer",
"used",
"for",
"calculate",
"time",
"elapsed"
] | 00f7e151e3ce1f3a7f43b353b695c4dba83c7f28 | https://github.com/CodersOfTheNight/oshino/blob/00f7e151e3ce1f3a7f43b353b695c4dba83c7f28/oshino/util.py#L20-L29 | train |
adaptive-learning/proso-apps | proso/rand.py | roulette | def roulette(weights, n):
"""
Choose randomly the given number of items. The probability the item is
chosen is proportionate to its weight.
.. testsetup::
import random
from proso.rand import roulette
random.seed(1)
.. testcode::
print(roulette({'cat': 2, 'dog': ... | python | def roulette(weights, n):
"""
Choose randomly the given number of items. The probability the item is
chosen is proportionate to its weight.
.. testsetup::
import random
from proso.rand import roulette
random.seed(1)
.. testcode::
print(roulette({'cat': 2, 'dog': ... | [
"def",
"roulette",
"(",
"weights",
",",
"n",
")",
":",
"if",
"n",
">",
"len",
"(",
"weights",
")",
":",
"raise",
"Exception",
"(",
"\"Can't choose {} samples from {} items\"",
".",
"format",
"(",
"n",
",",
"len",
"(",
"weights",
")",
")",
")",
"if",
"a... | Choose randomly the given number of items. The probability the item is
chosen is proportionate to its weight.
.. testsetup::
import random
from proso.rand import roulette
random.seed(1)
.. testcode::
print(roulette({'cat': 2, 'dog': 1000}, 1))
.. testoutput::
... | [
"Choose",
"randomly",
"the",
"given",
"number",
"of",
"items",
".",
"The",
"probability",
"the",
"item",
"is",
"chosen",
"is",
"proportionate",
"to",
"its",
"weight",
"."
] | 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso/rand.py#L9-L54 | train |
ethan92429/onshapepy | onshapepy/uri.py | Uri.as_dict | def as_dict(self):
""" Return the URI object as a dictionary"""
d = {k:v for (k,v) in self.__dict__.items()}
return d | python | def as_dict(self):
""" Return the URI object as a dictionary"""
d = {k:v for (k,v) in self.__dict__.items()}
return d | [
"def",
"as_dict",
"(",
"self",
")",
":",
"d",
"=",
"{",
"k",
":",
"v",
"for",
"(",
"k",
",",
"v",
")",
"in",
"self",
".",
"__dict__",
".",
"items",
"(",
")",
"}",
"return",
"d"
] | Return the URI object as a dictionary | [
"Return",
"the",
"URI",
"object",
"as",
"a",
"dictionary"
] | 61dc7ccbdc6095fa6cc3b4a414e2f72d03d1c9df | https://github.com/ethan92429/onshapepy/blob/61dc7ccbdc6095fa6cc3b4a414e2f72d03d1c9df/onshapepy/uri.py#L53-L56 | train |
andialbrecht/sentry-comments | sentry_comments/plugin.py | CommentsPlugin.get_title | def get_title(self, group=None):
"""Adds number of comments to title."""
title = super(CommentsPlugin, self).get_title()
if group is not None:
count = GroupComments.objects.filter(group=group).count()
else:
count = None
if count:
title = u'%s (... | python | def get_title(self, group=None):
"""Adds number of comments to title."""
title = super(CommentsPlugin, self).get_title()
if group is not None:
count = GroupComments.objects.filter(group=group).count()
else:
count = None
if count:
title = u'%s (... | [
"def",
"get_title",
"(",
"self",
",",
"group",
"=",
"None",
")",
":",
"title",
"=",
"super",
"(",
"CommentsPlugin",
",",
"self",
")",
".",
"get_title",
"(",
")",
"if",
"group",
"is",
"not",
"None",
":",
"count",
"=",
"GroupComments",
".",
"objects",
... | Adds number of comments to title. | [
"Adds",
"number",
"of",
"comments",
"to",
"title",
"."
] | b9319320dc3b25b6d813377e69b2d379bcbf6197 | https://github.com/andialbrecht/sentry-comments/blob/b9319320dc3b25b6d813377e69b2d379bcbf6197/sentry_comments/plugin.py#L38-L47 | train |
andialbrecht/sentry-comments | sentry_comments/plugin.py | CommentsPlugin.view | def view(self, request, group, **kwargs):
"""Display and store comments."""
if request.method == 'POST':
message = request.POST.get('message')
if message is not None and message.strip():
comment = GroupComments(group=group, author=request.user,
... | python | def view(self, request, group, **kwargs):
"""Display and store comments."""
if request.method == 'POST':
message = request.POST.get('message')
if message is not None and message.strip():
comment = GroupComments(group=group, author=request.user,
... | [
"def",
"view",
"(",
"self",
",",
"request",
",",
"group",
",",
"**",
"kwargs",
")",
":",
"if",
"request",
".",
"method",
"==",
"'POST'",
":",
"message",
"=",
"request",
".",
"POST",
".",
"get",
"(",
"'message'",
")",
"if",
"message",
"is",
"not",
"... | Display and store comments. | [
"Display",
"and",
"store",
"comments",
"."
] | b9319320dc3b25b6d813377e69b2d379bcbf6197 | https://github.com/andialbrecht/sentry-comments/blob/b9319320dc3b25b6d813377e69b2d379bcbf6197/sentry_comments/plugin.py#L49-L69 | train |
TheGhouls/oct | oct/results/output.py | generate_graphs | def generate_graphs(data, name, results_dir):
"""Generate all reports from original dataframe
:param dic data: dict containing raw and compiled results dataframes
:param str name: name for prefixing graphs output
:param str results_dir: results output directory
"""
graphs.resp_graph_raw(data['r... | python | def generate_graphs(data, name, results_dir):
"""Generate all reports from original dataframe
:param dic data: dict containing raw and compiled results dataframes
:param str name: name for prefixing graphs output
:param str results_dir: results output directory
"""
graphs.resp_graph_raw(data['r... | [
"def",
"generate_graphs",
"(",
"data",
",",
"name",
",",
"results_dir",
")",
":",
"graphs",
".",
"resp_graph_raw",
"(",
"data",
"[",
"'raw'",
"]",
",",
"name",
"+",
"'_response_times.svg'",
",",
"results_dir",
")",
"graphs",
".",
"resp_graph",
"(",
"data",
... | Generate all reports from original dataframe
:param dic data: dict containing raw and compiled results dataframes
:param str name: name for prefixing graphs output
:param str results_dir: results output directory | [
"Generate",
"all",
"reports",
"from",
"original",
"dataframe"
] | 7e9bddeb3b8495a26442b1c86744e9fb187fe88f | https://github.com/TheGhouls/oct/blob/7e9bddeb3b8495a26442b1c86744e9fb187fe88f/oct/results/output.py#L12-L21 | train |
TheGhouls/oct | oct/results/output.py | print_infos | def print_infos(results):
"""Print informations in standard output
:param ReportResults results: the report result containing all compiled informations
"""
print('transactions: %i' % results.total_transactions)
print('timers: %i' % results.total_timers)
print('errors: %i' % results.total_errors... | python | def print_infos(results):
"""Print informations in standard output
:param ReportResults results: the report result containing all compiled informations
"""
print('transactions: %i' % results.total_transactions)
print('timers: %i' % results.total_timers)
print('errors: %i' % results.total_errors... | [
"def",
"print_infos",
"(",
"results",
")",
":",
"print",
"(",
"'transactions: %i'",
"%",
"results",
".",
"total_transactions",
")",
"print",
"(",
"'timers: %i'",
"%",
"results",
".",
"total_timers",
")",
"print",
"(",
"'errors: %i'",
"%",
"results",
".",
"tota... | Print informations in standard output
:param ReportResults results: the report result containing all compiled informations | [
"Print",
"informations",
"in",
"standard",
"output"
] | 7e9bddeb3b8495a26442b1c86744e9fb187fe88f | https://github.com/TheGhouls/oct/blob/7e9bddeb3b8495a26442b1c86744e9fb187fe88f/oct/results/output.py#L24-L33 | train |
TheGhouls/oct | oct/results/output.py | write_template | def write_template(data, results_dir, parent):
"""Write the html template
:param dict data: the dict containing all data for output
:param str results_dir: the ouput directory for results
:param str parent: the parent directory
"""
print("Generating html report...")
partial = time.time()
... | python | def write_template(data, results_dir, parent):
"""Write the html template
:param dict data: the dict containing all data for output
:param str results_dir: the ouput directory for results
:param str parent: the parent directory
"""
print("Generating html report...")
partial = time.time()
... | [
"def",
"write_template",
"(",
"data",
",",
"results_dir",
",",
"parent",
")",
":",
"print",
"(",
"\"Generating html report...\"",
")",
"partial",
"=",
"time",
".",
"time",
"(",
")",
"j_env",
"=",
"Environment",
"(",
"loader",
"=",
"FileSystemLoader",
"(",
"o... | Write the html template
:param dict data: the dict containing all data for output
:param str results_dir: the ouput directory for results
:param str parent: the parent directory | [
"Write",
"the",
"html",
"template"
] | 7e9bddeb3b8495a26442b1c86744e9fb187fe88f | https://github.com/TheGhouls/oct/blob/7e9bddeb3b8495a26442b1c86744e9fb187fe88f/oct/results/output.py#L36-L50 | train |
TheGhouls/oct | oct/results/output.py | output | def output(results_dir, config, parent='../../'):
"""Write the results output for the given test
:param str results_dir: the directory for the results
:param dict config: the configuration of the test
:param str parents: the parent directory
"""
start = time.time()
print("Compiling results.... | python | def output(results_dir, config, parent='../../'):
"""Write the results output for the given test
:param str results_dir: the directory for the results
:param dict config: the configuration of the test
:param str parents: the parent directory
"""
start = time.time()
print("Compiling results.... | [
"def",
"output",
"(",
"results_dir",
",",
"config",
",",
"parent",
"=",
"'../../'",
")",
":",
"start",
"=",
"time",
".",
"time",
"(",
")",
"print",
"(",
"\"Compiling results...\"",
")",
"results_dir",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"results... | Write the results output for the given test
:param str results_dir: the directory for the results
:param dict config: the configuration of the test
:param str parents: the parent directory | [
"Write",
"the",
"results",
"output",
"for",
"the",
"given",
"test"
] | 7e9bddeb3b8495a26442b1c86744e9fb187fe88f | https://github.com/TheGhouls/oct/blob/7e9bddeb3b8495a26442b1c86744e9fb187fe88f/oct/results/output.py#L53-L91 | train |
Kortemme-Lab/klab | klab/klfilesystem.py | safeMkdir | def safeMkdir(p, permissions = permissions755):
'''Wrapper around os.mkdir which does not raise an error if the directory exists.'''
try:
os.mkdir(p)
except OSError:
pass
os.chmod(p, permissions) | python | def safeMkdir(p, permissions = permissions755):
'''Wrapper around os.mkdir which does not raise an error if the directory exists.'''
try:
os.mkdir(p)
except OSError:
pass
os.chmod(p, permissions) | [
"def",
"safeMkdir",
"(",
"p",
",",
"permissions",
"=",
"permissions755",
")",
":",
"try",
":",
"os",
".",
"mkdir",
"(",
"p",
")",
"except",
"OSError",
":",
"pass",
"os",
".",
"chmod",
"(",
"p",
",",
"permissions",
")"
] | Wrapper around os.mkdir which does not raise an error if the directory exists. | [
"Wrapper",
"around",
"os",
".",
"mkdir",
"which",
"does",
"not",
"raise",
"an",
"error",
"if",
"the",
"directory",
"exists",
"."
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/klfilesystem.py#L107-L113 | train |
projectshift/shift-boiler | boiler/cli/boiler.py | install_dependencies | def install_dependencies(feature=None):
""" Install dependencies for a feature """
import subprocess
echo(green('\nInstall dependencies:'))
echo(green('-' * 40))
req_path = os.path.realpath(os.path.dirname(__file__) + '/../_requirements')
# list all features if no feature name
if not feat... | python | def install_dependencies(feature=None):
""" Install dependencies for a feature """
import subprocess
echo(green('\nInstall dependencies:'))
echo(green('-' * 40))
req_path = os.path.realpath(os.path.dirname(__file__) + '/../_requirements')
# list all features if no feature name
if not feat... | [
"def",
"install_dependencies",
"(",
"feature",
"=",
"None",
")",
":",
"import",
"subprocess",
"echo",
"(",
"green",
"(",
"'\\nInstall dependencies:'",
")",
")",
"echo",
"(",
"green",
"(",
"'-'",
"*",
"40",
")",
")",
"req_path",
"=",
"os",
".",
"path",
".... | Install dependencies for a feature | [
"Install",
"dependencies",
"for",
"a",
"feature"
] | 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/cli/boiler.py#L231-L289 | train |
Kortemme-Lab/klab | klab/bio/blast.py | BLAST._post | def _post(self, xml_query):
'''POST the request.'''
req = urllib2.Request(url = 'http://www.rcsb.org/pdb/rest/search', data=xml_query)
f = urllib2.urlopen(req)
return f.read().strip() | python | def _post(self, xml_query):
'''POST the request.'''
req = urllib2.Request(url = 'http://www.rcsb.org/pdb/rest/search', data=xml_query)
f = urllib2.urlopen(req)
return f.read().strip() | [
"def",
"_post",
"(",
"self",
",",
"xml_query",
")",
":",
"req",
"=",
"urllib2",
".",
"Request",
"(",
"url",
"=",
"'http://www.rcsb.org/pdb/rest/search'",
",",
"data",
"=",
"xml_query",
")",
"f",
"=",
"urllib2",
".",
"urlopen",
"(",
"req",
")",
"return",
... | POST the request. | [
"POST",
"the",
"request",
"."
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/blast.py#L222-L226 | train |
uogbuji/versa | tools/py/contrib/datachefids.py | simple_hashstring | def simple_hashstring(obj, bits=64):
'''
Creates a simple hash in brief string form from obj
bits is an optional bit width, defaulting to 64, and should be in multiples of 8 with a maximum of 64
>>> from bibframe.contrib.datachefids import simple_hashstring
>>> simple_hashstring("The quick brown fo... | python | def simple_hashstring(obj, bits=64):
'''
Creates a simple hash in brief string form from obj
bits is an optional bit width, defaulting to 64, and should be in multiples of 8 with a maximum of 64
>>> from bibframe.contrib.datachefids import simple_hashstring
>>> simple_hashstring("The quick brown fo... | [
"def",
"simple_hashstring",
"(",
"obj",
",",
"bits",
"=",
"64",
")",
":",
"basis",
"=",
"mmh3",
".",
"hash64",
"(",
"str",
"(",
"obj",
")",
")",
"[",
"0",
"]",
">>",
"(",
"64",
"-",
"bits",
")",
"if",
"bits",
"==",
"64",
":",
"raw_hash",
"=",
... | Creates a simple hash in brief string form from obj
bits is an optional bit width, defaulting to 64, and should be in multiples of 8 with a maximum of 64
>>> from bibframe.contrib.datachefids import simple_hashstring
>>> simple_hashstring("The quick brown fox jumps over the lazy dog")
'bBsHvHu8S-M'
... | [
"Creates",
"a",
"simple",
"hash",
"in",
"brief",
"string",
"form",
"from",
"obj",
"bits",
"is",
"an",
"optional",
"bit",
"width",
"defaulting",
"to",
"64",
"and",
"should",
"be",
"in",
"multiples",
"of",
"8",
"with",
"a",
"maximum",
"of",
"64"
] | f092ffc7ed363a5b170890955168500f32de0dd5 | https://github.com/uogbuji/versa/blob/f092ffc7ed363a5b170890955168500f32de0dd5/tools/py/contrib/datachefids.py#L35-L55 | train |
uogbuji/versa | tools/py/contrib/datachefids.py | create_slug | def create_slug(title, plain_len=None):
'''
Tries to create a slug from a title, trading off collision risk with readability and minimized cruft
title - a unicode object with a title to use as basis of the slug
plain_len - the maximum character length preserved (from the beginning) of the title
>>... | python | def create_slug(title, plain_len=None):
'''
Tries to create a slug from a title, trading off collision risk with readability and minimized cruft
title - a unicode object with a title to use as basis of the slug
plain_len - the maximum character length preserved (from the beginning) of the title
>>... | [
"def",
"create_slug",
"(",
"title",
",",
"plain_len",
"=",
"None",
")",
":",
"if",
"plain_len",
":",
"title",
"=",
"title",
"[",
":",
"plain_len",
"]",
"pass1",
"=",
"OMIT_FROM_SLUG_PAT",
".",
"sub",
"(",
"'_'",
",",
"title",
")",
".",
"lower",
"(",
... | Tries to create a slug from a title, trading off collision risk with readability and minimized cruft
title - a unicode object with a title to use as basis of the slug
plain_len - the maximum character length preserved (from the beginning) of the title
>>> from versa.contrib.datachefids import create_slug
... | [
"Tries",
"to",
"create",
"a",
"slug",
"from",
"a",
"title",
"trading",
"off",
"collision",
"risk",
"with",
"readability",
"and",
"minimized",
"cruft"
] | f092ffc7ed363a5b170890955168500f32de0dd5 | https://github.com/uogbuji/versa/blob/f092ffc7ed363a5b170890955168500f32de0dd5/tools/py/contrib/datachefids.py#L58-L73 | train |
peergradeio/flask-mongo-profiler | flask_mongo_profiler/contrib/flask_admin/formatters/profiling.py | profiling_query_formatter | def profiling_query_formatter(view, context, query_document, name):
"""Format a ProfilingQuery entry for a ProfilingRequest detail field
Parameters
----------
query_document : model.ProfilingQuery
"""
return Markup(
''.join(
[
'<div class="pymongo-query row">... | python | def profiling_query_formatter(view, context, query_document, name):
"""Format a ProfilingQuery entry for a ProfilingRequest detail field
Parameters
----------
query_document : model.ProfilingQuery
"""
return Markup(
''.join(
[
'<div class="pymongo-query row">... | [
"def",
"profiling_query_formatter",
"(",
"view",
",",
"context",
",",
"query_document",
",",
"name",
")",
":",
"return",
"Markup",
"(",
"''",
".",
"join",
"(",
"[",
"'<div class=\"pymongo-query row\">'",
",",
"'<div class=\"col-md-1\">'",
",",
"'<a href=\"{}\">'",
"... | Format a ProfilingQuery entry for a ProfilingRequest detail field
Parameters
----------
query_document : model.ProfilingQuery | [
"Format",
"a",
"ProfilingQuery",
"entry",
"for",
"a",
"ProfilingRequest",
"detail",
"field"
] | a267eeb49fea07c9a24fb370bd9d7a90ed313ccf | https://github.com/peergradeio/flask-mongo-profiler/blob/a267eeb49fea07c9a24fb370bd9d7a90ed313ccf/flask_mongo_profiler/contrib/flask_admin/formatters/profiling.py#L94-L127 | train |
trendels/rhino | rhino/resource.py | make_response | def make_response(obj):
"""Try to coerce an object into a Response object."""
if obj is None:
raise TypeError("Handler return value cannot be None.")
if isinstance(obj, Response):
return obj
return Response(200, body=obj) | python | def make_response(obj):
"""Try to coerce an object into a Response object."""
if obj is None:
raise TypeError("Handler return value cannot be None.")
if isinstance(obj, Response):
return obj
return Response(200, body=obj) | [
"def",
"make_response",
"(",
"obj",
")",
":",
"if",
"obj",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"\"Handler return value cannot be None.\"",
")",
"if",
"isinstance",
"(",
"obj",
",",
"Response",
")",
":",
"return",
"obj",
"return",
"Response",
"(",
"... | Try to coerce an object into a Response object. | [
"Try",
"to",
"coerce",
"an",
"object",
"into",
"a",
"Response",
"object",
"."
] | f1f0ef21b6080a2bd130b38b5bef163074c94aed | https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/resource.py#L90-L96 | train |
trendels/rhino | rhino/resource.py | resolve_handler | def resolve_handler(request, view_handlers):
"""Select a suitable handler to handle the request.
Returns a (handler, vary) tuple, where handler is a handler_metadata tuple
and vary is a set containing header names that were used during content
negotiation and that should be included in the 'Vary' heade... | python | def resolve_handler(request, view_handlers):
"""Select a suitable handler to handle the request.
Returns a (handler, vary) tuple, where handler is a handler_metadata tuple
and vary is a set containing header names that were used during content
negotiation and that should be included in the 'Vary' heade... | [
"def",
"resolve_handler",
"(",
"request",
",",
"view_handlers",
")",
":",
"view",
"=",
"None",
"if",
"request",
".",
"_context",
":",
"route_name",
"=",
"request",
".",
"_context",
"[",
"-",
"1",
"]",
".",
"route",
".",
"name",
"if",
"route_name",
"and",... | Select a suitable handler to handle the request.
Returns a (handler, vary) tuple, where handler is a handler_metadata tuple
and vary is a set containing header names that were used during content
negotiation and that should be included in the 'Vary' header of the
outgoing response.
When no suitabl... | [
"Select",
"a",
"suitable",
"handler",
"to",
"handle",
"the",
"request",
"."
] | f1f0ef21b6080a2bd130b38b5bef163074c94aed | https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/resource.py#L99-L151 | train |
trendels/rhino | rhino/resource.py | negotiate_content_type | def negotiate_content_type(content_type, handlers):
"""Filter handlers that accept a given content-type.
Finds the most specific media-range that matches `content_type`, and
returns those handlers that accept it.
"""
accepted = [h.accepts for h in handlers]
scored_ranges = [(mimeparse.fitness_a... | python | def negotiate_content_type(content_type, handlers):
"""Filter handlers that accept a given content-type.
Finds the most specific media-range that matches `content_type`, and
returns those handlers that accept it.
"""
accepted = [h.accepts for h in handlers]
scored_ranges = [(mimeparse.fitness_a... | [
"def",
"negotiate_content_type",
"(",
"content_type",
",",
"handlers",
")",
":",
"accepted",
"=",
"[",
"h",
".",
"accepts",
"for",
"h",
"in",
"handlers",
"]",
"scored_ranges",
"=",
"[",
"(",
"mimeparse",
".",
"fitness_and_quality_parsed",
"(",
"content_type",
... | Filter handlers that accept a given content-type.
Finds the most specific media-range that matches `content_type`, and
returns those handlers that accept it. | [
"Filter",
"handlers",
"that",
"accept",
"a",
"given",
"content",
"-",
"type",
"."
] | f1f0ef21b6080a2bd130b38b5bef163074c94aed | https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/resource.py#L154-L172 | train |
trendels/rhino | rhino/resource.py | negotiate_accept | def negotiate_accept(accept, handlers):
"""Filter handlers that provide an acceptable mime-type.
Finds the best match among handlers given an Accept header, and returns
those handlers that provide the matching mime-type.
"""
provided = [h.provides for h in handlers]
if None in provided:
... | python | def negotiate_accept(accept, handlers):
"""Filter handlers that provide an acceptable mime-type.
Finds the best match among handlers given an Accept header, and returns
those handlers that provide the matching mime-type.
"""
provided = [h.provides for h in handlers]
if None in provided:
... | [
"def",
"negotiate_accept",
"(",
"accept",
",",
"handlers",
")",
":",
"provided",
"=",
"[",
"h",
".",
"provides",
"for",
"h",
"in",
"handlers",
"]",
"if",
"None",
"in",
"provided",
":",
"return",
"[",
"h",
"for",
"h",
"in",
"handlers",
"if",
"h",
".",... | Filter handlers that provide an acceptable mime-type.
Finds the best match among handlers given an Accept header, and returns
those handlers that provide the matching mime-type. | [
"Filter",
"handlers",
"that",
"provide",
"an",
"acceptable",
"mime",
"-",
"type",
"."
] | f1f0ef21b6080a2bd130b38b5bef163074c94aed | https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/resource.py#L175-L199 | train |
trendels/rhino | rhino/request.py | QueryDict.get | def get(self, key, default=None, type=None):
"""Returns the first value for a key.
If `type` is not None, the value will be converted by calling
`type` with the value as argument. If type() raises `ValueError`, it
will be treated as if the value didn't exist, and `default` will be
... | python | def get(self, key, default=None, type=None):
"""Returns the first value for a key.
If `type` is not None, the value will be converted by calling
`type` with the value as argument. If type() raises `ValueError`, it
will be treated as if the value didn't exist, and `default` will be
... | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
",",
"type",
"=",
"None",
")",
":",
"try",
":",
"value",
"=",
"self",
"[",
"key",
"]",
"if",
"type",
"is",
"not",
"None",
":",
"return",
"type",
"(",
"value",
")",
"return",
"v... | Returns the first value for a key.
If `type` is not None, the value will be converted by calling
`type` with the value as argument. If type() raises `ValueError`, it
will be treated as if the value didn't exist, and `default` will be
returned instead. | [
"Returns",
"the",
"first",
"value",
"for",
"a",
"key",
"."
] | f1f0ef21b6080a2bd130b38b5bef163074c94aed | https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/request.py#L91-L105 | train |
trendels/rhino | rhino/request.py | QueryDict.getall | def getall(self, key, type=None):
"""Return a list of values for the given key.
If `type` is not None, all values will be converted by calling `type`
with the value as argument. if type() raises `ValueError`, the value
will not appear in the result list.
"""
values = []
... | python | def getall(self, key, type=None):
"""Return a list of values for the given key.
If `type` is not None, all values will be converted by calling `type`
with the value as argument. if type() raises `ValueError`, the value
will not appear in the result list.
"""
values = []
... | [
"def",
"getall",
"(",
"self",
",",
"key",
",",
"type",
"=",
"None",
")",
":",
"values",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"self",
".",
"_items",
":",
"if",
"k",
"==",
"key",
":",
"if",
"type",
"is",
"not",
"None",
":",
"try",
":",
... | Return a list of values for the given key.
If `type` is not None, all values will be converted by calling `type`
with the value as argument. if type() raises `ValueError`, the value
will not appear in the result list. | [
"Return",
"a",
"list",
"of",
"values",
"for",
"the",
"given",
"key",
"."
] | f1f0ef21b6080a2bd130b38b5bef163074c94aed | https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/request.py#L107-L124 | train |
trendels/rhino | rhino/request.py | Request.url_for | def url_for(*args, **kw):
"""Build the URL for a target route.
The target is the first positional argument, and can be any valid
target for `Mapper.path`, which will be looked up on the current
mapper object and used to build the URL for that route.
Additionally, it can be one o... | python | def url_for(*args, **kw):
"""Build the URL for a target route.
The target is the first positional argument, and can be any valid
target for `Mapper.path`, which will be looked up on the current
mapper object and used to build the URL for that route.
Additionally, it can be one o... | [
"def",
"url_for",
"(",
"*",
"args",
",",
"**",
"kw",
")",
":",
"self",
",",
"target",
",",
"args",
"=",
"args",
"[",
"0",
"]",
",",
"args",
"[",
"1",
"]",
",",
"list",
"(",
"args",
"[",
"2",
":",
"]",
")",
"query",
"=",
"kw",
".",
"pop",
... | Build the URL for a target route.
The target is the first positional argument, and can be any valid
target for `Mapper.path`, which will be looked up on the current
mapper object and used to build the URL for that route.
Additionally, it can be one of:
'.'
: Builds th... | [
"Build",
"the",
"URL",
"for",
"a",
"target",
"route",
"."
] | f1f0ef21b6080a2bd130b38b5bef163074c94aed | https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/request.py#L220-L268 | train |
trendels/rhino | rhino/request.py | Request.input | def input(self):
"""Returns a file-like object representing the request body."""
if self._input is None:
input_file = self.environ['wsgi.input']
content_length = self.content_length or 0
self._input = WsgiInput(input_file, self.content_length)
return self._inp... | python | def input(self):
"""Returns a file-like object representing the request body."""
if self._input is None:
input_file = self.environ['wsgi.input']
content_length = self.content_length or 0
self._input = WsgiInput(input_file, self.content_length)
return self._inp... | [
"def",
"input",
"(",
"self",
")",
":",
"if",
"self",
".",
"_input",
"is",
"None",
":",
"input_file",
"=",
"self",
".",
"environ",
"[",
"'wsgi.input'",
"]",
"content_length",
"=",
"self",
".",
"content_length",
"or",
"0",
"self",
".",
"_input",
"=",
"Ws... | Returns a file-like object representing the request body. | [
"Returns",
"a",
"file",
"-",
"like",
"object",
"representing",
"the",
"request",
"body",
"."
] | f1f0ef21b6080a2bd130b38b5bef163074c94aed | https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/request.py#L364-L370 | train |
trendels/rhino | rhino/request.py | Request.body | def body(self):
"""Reads and returns the entire request body.
On first access, reads `content_length` bytes from `input` and stores
the result on the request object. On subsequent access, returns the
cached value.
"""
if self._body is None:
if self._body_read... | python | def body(self):
"""Reads and returns the entire request body.
On first access, reads `content_length` bytes from `input` and stores
the result on the request object. On subsequent access, returns the
cached value.
"""
if self._body is None:
if self._body_read... | [
"def",
"body",
"(",
"self",
")",
":",
"if",
"self",
".",
"_body",
"is",
"None",
":",
"if",
"self",
".",
"_body_reader",
"is",
"None",
":",
"self",
".",
"_body",
"=",
"self",
".",
"input",
".",
"read",
"(",
"self",
".",
"content_length",
"or",
"0",
... | Reads and returns the entire request body.
On first access, reads `content_length` bytes from `input` and stores
the result on the request object. On subsequent access, returns the
cached value. | [
"Reads",
"and",
"returns",
"the",
"entire",
"request",
"body",
"."
] | f1f0ef21b6080a2bd130b38b5bef163074c94aed | https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/request.py#L373-L385 | train |
trendels/rhino | rhino/request.py | Request.form | def form(self):
"""Reads the request body and tries to parse it as a web form.
Parsing is done using the stdlib's `cgi.FieldStorage` class
which supports multipart forms (file uploads).
Returns a `QueryDict` object holding the form fields. Uploaded files
are represented as form ... | python | def form(self):
"""Reads the request body and tries to parse it as a web form.
Parsing is done using the stdlib's `cgi.FieldStorage` class
which supports multipart forms (file uploads).
Returns a `QueryDict` object holding the form fields. Uploaded files
are represented as form ... | [
"def",
"form",
"(",
"self",
")",
":",
"if",
"self",
".",
"_form",
"is",
"None",
":",
"environ",
"=",
"self",
".",
"environ",
".",
"copy",
"(",
")",
"environ",
"[",
"'QUERY_STRING'",
"]",
"=",
"''",
"environ",
"[",
"'REQUEST_METHOD'",
"]",
"=",
"'POST... | Reads the request body and tries to parse it as a web form.
Parsing is done using the stdlib's `cgi.FieldStorage` class
which supports multipart forms (file uploads).
Returns a `QueryDict` object holding the form fields. Uploaded files
are represented as form fields with a 'filename' at... | [
"Reads",
"the",
"request",
"body",
"and",
"tries",
"to",
"parse",
"it",
"as",
"a",
"web",
"form",
"."
] | f1f0ef21b6080a2bd130b38b5bef163074c94aed | https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/request.py#L389-L418 | train |
trendels/rhino | rhino/request.py | Request.cookies | def cookies(self):
"""Returns a dictionary mapping cookie names to their values."""
if self._cookies is None:
c = SimpleCookie(self.environ.get('HTTP_COOKIE'))
self._cookies = dict([
(k.decode('utf-8'), v.value.decode('utf-8'))
for k, v in c.items(... | python | def cookies(self):
"""Returns a dictionary mapping cookie names to their values."""
if self._cookies is None:
c = SimpleCookie(self.environ.get('HTTP_COOKIE'))
self._cookies = dict([
(k.decode('utf-8'), v.value.decode('utf-8'))
for k, v in c.items(... | [
"def",
"cookies",
"(",
"self",
")",
":",
"if",
"self",
".",
"_cookies",
"is",
"None",
":",
"c",
"=",
"SimpleCookie",
"(",
"self",
".",
"environ",
".",
"get",
"(",
"'HTTP_COOKIE'",
")",
")",
"self",
".",
"_cookies",
"=",
"dict",
"(",
"[",
"(",
"k",
... | Returns a dictionary mapping cookie names to their values. | [
"Returns",
"a",
"dictionary",
"mapping",
"cookie",
"names",
"to",
"their",
"values",
"."
] | f1f0ef21b6080a2bd130b38b5bef163074c94aed | https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/request.py#L421-L429 | train |
reillysiemens/layabout | layabout.py | _format_parameter_error_message | def _format_parameter_error_message(name: str, sig: Signature,
num_params: int) -> str:
"""
Format an error message for missing positional arguments.
Args:
name: The function name.
sig: The function's signature.
num_params: The number of function ... | python | def _format_parameter_error_message(name: str, sig: Signature,
num_params: int) -> str:
"""
Format an error message for missing positional arguments.
Args:
name: The function name.
sig: The function's signature.
num_params: The number of function ... | [
"def",
"_format_parameter_error_message",
"(",
"name",
":",
"str",
",",
"sig",
":",
"Signature",
",",
"num_params",
":",
"int",
")",
"->",
"str",
":",
"if",
"num_params",
"==",
"0",
":",
"plural",
"=",
"'s'",
"missing",
"=",
"2",
"arguments",
"=",
"\"'sl... | Format an error message for missing positional arguments.
Args:
name: The function name.
sig: The function's signature.
num_params: The number of function parameters.
Returns:
str: A formatted error message. | [
"Format",
"an",
"error",
"message",
"for",
"missing",
"positional",
"arguments",
"."
] | a146c47f2558e66bb51cf708d39909b93eaea7f4 | https://github.com/reillysiemens/layabout/blob/a146c47f2558e66bb51cf708d39909b93eaea7f4/layabout.py#L252-L275 | train |
reillysiemens/layabout | layabout.py | _SlackClientWrapper.connect_with_retry | def connect_with_retry(self) -> None:
""" Attempt to connect to the Slack API. Retry on failures. """
if self.is_connected():
log.debug('Already connected to the Slack API')
return
for retry in range(1, self.retries + 1):
self.connect()
if self.is... | python | def connect_with_retry(self) -> None:
""" Attempt to connect to the Slack API. Retry on failures. """
if self.is_connected():
log.debug('Already connected to the Slack API')
return
for retry in range(1, self.retries + 1):
self.connect()
if self.is... | [
"def",
"connect_with_retry",
"(",
"self",
")",
"->",
"None",
":",
"if",
"self",
".",
"is_connected",
"(",
")",
":",
"log",
".",
"debug",
"(",
"'Already connected to the Slack API'",
")",
"return",
"for",
"retry",
"in",
"range",
"(",
"1",
",",
"self",
".",
... | Attempt to connect to the Slack API. Retry on failures. | [
"Attempt",
"to",
"connect",
"to",
"the",
"Slack",
"API",
".",
"Retry",
"on",
"failures",
"."
] | a146c47f2558e66bb51cf708d39909b93eaea7f4 | https://github.com/reillysiemens/layabout/blob/a146c47f2558e66bb51cf708d39909b93eaea7f4/layabout.py#L78-L94 | train |
reillysiemens/layabout | layabout.py | _SlackClientWrapper.fetch_events | def fetch_events(self) -> List[dict]:
""" Fetch new RTM events from the API. """
try:
return self.inner.rtm_read()
# TODO: The TimeoutError could be more elegantly resolved by making
# a PR to the websocket-client library and letting them coerce that
# exception to a... | python | def fetch_events(self) -> List[dict]:
""" Fetch new RTM events from the API. """
try:
return self.inner.rtm_read()
# TODO: The TimeoutError could be more elegantly resolved by making
# a PR to the websocket-client library and letting them coerce that
# exception to a... | [
"def",
"fetch_events",
"(",
"self",
")",
"->",
"List",
"[",
"dict",
"]",
":",
"try",
":",
"return",
"self",
".",
"inner",
".",
"rtm_read",
"(",
")",
"except",
"TimeoutError",
":",
"log",
".",
"debug",
"(",
"'Lost connection to the Slack API, attempting to '",
... | Fetch new RTM events from the API. | [
"Fetch",
"new",
"RTM",
"events",
"from",
"the",
"API",
"."
] | a146c47f2558e66bb51cf708d39909b93eaea7f4 | https://github.com/reillysiemens/layabout/blob/a146c47f2558e66bb51cf708d39909b93eaea7f4/layabout.py#L96-L109 | train |
reillysiemens/layabout | layabout.py | Layabout._ensure_slack | def _ensure_slack(self, connector: Any, retries: int,
backoff: Callable[[int], float]) -> None:
""" Ensure we have a SlackClient. """
connector = self._env_var if connector is None else connector
slack: SlackClient = _create_slack(connector)
self._slack = _SlackClie... | python | def _ensure_slack(self, connector: Any, retries: int,
backoff: Callable[[int], float]) -> None:
""" Ensure we have a SlackClient. """
connector = self._env_var if connector is None else connector
slack: SlackClient = _create_slack(connector)
self._slack = _SlackClie... | [
"def",
"_ensure_slack",
"(",
"self",
",",
"connector",
":",
"Any",
",",
"retries",
":",
"int",
",",
"backoff",
":",
"Callable",
"[",
"[",
"int",
"]",
",",
"float",
"]",
")",
"->",
"None",
":",
"connector",
"=",
"self",
".",
"_env_var",
"if",
"connect... | Ensure we have a SlackClient. | [
"Ensure",
"we",
"have",
"a",
"SlackClient",
"."
] | a146c47f2558e66bb51cf708d39909b93eaea7f4 | https://github.com/reillysiemens/layabout/blob/a146c47f2558e66bb51cf708d39909b93eaea7f4/layabout.py#L177-L186 | train |
reillysiemens/layabout | layabout.py | Layabout.run | def run(self, *,
connector: Union[EnvVar, Token, SlackClient, None] = None,
interval: float = 0.5, retries: int = 16,
backoff: Callable[[int], float] = None,
until: Callable[[List[dict]], bool] = None) -> None:
"""
Connect to the Slack API and run the even... | python | def run(self, *,
connector: Union[EnvVar, Token, SlackClient, None] = None,
interval: float = 0.5, retries: int = 16,
backoff: Callable[[int], float] = None,
until: Callable[[List[dict]], bool] = None) -> None:
"""
Connect to the Slack API and run the even... | [
"def",
"run",
"(",
"self",
",",
"*",
",",
"connector",
":",
"Union",
"[",
"EnvVar",
",",
"Token",
",",
"SlackClient",
",",
"None",
"]",
"=",
"None",
",",
"interval",
":",
"float",
"=",
"0.5",
",",
"retries",
":",
"int",
"=",
"16",
",",
"backoff",
... | Connect to the Slack API and run the event handler loop.
Args:
connector: A means of connecting to the Slack API. This can be an
API :obj:`Token`, an :obj:`EnvVar` from which a token can be
retrieved, or an established :obj:`SlackClient` instance. If
... | [
"Connect",
"to",
"the",
"Slack",
"API",
"and",
"run",
"the",
"event",
"handler",
"loop",
"."
] | a146c47f2558e66bb51cf708d39909b93eaea7f4 | https://github.com/reillysiemens/layabout/blob/a146c47f2558e66bb51cf708d39909b93eaea7f4/layabout.py#L188-L249 | train |
cozy/python_cozy_management | cozy_management/weboob.py | install | def install():
'''
Install weboob system-wide
'''
tmp_weboob_dir = '/tmp/weboob'
# Check that the directory does not already exists
while (os.path.exists(tmp_weboob_dir)):
tmp_weboob_dir += '1'
# Clone the repository
print 'Fetching sources in temporary dir {}'.format(tmp_w... | python | def install():
'''
Install weboob system-wide
'''
tmp_weboob_dir = '/tmp/weboob'
# Check that the directory does not already exists
while (os.path.exists(tmp_weboob_dir)):
tmp_weboob_dir += '1'
# Clone the repository
print 'Fetching sources in temporary dir {}'.format(tmp_w... | [
"def",
"install",
"(",
")",
":",
"tmp_weboob_dir",
"=",
"'/tmp/weboob'",
"while",
"(",
"os",
".",
"path",
".",
"exists",
"(",
"tmp_weboob_dir",
")",
")",
":",
"tmp_weboob_dir",
"+=",
"'1'",
"print",
"'Fetching sources in temporary dir {}'",
".",
"format",
"(",
... | Install weboob system-wide | [
"Install",
"weboob",
"system",
"-",
"wide"
] | 820cea58458ae3e067fa8cc2da38edbda4681dac | https://github.com/cozy/python_cozy_management/blob/820cea58458ae3e067fa8cc2da38edbda4681dac/cozy_management/weboob.py#L32-L72 | train |
uogbuji/versa | tools/py/driver/memory.py | connection.add_many | def add_many(self, rels):
'''
Add a list of relationships to the extent
rels - a list of 0 or more relationship tuples, e.g.:
[
(origin, rel, target, {attrname1: attrval1, attrname2: attrval2}),
]
origin - origin of the relationship (similar to an RDF subjec... | python | def add_many(self, rels):
'''
Add a list of relationships to the extent
rels - a list of 0 or more relationship tuples, e.g.:
[
(origin, rel, target, {attrname1: attrval1, attrname2: attrval2}),
]
origin - origin of the relationship (similar to an RDF subjec... | [
"def",
"add_many",
"(",
"self",
",",
"rels",
")",
":",
"for",
"curr_rel",
"in",
"rels",
":",
"attrs",
"=",
"self",
".",
"_attr_cls",
"(",
")",
"if",
"len",
"(",
"curr_rel",
")",
"==",
"2",
":",
"origin",
",",
"rel",
",",
"target",
",",
"attrs",
"... | Add a list of relationships to the extent
rels - a list of 0 or more relationship tuples, e.g.:
[
(origin, rel, target, {attrname1: attrval1, attrname2: attrval2}),
]
origin - origin of the relationship (similar to an RDF subject)
rel - type IRI of the relationship ... | [
"Add",
"a",
"list",
"of",
"relationships",
"to",
"the",
"extent"
] | f092ffc7ed363a5b170890955168500f32de0dd5 | https://github.com/uogbuji/versa/blob/f092ffc7ed363a5b170890955168500f32de0dd5/tools/py/driver/memory.py#L168-L196 | train |
ronhanson/python-tbx | tbx/process.py | call_repeatedly | def call_repeatedly(func, interval, *args, **kwargs):
"""
Call a function at interval
Returns both the thread object and the loop stopper Event.
"""
main_thead = threading.current_thread()
stopped = threading.Event()
def loop():
while not stopped.wait(interval) and main_thead.is_ali... | python | def call_repeatedly(func, interval, *args, **kwargs):
"""
Call a function at interval
Returns both the thread object and the loop stopper Event.
"""
main_thead = threading.current_thread()
stopped = threading.Event()
def loop():
while not stopped.wait(interval) and main_thead.is_ali... | [
"def",
"call_repeatedly",
"(",
"func",
",",
"interval",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"main_thead",
"=",
"threading",
".",
"current_thread",
"(",
")",
"stopped",
"=",
"threading",
".",
"Event",
"(",
")",
"def",
"loop",
"(",
")",
":",... | Call a function at interval
Returns both the thread object and the loop stopper Event. | [
"Call",
"a",
"function",
"at",
"interval",
"Returns",
"both",
"the",
"thread",
"object",
"and",
"the",
"loop",
"stopper",
"Event",
"."
] | 87f72ae0cadecafbcd144f1e930181fba77f6b83 | https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/process.py#L54-L73 | train |
ronhanson/python-tbx | tbx/process.py | execute | def execute(command, return_output=True, log_file=None, log_settings=None, error_logfile=None, timeout=None, line_function=None, poll_timing = 0.01, logger=None, working_folder=None, env=None):
"""
Execute a program and logs standard output into a file.
:param return_output: returns the STDOUT... | python | def execute(command, return_output=True, log_file=None, log_settings=None, error_logfile=None, timeout=None, line_function=None, poll_timing = 0.01, logger=None, working_folder=None, env=None):
"""
Execute a program and logs standard output into a file.
:param return_output: returns the STDOUT... | [
"def",
"execute",
"(",
"command",
",",
"return_output",
"=",
"True",
",",
"log_file",
"=",
"None",
",",
"log_settings",
"=",
"None",
",",
"error_logfile",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
"line_function",
"=",
"None",
",",
"poll_timing",
"=",... | Execute a program and logs standard output into a file.
:param return_output: returns the STDOUT value if True or returns the return code
:param logfile: path where log file should be written ( displayed on STDOUT if not set)
:param error_logfile: path where error log file ... | [
"Execute",
"a",
"program",
"and",
"logs",
"standard",
"output",
"into",
"a",
"file",
"."
] | 87f72ae0cadecafbcd144f1e930181fba77f6b83 | https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/process.py#L97-L195 | train |
projectshift/shift-boiler | boiler/user/role_service.py | RoleService.save | def save(self, role, commit=True):
""" Persist role model """
self.is_instance(role)
schema = RoleSchema()
valid = schema.process(role)
if not valid:
return valid
db.session.add(role)
if commit:
db.session.commit()
events.role_sa... | python | def save(self, role, commit=True):
""" Persist role model """
self.is_instance(role)
schema = RoleSchema()
valid = schema.process(role)
if not valid:
return valid
db.session.add(role)
if commit:
db.session.commit()
events.role_sa... | [
"def",
"save",
"(",
"self",
",",
"role",
",",
"commit",
"=",
"True",
")",
":",
"self",
".",
"is_instance",
"(",
"role",
")",
"schema",
"=",
"RoleSchema",
"(",
")",
"valid",
"=",
"schema",
".",
"process",
"(",
"role",
")",
"if",
"not",
"valid",
":",... | Persist role model | [
"Persist",
"role",
"model"
] | 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/role_service.py#L14-L28 | train |
adaptive-learning/proso-apps | proso/models/prediction.py | PredictiveModel.update_phase | def update_phase(self, environment, data, prediction, user, item, correct, time, answer_id, **kwargs):
"""
After the prediction update the environment and persist some
information for the predictive model.
Args:
environment (proso.models.environment.Environment):
... | python | def update_phase(self, environment, data, prediction, user, item, correct, time, answer_id, **kwargs):
"""
After the prediction update the environment and persist some
information for the predictive model.
Args:
environment (proso.models.environment.Environment):
... | [
"def",
"update_phase",
"(",
"self",
",",
"environment",
",",
"data",
",",
"prediction",
",",
"user",
",",
"item",
",",
"correct",
",",
"time",
",",
"answer_id",
",",
"**",
"kwargs",
")",
":",
"pass"
] | After the prediction update the environment and persist some
information for the predictive model.
Args:
environment (proso.models.environment.Environment):
environment where all the important data are persist
data (object):
data from the prepare ... | [
"After",
"the",
"prediction",
"update",
"the",
"environment",
"and",
"persist",
"some",
"information",
"for",
"the",
"predictive",
"model",
"."
] | 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso/models/prediction.py#L91-L108 | train |
PBR/MQ2 | MQ2/mapchart.py | append_flanking_markers | def append_flanking_markers(qtls_mk_file, flanking_markers):
""" Append the flanking markers extracted in the process of
generating the MapChart to the QTL list file.
"""
matrix = read_input_file(qtls_mk_file, sep=',')
output = []
cnt = 0
for row in matrix:
if cnt == 0:
m... | python | def append_flanking_markers(qtls_mk_file, flanking_markers):
""" Append the flanking markers extracted in the process of
generating the MapChart to the QTL list file.
"""
matrix = read_input_file(qtls_mk_file, sep=',')
output = []
cnt = 0
for row in matrix:
if cnt == 0:
m... | [
"def",
"append_flanking_markers",
"(",
"qtls_mk_file",
",",
"flanking_markers",
")",
":",
"matrix",
"=",
"read_input_file",
"(",
"qtls_mk_file",
",",
"sep",
"=",
"','",
")",
"output",
"=",
"[",
"]",
"cnt",
"=",
"0",
"for",
"row",
"in",
"matrix",
":",
"if",... | Append the flanking markers extracted in the process of
generating the MapChart to the QTL list file. | [
"Append",
"the",
"flanking",
"markers",
"extracted",
"in",
"the",
"process",
"of",
"generating",
"the",
"MapChart",
"to",
"the",
"QTL",
"list",
"file",
"."
] | 6d84dea47e6751333004743f588f03158e35c28d | https://github.com/PBR/MQ2/blob/6d84dea47e6751333004743f588f03158e35c28d/MQ2/mapchart.py#L231-L248 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.