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_type,
index=index)
db.session.add(obj)
except IntegrityError:
raise Exception("PID Relation already exists.")
# msg = "PIDRelation already exists: " \
# "{0} -> {1} ({2})".format(
# parent_pid, child_pid, relation_type)
# logger.exception(msg)
# raise Exception(msg)
return obj | 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_type,
index=index)
db.session.add(obj)
except IntegrityError:
raise Exception("PID Relation already exists.")
# msg = "PIDRelation already exists: " \
# "{0} -> {1} ({2})".format(
# parent_pid, child_pid, relation_type)
# logger.exception(msg)
# raise Exception(msg)
return obj | [
"def",
"create",
"(",
"cls",
",",
"parent",
",",
"child",
",",
"relation_type",
",",
"index",
"=",
"None",
")",
":",
"try",
":",
"with",
"db",
".",
"session",
".",
"begin_nested",
"(",
")",
":",
"obj",
"=",
"cls",
"(",
"parent_id",
"=",
"parent",
".",
"id",
",",
"child_id",
"=",
"child",
".",
"id",
",",
"relation_type",
"=",
"relation_type",
",",
"index",
"=",
"index",
")",
"db",
".",
"session",
".",
"add",
"(",
"obj",
")",
"except",
"IntegrityError",
":",
"raise",
"Exception",
"(",
"\"PID Relation already exists.\"",
")",
"# msg = \"PIDRelation already exists: \" \\",
"# \"{0} -> {1} ({2})\".format(",
"# parent_pid, child_pid, relation_type)",
"# logger.exception(msg)",
"# raise Exception(msg)",
"return",
"obj"
]
| 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",
",",
"relation_type",
"=",
"relation_type",
")",
".",
"count",
"(",
")",
">",
"0"
]
| 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 wrapping on long filesystem names
stdout, stderr = p.communicate()
lines = stdout.split("\n")
lines[0] = lines[0].replace("Mounted on", "MountedOn").replace("1K-blocks", "Size").replace("1024-blocks", "Size")
assert(lines[0].split() == headers)
lines = [l.strip() for l in lines if l.strip()]
for line in lines[1:]:
tokens = line.split()
if tokens[0] == 'none': # skip uninteresting entries
continue
assert(len(tokens) == n)
d = {}
for x in range(1, len(headers)):
d[headers[x]] = tokens[x]
d['Size'] = float(d['Size']) / unit
assert(d['Capacity'].endswith("%"))
d['Use%'] = d['Capacity']
d['Used'] = float(d['Used']) / unit
d['Available'] = float(d['Available']) / unit
d['Using'] = 100*(d['Used']/d['Size']) # same as Use% but with more precision
if d['Type'].startswith('ext'):
pass
d['Using'] += 5 # ext2, ext3, and ext4 reserve 5% by default
else:
ext3_filesystems = ['ganon:', 'kortemmelab:', 'albana:']
for e3fs in ext3_filesystems:
if tokens[0].find(e3fs) != -1:
d['Using'] += 5 # ext3 reserves 5%
break
details[tokens[0]] = d
return details | 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 wrapping on long filesystem names
stdout, stderr = p.communicate()
lines = stdout.split("\n")
lines[0] = lines[0].replace("Mounted on", "MountedOn").replace("1K-blocks", "Size").replace("1024-blocks", "Size")
assert(lines[0].split() == headers)
lines = [l.strip() for l in lines if l.strip()]
for line in lines[1:]:
tokens = line.split()
if tokens[0] == 'none': # skip uninteresting entries
continue
assert(len(tokens) == n)
d = {}
for x in range(1, len(headers)):
d[headers[x]] = tokens[x]
d['Size'] = float(d['Size']) / unit
assert(d['Capacity'].endswith("%"))
d['Use%'] = d['Capacity']
d['Used'] = float(d['Used']) / unit
d['Available'] = float(d['Available']) / unit
d['Using'] = 100*(d['Used']/d['Size']) # same as Use% but with more precision
if d['Type'].startswith('ext'):
pass
d['Using'] += 5 # ext2, ext3, and ext4 reserve 5% by default
else:
ext3_filesystems = ['ganon:', 'kortemmelab:', 'albana:']
for e3fs in ext3_filesystems:
if tokens[0].find(e3fs) != -1:
d['Using'] += 5 # ext3 reserves 5%
break
details[tokens[0]] = d
return details | [
"def",
"df",
"(",
"unit",
"=",
"'GB'",
")",
":",
"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 wrapping on long filesystem names",
"stdout",
",",
"stderr",
"=",
"p",
".",
"communicate",
"(",
")",
"lines",
"=",
"stdout",
".",
"split",
"(",
"\"\\n\"",
")",
"lines",
"[",
"0",
"]",
"=",
"lines",
"[",
"0",
"]",
".",
"replace",
"(",
"\"Mounted on\"",
",",
"\"MountedOn\"",
")",
".",
"replace",
"(",
"\"1K-blocks\"",
",",
"\"Size\"",
")",
".",
"replace",
"(",
"\"1024-blocks\"",
",",
"\"Size\"",
")",
"assert",
"(",
"lines",
"[",
"0",
"]",
".",
"split",
"(",
")",
"==",
"headers",
")",
"lines",
"=",
"[",
"l",
".",
"strip",
"(",
")",
"for",
"l",
"in",
"lines",
"if",
"l",
".",
"strip",
"(",
")",
"]",
"for",
"line",
"in",
"lines",
"[",
"1",
":",
"]",
":",
"tokens",
"=",
"line",
".",
"split",
"(",
")",
"if",
"tokens",
"[",
"0",
"]",
"==",
"'none'",
":",
"# skip uninteresting entries",
"continue",
"assert",
"(",
"len",
"(",
"tokens",
")",
"==",
"n",
")",
"d",
"=",
"{",
"}",
"for",
"x",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"headers",
")",
")",
":",
"d",
"[",
"headers",
"[",
"x",
"]",
"]",
"=",
"tokens",
"[",
"x",
"]",
"d",
"[",
"'Size'",
"]",
"=",
"float",
"(",
"d",
"[",
"'Size'",
"]",
")",
"/",
"unit",
"assert",
"(",
"d",
"[",
"'Capacity'",
"]",
".",
"endswith",
"(",
"\"%\"",
")",
")",
"d",
"[",
"'Use%'",
"]",
"=",
"d",
"[",
"'Capacity'",
"]",
"d",
"[",
"'Used'",
"]",
"=",
"float",
"(",
"d",
"[",
"'Used'",
"]",
")",
"/",
"unit",
"d",
"[",
"'Available'",
"]",
"=",
"float",
"(",
"d",
"[",
"'Available'",
"]",
")",
"/",
"unit",
"d",
"[",
"'Using'",
"]",
"=",
"100",
"*",
"(",
"d",
"[",
"'Used'",
"]",
"/",
"d",
"[",
"'Size'",
"]",
")",
"# same as Use% but with more precision",
"if",
"d",
"[",
"'Type'",
"]",
".",
"startswith",
"(",
"'ext'",
")",
":",
"pass",
"d",
"[",
"'Using'",
"]",
"+=",
"5",
"# ext2, ext3, and ext4 reserve 5% by default",
"else",
":",
"ext3_filesystems",
"=",
"[",
"'ganon:'",
",",
"'kortemmelab:'",
",",
"'albana:'",
"]",
"for",
"e3fs",
"in",
"ext3_filesystems",
":",
"if",
"tokens",
"[",
"0",
"]",
".",
"find",
"(",
"e3fs",
")",
"!=",
"-",
"1",
":",
"d",
"[",
"'Using'",
"]",
"+=",
"5",
"# ext3 reserves 5%",
"break",
"details",
"[",
"tokens",
"[",
"0",
"]",
"]",
"=",
"d",
"return",
"details"
]
| 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",
".",
"urlencode",
"(",
")"
]
| 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['page']) if 'page' in context['request'].GET else 1
if current_page in (chosen_page + 1, chosen_page + 2, chosen_page - 1, chosen_page - 2,
paginator.num_pages, paginator.num_pages - 1, 1, 2, chosen_page):
return current_page
if current_page in (chosen_page + 3, chosen_page - 3):
return '...' | 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['page']) if 'page' in context['request'].GET else 1
if current_page in (chosen_page + 1, chosen_page + 2, chosen_page - 1, chosen_page - 2,
paginator.num_pages, paginator.num_pages - 1, 1, 2, chosen_page):
return current_page
if current_page in (chosen_page + 3, chosen_page - 3):
return '...' | [
"def",
"ellipsis_or_number",
"(",
"context",
",",
"paginator",
",",
"current_page",
")",
":",
"# Checks is it first page",
"chosen_page",
"=",
"int",
"(",
"context",
"[",
"'request'",
"]",
".",
"GET",
"[",
"'page'",
"]",
")",
"if",
"'page'",
"in",
"context",
"[",
"'request'",
"]",
".",
"GET",
"else",
"1",
"if",
"current_page",
"in",
"(",
"chosen_page",
"+",
"1",
",",
"chosen_page",
"+",
"2",
",",
"chosen_page",
"-",
"1",
",",
"chosen_page",
"-",
"2",
",",
"paginator",
".",
"num_pages",
",",
"paginator",
".",
"num_pages",
"-",
"1",
",",
"1",
",",
"2",
",",
"chosen_page",
")",
":",
"return",
"current_page",
"if",
"current_page",
"in",
"(",
"chosen_page",
"+",
"3",
",",
"chosen_page",
"-",
"3",
")",
":",
"return",
"'...'"
]
| 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')
item.save()
instance.item = item | 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')
item.save()
instance.item = item | [
"def",
"create_items",
"(",
"sender",
",",
"instance",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"instance",
".",
"item_id",
"is",
"None",
"and",
"instance",
".",
"item",
"is",
"None",
":",
"item",
"=",
"Item",
"(",
")",
"if",
"hasattr",
"(",
"instance",
",",
"'active'",
")",
":",
"item",
".",
"active",
"=",
"getattr",
"(",
"instance",
",",
"'active'",
")",
"item",
".",
"save",
"(",
")",
"instance",
".",
"item",
"=",
"item"
]
| 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.get_or_create(
parent_id=parent,
child_id=child,
visible=True,
) | 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.get_or_create(
parent_id=parent,
child_id=child,
visible=True,
) | [
"def",
"add_parent",
"(",
"sender",
",",
"instance",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"kwargs",
"[",
"'created'",
"]",
":",
"return",
"for",
"att",
"in",
"[",
"'task'",
",",
"'context'",
"]",
":",
"parent",
"=",
"getattr",
"(",
"instance",
",",
"att",
")",
".",
"item_id",
"child",
"=",
"instance",
".",
"item_id",
"ItemRelation",
".",
"objects",
".",
"get_or_create",
"(",
"parent_id",
"=",
"parent",
",",
"child_id",
"=",
"child",
",",
"visible",
"=",
"True",
",",
")"
]
| 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.diff
parent = diff['task'][0] if 'task' in diff else diff['task_id'][0]
parent_id = parent.item_id if isinstance(parent, Task) else Task.objects.get(pk=parent).item_id
child_id = instance.item_id
ItemRelation.objects.filter(parent_id=parent_id, child_id=child_id).delete()
ItemRelation.objects.create(parent_id=instance.task.item_id, child_id=child_id, visible=True)
if len({'context', 'context_id'} & set(instance.changed_fields)) != 0:
diff = instance.diff
parent = diff['context'][0] if 'context' in diff else diff['context_id'][0]
parent_id = parent.item_id if isinstance(parent, Context) else Context.objects.get(pk=parent).item_id
child_id = instance.item_id
ItemRelation.objects.filter(parent_id=parent_id, child_id=child_id).delete()
ItemRelation.objects.create(parent_id=instance.context.item_id, child_id=child_id, visible=False) | 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.diff
parent = diff['task'][0] if 'task' in diff else diff['task_id'][0]
parent_id = parent.item_id if isinstance(parent, Task) else Task.objects.get(pk=parent).item_id
child_id = instance.item_id
ItemRelation.objects.filter(parent_id=parent_id, child_id=child_id).delete()
ItemRelation.objects.create(parent_id=instance.task.item_id, child_id=child_id, visible=True)
if len({'context', 'context_id'} & set(instance.changed_fields)) != 0:
diff = instance.diff
parent = diff['context'][0] if 'context' in diff else diff['context_id'][0]
parent_id = parent.item_id if isinstance(parent, Context) else Context.objects.get(pk=parent).item_id
child_id = instance.item_id
ItemRelation.objects.filter(parent_id=parent_id, child_id=child_id).delete()
ItemRelation.objects.create(parent_id=instance.context.item_id, child_id=child_id, visible=False) | [
"def",
"change_parent",
"(",
"sender",
",",
"instance",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"instance",
".",
"id",
"is",
"None",
":",
"return",
"if",
"len",
"(",
"{",
"'task'",
",",
"'task_id'",
"}",
"&",
"set",
"(",
"instance",
".",
"changed_fields",
")",
")",
"!=",
"0",
":",
"diff",
"=",
"instance",
".",
"diff",
"parent",
"=",
"diff",
"[",
"'task'",
"]",
"[",
"0",
"]",
"if",
"'task'",
"in",
"diff",
"else",
"diff",
"[",
"'task_id'",
"]",
"[",
"0",
"]",
"parent_id",
"=",
"parent",
".",
"item_id",
"if",
"isinstance",
"(",
"parent",
",",
"Task",
")",
"else",
"Task",
".",
"objects",
".",
"get",
"(",
"pk",
"=",
"parent",
")",
".",
"item_id",
"child_id",
"=",
"instance",
".",
"item_id",
"ItemRelation",
".",
"objects",
".",
"filter",
"(",
"parent_id",
"=",
"parent_id",
",",
"child_id",
"=",
"child_id",
")",
".",
"delete",
"(",
")",
"ItemRelation",
".",
"objects",
".",
"create",
"(",
"parent_id",
"=",
"instance",
".",
"task",
".",
"item_id",
",",
"child_id",
"=",
"child_id",
",",
"visible",
"=",
"True",
")",
"if",
"len",
"(",
"{",
"'context'",
",",
"'context_id'",
"}",
"&",
"set",
"(",
"instance",
".",
"changed_fields",
")",
")",
"!=",
"0",
":",
"diff",
"=",
"instance",
".",
"diff",
"parent",
"=",
"diff",
"[",
"'context'",
"]",
"[",
"0",
"]",
"if",
"'context'",
"in",
"diff",
"else",
"diff",
"[",
"'context_id'",
"]",
"[",
"0",
"]",
"parent_id",
"=",
"parent",
".",
"item_id",
"if",
"isinstance",
"(",
"parent",
",",
"Context",
")",
"else",
"Context",
".",
"objects",
".",
"get",
"(",
"pk",
"=",
"parent",
")",
".",
"item_id",
"child_id",
"=",
"instance",
".",
"item_id",
"ItemRelation",
".",
"objects",
".",
"filter",
"(",
"parent_id",
"=",
"parent_id",
",",
"child_id",
"=",
"child_id",
")",
".",
"delete",
"(",
")",
"ItemRelation",
".",
"objects",
".",
"create",
"(",
"parent_id",
"=",
"instance",
".",
"context",
".",
"item_id",
",",
"child_id",
"=",
"child_id",
",",
"visible",
"=",
"False",
")"
]
| 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_root_pair) )
unmoved_atom_names = []
new_coords = [ None for x in xrange( len(self_root_pair) ) ]
for atom in self.names:
if atom in self_root_pair:
i = self_root_pair.index(atom)
assert( new_coords[i] == None )
new_coords[i] = self.get_coords_for_name(atom)
if atom in mapping:
other_atom = mapping[atom]
self.set_coords_for_name( atom, other.get_coords_for_name(other_atom) )
else:
unmoved_atom_names.append(atom)
# Move unmoved coordinates after all other atoms have been moved (so that
# references will have been moved already)
if None in new_coords:
print new_coords
assert( None not in new_coords )
ref_coords = [other.get_coords_for_name(x) for x in other_root_pair]
# Calculate translation and rotation matrices
U, new_centroid, ref_centroid = calc_rotation_translation_matrices( ref_coords, new_coords )
for atom in unmoved_atom_names:
original_coord = self.get_coords_for_name(atom)
self.set_coords_for_name( atom, rotate_and_translate_coord(original_coord, U, new_centroid, ref_centroid) )
self.chain = other.chain | 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_root_pair) )
unmoved_atom_names = []
new_coords = [ None for x in xrange( len(self_root_pair) ) ]
for atom in self.names:
if atom in self_root_pair:
i = self_root_pair.index(atom)
assert( new_coords[i] == None )
new_coords[i] = self.get_coords_for_name(atom)
if atom in mapping:
other_atom = mapping[atom]
self.set_coords_for_name( atom, other.get_coords_for_name(other_atom) )
else:
unmoved_atom_names.append(atom)
# Move unmoved coordinates after all other atoms have been moved (so that
# references will have been moved already)
if None in new_coords:
print new_coords
assert( None not in new_coords )
ref_coords = [other.get_coords_for_name(x) for x in other_root_pair]
# Calculate translation and rotation matrices
U, new_centroid, ref_centroid = calc_rotation_translation_matrices( ref_coords, new_coords )
for atom in unmoved_atom_names:
original_coord = self.get_coords_for_name(atom)
self.set_coords_for_name( atom, rotate_and_translate_coord(original_coord, U, new_centroid, ref_centroid) )
self.chain = other.chain | [
"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_root_pair",
")",
"==",
"len",
"(",
"other_root_pair",
")",
")",
"unmoved_atom_names",
"=",
"[",
"]",
"new_coords",
"=",
"[",
"None",
"for",
"x",
"in",
"xrange",
"(",
"len",
"(",
"self_root_pair",
")",
")",
"]",
"for",
"atom",
"in",
"self",
".",
"names",
":",
"if",
"atom",
"in",
"self_root_pair",
":",
"i",
"=",
"self_root_pair",
".",
"index",
"(",
"atom",
")",
"assert",
"(",
"new_coords",
"[",
"i",
"]",
"==",
"None",
")",
"new_coords",
"[",
"i",
"]",
"=",
"self",
".",
"get_coords_for_name",
"(",
"atom",
")",
"if",
"atom",
"in",
"mapping",
":",
"other_atom",
"=",
"mapping",
"[",
"atom",
"]",
"self",
".",
"set_coords_for_name",
"(",
"atom",
",",
"other",
".",
"get_coords_for_name",
"(",
"other_atom",
")",
")",
"else",
":",
"unmoved_atom_names",
".",
"append",
"(",
"atom",
")",
"# Move unmoved coordinates after all other atoms have been moved (so that",
"# references will have been moved already)",
"if",
"None",
"in",
"new_coords",
":",
"print",
"new_coords",
"assert",
"(",
"None",
"not",
"in",
"new_coords",
")",
"ref_coords",
"=",
"[",
"other",
".",
"get_coords_for_name",
"(",
"x",
")",
"for",
"x",
"in",
"other_root_pair",
"]",
"# Calculate translation and rotation matrices",
"U",
",",
"new_centroid",
",",
"ref_centroid",
"=",
"calc_rotation_translation_matrices",
"(",
"ref_coords",
",",
"new_coords",
")",
"for",
"atom",
"in",
"unmoved_atom_names",
":",
"original_coord",
"=",
"self",
".",
"get_coords_for_name",
"(",
"atom",
")",
"self",
".",
"set_coords_for_name",
"(",
"atom",
",",
"rotate_and_translate_coord",
"(",
"original_coord",
",",
"U",
",",
"new_centroid",
",",
"ref_centroid",
")",
")",
"self",
".",
"chain",
"=",
"other",
".",
"chain"
]
| 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.read_events():
yield element
try:
parser.feed(next(source))
except StopIteration:
# forces close of any unclosed tags
parser.feed('</html>')
for element in parser.read_events():
yield element
break | 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.read_events():
yield element
try:
parser.feed(next(source))
except StopIteration:
# forces close of any unclosed tags
parser.feed('</html>')
for element in parser.read_events():
yield element
break | [
"def",
"pumper",
"(",
"html_generator",
")",
":",
"source",
"=",
"html_generator",
"(",
")",
"parser",
"=",
"etree",
".",
"HTMLPullParser",
"(",
"events",
"=",
"(",
"'start'",
",",
"'end'",
")",
",",
"remove_comments",
"=",
"True",
")",
"while",
"True",
":",
"for",
"element",
"in",
"parser",
".",
"read_events",
"(",
")",
":",
"yield",
"element",
"try",
":",
"parser",
".",
"feed",
"(",
"next",
"(",
"source",
")",
")",
"except",
"StopIteration",
":",
"# forces close of any unclosed tags",
"parser",
".",
"feed",
"(",
"'</html>'",
")",
"for",
"element",
"in",
"parser",
".",
"read_events",
"(",
")",
":",
"yield",
"element",
"break"
]
| 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)
return v | 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)
return v | [
"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",
".",
"strftime",
"(",
"\"%A %B %d %Y\"",
")",
"if",
"locale_",
":",
"locale",
".",
"setlocale",
"(",
"locale",
".",
"LC_ALL",
",",
"old_locale",
")",
"return",
"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 whether we have a cached copy of the PDB file
filepath = os.path.join(cache_dir, '{0}.pdb'.format(pdb_id))
if os.path.exists(filepath):
return PDB.from_filepath(filepath)
# Get any missing files from the RCSB and create cached copies if appropriate
pdb_contents = retrieve_pdb(pdb_id)
if cache_dir:
write_file(os.path.join(cache_dir, "%s.pdb" % pdb_id), pdb_contents)
return PDB(pdb_contents) | 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 whether we have a cached copy of the PDB file
filepath = os.path.join(cache_dir, '{0}.pdb'.format(pdb_id))
if os.path.exists(filepath):
return PDB.from_filepath(filepath)
# Get any missing files from the RCSB and create cached copies if appropriate
pdb_contents = retrieve_pdb(pdb_id)
if cache_dir:
write_file(os.path.join(cache_dir, "%s.pdb" % pdb_id), pdb_contents)
return PDB(pdb_contents) | [
"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",
")",
"if",
"cache_dir",
":",
"# Check to see whether we have a cached copy of the PDB file",
"filepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"cache_dir",
",",
"'{0}.pdb'",
".",
"format",
"(",
"pdb_id",
")",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"filepath",
")",
":",
"return",
"PDB",
".",
"from_filepath",
"(",
"filepath",
")",
"# Get any missing files from the RCSB and create cached copies if appropriate",
"pdb_contents",
"=",
"retrieve_pdb",
"(",
"pdb_id",
")",
"if",
"cache_dir",
":",
"write_file",
"(",
"os",
".",
"path",
".",
"join",
"(",
"cache_dir",
",",
"\"%s.pdb\"",
"%",
"pdb_id",
")",
",",
"pdb_contents",
")",
"return",
"PDB",
"(",
"pdb_contents",
")"
]
| 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)
command_line = 'cd {home}'.format(home=home)
command_line += ' && git pull'
if force:
command_line += ' && ([ -d node_modules ] && rm -rf node_modules || true)'
command_line += ' && ([ -d .node-gyp ] && rm -rf .node-gyp || true)'
command_line += ' && ([ -d .npm ] && rm -rf .npm || true)'
command_line += ' && chown -R {user}:{user} .'.format(user=user)
command_line += ' && sudo -u {user} env HOME={home} npm install --production'.format(
user=user,
home=home
)
if restart:
command_line += ' && cozy-monitor update {app_name}'.format(
app_name=app_name)
command_line += ' && cozy-monitor restart {app_name}'.format(
app_name=app_name)
if not quiet:
print 'Execute:'
print command_line
if not without_exec:
result = helpers.cmd_exec(command_line)
print result['stdout']
print result['stderr']
print result['error'] | 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)
command_line = 'cd {home}'.format(home=home)
command_line += ' && git pull'
if force:
command_line += ' && ([ -d node_modules ] && rm -rf node_modules || true)'
command_line += ' && ([ -d .node-gyp ] && rm -rf .node-gyp || true)'
command_line += ' && ([ -d .npm ] && rm -rf .npm || true)'
command_line += ' && chown -R {user}:{user} .'.format(user=user)
command_line += ' && sudo -u {user} env HOME={home} npm install --production'.format(
user=user,
home=home
)
if restart:
command_line += ' && cozy-monitor update {app_name}'.format(
app_name=app_name)
command_line += ' && cozy-monitor restart {app_name}'.format(
app_name=app_name)
if not quiet:
print 'Execute:'
print command_line
if not without_exec:
result = helpers.cmd_exec(command_line)
print result['stdout']
print result['stderr']
print result['error'] | [
"def",
"rebuild_app",
"(",
"app_name",
",",
"quiet",
"=",
"False",
",",
"force",
"=",
"True",
",",
"without_exec",
"=",
"False",
",",
"restart",
"=",
"False",
")",
":",
"user",
"=",
"'cozy-{app_name}'",
".",
"format",
"(",
"app_name",
"=",
"app_name",
")",
"home",
"=",
"'{prefix}/{app_name}'",
".",
"format",
"(",
"prefix",
"=",
"PREFIX",
",",
"app_name",
"=",
"app_name",
")",
"command_line",
"=",
"'cd {home}'",
".",
"format",
"(",
"home",
"=",
"home",
")",
"command_line",
"+=",
"' && git pull'",
"if",
"force",
":",
"command_line",
"+=",
"' && ([ -d node_modules ] && rm -rf node_modules || true)'",
"command_line",
"+=",
"' && ([ -d .node-gyp ] && rm -rf .node-gyp || true)'",
"command_line",
"+=",
"' && ([ -d .npm ] && rm -rf .npm || true)'",
"command_line",
"+=",
"' && chown -R {user}:{user} .'",
".",
"format",
"(",
"user",
"=",
"user",
")",
"command_line",
"+=",
"' && sudo -u {user} env HOME={home} npm install --production'",
".",
"format",
"(",
"user",
"=",
"user",
",",
"home",
"=",
"home",
")",
"if",
"restart",
":",
"command_line",
"+=",
"' && cozy-monitor update {app_name}'",
".",
"format",
"(",
"app_name",
"=",
"app_name",
")",
"command_line",
"+=",
"' && cozy-monitor restart {app_name}'",
".",
"format",
"(",
"app_name",
"=",
"app_name",
")",
"if",
"not",
"quiet",
":",
"print",
"'Execute:'",
"print",
"command_line",
"if",
"not",
"without_exec",
":",
"result",
"=",
"helpers",
".",
"cmd_exec",
"(",
"command_line",
")",
"print",
"result",
"[",
"'stdout'",
"]",
"print",
"result",
"[",
"'stderr'",
"]",
"print",
"result",
"[",
"'error'",
"]"
]
| 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",
"(",
"app",
",",
"force",
"=",
"force",
",",
"restart",
"=",
"restart",
")"
]
| 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)
rebuild_app(app, force=False)
monitor.start(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)
rebuild_app(app, force=False)
monitor.start(app) | [
"def",
"restart_stopped_apps",
"(",
")",
":",
"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",
")",
"rebuild_app",
"(",
"app",
",",
"force",
"=",
"False",
")",
"monitor",
".",
"start",
"(",
"app",
")"
]
| 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('rm /etc/supervisor/conf.d/cozy-indexer.conf',
show_output=True)
helpers.cmd_exec('supervisorctl reload', show_output=True)
helpers.wait_cozy_stack()
ssl.normalize_cert_dir()
helpers.cmd_exec('apt-get update', show_output=True)
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', show_output=True)
helpers.cmd_exec('apt-get remove -y nodejs-legacy', show_output=True)
helpers.cmd_exec('apt-get remove -y nodejs-dev', show_output=True)
helpers.cmd_exec('apt-get remove -y npm', show_output=True)
helpers.cmd_exec('apt-get install -y nodejs', show_output=True)
helpers.cmd_exec('apt-get install -y cozy', show_output=True)
helpers.cmd_exec('npm install -g cozy-monitor cozy-controller',
show_output=True)
rebuild_app('data-system')
rebuild_app('home')
rebuild_app('proxy')
helpers.cmd_exec('supervisorctl restart cozy-controller', show_output=True)
helpers.wait_cozy_stack()
rebuild_all_apps(restart=True)
restart_stopped_apps()
helpers.cmd_exec('apt-get install -y cozy', show_output=True) | 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('rm /etc/supervisor/conf.d/cozy-indexer.conf',
show_output=True)
helpers.cmd_exec('supervisorctl reload', show_output=True)
helpers.wait_cozy_stack()
ssl.normalize_cert_dir()
helpers.cmd_exec('apt-get update', show_output=True)
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', show_output=True)
helpers.cmd_exec('apt-get remove -y nodejs-legacy', show_output=True)
helpers.cmd_exec('apt-get remove -y nodejs-dev', show_output=True)
helpers.cmd_exec('apt-get remove -y npm', show_output=True)
helpers.cmd_exec('apt-get install -y nodejs', show_output=True)
helpers.cmd_exec('apt-get install -y cozy', show_output=True)
helpers.cmd_exec('npm install -g cozy-monitor cozy-controller',
show_output=True)
rebuild_app('data-system')
rebuild_app('home')
rebuild_app('proxy')
helpers.cmd_exec('supervisorctl restart cozy-controller', show_output=True)
helpers.wait_cozy_stack()
rebuild_all_apps(restart=True)
restart_stopped_apps()
helpers.cmd_exec('apt-get install -y cozy', show_output=True) | [
"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",
".",
"cmd_exec",
"(",
"'update-all'",
",",
"show_output",
"=",
"True",
")",
"helpers",
".",
"cmd_exec",
"(",
"'rm /etc/supervisor/conf.d/cozy-indexer.conf'",
",",
"show_output",
"=",
"True",
")",
"helpers",
".",
"cmd_exec",
"(",
"'supervisorctl reload'",
",",
"show_output",
"=",
"True",
")",
"helpers",
".",
"wait_cozy_stack",
"(",
")",
"ssl",
".",
"normalize_cert_dir",
"(",
")",
"helpers",
".",
"cmd_exec",
"(",
"'apt-get update'",
",",
"show_output",
"=",
"True",
")",
"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'",
",",
"show_output",
"=",
"True",
")",
"helpers",
".",
"cmd_exec",
"(",
"'apt-get remove -y nodejs-legacy'",
",",
"show_output",
"=",
"True",
")",
"helpers",
".",
"cmd_exec",
"(",
"'apt-get remove -y nodejs-dev'",
",",
"show_output",
"=",
"True",
")",
"helpers",
".",
"cmd_exec",
"(",
"'apt-get remove -y npm'",
",",
"show_output",
"=",
"True",
")",
"helpers",
".",
"cmd_exec",
"(",
"'apt-get install -y nodejs'",
",",
"show_output",
"=",
"True",
")",
"helpers",
".",
"cmd_exec",
"(",
"'apt-get install -y cozy'",
",",
"show_output",
"=",
"True",
")",
"helpers",
".",
"cmd_exec",
"(",
"'npm install -g cozy-monitor cozy-controller'",
",",
"show_output",
"=",
"True",
")",
"rebuild_app",
"(",
"'data-system'",
")",
"rebuild_app",
"(",
"'home'",
")",
"rebuild_app",
"(",
"'proxy'",
")",
"helpers",
".",
"cmd_exec",
"(",
"'supervisorctl restart cozy-controller'",
",",
"show_output",
"=",
"True",
")",
"helpers",
".",
"wait_cozy_stack",
"(",
")",
"rebuild_all_apps",
"(",
"restart",
"=",
"True",
")",
"restart_stopped_apps",
"(",
")",
"helpers",
".",
"cmd_exec",
"(",
"'apt-get install -y cozy'",
",",
"show_output",
"=",
"True",
")"
]
| 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', show_output=True)
command_line = 'apt-get install -y nodejs'
command_line += ' && apt-get install -y cozy-depends'
return_code = helpers.cmd_exec(command_line, show_output=True)
if return_code != 0:
sys.exit(return_code)
weboob.install() | 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', show_output=True)
command_line = 'apt-get install -y nodejs'
command_line += ' && apt-get install -y cozy-depends'
return_code = helpers.cmd_exec(command_line, show_output=True)
if return_code != 0:
sys.exit(return_code)
weboob.install() | [
"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_output",
"=",
"True",
")",
"helpers",
".",
"cmd_exec",
"(",
"'apt-get update'",
",",
"show_output",
"=",
"True",
")",
"command_line",
"=",
"'apt-get install -y nodejs'",
"command_line",
"+=",
"' && apt-get install -y cozy-depends'",
"return_code",
"=",
"helpers",
".",
"cmd_exec",
"(",
"command_line",
",",
"show_output",
"=",
"True",
")",
"if",
"return_code",
"!=",
"0",
":",
"sys",
".",
"exit",
"(",
"return_code",
")",
"weboob",
".",
"install",
"(",
")"
]
| 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",
",",
"text",
")",
")",
"self",
".",
"save",
"(",
")"
]
| 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 session and will not
be returned in subsequent calls.
Returns a list of namedtuples with the fields (type, text).
"""
key = self._msg_key
messages = []
if type is None:
messages = self.pop(key, [])
else:
keep_messages = []
for msg in self.get(key, []):
if msg.type == type:
messages.append(msg)
else:
keep_messages.append(msg)
if not keep_messages and key in self:
del self[key]
else:
self[key] = keep_messages
if messages:
self.save()
return messages | 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 session and will not
be returned in subsequent calls.
Returns a list of namedtuples with the fields (type, text).
"""
key = self._msg_key
messages = []
if type is None:
messages = self.pop(key, [])
else:
keep_messages = []
for msg in self.get(key, []):
if msg.type == type:
messages.append(msg)
else:
keep_messages.append(msg)
if not keep_messages and key in self:
del self[key]
else:
self[key] = keep_messages
if messages:
self.save()
return messages | [
"def",
"pop_messages",
"(",
"self",
",",
"type",
"=",
"None",
")",
":",
"key",
"=",
"self",
".",
"_msg_key",
"messages",
"=",
"[",
"]",
"if",
"type",
"is",
"None",
":",
"messages",
"=",
"self",
".",
"pop",
"(",
"key",
",",
"[",
"]",
")",
"else",
":",
"keep_messages",
"=",
"[",
"]",
"for",
"msg",
"in",
"self",
".",
"get",
"(",
"key",
",",
"[",
"]",
")",
":",
"if",
"msg",
".",
"type",
"==",
"type",
":",
"messages",
".",
"append",
"(",
"msg",
")",
"else",
":",
"keep_messages",
".",
"append",
"(",
"msg",
")",
"if",
"not",
"keep_messages",
"and",
"key",
"in",
"self",
":",
"del",
"self",
"[",
"key",
"]",
"else",
":",
"self",
"[",
"key",
"]",
"=",
"keep_messages",
"if",
"messages",
":",
"self",
".",
"save",
"(",
")",
"return",
"messages"
]
| 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 subsequent calls.
Returns a list of namedtuples with the fields (type, text). | [
"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 = list(candidates)
shuffle(rcands)
rcands = rcands[:min(n_winners, len(rcands))]
best = [(i, 0.0) for i in rcands]
return best | 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 = list(candidates)
shuffle(rcands)
rcands = rcands[:min(n_winners, len(rcands))]
best = [(i, 0.0) for i in rcands]
return best | [
"def",
"vote_random",
"(",
"candidates",
",",
"votes",
",",
"n_winners",
")",
":",
"rcands",
"=",
"list",
"(",
"candidates",
")",
"shuffle",
"(",
"rcands",
")",
"rcands",
"=",
"rcands",
"[",
":",
"min",
"(",
"n_winners",
",",
"len",
"(",
"rcands",
")",
")",
"]",
"best",
"=",
"[",
"(",
"i",
",",
"0.0",
")",
"for",
"i",
"in",
"rcands",
"]",
"return",
"best"
]
| 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 candidates in the vote
:param votes: Votes from the agents
:param int n_winners: The number of vote winners
"""
worsts = {str(c): 100000000.0 for c in candidates}
for v in votes:
for e in v:
if worsts[str(e[0])] > e[1]:
worsts[str(e[0])] = e[1]
s = sorted(worsts.items(), key=lambda x: x[1], reverse=True)
best = s[:min(n_winners, len(candidates))]
d = []
for e in best:
for c in candidates:
if str(c) == e[0]:
d.append((c, e[1]))
return d | 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 candidates in the vote
:param votes: Votes from the agents
:param int n_winners: The number of vote winners
"""
worsts = {str(c): 100000000.0 for c in candidates}
for v in votes:
for e in v:
if worsts[str(e[0])] > e[1]:
worsts[str(e[0])] = e[1]
s = sorted(worsts.items(), key=lambda x: x[1], reverse=True)
best = s[:min(n_winners, len(candidates))]
d = []
for e in best:
for c in candidates:
if str(c) == e[0]:
d.append((c, e[1]))
return d | [
"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",
":",
"if",
"worsts",
"[",
"str",
"(",
"e",
"[",
"0",
"]",
")",
"]",
">",
"e",
"[",
"1",
"]",
":",
"worsts",
"[",
"str",
"(",
"e",
"[",
"0",
"]",
")",
"]",
"=",
"e",
"[",
"1",
"]",
"s",
"=",
"sorted",
"(",
"worsts",
".",
"items",
"(",
")",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"1",
"]",
",",
"reverse",
"=",
"True",
")",
"best",
"=",
"s",
"[",
":",
"min",
"(",
"n_winners",
",",
"len",
"(",
"candidates",
")",
")",
"]",
"d",
"=",
"[",
"]",
"for",
"e",
"in",
"best",
":",
"for",
"c",
"in",
"candidates",
":",
"if",
"str",
"(",
"c",
")",
"==",
"e",
"[",
"0",
"]",
":",
"d",
".",
"append",
"(",
"(",
"c",
",",
"e",
"[",
"1",
"]",
")",
")",
"return",
"d"
]
| 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 agents
:param int n_winners: The number of vote winners | [
"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
"""
best = [votes[0][0]]
for v in votes[1:]:
if v[0][1] > best[0][1]:
best = [v[0]]
return best | 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
"""
best = [votes[0][0]]
for v in votes[1:]:
if v[0][1] > best[0][1]:
best = [v[0]]
return best | [
"def",
"vote_best",
"(",
"candidates",
",",
"votes",
",",
"n_winners",
")",
":",
"best",
"=",
"[",
"votes",
"[",
"0",
"]",
"[",
"0",
"]",
"]",
"for",
"v",
"in",
"votes",
"[",
"1",
":",
"]",
":",
"if",
"v",
"[",
"0",
"]",
"[",
"1",
"]",
">",
"best",
"[",
"0",
"]",
"[",
"1",
"]",
":",
"best",
"=",
"[",
"v",
"[",
"0",
"]",
"]",
"return",
"best"
]
| 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",
":",
"if",
"c",
"not",
"in",
"fpl",
":",
"if",
"c",
"not",
"in",
"ranking",
":",
"ranking",
".",
"append",
"(",
"(",
"c",
",",
"0",
")",
")"
]
| 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",
"in",
"cl",
":",
"if",
"c",
"==",
"fpl",
"[",
"-",
"1",
"]",
":",
"if",
"c",
"not",
"in",
"ranking",
":",
"ranking",
".",
"append",
"(",
"(",
"c",
",",
"len",
"(",
"ranking",
")",
"+",
"1",
")",
")"
]
| 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.
votes = [[e[0] for e in v] for v in votes]
f = lambda x: Counter(e[0] for e in x).most_common()
cl = list(candidates)
ranking = []
fp = f(votes)
fpl = [e[0] for e in fp]
while len(fpl) > 1:
_remove_zeros(votes, fpl, cl, ranking)
_remove_last(votes, fpl, cl, ranking)
cl = fpl[:-1]
fp = f(votes)
fpl = [e[0] for e in fp]
ranking.append((fpl[0], len(ranking) + 1))
ranking = list(reversed(ranking))
return ranking[:min(n_winners, len(ranking))] | 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.
votes = [[e[0] for e in v] for v in votes]
f = lambda x: Counter(e[0] for e in x).most_common()
cl = list(candidates)
ranking = []
fp = f(votes)
fpl = [e[0] for e in fp]
while len(fpl) > 1:
_remove_zeros(votes, fpl, cl, ranking)
_remove_last(votes, fpl, cl, ranking)
cl = fpl[:-1]
fp = f(votes)
fpl = [e[0] for e in fp]
ranking.append((fpl[0], len(ranking) + 1))
ranking = list(reversed(ranking))
return ranking[:min(n_winners, len(ranking))] | [
"def",
"vote_IRV",
"(",
"candidates",
",",
"votes",
",",
"n_winners",
")",
":",
"# TODO: Check what is wrong in here.",
"votes",
"=",
"[",
"[",
"e",
"[",
"0",
"]",
"for",
"e",
"in",
"v",
"]",
"for",
"v",
"in",
"votes",
"]",
"f",
"=",
"lambda",
"x",
":",
"Counter",
"(",
"e",
"[",
"0",
"]",
"for",
"e",
"in",
"x",
")",
".",
"most_common",
"(",
")",
"cl",
"=",
"list",
"(",
"candidates",
")",
"ranking",
"=",
"[",
"]",
"fp",
"=",
"f",
"(",
"votes",
")",
"fpl",
"=",
"[",
"e",
"[",
"0",
"]",
"for",
"e",
"in",
"fp",
"]",
"while",
"len",
"(",
"fpl",
")",
">",
"1",
":",
"_remove_zeros",
"(",
"votes",
",",
"fpl",
",",
"cl",
",",
"ranking",
")",
"_remove_last",
"(",
"votes",
",",
"fpl",
",",
"cl",
",",
"ranking",
")",
"cl",
"=",
"fpl",
"[",
":",
"-",
"1",
"]",
"fp",
"=",
"f",
"(",
"votes",
")",
"fpl",
"=",
"[",
"e",
"[",
"0",
"]",
"for",
"e",
"in",
"fp",
"]",
"ranking",
".",
"append",
"(",
"(",
"fpl",
"[",
"0",
"]",
",",
"len",
"(",
"ranking",
")",
"+",
"1",
")",
")",
"ranking",
"=",
"list",
"(",
"reversed",
"(",
"ranking",
")",
")",
"return",
"ranking",
"[",
":",
"min",
"(",
"n_winners",
",",
"len",
"(",
"ranking",
")",
")",
"]"
]
| 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 in the vote
:param votes: Votes from the agents
:param int n_winners: The number of vote winners
"""
sums = {str(candidate): [] for candidate in candidates}
for vote in votes:
for v in vote:
sums[str(v[0])].append(v[1])
for s in sums:
sums[s] = sum(sums[s]) / len(sums[s])
ordering = list(sums.items())
ordering.sort(key=operator.itemgetter(1), reverse=True)
best = ordering[:min(n_winners, len(ordering))]
d = []
for e in best:
for c in candidates:
if str(c) == e[0]:
d.append((c, e[1]))
return d | 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 in the vote
:param votes: Votes from the agents
:param int n_winners: The number of vote winners
"""
sums = {str(candidate): [] for candidate in candidates}
for vote in votes:
for v in vote:
sums[str(v[0])].append(v[1])
for s in sums:
sums[s] = sum(sums[s]) / len(sums[s])
ordering = list(sums.items())
ordering.sort(key=operator.itemgetter(1), reverse=True)
best = ordering[:min(n_winners, len(ordering))]
d = []
for e in best:
for c in candidates:
if str(c) == e[0]:
d.append((c, e[1]))
return d | [
"def",
"vote_mean",
"(",
"candidates",
",",
"votes",
",",
"n_winners",
")",
":",
"sums",
"=",
"{",
"str",
"(",
"candidate",
")",
":",
"[",
"]",
"for",
"candidate",
"in",
"candidates",
"}",
"for",
"vote",
"in",
"votes",
":",
"for",
"v",
"in",
"vote",
":",
"sums",
"[",
"str",
"(",
"v",
"[",
"0",
"]",
")",
"]",
".",
"append",
"(",
"v",
"[",
"1",
"]",
")",
"for",
"s",
"in",
"sums",
":",
"sums",
"[",
"s",
"]",
"=",
"sum",
"(",
"sums",
"[",
"s",
"]",
")",
"/",
"len",
"(",
"sums",
"[",
"s",
"]",
")",
"ordering",
"=",
"list",
"(",
"sums",
".",
"items",
"(",
")",
")",
"ordering",
".",
"sort",
"(",
"key",
"=",
"operator",
".",
"itemgetter",
"(",
"1",
")",
",",
"reverse",
"=",
"True",
")",
"best",
"=",
"ordering",
"[",
":",
"min",
"(",
"n_winners",
",",
"len",
"(",
"ordering",
")",
")",
"]",
"d",
"=",
"[",
"]",
"for",
"e",
"in",
"best",
":",
"for",
"c",
"in",
"candidates",
":",
"if",
"str",
"(",
"c",
")",
"==",
"e",
"[",
"0",
"]",
":",
"d",
".",
"append",
"(",
"(",
"c",
",",
"e",
"[",
"1",
"]",
")",
")",
"return",
"d"
]
| 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
:param int n_winners: The number of vote winners | [
"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 might be omitted from the actual decision
making, or only a number of (the highest ranking) candidates may be
used.
This basic implementation ranks candidates based on
:meth:`~creamas.core.agent.CreativeAgent.evaluate`.
:param candidates:
list of :py:class:`~creamas.core.artifact.Artifact` objects to be
ranked
:returns:
Ordered list of (candidate, evaluation)-tuples
"""
ranks = [(c, self.evaluate(c)[0]) for c in candidates]
ranks.sort(key=operator.itemgetter(1), reverse=True)
return ranks | 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 might be omitted from the actual decision
making, or only a number of (the highest ranking) candidates may be
used.
This basic implementation ranks candidates based on
:meth:`~creamas.core.agent.CreativeAgent.evaluate`.
:param candidates:
list of :py:class:`~creamas.core.artifact.Artifact` objects to be
ranked
:returns:
Ordered list of (candidate, evaluation)-tuples
"""
ranks = [(c, self.evaluate(c)[0]) for c in candidates]
ranks.sort(key=operator.itemgetter(1), reverse=True)
return ranks | [
"def",
"vote",
"(",
"self",
",",
"candidates",
")",
":",
"ranks",
"=",
"[",
"(",
"c",
",",
"self",
".",
"evaluate",
"(",
"c",
")",
"[",
"0",
"]",
")",
"for",
"c",
"in",
"candidates",
"]",
"ranks",
".",
"sort",
"(",
"key",
"=",
"operator",
".",
"itemgetter",
"(",
"1",
")",
",",
"reverse",
"=",
"True",
")",
"return",
"ranks"
]
| 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 decision
making, or only a number of (the highest ranking) candidates may be
used.
This basic implementation ranks candidates based on
:meth:`~creamas.core.agent.CreativeAgent.evaluate`.
:param candidates:
list of :py:class:`~creamas.core.artifact.Artifact` objects to be
ranked
:returns:
Ordered list of (candidate, evaluation)-tuples | [
"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 the
environment.
"""
valid_candidates = set(candidates)
for a in self.get_agents(addr=False):
vc = set(a.validate(candidates))
valid_candidates = valid_candidates.intersection(vc)
return list(valid_candidates) | 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 the
environment.
"""
valid_candidates = set(candidates)
for a in self.get_agents(addr=False):
vc = set(a.validate(candidates))
valid_candidates = valid_candidates.intersection(vc)
return list(valid_candidates) | [
"def",
"validate_candidates",
"(",
"self",
",",
"candidates",
")",
":",
"valid_candidates",
"=",
"set",
"(",
"candidates",
")",
"for",
"a",
"in",
"self",
".",
"get_agents",
"(",
"addr",
"=",
"False",
")",
":",
"vc",
"=",
"set",
"(",
"a",
".",
"validate",
"(",
"candidates",
")",
")",
"valid_candidates",
"=",
"valid_candidates",
".",
"intersection",
"(",
"vc",
")",
"return",
"list",
"(",
"valid_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 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 ``(artifact, preference)``
-tuples sorted in a preference order of a single agent.
"""
votes = []
for a in self.get_agents(addr=False):
vote = a.vote(candidates)
votes.append(vote)
return votes | 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 ``(artifact, preference)``
-tuples sorted in a preference order of a single agent.
"""
votes = []
for a in self.get_agents(addr=False):
vote = a.vote(candidates)
votes.append(vote)
return votes | [
"def",
"gather_votes",
"(",
"self",
",",
"candidates",
")",
":",
"votes",
"=",
"[",
"]",
"for",
"a",
"in",
"self",
".",
"get_agents",
"(",
"addr",
"=",
"False",
")",
":",
"vote",
"=",
"a",
".",
"vote",
"(",
"candidates",
")",
"votes",
".",
"append",
"(",
"vote",
")",
"return",
"votes"
]
| 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 a preference order of a single agent. | [
"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",
"(",
")",
"return",
"self",
".",
"_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(addr)
return await r_manager.gather_votes(candidates)
if len(self.candidates) == 0:
self._log(logging.DEBUG, "Could not gather votes because there "
"are no candidates!")
self._votes = []
return
self._log(logging.DEBUG, "Gathering votes for {} candidates."
.format(len(self.candidates)))
if self._single_env:
self._votes = self.env.gather_votes(self.candidates)
else:
mgrs = self.get_managers()
tasks = create_tasks(slave_task, mgrs, self.candidates)
self._votes = run(tasks) | 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(addr)
return await r_manager.gather_votes(candidates)
if len(self.candidates) == 0:
self._log(logging.DEBUG, "Could not gather votes because there "
"are no candidates!")
self._votes = []
return
self._log(logging.DEBUG, "Gathering votes for {} candidates."
.format(len(self.candidates)))
if self._single_env:
self._votes = self.env.gather_votes(self.candidates)
else:
mgrs = self.get_managers()
tasks = create_tasks(slave_task, mgrs, self.candidates)
self._votes = run(tasks) | [
"def",
"gather_votes",
"(",
"self",
")",
":",
"async",
"def",
"slave_task",
"(",
"addr",
",",
"candidates",
")",
":",
"r_manager",
"=",
"await",
"self",
".",
"env",
".",
"connect",
"(",
"addr",
")",
"return",
"await",
"r_manager",
".",
"gather_votes",
"(",
"candidates",
")",
"if",
"len",
"(",
"self",
".",
"candidates",
")",
"==",
"0",
":",
"self",
".",
"_log",
"(",
"logging",
".",
"DEBUG",
",",
"\"Could not gather votes because there \"",
"\"are no candidates!\"",
")",
"self",
".",
"_votes",
"=",
"[",
"]",
"return",
"self",
".",
"_log",
"(",
"logging",
".",
"DEBUG",
",",
"\"Gathering votes for {} candidates.\"",
".",
"format",
"(",
"len",
"(",
"self",
".",
"candidates",
")",
")",
")",
"if",
"self",
".",
"_single_env",
":",
"self",
".",
"_votes",
"=",
"self",
".",
"env",
".",
"gather_votes",
"(",
"self",
".",
"candidates",
")",
"else",
":",
"mgrs",
"=",
"self",
".",
"get_managers",
"(",
")",
"tasks",
"=",
"create_tasks",
"(",
"slave_task",
",",
"mgrs",
",",
"self",
".",
"candidates",
")",
"self",
".",
"_votes",
"=",
"run",
"(",
"tasks",
")"
]
| 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_manager.get_candidates()
if self._single_env:
self._candidates = self.env.candidates
else:
mgrs = self.get_managers()
tasks = create_tasks(slave_task, mgrs)
self._candidates = run(tasks) | 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_manager.get_candidates()
if self._single_env:
self._candidates = self.env.candidates
else:
mgrs = self.get_managers()
tasks = create_tasks(slave_task, mgrs)
self._candidates = run(tasks) | [
"def",
"gather_candidates",
"(",
"self",
")",
":",
"async",
"def",
"slave_task",
"(",
"addr",
")",
":",
"r_manager",
"=",
"await",
"self",
".",
"env",
".",
"connect",
"(",
"addr",
")",
"return",
"await",
"r_manager",
".",
"get_candidates",
"(",
")",
"if",
"self",
".",
"_single_env",
":",
"self",
".",
"_candidates",
"=",
"self",
".",
"env",
".",
"candidates",
"else",
":",
"mgrs",
"=",
"self",
".",
"get_managers",
"(",
")",
"tasks",
"=",
"create_tasks",
"(",
"slave_task",
",",
"mgrs",
")",
"self",
".",
"_candidates",
"=",
"run",
"(",
"tasks",
")"
]
| 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.connect(addr)
return await r_manager.clear_candidates()
self._candidates = []
if clear_env:
if self._single_env:
self.env.clear_candidates()
else:
mgrs = self.get_managers()
run(create_tasks(slave_task, mgrs)) | 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.connect(addr)
return await r_manager.clear_candidates()
self._candidates = []
if clear_env:
if self._single_env:
self.env.clear_candidates()
else:
mgrs = self.get_managers()
run(create_tasks(slave_task, mgrs)) | [
"def",
"clear_candidates",
"(",
"self",
",",
"clear_env",
"=",
"True",
")",
":",
"async",
"def",
"slave_task",
"(",
"addr",
")",
":",
"r_manager",
"=",
"await",
"self",
".",
"env",
".",
"connect",
"(",
"addr",
")",
"return",
"await",
"r_manager",
".",
"clear_candidates",
"(",
")",
"self",
".",
"_candidates",
"=",
"[",
"]",
"if",
"clear_env",
":",
"if",
"self",
".",
"_single_env",
":",
"self",
".",
"env",
".",
"clear_candidates",
"(",
")",
"else",
":",
"mgrs",
"=",
"self",
".",
"get_managers",
"(",
")",
"run",
"(",
"create_tasks",
"(",
"slave_task",
",",
"mgrs",
")",
")"
]
| 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 artifact candidates must be hashable and have a :meth:`__eq__`
implemented for validation to work on multi-environments and
distributed environments.
"""
async def slave_task(addr, candidates):
r_manager = await self.env.connect(addr)
return await r_manager.validate_candidates(candidates)
self._log(logging.DEBUG, "Validating {} candidates"
.format(len(self.candidates)))
candidates = self.candidates
if self._single_env:
self._candidates = self.env.validate_candidates(candidates)
else:
mgrs = self.get_managers()
tasks = create_tasks(slave_task, mgrs, candidates, flatten=False)
rets = run(tasks)
valid_candidates = set(self.candidates)
for r in rets:
valid_candidates = valid_candidates.intersection(set(r))
self._candidates = list(valid_candidates)
self._log(logging.DEBUG, "{} candidates after validation"
.format(len(self.candidates))) | 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 artifact candidates must be hashable and have a :meth:`__eq__`
implemented for validation to work on multi-environments and
distributed environments.
"""
async def slave_task(addr, candidates):
r_manager = await self.env.connect(addr)
return await r_manager.validate_candidates(candidates)
self._log(logging.DEBUG, "Validating {} candidates"
.format(len(self.candidates)))
candidates = self.candidates
if self._single_env:
self._candidates = self.env.validate_candidates(candidates)
else:
mgrs = self.get_managers()
tasks = create_tasks(slave_task, mgrs, candidates, flatten=False)
rets = run(tasks)
valid_candidates = set(self.candidates)
for r in rets:
valid_candidates = valid_candidates.intersection(set(r))
self._candidates = list(valid_candidates)
self._log(logging.DEBUG, "{} candidates after validation"
.format(len(self.candidates))) | [
"def",
"validate_candidates",
"(",
"self",
")",
":",
"async",
"def",
"slave_task",
"(",
"addr",
",",
"candidates",
")",
":",
"r_manager",
"=",
"await",
"self",
".",
"env",
".",
"connect",
"(",
"addr",
")",
"return",
"await",
"r_manager",
".",
"validate_candidates",
"(",
"candidates",
")",
"self",
".",
"_log",
"(",
"logging",
".",
"DEBUG",
",",
"\"Validating {} candidates\"",
".",
"format",
"(",
"len",
"(",
"self",
".",
"candidates",
")",
")",
")",
"candidates",
"=",
"self",
".",
"candidates",
"if",
"self",
".",
"_single_env",
":",
"self",
".",
"_candidates",
"=",
"self",
".",
"env",
".",
"validate_candidates",
"(",
"candidates",
")",
"else",
":",
"mgrs",
"=",
"self",
".",
"get_managers",
"(",
")",
"tasks",
"=",
"create_tasks",
"(",
"slave_task",
",",
"mgrs",
",",
"candidates",
",",
"flatten",
"=",
"False",
")",
"rets",
"=",
"run",
"(",
"tasks",
")",
"valid_candidates",
"=",
"set",
"(",
"self",
".",
"candidates",
")",
"for",
"r",
"in",
"rets",
":",
"valid_candidates",
"=",
"valid_candidates",
".",
"intersection",
"(",
"set",
"(",
"r",
")",
")",
"self",
".",
"_candidates",
"=",
"list",
"(",
"valid_candidates",
")",
"self",
".",
"_log",
"(",
"logging",
".",
"DEBUG",
",",
"\"{} candidates after validation\"",
".",
"format",
"(",
"len",
"(",
"self",
".",
"candidates",
")",
")",
")"
]
| 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 :meth:`__eq__`
implemented for validation to work on multi-environments and
distributed environments. | [
"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:
The voting method to use, see
:meth:`~creamas.vote.VoteOrganizer.compute_results` for details.
:param bool validate: Validate gathered candidates before voting.
:param int winners: The number of vote winners
:returns: Winner(s) of the vote.
"""
self.gather_candidates()
if validate:
self.validate_candidates()
self.gather_votes()
r = self.compute_results(voting_method, self.votes, winners=winners,
**kwargs)
return r | 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:
The voting method to use, see
:meth:`~creamas.vote.VoteOrganizer.compute_results` for details.
:param bool validate: Validate gathered candidates before voting.
:param int winners: The number of vote winners
:returns: Winner(s) of the vote.
"""
self.gather_candidates()
if validate:
self.validate_candidates()
self.gather_votes()
r = self.compute_results(voting_method, self.votes, winners=winners,
**kwargs)
return r | [
"def",
"gather_and_vote",
"(",
"self",
",",
"voting_method",
",",
"validate",
"=",
"False",
",",
"winners",
"=",
"1",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"gather_candidates",
"(",
")",
"if",
"validate",
":",
"self",
".",
"validate_candidates",
"(",
")",
"self",
".",
"gather_votes",
"(",
")",
"r",
"=",
"self",
".",
"compute_results",
"(",
"voting_method",
",",
"self",
".",
"votes",
",",
"winners",
"=",
"winners",
",",
"*",
"*",
"kwargs",
")",
"return",
"r"
]
| 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.
:param bool validate: Validate gathered candidates before voting.
:param int winners: The number of vote winners
:returns: Winner(s) of the vote. | [
"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)
device(frontend, backend) | 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)
device(frontend, backend) | [
"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.publish(self.START) | 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.publish(self.START) | [
"def",
"start",
"(",
"self",
",",
"transaction_context",
"=",
"None",
")",
":",
"transaction_context",
"=",
"transaction_context",
"or",
"{",
"}",
"context_cmd",
"=",
"{",
"'command'",
":",
"'set_transaction_context'",
",",
"'msg'",
":",
"transaction_context",
"}",
"self",
".",
"publish",
"(",
"context_cmd",
")",
"self",
".",
"publish",
"(",
"self",
".",
"START",
")"
]
| 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:
return False
message['name'] = message['turret']
del message['turret']
if not self.add(message, is_started):
return self.update(message)
return True | 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:
return False
message['name'] = message['turret']
del message['turret']
if not self.add(message, is_started):
return self.update(message)
return True | [
"def",
"process_message",
"(",
"self",
",",
"message",
",",
"is_started",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"master",
":",
"return",
"False",
"if",
"'status'",
"not",
"in",
"message",
":",
"return",
"False",
"message",
"[",
"'name'",
"]",
"=",
"message",
"[",
"'turret'",
"]",
"del",
"message",
"[",
"'turret'",
"]",
"if",
"not",
"self",
".",
"add",
"(",
"message",
",",
"is_started",
")",
":",
"return",
"self",
".",
"update",
"(",
"message",
")",
"return",
"True"
]
| 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 False
turret = Turret(**turret_data)
self.write(turret)
self.turrets[turret.uuid] = turret
if is_started:
self.publish(self.START, turret.uuid)
return True | 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 False
turret = Turret(**turret_data)
self.write(turret)
self.turrets[turret.uuid] = turret
if is_started:
self.publish(self.START, turret.uuid)
return True | [
"def",
"add",
"(",
"self",
",",
"turret_data",
",",
"is_started",
"=",
"False",
")",
":",
"if",
"turret_data",
".",
"get",
"(",
"'uuid'",
")",
"in",
"self",
".",
"turrets",
":",
"return",
"False",
"turret",
"=",
"Turret",
"(",
"*",
"*",
"turret_data",
")",
"self",
".",
"write",
"(",
"turret",
")",
"self",
".",
"turrets",
"[",
"turret",
".",
"uuid",
"]",
"=",
"turret",
"if",
"is_started",
":",
"self",
".",
"publish",
"(",
"self",
".",
"START",
",",
"turret",
".",
"uuid",
")",
"return",
"True"
]
| 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)
self.write(turret)
return True | 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)
self.write(turret)
return True | [
"def",
"update",
"(",
"self",
",",
"turret_data",
")",
":",
"if",
"turret_data",
".",
"get",
"(",
"'uuid'",
")",
"not",
"in",
"self",
".",
"turrets",
":",
"return",
"False",
"turret",
"=",
"self",
".",
"turrets",
"[",
"turret_data",
".",
"get",
"(",
"'uuid'",
")",
"]",
"turret",
".",
"update",
"(",
"*",
"*",
"turret_data",
")",
"self",
".",
"write",
"(",
"turret",
")",
"return",
"True"
]
| 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 ''
data = json.dumps(message)
self.publisher.send_string("%s %s" % (channel, data)) | 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 ''
data = json.dumps(message)
self.publisher.send_string("%s %s" % (channel, data)) | [
"def",
"publish",
"(",
"self",
",",
"message",
",",
"channel",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"master",
":",
"return",
"channel",
"=",
"channel",
"or",
"''",
"data",
"=",
"json",
".",
"dumps",
"(",
"message",
")",
"self",
".",
"publisher",
".",
"send_string",
"(",
"\"%s %s\"",
"%",
"(",
"channel",
",",
"data",
")",
")"
]
| 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
psiturk_access_key_id = os.getenv(
"psiturk_access_key_id",
self.config.get("psiTurk Access", "psiturk_access_key_id"))
psiturk_secret_access_id = os.getenv(
"psiturk_secret_access_id",
self.config.get("psiTurk Access", "psiturk_secret_access_id"))
web_services = PsiturkOrgServices(
psiturk_access_key_id,
psiturk_secret_access_id)
aws_rds_services = RDSServices(
self.aws_access_key_id,
self.aws_secret_access_key,
self.aws_region)
self.amt_services = MTurkServices(
self.aws_access_key_id,
self.aws_secret_access_key,
self.config.getboolean(
'Shell Parameters', 'launch_in_sandbox_mode'))
self.shell = PsiturkNetworkShell(
self.config, self.amt_services, aws_rds_services, web_services,
self.server,
self.config.getboolean(
'Shell Parameters', 'launch_in_sandbox_mode'))
try:
participants = Participant.query.all()
assert(participants)
except Exception:
# Create the first HIT.
self.shell.hit_create(
n,
self.config.get('HIT Configuration', 'base_payment'),
self.config.get('HIT Configuration', 'duration'))
else:
# HIT was already created, no need to recreate it.
print "Reject recruitment reopening: experiment has started." | 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
psiturk_access_key_id = os.getenv(
"psiturk_access_key_id",
self.config.get("psiTurk Access", "psiturk_access_key_id"))
psiturk_secret_access_id = os.getenv(
"psiturk_secret_access_id",
self.config.get("psiTurk Access", "psiturk_secret_access_id"))
web_services = PsiturkOrgServices(
psiturk_access_key_id,
psiturk_secret_access_id)
aws_rds_services = RDSServices(
self.aws_access_key_id,
self.aws_secret_access_key,
self.aws_region)
self.amt_services = MTurkServices(
self.aws_access_key_id,
self.aws_secret_access_key,
self.config.getboolean(
'Shell Parameters', 'launch_in_sandbox_mode'))
self.shell = PsiturkNetworkShell(
self.config, self.amt_services, aws_rds_services, web_services,
self.server,
self.config.getboolean(
'Shell Parameters', 'launch_in_sandbox_mode'))
try:
participants = Participant.query.all()
assert(participants)
except Exception:
# Create the first HIT.
self.shell.hit_create(
n,
self.config.get('HIT Configuration', 'base_payment'),
self.config.get('HIT Configuration', 'duration'))
else:
# HIT was already created, no need to recreate it.
print "Reject recruitment reopening: experiment has started." | [
"def",
"open_recruitment",
"(",
"self",
",",
"n",
"=",
"1",
")",
":",
"from",
"psiturk",
".",
"amt_services",
"import",
"MTurkServices",
",",
"RDSServices",
"from",
"psiturk",
".",
"psiturk_shell",
"import",
"PsiturkNetworkShell",
"from",
"psiturk",
".",
"psiturk_org_services",
"import",
"PsiturkOrgServices",
"psiturk_access_key_id",
"=",
"os",
".",
"getenv",
"(",
"\"psiturk_access_key_id\"",
",",
"self",
".",
"config",
".",
"get",
"(",
"\"psiTurk Access\"",
",",
"\"psiturk_access_key_id\"",
")",
")",
"psiturk_secret_access_id",
"=",
"os",
".",
"getenv",
"(",
"\"psiturk_secret_access_id\"",
",",
"self",
".",
"config",
".",
"get",
"(",
"\"psiTurk Access\"",
",",
"\"psiturk_secret_access_id\"",
")",
")",
"web_services",
"=",
"PsiturkOrgServices",
"(",
"psiturk_access_key_id",
",",
"psiturk_secret_access_id",
")",
"aws_rds_services",
"=",
"RDSServices",
"(",
"self",
".",
"aws_access_key_id",
",",
"self",
".",
"aws_secret_access_key",
",",
"self",
".",
"aws_region",
")",
"self",
".",
"amt_services",
"=",
"MTurkServices",
"(",
"self",
".",
"aws_access_key_id",
",",
"self",
".",
"aws_secret_access_key",
",",
"self",
".",
"config",
".",
"getboolean",
"(",
"'Shell Parameters'",
",",
"'launch_in_sandbox_mode'",
")",
")",
"self",
".",
"shell",
"=",
"PsiturkNetworkShell",
"(",
"self",
".",
"config",
",",
"self",
".",
"amt_services",
",",
"aws_rds_services",
",",
"web_services",
",",
"self",
".",
"server",
",",
"self",
".",
"config",
".",
"getboolean",
"(",
"'Shell Parameters'",
",",
"'launch_in_sandbox_mode'",
")",
")",
"try",
":",
"participants",
"=",
"Participant",
".",
"query",
".",
"all",
"(",
")",
"assert",
"(",
"participants",
")",
"except",
"Exception",
":",
"# Create the first HIT.",
"self",
".",
"shell",
".",
"hit_create",
"(",
"n",
",",
"self",
".",
"config",
".",
"get",
"(",
"'HIT Configuration'",
",",
"'base_payment'",
")",
",",
"self",
".",
"config",
".",
"get",
"(",
"'HIT Configuration'",
",",
"'duration'",
")",
")",
"else",
":",
"# HIT was already created, no need to recreate it.",
"print",
"\"Reject recruitment reopening: experiment has started.\""
]
| 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', 'launch_in_sandbox_mode'))
return self.amt_services.approve_worker(assignment_id) | 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', 'launch_in_sandbox_mode'))
return self.amt_services.approve_worker(assignment_id) | [
"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",
",",
"self",
".",
"config",
".",
"getboolean",
"(",
"'Shell Parameters'",
",",
"'launch_in_sandbox_mode'",
")",
")",
"return",
"self",
".",
"amt_services",
".",
"approve_worker",
"(",
"assignment_id",
")"
]
| 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(
'Shell Parameters', 'launch_in_sandbox_mode'))
return self.amt_services.bonus_worker(assignment_id, amount, reason) | 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(
'Shell Parameters', 'launch_in_sandbox_mode'))
return self.amt_services.bonus_worker(assignment_id, amount, reason) | [
"def",
"reward_bonus",
"(",
"self",
",",
"assignment_id",
",",
"amount",
",",
"reason",
")",
":",
"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'",
",",
"'launch_in_sandbox_mode'",
")",
")",
"return",
"self",
".",
"amt_services",
".",
"bonus_worker",
"(",
"assignment_id",
",",
"amount",
",",
"reason",
")"
]
| 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_by(func.random()).limit(limit).all()
if auto_close: # pragma: no cover
ses.close()
return result | 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_by(func.random()).limit(limit).all()
if auto_close: # pragma: no cover
ses.close()
return result | [
"def",
"random",
"(",
"cls",
",",
"engine_or_session",
",",
"limit",
"=",
"5",
")",
":",
"ses",
",",
"auto_close",
"=",
"ensure_session",
"(",
"engine_or_session",
")",
"result",
"=",
"ses",
".",
"query",
"(",
"cls",
")",
".",
"order_by",
"(",
"func",
".",
"random",
"(",
")",
")",
".",
"limit",
"(",
"limit",
")",
".",
"all",
"(",
")",
"if",
"auto_close",
":",
"# pragma: no cover",
"ses",
".",
"close",
"(",
")",
"return",
"result"
]
| 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",
nargs=argparse.REMAINDER,
help="Floating point data, any delimiter."
)
parser.add_argument(
"--version",
"-v",
action="store_true",
help="Display the version number and exit."
)
args = parser.parse_args()
if args.version:
version = require("pysparklines")[0].version
print (version)
sys.exit(0)
if os.isatty(0) and not args.data:
parser.print_help()
sys.exit(1)
elif args.data:
arg_string = u' '.join(args.data)
else:
arg_string = sys.stdin.read()
try:
output = sparkify(guess_series(arg_string))
except:
sys.stderr.write("Could not convert input data to valid sparkline\n")
sys.exit(1)
print (output.encode('utf-8', 'ignore')) | 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",
nargs=argparse.REMAINDER,
help="Floating point data, any delimiter."
)
parser.add_argument(
"--version",
"-v",
action="store_true",
help="Display the version number and exit."
)
args = parser.parse_args()
if args.version:
version = require("pysparklines")[0].version
print (version)
sys.exit(0)
if os.isatty(0) and not args.data:
parser.print_help()
sys.exit(1)
elif args.data:
arg_string = u' '.join(args.data)
else:
arg_string = sys.stdin.read()
try:
output = sparkify(guess_series(arg_string))
except:
sys.stderr.write("Could not convert input data to valid sparkline\n")
sys.exit(1)
print (output.encode('utf-8', 'ignore')) | [
"def",
"main",
"(",
")",
":",
"import",
"argparse",
"from",
"pkg_resources",
"import",
"require",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"main",
".",
"__doc__",
")",
"parser",
".",
"add_argument",
"(",
"\"data\"",
",",
"nargs",
"=",
"argparse",
".",
"REMAINDER",
",",
"help",
"=",
"\"Floating point data, any delimiter.\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--version\"",
",",
"\"-v\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Display the version number and exit.\"",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"if",
"args",
".",
"version",
":",
"version",
"=",
"require",
"(",
"\"pysparklines\"",
")",
"[",
"0",
"]",
".",
"version",
"print",
"(",
"version",
")",
"sys",
".",
"exit",
"(",
"0",
")",
"if",
"os",
".",
"isatty",
"(",
"0",
")",
"and",
"not",
"args",
".",
"data",
":",
"parser",
".",
"print_help",
"(",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"elif",
"args",
".",
"data",
":",
"arg_string",
"=",
"u' '",
".",
"join",
"(",
"args",
".",
"data",
")",
"else",
":",
"arg_string",
"=",
"sys",
".",
"stdin",
".",
"read",
"(",
")",
"try",
":",
"output",
"=",
"sparkify",
"(",
"guess_series",
"(",
"arg_string",
")",
")",
"except",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"Could not convert input data to valid sparkline\\n\"",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"print",
"(",
"output",
".",
"encode",
"(",
"'utf-8'",
",",
"'ignore'",
")",
")"
]
| 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 the cache
if sub_state not in self._is_active:
params = self._transform_state_to_dict(sub_state)
# We add the result of the expression for this state of the multiplex to the cache
self._is_active[sub_state] = self.expression.evaluate(**params)
return self._is_active[sub_state] | 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 the cache
if sub_state not in self._is_active:
params = self._transform_state_to_dict(sub_state)
# We add the result of the expression for this state of the multiplex to the cache
self._is_active[sub_state] = self.expression.evaluate(**params)
return self._is_active[sub_state] | [
"def",
"is_active",
"(",
"self",
",",
"state",
":",
"'State'",
")",
"->",
"bool",
":",
"# 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 the cache",
"if",
"sub_state",
"not",
"in",
"self",
".",
"_is_active",
":",
"params",
"=",
"self",
".",
"_transform_state_to_dict",
"(",
"sub_state",
")",
"# We add the result of the expression for this state of the multiplex to the cache",
"self",
".",
"_is_active",
"[",
"sub_state",
"]",
"=",
"self",
".",
"expression",
".",
"evaluate",
"(",
"*",
"*",
"params",
")",
"return",
"self",
".",
"_is_active",
"[",
"sub_state",
"]"
]
| 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:
layers = key.split('.')
value = self.registrar
for key in layers:
value = value[key]
return value
except:
return None | 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:
layers = key.split('.')
value = self.registrar
for key in layers:
value = value[key]
return value
except:
return None | [
"def",
"get",
"(",
"self",
",",
"key",
")",
":",
"try",
":",
"layers",
"=",
"key",
".",
"split",
"(",
"'.'",
")",
"value",
"=",
"self",
".",
"registrar",
"for",
"key",
"in",
"layers",
":",
"value",
"=",
"value",
"[",
"key",
"]",
"return",
"value",
"except",
":",
"return",
"None"
]
| 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]:
target = target.setdefault(element, dict())
target[key.split(".")[-1]] = value | 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]:
target = target.setdefault(element, dict())
target[key.split(".")[-1]] = value | [
"def",
"set",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"target",
"=",
"self",
".",
"registrar",
"for",
"element",
"in",
"key",
".",
"split",
"(",
"'.'",
")",
"[",
":",
"-",
"1",
"]",
":",
"target",
"=",
"target",
".",
"setdefault",
"(",
"element",
",",
"dict",
"(",
")",
")",
"target",
"[",
"key",
".",
"split",
"(",
"\".\"",
")",
"[",
"-",
"1",
"]",
"]",
"=",
"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. | [
"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 arguments): the keyword arguments
that are passed to the class of accessor.
"""
if cls.accessor is not None:
if cls.instance is None:
cls.instance = cls.accessor(*args, **kwargs) | 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 arguments): the keyword arguments
that are passed to the class of accessor.
"""
if cls.accessor is not None:
if cls.instance is None:
cls.instance = cls.accessor(*args, **kwargs) | [
"def",
"boot",
"(",
"cls",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"cls",
".",
"accessor",
"is",
"not",
"None",
":",
"if",
"cls",
".",
"instance",
"is",
"None",
":",
"cls",
".",
"instance",
"=",
"cls",
".",
"accessor",
"(",
"*",
"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 arguments): the keyword arguments
that are passed to the class of accessor. | [
"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 None:
cls.instance = cls.accessor(config) | 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 None:
cls.instance = cls.accessor(config) | [
"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,
RHTMLName = self.rhtmlname,
FunctionalClassID = self.functional_class_id,
PPDBMFunctionalClassID = self.functional_class_id_ppdbm,
PPDBMDifficulty = self.difficulty_ppdbm,
IsWildType = self.is_wildtype,
WildTypeComplexID = self.wildtype_complex,
Notes = self.notes,
Warnings = self.warnings,
)
if self.id:
d['ID'] = self.id
return d | 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,
RHTMLName = self.rhtmlname,
FunctionalClassID = self.functional_class_id,
PPDBMFunctionalClassID = self.functional_class_id_ppdbm,
PPDBMDifficulty = self.difficulty_ppdbm,
IsWildType = self.is_wildtype,
WildTypeComplexID = self.wildtype_complex,
Notes = self.notes,
Warnings = self.warnings,
)
if self.id:
d['ID'] = self.id
return d | [
"def",
"get_complex",
"(",
"self",
")",
":",
"d",
"=",
"dict",
"(",
"LName",
"=",
"self",
".",
"lname",
",",
"LShortName",
"=",
"self",
".",
"lshortname",
",",
"LHTMLName",
"=",
"self",
".",
"lhtmlname",
",",
"RName",
"=",
"self",
".",
"rname",
",",
"RShortName",
"=",
"self",
".",
"rshortname",
",",
"RHTMLName",
"=",
"self",
".",
"rhtmlname",
",",
"FunctionalClassID",
"=",
"self",
".",
"functional_class_id",
",",
"PPDBMFunctionalClassID",
"=",
"self",
".",
"functional_class_id_ppdbm",
",",
"PPDBMDifficulty",
"=",
"self",
".",
"difficulty_ppdbm",
",",
"IsWildType",
"=",
"self",
".",
"is_wildtype",
",",
"WildTypeComplexID",
"=",
"self",
".",
"wildtype_complex",
",",
"Notes",
"=",
"self",
".",
"notes",
",",
"Warnings",
"=",
"self",
".",
"warnings",
",",
")",
"if",
"self",
".",
"id",
":",
"d",
"[",
"'ID'",
"]",
"=",
"self",
".",
"id",
"return",
"d"
]
| 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 = self.id,
SetNumber = pdb_set['set_number'],
IsComplex = pdb_set['is_complex'],
Notes = pdb_set['notes'],
)
chain_records = []
for side, chain_details in sorted(pdb_set['chains'].iteritems()):
chain_records.append(dict(
PPComplexID = self.id,
SetNumber = pdb_set['set_number'],
Side = side,
ChainIndex = chain_details['chain_index'],
PDBFileID = chain_details['pdb_file_id'],
Chain = chain_details['chain_id'],
NMRModel = chain_details['nmr_model'],
))
data.append(dict(pdb_set = pdb_set_record, chain_records = chain_records))
return data | 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 = self.id,
SetNumber = pdb_set['set_number'],
IsComplex = pdb_set['is_complex'],
Notes = pdb_set['notes'],
)
chain_records = []
for side, chain_details in sorted(pdb_set['chains'].iteritems()):
chain_records.append(dict(
PPComplexID = self.id,
SetNumber = pdb_set['set_number'],
Side = side,
ChainIndex = chain_details['chain_index'],
PDBFileID = chain_details['pdb_file_id'],
Chain = chain_details['chain_id'],
NMRModel = chain_details['nmr_model'],
))
data.append(dict(pdb_set = pdb_set_record, chain_records = chain_records))
return data | [
"def",
"get_pdb_sets",
"(",
"self",
")",
":",
"assert",
"(",
"self",
".",
"id",
"!=",
"None",
")",
"data",
"=",
"[",
"]",
"for",
"pdb_set",
"in",
"self",
".",
"pdb_sets",
":",
"pdb_set_record",
"=",
"dict",
"(",
"PPComplexID",
"=",
"self",
".",
"id",
",",
"SetNumber",
"=",
"pdb_set",
"[",
"'set_number'",
"]",
",",
"IsComplex",
"=",
"pdb_set",
"[",
"'is_complex'",
"]",
",",
"Notes",
"=",
"pdb_set",
"[",
"'notes'",
"]",
",",
")",
"chain_records",
"=",
"[",
"]",
"for",
"side",
",",
"chain_details",
"in",
"sorted",
"(",
"pdb_set",
"[",
"'chains'",
"]",
".",
"iteritems",
"(",
")",
")",
":",
"chain_records",
".",
"append",
"(",
"dict",
"(",
"PPComplexID",
"=",
"self",
".",
"id",
",",
"SetNumber",
"=",
"pdb_set",
"[",
"'set_number'",
"]",
",",
"Side",
"=",
"side",
",",
"ChainIndex",
"=",
"chain_details",
"[",
"'chain_index'",
"]",
",",
"PDBFileID",
"=",
"chain_details",
"[",
"'pdb_file_id'",
"]",
",",
"Chain",
"=",
"chain_details",
"[",
"'chain_id'",
"]",
",",
"NMRModel",
"=",
"chain_details",
"[",
"'nmr_model'",
"]",
",",
")",
")",
"data",
".",
"append",
"(",
"dict",
"(",
"pdb_set",
"=",
"pdb_set_record",
",",
"chain_records",
"=",
"chain_records",
")",
")",
"return",
"data"
]
| 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",
"(",
"pos",
".",
"childNodes",
")",
"==",
"1",
")",
"return",
"float",
"(",
"pos",
".",
"childNodes",
"[",
"0",
"]",
".",
"data",
")"
]
| 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 floats allowed
return int(v) | 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 floats allowed
return int(v) | [
"def",
"parse_singular_int",
"(",
"t",
",",
"tag_name",
")",
":",
"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 floats allowed",
"return",
"int",
"(",
"v",
")"
]
| 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
assert(len(v) == 1 and v >= 'A' and 'v' <= 'z') # no floats allowed
return v | 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
assert(len(v) == 1 and v >= 'A' and 'v' <= 'z') # no floats allowed
return v | [
"def",
"parse_singular_alphabetic_character",
"(",
"t",
",",
"tag_name",
")",
":",
"pos",
"=",
"t",
".",
"getElementsByTagName",
"(",
"tag_name",
")",
"assert",
"(",
"len",
"(",
"pos",
")",
"==",
"1",
")",
"pos",
"=",
"pos",
"[",
"0",
"]",
"assert",
"(",
"len",
"(",
"pos",
".",
"childNodes",
")",
"==",
"1",
")",
"v",
"=",
"pos",
".",
"childNodes",
"[",
"0",
"]",
".",
"data",
"assert",
"(",
"len",
"(",
"v",
")",
"==",
"1",
"and",
"v",
">=",
"'A'",
"and",
"'v'",
"<=",
"'z'",
")",
"# no floats allowed",
"return",
"v"
]
| 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",
"(",
"pos",
".",
"childNodes",
")",
"==",
"1",
")",
"return",
"pos",
".",
"childNodes",
"[",
"0",
"]",
".",
"data"
]
| 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': 1000}, 1))
.. testoutput::
['dog']
Args:
weights (dict): item -> weight mapping, non-positive weights are forbidden
n (int): number of chosen items
Returns:
list: randomly chosen items
"""
if n > len(weights):
raise Exception("Can't choose {} samples from {} items".format(n, len(weights)))
if any(map(lambda w: w <= 0, weights.values())):
raise Exception("The weight can't be a non-positive number.")
items = weights.items()
chosen = set()
for i in range(n):
total = sum(list(zip(*items))[1])
dice = random.random() * total
running_weight = 0
chosen_item = None
for item, weight in items:
if dice < running_weight + weight:
chosen_item = item
break
running_weight += weight
chosen.add(chosen_item)
items = [(i, w) for (i, w) in items if i != chosen_item]
return list(chosen) | 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': 1000}, 1))
.. testoutput::
['dog']
Args:
weights (dict): item -> weight mapping, non-positive weights are forbidden
n (int): number of chosen items
Returns:
list: randomly chosen items
"""
if n > len(weights):
raise Exception("Can't choose {} samples from {} items".format(n, len(weights)))
if any(map(lambda w: w <= 0, weights.values())):
raise Exception("The weight can't be a non-positive number.")
items = weights.items()
chosen = set()
for i in range(n):
total = sum(list(zip(*items))[1])
dice = random.random() * total
running_weight = 0
chosen_item = None
for item, weight in items:
if dice < running_weight + weight:
chosen_item = item
break
running_weight += weight
chosen.add(chosen_item)
items = [(i, w) for (i, w) in items if i != chosen_item]
return list(chosen) | [
"def",
"roulette",
"(",
"weights",
",",
"n",
")",
":",
"if",
"n",
">",
"len",
"(",
"weights",
")",
":",
"raise",
"Exception",
"(",
"\"Can't choose {} samples from {} items\"",
".",
"format",
"(",
"n",
",",
"len",
"(",
"weights",
")",
")",
")",
"if",
"any",
"(",
"map",
"(",
"lambda",
"w",
":",
"w",
"<=",
"0",
",",
"weights",
".",
"values",
"(",
")",
")",
")",
":",
"raise",
"Exception",
"(",
"\"The weight can't be a non-positive number.\"",
")",
"items",
"=",
"weights",
".",
"items",
"(",
")",
"chosen",
"=",
"set",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"n",
")",
":",
"total",
"=",
"sum",
"(",
"list",
"(",
"zip",
"(",
"*",
"items",
")",
")",
"[",
"1",
"]",
")",
"dice",
"=",
"random",
".",
"random",
"(",
")",
"*",
"total",
"running_weight",
"=",
"0",
"chosen_item",
"=",
"None",
"for",
"item",
",",
"weight",
"in",
"items",
":",
"if",
"dice",
"<",
"running_weight",
"+",
"weight",
":",
"chosen_item",
"=",
"item",
"break",
"running_weight",
"+=",
"weight",
"chosen",
".",
"add",
"(",
"chosen_item",
")",
"items",
"=",
"[",
"(",
"i",
",",
"w",
")",
"for",
"(",
"i",
",",
"w",
")",
"in",
"items",
"if",
"i",
"!=",
"chosen_item",
"]",
"return",
"list",
"(",
"chosen",
")"
]
| 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::
['dog']
Args:
weights (dict): item -> weight mapping, non-positive weights are forbidden
n (int): number of chosen items
Returns:
list: randomly chosen items | [
"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 (%d)' % (title, count)
return title | 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 (%d)' % (title, count)
return title | [
"def",
"get_title",
"(",
"self",
",",
"group",
"=",
"None",
")",
":",
"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 (%d)'",
"%",
"(",
"title",
",",
"count",
")",
"return",
"title"
]
| 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,
message=message.strip())
comment.save()
msg = _(u'Comment added.')
if request.POST.get('sendmail', ''):
self._send_mail(comment, group)
if 'postresolve' in request.POST:
self._resolve_group(request, group)
msg = _(u'Comment added and event marked as resolved.')
messages.success(request, msg)
return HttpResponseRedirect(request.path)
query = GroupComments.objects.filter(group=group).order_by('-created')
return self.render('sentry_comments/index.html', {
'comments': query,
'group': group,
}) | 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,
message=message.strip())
comment.save()
msg = _(u'Comment added.')
if request.POST.get('sendmail', ''):
self._send_mail(comment, group)
if 'postresolve' in request.POST:
self._resolve_group(request, group)
msg = _(u'Comment added and event marked as resolved.')
messages.success(request, msg)
return HttpResponseRedirect(request.path)
query = GroupComments.objects.filter(group=group).order_by('-created')
return self.render('sentry_comments/index.html', {
'comments': query,
'group': group,
}) | [
"def",
"view",
"(",
"self",
",",
"request",
",",
"group",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"request",
".",
"method",
"==",
"'POST'",
":",
"message",
"=",
"request",
".",
"POST",
".",
"get",
"(",
"'message'",
")",
"if",
"message",
"is",
"not",
"None",
"and",
"message",
".",
"strip",
"(",
")",
":",
"comment",
"=",
"GroupComments",
"(",
"group",
"=",
"group",
",",
"author",
"=",
"request",
".",
"user",
",",
"message",
"=",
"message",
".",
"strip",
"(",
")",
")",
"comment",
".",
"save",
"(",
")",
"msg",
"=",
"_",
"(",
"u'Comment added.'",
")",
"if",
"request",
".",
"POST",
".",
"get",
"(",
"'sendmail'",
",",
"''",
")",
":",
"self",
".",
"_send_mail",
"(",
"comment",
",",
"group",
")",
"if",
"'postresolve'",
"in",
"request",
".",
"POST",
":",
"self",
".",
"_resolve_group",
"(",
"request",
",",
"group",
")",
"msg",
"=",
"_",
"(",
"u'Comment added and event marked as resolved.'",
")",
"messages",
".",
"success",
"(",
"request",
",",
"msg",
")",
"return",
"HttpResponseRedirect",
"(",
"request",
".",
"path",
")",
"query",
"=",
"GroupComments",
".",
"objects",
".",
"filter",
"(",
"group",
"=",
"group",
")",
".",
"order_by",
"(",
"'-created'",
")",
"return",
"self",
".",
"render",
"(",
"'sentry_comments/index.html'",
",",
"{",
"'comments'",
":",
"query",
",",
"'group'",
":",
"group",
",",
"}",
")"
]
| 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['raw'], name + '_response_times.svg', results_dir)
graphs.resp_graph(data['compiled'], name + '_response_times_intervals.svg', results_dir)
graphs.tp_graph(data['compiled'], name + '_throughput.svg', results_dir) | 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['raw'], name + '_response_times.svg', results_dir)
graphs.resp_graph(data['compiled'], name + '_response_times_intervals.svg', results_dir)
graphs.tp_graph(data['compiled'], name + '_throughput.svg', results_dir) | [
"def",
"generate_graphs",
"(",
"data",
",",
"name",
",",
"results_dir",
")",
":",
"graphs",
".",
"resp_graph_raw",
"(",
"data",
"[",
"'raw'",
"]",
",",
"name",
"+",
"'_response_times.svg'",
",",
"results_dir",
")",
"graphs",
".",
"resp_graph",
"(",
"data",
"[",
"'compiled'",
"]",
",",
"name",
"+",
"'_response_times_intervals.svg'",
",",
"results_dir",
")",
"graphs",
".",
"tp_graph",
"(",
"data",
"[",
"'compiled'",
"]",
",",
"name",
"+",
"'_throughput.svg'",
",",
"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 | [
"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)
print('test start: %s' % results.start_datetime)
print('test finish: %s\n' % results.finish_datetime) | 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)
print('test start: %s' % results.start_datetime)
print('test finish: %s\n' % results.finish_datetime) | [
"def",
"print_infos",
"(",
"results",
")",
":",
"print",
"(",
"'transactions: %i'",
"%",
"results",
".",
"total_transactions",
")",
"print",
"(",
"'timers: %i'",
"%",
"results",
".",
"total_timers",
")",
"print",
"(",
"'errors: %i'",
"%",
"results",
".",
"total_errors",
")",
"print",
"(",
"'test start: %s'",
"%",
"results",
".",
"start_datetime",
")",
"print",
"(",
"'test finish: %s\\n'",
"%",
"results",
".",
"finish_datetime",
")"
]
| 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()
j_env = Environment(loader=FileSystemLoader(os.path.join(results_dir, parent, 'templates')))
template = j_env.get_template('report.html')
report_writer = ReportWriter(results_dir, parent)
report_writer.write_report(template.render(data))
print("HTML report generated in {} seconds\n".format(time.time() - partial)) | 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()
j_env = Environment(loader=FileSystemLoader(os.path.join(results_dir, parent, 'templates')))
template = j_env.get_template('report.html')
report_writer = ReportWriter(results_dir, parent)
report_writer.write_report(template.render(data))
print("HTML report generated in {} seconds\n".format(time.time() - partial)) | [
"def",
"write_template",
"(",
"data",
",",
"results_dir",
",",
"parent",
")",
":",
"print",
"(",
"\"Generating html report...\"",
")",
"partial",
"=",
"time",
".",
"time",
"(",
")",
"j_env",
"=",
"Environment",
"(",
"loader",
"=",
"FileSystemLoader",
"(",
"os",
".",
"path",
".",
"join",
"(",
"results_dir",
",",
"parent",
",",
"'templates'",
")",
")",
")",
"template",
"=",
"j_env",
".",
"get_template",
"(",
"'report.html'",
")",
"report_writer",
"=",
"ReportWriter",
"(",
"results_dir",
",",
"parent",
")",
"report_writer",
".",
"write_report",
"(",
"template",
".",
"render",
"(",
"data",
")",
")",
"print",
"(",
"\"HTML report generated in {} seconds\\n\"",
".",
"format",
"(",
"time",
".",
"time",
"(",
")",
"-",
"partial",
")",
")"
]
| 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...")
results_dir = os.path.abspath(results_dir)
results = ReportResults(config['run_time'], config['results_ts_interval'])
results.compile_results()
print("Results compiled in {} seconds\n".format(time.time() - start))
if results.total_transactions == 0:
print("No results, cannot create report")
return False
print_infos(results)
data = {
'report': results,
'run_time': config['run_time'],
'ts_interval': config['results_ts_interval'],
'turrets_config': results.turrets,
'results': {"all": results.main_results, "timers": results.timers_results}
}
print("Generating graphs...")
partial = time.time()
generate_graphs(results.main_results, 'All_Transactions', results_dir)
for key, value in results.timers_results.items():
generate_graphs(value, key, results_dir)
print("All graphs generated in {} seconds\n".format(time.time() - partial))
write_template(data, results_dir, parent)
print("Full report generated in {} seconds".format(time.time() - start))
return True | 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...")
results_dir = os.path.abspath(results_dir)
results = ReportResults(config['run_time'], config['results_ts_interval'])
results.compile_results()
print("Results compiled in {} seconds\n".format(time.time() - start))
if results.total_transactions == 0:
print("No results, cannot create report")
return False
print_infos(results)
data = {
'report': results,
'run_time': config['run_time'],
'ts_interval': config['results_ts_interval'],
'turrets_config': results.turrets,
'results': {"all": results.main_results, "timers": results.timers_results}
}
print("Generating graphs...")
partial = time.time()
generate_graphs(results.main_results, 'All_Transactions', results_dir)
for key, value in results.timers_results.items():
generate_graphs(value, key, results_dir)
print("All graphs generated in {} seconds\n".format(time.time() - partial))
write_template(data, results_dir, parent)
print("Full report generated in {} seconds".format(time.time() - start))
return True | [
"def",
"output",
"(",
"results_dir",
",",
"config",
",",
"parent",
"=",
"'../../'",
")",
":",
"start",
"=",
"time",
".",
"time",
"(",
")",
"print",
"(",
"\"Compiling results...\"",
")",
"results_dir",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"results_dir",
")",
"results",
"=",
"ReportResults",
"(",
"config",
"[",
"'run_time'",
"]",
",",
"config",
"[",
"'results_ts_interval'",
"]",
")",
"results",
".",
"compile_results",
"(",
")",
"print",
"(",
"\"Results compiled in {} seconds\\n\"",
".",
"format",
"(",
"time",
".",
"time",
"(",
")",
"-",
"start",
")",
")",
"if",
"results",
".",
"total_transactions",
"==",
"0",
":",
"print",
"(",
"\"No results, cannot create report\"",
")",
"return",
"False",
"print_infos",
"(",
"results",
")",
"data",
"=",
"{",
"'report'",
":",
"results",
",",
"'run_time'",
":",
"config",
"[",
"'run_time'",
"]",
",",
"'ts_interval'",
":",
"config",
"[",
"'results_ts_interval'",
"]",
",",
"'turrets_config'",
":",
"results",
".",
"turrets",
",",
"'results'",
":",
"{",
"\"all\"",
":",
"results",
".",
"main_results",
",",
"\"timers\"",
":",
"results",
".",
"timers_results",
"}",
"}",
"print",
"(",
"\"Generating graphs...\"",
")",
"partial",
"=",
"time",
".",
"time",
"(",
")",
"generate_graphs",
"(",
"results",
".",
"main_results",
",",
"'All_Transactions'",
",",
"results_dir",
")",
"for",
"key",
",",
"value",
"in",
"results",
".",
"timers_results",
".",
"items",
"(",
")",
":",
"generate_graphs",
"(",
"value",
",",
"key",
",",
"results_dir",
")",
"print",
"(",
"\"All graphs generated in {} seconds\\n\"",
".",
"format",
"(",
"time",
".",
"time",
"(",
")",
"-",
"partial",
")",
")",
"write_template",
"(",
"data",
",",
"results_dir",
",",
"parent",
")",
"print",
"(",
"\"Full report generated in {} seconds\"",
".",
"format",
"(",
"time",
".",
"time",
"(",
")",
"-",
"start",
")",
")",
"return",
"True"
]
| 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 feature:
echo(yellow('Please specify a feature to install. \n'))
for index, item in enumerate(os.listdir(req_path)):
item = item.replace('.txt', '')
echo(green('{}. {}'.format(index + 1, item)))
echo()
return
# install if got feature name
feature_file = feature.lower() + '.txt'
feature_reqs = os.path.join(req_path, feature_file)
# check existence
if not os.path.isfile(feature_reqs):
msg = 'Unable to locate feature requirements file [{}]'
echo(red(msg.format(feature_file)) + '\n')
return
msg = 'Now installing dependencies for "{}" feature...'.format(feature)
echo(yellow(msg))
subprocess.check_call([
sys.executable, '-m', 'pip', 'install', '-r', feature_reqs]
)
# update requirements file with dependencies
reqs = os.path.join(os.getcwd(), 'requirements.txt')
if os.path.exists(reqs):
with open(reqs) as file:
existing = [x.strip().split('==')[0] for x in file.readlines() if x]
lines = ['\n']
with open(feature_reqs) as file:
incoming = file.readlines()
for line in incoming:
if not(len(line)) or line.startswith('#'):
lines.append(line)
continue
package = line.strip().split('==')[0]
if package not in existing:
lines.append(line)
with open(reqs, 'a') as file:
file.writelines(lines)
echo(green('DONE\n')) | 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 feature:
echo(yellow('Please specify a feature to install. \n'))
for index, item in enumerate(os.listdir(req_path)):
item = item.replace('.txt', '')
echo(green('{}. {}'.format(index + 1, item)))
echo()
return
# install if got feature name
feature_file = feature.lower() + '.txt'
feature_reqs = os.path.join(req_path, feature_file)
# check existence
if not os.path.isfile(feature_reqs):
msg = 'Unable to locate feature requirements file [{}]'
echo(red(msg.format(feature_file)) + '\n')
return
msg = 'Now installing dependencies for "{}" feature...'.format(feature)
echo(yellow(msg))
subprocess.check_call([
sys.executable, '-m', 'pip', 'install', '-r', feature_reqs]
)
# update requirements file with dependencies
reqs = os.path.join(os.getcwd(), 'requirements.txt')
if os.path.exists(reqs):
with open(reqs) as file:
existing = [x.strip().split('==')[0] for x in file.readlines() if x]
lines = ['\n']
with open(feature_reqs) as file:
incoming = file.readlines()
for line in incoming:
if not(len(line)) or line.startswith('#'):
lines.append(line)
continue
package = line.strip().split('==')[0]
if package not in existing:
lines.append(line)
with open(reqs, 'a') as file:
file.writelines(lines)
echo(green('DONE\n')) | [
"def",
"install_dependencies",
"(",
"feature",
"=",
"None",
")",
":",
"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",
"feature",
":",
"echo",
"(",
"yellow",
"(",
"'Please specify a feature to install. \\n'",
")",
")",
"for",
"index",
",",
"item",
"in",
"enumerate",
"(",
"os",
".",
"listdir",
"(",
"req_path",
")",
")",
":",
"item",
"=",
"item",
".",
"replace",
"(",
"'.txt'",
",",
"''",
")",
"echo",
"(",
"green",
"(",
"'{}. {}'",
".",
"format",
"(",
"index",
"+",
"1",
",",
"item",
")",
")",
")",
"echo",
"(",
")",
"return",
"# install if got feature name",
"feature_file",
"=",
"feature",
".",
"lower",
"(",
")",
"+",
"'.txt'",
"feature_reqs",
"=",
"os",
".",
"path",
".",
"join",
"(",
"req_path",
",",
"feature_file",
")",
"# check existence",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"feature_reqs",
")",
":",
"msg",
"=",
"'Unable to locate feature requirements file [{}]'",
"echo",
"(",
"red",
"(",
"msg",
".",
"format",
"(",
"feature_file",
")",
")",
"+",
"'\\n'",
")",
"return",
"msg",
"=",
"'Now installing dependencies for \"{}\" feature...'",
".",
"format",
"(",
"feature",
")",
"echo",
"(",
"yellow",
"(",
"msg",
")",
")",
"subprocess",
".",
"check_call",
"(",
"[",
"sys",
".",
"executable",
",",
"'-m'",
",",
"'pip'",
",",
"'install'",
",",
"'-r'",
",",
"feature_reqs",
"]",
")",
"# update requirements file with dependencies",
"reqs",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getcwd",
"(",
")",
",",
"'requirements.txt'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"reqs",
")",
":",
"with",
"open",
"(",
"reqs",
")",
"as",
"file",
":",
"existing",
"=",
"[",
"x",
".",
"strip",
"(",
")",
".",
"split",
"(",
"'=='",
")",
"[",
"0",
"]",
"for",
"x",
"in",
"file",
".",
"readlines",
"(",
")",
"if",
"x",
"]",
"lines",
"=",
"[",
"'\\n'",
"]",
"with",
"open",
"(",
"feature_reqs",
")",
"as",
"file",
":",
"incoming",
"=",
"file",
".",
"readlines",
"(",
")",
"for",
"line",
"in",
"incoming",
":",
"if",
"not",
"(",
"len",
"(",
"line",
")",
")",
"or",
"line",
".",
"startswith",
"(",
"'#'",
")",
":",
"lines",
".",
"append",
"(",
"line",
")",
"continue",
"package",
"=",
"line",
".",
"strip",
"(",
")",
".",
"split",
"(",
"'=='",
")",
"[",
"0",
"]",
"if",
"package",
"not",
"in",
"existing",
":",
"lines",
".",
"append",
"(",
"line",
")",
"with",
"open",
"(",
"reqs",
",",
"'a'",
")",
"as",
"file",
":",
"file",
".",
"writelines",
"(",
"lines",
")",
"echo",
"(",
"green",
"(",
"'DONE\\n'",
")",
")"
]
| 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",
"f",
".",
"read",
"(",
")",
".",
"strip",
"(",
")"
]
| 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 fox jumps over the lazy dog")
'bBsHvHu8S-M'
>>> simple_hashstring("The quick brown fox jumps over the lazy dog", bits=48)
'B7x7vEvj'
'''
#Useful discussion of techniques here: http://stackoverflow.com/questions/1303021/shortest-hash-in-python-to-name-cache-files
#Use MurmurHash3
#Get a 64-bit integer, the first half of the 128-bit tuple from mmh and then bit shift it to get the desired bit length
basis = mmh3.hash64(str(obj))[0] >> (64-bits)
if bits == 64:
raw_hash = struct.pack('!q', basis)
else:
raw_hash = struct.pack('!q', basis)[:-int((64-bits)/8)]
hashstr = base64.urlsafe_b64encode(raw_hash).rstrip(b"=")
return hashstr.decode('ascii') | 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 fox jumps over the lazy dog")
'bBsHvHu8S-M'
>>> simple_hashstring("The quick brown fox jumps over the lazy dog", bits=48)
'B7x7vEvj'
'''
#Useful discussion of techniques here: http://stackoverflow.com/questions/1303021/shortest-hash-in-python-to-name-cache-files
#Use MurmurHash3
#Get a 64-bit integer, the first half of the 128-bit tuple from mmh and then bit shift it to get the desired bit length
basis = mmh3.hash64(str(obj))[0] >> (64-bits)
if bits == 64:
raw_hash = struct.pack('!q', basis)
else:
raw_hash = struct.pack('!q', basis)[:-int((64-bits)/8)]
hashstr = base64.urlsafe_b64encode(raw_hash).rstrip(b"=")
return hashstr.decode('ascii') | [
"def",
"simple_hashstring",
"(",
"obj",
",",
"bits",
"=",
"64",
")",
":",
"#Useful discussion of techniques here: http://stackoverflow.com/questions/1303021/shortest-hash-in-python-to-name-cache-files",
"#Use MurmurHash3",
"#Get a 64-bit integer, the first half of the 128-bit tuple from mmh and then bit shift it to get the desired bit length",
"basis",
"=",
"mmh3",
".",
"hash64",
"(",
"str",
"(",
"obj",
")",
")",
"[",
"0",
"]",
">>",
"(",
"64",
"-",
"bits",
")",
"if",
"bits",
"==",
"64",
":",
"raw_hash",
"=",
"struct",
".",
"pack",
"(",
"'!q'",
",",
"basis",
")",
"else",
":",
"raw_hash",
"=",
"struct",
".",
"pack",
"(",
"'!q'",
",",
"basis",
")",
"[",
":",
"-",
"int",
"(",
"(",
"64",
"-",
"bits",
")",
"/",
"8",
")",
"]",
"hashstr",
"=",
"base64",
".",
"urlsafe_b64encode",
"(",
"raw_hash",
")",
".",
"rstrip",
"(",
"b\"=\"",
")",
"return",
"hashstr",
".",
"decode",
"(",
"'ascii'",
")"
]
| 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'
>>> simple_hashstring("The quick brown fox jumps over the lazy dog", bits=48)
'B7x7vEvj' | [
"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
>>> from versa.contrib.datachefids import create_slug
>>> create_slug(u"The quick brown fox jumps over the lazy dog")
'the_quick_brown_fox_jumps_over_the_lazy_dog'
>>> create_slug(u"The quick brown fox jumps over the lazy dog", 20)
'the_quick_brown_fox'
'''
if plain_len: title = title[:plain_len]
pass1 = OMIT_FROM_SLUG_PAT.sub('_', title).lower()
return NORMALIZE_UNDERSCORES_PAT.sub('_', pass1) | 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
>>> from versa.contrib.datachefids import create_slug
>>> create_slug(u"The quick brown fox jumps over the lazy dog")
'the_quick_brown_fox_jumps_over_the_lazy_dog'
>>> create_slug(u"The quick brown fox jumps over the lazy dog", 20)
'the_quick_brown_fox'
'''
if plain_len: title = title[:plain_len]
pass1 = OMIT_FROM_SLUG_PAT.sub('_', title).lower()
return NORMALIZE_UNDERSCORES_PAT.sub('_', pass1) | [
"def",
"create_slug",
"(",
"title",
",",
"plain_len",
"=",
"None",
")",
":",
"if",
"plain_len",
":",
"title",
"=",
"title",
"[",
":",
"plain_len",
"]",
"pass1",
"=",
"OMIT_FROM_SLUG_PAT",
".",
"sub",
"(",
"'_'",
",",
"title",
")",
".",
"lower",
"(",
")",
"return",
"NORMALIZE_UNDERSCORES_PAT",
".",
"sub",
"(",
"'_'",
",",
"pass1",
")"
]
| 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
>>> create_slug(u"The quick brown fox jumps over the lazy dog")
'the_quick_brown_fox_jumps_over_the_lazy_dog'
>>> create_slug(u"The quick brown fox jumps over the lazy dog", 20)
'the_quick_brown_fox' | [
"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">',
'<div class="col-md-1">',
'<a href="{}">'.format(query_document.get_admin_url(_external=True)),
mongo_command_name_formatter(
view, context, query_document, 'command_name'
),
# '<span class="label {}">{}</span>'.format(
# command_name_map.get(query_document.command_name, 'label-default'),
# query_document.command_name,
# ),
'</div>',
'<div class="col-md-10">',
profiling_pure_query_formatter(
None, None, query_document, 'command', tag='pre'
),
'</div>',
'<div class="col-md-1">',
'<small>{} ms</small>'.format(query_document.duration),
'</a>',
'</div>',
'</div>',
]
)
) | 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">',
'<div class="col-md-1">',
'<a href="{}">'.format(query_document.get_admin_url(_external=True)),
mongo_command_name_formatter(
view, context, query_document, 'command_name'
),
# '<span class="label {}">{}</span>'.format(
# command_name_map.get(query_document.command_name, 'label-default'),
# query_document.command_name,
# ),
'</div>',
'<div class="col-md-10">',
profiling_pure_query_formatter(
None, None, query_document, 'command', tag='pre'
),
'</div>',
'<div class="col-md-1">',
'<small>{} ms</small>'.format(query_document.duration),
'</a>',
'</div>',
'</div>',
]
)
) | [
"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",
"(",
"query_document",
".",
"get_admin_url",
"(",
"_external",
"=",
"True",
")",
")",
",",
"mongo_command_name_formatter",
"(",
"view",
",",
"context",
",",
"query_document",
",",
"'command_name'",
")",
",",
"# '<span class=\"label {}\">{}</span>'.format(",
"# command_name_map.get(query_document.command_name, 'label-default'),",
"# query_document.command_name,",
"# ),",
"'</div>'",
",",
"'<div class=\"col-md-10\">'",
",",
"profiling_pure_query_formatter",
"(",
"None",
",",
"None",
",",
"query_document",
",",
"'command'",
",",
"tag",
"=",
"'pre'",
")",
",",
"'</div>'",
",",
"'<div class=\"col-md-1\">'",
",",
"'<small>{} ms</small>'",
".",
"format",
"(",
"query_document",
".",
"duration",
")",
",",
"'</a>'",
",",
"'</div>'",
",",
"'</div>'",
",",
"]",
")",
")"
]
| 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",
"(",
"200",
",",
"body",
"=",
"obj",
")"
]
| 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' header of the
outgoing response.
When no suitable handler exists, raises NotFound, MethodNotAllowed,
UnsupportedMediaType or NotAcceptable.
"""
view = None
if request._context: # Allow context to be missing for easier testing
route_name = request._context[-1].route.name
if route_name and VIEW_SEPARATOR in route_name:
view = route_name.split(VIEW_SEPARATOR, 1)[1] or None
if view not in view_handlers:
raise NotFound
method_handlers = view_handlers[view]
verb = request.method
if verb not in method_handlers:
if verb == 'HEAD' and 'GET' in method_handlers:
verb = 'GET'
else:
allowed_methods = set(method_handlers.keys())
if 'HEAD' not in allowed_methods and 'GET' in allowed_methods:
allowed_methods.add('HEAD')
allow = ', '.join(sorted(allowed_methods))
raise MethodNotAllowed(allow=allow)
handlers = method_handlers[verb]
vary = set()
if len(set(h.provides for h in handlers if h.provides is not None)) > 1:
vary.add('Accept')
if len(set(h.accepts for h in handlers)) > 1:
vary.add('Content-Type')
content_type = request.content_type
if content_type:
handlers = negotiate_content_type(content_type, handlers)
if not handlers:
raise UnsupportedMediaType
accept = request.headers.get('Accept')
if accept:
handlers = negotiate_accept(accept, handlers)
if not handlers:
raise NotAcceptable
return handlers[0], vary | 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' header of the
outgoing response.
When no suitable handler exists, raises NotFound, MethodNotAllowed,
UnsupportedMediaType or NotAcceptable.
"""
view = None
if request._context: # Allow context to be missing for easier testing
route_name = request._context[-1].route.name
if route_name and VIEW_SEPARATOR in route_name:
view = route_name.split(VIEW_SEPARATOR, 1)[1] or None
if view not in view_handlers:
raise NotFound
method_handlers = view_handlers[view]
verb = request.method
if verb not in method_handlers:
if verb == 'HEAD' and 'GET' in method_handlers:
verb = 'GET'
else:
allowed_methods = set(method_handlers.keys())
if 'HEAD' not in allowed_methods and 'GET' in allowed_methods:
allowed_methods.add('HEAD')
allow = ', '.join(sorted(allowed_methods))
raise MethodNotAllowed(allow=allow)
handlers = method_handlers[verb]
vary = set()
if len(set(h.provides for h in handlers if h.provides is not None)) > 1:
vary.add('Accept')
if len(set(h.accepts for h in handlers)) > 1:
vary.add('Content-Type')
content_type = request.content_type
if content_type:
handlers = negotiate_content_type(content_type, handlers)
if not handlers:
raise UnsupportedMediaType
accept = request.headers.get('Accept')
if accept:
handlers = negotiate_accept(accept, handlers)
if not handlers:
raise NotAcceptable
return handlers[0], vary | [
"def",
"resolve_handler",
"(",
"request",
",",
"view_handlers",
")",
":",
"view",
"=",
"None",
"if",
"request",
".",
"_context",
":",
"# Allow context to be missing for easier testing",
"route_name",
"=",
"request",
".",
"_context",
"[",
"-",
"1",
"]",
".",
"route",
".",
"name",
"if",
"route_name",
"and",
"VIEW_SEPARATOR",
"in",
"route_name",
":",
"view",
"=",
"route_name",
".",
"split",
"(",
"VIEW_SEPARATOR",
",",
"1",
")",
"[",
"1",
"]",
"or",
"None",
"if",
"view",
"not",
"in",
"view_handlers",
":",
"raise",
"NotFound",
"method_handlers",
"=",
"view_handlers",
"[",
"view",
"]",
"verb",
"=",
"request",
".",
"method",
"if",
"verb",
"not",
"in",
"method_handlers",
":",
"if",
"verb",
"==",
"'HEAD'",
"and",
"'GET'",
"in",
"method_handlers",
":",
"verb",
"=",
"'GET'",
"else",
":",
"allowed_methods",
"=",
"set",
"(",
"method_handlers",
".",
"keys",
"(",
")",
")",
"if",
"'HEAD'",
"not",
"in",
"allowed_methods",
"and",
"'GET'",
"in",
"allowed_methods",
":",
"allowed_methods",
".",
"add",
"(",
"'HEAD'",
")",
"allow",
"=",
"', '",
".",
"join",
"(",
"sorted",
"(",
"allowed_methods",
")",
")",
"raise",
"MethodNotAllowed",
"(",
"allow",
"=",
"allow",
")",
"handlers",
"=",
"method_handlers",
"[",
"verb",
"]",
"vary",
"=",
"set",
"(",
")",
"if",
"len",
"(",
"set",
"(",
"h",
".",
"provides",
"for",
"h",
"in",
"handlers",
"if",
"h",
".",
"provides",
"is",
"not",
"None",
")",
")",
">",
"1",
":",
"vary",
".",
"add",
"(",
"'Accept'",
")",
"if",
"len",
"(",
"set",
"(",
"h",
".",
"accepts",
"for",
"h",
"in",
"handlers",
")",
")",
">",
"1",
":",
"vary",
".",
"add",
"(",
"'Content-Type'",
")",
"content_type",
"=",
"request",
".",
"content_type",
"if",
"content_type",
":",
"handlers",
"=",
"negotiate_content_type",
"(",
"content_type",
",",
"handlers",
")",
"if",
"not",
"handlers",
":",
"raise",
"UnsupportedMediaType",
"accept",
"=",
"request",
".",
"headers",
".",
"get",
"(",
"'Accept'",
")",
"if",
"accept",
":",
"handlers",
"=",
"negotiate_accept",
"(",
"accept",
",",
"handlers",
")",
"if",
"not",
"handlers",
":",
"raise",
"NotAcceptable",
"return",
"handlers",
"[",
"0",
"]",
",",
"vary"
]
| 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 suitable handler exists, raises NotFound, MethodNotAllowed,
UnsupportedMediaType or NotAcceptable. | [
"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_and_quality_parsed(content_type,
[mimeparse.parse_media_range(mr)]), mr) for mr in accepted]
# Sort by fitness, then quality parsed (higher is better)
scored_ranges.sort(reverse=True)
best_score = scored_ranges[0][0] # (fitness, quality)
if best_score == MIMEPARSE_NO_MATCH or not best_score[1]:
return []
media_ranges = [pair[1] for pair in scored_ranges if pair[0] == best_score]
best_range = media_ranges[0]
return [h for h in handlers if h.accepts == best_range] | 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_and_quality_parsed(content_type,
[mimeparse.parse_media_range(mr)]), mr) for mr in accepted]
# Sort by fitness, then quality parsed (higher is better)
scored_ranges.sort(reverse=True)
best_score = scored_ranges[0][0] # (fitness, quality)
if best_score == MIMEPARSE_NO_MATCH or not best_score[1]:
return []
media_ranges = [pair[1] for pair in scored_ranges if pair[0] == best_score]
best_range = media_ranges[0]
return [h for h in handlers if h.accepts == best_range] | [
"def",
"negotiate_content_type",
"(",
"content_type",
",",
"handlers",
")",
":",
"accepted",
"=",
"[",
"h",
".",
"accepts",
"for",
"h",
"in",
"handlers",
"]",
"scored_ranges",
"=",
"[",
"(",
"mimeparse",
".",
"fitness_and_quality_parsed",
"(",
"content_type",
",",
"[",
"mimeparse",
".",
"parse_media_range",
"(",
"mr",
")",
"]",
")",
",",
"mr",
")",
"for",
"mr",
"in",
"accepted",
"]",
"# Sort by fitness, then quality parsed (higher is better)",
"scored_ranges",
".",
"sort",
"(",
"reverse",
"=",
"True",
")",
"best_score",
"=",
"scored_ranges",
"[",
"0",
"]",
"[",
"0",
"]",
"# (fitness, quality)",
"if",
"best_score",
"==",
"MIMEPARSE_NO_MATCH",
"or",
"not",
"best_score",
"[",
"1",
"]",
":",
"return",
"[",
"]",
"media_ranges",
"=",
"[",
"pair",
"[",
"1",
"]",
"for",
"pair",
"in",
"scored_ranges",
"if",
"pair",
"[",
"0",
"]",
"==",
"best_score",
"]",
"best_range",
"=",
"media_ranges",
"[",
"0",
"]",
"return",
"[",
"h",
"for",
"h",
"in",
"handlers",
"if",
"h",
".",
"accepts",
"==",
"best_range",
"]"
]
| 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:
# Not all handlers are annotated - disable content-negotiation
# for Accept.
# TODO: We could implement an "optimistic mode": If a fully qualified
# mime-type was requested and we have a specific handler that provides
# it, choose that handler instead of the default handler (depending on
# 'q' value).
return [h for h in handlers if h.provides is None]
else:
# All handlers are annotated with the mime-type they
# provide: find the best match.
#
# mimeparse.best_match expects the supported mime-types to be sorted
# in order of increasing desirability. By default, we use the order in
# which handlers were added (earlier means better).
# TODO: add "priority" parameter for user-defined priorities.
best_match = mimeparse.best_match(reversed(provided), accept)
return [h for h in handlers if h.provides == best_match] | 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:
# Not all handlers are annotated - disable content-negotiation
# for Accept.
# TODO: We could implement an "optimistic mode": If a fully qualified
# mime-type was requested and we have a specific handler that provides
# it, choose that handler instead of the default handler (depending on
# 'q' value).
return [h for h in handlers if h.provides is None]
else:
# All handlers are annotated with the mime-type they
# provide: find the best match.
#
# mimeparse.best_match expects the supported mime-types to be sorted
# in order of increasing desirability. By default, we use the order in
# which handlers were added (earlier means better).
# TODO: add "priority" parameter for user-defined priorities.
best_match = mimeparse.best_match(reversed(provided), accept)
return [h for h in handlers if h.provides == best_match] | [
"def",
"negotiate_accept",
"(",
"accept",
",",
"handlers",
")",
":",
"provided",
"=",
"[",
"h",
".",
"provides",
"for",
"h",
"in",
"handlers",
"]",
"if",
"None",
"in",
"provided",
":",
"# Not all handlers are annotated - disable content-negotiation",
"# for Accept.",
"# TODO: We could implement an \"optimistic mode\": If a fully qualified",
"# mime-type was requested and we have a specific handler that provides",
"# it, choose that handler instead of the default handler (depending on",
"# 'q' value).",
"return",
"[",
"h",
"for",
"h",
"in",
"handlers",
"if",
"h",
".",
"provides",
"is",
"None",
"]",
"else",
":",
"# All handlers are annotated with the mime-type they",
"# provide: find the best match.",
"#",
"# mimeparse.best_match expects the supported mime-types to be sorted",
"# in order of increasing desirability. By default, we use the order in",
"# which handlers were added (earlier means better).",
"# TODO: add \"priority\" parameter for user-defined priorities.",
"best_match",
"=",
"mimeparse",
".",
"best_match",
"(",
"reversed",
"(",
"provided",
")",
",",
"accept",
")",
"return",
"[",
"h",
"for",
"h",
"in",
"handlers",
"if",
"h",
".",
"provides",
"==",
"best_match",
"]"
]
| 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
returned instead.
"""
try:
value = self[key]
if type is not None:
return type(value)
return value
except (KeyError, ValueError):
return default | 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
returned instead.
"""
try:
value = self[key]
if type is not None:
return type(value)
return value
except (KeyError, ValueError):
return default | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
",",
"type",
"=",
"None",
")",
":",
"try",
":",
"value",
"=",
"self",
"[",
"key",
"]",
"if",
"type",
"is",
"not",
"None",
":",
"return",
"type",
"(",
"value",
")",
"return",
"value",
"except",
"(",
"KeyError",
",",
"ValueError",
")",
":",
"return",
"default"
]
| 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 = []
for k, v in self._items:
if k == key:
if type is not None:
try:
values.append(type(v))
except ValueError:
pass
else:
values.append(v)
return 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 = []
for k, v in self._items:
if k == key:
if type is not None:
try:
values.append(type(v))
except ValueError:
pass
else:
values.append(v)
return values | [
"def",
"getall",
"(",
"self",
",",
"key",
",",
"type",
"=",
"None",
")",
":",
"values",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"self",
".",
"_items",
":",
"if",
"k",
"==",
"key",
":",
"if",
"type",
"is",
"not",
"None",
":",
"try",
":",
"values",
".",
"append",
"(",
"type",
"(",
"v",
")",
")",
"except",
"ValueError",
":",
"pass",
"else",
":",
"values",
".",
"append",
"(",
"v",
")",
"return",
"values"
]
| 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 of:
'.'
: Builds the URL for the current route.
'/'
: Builds the URL for the root (top-most) mapper object.
'/a', '/a:b', etc.
: Builds the URL for a named route relative to the root mapper.
'.a', '..a', '..a:b', etc.
: Builds a URL for a named route relative to the current mapper.
Each additional leading '.' after the first one starts one
level higher in the hierarchy of nested mappers (i.e. '.a' is
equivalent to 'a').
Special keyword arguments:
`_query`
: Append a query string to the URL (dict or list of tuples)
`_relative`
: When True, build a relative URL (default: False)
All other keyword arguments are treated as parameters for the URL
template.
"""
# Allow passing 'self' as named parameter
self, target, args = args[0], args[1], list(args[2:])
query = kw.pop('_query', None)
relative = kw.pop('_relative', False)
url = build_url(self._context, target, args, kw)
if query:
if isinstance(query, dict):
query = sorted(query.items())
query_part = urllib.urlencode(query)
query_sep = '&' if '?' in url else '?'
url = url + query_sep + query_part
if relative:
return url
else:
return urlparse.urljoin(self.application_uri, url) | 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 of:
'.'
: Builds the URL for the current route.
'/'
: Builds the URL for the root (top-most) mapper object.
'/a', '/a:b', etc.
: Builds the URL for a named route relative to the root mapper.
'.a', '..a', '..a:b', etc.
: Builds a URL for a named route relative to the current mapper.
Each additional leading '.' after the first one starts one
level higher in the hierarchy of nested mappers (i.e. '.a' is
equivalent to 'a').
Special keyword arguments:
`_query`
: Append a query string to the URL (dict or list of tuples)
`_relative`
: When True, build a relative URL (default: False)
All other keyword arguments are treated as parameters for the URL
template.
"""
# Allow passing 'self' as named parameter
self, target, args = args[0], args[1], list(args[2:])
query = kw.pop('_query', None)
relative = kw.pop('_relative', False)
url = build_url(self._context, target, args, kw)
if query:
if isinstance(query, dict):
query = sorted(query.items())
query_part = urllib.urlencode(query)
query_sep = '&' if '?' in url else '?'
url = url + query_sep + query_part
if relative:
return url
else:
return urlparse.urljoin(self.application_uri, url) | [
"def",
"url_for",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"# Allow passing 'self' as named parameter",
"self",
",",
"target",
",",
"args",
"=",
"args",
"[",
"0",
"]",
",",
"args",
"[",
"1",
"]",
",",
"list",
"(",
"args",
"[",
"2",
":",
"]",
")",
"query",
"=",
"kw",
".",
"pop",
"(",
"'_query'",
",",
"None",
")",
"relative",
"=",
"kw",
".",
"pop",
"(",
"'_relative'",
",",
"False",
")",
"url",
"=",
"build_url",
"(",
"self",
".",
"_context",
",",
"target",
",",
"args",
",",
"kw",
")",
"if",
"query",
":",
"if",
"isinstance",
"(",
"query",
",",
"dict",
")",
":",
"query",
"=",
"sorted",
"(",
"query",
".",
"items",
"(",
")",
")",
"query_part",
"=",
"urllib",
".",
"urlencode",
"(",
"query",
")",
"query_sep",
"=",
"'&'",
"if",
"'?'",
"in",
"url",
"else",
"'?'",
"url",
"=",
"url",
"+",
"query_sep",
"+",
"query_part",
"if",
"relative",
":",
"return",
"url",
"else",
":",
"return",
"urlparse",
".",
"urljoin",
"(",
"self",
".",
"application_uri",
",",
"url",
")"
]
| 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 the URL for the current route.
'/'
: Builds the URL for the root (top-most) mapper object.
'/a', '/a:b', etc.
: Builds the URL for a named route relative to the root mapper.
'.a', '..a', '..a:b', etc.
: Builds a URL for a named route relative to the current mapper.
Each additional leading '.' after the first one starts one
level higher in the hierarchy of nested mappers (i.e. '.a' is
equivalent to 'a').
Special keyword arguments:
`_query`
: Append a query string to the URL (dict or list of tuples)
`_relative`
: When True, build a relative URL (default: False)
All other keyword arguments are treated as parameters for the URL
template. | [
"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._input | 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._input | [
"def",
"input",
"(",
"self",
")",
":",
"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",
".",
"_input"
]
| 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_reader is None:
self._body = self.input.read(self.content_length or 0)
else:
self._body = self._body_reader(self.input)
return self._body | 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_reader is None:
self._body = self.input.read(self.content_length or 0)
else:
self._body = self._body_reader(self.input)
return self._body | [
"def",
"body",
"(",
"self",
")",
":",
"if",
"self",
".",
"_body",
"is",
"None",
":",
"if",
"self",
".",
"_body_reader",
"is",
"None",
":",
"self",
".",
"_body",
"=",
"self",
".",
"input",
".",
"read",
"(",
"self",
".",
"content_length",
"or",
"0",
")",
"else",
":",
"self",
".",
"_body",
"=",
"self",
".",
"_body_reader",
"(",
"self",
".",
"input",
")",
"return",
"self",
".",
"_body"
]
| 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 fields with a 'filename' attribute.
"""
if self._form is None:
# Make sure FieldStorage always parses the form content,
# and never the query string.
environ = self.environ.copy()
environ['QUERY_STRING'] = ''
environ['REQUEST_METHOD'] = 'POST'
fs = cgi.FieldStorage(
fp=self.input,
environ=environ,
keep_blank_values=True)
# File upload field handling copied from WebOb
fields = []
for f in fs.list or []:
if f.filename:
f.filename = f.filename.decode('utf-8')
fields.append((f.name.decode('utf-8'), f))
else:
fields.append(
(f.name.decode('utf-8'), f.value.decode('utf-8'))
)
self._form = QueryDict(fields)
return self._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 fields with a 'filename' attribute.
"""
if self._form is None:
# Make sure FieldStorage always parses the form content,
# and never the query string.
environ = self.environ.copy()
environ['QUERY_STRING'] = ''
environ['REQUEST_METHOD'] = 'POST'
fs = cgi.FieldStorage(
fp=self.input,
environ=environ,
keep_blank_values=True)
# File upload field handling copied from WebOb
fields = []
for f in fs.list or []:
if f.filename:
f.filename = f.filename.decode('utf-8')
fields.append((f.name.decode('utf-8'), f))
else:
fields.append(
(f.name.decode('utf-8'), f.value.decode('utf-8'))
)
self._form = QueryDict(fields)
return self._form | [
"def",
"form",
"(",
"self",
")",
":",
"if",
"self",
".",
"_form",
"is",
"None",
":",
"# Make sure FieldStorage always parses the form content,",
"# and never the query string.",
"environ",
"=",
"self",
".",
"environ",
".",
"copy",
"(",
")",
"environ",
"[",
"'QUERY_STRING'",
"]",
"=",
"''",
"environ",
"[",
"'REQUEST_METHOD'",
"]",
"=",
"'POST'",
"fs",
"=",
"cgi",
".",
"FieldStorage",
"(",
"fp",
"=",
"self",
".",
"input",
",",
"environ",
"=",
"environ",
",",
"keep_blank_values",
"=",
"True",
")",
"# File upload field handling copied from WebOb",
"fields",
"=",
"[",
"]",
"for",
"f",
"in",
"fs",
".",
"list",
"or",
"[",
"]",
":",
"if",
"f",
".",
"filename",
":",
"f",
".",
"filename",
"=",
"f",
".",
"filename",
".",
"decode",
"(",
"'utf-8'",
")",
"fields",
".",
"append",
"(",
"(",
"f",
".",
"name",
".",
"decode",
"(",
"'utf-8'",
")",
",",
"f",
")",
")",
"else",
":",
"fields",
".",
"append",
"(",
"(",
"f",
".",
"name",
".",
"decode",
"(",
"'utf-8'",
")",
",",
"f",
".",
"value",
".",
"decode",
"(",
"'utf-8'",
")",
")",
")",
"self",
".",
"_form",
"=",
"QueryDict",
"(",
"fields",
")",
"return",
"self",
".",
"_form"
]
| 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' attribute. | [
"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()
])
return self._cookies | 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()
])
return self._cookies | [
"def",
"cookies",
"(",
"self",
")",
":",
"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",
"(",
")",
"]",
")",
"return",
"self",
".",
"_cookies"
]
| 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 parameters.
Returns:
str: A formatted error message.
"""
if num_params == 0:
plural = 's'
missing = 2
arguments = "'slack' and 'event'"
else:
plural = ''
missing = 1
arguments = "'event'"
return (f"{name}{sig} missing {missing} required positional "
f"argument{plural}: {arguments}") | 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 parameters.
Returns:
str: A formatted error message.
"""
if num_params == 0:
plural = 's'
missing = 2
arguments = "'slack' and 'event'"
else:
plural = ''
missing = 1
arguments = "'event'"
return (f"{name}{sig} missing {missing} required positional "
f"argument{plural}: {arguments}") | [
"def",
"_format_parameter_error_message",
"(",
"name",
":",
"str",
",",
"sig",
":",
"Signature",
",",
"num_params",
":",
"int",
")",
"->",
"str",
":",
"if",
"num_params",
"==",
"0",
":",
"plural",
"=",
"'s'",
"missing",
"=",
"2",
"arguments",
"=",
"\"'slack' and 'event'\"",
"else",
":",
"plural",
"=",
"''",
"missing",
"=",
"1",
"arguments",
"=",
"\"'event'\"",
"return",
"(",
"f\"{name}{sig} missing {missing} required positional \"",
"f\"argument{plural}: {arguments}\"",
")"
]
| 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_connected():
log.debug('Connected to the Slack API')
return
else:
interval = self.backoff(retry)
log.debug("Waiting %.3fs before retrying", interval)
time.sleep(interval)
raise FailedConnection('Failed to connect to the Slack API') | 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_connected():
log.debug('Connected to the Slack API')
return
else:
interval = self.backoff(retry)
log.debug("Waiting %.3fs before retrying", interval)
time.sleep(interval)
raise FailedConnection('Failed to connect to the Slack API') | [
"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",
".",
"retries",
"+",
"1",
")",
":",
"self",
".",
"connect",
"(",
")",
"if",
"self",
".",
"is_connected",
"(",
")",
":",
"log",
".",
"debug",
"(",
"'Connected to the Slack API'",
")",
"return",
"else",
":",
"interval",
"=",
"self",
".",
"backoff",
"(",
"retry",
")",
"log",
".",
"debug",
"(",
"\"Waiting %.3fs before retrying\"",
",",
"interval",
")",
"time",
".",
"sleep",
"(",
"interval",
")",
"raise",
"FailedConnection",
"(",
"'Failed to connect to the Slack API'",
")"
]
| 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 WebSocketTimeoutException that could be caught by
# the slackclient library and then we could just use auto_reconnect.
except TimeoutError:
log.debug('Lost connection to the Slack API, attempting to '
'reconnect')
self.connect_with_retry()
return [] | 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 WebSocketTimeoutException that could be caught by
# the slackclient library and then we could just use auto_reconnect.
except TimeoutError:
log.debug('Lost connection to the Slack API, attempting to '
'reconnect')
self.connect_with_retry()
return [] | [
"def",
"fetch_events",
"(",
"self",
")",
"->",
"List",
"[",
"dict",
"]",
":",
"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 WebSocketTimeoutException that could be caught by",
"# the slackclient library and then we could just use auto_reconnect.",
"except",
"TimeoutError",
":",
"log",
".",
"debug",
"(",
"'Lost connection to the Slack API, attempting to '",
"'reconnect'",
")",
"self",
".",
"connect_with_retry",
"(",
")",
"return",
"[",
"]"
]
| 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 = _SlackClientWrapper(
slack=slack,
retries=retries,
backoff=backoff
) | 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 = _SlackClientWrapper(
slack=slack,
retries=retries,
backoff=backoff
) | [
"def",
"_ensure_slack",
"(",
"self",
",",
"connector",
":",
"Any",
",",
"retries",
":",
"int",
",",
"backoff",
":",
"Callable",
"[",
"[",
"int",
"]",
",",
"float",
"]",
")",
"->",
"None",
":",
"connector",
"=",
"self",
".",
"_env_var",
"if",
"connector",
"is",
"None",
"else",
"connector",
"slack",
":",
"SlackClient",
"=",
"_create_slack",
"(",
"connector",
")",
"self",
".",
"_slack",
"=",
"_SlackClientWrapper",
"(",
"slack",
"=",
"slack",
",",
"retries",
"=",
"retries",
",",
"backoff",
"=",
"backoff",
")"
]
| 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 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
absent an attempt will be made to use the ``LAYABOUT_TOKEN``
environment variable.
interval: The number of seconds to wait between fetching events
from the Slack API.
retries: The number of retry attempts to make if a connection to
Slack is not established or is lost.
backoff: The strategy used to determine how long to wait between
retries. Must take as input the number of the current retry and
output a :obj:`float`. The retry count begins at 1 and
continues up to ``retries``. If absent a
`truncated exponential backoff`_ strategy will be used.
until: The condition used to evaluate whether this method
terminates. Must take as input a :obj:`list` of :obj:`dict`
representing Slack RTM API events and return a :obj:`bool`. If
absent this method will run forever.
Raises:
TypeError: If an unsupported connector is given.
MissingToken: If no API token is available.
FailedConnection: If connecting to the Slack API fails.
.. _truncated exponential backoff:
https://cloud.google.com/storage/docs/exponential-backoff
"""
backoff = backoff or _truncated_exponential
until = until or _forever
self._ensure_slack(
connector=connector,
retries=retries,
backoff=backoff
)
assert self._slack is not None
while True:
events = self._slack.fetch_events()
if not until(events):
log.debug('Exiting event loop')
break
# Handle events!
for event in events:
type_ = event.get('type', '')
for handler in self._handlers[type_] + self._handlers['*']:
fn, kwargs = handler
fn(self._slack.inner, event, **kwargs)
# Maybe don't pester the Slack API too much.
time.sleep(interval) | 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 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
absent an attempt will be made to use the ``LAYABOUT_TOKEN``
environment variable.
interval: The number of seconds to wait between fetching events
from the Slack API.
retries: The number of retry attempts to make if a connection to
Slack is not established or is lost.
backoff: The strategy used to determine how long to wait between
retries. Must take as input the number of the current retry and
output a :obj:`float`. The retry count begins at 1 and
continues up to ``retries``. If absent a
`truncated exponential backoff`_ strategy will be used.
until: The condition used to evaluate whether this method
terminates. Must take as input a :obj:`list` of :obj:`dict`
representing Slack RTM API events and return a :obj:`bool`. If
absent this method will run forever.
Raises:
TypeError: If an unsupported connector is given.
MissingToken: If no API token is available.
FailedConnection: If connecting to the Slack API fails.
.. _truncated exponential backoff:
https://cloud.google.com/storage/docs/exponential-backoff
"""
backoff = backoff or _truncated_exponential
until = until or _forever
self._ensure_slack(
connector=connector,
retries=retries,
backoff=backoff
)
assert self._slack is not None
while True:
events = self._slack.fetch_events()
if not until(events):
log.debug('Exiting event loop')
break
# Handle events!
for event in events:
type_ = event.get('type', '')
for handler in self._handlers[type_] + self._handlers['*']:
fn, kwargs = handler
fn(self._slack.inner, event, **kwargs)
# Maybe don't pester the Slack API too much.
time.sleep(interval) | [
"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",
":",
"backoff",
"=",
"backoff",
"or",
"_truncated_exponential",
"until",
"=",
"until",
"or",
"_forever",
"self",
".",
"_ensure_slack",
"(",
"connector",
"=",
"connector",
",",
"retries",
"=",
"retries",
",",
"backoff",
"=",
"backoff",
")",
"assert",
"self",
".",
"_slack",
"is",
"not",
"None",
"while",
"True",
":",
"events",
"=",
"self",
".",
"_slack",
".",
"fetch_events",
"(",
")",
"if",
"not",
"until",
"(",
"events",
")",
":",
"log",
".",
"debug",
"(",
"'Exiting event loop'",
")",
"break",
"# Handle events!",
"for",
"event",
"in",
"events",
":",
"type_",
"=",
"event",
".",
"get",
"(",
"'type'",
",",
"''",
")",
"for",
"handler",
"in",
"self",
".",
"_handlers",
"[",
"type_",
"]",
"+",
"self",
".",
"_handlers",
"[",
"'*'",
"]",
":",
"fn",
",",
"kwargs",
"=",
"handler",
"fn",
"(",
"self",
".",
"_slack",
".",
"inner",
",",
"event",
",",
"*",
"*",
"kwargs",
")",
"# Maybe don't pester the Slack API too much.",
"time",
".",
"sleep",
"(",
"interval",
")"
]
| 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
absent an attempt will be made to use the ``LAYABOUT_TOKEN``
environment variable.
interval: The number of seconds to wait between fetching events
from the Slack API.
retries: The number of retry attempts to make if a connection to
Slack is not established or is lost.
backoff: The strategy used to determine how long to wait between
retries. Must take as input the number of the current retry and
output a :obj:`float`. The retry count begins at 1 and
continues up to ``retries``. If absent a
`truncated exponential backoff`_ strategy will be used.
until: The condition used to evaluate whether this method
terminates. Must take as input a :obj:`list` of :obj:`dict`
representing Slack RTM API events and return a :obj:`bool`. If
absent this method will run forever.
Raises:
TypeError: If an unsupported connector is given.
MissingToken: If no API token is available.
FailedConnection: If connecting to the Slack API fails.
.. _truncated exponential backoff:
https://cloud.google.com/storage/docs/exponential-backoff | [
"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_weboob_dir)
result = cmd_exec('git clone {} {}'.format(WEBOOB_REPO, tmp_weboob_dir))
if (result['error']):
print result['stderr']
print 'Weboob installation failed: could not clone repository'
exit()
print 'Sources fetched, will now process to installation'
# Launch the installation
result = cmd_exec('cd {} && ./setup.py install'.format(tmp_weboob_dir))
# Remove the weboob directory
shutil.rmtree(tmp_weboob_dir)
if (result['error']):
print result['stderr']
print 'Weboob installation failed: setup failed'
exit()
print result['stdout']
# Check weboob version
weboob_version = get_weboob_version()
if (not weboob_version):
print 'Weboob installation failed: version not detected'
exit()
print 'Weboob (version: {}) installation succeeded'.format(weboob_version)
update() | 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_weboob_dir)
result = cmd_exec('git clone {} {}'.format(WEBOOB_REPO, tmp_weboob_dir))
if (result['error']):
print result['stderr']
print 'Weboob installation failed: could not clone repository'
exit()
print 'Sources fetched, will now process to installation'
# Launch the installation
result = cmd_exec('cd {} && ./setup.py install'.format(tmp_weboob_dir))
# Remove the weboob directory
shutil.rmtree(tmp_weboob_dir)
if (result['error']):
print result['stderr']
print 'Weboob installation failed: setup failed'
exit()
print result['stdout']
# Check weboob version
weboob_version = get_weboob_version()
if (not weboob_version):
print 'Weboob installation failed: version not detected'
exit()
print 'Weboob (version: {}) installation succeeded'.format(weboob_version)
update() | [
"def",
"install",
"(",
")",
":",
"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_weboob_dir",
")",
"result",
"=",
"cmd_exec",
"(",
"'git clone {} {}'",
".",
"format",
"(",
"WEBOOB_REPO",
",",
"tmp_weboob_dir",
")",
")",
"if",
"(",
"result",
"[",
"'error'",
"]",
")",
":",
"print",
"result",
"[",
"'stderr'",
"]",
"print",
"'Weboob installation failed: could not clone repository'",
"exit",
"(",
")",
"print",
"'Sources fetched, will now process to installation'",
"# Launch the installation",
"result",
"=",
"cmd_exec",
"(",
"'cd {} && ./setup.py install'",
".",
"format",
"(",
"tmp_weboob_dir",
")",
")",
"# Remove the weboob directory",
"shutil",
".",
"rmtree",
"(",
"tmp_weboob_dir",
")",
"if",
"(",
"result",
"[",
"'error'",
"]",
")",
":",
"print",
"result",
"[",
"'stderr'",
"]",
"print",
"'Weboob installation failed: setup failed'",
"exit",
"(",
")",
"print",
"result",
"[",
"'stdout'",
"]",
"# Check weboob version",
"weboob_version",
"=",
"get_weboob_version",
"(",
")",
"if",
"(",
"not",
"weboob_version",
")",
":",
"print",
"'Weboob installation failed: version not detected'",
"exit",
"(",
")",
"print",
"'Weboob (version: {}) installation succeeded'",
".",
"format",
"(",
"weboob_version",
")",
"update",
"(",
")"
]
| 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 subject)
rel - type IRI of the relationship (similar to an RDF predicate)
target - target of the relationship (similar to an RDF object), a boolean, floating point or unicode object
attrs - optional attribute mapping of relationship metadata, i.e. {attrname1: attrval1, attrname2: attrval2}
you can omit the dictionary of attributes if there are none, as long as you are not specifying a statement ID
'''
for curr_rel in rels:
attrs = self._attr_cls()
if len(curr_rel) == 2: # handle __iter__ output for copy()
origin, rel, target, attrs = curr_rel[1]
elif len(curr_rel) == 3:
origin, rel, target = curr_rel
elif len(curr_rel) == 4:
origin, rel, target, attrs = curr_rel
else:
raise ValueError
assert rel
self.add(origin, rel, target, attrs)
return | 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 subject)
rel - type IRI of the relationship (similar to an RDF predicate)
target - target of the relationship (similar to an RDF object), a boolean, floating point or unicode object
attrs - optional attribute mapping of relationship metadata, i.e. {attrname1: attrval1, attrname2: attrval2}
you can omit the dictionary of attributes if there are none, as long as you are not specifying a statement ID
'''
for curr_rel in rels:
attrs = self._attr_cls()
if len(curr_rel) == 2: # handle __iter__ output for copy()
origin, rel, target, attrs = curr_rel[1]
elif len(curr_rel) == 3:
origin, rel, target = curr_rel
elif len(curr_rel) == 4:
origin, rel, target, attrs = curr_rel
else:
raise ValueError
assert rel
self.add(origin, rel, target, attrs)
return | [
"def",
"add_many",
"(",
"self",
",",
"rels",
")",
":",
"for",
"curr_rel",
"in",
"rels",
":",
"attrs",
"=",
"self",
".",
"_attr_cls",
"(",
")",
"if",
"len",
"(",
"curr_rel",
")",
"==",
"2",
":",
"# handle __iter__ output for copy()",
"origin",
",",
"rel",
",",
"target",
",",
"attrs",
"=",
"curr_rel",
"[",
"1",
"]",
"elif",
"len",
"(",
"curr_rel",
")",
"==",
"3",
":",
"origin",
",",
"rel",
",",
"target",
"=",
"curr_rel",
"elif",
"len",
"(",
"curr_rel",
")",
"==",
"4",
":",
"origin",
",",
"rel",
",",
"target",
",",
"attrs",
"=",
"curr_rel",
"else",
":",
"raise",
"ValueError",
"assert",
"rel",
"self",
".",
"add",
"(",
"origin",
",",
"rel",
",",
"target",
",",
"attrs",
")",
"return"
]
| 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 (similar to an RDF predicate)
target - target of the relationship (similar to an RDF object), a boolean, floating point or unicode object
attrs - optional attribute mapping of relationship metadata, i.e. {attrname1: attrval1, attrname2: attrval2}
you can omit the dictionary of attributes if there are none, as long as you are not specifying a statement ID | [
"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_alive(): # the first call is in `interval` secs
func(*args, **kwargs)
return
timer_thread = threading.Thread(target=loop, daemon=True)
timer_thread.start()
atexit.register(stopped.set)
return timer_thread, stopped.set | 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_alive(): # the first call is in `interval` secs
func(*args, **kwargs)
return
timer_thread = threading.Thread(target=loop, daemon=True)
timer_thread.start()
atexit.register(stopped.set)
return timer_thread, stopped.set | [
"def",
"call_repeatedly",
"(",
"func",
",",
"interval",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"main_thead",
"=",
"threading",
".",
"current_thread",
"(",
")",
"stopped",
"=",
"threading",
".",
"Event",
"(",
")",
"def",
"loop",
"(",
")",
":",
"while",
"not",
"stopped",
".",
"wait",
"(",
"interval",
")",
"and",
"main_thead",
".",
"is_alive",
"(",
")",
":",
"# the first call is in `interval` secs",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"timer_thread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"loop",
",",
"daemon",
"=",
"True",
")",
"timer_thread",
".",
"start",
"(",
")",
"atexit",
".",
"register",
"(",
"stopped",
".",
"set",
")",
"return",
"timer_thread",
",",
"stopped",
".",
"set"
]
| 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 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 should be written ( displayed on STDERR if not set)
:param timeout: if set, it will kill the subprocess created when "timeout" seconds is reached. It will then raise an Exception.
:param line_function: set it to a "function pointer" for the function to be called each time a new line is written (line passed as a parameter).
:param poll_timing: wait time between timeout checks and std output check.
:returns: Standard output of the command or if return_output=False, it will give the "return code" of the command
"""
tmp_log = False
if log_settings:
log_folder = log_settings.get('LOG_FOLDER')
else:
tmp_log = True
log_folder = tempfile.mkdtemp()
if not log_file:
log_file = os.path.join(log_folder, "commands", "execute-command-logfile-%s.log" % UUID.uuid4())
try:
if not os.path.isdir(os.path.join(log_folder, "commands")):
os.makedirs(os.path.join(log_folder, "commands"))
except:
pass
if not logger:
logger = logging.getLogger('command_execute')
logfile_writer = open(log_file, 'a')
header = "%s - Executing command (timeout=%s) :\n\t%s\n\n\n" % (datetime.now().isoformat(), timeout, command)
logfile_writer.write(header)
logfile_writer.flush()
logfile_reader = open(log_file, 'rb')
logfile_reader.seek(0, os.SEEK_END)
logfile_start_position = logfile_reader.tell()
if error_logfile:
err_logfile_writer = open(error_logfile, 'a')
else:
err_logfile_writer = logfile_writer
start = datetime.now()
timeout_string = ""
if timeout:
timeout_string = "(timeout=%s)" % timeout
logger.info(u"Executing command %s :\n\t\t%s" % (timeout_string, command) )
# We use "exec <command>" as Popen launches a shell, that runs the command.
# It will transform the child process "sh" into the "command exectable" because of the "exec".
# Said more accuratly, it won't fork to create launch the command in a sub sub process.
# Therefore, when you kill the child process, you kill the "command" process and not the unecessary "sh" parent process.
if sys.platform != 'win32':
command = u"exec %s" % text_utils.uni(command)
process = subprocess.Popen(command, stdout=logfile_writer, stderr=err_logfile_writer, bufsize=1, shell=True, cwd=working_folder, env=env)
while process.poll() == None:
# In order to avoid unecessary cpu usage, we wait for "poll_timing" seconds ( default: 0.1 sec )
time.sleep(poll_timing)
# Timeout check
if timeout != None:
now = datetime.now()
if (now - start).seconds> timeout:
#process.terminate() ??
os.kill(process.pid, signal.SIGKILL)
os.waitpid(-1, os.WNOHANG)
raise Exception("Command execution timed out (took more than %s seconds...)" % timeout)
# Line function call:
# => if line_function is defined, we call it on each new line of the file.
if line_function:
o = text_utils.uni(logfile_reader.readline()).rstrip()
while o != '':
line_function(o)
o = text_utils.uni(logfile_reader.readline()).rstrip()
if not return_output:
# Return result code and ensure we have waited for the end of sub process
return process.wait()
logfile_reader.seek(logfile_start_position, os.SEEK_SET) #back to the beginning of the file
res = text_utils.uni(logfile_reader.read())
try:
logfile_reader.close()
logfile_writer.close()
err_logfile_writer.close()
if tmp_log:
shutil.rmtree(log_folder, ignore_errors=True)
except:
logger.exception("Error while cleaning after tbx.execute() call.")
return res | 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 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 should be written ( displayed on STDERR if not set)
:param timeout: if set, it will kill the subprocess created when "timeout" seconds is reached. It will then raise an Exception.
:param line_function: set it to a "function pointer" for the function to be called each time a new line is written (line passed as a parameter).
:param poll_timing: wait time between timeout checks and std output check.
:returns: Standard output of the command or if return_output=False, it will give the "return code" of the command
"""
tmp_log = False
if log_settings:
log_folder = log_settings.get('LOG_FOLDER')
else:
tmp_log = True
log_folder = tempfile.mkdtemp()
if not log_file:
log_file = os.path.join(log_folder, "commands", "execute-command-logfile-%s.log" % UUID.uuid4())
try:
if not os.path.isdir(os.path.join(log_folder, "commands")):
os.makedirs(os.path.join(log_folder, "commands"))
except:
pass
if not logger:
logger = logging.getLogger('command_execute')
logfile_writer = open(log_file, 'a')
header = "%s - Executing command (timeout=%s) :\n\t%s\n\n\n" % (datetime.now().isoformat(), timeout, command)
logfile_writer.write(header)
logfile_writer.flush()
logfile_reader = open(log_file, 'rb')
logfile_reader.seek(0, os.SEEK_END)
logfile_start_position = logfile_reader.tell()
if error_logfile:
err_logfile_writer = open(error_logfile, 'a')
else:
err_logfile_writer = logfile_writer
start = datetime.now()
timeout_string = ""
if timeout:
timeout_string = "(timeout=%s)" % timeout
logger.info(u"Executing command %s :\n\t\t%s" % (timeout_string, command) )
# We use "exec <command>" as Popen launches a shell, that runs the command.
# It will transform the child process "sh" into the "command exectable" because of the "exec".
# Said more accuratly, it won't fork to create launch the command in a sub sub process.
# Therefore, when you kill the child process, you kill the "command" process and not the unecessary "sh" parent process.
if sys.platform != 'win32':
command = u"exec %s" % text_utils.uni(command)
process = subprocess.Popen(command, stdout=logfile_writer, stderr=err_logfile_writer, bufsize=1, shell=True, cwd=working_folder, env=env)
while process.poll() == None:
# In order to avoid unecessary cpu usage, we wait for "poll_timing" seconds ( default: 0.1 sec )
time.sleep(poll_timing)
# Timeout check
if timeout != None:
now = datetime.now()
if (now - start).seconds> timeout:
#process.terminate() ??
os.kill(process.pid, signal.SIGKILL)
os.waitpid(-1, os.WNOHANG)
raise Exception("Command execution timed out (took more than %s seconds...)" % timeout)
# Line function call:
# => if line_function is defined, we call it on each new line of the file.
if line_function:
o = text_utils.uni(logfile_reader.readline()).rstrip()
while o != '':
line_function(o)
o = text_utils.uni(logfile_reader.readline()).rstrip()
if not return_output:
# Return result code and ensure we have waited for the end of sub process
return process.wait()
logfile_reader.seek(logfile_start_position, os.SEEK_SET) #back to the beginning of the file
res = text_utils.uni(logfile_reader.read())
try:
logfile_reader.close()
logfile_writer.close()
err_logfile_writer.close()
if tmp_log:
shutil.rmtree(log_folder, ignore_errors=True)
except:
logger.exception("Error while cleaning after tbx.execute() call.")
return res | [
"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",
")",
":",
"tmp_log",
"=",
"False",
"if",
"log_settings",
":",
"log_folder",
"=",
"log_settings",
".",
"get",
"(",
"'LOG_FOLDER'",
")",
"else",
":",
"tmp_log",
"=",
"True",
"log_folder",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"if",
"not",
"log_file",
":",
"log_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"log_folder",
",",
"\"commands\"",
",",
"\"execute-command-logfile-%s.log\"",
"%",
"UUID",
".",
"uuid4",
"(",
")",
")",
"try",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"log_folder",
",",
"\"commands\"",
")",
")",
":",
"os",
".",
"makedirs",
"(",
"os",
".",
"path",
".",
"join",
"(",
"log_folder",
",",
"\"commands\"",
")",
")",
"except",
":",
"pass",
"if",
"not",
"logger",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"'command_execute'",
")",
"logfile_writer",
"=",
"open",
"(",
"log_file",
",",
"'a'",
")",
"header",
"=",
"\"%s - Executing command (timeout=%s) :\\n\\t%s\\n\\n\\n\"",
"%",
"(",
"datetime",
".",
"now",
"(",
")",
".",
"isoformat",
"(",
")",
",",
"timeout",
",",
"command",
")",
"logfile_writer",
".",
"write",
"(",
"header",
")",
"logfile_writer",
".",
"flush",
"(",
")",
"logfile_reader",
"=",
"open",
"(",
"log_file",
",",
"'rb'",
")",
"logfile_reader",
".",
"seek",
"(",
"0",
",",
"os",
".",
"SEEK_END",
")",
"logfile_start_position",
"=",
"logfile_reader",
".",
"tell",
"(",
")",
"if",
"error_logfile",
":",
"err_logfile_writer",
"=",
"open",
"(",
"error_logfile",
",",
"'a'",
")",
"else",
":",
"err_logfile_writer",
"=",
"logfile_writer",
"start",
"=",
"datetime",
".",
"now",
"(",
")",
"timeout_string",
"=",
"\"\"",
"if",
"timeout",
":",
"timeout_string",
"=",
"\"(timeout=%s)\"",
"%",
"timeout",
"logger",
".",
"info",
"(",
"u\"Executing command %s :\\n\\t\\t%s\"",
"%",
"(",
"timeout_string",
",",
"command",
")",
")",
"# We use \"exec <command>\" as Popen launches a shell, that runs the command.",
"# It will transform the child process \"sh\" into the \"command exectable\" because of the \"exec\".",
"# Said more accuratly, it won't fork to create launch the command in a sub sub process.",
"# Therefore, when you kill the child process, you kill the \"command\" process and not the unecessary \"sh\" parent process.",
"if",
"sys",
".",
"platform",
"!=",
"'win32'",
":",
"command",
"=",
"u\"exec %s\"",
"%",
"text_utils",
".",
"uni",
"(",
"command",
")",
"process",
"=",
"subprocess",
".",
"Popen",
"(",
"command",
",",
"stdout",
"=",
"logfile_writer",
",",
"stderr",
"=",
"err_logfile_writer",
",",
"bufsize",
"=",
"1",
",",
"shell",
"=",
"True",
",",
"cwd",
"=",
"working_folder",
",",
"env",
"=",
"env",
")",
"while",
"process",
".",
"poll",
"(",
")",
"==",
"None",
":",
"# In order to avoid unecessary cpu usage, we wait for \"poll_timing\" seconds ( default: 0.1 sec )",
"time",
".",
"sleep",
"(",
"poll_timing",
")",
"# Timeout check",
"if",
"timeout",
"!=",
"None",
":",
"now",
"=",
"datetime",
".",
"now",
"(",
")",
"if",
"(",
"now",
"-",
"start",
")",
".",
"seconds",
">",
"timeout",
":",
"#process.terminate() ??",
"os",
".",
"kill",
"(",
"process",
".",
"pid",
",",
"signal",
".",
"SIGKILL",
")",
"os",
".",
"waitpid",
"(",
"-",
"1",
",",
"os",
".",
"WNOHANG",
")",
"raise",
"Exception",
"(",
"\"Command execution timed out (took more than %s seconds...)\"",
"%",
"timeout",
")",
"# Line function call:",
"# => if line_function is defined, we call it on each new line of the file.",
"if",
"line_function",
":",
"o",
"=",
"text_utils",
".",
"uni",
"(",
"logfile_reader",
".",
"readline",
"(",
")",
")",
".",
"rstrip",
"(",
")",
"while",
"o",
"!=",
"''",
":",
"line_function",
"(",
"o",
")",
"o",
"=",
"text_utils",
".",
"uni",
"(",
"logfile_reader",
".",
"readline",
"(",
")",
")",
".",
"rstrip",
"(",
")",
"if",
"not",
"return_output",
":",
"# Return result code and ensure we have waited for the end of sub process",
"return",
"process",
".",
"wait",
"(",
")",
"logfile_reader",
".",
"seek",
"(",
"logfile_start_position",
",",
"os",
".",
"SEEK_SET",
")",
"#back to the beginning of the file",
"res",
"=",
"text_utils",
".",
"uni",
"(",
"logfile_reader",
".",
"read",
"(",
")",
")",
"try",
":",
"logfile_reader",
".",
"close",
"(",
")",
"logfile_writer",
".",
"close",
"(",
")",
"err_logfile_writer",
".",
"close",
"(",
")",
"if",
"tmp_log",
":",
"shutil",
".",
"rmtree",
"(",
"log_folder",
",",
"ignore_errors",
"=",
"True",
")",
"except",
":",
"logger",
".",
"exception",
"(",
"\"Error while cleaning after tbx.execute() call.\"",
")",
"return",
"res"
]
| 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 should be written ( displayed on STDERR if not set)
:param timeout: if set, it will kill the subprocess created when "timeout" seconds is reached. It will then raise an Exception.
:param line_function: set it to a "function pointer" for the function to be called each time a new line is written (line passed as a parameter).
:param poll_timing: wait time between timeout checks and std output check.
:returns: Standard output of the command or if return_output=False, it will give the "return code" of the command | [
"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_saved_event.send(role)
return role | 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_saved_event.send(role)
return role | [
"def",
"save",
"(",
"self",
",",
"role",
",",
"commit",
"=",
"True",
")",
":",
"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_saved_event",
".",
"send",
"(",
"role",
")",
"return",
"role"
]
| 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):
environment where all the important data are persist
data (object):
data from the prepare phase
user (int):
identifier of the user answering the question
item (int):
identifier of the question item
correct (bool):
corretness of the answer
"""
pass | 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):
environment where all the important data are persist
data (object):
data from the prepare phase
user (int):
identifier of the user answering the question
item (int):
identifier of the question item
correct (bool):
corretness of the answer
"""
pass | [
"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 phase
user (int):
identifier of the user answering the question
item (int):
identifier of the question item
correct (bool):
corretness of the answer | [
"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:
markers = ['LOD2 interval start', 'LOD2 interval end']
elif row[3] in flanking_markers:
markers = flanking_markers[row[3]]
else:
markers = ['NA', 'NA']
cnt += 1
row.extend(markers)
output.append(row)
write_matrix(qtls_mk_file, output) | 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:
markers = ['LOD2 interval start', 'LOD2 interval end']
elif row[3] in flanking_markers:
markers = flanking_markers[row[3]]
else:
markers = ['NA', 'NA']
cnt += 1
row.extend(markers)
output.append(row)
write_matrix(qtls_mk_file, output) | [
"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",
"cnt",
"==",
"0",
":",
"markers",
"=",
"[",
"'LOD2 interval start'",
",",
"'LOD2 interval end'",
"]",
"elif",
"row",
"[",
"3",
"]",
"in",
"flanking_markers",
":",
"markers",
"=",
"flanking_markers",
"[",
"row",
"[",
"3",
"]",
"]",
"else",
":",
"markers",
"=",
"[",
"'NA'",
",",
"'NA'",
"]",
"cnt",
"+=",
"1",
"row",
".",
"extend",
"(",
"markers",
")",
"output",
".",
"append",
"(",
"row",
")",
"write_matrix",
"(",
"qtls_mk_file",
",",
"output",
")"
]
| 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.