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 listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
aiidalab/aiidalab-widgets-base | aiidalab_widgets_base/computers.py | SshComputerSetup.username | def username(self):
"""Loking for username in user's input and config file"""
if len(self._inp_username.value.strip()) == 0: # if username provided by user
if not self.hostname is None:
config = parse_sshconfig(self.hostname)
if 'user' in config: # if username is present in the config file
return config['user']
else:
return None
else:
return self._inp_username.value | python | def username(self):
"""Loking for username in user's input and config file"""
if len(self._inp_username.value.strip()) == 0: # if username provided by user
if not self.hostname is None:
config = parse_sshconfig(self.hostname)
if 'user' in config: # if username is present in the config file
return config['user']
else:
return None
else:
return self._inp_username.value | [
"def",
"username",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"_inp_username",
".",
"value",
".",
"strip",
"(",
")",
")",
"==",
"0",
":",
"# if username provided by user",
"if",
"not",
"self",
".",
"hostname",
"is",
"None",
":",
"config",
"=... | Loking for username in user's input and config file | [
"Loking",
"for",
"username",
"in",
"user",
"s",
"input",
"and",
"config",
"file"
] | 291a9b159eac902aee655862322670ec1b0cd5b1 | https://github.com/aiidalab/aiidalab-widgets-base/blob/291a9b159eac902aee655862322670ec1b0cd5b1/aiidalab_widgets_base/computers.py#L369-L379 | train | 50,200 |
internetarchive/doublethink | doublethink/orm.py | Document.load | def load(cls, rr, pk):
'''
Retrieves a document from the database, by primary key.
'''
if pk is None:
return None
d = rr.table(cls.table).get(pk).run()
if d is None:
return None
doc = cls(rr, d)
return doc | python | def load(cls, rr, pk):
'''
Retrieves a document from the database, by primary key.
'''
if pk is None:
return None
d = rr.table(cls.table).get(pk).run()
if d is None:
return None
doc = cls(rr, d)
return doc | [
"def",
"load",
"(",
"cls",
",",
"rr",
",",
"pk",
")",
":",
"if",
"pk",
"is",
"None",
":",
"return",
"None",
"d",
"=",
"rr",
".",
"table",
"(",
"cls",
".",
"table",
")",
".",
"get",
"(",
"pk",
")",
".",
"run",
"(",
")",
"if",
"d",
"is",
"N... | Retrieves a document from the database, by primary key. | [
"Retrieves",
"a",
"document",
"from",
"the",
"database",
"by",
"primary",
"key",
"."
] | f7fc7da725c9b572d473c717b3dad9af98a7a2b4 | https://github.com/internetarchive/doublethink/blob/f7fc7da725c9b572d473c717b3dad9af98a7a2b4/doublethink/orm.py#L161-L171 | train | 50,201 |
internetarchive/doublethink | doublethink/orm.py | Document.table_ensure | def table_ensure(cls, rr):
'''
Creates the table if it doesn't exist.
'''
dbs = rr.db_list().run()
if not rr.dbname in dbs:
logging.info('creating rethinkdb database %s', repr(rr.dbname))
rr.db_create(rr.dbname).run()
tables = rr.table_list().run()
if not cls.table in tables:
logging.info(
'creating rethinkdb table %s in database %s',
repr(cls.table), repr(rr.dbname))
cls.table_create(rr) | python | def table_ensure(cls, rr):
'''
Creates the table if it doesn't exist.
'''
dbs = rr.db_list().run()
if not rr.dbname in dbs:
logging.info('creating rethinkdb database %s', repr(rr.dbname))
rr.db_create(rr.dbname).run()
tables = rr.table_list().run()
if not cls.table in tables:
logging.info(
'creating rethinkdb table %s in database %s',
repr(cls.table), repr(rr.dbname))
cls.table_create(rr) | [
"def",
"table_ensure",
"(",
"cls",
",",
"rr",
")",
":",
"dbs",
"=",
"rr",
".",
"db_list",
"(",
")",
".",
"run",
"(",
")",
"if",
"not",
"rr",
".",
"dbname",
"in",
"dbs",
":",
"logging",
".",
"info",
"(",
"'creating rethinkdb database %s'",
",",
"repr"... | Creates the table if it doesn't exist. | [
"Creates",
"the",
"table",
"if",
"it",
"doesn",
"t",
"exist",
"."
] | f7fc7da725c9b572d473c717b3dad9af98a7a2b4 | https://github.com/internetarchive/doublethink/blob/f7fc7da725c9b572d473c717b3dad9af98a7a2b4/doublethink/orm.py#L182-L195 | train | 50,202 |
internetarchive/doublethink | doublethink/orm.py | Document.pk_field | def pk_field(self):
'''
Name of the primary key field as retrieved from rethinkdb table
metadata, 'id' by default. Should not be overridden. Override
`table_create` if you want to use a nonstandard field as the primary
key.
'''
if not self._pk:
try:
pk = self.rr.db('rethinkdb').table('table_config').filter({
'db': self.rr.dbname, 'name': self.table}).get_field(
'primary_key')[0].run()
self._pk = pk
except Exception as e:
raise Exception(
'problem determining primary key for table %s.%s: %s',
self.rr.dbname, self.table, e)
return self._pk | python | def pk_field(self):
'''
Name of the primary key field as retrieved from rethinkdb table
metadata, 'id' by default. Should not be overridden. Override
`table_create` if you want to use a nonstandard field as the primary
key.
'''
if not self._pk:
try:
pk = self.rr.db('rethinkdb').table('table_config').filter({
'db': self.rr.dbname, 'name': self.table}).get_field(
'primary_key')[0].run()
self._pk = pk
except Exception as e:
raise Exception(
'problem determining primary key for table %s.%s: %s',
self.rr.dbname, self.table, e)
return self._pk | [
"def",
"pk_field",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_pk",
":",
"try",
":",
"pk",
"=",
"self",
".",
"rr",
".",
"db",
"(",
"'rethinkdb'",
")",
".",
"table",
"(",
"'table_config'",
")",
".",
"filter",
"(",
"{",
"'db'",
":",
"self",
... | Name of the primary key field as retrieved from rethinkdb table
metadata, 'id' by default. Should not be overridden. Override
`table_create` if you want to use a nonstandard field as the primary
key. | [
"Name",
"of",
"the",
"primary",
"key",
"field",
"as",
"retrieved",
"from",
"rethinkdb",
"table",
"metadata",
"id",
"by",
"default",
".",
"Should",
"not",
"be",
"overridden",
".",
"Override",
"table_create",
"if",
"you",
"want",
"to",
"use",
"a",
"nonstandard... | f7fc7da725c9b572d473c717b3dad9af98a7a2b4 | https://github.com/internetarchive/doublethink/blob/f7fc7da725c9b572d473c717b3dad9af98a7a2b4/doublethink/orm.py#L268-L285 | train | 50,203 |
internetarchive/doublethink | doublethink/orm.py | Document.save | def save(self):
'''
Persist changes to rethinkdb. Updates only the fields that have
changed. Performs insert rather than update if the document has no
primary key or if the primary key is absent from the database.
If there have been any changes to nested fields, updates the first
level attribute. For example, if foo['bar']['baz']['quux'] has changed,
all of foo['bar'] is replaced, but foo['something_else'] is not
touched.
'''
should_insert = False
try:
self[self.pk_field] # raises KeyError if missing
if self._updates:
# r.literal() to replace, not merge with, nested fields
updates = {field: r.literal(self._updates[field])
for field in self._updates}
query = self.rr.table(self.table).get(
self.pk_value).update(updates)
result = query.run()
if result['skipped']: # primary key not found
should_insert = True
elif result['errors'] or result['deleted']:
raise Exception(
'unexpected result %s from rethinkdb query %s' % (
result, query))
if not should_insert and self._deletes:
query = self.rr.table(self.table).get(self.pk_value).replace(
r.row.without(self._deletes))
result = query.run()
if result['errors']: # primary key not found
should_insert = True
elif result['replaced'] != 1:
raise Exception(
'unexpected result %s from rethinkdb query %s' % (
result, query))
except KeyError:
should_insert = True
if should_insert:
query = self.rr.table(self.table).insert(self)
result = query.run()
if result['inserted'] != 1:
raise Exception(
'unexpected result %s from rethinkdb query %s' % (
result, query))
if 'generated_keys' in result:
dict.__setitem__(
self, self.pk_field, result['generated_keys'][0])
self._clear_updates() | python | def save(self):
'''
Persist changes to rethinkdb. Updates only the fields that have
changed. Performs insert rather than update if the document has no
primary key or if the primary key is absent from the database.
If there have been any changes to nested fields, updates the first
level attribute. For example, if foo['bar']['baz']['quux'] has changed,
all of foo['bar'] is replaced, but foo['something_else'] is not
touched.
'''
should_insert = False
try:
self[self.pk_field] # raises KeyError if missing
if self._updates:
# r.literal() to replace, not merge with, nested fields
updates = {field: r.literal(self._updates[field])
for field in self._updates}
query = self.rr.table(self.table).get(
self.pk_value).update(updates)
result = query.run()
if result['skipped']: # primary key not found
should_insert = True
elif result['errors'] or result['deleted']:
raise Exception(
'unexpected result %s from rethinkdb query %s' % (
result, query))
if not should_insert and self._deletes:
query = self.rr.table(self.table).get(self.pk_value).replace(
r.row.without(self._deletes))
result = query.run()
if result['errors']: # primary key not found
should_insert = True
elif result['replaced'] != 1:
raise Exception(
'unexpected result %s from rethinkdb query %s' % (
result, query))
except KeyError:
should_insert = True
if should_insert:
query = self.rr.table(self.table).insert(self)
result = query.run()
if result['inserted'] != 1:
raise Exception(
'unexpected result %s from rethinkdb query %s' % (
result, query))
if 'generated_keys' in result:
dict.__setitem__(
self, self.pk_field, result['generated_keys'][0])
self._clear_updates() | [
"def",
"save",
"(",
"self",
")",
":",
"should_insert",
"=",
"False",
"try",
":",
"self",
"[",
"self",
".",
"pk_field",
"]",
"# raises KeyError if missing",
"if",
"self",
".",
"_updates",
":",
"# r.literal() to replace, not merge with, nested fields",
"updates",
"=",... | Persist changes to rethinkdb. Updates only the fields that have
changed. Performs insert rather than update if the document has no
primary key or if the primary key is absent from the database.
If there have been any changes to nested fields, updates the first
level attribute. For example, if foo['bar']['baz']['quux'] has changed,
all of foo['bar'] is replaced, but foo['something_else'] is not
touched. | [
"Persist",
"changes",
"to",
"rethinkdb",
".",
"Updates",
"only",
"the",
"fields",
"that",
"have",
"changed",
".",
"Performs",
"insert",
"rather",
"than",
"update",
"if",
"the",
"document",
"has",
"no",
"primary",
"key",
"or",
"if",
"the",
"primary",
"key",
... | f7fc7da725c9b572d473c717b3dad9af98a7a2b4 | https://github.com/internetarchive/doublethink/blob/f7fc7da725c9b572d473c717b3dad9af98a7a2b4/doublethink/orm.py#L302-L353 | train | 50,204 |
internetarchive/doublethink | doublethink/orm.py | Document.refresh | def refresh(self):
'''
Refresh the document from the database.
'''
d = self.rr.table(self.table).get(self.pk_value).run()
if d is None:
raise KeyError
for k in d:
dict.__setitem__(
self, k, watch(d[k], callback=self._updated, field=k)) | python | def refresh(self):
'''
Refresh the document from the database.
'''
d = self.rr.table(self.table).get(self.pk_value).run()
if d is None:
raise KeyError
for k in d:
dict.__setitem__(
self, k, watch(d[k], callback=self._updated, field=k)) | [
"def",
"refresh",
"(",
"self",
")",
":",
"d",
"=",
"self",
".",
"rr",
".",
"table",
"(",
"self",
".",
"table",
")",
".",
"get",
"(",
"self",
".",
"pk_value",
")",
".",
"run",
"(",
")",
"if",
"d",
"is",
"None",
":",
"raise",
"KeyError",
"for",
... | Refresh the document from the database. | [
"Refresh",
"the",
"document",
"from",
"the",
"database",
"."
] | f7fc7da725c9b572d473c717b3dad9af98a7a2b4 | https://github.com/internetarchive/doublethink/blob/f7fc7da725c9b572d473c717b3dad9af98a7a2b4/doublethink/orm.py#L355-L364 | train | 50,205 |
eumis/pyviews | pyviews/core/xml.py | Parser.parse | def parse(self, xml_file, view_name=None) -> XmlNode:
"""Parses xml file with xml_path and returns XmlNode"""
self._setup_parser()
try:
self._view_name = view_name
self._parser.ParseFile(xml_file)
except ExpatError as error:
# pylint: disable=E1101
raise XmlError(errors.messages[error.code], ViewInfo(view_name, error.lineno))
root = self._root
self._reset()
return root | python | def parse(self, xml_file, view_name=None) -> XmlNode:
"""Parses xml file with xml_path and returns XmlNode"""
self._setup_parser()
try:
self._view_name = view_name
self._parser.ParseFile(xml_file)
except ExpatError as error:
# pylint: disable=E1101
raise XmlError(errors.messages[error.code], ViewInfo(view_name, error.lineno))
root = self._root
self._reset()
return root | [
"def",
"parse",
"(",
"self",
",",
"xml_file",
",",
"view_name",
"=",
"None",
")",
"->",
"XmlNode",
":",
"self",
".",
"_setup_parser",
"(",
")",
"try",
":",
"self",
".",
"_view_name",
"=",
"view_name",
"self",
".",
"_parser",
".",
"ParseFile",
"(",
"xml... | Parses xml file with xml_path and returns XmlNode | [
"Parses",
"xml",
"file",
"with",
"xml_path",
"and",
"returns",
"XmlNode"
] | 80a868242ee9cdc6f4ded594b3e0544cc238ed55 | https://github.com/eumis/pyviews/blob/80a868242ee9cdc6f4ded594b3e0544cc238ed55/pyviews/core/xml.py#L111-L123 | train | 50,206 |
QualiSystems/cloudshell-networking-devices | cloudshell/devices/runners/connectivity_runner.py | ConnectivityRunner.apply_connectivity_changes | def apply_connectivity_changes(self, request):
""" Handle apply connectivity changes request json, trigger add or remove vlan methods,
get responce from them and create json response
:param request: json with all required action to configure or remove vlans from certain port
:return Serialized DriverResponseRoot to json
:rtype json
"""
if request is None or request == "":
raise Exception(self.__class__.__name__, "request is None or empty")
holder = JsonRequestDeserializer(jsonpickle.decode(request))
if not holder or not hasattr(holder, "driverRequest"):
raise Exception(self.__class__.__name__, "Deserialized request is None or empty")
driver_response = DriverResponse()
add_vlan_thread_list = []
remove_vlan_thread_list = []
driver_response_root = DriverResponseRoot()
for action in holder.driverRequest.actions:
self._logger.info("Action: ", action.__dict__)
self._validate_request_action(action)
action_id = action.actionId
full_name = action.actionTarget.fullName
port_mode = action.connectionParams.mode.lower()
if action.type == "setVlan":
qnq = False
ctag = ""
for attribute in action.connectionParams.vlanServiceAttributes:
if attribute.attributeName.lower() == "qnq" and attribute.attributeValue.lower() == "true":
qnq = True
if attribute.attributeName.lower() == "ctag":
ctag = attribute.attributeValue
for vlan_id in self._get_vlan_list(action.connectionParams.vlanId):
add_vlan_thread = Thread(target=self.add_vlan,
name=action_id,
args=(vlan_id, full_name, port_mode, qnq, ctag))
add_vlan_thread_list.append(add_vlan_thread)
elif action.type == "removeVlan":
for vlan_id in self._get_vlan_list(action.connectionParams.vlanId):
remove_vlan_thread = Thread(target=self.remove_vlan,
name=action_id,
args=(vlan_id, full_name, port_mode,))
remove_vlan_thread_list.append(remove_vlan_thread)
else:
self._logger.warning("Undefined action type determined '{}': {}".format(action.type, action.__dict__))
continue
# Start all created remove_vlan_threads
for thread in remove_vlan_thread_list:
thread.start()
# Join all remove_vlan_threads. Main thread will wait completion of all remove_vlan_thread
for thread in remove_vlan_thread_list:
thread.join()
# Start all created add_vlan_threads
for thread in add_vlan_thread_list:
thread.start()
# Join all add_vlan_threads. Main thread will wait completion of all add_vlan_thread
for thread in add_vlan_thread_list:
thread.join()
request_result = []
for action in holder.driverRequest.actions:
result_statuses, message = zip(*self.result.get(action.actionId))
if all(result_statuses):
action_result = ConnectivitySuccessResponse(action,
"Add Vlan {vlan} configuration successfully completed"
.format(vlan=action.connectionParams.vlanId))
else:
message_details = "\n\t".join(message)
action_result = ConnectivityErrorResponse(action, "Add Vlan {vlan} configuration failed."
"\nAdd Vlan configuration details:\n{message_details}"
.format(vlan=action.connectionParams.vlanId,
message_details=message_details))
request_result.append(action_result)
driver_response.actionResults = request_result
driver_response_root.driverResponse = driver_response
return serialize_to_json(driver_response_root) | python | def apply_connectivity_changes(self, request):
""" Handle apply connectivity changes request json, trigger add or remove vlan methods,
get responce from them and create json response
:param request: json with all required action to configure or remove vlans from certain port
:return Serialized DriverResponseRoot to json
:rtype json
"""
if request is None or request == "":
raise Exception(self.__class__.__name__, "request is None or empty")
holder = JsonRequestDeserializer(jsonpickle.decode(request))
if not holder or not hasattr(holder, "driverRequest"):
raise Exception(self.__class__.__name__, "Deserialized request is None or empty")
driver_response = DriverResponse()
add_vlan_thread_list = []
remove_vlan_thread_list = []
driver_response_root = DriverResponseRoot()
for action in holder.driverRequest.actions:
self._logger.info("Action: ", action.__dict__)
self._validate_request_action(action)
action_id = action.actionId
full_name = action.actionTarget.fullName
port_mode = action.connectionParams.mode.lower()
if action.type == "setVlan":
qnq = False
ctag = ""
for attribute in action.connectionParams.vlanServiceAttributes:
if attribute.attributeName.lower() == "qnq" and attribute.attributeValue.lower() == "true":
qnq = True
if attribute.attributeName.lower() == "ctag":
ctag = attribute.attributeValue
for vlan_id in self._get_vlan_list(action.connectionParams.vlanId):
add_vlan_thread = Thread(target=self.add_vlan,
name=action_id,
args=(vlan_id, full_name, port_mode, qnq, ctag))
add_vlan_thread_list.append(add_vlan_thread)
elif action.type == "removeVlan":
for vlan_id in self._get_vlan_list(action.connectionParams.vlanId):
remove_vlan_thread = Thread(target=self.remove_vlan,
name=action_id,
args=(vlan_id, full_name, port_mode,))
remove_vlan_thread_list.append(remove_vlan_thread)
else:
self._logger.warning("Undefined action type determined '{}': {}".format(action.type, action.__dict__))
continue
# Start all created remove_vlan_threads
for thread in remove_vlan_thread_list:
thread.start()
# Join all remove_vlan_threads. Main thread will wait completion of all remove_vlan_thread
for thread in remove_vlan_thread_list:
thread.join()
# Start all created add_vlan_threads
for thread in add_vlan_thread_list:
thread.start()
# Join all add_vlan_threads. Main thread will wait completion of all add_vlan_thread
for thread in add_vlan_thread_list:
thread.join()
request_result = []
for action in holder.driverRequest.actions:
result_statuses, message = zip(*self.result.get(action.actionId))
if all(result_statuses):
action_result = ConnectivitySuccessResponse(action,
"Add Vlan {vlan} configuration successfully completed"
.format(vlan=action.connectionParams.vlanId))
else:
message_details = "\n\t".join(message)
action_result = ConnectivityErrorResponse(action, "Add Vlan {vlan} configuration failed."
"\nAdd Vlan configuration details:\n{message_details}"
.format(vlan=action.connectionParams.vlanId,
message_details=message_details))
request_result.append(action_result)
driver_response.actionResults = request_result
driver_response_root.driverResponse = driver_response
return serialize_to_json(driver_response_root) | [
"def",
"apply_connectivity_changes",
"(",
"self",
",",
"request",
")",
":",
"if",
"request",
"is",
"None",
"or",
"request",
"==",
"\"\"",
":",
"raise",
"Exception",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"\"request is None or empty\"",
")",
"hold... | Handle apply connectivity changes request json, trigger add or remove vlan methods,
get responce from them and create json response
:param request: json with all required action to configure or remove vlans from certain port
:return Serialized DriverResponseRoot to json
:rtype json | [
"Handle",
"apply",
"connectivity",
"changes",
"request",
"json",
"trigger",
"add",
"or",
"remove",
"vlan",
"methods",
"get",
"responce",
"from",
"them",
"and",
"create",
"json",
"response"
] | 009aab33edb30035b52fe10dbb91db61c95ba4d9 | https://github.com/QualiSystems/cloudshell-networking-devices/blob/009aab33edb30035b52fe10dbb91db61c95ba4d9/cloudshell/devices/runners/connectivity_runner.py#L58-L145 | train | 50,207 |
QualiSystems/cloudshell-networking-devices | cloudshell/devices/runners/connectivity_runner.py | ConnectivityRunner._validate_request_action | def _validate_request_action(self, action):
""" Validate action from the request json,
according to APPLY_CONNECTIVITY_CHANGES_ACTION_REQUIRED_ATTRIBUTE_LIST
"""
is_fail = False
fail_attribute = ""
for class_attribute in self.APPLY_CONNECTIVITY_CHANGES_ACTION_REQUIRED_ATTRIBUTE_LIST:
if type(class_attribute) is tuple:
if not hasattr(action, class_attribute[0]):
is_fail = True
fail_attribute = class_attribute[0]
if not hasattr(getattr(action, class_attribute[0]), class_attribute[1]):
is_fail = True
fail_attribute = class_attribute[1]
else:
if not hasattr(action, class_attribute):
is_fail = True
fail_attribute = class_attribute
if is_fail:
raise Exception(self.__class__.__name__,
"Mandatory field {0} is missing in ApplyConnectivityChanges request json".format(
fail_attribute)) | python | def _validate_request_action(self, action):
""" Validate action from the request json,
according to APPLY_CONNECTIVITY_CHANGES_ACTION_REQUIRED_ATTRIBUTE_LIST
"""
is_fail = False
fail_attribute = ""
for class_attribute in self.APPLY_CONNECTIVITY_CHANGES_ACTION_REQUIRED_ATTRIBUTE_LIST:
if type(class_attribute) is tuple:
if not hasattr(action, class_attribute[0]):
is_fail = True
fail_attribute = class_attribute[0]
if not hasattr(getattr(action, class_attribute[0]), class_attribute[1]):
is_fail = True
fail_attribute = class_attribute[1]
else:
if not hasattr(action, class_attribute):
is_fail = True
fail_attribute = class_attribute
if is_fail:
raise Exception(self.__class__.__name__,
"Mandatory field {0} is missing in ApplyConnectivityChanges request json".format(
fail_attribute)) | [
"def",
"_validate_request_action",
"(",
"self",
",",
"action",
")",
":",
"is_fail",
"=",
"False",
"fail_attribute",
"=",
"\"\"",
"for",
"class_attribute",
"in",
"self",
".",
"APPLY_CONNECTIVITY_CHANGES_ACTION_REQUIRED_ATTRIBUTE_LIST",
":",
"if",
"type",
"(",
"class_at... | Validate action from the request json,
according to APPLY_CONNECTIVITY_CHANGES_ACTION_REQUIRED_ATTRIBUTE_LIST | [
"Validate",
"action",
"from",
"the",
"request",
"json",
"according",
"to",
"APPLY_CONNECTIVITY_CHANGES_ACTION_REQUIRED_ATTRIBUTE_LIST"
] | 009aab33edb30035b52fe10dbb91db61c95ba4d9 | https://github.com/QualiSystems/cloudshell-networking-devices/blob/009aab33edb30035b52fe10dbb91db61c95ba4d9/cloudshell/devices/runners/connectivity_runner.py#L147-L169 | train | 50,208 |
QualiSystems/cloudshell-networking-devices | cloudshell/devices/runners/connectivity_runner.py | ConnectivityRunner._get_vlan_list | def _get_vlan_list(self, vlan_str):
""" Get VLAN list from input string
:param vlan_str:
:return list of VLANs or Exception
"""
result = set()
for splitted_vlan in vlan_str.split(","):
if "-" not in splitted_vlan:
if validate_vlan_number(splitted_vlan):
result.add(int(splitted_vlan))
else:
raise Exception(self.__class__.__name__, "Wrong VLAN number detected {}".format(splitted_vlan))
else:
if self.IS_VLAN_RANGE_SUPPORTED:
if validate_vlan_range(splitted_vlan):
result.add(splitted_vlan)
else:
raise Exception(self.__class__.__name__, "Wrong VLANs range detected {}".format(vlan_str))
else:
start, end = map(int, splitted_vlan.split("-"))
if validate_vlan_number(start) and validate_vlan_number(end):
if start > end:
start, end = end, start
for vlan in range(start, end + 1):
result.add(vlan)
else:
raise Exception(self.__class__.__name__, "Wrong VLANs range detected {}".format(vlan_str))
return map(str, list(result)) | python | def _get_vlan_list(self, vlan_str):
""" Get VLAN list from input string
:param vlan_str:
:return list of VLANs or Exception
"""
result = set()
for splitted_vlan in vlan_str.split(","):
if "-" not in splitted_vlan:
if validate_vlan_number(splitted_vlan):
result.add(int(splitted_vlan))
else:
raise Exception(self.__class__.__name__, "Wrong VLAN number detected {}".format(splitted_vlan))
else:
if self.IS_VLAN_RANGE_SUPPORTED:
if validate_vlan_range(splitted_vlan):
result.add(splitted_vlan)
else:
raise Exception(self.__class__.__name__, "Wrong VLANs range detected {}".format(vlan_str))
else:
start, end = map(int, splitted_vlan.split("-"))
if validate_vlan_number(start) and validate_vlan_number(end):
if start > end:
start, end = end, start
for vlan in range(start, end + 1):
result.add(vlan)
else:
raise Exception(self.__class__.__name__, "Wrong VLANs range detected {}".format(vlan_str))
return map(str, list(result)) | [
"def",
"_get_vlan_list",
"(",
"self",
",",
"vlan_str",
")",
":",
"result",
"=",
"set",
"(",
")",
"for",
"splitted_vlan",
"in",
"vlan_str",
".",
"split",
"(",
"\",\"",
")",
":",
"if",
"\"-\"",
"not",
"in",
"splitted_vlan",
":",
"if",
"validate_vlan_number",... | Get VLAN list from input string
:param vlan_str:
:return list of VLANs or Exception | [
"Get",
"VLAN",
"list",
"from",
"input",
"string"
] | 009aab33edb30035b52fe10dbb91db61c95ba4d9 | https://github.com/QualiSystems/cloudshell-networking-devices/blob/009aab33edb30035b52fe10dbb91db61c95ba4d9/cloudshell/devices/runners/connectivity_runner.py#L171-L201 | train | 50,209 |
eumis/pyviews | pyviews/rendering/views.py | render_view | def render_view(view_name, **args):
'''Process view and return root Node'''
try:
root_xml = get_view_root(view_name)
return render(root_xml, **args)
except CoreError as error:
error.add_view_info(ViewInfo(view_name, None))
raise
except:
info = exc_info()
error = ViewError('Unknown error occured during rendering', ViewInfo(view_name, None))
error.add_cause(info[1])
raise error from info[1] | python | def render_view(view_name, **args):
'''Process view and return root Node'''
try:
root_xml = get_view_root(view_name)
return render(root_xml, **args)
except CoreError as error:
error.add_view_info(ViewInfo(view_name, None))
raise
except:
info = exc_info()
error = ViewError('Unknown error occured during rendering', ViewInfo(view_name, None))
error.add_cause(info[1])
raise error from info[1] | [
"def",
"render_view",
"(",
"view_name",
",",
"*",
"*",
"args",
")",
":",
"try",
":",
"root_xml",
"=",
"get_view_root",
"(",
"view_name",
")",
"return",
"render",
"(",
"root_xml",
",",
"*",
"*",
"args",
")",
"except",
"CoreError",
"as",
"error",
":",
"e... | Process view and return root Node | [
"Process",
"view",
"and",
"return",
"root",
"Node"
] | 80a868242ee9cdc6f4ded594b3e0544cc238ed55 | https://github.com/eumis/pyviews/blob/80a868242ee9cdc6f4ded594b3e0544cc238ed55/pyviews/rendering/views.py#L13-L25 | train | 50,210 |
eumis/pyviews | pyviews/rendering/views.py | get_view_root | def get_view_root(view_name: str) -> XmlNode:
'''Parses xml file and return root XmlNode'''
try:
path = join(deps.views_folder, '{0}.{1}'.format(view_name, deps.view_ext))
parser = Parser()
if path not in _XML_CACHE:
with open(path, 'rb') as xml_file:
_XML_CACHE[path] = parser.parse(xml_file, view_name)
return _XML_CACHE[path]
except FileNotFoundError as error:
error = ViewError('View is not found')
error.add_info('View name', view_name)
error.add_info('Path', path)
raise error
except CoreError as error:
error.add_view_info(ViewInfo(view_name, None))
raise
except:
info = exc_info()
error = ViewError('Unknown error occured during parsing xml', ViewInfo(view_name, None))
error.add_cause(info[1])
raise error from info[1] | python | def get_view_root(view_name: str) -> XmlNode:
'''Parses xml file and return root XmlNode'''
try:
path = join(deps.views_folder, '{0}.{1}'.format(view_name, deps.view_ext))
parser = Parser()
if path not in _XML_CACHE:
with open(path, 'rb') as xml_file:
_XML_CACHE[path] = parser.parse(xml_file, view_name)
return _XML_CACHE[path]
except FileNotFoundError as error:
error = ViewError('View is not found')
error.add_info('View name', view_name)
error.add_info('Path', path)
raise error
except CoreError as error:
error.add_view_info(ViewInfo(view_name, None))
raise
except:
info = exc_info()
error = ViewError('Unknown error occured during parsing xml', ViewInfo(view_name, None))
error.add_cause(info[1])
raise error from info[1] | [
"def",
"get_view_root",
"(",
"view_name",
":",
"str",
")",
"->",
"XmlNode",
":",
"try",
":",
"path",
"=",
"join",
"(",
"deps",
".",
"views_folder",
",",
"'{0}.{1}'",
".",
"format",
"(",
"view_name",
",",
"deps",
".",
"view_ext",
")",
")",
"parser",
"="... | Parses xml file and return root XmlNode | [
"Parses",
"xml",
"file",
"and",
"return",
"root",
"XmlNode"
] | 80a868242ee9cdc6f4ded594b3e0544cc238ed55 | https://github.com/eumis/pyviews/blob/80a868242ee9cdc6f4ded594b3e0544cc238ed55/pyviews/rendering/views.py#L29-L50 | train | 50,211 |
eumis/pyviews | pyviews/rendering/modifiers.py | import_global | def import_global(node: Node, key: str, path: Any):
"""Import passed module, class, function full name and stores it to node's globals"""
node.node_globals[key] = import_path(path) | python | def import_global(node: Node, key: str, path: Any):
"""Import passed module, class, function full name and stores it to node's globals"""
node.node_globals[key] = import_path(path) | [
"def",
"import_global",
"(",
"node",
":",
"Node",
",",
"key",
":",
"str",
",",
"path",
":",
"Any",
")",
":",
"node",
".",
"node_globals",
"[",
"key",
"]",
"=",
"import_path",
"(",
"path",
")"
] | Import passed module, class, function full name and stores it to node's globals | [
"Import",
"passed",
"module",
"class",
"function",
"full",
"name",
"and",
"stores",
"it",
"to",
"node",
"s",
"globals"
] | 80a868242ee9cdc6f4ded594b3e0544cc238ed55 | https://github.com/eumis/pyviews/blob/80a868242ee9cdc6f4ded594b3e0544cc238ed55/pyviews/rendering/modifiers.py#L8-L10 | train | 50,212 |
eumis/pyviews | pyviews/rendering/modifiers.py | inject_global | def inject_global(node: Node, global_key: str, inject_key: Any):
"""Resolves passed dependency and stores it to node's globals"""
value = get_current_scope().container.get(inject_key)
set_global(node, global_key, value) | python | def inject_global(node: Node, global_key: str, inject_key: Any):
"""Resolves passed dependency and stores it to node's globals"""
value = get_current_scope().container.get(inject_key)
set_global(node, global_key, value) | [
"def",
"inject_global",
"(",
"node",
":",
"Node",
",",
"global_key",
":",
"str",
",",
"inject_key",
":",
"Any",
")",
":",
"value",
"=",
"get_current_scope",
"(",
")",
".",
"container",
".",
"get",
"(",
"inject_key",
")",
"set_global",
"(",
"node",
",",
... | Resolves passed dependency and stores it to node's globals | [
"Resolves",
"passed",
"dependency",
"and",
"stores",
"it",
"to",
"node",
"s",
"globals"
] | 80a868242ee9cdc6f4ded594b3e0544cc238ed55 | https://github.com/eumis/pyviews/blob/80a868242ee9cdc6f4ded594b3e0544cc238ed55/pyviews/rendering/modifiers.py#L13-L16 | train | 50,213 |
eumis/pyviews | pyviews/rendering/modifiers.py | set_global | def set_global(node: Node, key: str, value: Any):
"""Adds passed value to node's globals"""
node.node_globals[key] = value | python | def set_global(node: Node, key: str, value: Any):
"""Adds passed value to node's globals"""
node.node_globals[key] = value | [
"def",
"set_global",
"(",
"node",
":",
"Node",
",",
"key",
":",
"str",
",",
"value",
":",
"Any",
")",
":",
"node",
".",
"node_globals",
"[",
"key",
"]",
"=",
"value"
] | Adds passed value to node's globals | [
"Adds",
"passed",
"value",
"to",
"node",
"s",
"globals"
] | 80a868242ee9cdc6f4ded594b3e0544cc238ed55 | https://github.com/eumis/pyviews/blob/80a868242ee9cdc6f4ded594b3e0544cc238ed55/pyviews/rendering/modifiers.py#L19-L21 | train | 50,214 |
eumis/pyviews | pyviews/rendering/modifiers.py | call | def call(node: Node, key: str, value: Any):
"""Calls node or node instance method"""
value = _to_list(value)
if not value or not isinstance(value[-1], dict):
value.append({})
args = value[0:-1]
kwargs = value[-1]
node.__dict__[key](*args, **kwargs) | python | def call(node: Node, key: str, value: Any):
"""Calls node or node instance method"""
value = _to_list(value)
if not value or not isinstance(value[-1], dict):
value.append({})
args = value[0:-1]
kwargs = value[-1]
node.__dict__[key](*args, **kwargs) | [
"def",
"call",
"(",
"node",
":",
"Node",
",",
"key",
":",
"str",
",",
"value",
":",
"Any",
")",
":",
"value",
"=",
"_to_list",
"(",
"value",
")",
"if",
"not",
"value",
"or",
"not",
"isinstance",
"(",
"value",
"[",
"-",
"1",
"]",
",",
"dict",
")... | Calls node or node instance method | [
"Calls",
"node",
"or",
"node",
"instance",
"method"
] | 80a868242ee9cdc6f4ded594b3e0544cc238ed55 | https://github.com/eumis/pyviews/blob/80a868242ee9cdc6f4ded594b3e0544cc238ed55/pyviews/rendering/modifiers.py#L24-L31 | train | 50,215 |
upsight/doctor | doctor/docs/flask.py | AutoFlaskHarness.iter_annotations | def iter_annotations(self):
"""Yield a tuple for each Flask handler containing annotated methods.
Each tuple contains a heading, routing rule, the view class associated
with the rule, and the annotations for the methods in that class.
"""
# Need to store a list of route, view_class, and annotations by a
# section key so that all methods of a resource are kept together in
# the documentation. The key of the section will be the heading that
# the route documentation goes under.
section_map = defaultdict(list)
for rule in self.app.url_map.iter_rules():
if rule.endpoint == 'static':
# Don't document static file endpoints.
continue
# This gives us the auto-generated view function.
view_function = self.app.view_functions.get(rule.endpoint)
if view_function is None:
continue
# This gives us the actual Flask resource class.
view_class = getattr(view_function, 'view_class', None)
if view_class is None:
continue
annotations = []
for method_name in HTTP_METHODS:
method = getattr(view_class, method_name, None)
if not method:
continue
annotation = ResourceAnnotation(
method, method_name, method._doctor_title)
annotations.append(annotation)
if annotations:
heading = self._get_annotation_heading(view_class, str(rule))
section_map[heading].append((rule, view_class, annotations))
# Loop through each heading and it's items and yield the values.
for heading in sorted(section_map.keys()):
for item in section_map[heading]:
rule, view_class, annotations = item
yield (heading, rule, view_class, annotations) | python | def iter_annotations(self):
"""Yield a tuple for each Flask handler containing annotated methods.
Each tuple contains a heading, routing rule, the view class associated
with the rule, and the annotations for the methods in that class.
"""
# Need to store a list of route, view_class, and annotations by a
# section key so that all methods of a resource are kept together in
# the documentation. The key of the section will be the heading that
# the route documentation goes under.
section_map = defaultdict(list)
for rule in self.app.url_map.iter_rules():
if rule.endpoint == 'static':
# Don't document static file endpoints.
continue
# This gives us the auto-generated view function.
view_function = self.app.view_functions.get(rule.endpoint)
if view_function is None:
continue
# This gives us the actual Flask resource class.
view_class = getattr(view_function, 'view_class', None)
if view_class is None:
continue
annotations = []
for method_name in HTTP_METHODS:
method = getattr(view_class, method_name, None)
if not method:
continue
annotation = ResourceAnnotation(
method, method_name, method._doctor_title)
annotations.append(annotation)
if annotations:
heading = self._get_annotation_heading(view_class, str(rule))
section_map[heading].append((rule, view_class, annotations))
# Loop through each heading and it's items and yield the values.
for heading in sorted(section_map.keys()):
for item in section_map[heading]:
rule, view_class, annotations = item
yield (heading, rule, view_class, annotations) | [
"def",
"iter_annotations",
"(",
"self",
")",
":",
"# Need to store a list of route, view_class, and annotations by a",
"# section key so that all methods of a resource are kept together in",
"# the documentation. The key of the section will be the heading that",
"# the route documentation goes un... | Yield a tuple for each Flask handler containing annotated methods.
Each tuple contains a heading, routing rule, the view class associated
with the rule, and the annotations for the methods in that class. | [
"Yield",
"a",
"tuple",
"for",
"each",
"Flask",
"handler",
"containing",
"annotated",
"methods",
"."
] | 2cf1d433f6f1aa1355644b449a757c0660793cdd | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/docs/flask.py#L41-L81 | train | 50,216 |
upsight/doctor | doctor/docs/flask.py | AutoFlaskHarness.request | def request(self, rule, view_class, annotation):
"""Make a request against the app.
This attempts to use the schema to replace any url params in the path
pattern. If there are any unused parameters in the schema, after
substituting the ones in the path, they will be sent as query string
parameters or form parameters. The substituted values are taken from
the "example" value in the schema.
Returns a dict with the following keys:
- **url** -- Example URL, with url_prefix added to the path pattern,
and the example values substituted in for URL params.
- **method** -- HTTP request method (e.g. "GET").
- **params** -- A dictionary of query string or form parameters.
- **response** -- The text response to the request.
:param route: Werkzeug Route object.
:param view_class: View class for the annotated method.
:param annotation: Annotation for the method to be requested.
:type annotation: doctor.resource.ResourceAnnotation
:returns: dict
"""
headers = self._get_headers(rule, annotation)
example_values = self._get_example_values(rule, annotation)
# If any of the example values for DELETE/GET HTTP methods are dicts
# or lists, we will need to json dump them before building the rule,
# otherwise the query string parameter won't get parsed correctly
# by doctor.
if annotation.http_method.upper() in ('DELETE', 'GET'):
for key, value in list(example_values.items()):
if isinstance(value, (dict, list)):
example_values[key] = json.dumps(value)
_, path = rule.build(example_values, append_unknown=True)
if annotation.http_method.upper() not in ('DELETE', 'GET'):
parsed_path = parse.urlparse(path)
path = parsed_path.path
params = example_values
else:
params = {}
method_name = annotation.http_method.lower()
method = getattr(self.test_client, method_name)
if method_name in ('post', 'put'):
response = method(path, data=json.dumps(params), headers=headers,
content_type='application/json')
else:
response = method(path, data=params, headers=headers)
return {
'url': '/'.join([self.url_prefix, path.lstrip('/')]),
'method': annotation.http_method.upper(),
'params': params,
'response': response.data,
} | python | def request(self, rule, view_class, annotation):
"""Make a request against the app.
This attempts to use the schema to replace any url params in the path
pattern. If there are any unused parameters in the schema, after
substituting the ones in the path, they will be sent as query string
parameters or form parameters. The substituted values are taken from
the "example" value in the schema.
Returns a dict with the following keys:
- **url** -- Example URL, with url_prefix added to the path pattern,
and the example values substituted in for URL params.
- **method** -- HTTP request method (e.g. "GET").
- **params** -- A dictionary of query string or form parameters.
- **response** -- The text response to the request.
:param route: Werkzeug Route object.
:param view_class: View class for the annotated method.
:param annotation: Annotation for the method to be requested.
:type annotation: doctor.resource.ResourceAnnotation
:returns: dict
"""
headers = self._get_headers(rule, annotation)
example_values = self._get_example_values(rule, annotation)
# If any of the example values for DELETE/GET HTTP methods are dicts
# or lists, we will need to json dump them before building the rule,
# otherwise the query string parameter won't get parsed correctly
# by doctor.
if annotation.http_method.upper() in ('DELETE', 'GET'):
for key, value in list(example_values.items()):
if isinstance(value, (dict, list)):
example_values[key] = json.dumps(value)
_, path = rule.build(example_values, append_unknown=True)
if annotation.http_method.upper() not in ('DELETE', 'GET'):
parsed_path = parse.urlparse(path)
path = parsed_path.path
params = example_values
else:
params = {}
method_name = annotation.http_method.lower()
method = getattr(self.test_client, method_name)
if method_name in ('post', 'put'):
response = method(path, data=json.dumps(params), headers=headers,
content_type='application/json')
else:
response = method(path, data=params, headers=headers)
return {
'url': '/'.join([self.url_prefix, path.lstrip('/')]),
'method': annotation.http_method.upper(),
'params': params,
'response': response.data,
} | [
"def",
"request",
"(",
"self",
",",
"rule",
",",
"view_class",
",",
"annotation",
")",
":",
"headers",
"=",
"self",
".",
"_get_headers",
"(",
"rule",
",",
"annotation",
")",
"example_values",
"=",
"self",
".",
"_get_example_values",
"(",
"rule",
",",
"anno... | Make a request against the app.
This attempts to use the schema to replace any url params in the path
pattern. If there are any unused parameters in the schema, after
substituting the ones in the path, they will be sent as query string
parameters or form parameters. The substituted values are taken from
the "example" value in the schema.
Returns a dict with the following keys:
- **url** -- Example URL, with url_prefix added to the path pattern,
and the example values substituted in for URL params.
- **method** -- HTTP request method (e.g. "GET").
- **params** -- A dictionary of query string or form parameters.
- **response** -- The text response to the request.
:param route: Werkzeug Route object.
:param view_class: View class for the annotated method.
:param annotation: Annotation for the method to be requested.
:type annotation: doctor.resource.ResourceAnnotation
:returns: dict | [
"Make",
"a",
"request",
"against",
"the",
"app",
"."
] | 2cf1d433f6f1aa1355644b449a757c0660793cdd | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/docs/flask.py#L83-L135 | train | 50,217 |
eumis/pyviews | pyviews/core/observable.py | Observable.release | def release(self, key: str, callback: Callable[[Any, Any], None]):
"""Releases callback from key changes"""
try:
self._callbacks[key].remove(callback)
except (KeyError, ValueError):
pass | python | def release(self, key: str, callback: Callable[[Any, Any], None]):
"""Releases callback from key changes"""
try:
self._callbacks[key].remove(callback)
except (KeyError, ValueError):
pass | [
"def",
"release",
"(",
"self",
",",
"key",
":",
"str",
",",
"callback",
":",
"Callable",
"[",
"[",
"Any",
",",
"Any",
"]",
",",
"None",
"]",
")",
":",
"try",
":",
"self",
".",
"_callbacks",
"[",
"key",
"]",
".",
"remove",
"(",
"callback",
")",
... | Releases callback from key changes | [
"Releases",
"callback",
"from",
"key",
"changes"
] | 80a868242ee9cdc6f4ded594b3e0544cc238ed55 | https://github.com/eumis/pyviews/blob/80a868242ee9cdc6f4ded594b3e0544cc238ed55/pyviews/core/observable.py#L30-L35 | train | 50,218 |
eumis/pyviews | pyviews/core/observable.py | InheritedDict.inherit | def inherit(self, parent):
"""Inherit passed dictionary"""
if self._parent == parent:
return
if self._parent:
self._parent.release_all(self._parent_changed)
self_values = {key: self._container[key] for key in self._own_keys}
self._container = {**parent.to_dictionary(), **self_values}
self._parent = parent
self._parent.observe_all(self._parent_changed) | python | def inherit(self, parent):
"""Inherit passed dictionary"""
if self._parent == parent:
return
if self._parent:
self._parent.release_all(self._parent_changed)
self_values = {key: self._container[key] for key in self._own_keys}
self._container = {**parent.to_dictionary(), **self_values}
self._parent = parent
self._parent.observe_all(self._parent_changed) | [
"def",
"inherit",
"(",
"self",
",",
"parent",
")",
":",
"if",
"self",
".",
"_parent",
"==",
"parent",
":",
"return",
"if",
"self",
".",
"_parent",
":",
"self",
".",
"_parent",
".",
"release_all",
"(",
"self",
".",
"_parent_changed",
")",
"self_values",
... | Inherit passed dictionary | [
"Inherit",
"passed",
"dictionary"
] | 80a868242ee9cdc6f4ded594b3e0544cc238ed55 | https://github.com/eumis/pyviews/blob/80a868242ee9cdc6f4ded594b3e0544cc238ed55/pyviews/core/observable.py#L99-L108 | train | 50,219 |
eumis/pyviews | pyviews/core/observable.py | InheritedDict.observe_all | def observe_all(self, callback: Callable[[str, Any, Any], None]):
"""Subscribes to all keys changes"""
self._all_callbacks.append(callback) | python | def observe_all(self, callback: Callable[[str, Any, Any], None]):
"""Subscribes to all keys changes"""
self._all_callbacks.append(callback) | [
"def",
"observe_all",
"(",
"self",
",",
"callback",
":",
"Callable",
"[",
"[",
"str",
",",
"Any",
",",
"Any",
"]",
",",
"None",
"]",
")",
":",
"self",
".",
"_all_callbacks",
".",
"append",
"(",
"callback",
")"
] | Subscribes to all keys changes | [
"Subscribes",
"to",
"all",
"keys",
"changes"
] | 80a868242ee9cdc6f4ded594b3e0544cc238ed55 | https://github.com/eumis/pyviews/blob/80a868242ee9cdc6f4ded594b3e0544cc238ed55/pyviews/core/observable.py#L110-L112 | train | 50,220 |
eumis/pyviews | pyviews/core/observable.py | InheritedDict.release_all | def release_all(self, callback: Callable[[str, Any, Any], None]):
"""Releases callback from all keys changes"""
self._all_callbacks.remove(callback) | python | def release_all(self, callback: Callable[[str, Any, Any], None]):
"""Releases callback from all keys changes"""
self._all_callbacks.remove(callback) | [
"def",
"release_all",
"(",
"self",
",",
"callback",
":",
"Callable",
"[",
"[",
"str",
",",
"Any",
",",
"Any",
"]",
",",
"None",
"]",
")",
":",
"self",
".",
"_all_callbacks",
".",
"remove",
"(",
"callback",
")"
] | Releases callback from all keys changes | [
"Releases",
"callback",
"from",
"all",
"keys",
"changes"
] | 80a868242ee9cdc6f4ded594b3e0544cc238ed55 | https://github.com/eumis/pyviews/blob/80a868242ee9cdc6f4ded594b3e0544cc238ed55/pyviews/core/observable.py#L124-L126 | train | 50,221 |
eumis/pyviews | pyviews/core/observable.py | InheritedDict.remove_key | def remove_key(self, key):
"""Remove own key, value"""
try:
self._own_keys.discard(key)
if self._parent and self._parent.has_key(key):
self._container[key] = self._parent[key]
else:
del self._container[key]
except KeyError:
pass | python | def remove_key(self, key):
"""Remove own key, value"""
try:
self._own_keys.discard(key)
if self._parent and self._parent.has_key(key):
self._container[key] = self._parent[key]
else:
del self._container[key]
except KeyError:
pass | [
"def",
"remove_key",
"(",
"self",
",",
"key",
")",
":",
"try",
":",
"self",
".",
"_own_keys",
".",
"discard",
"(",
"key",
")",
"if",
"self",
".",
"_parent",
"and",
"self",
".",
"_parent",
".",
"has_key",
"(",
"key",
")",
":",
"self",
".",
"_contain... | Remove own key, value | [
"Remove",
"own",
"key",
"value"
] | 80a868242ee9cdc6f4ded594b3e0544cc238ed55 | https://github.com/eumis/pyviews/blob/80a868242ee9cdc6f4ded594b3e0544cc238ed55/pyviews/core/observable.py#L136-L145 | train | 50,222 |
eumis/pyviews | pyviews/core/binding.py | Binder.add_rule | def add_rule(self, binding_type: str, rule: BindingRule):
"""Adds new rule"""
if binding_type not in self._rules:
self._rules[binding_type] = []
self._rules[binding_type].insert(0, rule) | python | def add_rule(self, binding_type: str, rule: BindingRule):
"""Adds new rule"""
if binding_type not in self._rules:
self._rules[binding_type] = []
self._rules[binding_type].insert(0, rule) | [
"def",
"add_rule",
"(",
"self",
",",
"binding_type",
":",
"str",
",",
"rule",
":",
"BindingRule",
")",
":",
"if",
"binding_type",
"not",
"in",
"self",
".",
"_rules",
":",
"self",
".",
"_rules",
"[",
"binding_type",
"]",
"=",
"[",
"]",
"self",
".",
"_... | Adds new rule | [
"Adds",
"new",
"rule"
] | 80a868242ee9cdc6f4ded594b3e0544cc238ed55 | https://github.com/eumis/pyviews/blob/80a868242ee9cdc6f4ded594b3e0544cc238ed55/pyviews/core/binding.py#L53-L58 | train | 50,223 |
eumis/pyviews | pyviews/core/binding.py | Binder.find_rule | def find_rule(self, binding_type: str, **args):
"""Finds rule by binding type and args"""
try:
rules = self._rules[binding_type]
return next(rule for rule in rules if rule.suitable(**args))
except (KeyError, StopIteration):
return None | python | def find_rule(self, binding_type: str, **args):
"""Finds rule by binding type and args"""
try:
rules = self._rules[binding_type]
return next(rule for rule in rules if rule.suitable(**args))
except (KeyError, StopIteration):
return None | [
"def",
"find_rule",
"(",
"self",
",",
"binding_type",
":",
"str",
",",
"*",
"*",
"args",
")",
":",
"try",
":",
"rules",
"=",
"self",
".",
"_rules",
"[",
"binding_type",
"]",
"return",
"next",
"(",
"rule",
"for",
"rule",
"in",
"rules",
"if",
"rule",
... | Finds rule by binding type and args | [
"Finds",
"rule",
"by",
"binding",
"type",
"and",
"args"
] | 80a868242ee9cdc6f4ded594b3e0544cc238ed55 | https://github.com/eumis/pyviews/blob/80a868242ee9cdc6f4ded594b3e0544cc238ed55/pyviews/core/binding.py#L60-L66 | train | 50,224 |
eumis/pyviews | pyviews/core/binding.py | Binder.apply | def apply(self, binding_type, **args):
"""Returns apply function"""
rule = self.find_rule(binding_type, **args)
if rule is None:
error = BindingError('Binding rule is not found')
error.add_info('Binding type', binding_type)
error.add_info('args', args)
raise error
binding = rule.apply(**args)
if binding:
args['node'].add_binding(rule.apply(**args)) | python | def apply(self, binding_type, **args):
"""Returns apply function"""
rule = self.find_rule(binding_type, **args)
if rule is None:
error = BindingError('Binding rule is not found')
error.add_info('Binding type', binding_type)
error.add_info('args', args)
raise error
binding = rule.apply(**args)
if binding:
args['node'].add_binding(rule.apply(**args)) | [
"def",
"apply",
"(",
"self",
",",
"binding_type",
",",
"*",
"*",
"args",
")",
":",
"rule",
"=",
"self",
".",
"find_rule",
"(",
"binding_type",
",",
"*",
"*",
"args",
")",
"if",
"rule",
"is",
"None",
":",
"error",
"=",
"BindingError",
"(",
"'Binding r... | Returns apply function | [
"Returns",
"apply",
"function"
] | 80a868242ee9cdc6f4ded594b3e0544cc238ed55 | https://github.com/eumis/pyviews/blob/80a868242ee9cdc6f4ded594b3e0544cc238ed55/pyviews/core/binding.py#L68-L78 | train | 50,225 |
eumis/pyviews | pyviews/binding/implementations.py | get_expression_target | def get_expression_target(expression: Expression, expr_vars: InheritedDict) -> BindingTarget:
'''Factory method to create expression target'''
root = expression.get_object_tree()
if len(root.children) != 1 or not PROPERTY_EXPRESSION_REGEX.fullmatch(expression.code):
error = BindingError('Expression should be property expression')
error.add_info('Expression', expression.code)
raise error
if root.children[0].children:
return PropertyExpressionTarget(expression, expr_vars)
return GlobalValueExpressionTarget(expression, expr_vars) | python | def get_expression_target(expression: Expression, expr_vars: InheritedDict) -> BindingTarget:
'''Factory method to create expression target'''
root = expression.get_object_tree()
if len(root.children) != 1 or not PROPERTY_EXPRESSION_REGEX.fullmatch(expression.code):
error = BindingError('Expression should be property expression')
error.add_info('Expression', expression.code)
raise error
if root.children[0].children:
return PropertyExpressionTarget(expression, expr_vars)
return GlobalValueExpressionTarget(expression, expr_vars) | [
"def",
"get_expression_target",
"(",
"expression",
":",
"Expression",
",",
"expr_vars",
":",
"InheritedDict",
")",
"->",
"BindingTarget",
":",
"root",
"=",
"expression",
".",
"get_object_tree",
"(",
")",
"if",
"len",
"(",
"root",
".",
"children",
")",
"!=",
... | Factory method to create expression target | [
"Factory",
"method",
"to",
"create",
"expression",
"target"
] | 80a868242ee9cdc6f4ded594b3e0544cc238ed55 | https://github.com/eumis/pyviews/blob/80a868242ee9cdc6f4ded594b3e0544cc238ed55/pyviews/binding/implementations.py#L219-L228 | train | 50,226 |
eumis/pyviews | pyviews/binding/implementations.py | PropertyTarget.on_change | def on_change(self, value):
'''Calles modifier on instance with passed value'''
self._modifier(self.inst, self.prop, value) | python | def on_change(self, value):
'''Calles modifier on instance with passed value'''
self._modifier(self.inst, self.prop, value) | [
"def",
"on_change",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_modifier",
"(",
"self",
".",
"inst",
",",
"self",
".",
"prop",
",",
"value",
")"
] | Calles modifier on instance with passed value | [
"Calles",
"modifier",
"on",
"instance",
"with",
"passed",
"value"
] | 80a868242ee9cdc6f4ded594b3e0544cc238ed55 | https://github.com/eumis/pyviews/blob/80a868242ee9cdc6f4ded594b3e0544cc238ed55/pyviews/binding/implementations.py#L18-L20 | train | 50,227 |
eumis/pyviews | pyviews/binding/implementations.py | Dependency.destroy | def destroy(self):
'''Unsubscribes callback from observable'''
self._observable.release(self._key, self._callback)
self._observable = None
self._key = None
self._callback = None | python | def destroy(self):
'''Unsubscribes callback from observable'''
self._observable.release(self._key, self._callback)
self._observable = None
self._key = None
self._callback = None | [
"def",
"destroy",
"(",
"self",
")",
":",
"self",
".",
"_observable",
".",
"release",
"(",
"self",
".",
"_key",
",",
"self",
".",
"_callback",
")",
"self",
".",
"_observable",
"=",
"None",
"self",
".",
"_key",
"=",
"None",
"self",
".",
"_callback",
"=... | Unsubscribes callback from observable | [
"Unsubscribes",
"callback",
"from",
"observable"
] | 80a868242ee9cdc6f4ded594b3e0544cc238ed55 | https://github.com/eumis/pyviews/blob/80a868242ee9cdc6f4ded594b3e0544cc238ed55/pyviews/binding/implementations.py#L37-L42 | train | 50,228 |
Workiva/furious | example/runner.py | args | def args():
"""Add and parse the arguments for the script.
url: the url of the example to run
gae-sdk-path: this allows a user to point the script to their GAE SDK
if it's not in /usr/local/google_appengine.
"""
parser = argparse.ArgumentParser(description='Run the Furious Examples.')
parser.add_argument('--gae-sdk-path', metavar='S', dest="gae_lib_path",
default="/usr/local/google_appengine",
help='path to the GAE SDK')
parser.add_argument('url', metavar='U', default="", nargs=1,
help="the endpoint to run")
return parser.parse_args() | python | def args():
"""Add and parse the arguments for the script.
url: the url of the example to run
gae-sdk-path: this allows a user to point the script to their GAE SDK
if it's not in /usr/local/google_appengine.
"""
parser = argparse.ArgumentParser(description='Run the Furious Examples.')
parser.add_argument('--gae-sdk-path', metavar='S', dest="gae_lib_path",
default="/usr/local/google_appengine",
help='path to the GAE SDK')
parser.add_argument('url', metavar='U', default="", nargs=1,
help="the endpoint to run")
return parser.parse_args() | [
"def",
"args",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Run the Furious Examples.'",
")",
"parser",
".",
"add_argument",
"(",
"'--gae-sdk-path'",
",",
"metavar",
"=",
"'S'",
",",
"dest",
"=",
"\"gae_lib_path\"",... | Add and parse the arguments for the script.
url: the url of the example to run
gae-sdk-path: this allows a user to point the script to their GAE SDK
if it's not in /usr/local/google_appengine. | [
"Add",
"and",
"parse",
"the",
"arguments",
"for",
"the",
"script",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/example/runner.py#L17-L33 | train | 50,229 |
Workiva/furious | example/runner.py | setup | def setup(options):
"""Grabs the gae_lib_path from the options and inserts it into the first
index of the sys.path. Then calls GAE's fix_sys_path to get all the proper
GAE paths included.
:param options:
"""
sys.path.insert(0, options.gae_lib_path)
from dev_appserver import fix_sys_path
fix_sys_path() | python | def setup(options):
"""Grabs the gae_lib_path from the options and inserts it into the first
index of the sys.path. Then calls GAE's fix_sys_path to get all the proper
GAE paths included.
:param options:
"""
sys.path.insert(0, options.gae_lib_path)
from dev_appserver import fix_sys_path
fix_sys_path() | [
"def",
"setup",
"(",
"options",
")",
":",
"sys",
".",
"path",
".",
"insert",
"(",
"0",
",",
"options",
".",
"gae_lib_path",
")",
"from",
"dev_appserver",
"import",
"fix_sys_path",
"fix_sys_path",
"(",
")"
] | Grabs the gae_lib_path from the options and inserts it into the first
index of the sys.path. Then calls GAE's fix_sys_path to get all the proper
GAE paths included.
:param options: | [
"Grabs",
"the",
"gae_lib_path",
"from",
"the",
"options",
"and",
"inserts",
"it",
"into",
"the",
"first",
"index",
"of",
"the",
"sys",
".",
"path",
".",
"Then",
"calls",
"GAE",
"s",
"fix_sys_path",
"to",
"get",
"all",
"the",
"proper",
"GAE",
"paths",
"in... | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/example/runner.py#L36-L46 | train | 50,230 |
Workiva/furious | example/runner.py | run | def run(options):
"""Run the passed in url of the example using GAE's rpc runner.
Uses appengine_rpc.HttpRpcServer to send a request to the url passed in
via the options.
:param options:
"""
from google.appengine.tools import appengine_rpc
from google.appengine.tools import appcfg
source = 'furious'
# use the same user agent that GAE uses in appcfg
user_agent = appcfg.GetUserAgent()
# Since we're only using the dev server for now we can hard code these
# values. This will need to change and accept these values as variables
# when this is wired up to hit appspots.
server = appengine_rpc.HttpRpcServer(
'localhost:8080', lambda: ('test@example.com', 'password'), user_agent,
source, secure=False)
# if no url is passed in just use the top level.
url = "/"
if options.url:
url += options.url[0]
# use the dev server authentication for now.
server._DevAppServerAuthenticate()
# send a simple GET request to the url
server.Send(url, content_type="text/html; charset=utf-8",
payload=None) | python | def run(options):
"""Run the passed in url of the example using GAE's rpc runner.
Uses appengine_rpc.HttpRpcServer to send a request to the url passed in
via the options.
:param options:
"""
from google.appengine.tools import appengine_rpc
from google.appengine.tools import appcfg
source = 'furious'
# use the same user agent that GAE uses in appcfg
user_agent = appcfg.GetUserAgent()
# Since we're only using the dev server for now we can hard code these
# values. This will need to change and accept these values as variables
# when this is wired up to hit appspots.
server = appengine_rpc.HttpRpcServer(
'localhost:8080', lambda: ('test@example.com', 'password'), user_agent,
source, secure=False)
# if no url is passed in just use the top level.
url = "/"
if options.url:
url += options.url[0]
# use the dev server authentication for now.
server._DevAppServerAuthenticate()
# send a simple GET request to the url
server.Send(url, content_type="text/html; charset=utf-8",
payload=None) | [
"def",
"run",
"(",
"options",
")",
":",
"from",
"google",
".",
"appengine",
".",
"tools",
"import",
"appengine_rpc",
"from",
"google",
".",
"appengine",
".",
"tools",
"import",
"appcfg",
"source",
"=",
"'furious'",
"# use the same user agent that GAE uses in appcfg"... | Run the passed in url of the example using GAE's rpc runner.
Uses appengine_rpc.HttpRpcServer to send a request to the url passed in
via the options.
:param options: | [
"Run",
"the",
"passed",
"in",
"url",
"of",
"the",
"example",
"using",
"GAE",
"s",
"rpc",
"runner",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/example/runner.py#L49-L82 | train | 50,231 |
horejsek/python-sqlpuzzle | sqlpuzzle/_queries/query.py | Query.has | def has(self, querypart_name, value=None):
"""Returns True if `querypart_name` with `value` is set.
For example you can check if you already used condition by `sql.has('where')`.
If you want to check for more information, for example if that condition
also contain ID, you can do this by `sql.has('where', 'id')`.
"""
querypart = self._queryparts.get(querypart_name)
if not querypart:
return False
if not querypart.is_set:
return False
if value:
return querypart.has(value)
return True | python | def has(self, querypart_name, value=None):
"""Returns True if `querypart_name` with `value` is set.
For example you can check if you already used condition by `sql.has('where')`.
If you want to check for more information, for example if that condition
also contain ID, you can do this by `sql.has('where', 'id')`.
"""
querypart = self._queryparts.get(querypart_name)
if not querypart:
return False
if not querypart.is_set:
return False
if value:
return querypart.has(value)
return True | [
"def",
"has",
"(",
"self",
",",
"querypart_name",
",",
"value",
"=",
"None",
")",
":",
"querypart",
"=",
"self",
".",
"_queryparts",
".",
"get",
"(",
"querypart_name",
")",
"if",
"not",
"querypart",
":",
"return",
"False",
"if",
"not",
"querypart",
".",
... | Returns True if `querypart_name` with `value` is set.
For example you can check if you already used condition by `sql.has('where')`.
If you want to check for more information, for example if that condition
also contain ID, you can do this by `sql.has('where', 'id')`. | [
"Returns",
"True",
"if",
"querypart_name",
"with",
"value",
"is",
"set",
"."
] | d3a42ed1b339b8eafddb8d2c28a3a5832b3998dd | https://github.com/horejsek/python-sqlpuzzle/blob/d3a42ed1b339b8eafddb8d2c28a3a5832b3998dd/sqlpuzzle/_queries/query.py#L46-L61 | train | 50,232 |
eumis/pyviews | pyviews/compilation/expression.py | CompiledExpression.execute | def execute(self, parameters: dict = None):
"""Executes expression with passed parameters and returns result"""
try:
parameters = {} if parameters is None else parameters
return eval(self._compiled_code, parameters, {})
except:
info = exc_info()
error = CompilationError('Error occurred in expression execution', self.code)
error.add_cause(info[1])
raise error from info[1] | python | def execute(self, parameters: dict = None):
"""Executes expression with passed parameters and returns result"""
try:
parameters = {} if parameters is None else parameters
return eval(self._compiled_code, parameters, {})
except:
info = exc_info()
error = CompilationError('Error occurred in expression execution', self.code)
error.add_cause(info[1])
raise error from info[1] | [
"def",
"execute",
"(",
"self",
",",
"parameters",
":",
"dict",
"=",
"None",
")",
":",
"try",
":",
"parameters",
"=",
"{",
"}",
"if",
"parameters",
"is",
"None",
"else",
"parameters",
"return",
"eval",
"(",
"self",
".",
"_compiled_code",
",",
"parameters"... | Executes expression with passed parameters and returns result | [
"Executes",
"expression",
"with",
"passed",
"parameters",
"and",
"returns",
"result"
] | 80a868242ee9cdc6f4ded594b3e0544cc238ed55 | https://github.com/eumis/pyviews/blob/80a868242ee9cdc6f4ded594b3e0544cc238ed55/pyviews/compilation/expression.py#L88-L97 | train | 50,233 |
Workiva/furious | example/abort_and_restart.py | aborting_function | def aborting_function():
"""There is a 50% chance that this function will AbortAndRestart or
complete successfully.
The 50% chance simply represents a process that will fail half the time
and succeed half the time.
"""
import random
logging.info('In aborting_function')
if random.random() < .5:
from furious.errors import AbortAndRestart
logging.info('Getting ready to restart')
# Raise AbortAndRestart like an Exception, and watch the magic happen.
raise AbortAndRestart()
logging.info('No longer restarting') | python | def aborting_function():
"""There is a 50% chance that this function will AbortAndRestart or
complete successfully.
The 50% chance simply represents a process that will fail half the time
and succeed half the time.
"""
import random
logging.info('In aborting_function')
if random.random() < .5:
from furious.errors import AbortAndRestart
logging.info('Getting ready to restart')
# Raise AbortAndRestart like an Exception, and watch the magic happen.
raise AbortAndRestart()
logging.info('No longer restarting') | [
"def",
"aborting_function",
"(",
")",
":",
"import",
"random",
"logging",
".",
"info",
"(",
"'In aborting_function'",
")",
"if",
"random",
".",
"random",
"(",
")",
"<",
".5",
":",
"from",
"furious",
".",
"errors",
"import",
"AbortAndRestart",
"logging",
".",... | There is a 50% chance that this function will AbortAndRestart or
complete successfully.
The 50% chance simply represents a process that will fail half the time
and succeed half the time. | [
"There",
"is",
"a",
"50%",
"chance",
"that",
"this",
"function",
"will",
"AbortAndRestart",
"or",
"complete",
"successfully",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/example/abort_and_restart.py#L41-L60 | train | 50,234 |
datacamp/shellwhat | shellwhat/checks/check_funcs.py | strip_ansi | def strip_ansi(state):
"""Remove ANSI escape codes from student result."""
stu_res = _strip_ansi(state.student_result)
return state.to_child(student_result = stu_res) | python | def strip_ansi(state):
"""Remove ANSI escape codes from student result."""
stu_res = _strip_ansi(state.student_result)
return state.to_child(student_result = stu_res) | [
"def",
"strip_ansi",
"(",
"state",
")",
":",
"stu_res",
"=",
"_strip_ansi",
"(",
"state",
".",
"student_result",
")",
"return",
"state",
".",
"to_child",
"(",
"student_result",
"=",
"stu_res",
")"
] | Remove ANSI escape codes from student result. | [
"Remove",
"ANSI",
"escape",
"codes",
"from",
"student",
"result",
"."
] | ee2f875e3db0eb06d69cc946c8e9700e0edceea2 | https://github.com/datacamp/shellwhat/blob/ee2f875e3db0eb06d69cc946c8e9700e0edceea2/shellwhat/checks/check_funcs.py#L9-L13 | train | 50,235 |
datacamp/shellwhat | shellwhat/checks/check_funcs.py | has_code | def has_code(state, text, incorrect_msg="The checker expected to find `{{text}}` in your command.", fixed=False):
"""Check whether the student code contains text.
This function is a simpler override of the `has_code` function in protowhat,
because ``ast_node._get_text()`` is not implemented in the OSH parser
Using ``has_code()`` should be a last resort. It is always better to look at the result of code
or the side effects they had on the state of your program.
Args:
state: State instance describing student and solution code. Can be omitted if used with Ex().
text : text that student code must contain. Can be a regex pattern or a simple string.
incorrect_msg: if specified, this overrides the automatically generated feedback message
in case ``text`` is not found in the student code.
fixed: whether to match ``text`` exactly, rather than using regular expressions.
:Example:
Suppose the solution requires you to do: ::
git push origin master
The following SCT can be written: ::
Ex().has_code(r'git\\s+push\\s+origin\\s+master')
Submissions that would pass: ::
git push origin master
git push origin master
Submissions that would fail: ::
git push --force origin master
"""
stu_code = state.student_code
# either simple text matching or regex test
res = text in stu_code if fixed else re.search(text, stu_code)
if not res:
_msg = state.build_message(incorrect_msg, fmt_kwargs={ 'text': text })
state.do_test(_msg)
return state | python | def has_code(state, text, incorrect_msg="The checker expected to find `{{text}}` in your command.", fixed=False):
"""Check whether the student code contains text.
This function is a simpler override of the `has_code` function in protowhat,
because ``ast_node._get_text()`` is not implemented in the OSH parser
Using ``has_code()`` should be a last resort. It is always better to look at the result of code
or the side effects they had on the state of your program.
Args:
state: State instance describing student and solution code. Can be omitted if used with Ex().
text : text that student code must contain. Can be a regex pattern or a simple string.
incorrect_msg: if specified, this overrides the automatically generated feedback message
in case ``text`` is not found in the student code.
fixed: whether to match ``text`` exactly, rather than using regular expressions.
:Example:
Suppose the solution requires you to do: ::
git push origin master
The following SCT can be written: ::
Ex().has_code(r'git\\s+push\\s+origin\\s+master')
Submissions that would pass: ::
git push origin master
git push origin master
Submissions that would fail: ::
git push --force origin master
"""
stu_code = state.student_code
# either simple text matching or regex test
res = text in stu_code if fixed else re.search(text, stu_code)
if not res:
_msg = state.build_message(incorrect_msg, fmt_kwargs={ 'text': text })
state.do_test(_msg)
return state | [
"def",
"has_code",
"(",
"state",
",",
"text",
",",
"incorrect_msg",
"=",
"\"The checker expected to find `{{text}}` in your command.\"",
",",
"fixed",
"=",
"False",
")",
":",
"stu_code",
"=",
"state",
".",
"student_code",
"# either simple text matching or regex test",
"re... | Check whether the student code contains text.
This function is a simpler override of the `has_code` function in protowhat,
because ``ast_node._get_text()`` is not implemented in the OSH parser
Using ``has_code()`` should be a last resort. It is always better to look at the result of code
or the side effects they had on the state of your program.
Args:
state: State instance describing student and solution code. Can be omitted if used with Ex().
text : text that student code must contain. Can be a regex pattern or a simple string.
incorrect_msg: if specified, this overrides the automatically generated feedback message
in case ``text`` is not found in the student code.
fixed: whether to match ``text`` exactly, rather than using regular expressions.
:Example:
Suppose the solution requires you to do: ::
git push origin master
The following SCT can be written: ::
Ex().has_code(r'git\\s+push\\s+origin\\s+master')
Submissions that would pass: ::
git push origin master
git push origin master
Submissions that would fail: ::
git push --force origin master | [
"Check",
"whether",
"the",
"student",
"code",
"contains",
"text",
"."
] | ee2f875e3db0eb06d69cc946c8e9700e0edceea2 | https://github.com/datacamp/shellwhat/blob/ee2f875e3db0eb06d69cc946c8e9700e0edceea2/shellwhat/checks/check_funcs.py#L15-L60 | train | 50,236 |
datacamp/shellwhat | shellwhat/checks/check_funcs.py | has_output | def has_output(state,
text,
incorrect_msg="The checker expected to find {{'' if fixed else 'the pattern '}}`{{text}}` in the output of your command.",
fixed=False,
strip_ansi=True):
"""Check whether student output contains specific text.
Before you use ``has_output()``, have a look at ``has_expr_output()`` or ``has_expr_error()``;
they might be more fit for your use case.
Args:
state: State instance describing student and solution code. Can be omitted if used with ``Ex()``.
text : text that student output must contain. Can be a regex pattern or a simple string.
incorrect_msg: if specified, this overrides the automatically generated feedback message
in case ``text`` is not found in the student output.
fixed: whether to match ``text`` exactly, rather than using regular expressions.
strip_ansi: whether to remove ANSI escape codes from output
:Example:
Suppose the solution requires you to do: ::
echo 'this is a printout!'
The following SCT can be written: ::
Ex().has_output(r'this\\s+is\\s+a\\s+print\\s*out')
Submissions that would pass: ::
echo 'this is a print out'
test='this is a printout!' && echo $test
Submissions that would fail: ::
echo 'this is a wrong printout'
"""
stu_output = state.student_result
if strip_ansi: stu_output = _strip_ansi(stu_output)
# either simple text matching or regex test
res = text in stu_output if fixed else re.search(text, stu_output)
if not res:
_msg = state.build_message(incorrect_msg, fmt_kwargs={ 'text': text, 'fixed': fixed })
state.do_test(_msg)
return state | python | def has_output(state,
text,
incorrect_msg="The checker expected to find {{'' if fixed else 'the pattern '}}`{{text}}` in the output of your command.",
fixed=False,
strip_ansi=True):
"""Check whether student output contains specific text.
Before you use ``has_output()``, have a look at ``has_expr_output()`` or ``has_expr_error()``;
they might be more fit for your use case.
Args:
state: State instance describing student and solution code. Can be omitted if used with ``Ex()``.
text : text that student output must contain. Can be a regex pattern or a simple string.
incorrect_msg: if specified, this overrides the automatically generated feedback message
in case ``text`` is not found in the student output.
fixed: whether to match ``text`` exactly, rather than using regular expressions.
strip_ansi: whether to remove ANSI escape codes from output
:Example:
Suppose the solution requires you to do: ::
echo 'this is a printout!'
The following SCT can be written: ::
Ex().has_output(r'this\\s+is\\s+a\\s+print\\s*out')
Submissions that would pass: ::
echo 'this is a print out'
test='this is a printout!' && echo $test
Submissions that would fail: ::
echo 'this is a wrong printout'
"""
stu_output = state.student_result
if strip_ansi: stu_output = _strip_ansi(stu_output)
# either simple text matching or regex test
res = text in stu_output if fixed else re.search(text, stu_output)
if not res:
_msg = state.build_message(incorrect_msg, fmt_kwargs={ 'text': text, 'fixed': fixed })
state.do_test(_msg)
return state | [
"def",
"has_output",
"(",
"state",
",",
"text",
",",
"incorrect_msg",
"=",
"\"The checker expected to find {{'' if fixed else 'the pattern '}}`{{text}}` in the output of your command.\"",
",",
"fixed",
"=",
"False",
",",
"strip_ansi",
"=",
"True",
")",
":",
"stu_output",
"=... | Check whether student output contains specific text.
Before you use ``has_output()``, have a look at ``has_expr_output()`` or ``has_expr_error()``;
they might be more fit for your use case.
Args:
state: State instance describing student and solution code. Can be omitted if used with ``Ex()``.
text : text that student output must contain. Can be a regex pattern or a simple string.
incorrect_msg: if specified, this overrides the automatically generated feedback message
in case ``text`` is not found in the student output.
fixed: whether to match ``text`` exactly, rather than using regular expressions.
strip_ansi: whether to remove ANSI escape codes from output
:Example:
Suppose the solution requires you to do: ::
echo 'this is a printout!'
The following SCT can be written: ::
Ex().has_output(r'this\\s+is\\s+a\\s+print\\s*out')
Submissions that would pass: ::
echo 'this is a print out'
test='this is a printout!' && echo $test
Submissions that would fail: ::
echo 'this is a wrong printout' | [
"Check",
"whether",
"student",
"output",
"contains",
"specific",
"text",
"."
] | ee2f875e3db0eb06d69cc946c8e9700e0edceea2 | https://github.com/datacamp/shellwhat/blob/ee2f875e3db0eb06d69cc946c8e9700e0edceea2/shellwhat/checks/check_funcs.py#L62-L111 | train | 50,237 |
datacamp/shellwhat | shellwhat/checks/check_funcs.py | has_cwd | def has_cwd(state, dir, incorrect_msg="Your current working directory should be `{{dir}}`. Use `cd {{dir}}` to navigate there."):
"""Check whether the student is in the expected directory.
This check is typically used before using ``has_expr_output()``
to make sure the student didn't navigate somewhere else.
Args:
state: State instance describing student and solution code. Can be omitted if used with ``Ex()``.
dir: Directory that the student should be in. Always use the absolute path.
incorrect_msg: If specified, this overrides the automatically generated message in
case the student is not in the expected directory.
:Example:
If you want to be sure that the student is in ``/home/repl/my_dir``: ::
Ex().has_cwd('/home/repl/my_dir')
"""
expr = "[[ $PWD == '{}' ]]".format(dir)
_msg = state.build_message(incorrect_msg, fmt_kwargs={ 'dir': dir })
has_expr_exit_code(state, expr, output="0", incorrect_msg=_msg)
return state | python | def has_cwd(state, dir, incorrect_msg="Your current working directory should be `{{dir}}`. Use `cd {{dir}}` to navigate there."):
"""Check whether the student is in the expected directory.
This check is typically used before using ``has_expr_output()``
to make sure the student didn't navigate somewhere else.
Args:
state: State instance describing student and solution code. Can be omitted if used with ``Ex()``.
dir: Directory that the student should be in. Always use the absolute path.
incorrect_msg: If specified, this overrides the automatically generated message in
case the student is not in the expected directory.
:Example:
If you want to be sure that the student is in ``/home/repl/my_dir``: ::
Ex().has_cwd('/home/repl/my_dir')
"""
expr = "[[ $PWD == '{}' ]]".format(dir)
_msg = state.build_message(incorrect_msg, fmt_kwargs={ 'dir': dir })
has_expr_exit_code(state, expr, output="0", incorrect_msg=_msg)
return state | [
"def",
"has_cwd",
"(",
"state",
",",
"dir",
",",
"incorrect_msg",
"=",
"\"Your current working directory should be `{{dir}}`. Use `cd {{dir}}` to navigate there.\"",
")",
":",
"expr",
"=",
"\"[[ $PWD == '{}' ]]\"",
".",
"format",
"(",
"dir",
")",
"_msg",
"=",
"state",
"... | Check whether the student is in the expected directory.
This check is typically used before using ``has_expr_output()``
to make sure the student didn't navigate somewhere else.
Args:
state: State instance describing student and solution code. Can be omitted if used with ``Ex()``.
dir: Directory that the student should be in. Always use the absolute path.
incorrect_msg: If specified, this overrides the automatically generated message in
case the student is not in the expected directory.
:Example:
If you want to be sure that the student is in ``/home/repl/my_dir``: ::
Ex().has_cwd('/home/repl/my_dir') | [
"Check",
"whether",
"the",
"student",
"is",
"in",
"the",
"expected",
"directory",
"."
] | ee2f875e3db0eb06d69cc946c8e9700e0edceea2 | https://github.com/datacamp/shellwhat/blob/ee2f875e3db0eb06d69cc946c8e9700e0edceea2/shellwhat/checks/check_funcs.py#L113-L135 | train | 50,238 |
internetarchive/doublethink | doublethink/services.py | ServiceRegistry.heartbeat | def heartbeat(self, status_info):
'''
Update service status, indicating "up"-ness.
Args:
status_info (dict): a dictionary representing the status of the
service
`status_info` must have at least the fields 'role', 'load', and
'ttl'. Some additional fields are populated automatically by this
method. If the field 'id' is absent, it will be generated by rethinkdb.
See the ServiceRegistry class-level documentation for more information
about the various fields.
Returns:
On success, returns the modified status info dict. On failure
communicating with rethinkdb, returns `status_info` unmodified.
Raises:
Exception: if `status_info` is missing a required field, or a
`status_info['ttl']` is not a number greater than zero
'''
for field in 'role', 'ttl', 'load':
if not field in status_info:
raise Exception(
'status_info is missing required field %s',
repr(field))
val = status_info['ttl']
if not (isinstance(val, float) or isinstance(val, int)) or val <= 0:
raise Exception('ttl must be a number > 0')
updated_status_info = dict(status_info)
updated_status_info['last_heartbeat'] = r.now()
if not 'first_heartbeat' in updated_status_info:
updated_status_info['first_heartbeat'] = updated_status_info['last_heartbeat']
if not 'host' in updated_status_info:
updated_status_info['host'] = socket.gethostname()
if not 'pid' in updated_status_info:
updated_status_info['pid'] = os.getpid()
try:
result = self.rr.table(self.table).insert(
updated_status_info, conflict='replace',
return_changes=True).run()
return result['changes'][0]['new_val'] # XXX check
except:
self.logger.error('error updating service registry', exc_info=True)
return status_info | python | def heartbeat(self, status_info):
'''
Update service status, indicating "up"-ness.
Args:
status_info (dict): a dictionary representing the status of the
service
`status_info` must have at least the fields 'role', 'load', and
'ttl'. Some additional fields are populated automatically by this
method. If the field 'id' is absent, it will be generated by rethinkdb.
See the ServiceRegistry class-level documentation for more information
about the various fields.
Returns:
On success, returns the modified status info dict. On failure
communicating with rethinkdb, returns `status_info` unmodified.
Raises:
Exception: if `status_info` is missing a required field, or a
`status_info['ttl']` is not a number greater than zero
'''
for field in 'role', 'ttl', 'load':
if not field in status_info:
raise Exception(
'status_info is missing required field %s',
repr(field))
val = status_info['ttl']
if not (isinstance(val, float) or isinstance(val, int)) or val <= 0:
raise Exception('ttl must be a number > 0')
updated_status_info = dict(status_info)
updated_status_info['last_heartbeat'] = r.now()
if not 'first_heartbeat' in updated_status_info:
updated_status_info['first_heartbeat'] = updated_status_info['last_heartbeat']
if not 'host' in updated_status_info:
updated_status_info['host'] = socket.gethostname()
if not 'pid' in updated_status_info:
updated_status_info['pid'] = os.getpid()
try:
result = self.rr.table(self.table).insert(
updated_status_info, conflict='replace',
return_changes=True).run()
return result['changes'][0]['new_val'] # XXX check
except:
self.logger.error('error updating service registry', exc_info=True)
return status_info | [
"def",
"heartbeat",
"(",
"self",
",",
"status_info",
")",
":",
"for",
"field",
"in",
"'role'",
",",
"'ttl'",
",",
"'load'",
":",
"if",
"not",
"field",
"in",
"status_info",
":",
"raise",
"Exception",
"(",
"'status_info is missing required field %s'",
",",
"repr... | Update service status, indicating "up"-ness.
Args:
status_info (dict): a dictionary representing the status of the
service
`status_info` must have at least the fields 'role', 'load', and
'ttl'. Some additional fields are populated automatically by this
method. If the field 'id' is absent, it will be generated by rethinkdb.
See the ServiceRegistry class-level documentation for more information
about the various fields.
Returns:
On success, returns the modified status info dict. On failure
communicating with rethinkdb, returns `status_info` unmodified.
Raises:
Exception: if `status_info` is missing a required field, or a
`status_info['ttl']` is not a number greater than zero | [
"Update",
"service",
"status",
"indicating",
"up",
"-",
"ness",
"."
] | f7fc7da725c9b572d473c717b3dad9af98a7a2b4 | https://github.com/internetarchive/doublethink/blob/f7fc7da725c9b572d473c717b3dad9af98a7a2b4/doublethink/services.py#L115-L161 | train | 50,239 |
internetarchive/doublethink | doublethink/services.py | ServiceRegistry.unregister | def unregister(self, id):
'''
Remove the service with id `id` from the service registry.
'''
result = self.rr.table(self.table).get(id).delete().run()
if result != {
'deleted':1, 'errors':0,'inserted':0,
'replaced':0,'skipped':0,'unchanged':0}:
self.logger.warn(
'unexpected result attempting to delete id=%s from '
'rethinkdb services table: %s', id, result) | python | def unregister(self, id):
'''
Remove the service with id `id` from the service registry.
'''
result = self.rr.table(self.table).get(id).delete().run()
if result != {
'deleted':1, 'errors':0,'inserted':0,
'replaced':0,'skipped':0,'unchanged':0}:
self.logger.warn(
'unexpected result attempting to delete id=%s from '
'rethinkdb services table: %s', id, result) | [
"def",
"unregister",
"(",
"self",
",",
"id",
")",
":",
"result",
"=",
"self",
".",
"rr",
".",
"table",
"(",
"self",
".",
"table",
")",
".",
"get",
"(",
"id",
")",
".",
"delete",
"(",
")",
".",
"run",
"(",
")",
"if",
"result",
"!=",
"{",
"'del... | Remove the service with id `id` from the service registry. | [
"Remove",
"the",
"service",
"with",
"id",
"id",
"from",
"the",
"service",
"registry",
"."
] | f7fc7da725c9b572d473c717b3dad9af98a7a2b4 | https://github.com/internetarchive/doublethink/blob/f7fc7da725c9b572d473c717b3dad9af98a7a2b4/doublethink/services.py#L163-L173 | train | 50,240 |
internetarchive/doublethink | doublethink/services.py | ServiceRegistry.unique_service | def unique_service(self, role, candidate=None):
'''
Retrieve a unique service, possibly setting or heartbeating it first.
A "unique service" is a service with only one instance for a given
role. Uniqueness is enforced by using the role name as the primary key
`{'id':role, ...}`.
Args:
role (str): role name
candidate (dict): if supplied, candidate info for the unique
service, explained below
`candidate` normally represents "myself, this instance of the service".
When a service supplies `candidate`, it is nominating itself for
selection as the unique service, or retaining its claim to the role
(heartbeating).
If `candidate` is supplied:
First, atomically in a single rethinkdb query, checks if there is
already a unique healthy instance of this service in rethinkdb, and
if not, sets `candidate` as the unique service.
Looks at the result of that query to determine if `candidate` is
the unique service or not. If it is, updates 'last_heartbeat' in
rethinkdb.
To determine whether `candidate` is the unique service, checks that
all the fields other than 'first_heartbeat' and 'last_heartbeat'
have the same value in `candidate` as in the value returned from
rethinkdb.
***Important***: this means that the caller must ensure that none
of the fields of the unique service ever change. Don't store things
like 'load' or any other volatile value in there. If you try to do
that, heartbeats will end up not being sent, and the unique service
will flap among the candidates.
Finally, retrieves the service from rethinkdb and returns it, if it is
healthy.
Returns:
the unique service, if there is one and it is healthy, otherwise
None
'''
# use the same concept of 'now' for all queries
now = doublethink.utcnow()
if candidate is not None:
candidate['id'] = role
if not 'ttl' in candidate:
raise Exception("candidate is missing required field 'ttl'")
val = candidate['ttl']
if not (isinstance(val, float) or isinstance(val, int)) or val <= 0:
raise Exception("'ttl' must be a number > 0")
candidate['first_heartbeat'] = now
candidate['last_heartbeat'] = now
if not 'host' in candidate:
candidate['host'] = socket.gethostname()
if not 'pid' in candidate:
candidate['pid'] = os.getpid()
result = self.rr.table(
self.table, read_mode='majority').get(role).replace(
lambda row: r.branch(
r.branch(
row,
row['last_heartbeat'] > now - row['ttl'],
False),
row, candidate),
return_changes='always').run()
new_val = result['changes'][0]['new_val']
if all([new_val.get(k) == candidate[k] for k in candidate
if k not in ('first_heartbeat', 'last_heartbeat')]):
# candidate is the unique_service, send a heartbeat
del candidate['first_heartbeat'] # don't touch first_heartbeat
self.rr.table(self.table).get(role).update(candidate).run()
results = list(self.rr.table(
self.table, read_mode='majority').get_all(role).filter(
lambda row: row['last_heartbeat'] > now - row['ttl']).run())
if results:
return results[0]
else:
return None | python | def unique_service(self, role, candidate=None):
'''
Retrieve a unique service, possibly setting or heartbeating it first.
A "unique service" is a service with only one instance for a given
role. Uniqueness is enforced by using the role name as the primary key
`{'id':role, ...}`.
Args:
role (str): role name
candidate (dict): if supplied, candidate info for the unique
service, explained below
`candidate` normally represents "myself, this instance of the service".
When a service supplies `candidate`, it is nominating itself for
selection as the unique service, or retaining its claim to the role
(heartbeating).
If `candidate` is supplied:
First, atomically in a single rethinkdb query, checks if there is
already a unique healthy instance of this service in rethinkdb, and
if not, sets `candidate` as the unique service.
Looks at the result of that query to determine if `candidate` is
the unique service or not. If it is, updates 'last_heartbeat' in
rethinkdb.
To determine whether `candidate` is the unique service, checks that
all the fields other than 'first_heartbeat' and 'last_heartbeat'
have the same value in `candidate` as in the value returned from
rethinkdb.
***Important***: this means that the caller must ensure that none
of the fields of the unique service ever change. Don't store things
like 'load' or any other volatile value in there. If you try to do
that, heartbeats will end up not being sent, and the unique service
will flap among the candidates.
Finally, retrieves the service from rethinkdb and returns it, if it is
healthy.
Returns:
the unique service, if there is one and it is healthy, otherwise
None
'''
# use the same concept of 'now' for all queries
now = doublethink.utcnow()
if candidate is not None:
candidate['id'] = role
if not 'ttl' in candidate:
raise Exception("candidate is missing required field 'ttl'")
val = candidate['ttl']
if not (isinstance(val, float) or isinstance(val, int)) or val <= 0:
raise Exception("'ttl' must be a number > 0")
candidate['first_heartbeat'] = now
candidate['last_heartbeat'] = now
if not 'host' in candidate:
candidate['host'] = socket.gethostname()
if not 'pid' in candidate:
candidate['pid'] = os.getpid()
result = self.rr.table(
self.table, read_mode='majority').get(role).replace(
lambda row: r.branch(
r.branch(
row,
row['last_heartbeat'] > now - row['ttl'],
False),
row, candidate),
return_changes='always').run()
new_val = result['changes'][0]['new_val']
if all([new_val.get(k) == candidate[k] for k in candidate
if k not in ('first_heartbeat', 'last_heartbeat')]):
# candidate is the unique_service, send a heartbeat
del candidate['first_heartbeat'] # don't touch first_heartbeat
self.rr.table(self.table).get(role).update(candidate).run()
results = list(self.rr.table(
self.table, read_mode='majority').get_all(role).filter(
lambda row: row['last_heartbeat'] > now - row['ttl']).run())
if results:
return results[0]
else:
return None | [
"def",
"unique_service",
"(",
"self",
",",
"role",
",",
"candidate",
"=",
"None",
")",
":",
"# use the same concept of 'now' for all queries",
"now",
"=",
"doublethink",
".",
"utcnow",
"(",
")",
"if",
"candidate",
"is",
"not",
"None",
":",
"candidate",
"[",
"'... | Retrieve a unique service, possibly setting or heartbeating it first.
A "unique service" is a service with only one instance for a given
role. Uniqueness is enforced by using the role name as the primary key
`{'id':role, ...}`.
Args:
role (str): role name
candidate (dict): if supplied, candidate info for the unique
service, explained below
`candidate` normally represents "myself, this instance of the service".
When a service supplies `candidate`, it is nominating itself for
selection as the unique service, or retaining its claim to the role
(heartbeating).
If `candidate` is supplied:
First, atomically in a single rethinkdb query, checks if there is
already a unique healthy instance of this service in rethinkdb, and
if not, sets `candidate` as the unique service.
Looks at the result of that query to determine if `candidate` is
the unique service or not. If it is, updates 'last_heartbeat' in
rethinkdb.
To determine whether `candidate` is the unique service, checks that
all the fields other than 'first_heartbeat' and 'last_heartbeat'
have the same value in `candidate` as in the value returned from
rethinkdb.
***Important***: this means that the caller must ensure that none
of the fields of the unique service ever change. Don't store things
like 'load' or any other volatile value in there. If you try to do
that, heartbeats will end up not being sent, and the unique service
will flap among the candidates.
Finally, retrieves the service from rethinkdb and returns it, if it is
healthy.
Returns:
the unique service, if there is one and it is healthy, otherwise
None | [
"Retrieve",
"a",
"unique",
"service",
"possibly",
"setting",
"or",
"heartbeating",
"it",
"first",
"."
] | f7fc7da725c9b572d473c717b3dad9af98a7a2b4 | https://github.com/internetarchive/doublethink/blob/f7fc7da725c9b572d473c717b3dad9af98a7a2b4/doublethink/services.py#L175-L261 | train | 50,241 |
internetarchive/doublethink | doublethink/services.py | ServiceRegistry.healthy_services | def healthy_services(self, role=None):
'''
Look up healthy services in the registry.
A service is considered healthy if its 'last_heartbeat' was less than
'ttl' seconds ago
Args:
role (str, optional): role name
Returns:
If `role` is supplied, returns list of healthy services for the
given role, otherwise returns list of all healthy services. May
return an empty list.
'''
try:
query = self.rr.table(self.table)
if role:
query = query.get_all(role, index='role')
query = query.filter(
lambda svc: r.now().sub(svc["last_heartbeat"]) < svc["ttl"] #.default(20.0)
).order_by("load")
result = query.run()
return result
except r.ReqlNonExistenceError:
return [] | python | def healthy_services(self, role=None):
'''
Look up healthy services in the registry.
A service is considered healthy if its 'last_heartbeat' was less than
'ttl' seconds ago
Args:
role (str, optional): role name
Returns:
If `role` is supplied, returns list of healthy services for the
given role, otherwise returns list of all healthy services. May
return an empty list.
'''
try:
query = self.rr.table(self.table)
if role:
query = query.get_all(role, index='role')
query = query.filter(
lambda svc: r.now().sub(svc["last_heartbeat"]) < svc["ttl"] #.default(20.0)
).order_by("load")
result = query.run()
return result
except r.ReqlNonExistenceError:
return [] | [
"def",
"healthy_services",
"(",
"self",
",",
"role",
"=",
"None",
")",
":",
"try",
":",
"query",
"=",
"self",
".",
"rr",
".",
"table",
"(",
"self",
".",
"table",
")",
"if",
"role",
":",
"query",
"=",
"query",
".",
"get_all",
"(",
"role",
",",
"in... | Look up healthy services in the registry.
A service is considered healthy if its 'last_heartbeat' was less than
'ttl' seconds ago
Args:
role (str, optional): role name
Returns:
If `role` is supplied, returns list of healthy services for the
given role, otherwise returns list of all healthy services. May
return an empty list. | [
"Look",
"up",
"healthy",
"services",
"in",
"the",
"registry",
"."
] | f7fc7da725c9b572d473c717b3dad9af98a7a2b4 | https://github.com/internetarchive/doublethink/blob/f7fc7da725c9b572d473c717b3dad9af98a7a2b4/doublethink/services.py#L285-L310 | train | 50,242 |
Workiva/furious | furious/context/__init__.py | new | def new(batch_size=None, **options):
"""Get a new furious context and add it to the registry. If a batch size is
specified, use an AutoContext which inserts tasks in batches as they are
added to the context.
"""
if batch_size:
new_context = AutoContext(batch_size=batch_size, **options)
else:
new_context = Context(**options)
_local.get_local_context().registry.append(new_context)
return new_context | python | def new(batch_size=None, **options):
"""Get a new furious context and add it to the registry. If a batch size is
specified, use an AutoContext which inserts tasks in batches as they are
added to the context.
"""
if batch_size:
new_context = AutoContext(batch_size=batch_size, **options)
else:
new_context = Context(**options)
_local.get_local_context().registry.append(new_context)
return new_context | [
"def",
"new",
"(",
"batch_size",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"if",
"batch_size",
":",
"new_context",
"=",
"AutoContext",
"(",
"batch_size",
"=",
"batch_size",
",",
"*",
"*",
"options",
")",
"else",
":",
"new_context",
"=",
"Context",... | Get a new furious context and add it to the registry. If a batch size is
specified, use an AutoContext which inserts tasks in batches as they are
added to the context. | [
"Get",
"a",
"new",
"furious",
"context",
"and",
"add",
"it",
"to",
"the",
"registry",
".",
"If",
"a",
"batch",
"size",
"is",
"specified",
"use",
"an",
"AutoContext",
"which",
"inserts",
"tasks",
"in",
"batches",
"as",
"they",
"are",
"added",
"to",
"the",... | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/context/__init__.py#L53-L66 | train | 50,243 |
Workiva/furious | furious/context/__init__.py | get_current_async | def get_current_async():
"""Return a reference to the currently executing Async job object
or None if not in an Async job.
"""
local_context = _local.get_local_context()
if local_context._executing_async:
return local_context._executing_async[-1]
raise errors.NotInContextError('Not in an _ExecutionContext.') | python | def get_current_async():
"""Return a reference to the currently executing Async job object
or None if not in an Async job.
"""
local_context = _local.get_local_context()
if local_context._executing_async:
return local_context._executing_async[-1]
raise errors.NotInContextError('Not in an _ExecutionContext.') | [
"def",
"get_current_async",
"(",
")",
":",
"local_context",
"=",
"_local",
".",
"get_local_context",
"(",
")",
"if",
"local_context",
".",
"_executing_async",
":",
"return",
"local_context",
".",
"_executing_async",
"[",
"-",
"1",
"]",
"raise",
"errors",
".",
... | Return a reference to the currently executing Async job object
or None if not in an Async job. | [
"Return",
"a",
"reference",
"to",
"the",
"currently",
"executing",
"Async",
"job",
"object",
"or",
"None",
"if",
"not",
"in",
"an",
"Async",
"job",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/context/__init__.py#L69-L78 | train | 50,244 |
Workiva/furious | furious/context/__init__.py | get_current_context | def get_current_context():
"""Return a reference to the current Context object.
"""
local_context = _local.get_local_context()
if local_context.registry:
return local_context.registry[-1]
raise errors.NotInContextError('Not in a Context.') | python | def get_current_context():
"""Return a reference to the current Context object.
"""
local_context = _local.get_local_context()
if local_context.registry:
return local_context.registry[-1]
raise errors.NotInContextError('Not in a Context.') | [
"def",
"get_current_context",
"(",
")",
":",
"local_context",
"=",
"_local",
".",
"get_local_context",
"(",
")",
"if",
"local_context",
".",
"registry",
":",
"return",
"local_context",
".",
"registry",
"[",
"-",
"1",
"]",
"raise",
"errors",
".",
"NotInContextE... | Return a reference to the current Context object. | [
"Return",
"a",
"reference",
"to",
"the",
"current",
"Context",
"object",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/context/__init__.py#L81-L89 | train | 50,245 |
internetarchive/doublethink | doublethink/cli.py | purge_stale_services | def purge_stale_services(argv=None):
"""Command-line utility to periodically purge stale entries from the "services" table.
It is designed to be used in conjunction with cron.
"""
argv = argv or sys.argv
arg_parser = argparse.ArgumentParser(
prog=os.path.basename(argv[0]), description=(
'doublethink-purge-stale-services: utility to periodically '
'purge stale entries from the "services" table.'))
arg_parser.add_argument(
"-d", "--rethinkdb-db", required=True, dest="database",
help="A RethinkDB database containing a 'services' table")
arg_parser.add_argument("-s", "--rethinkdb-servers",
metavar="SERVERS", dest="servers", default='localhost',
help="rethinkdb servers, e.g. db0.foo.org,db0.foo.org:38015,db1.foo.org")
arg_parser.add_argument(
'-v', '--verbose', dest='log_level', action='store_const',
default=logging.INFO, const=logging.DEBUG, help=(
'verbose logging'))
args = arg_parser.parse_args(argv[1:])
logging.basicConfig(
stream=sys.stdout, level=args.log_level, format=(
'%(asctime)s %(process)d %(levelname)s %(threadName)s '
'%(name)s.%(funcName)s(%(filename)s:%(lineno)d) %(message)s'))
args.servers = [srv.strip() for srv in args.servers.split(",")]
rethinker = doublethink.Rethinker(servers=args.servers, db=args.database)
registry = doublethink.services.ServiceRegistry(rethinker)
registry.purge_stale_services()
return 0 | python | def purge_stale_services(argv=None):
"""Command-line utility to periodically purge stale entries from the "services" table.
It is designed to be used in conjunction with cron.
"""
argv = argv or sys.argv
arg_parser = argparse.ArgumentParser(
prog=os.path.basename(argv[0]), description=(
'doublethink-purge-stale-services: utility to periodically '
'purge stale entries from the "services" table.'))
arg_parser.add_argument(
"-d", "--rethinkdb-db", required=True, dest="database",
help="A RethinkDB database containing a 'services' table")
arg_parser.add_argument("-s", "--rethinkdb-servers",
metavar="SERVERS", dest="servers", default='localhost',
help="rethinkdb servers, e.g. db0.foo.org,db0.foo.org:38015,db1.foo.org")
arg_parser.add_argument(
'-v', '--verbose', dest='log_level', action='store_const',
default=logging.INFO, const=logging.DEBUG, help=(
'verbose logging'))
args = arg_parser.parse_args(argv[1:])
logging.basicConfig(
stream=sys.stdout, level=args.log_level, format=(
'%(asctime)s %(process)d %(levelname)s %(threadName)s '
'%(name)s.%(funcName)s(%(filename)s:%(lineno)d) %(message)s'))
args.servers = [srv.strip() for srv in args.servers.split(",")]
rethinker = doublethink.Rethinker(servers=args.servers, db=args.database)
registry = doublethink.services.ServiceRegistry(rethinker)
registry.purge_stale_services()
return 0 | [
"def",
"purge_stale_services",
"(",
"argv",
"=",
"None",
")",
":",
"argv",
"=",
"argv",
"or",
"sys",
".",
"argv",
"arg_parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"prog",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"argv",
"[",
"0",
"]",
... | Command-line utility to periodically purge stale entries from the "services" table.
It is designed to be used in conjunction with cron. | [
"Command",
"-",
"line",
"utility",
"to",
"periodically",
"purge",
"stale",
"entries",
"from",
"the",
"services",
"table",
"."
] | f7fc7da725c9b572d473c717b3dad9af98a7a2b4 | https://github.com/internetarchive/doublethink/blob/f7fc7da725c9b572d473c717b3dad9af98a7a2b4/doublethink/cli.py#L25-L59 | train | 50,246 |
Workiva/furious | furious/context/context.py | _insert_tasks | def _insert_tasks(tasks, queue, transactional=False,
retry_transient_errors=True,
retry_delay=RETRY_SLEEP_SECS):
"""Insert a batch of tasks into the specified queue. If an error occurs
during insertion, split the batch and retry until they are successfully
inserted. Return the number of successfully inserted tasks.
"""
from google.appengine.api import taskqueue
if not tasks:
return 0
try:
taskqueue.Queue(name=queue).add(tasks, transactional=transactional)
return len(tasks)
except (taskqueue.BadTaskStateError,
taskqueue.TaskAlreadyExistsError,
taskqueue.TombstonedTaskError):
if len(tasks) <= 1:
# Task has already been inserted, no reason to report an error here.
return 0
# If a list of more than one Tasks is given, a raised exception does
# not guarantee that no tasks were added to the queue (unless
# transactional is set to True). To determine which tasks were
# successfully added when an exception is raised, check the
# Task.was_enqueued property.
reinsert = _tasks_to_reinsert(tasks, transactional)
count = len(reinsert)
inserted = len(tasks) - count
inserted += _insert_tasks(reinsert[:count / 2], queue, transactional,
retry_transient_errors, retry_delay)
inserted += _insert_tasks(reinsert[count / 2:], queue, transactional,
retry_transient_errors, retry_delay)
return inserted
except taskqueue.TransientError:
# Always re-raise for transactional insert, or if specified by
# options.
if transactional or not retry_transient_errors:
raise
reinsert = _tasks_to_reinsert(tasks, transactional)
# Retry with a delay, and then let any errors re-raise.
time.sleep(retry_delay)
taskqueue.Queue(name=queue).add(reinsert, transactional=transactional)
return len(tasks) | python | def _insert_tasks(tasks, queue, transactional=False,
retry_transient_errors=True,
retry_delay=RETRY_SLEEP_SECS):
"""Insert a batch of tasks into the specified queue. If an error occurs
during insertion, split the batch and retry until they are successfully
inserted. Return the number of successfully inserted tasks.
"""
from google.appengine.api import taskqueue
if not tasks:
return 0
try:
taskqueue.Queue(name=queue).add(tasks, transactional=transactional)
return len(tasks)
except (taskqueue.BadTaskStateError,
taskqueue.TaskAlreadyExistsError,
taskqueue.TombstonedTaskError):
if len(tasks) <= 1:
# Task has already been inserted, no reason to report an error here.
return 0
# If a list of more than one Tasks is given, a raised exception does
# not guarantee that no tasks were added to the queue (unless
# transactional is set to True). To determine which tasks were
# successfully added when an exception is raised, check the
# Task.was_enqueued property.
reinsert = _tasks_to_reinsert(tasks, transactional)
count = len(reinsert)
inserted = len(tasks) - count
inserted += _insert_tasks(reinsert[:count / 2], queue, transactional,
retry_transient_errors, retry_delay)
inserted += _insert_tasks(reinsert[count / 2:], queue, transactional,
retry_transient_errors, retry_delay)
return inserted
except taskqueue.TransientError:
# Always re-raise for transactional insert, or if specified by
# options.
if transactional or not retry_transient_errors:
raise
reinsert = _tasks_to_reinsert(tasks, transactional)
# Retry with a delay, and then let any errors re-raise.
time.sleep(retry_delay)
taskqueue.Queue(name=queue).add(reinsert, transactional=transactional)
return len(tasks) | [
"def",
"_insert_tasks",
"(",
"tasks",
",",
"queue",
",",
"transactional",
"=",
"False",
",",
"retry_transient_errors",
"=",
"True",
",",
"retry_delay",
"=",
"RETRY_SLEEP_SECS",
")",
":",
"from",
"google",
".",
"appengine",
".",
"api",
"import",
"taskqueue",
"i... | Insert a batch of tasks into the specified queue. If an error occurs
during insertion, split the batch and retry until they are successfully
inserted. Return the number of successfully inserted tasks. | [
"Insert",
"a",
"batch",
"of",
"tasks",
"into",
"the",
"specified",
"queue",
".",
"If",
"an",
"error",
"occurs",
"during",
"insertion",
"split",
"the",
"batch",
"and",
"retry",
"until",
"they",
"are",
"successfully",
"inserted",
".",
"Return",
"the",
"number"... | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/context/context.py#L368-L416 | train | 50,247 |
Workiva/furious | furious/context/context.py | _tasks_to_reinsert | def _tasks_to_reinsert(tasks, transactional):
"""Return a list containing the tasks that should be reinserted based on the
was_enqueued property and whether the insert is transactional or not.
"""
if transactional:
return tasks
return [task for task in tasks if not task.was_enqueued] | python | def _tasks_to_reinsert(tasks, transactional):
"""Return a list containing the tasks that should be reinserted based on the
was_enqueued property and whether the insert is transactional or not.
"""
if transactional:
return tasks
return [task for task in tasks if not task.was_enqueued] | [
"def",
"_tasks_to_reinsert",
"(",
"tasks",
",",
"transactional",
")",
":",
"if",
"transactional",
":",
"return",
"tasks",
"return",
"[",
"task",
"for",
"task",
"in",
"tasks",
"if",
"not",
"task",
".",
"was_enqueued",
"]"
] | Return a list containing the tasks that should be reinserted based on the
was_enqueued property and whether the insert is transactional or not. | [
"Return",
"a",
"list",
"containing",
"the",
"tasks",
"that",
"should",
"be",
"reinserted",
"based",
"on",
"the",
"was_enqueued",
"property",
"and",
"whether",
"the",
"insert",
"is",
"transactional",
"or",
"not",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/context/context.py#L419-L426 | train | 50,248 |
Workiva/furious | furious/context/context.py | _task_batcher | def _task_batcher(tasks, batch_size=None):
"""Batches large task lists into groups of 100 so that they can all be
inserted.
"""
from itertools import izip_longest
if not batch_size:
batch_size = DEFAULT_TASK_BATCH_SIZE
# Ensure the batch size is under the task api limit.
batch_size = min(batch_size, 100)
args = [iter(tasks)] * batch_size
return ([task for task in group if task] for group in izip_longest(*args)) | python | def _task_batcher(tasks, batch_size=None):
"""Batches large task lists into groups of 100 so that they can all be
inserted.
"""
from itertools import izip_longest
if not batch_size:
batch_size = DEFAULT_TASK_BATCH_SIZE
# Ensure the batch size is under the task api limit.
batch_size = min(batch_size, 100)
args = [iter(tasks)] * batch_size
return ([task for task in group if task] for group in izip_longest(*args)) | [
"def",
"_task_batcher",
"(",
"tasks",
",",
"batch_size",
"=",
"None",
")",
":",
"from",
"itertools",
"import",
"izip_longest",
"if",
"not",
"batch_size",
":",
"batch_size",
"=",
"DEFAULT_TASK_BATCH_SIZE",
"# Ensure the batch size is under the task api limit.",
"batch_size... | Batches large task lists into groups of 100 so that they can all be
inserted. | [
"Batches",
"large",
"task",
"lists",
"into",
"groups",
"of",
"100",
"so",
"that",
"they",
"can",
"all",
"be",
"inserted",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/context/context.py#L429-L442 | train | 50,249 |
Workiva/furious | furious/context/context.py | Context._handle_tasks_insert | def _handle_tasks_insert(self, batch_size=None):
"""Convert all Async's into tasks, then insert them into queues."""
if self._tasks_inserted:
raise errors.ContextAlreadyStartedError(
"This Context has already had its tasks inserted.")
task_map = self._get_tasks_by_queue()
# QUESTION: Should the persist happen before or after the task
# insertion? I feel like this is something that will alter the
# behavior of the tasks themselves by adding a callback (check context
# complete) to each Async's callback stack.
# If we are able to and there is a reason to persist... persist.
callbacks = self._options.get('callbacks')
if self._persistence_engine and callbacks:
self.persist()
retry_transient = self._options.get('retry_transient_errors', True)
retry_delay = self._options.get('retry_delay', RETRY_SLEEP_SECS)
for queue, tasks in task_map.iteritems():
for batch in _task_batcher(tasks, batch_size=batch_size):
inserted = self._insert_tasks(
batch, queue=queue, retry_transient_errors=retry_transient,
retry_delay=retry_delay
)
if isinstance(inserted, (int, long)):
# Don't blow up on insert_tasks that don't return counts.
self._insert_success_count += inserted
self._insert_failed_count += len(batch) - inserted | python | def _handle_tasks_insert(self, batch_size=None):
"""Convert all Async's into tasks, then insert them into queues."""
if self._tasks_inserted:
raise errors.ContextAlreadyStartedError(
"This Context has already had its tasks inserted.")
task_map = self._get_tasks_by_queue()
# QUESTION: Should the persist happen before or after the task
# insertion? I feel like this is something that will alter the
# behavior of the tasks themselves by adding a callback (check context
# complete) to each Async's callback stack.
# If we are able to and there is a reason to persist... persist.
callbacks = self._options.get('callbacks')
if self._persistence_engine and callbacks:
self.persist()
retry_transient = self._options.get('retry_transient_errors', True)
retry_delay = self._options.get('retry_delay', RETRY_SLEEP_SECS)
for queue, tasks in task_map.iteritems():
for batch in _task_batcher(tasks, batch_size=batch_size):
inserted = self._insert_tasks(
batch, queue=queue, retry_transient_errors=retry_transient,
retry_delay=retry_delay
)
if isinstance(inserted, (int, long)):
# Don't blow up on insert_tasks that don't return counts.
self._insert_success_count += inserted
self._insert_failed_count += len(batch) - inserted | [
"def",
"_handle_tasks_insert",
"(",
"self",
",",
"batch_size",
"=",
"None",
")",
":",
"if",
"self",
".",
"_tasks_inserted",
":",
"raise",
"errors",
".",
"ContextAlreadyStartedError",
"(",
"\"This Context has already had its tasks inserted.\"",
")",
"task_map",
"=",
"s... | Convert all Async's into tasks, then insert them into queues. | [
"Convert",
"all",
"Async",
"s",
"into",
"tasks",
"then",
"insert",
"them",
"into",
"queues",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/context/context.py#L127-L157 | train | 50,250 |
Workiva/furious | furious/context/context.py | Context.set_event_handler | def set_event_handler(self, event, handler):
"""Add an Async to be run on event."""
# QUESTION: Should we raise an exception if `event` is not in some
# known event-type list?
self._prepare_persistence_engine()
callbacks = self._options.get('callbacks', {})
callbacks[event] = handler
self._options['callbacks'] = callbacks | python | def set_event_handler(self, event, handler):
"""Add an Async to be run on event."""
# QUESTION: Should we raise an exception if `event` is not in some
# known event-type list?
self._prepare_persistence_engine()
callbacks = self._options.get('callbacks', {})
callbacks[event] = handler
self._options['callbacks'] = callbacks | [
"def",
"set_event_handler",
"(",
"self",
",",
"event",
",",
"handler",
")",
":",
"# QUESTION: Should we raise an exception if `event` is not in some",
"# known event-type list?",
"self",
".",
"_prepare_persistence_engine",
"(",
")",
"callbacks",
"=",
"self",
".",
"_options"... | Add an Async to be run on event. | [
"Add",
"an",
"Async",
"to",
"be",
"run",
"on",
"event",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/context/context.py#L204-L213 | train | 50,251 |
Workiva/furious | furious/context/context.py | Context.exec_event_handler | def exec_event_handler(self, event, transactional=False):
"""Execute the Async set to be run on event."""
# QUESTION: Should we raise an exception if `event` is not in some
# known event-type list?
callbacks = self._options.get('callbacks', {})
handler = callbacks.get(event)
if not handler:
raise Exception('Handler not defined!!!')
handler.start(transactional=transactional) | python | def exec_event_handler(self, event, transactional=False):
"""Execute the Async set to be run on event."""
# QUESTION: Should we raise an exception if `event` is not in some
# known event-type list?
callbacks = self._options.get('callbacks', {})
handler = callbacks.get(event)
if not handler:
raise Exception('Handler not defined!!!')
handler.start(transactional=transactional) | [
"def",
"exec_event_handler",
"(",
"self",
",",
"event",
",",
"transactional",
"=",
"False",
")",
":",
"# QUESTION: Should we raise an exception if `event` is not in some",
"# known event-type list?",
"callbacks",
"=",
"self",
".",
"_options",
".",
"get",
"(",
"'callbacks'... | Execute the Async set to be run on event. | [
"Execute",
"the",
"Async",
"set",
"to",
"be",
"run",
"on",
"event",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/context/context.py#L215-L227 | train | 50,252 |
Workiva/furious | furious/context/context.py | Context.load | def load(cls, context_id, persistence_engine=None):
"""Load and instantiate a Context from the persistence_engine."""
if not persistence_engine:
from furious.config import get_default_persistence_engine
persistence_engine = get_default_persistence_engine()
if not persistence_engine:
raise RuntimeError(
'Specify a valid persistence_engine to load the context.')
return persistence_engine.load_context(context_id) | python | def load(cls, context_id, persistence_engine=None):
"""Load and instantiate a Context from the persistence_engine."""
if not persistence_engine:
from furious.config import get_default_persistence_engine
persistence_engine = get_default_persistence_engine()
if not persistence_engine:
raise RuntimeError(
'Specify a valid persistence_engine to load the context.')
return persistence_engine.load_context(context_id) | [
"def",
"load",
"(",
"cls",
",",
"context_id",
",",
"persistence_engine",
"=",
"None",
")",
":",
"if",
"not",
"persistence_engine",
":",
"from",
"furious",
".",
"config",
"import",
"get_default_persistence_engine",
"persistence_engine",
"=",
"get_default_persistence_en... | Load and instantiate a Context from the persistence_engine. | [
"Load",
"and",
"instantiate",
"a",
"Context",
"from",
"the",
"persistence_engine",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/context/context.py#L269-L279 | train | 50,253 |
Workiva/furious | furious/context/context.py | Context.to_dict | def to_dict(self):
"""Return this Context as a dict suitable for json encoding."""
import copy
options = copy.deepcopy(self._options)
if self._insert_tasks:
options['insert_tasks'] = reference_to_path(self._insert_tasks)
if self._persistence_engine:
options['persistence_engine'] = reference_to_path(
self._persistence_engine)
options.update({
'_tasks_inserted': self._tasks_inserted,
})
callbacks = self._options.get('callbacks')
if callbacks:
options['callbacks'] = encode_callbacks(callbacks)
return options | python | def to_dict(self):
"""Return this Context as a dict suitable for json encoding."""
import copy
options = copy.deepcopy(self._options)
if self._insert_tasks:
options['insert_tasks'] = reference_to_path(self._insert_tasks)
if self._persistence_engine:
options['persistence_engine'] = reference_to_path(
self._persistence_engine)
options.update({
'_tasks_inserted': self._tasks_inserted,
})
callbacks = self._options.get('callbacks')
if callbacks:
options['callbacks'] = encode_callbacks(callbacks)
return options | [
"def",
"to_dict",
"(",
"self",
")",
":",
"import",
"copy",
"options",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"_options",
")",
"if",
"self",
".",
"_insert_tasks",
":",
"options",
"[",
"'insert_tasks'",
"]",
"=",
"reference_to_path",
"(",
"self",
... | Return this Context as a dict suitable for json encoding. | [
"Return",
"this",
"Context",
"as",
"a",
"dict",
"suitable",
"for",
"json",
"encoding",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/context/context.py#L281-L302 | train | 50,254 |
Workiva/furious | furious/context/context.py | Context.from_dict | def from_dict(cls, context_options_dict):
"""Return a context job from a dict output by Context.to_dict."""
import copy
context_options = copy.deepcopy(context_options_dict)
tasks_inserted = context_options.pop('_tasks_inserted', False)
insert_tasks = context_options.pop('insert_tasks', None)
if insert_tasks:
context_options['insert_tasks'] = path_to_reference(insert_tasks)
# The constructor expects a reference to the persistence engine.
persistence_engine = context_options.pop('persistence_engine', None)
if persistence_engine:
context_options['persistence_engine'] = path_to_reference(
persistence_engine)
# If there are callbacks, reconstitute them.
callbacks = context_options.pop('callbacks', None)
if callbacks:
context_options['callbacks'] = decode_callbacks(callbacks)
context = cls(**context_options)
context._tasks_inserted = tasks_inserted
return context | python | def from_dict(cls, context_options_dict):
"""Return a context job from a dict output by Context.to_dict."""
import copy
context_options = copy.deepcopy(context_options_dict)
tasks_inserted = context_options.pop('_tasks_inserted', False)
insert_tasks = context_options.pop('insert_tasks', None)
if insert_tasks:
context_options['insert_tasks'] = path_to_reference(insert_tasks)
# The constructor expects a reference to the persistence engine.
persistence_engine = context_options.pop('persistence_engine', None)
if persistence_engine:
context_options['persistence_engine'] = path_to_reference(
persistence_engine)
# If there are callbacks, reconstitute them.
callbacks = context_options.pop('callbacks', None)
if callbacks:
context_options['callbacks'] = decode_callbacks(callbacks)
context = cls(**context_options)
context._tasks_inserted = tasks_inserted
return context | [
"def",
"from_dict",
"(",
"cls",
",",
"context_options_dict",
")",
":",
"import",
"copy",
"context_options",
"=",
"copy",
".",
"deepcopy",
"(",
"context_options_dict",
")",
"tasks_inserted",
"=",
"context_options",
".",
"pop",
"(",
"'_tasks_inserted'",
",",
"False"... | Return a context job from a dict output by Context.to_dict. | [
"Return",
"a",
"context",
"job",
"from",
"a",
"dict",
"output",
"by",
"Context",
".",
"to_dict",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/context/context.py#L305-L332 | train | 50,255 |
Workiva/furious | furious/context/context.py | Context.result | def result(self):
"""Return the context result object pulled from the persistence_engine
if it has been set.
"""
if not self._result:
if not self._persistence_engine:
return None
self._result = self._persistence_engine.get_context_result(self)
return self._result | python | def result(self):
"""Return the context result object pulled from the persistence_engine
if it has been set.
"""
if not self._result:
if not self._persistence_engine:
return None
self._result = self._persistence_engine.get_context_result(self)
return self._result | [
"def",
"result",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_result",
":",
"if",
"not",
"self",
".",
"_persistence_engine",
":",
"return",
"None",
"self",
".",
"_result",
"=",
"self",
".",
"_persistence_engine",
".",
"get_context_result",
"(",
"self... | Return the context result object pulled from the persistence_engine
if it has been set. | [
"Return",
"the",
"context",
"result",
"object",
"pulled",
"from",
"the",
"persistence_engine",
"if",
"it",
"has",
"been",
"set",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/context/context.py#L335-L345 | train | 50,256 |
Workiva/furious | furious/extras/insert_task_handlers.py | insert_tasks_ignore_duplicate_names | def insert_tasks_ignore_duplicate_names(tasks, queue, *args, **kwargs):
"""Insert a batch of tasks into a specific queue. If a
DuplicateTaskNameError is raised, loop through the tasks and insert the
remaining, ignoring and logging the duplicate tasks.
Returns the number of successfully inserted tasks.
"""
from google.appengine.api import taskqueue
try:
inserted = _insert_tasks(tasks, queue, *args, **kwargs)
return inserted
except taskqueue.DuplicateTaskNameError:
# At least one task failed in our batch, attempt to re-insert the
# remaining tasks. Named tasks can never be transactional.
reinsert = _tasks_to_reinsert(tasks, transactional=False)
count = len(reinsert)
inserted = len(tasks) - count
# Our subsequent task inserts should raise TaskAlreadyExistsError at
# least once, but that will be swallowed by _insert_tasks.
for task in reinsert:
inserted += _insert_tasks([task], queue, *args, **kwargs)
return inserted | python | def insert_tasks_ignore_duplicate_names(tasks, queue, *args, **kwargs):
"""Insert a batch of tasks into a specific queue. If a
DuplicateTaskNameError is raised, loop through the tasks and insert the
remaining, ignoring and logging the duplicate tasks.
Returns the number of successfully inserted tasks.
"""
from google.appengine.api import taskqueue
try:
inserted = _insert_tasks(tasks, queue, *args, **kwargs)
return inserted
except taskqueue.DuplicateTaskNameError:
# At least one task failed in our batch, attempt to re-insert the
# remaining tasks. Named tasks can never be transactional.
reinsert = _tasks_to_reinsert(tasks, transactional=False)
count = len(reinsert)
inserted = len(tasks) - count
# Our subsequent task inserts should raise TaskAlreadyExistsError at
# least once, but that will be swallowed by _insert_tasks.
for task in reinsert:
inserted += _insert_tasks([task], queue, *args, **kwargs)
return inserted | [
"def",
"insert_tasks_ignore_duplicate_names",
"(",
"tasks",
",",
"queue",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"google",
".",
"appengine",
".",
"api",
"import",
"taskqueue",
"try",
":",
"inserted",
"=",
"_insert_tasks",
"(",
"tasks",
... | Insert a batch of tasks into a specific queue. If a
DuplicateTaskNameError is raised, loop through the tasks and insert the
remaining, ignoring and logging the duplicate tasks.
Returns the number of successfully inserted tasks. | [
"Insert",
"a",
"batch",
"of",
"tasks",
"into",
"a",
"specific",
"queue",
".",
"If",
"a",
"DuplicateTaskNameError",
"is",
"raised",
"loop",
"through",
"the",
"tasks",
"and",
"insert",
"the",
"remaining",
"ignoring",
"and",
"logging",
"the",
"duplicate",
"tasks"... | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/extras/insert_task_handlers.py#L5-L32 | train | 50,257 |
Workiva/furious | example/grep.py | build_and_start | def build_and_start(query, directory):
"""This function will create and then start a new Async task with the
default callbacks argument defined in the decorator."""
Async(target=grep, args=[query, directory]).start() | python | def build_and_start(query, directory):
"""This function will create and then start a new Async task with the
default callbacks argument defined in the decorator."""
Async(target=grep, args=[query, directory]).start() | [
"def",
"build_and_start",
"(",
"query",
",",
"directory",
")",
":",
"Async",
"(",
"target",
"=",
"grep",
",",
"args",
"=",
"[",
"query",
",",
"directory",
"]",
")",
".",
"start",
"(",
")"
] | This function will create and then start a new Async task with the
default callbacks argument defined in the decorator. | [
"This",
"function",
"will",
"create",
"and",
"then",
"start",
"a",
"new",
"Async",
"task",
"with",
"the",
"default",
"callbacks",
"argument",
"defined",
"in",
"the",
"decorator",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/example/grep.py#L60-L64 | train | 50,258 |
Workiva/furious | example/grep.py | grep_file | def grep_file(query, item):
"""This function performs the actual grep on a given file."""
return ['%s: %s' % (item, line) for line in open(item)
if re.search(query, line)] | python | def grep_file(query, item):
"""This function performs the actual grep on a given file."""
return ['%s: %s' % (item, line) for line in open(item)
if re.search(query, line)] | [
"def",
"grep_file",
"(",
"query",
",",
"item",
")",
":",
"return",
"[",
"'%s: %s'",
"%",
"(",
"item",
",",
"line",
")",
"for",
"line",
"in",
"open",
"(",
"item",
")",
"if",
"re",
".",
"search",
"(",
"query",
",",
"line",
")",
"]"
] | This function performs the actual grep on a given file. | [
"This",
"function",
"performs",
"the",
"actual",
"grep",
"on",
"a",
"given",
"file",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/example/grep.py#L67-L70 | train | 50,259 |
Workiva/furious | example/grep.py | grep | def grep(query, directory):
"""This function will search through the directory structure of the
application and for each directory it finds it launches an Async task to
run itself. For each .py file it finds, it actually greps the file and then
returns the found output."""
dir_contents = os.listdir(directory)
results = []
for item in dir_contents:
path = os.path.join(directory, item)
if os.path.isdir(path):
build_and_start(query, path)
else:
if item.endswith('.py'):
results.extend(grep_file(query, path))
return results | python | def grep(query, directory):
"""This function will search through the directory structure of the
application and for each directory it finds it launches an Async task to
run itself. For each .py file it finds, it actually greps the file and then
returns the found output."""
dir_contents = os.listdir(directory)
results = []
for item in dir_contents:
path = os.path.join(directory, item)
if os.path.isdir(path):
build_and_start(query, path)
else:
if item.endswith('.py'):
results.extend(grep_file(query, path))
return results | [
"def",
"grep",
"(",
"query",
",",
"directory",
")",
":",
"dir_contents",
"=",
"os",
".",
"listdir",
"(",
"directory",
")",
"results",
"=",
"[",
"]",
"for",
"item",
"in",
"dir_contents",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"director... | This function will search through the directory structure of the
application and for each directory it finds it launches an Async task to
run itself. For each .py file it finds, it actually greps the file and then
returns the found output. | [
"This",
"function",
"will",
"search",
"through",
"the",
"directory",
"structure",
"of",
"the",
"application",
"and",
"for",
"each",
"directory",
"it",
"finds",
"it",
"launches",
"an",
"Async",
"task",
"to",
"run",
"itself",
".",
"For",
"each",
".",
"py",
"... | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/example/grep.py#L74-L89 | train | 50,260 |
Workiva/furious | furious/config.py | find_furious_yaml | def find_furious_yaml(config_file=__file__):
"""
Traverse directory trees to find a furious.yaml file
Begins with the location of this file then checks the
working directory if not found
Args:
config_file: location of this file, override for
testing
Returns:
the path of furious.yaml or None if not found
"""
checked = set()
result = _find_furious_yaml(os.path.dirname(config_file), checked)
if not result:
result = _find_furious_yaml(os.getcwd(), checked)
return result | python | def find_furious_yaml(config_file=__file__):
"""
Traverse directory trees to find a furious.yaml file
Begins with the location of this file then checks the
working directory if not found
Args:
config_file: location of this file, override for
testing
Returns:
the path of furious.yaml or None if not found
"""
checked = set()
result = _find_furious_yaml(os.path.dirname(config_file), checked)
if not result:
result = _find_furious_yaml(os.getcwd(), checked)
return result | [
"def",
"find_furious_yaml",
"(",
"config_file",
"=",
"__file__",
")",
":",
"checked",
"=",
"set",
"(",
")",
"result",
"=",
"_find_furious_yaml",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"config_file",
")",
",",
"checked",
")",
"if",
"not",
"result",
... | Traverse directory trees to find a furious.yaml file
Begins with the location of this file then checks the
working directory if not found
Args:
config_file: location of this file, override for
testing
Returns:
the path of furious.yaml or None if not found | [
"Traverse",
"directory",
"trees",
"to",
"find",
"a",
"furious",
".",
"yaml",
"file"
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/config.py#L98-L115 | train | 50,261 |
Workiva/furious | furious/config.py | _find_furious_yaml | def _find_furious_yaml(start, checked):
"""Traverse the directory tree identified by start
until a directory already in checked is encountered or the path
of furious.yaml is found.
Checked is present both to make the loop termination easy
to reason about and so the same directories do not get
rechecked
Args:
start: the path to start looking in and work upward from
checked: the set of already checked directories
Returns:
the path of the furious.yaml file or None if it is not found
"""
directory = start
while directory not in checked:
checked.add(directory)
for fs_yaml_name in FURIOUS_YAML_NAMES:
yaml_path = os.path.join(directory, fs_yaml_name)
if os.path.exists(yaml_path):
return yaml_path
directory = os.path.dirname(directory)
return None | python | def _find_furious_yaml(start, checked):
"""Traverse the directory tree identified by start
until a directory already in checked is encountered or the path
of furious.yaml is found.
Checked is present both to make the loop termination easy
to reason about and so the same directories do not get
rechecked
Args:
start: the path to start looking in and work upward from
checked: the set of already checked directories
Returns:
the path of the furious.yaml file or None if it is not found
"""
directory = start
while directory not in checked:
checked.add(directory)
for fs_yaml_name in FURIOUS_YAML_NAMES:
yaml_path = os.path.join(directory, fs_yaml_name)
if os.path.exists(yaml_path):
return yaml_path
directory = os.path.dirname(directory)
return None | [
"def",
"_find_furious_yaml",
"(",
"start",
",",
"checked",
")",
":",
"directory",
"=",
"start",
"while",
"directory",
"not",
"in",
"checked",
":",
"checked",
".",
"add",
"(",
"directory",
")",
"for",
"fs_yaml_name",
"in",
"FURIOUS_YAML_NAMES",
":",
"yaml_path"... | Traverse the directory tree identified by start
until a directory already in checked is encountered or the path
of furious.yaml is found.
Checked is present both to make the loop termination easy
to reason about and so the same directories do not get
rechecked
Args:
start: the path to start looking in and work upward from
checked: the set of already checked directories
Returns:
the path of the furious.yaml file or None if it is not found | [
"Traverse",
"the",
"directory",
"tree",
"identified",
"by",
"start",
"until",
"a",
"directory",
"already",
"in",
"checked",
"is",
"encountered",
"or",
"the",
"path",
"of",
"furious",
".",
"yaml",
"is",
"found",
"."
] | c29823ec8b98549e7439d7273aa064d1e5830632 | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/config.py#L118-L142 | train | 50,262 |
eumis/pyviews | pyviews/code.py | run_code | def run_code(node: Code, parent_node: Node = None, node_globals: InheritedDict = None, **args): #pylint: disable=unused-argument
'''Executes node content as python module and adds its definitions to globals'''
if not node.xml_node.text:
return
code = node.xml_node.text
try:
globs = node_globals.to_dictionary()
exec(dedent(code), globs) #pylint: disable=exec-used
definitions = [(key, value) for key, value in globs.items() \
if key != '__builtins__' and not node_globals.has_key(key)]
for key, value in definitions:
parent_node.node_globals[key] = value
except SyntaxError as err:
error = _get_compilation_error(code, 'Invalid syntax', err, err.lineno)
raise error from err
except:
info = exc_info()
cause = info[1]
line_number = extract_tb(info[2])[-1][1]
error = _get_compilation_error(code, 'Code execution is failed', cause, line_number)
raise error from cause | python | def run_code(node: Code, parent_node: Node = None, node_globals: InheritedDict = None, **args): #pylint: disable=unused-argument
'''Executes node content as python module and adds its definitions to globals'''
if not node.xml_node.text:
return
code = node.xml_node.text
try:
globs = node_globals.to_dictionary()
exec(dedent(code), globs) #pylint: disable=exec-used
definitions = [(key, value) for key, value in globs.items() \
if key != '__builtins__' and not node_globals.has_key(key)]
for key, value in definitions:
parent_node.node_globals[key] = value
except SyntaxError as err:
error = _get_compilation_error(code, 'Invalid syntax', err, err.lineno)
raise error from err
except:
info = exc_info()
cause = info[1]
line_number = extract_tb(info[2])[-1][1]
error = _get_compilation_error(code, 'Code execution is failed', cause, line_number)
raise error from cause | [
"def",
"run_code",
"(",
"node",
":",
"Code",
",",
"parent_node",
":",
"Node",
"=",
"None",
",",
"node_globals",
":",
"InheritedDict",
"=",
"None",
",",
"*",
"*",
"args",
")",
":",
"#pylint: disable=unused-argument",
"if",
"not",
"node",
".",
"xml_node",
".... | Executes node content as python module and adds its definitions to globals | [
"Executes",
"node",
"content",
"as",
"python",
"module",
"and",
"adds",
"its",
"definitions",
"to",
"globals"
] | 80a868242ee9cdc6f4ded594b3e0544cc238ed55 | https://github.com/eumis/pyviews/blob/80a868242ee9cdc6f4ded594b3e0544cc238ed55/pyviews/code.py#L13-L33 | train | 50,263 |
bcj/AttrDict | attrdict/merge.py | merge | def merge(left, right):
"""
Merge two mappings objects together, combining overlapping Mappings,
and favoring right-values
left: The left Mapping object.
right: The right (favored) Mapping object.
NOTE: This is not commutative (merge(a,b) != merge(b,a)).
"""
merged = {}
left_keys = frozenset(left)
right_keys = frozenset(right)
# Items only in the left Mapping
for key in left_keys - right_keys:
merged[key] = left[key]
# Items only in the right Mapping
for key in right_keys - left_keys:
merged[key] = right[key]
# in both
for key in left_keys & right_keys:
left_value = left[key]
right_value = right[key]
if (isinstance(left_value, Mapping) and
isinstance(right_value, Mapping)): # recursive merge
merged[key] = merge(left_value, right_value)
else: # overwrite with right value
merged[key] = right_value
return merged | python | def merge(left, right):
"""
Merge two mappings objects together, combining overlapping Mappings,
and favoring right-values
left: The left Mapping object.
right: The right (favored) Mapping object.
NOTE: This is not commutative (merge(a,b) != merge(b,a)).
"""
merged = {}
left_keys = frozenset(left)
right_keys = frozenset(right)
# Items only in the left Mapping
for key in left_keys - right_keys:
merged[key] = left[key]
# Items only in the right Mapping
for key in right_keys - left_keys:
merged[key] = right[key]
# in both
for key in left_keys & right_keys:
left_value = left[key]
right_value = right[key]
if (isinstance(left_value, Mapping) and
isinstance(right_value, Mapping)): # recursive merge
merged[key] = merge(left_value, right_value)
else: # overwrite with right value
merged[key] = right_value
return merged | [
"def",
"merge",
"(",
"left",
",",
"right",
")",
":",
"merged",
"=",
"{",
"}",
"left_keys",
"=",
"frozenset",
"(",
"left",
")",
"right_keys",
"=",
"frozenset",
"(",
"right",
")",
"# Items only in the left Mapping",
"for",
"key",
"in",
"left_keys",
"-",
"rig... | Merge two mappings objects together, combining overlapping Mappings,
and favoring right-values
left: The left Mapping object.
right: The right (favored) Mapping object.
NOTE: This is not commutative (merge(a,b) != merge(b,a)). | [
"Merge",
"two",
"mappings",
"objects",
"together",
"combining",
"overlapping",
"Mappings",
"and",
"favoring",
"right",
"-",
"values"
] | 8c1883162178a124ee29144ca7abcd83cbd9d222 | https://github.com/bcj/AttrDict/blob/8c1883162178a124ee29144ca7abcd83cbd9d222/attrdict/merge.py#L10-L44 | train | 50,264 |
ruipgil/changepy | changepy/pelt.py | pelt | def pelt(cost, length, pen=None):
""" PELT algorithm to compute changepoints in time series
Ported from:
https://github.com/STOR-i/Changepoints.jl
https://github.com/rkillick/changepoint/
Reference:
Killick R, Fearnhead P, Eckley IA (2012) Optimal detection
of changepoints with a linear computational cost, JASA
107(500), 1590-1598
Args:
cost (function): cost function, with the following signature,
(int, int) -> float
where the parameters are the start index, and the second
the last index of the segment to compute the cost.
length (int): Data size
pen (float, optional): defaults to log(n)
Returns:
(:obj:`list` of int): List with the indexes of changepoints
"""
if pen is None:
pen = np.log(length)
F = np.zeros(length + 1)
R = np.array([0], dtype=np.int)
candidates = np.zeros(length + 1, dtype=np.int)
F[0] = -pen
for tstar in range(2, length + 1):
cpt_cands = R
seg_costs = np.zeros(len(cpt_cands))
for i in range(0, len(cpt_cands)):
seg_costs[i] = cost(cpt_cands[i], tstar)
F_cost = F[cpt_cands] + seg_costs
F[tstar], tau = find_min(F_cost, pen)
candidates[tstar] = cpt_cands[tau]
ineq_prune = [val < F[tstar] for val in F_cost]
R = [cpt_cands[j] for j, val in enumerate(ineq_prune) if val]
R.append(tstar - 1)
R = np.array(R, dtype=np.int)
last = candidates[-1]
changepoints = [last]
while last > 0:
last = candidates[last]
changepoints.append(last)
return sorted(changepoints) | python | def pelt(cost, length, pen=None):
""" PELT algorithm to compute changepoints in time series
Ported from:
https://github.com/STOR-i/Changepoints.jl
https://github.com/rkillick/changepoint/
Reference:
Killick R, Fearnhead P, Eckley IA (2012) Optimal detection
of changepoints with a linear computational cost, JASA
107(500), 1590-1598
Args:
cost (function): cost function, with the following signature,
(int, int) -> float
where the parameters are the start index, and the second
the last index of the segment to compute the cost.
length (int): Data size
pen (float, optional): defaults to log(n)
Returns:
(:obj:`list` of int): List with the indexes of changepoints
"""
if pen is None:
pen = np.log(length)
F = np.zeros(length + 1)
R = np.array([0], dtype=np.int)
candidates = np.zeros(length + 1, dtype=np.int)
F[0] = -pen
for tstar in range(2, length + 1):
cpt_cands = R
seg_costs = np.zeros(len(cpt_cands))
for i in range(0, len(cpt_cands)):
seg_costs[i] = cost(cpt_cands[i], tstar)
F_cost = F[cpt_cands] + seg_costs
F[tstar], tau = find_min(F_cost, pen)
candidates[tstar] = cpt_cands[tau]
ineq_prune = [val < F[tstar] for val in F_cost]
R = [cpt_cands[j] for j, val in enumerate(ineq_prune) if val]
R.append(tstar - 1)
R = np.array(R, dtype=np.int)
last = candidates[-1]
changepoints = [last]
while last > 0:
last = candidates[last]
changepoints.append(last)
return sorted(changepoints) | [
"def",
"pelt",
"(",
"cost",
",",
"length",
",",
"pen",
"=",
"None",
")",
":",
"if",
"pen",
"is",
"None",
":",
"pen",
"=",
"np",
".",
"log",
"(",
"length",
")",
"F",
"=",
"np",
".",
"zeros",
"(",
"length",
"+",
"1",
")",
"R",
"=",
"np",
".",... | PELT algorithm to compute changepoints in time series
Ported from:
https://github.com/STOR-i/Changepoints.jl
https://github.com/rkillick/changepoint/
Reference:
Killick R, Fearnhead P, Eckley IA (2012) Optimal detection
of changepoints with a linear computational cost, JASA
107(500), 1590-1598
Args:
cost (function): cost function, with the following signature,
(int, int) -> float
where the parameters are the start index, and the second
the last index of the segment to compute the cost.
length (int): Data size
pen (float, optional): defaults to log(n)
Returns:
(:obj:`list` of int): List with the indexes of changepoints | [
"PELT",
"algorithm",
"to",
"compute",
"changepoints",
"in",
"time",
"series"
] | 95a903a24d532d658d4f1775d298c7fd51cdf47c | https://github.com/ruipgil/changepy/blob/95a903a24d532d658d4f1775d298c7fd51cdf47c/changepy/pelt.py#L14-L65 | train | 50,265 |
ruipgil/changepy | changepy/costs.py | normal_mean | def normal_mean(data, variance):
""" Creates a segment cost function for a time series with a
Normal distribution with changing mean
Args:
data (:obj:`list` of float): 1D time series data
variance (float): variance
Returns:
function: Function with signature
(int, int) -> float
where the first arg is the starting index, and the second
is the last arg. Returns the cost of that segment
"""
if not isinstance(data, np.ndarray):
data = np.array(data)
i_variance_2 = 1 / (variance ** 2)
cmm = [0.0]
cmm.extend(np.cumsum(data))
cmm2 = [0.0]
cmm2.extend(np.cumsum(np.abs(data)))
def cost(start, end):
""" Cost function for normal distribution with variable mean
Args:
start (int): start index
end (int): end index
Returns:
float: Cost, from start to end
"""
cmm2_diff = cmm2[end] - cmm2[start]
cmm_diff = pow(cmm[end] - cmm[start], 2)
i_diff = end - start
diff = cmm2_diff - cmm_diff
return (diff/i_diff) * i_variance_2
return cost | python | def normal_mean(data, variance):
""" Creates a segment cost function for a time series with a
Normal distribution with changing mean
Args:
data (:obj:`list` of float): 1D time series data
variance (float): variance
Returns:
function: Function with signature
(int, int) -> float
where the first arg is the starting index, and the second
is the last arg. Returns the cost of that segment
"""
if not isinstance(data, np.ndarray):
data = np.array(data)
i_variance_2 = 1 / (variance ** 2)
cmm = [0.0]
cmm.extend(np.cumsum(data))
cmm2 = [0.0]
cmm2.extend(np.cumsum(np.abs(data)))
def cost(start, end):
""" Cost function for normal distribution with variable mean
Args:
start (int): start index
end (int): end index
Returns:
float: Cost, from start to end
"""
cmm2_diff = cmm2[end] - cmm2[start]
cmm_diff = pow(cmm[end] - cmm[start], 2)
i_diff = end - start
diff = cmm2_diff - cmm_diff
return (diff/i_diff) * i_variance_2
return cost | [
"def",
"normal_mean",
"(",
"data",
",",
"variance",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"np",
".",
"ndarray",
")",
":",
"data",
"=",
"np",
".",
"array",
"(",
"data",
")",
"i_variance_2",
"=",
"1",
"/",
"(",
"variance",
"**",
"2",... | Creates a segment cost function for a time series with a
Normal distribution with changing mean
Args:
data (:obj:`list` of float): 1D time series data
variance (float): variance
Returns:
function: Function with signature
(int, int) -> float
where the first arg is the starting index, and the second
is the last arg. Returns the cost of that segment | [
"Creates",
"a",
"segment",
"cost",
"function",
"for",
"a",
"time",
"series",
"with",
"a",
"Normal",
"distribution",
"with",
"changing",
"mean"
] | 95a903a24d532d658d4f1775d298c7fd51cdf47c | https://github.com/ruipgil/changepy/blob/95a903a24d532d658d4f1775d298c7fd51cdf47c/changepy/costs.py#L3-L41 | train | 50,266 |
ruipgil/changepy | changepy/costs.py | normal_var | def normal_var(data, mean):
""" Creates a segment cost function for a time series with a
Normal distribution with changing variance
Args:
data (:obj:`list` of float): 1D time series data
variance (float): variance
Returns:
function: Function with signature
(int, int) -> float
where the first arg is the starting index, and the second
is the last arg. Returns the cost of that segment
"""
if not isinstance(data, np.ndarray):
data = np.array(data)
cumm = [0.0]
cumm.extend(np.cumsum(np.power(np.abs(data - mean), 2)))
def cost(s, t):
""" Cost function for normal distribution with variable variance
Args:
start (int): start index
end (int): end index
Returns:
float: Cost, from start to end
"""
dist = float(t - s)
diff = cumm[t] - cumm[s]
return dist * np.log(diff/dist)
return cost | python | def normal_var(data, mean):
""" Creates a segment cost function for a time series with a
Normal distribution with changing variance
Args:
data (:obj:`list` of float): 1D time series data
variance (float): variance
Returns:
function: Function with signature
(int, int) -> float
where the first arg is the starting index, and the second
is the last arg. Returns the cost of that segment
"""
if not isinstance(data, np.ndarray):
data = np.array(data)
cumm = [0.0]
cumm.extend(np.cumsum(np.power(np.abs(data - mean), 2)))
def cost(s, t):
""" Cost function for normal distribution with variable variance
Args:
start (int): start index
end (int): end index
Returns:
float: Cost, from start to end
"""
dist = float(t - s)
diff = cumm[t] - cumm[s]
return dist * np.log(diff/dist)
return cost | [
"def",
"normal_var",
"(",
"data",
",",
"mean",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"np",
".",
"ndarray",
")",
":",
"data",
"=",
"np",
".",
"array",
"(",
"data",
")",
"cumm",
"=",
"[",
"0.0",
"]",
"cumm",
".",
"extend",
"(",
"... | Creates a segment cost function for a time series with a
Normal distribution with changing variance
Args:
data (:obj:`list` of float): 1D time series data
variance (float): variance
Returns:
function: Function with signature
(int, int) -> float
where the first arg is the starting index, and the second
is the last arg. Returns the cost of that segment | [
"Creates",
"a",
"segment",
"cost",
"function",
"for",
"a",
"time",
"series",
"with",
"a",
"Normal",
"distribution",
"with",
"changing",
"variance"
] | 95a903a24d532d658d4f1775d298c7fd51cdf47c | https://github.com/ruipgil/changepy/blob/95a903a24d532d658d4f1775d298c7fd51cdf47c/changepy/costs.py#L43-L75 | train | 50,267 |
ruipgil/changepy | changepy/costs.py | normal_meanvar | def normal_meanvar(data):
""" Creates a segment cost function for a time series with a
Normal distribution with changing mean and variance
Args:
data (:obj:`list` of float): 1D time series data
Returns:
function: Function with signature
(int, int) -> float
where the first arg is the starting index, and the second
is the last arg. Returns the cost of that segment
"""
data = np.hstack(([0.0], np.array(data)))
cumm = np.cumsum(data)
cumm_sq = np.cumsum([val**2 for val in data])
def cost(s, t):
""" Cost function for normal distribution with variable variance
Args:
start (int): start index
end (int): end index
Returns:
float: Cost, from start to end
"""
ts_i = 1.0 / (t-s)
mu = (cumm[t] - cumm[s]) * ts_i
sig = (cumm_sq[t] - cumm_sq[s]) * ts_i - mu**2
sig_i = 1.0 / sig
return (t-s) * np.log(sig) + (cumm_sq[t] - cumm_sq[s]) * sig_i - 2*(cumm[t] - cumm[s])*mu*sig_i + ((t-s)*mu**2)*sig_i
return cost | python | def normal_meanvar(data):
""" Creates a segment cost function for a time series with a
Normal distribution with changing mean and variance
Args:
data (:obj:`list` of float): 1D time series data
Returns:
function: Function with signature
(int, int) -> float
where the first arg is the starting index, and the second
is the last arg. Returns the cost of that segment
"""
data = np.hstack(([0.0], np.array(data)))
cumm = np.cumsum(data)
cumm_sq = np.cumsum([val**2 for val in data])
def cost(s, t):
""" Cost function for normal distribution with variable variance
Args:
start (int): start index
end (int): end index
Returns:
float: Cost, from start to end
"""
ts_i = 1.0 / (t-s)
mu = (cumm[t] - cumm[s]) * ts_i
sig = (cumm_sq[t] - cumm_sq[s]) * ts_i - mu**2
sig_i = 1.0 / sig
return (t-s) * np.log(sig) + (cumm_sq[t] - cumm_sq[s]) * sig_i - 2*(cumm[t] - cumm[s])*mu*sig_i + ((t-s)*mu**2)*sig_i
return cost | [
"def",
"normal_meanvar",
"(",
"data",
")",
":",
"data",
"=",
"np",
".",
"hstack",
"(",
"(",
"[",
"0.0",
"]",
",",
"np",
".",
"array",
"(",
"data",
")",
")",
")",
"cumm",
"=",
"np",
".",
"cumsum",
"(",
"data",
")",
"cumm_sq",
"=",
"np",
".",
"... | Creates a segment cost function for a time series with a
Normal distribution with changing mean and variance
Args:
data (:obj:`list` of float): 1D time series data
Returns:
function: Function with signature
(int, int) -> float
where the first arg is the starting index, and the second
is the last arg. Returns the cost of that segment | [
"Creates",
"a",
"segment",
"cost",
"function",
"for",
"a",
"time",
"series",
"with",
"a",
"Normal",
"distribution",
"with",
"changing",
"mean",
"and",
"variance"
] | 95a903a24d532d658d4f1775d298c7fd51cdf47c | https://github.com/ruipgil/changepy/blob/95a903a24d532d658d4f1775d298c7fd51cdf47c/changepy/costs.py#L77-L109 | train | 50,268 |
ruipgil/changepy | changepy/costs.py | poisson | def poisson(data):
""" Creates a segment cost function for a time series with a
poisson distribution with changing mean
Args:
data (:obj:`list` of float): 1D time series data
Returns:
function: Function with signature
(int, int) -> float
where the first arg is the starting index, and the second
is the last arg. Returns the cost of that segment
"""
data = np.hstack(([0.0], np.array(data)))
cumm = np.cumsum(data)
def cost(s, t):
""" Cost function for poisson distribution with changing mean
Args:
start (int): start index
end (int): end index
Returns:
float: Cost, from start to end
"""
diff = cumm[t]-cumm[s]
if diff == 0:
return -2 * diff * (- np.log(t-s) - 1)
else:
return -2 * diff * (np.log(diff) - np.log(t-s) - 1)
return cost | python | def poisson(data):
""" Creates a segment cost function for a time series with a
poisson distribution with changing mean
Args:
data (:obj:`list` of float): 1D time series data
Returns:
function: Function with signature
(int, int) -> float
where the first arg is the starting index, and the second
is the last arg. Returns the cost of that segment
"""
data = np.hstack(([0.0], np.array(data)))
cumm = np.cumsum(data)
def cost(s, t):
""" Cost function for poisson distribution with changing mean
Args:
start (int): start index
end (int): end index
Returns:
float: Cost, from start to end
"""
diff = cumm[t]-cumm[s]
if diff == 0:
return -2 * diff * (- np.log(t-s) - 1)
else:
return -2 * diff * (np.log(diff) - np.log(t-s) - 1)
return cost | [
"def",
"poisson",
"(",
"data",
")",
":",
"data",
"=",
"np",
".",
"hstack",
"(",
"(",
"[",
"0.0",
"]",
",",
"np",
".",
"array",
"(",
"data",
")",
")",
")",
"cumm",
"=",
"np",
".",
"cumsum",
"(",
"data",
")",
"def",
"cost",
"(",
"s",
",",
"t"... | Creates a segment cost function for a time series with a
poisson distribution with changing mean
Args:
data (:obj:`list` of float): 1D time series data
Returns:
function: Function with signature
(int, int) -> float
where the first arg is the starting index, and the second
is the last arg. Returns the cost of that segment | [
"Creates",
"a",
"segment",
"cost",
"function",
"for",
"a",
"time",
"series",
"with",
"a",
"poisson",
"distribution",
"with",
"changing",
"mean"
] | 95a903a24d532d658d4f1775d298c7fd51cdf47c | https://github.com/ruipgil/changepy/blob/95a903a24d532d658d4f1775d298c7fd51cdf47c/changepy/costs.py#L111-L141 | train | 50,269 |
ruipgil/changepy | changepy/costs.py | exponential | def exponential(data):
""" Creates a segment cost function for a time series with a
exponential distribution with changing mean
Args:
data (:obj:`list` of float): 1D time series data
Returns:
function: Function with signature
(int, int) -> float
where the first arg is the starting index, and the second
is the last arg. Returns the cost of that segment
"""
data = np.hstack(([0.0], np.array(data)))
cumm = np.cumsum(data)
def cost(s, t):
""" Cost function for exponential distribution with changing mean
Args:
start (int): start index
end (int): end index
Returns:
float: Cost, from start to end
"""
return -1*(t-s) * (np.log(t-s) - np.log(cumm[t] - cumm[s]))
return cost | python | def exponential(data):
""" Creates a segment cost function for a time series with a
exponential distribution with changing mean
Args:
data (:obj:`list` of float): 1D time series data
Returns:
function: Function with signature
(int, int) -> float
where the first arg is the starting index, and the second
is the last arg. Returns the cost of that segment
"""
data = np.hstack(([0.0], np.array(data)))
cumm = np.cumsum(data)
def cost(s, t):
""" Cost function for exponential distribution with changing mean
Args:
start (int): start index
end (int): end index
Returns:
float: Cost, from start to end
"""
return -1*(t-s) * (np.log(t-s) - np.log(cumm[t] - cumm[s]))
return cost | [
"def",
"exponential",
"(",
"data",
")",
":",
"data",
"=",
"np",
".",
"hstack",
"(",
"(",
"[",
"0.0",
"]",
",",
"np",
".",
"array",
"(",
"data",
")",
")",
")",
"cumm",
"=",
"np",
".",
"cumsum",
"(",
"data",
")",
"def",
"cost",
"(",
"s",
",",
... | Creates a segment cost function for a time series with a
exponential distribution with changing mean
Args:
data (:obj:`list` of float): 1D time series data
Returns:
function: Function with signature
(int, int) -> float
where the first arg is the starting index, and the second
is the last arg. Returns the cost of that segment | [
"Creates",
"a",
"segment",
"cost",
"function",
"for",
"a",
"time",
"series",
"with",
"a",
"exponential",
"distribution",
"with",
"changing",
"mean"
] | 95a903a24d532d658d4f1775d298c7fd51cdf47c | https://github.com/ruipgil/changepy/blob/95a903a24d532d658d4f1775d298c7fd51cdf47c/changepy/costs.py#L143-L169 | train | 50,270 |
openaddresses/pyesridump | esridump/dumper.py | EsriDumper._get_layer_min_max | def _get_layer_min_max(self, oid_field_name):
""" Find the min and max values for the OID field. """
query_args = self._build_query_args({
'f': 'json',
'outFields': '',
'outStatistics': json.dumps([
dict(statisticType='min', onStatisticField=oid_field_name, outStatisticFieldName='THE_MIN'),
dict(statisticType='max', onStatisticField=oid_field_name, outStatisticFieldName='THE_MAX'),
], separators=(',', ':'))
})
headers = self._build_headers()
url = self._build_url('/query')
response = self._request('GET', url, params=query_args, headers=headers)
metadata = self._handle_esri_errors(response, "Could not retrieve min/max oid values")
# Some servers (specifically version 10.11, it seems) will respond with SQL statements
# for the attribute names rather than the requested field names, so pick the min and max
# deliberately rather than relying on the names.
min_max_values = metadata['features'][0]['attributes'].values()
min_value = min(min_max_values)
max_value = max(min_max_values)
query_args = self._build_query_args({
'f': 'json',
'outFields': '*',
'outStatistics': json.dumps([
dict(statisticType='min', onStatisticField=oid_field_name, outStatisticFieldName='THE_MIN'),
dict(statisticType='max', onStatisticField=oid_field_name, outStatisticFieldName='THE_MAX'),
], separators=(',', ':'))
})
query_args = self._build_query_args({
'where': '{} = {} OR {} = {}'.format(
oid_field_name,
min_value,
oid_field_name,
max_value
),
'returnIdsOnly': 'true',
'f': 'json',
})
headers = self._build_headers()
url = self._build_url('/query')
response = self._request('GET', url, params=query_args, headers=headers)
oid_data = self._handle_esri_errors(response, "Could not check min/max values")
if not oid_data or not oid_data.get('objectIds') or min_value not in oid_data['objectIds'] or max_value not in oid_data['objectIds']:
raise EsriDownloadError('Server returned invalid min/max')
return (min_value, max_value) | python | def _get_layer_min_max(self, oid_field_name):
""" Find the min and max values for the OID field. """
query_args = self._build_query_args({
'f': 'json',
'outFields': '',
'outStatistics': json.dumps([
dict(statisticType='min', onStatisticField=oid_field_name, outStatisticFieldName='THE_MIN'),
dict(statisticType='max', onStatisticField=oid_field_name, outStatisticFieldName='THE_MAX'),
], separators=(',', ':'))
})
headers = self._build_headers()
url = self._build_url('/query')
response = self._request('GET', url, params=query_args, headers=headers)
metadata = self._handle_esri_errors(response, "Could not retrieve min/max oid values")
# Some servers (specifically version 10.11, it seems) will respond with SQL statements
# for the attribute names rather than the requested field names, so pick the min and max
# deliberately rather than relying on the names.
min_max_values = metadata['features'][0]['attributes'].values()
min_value = min(min_max_values)
max_value = max(min_max_values)
query_args = self._build_query_args({
'f': 'json',
'outFields': '*',
'outStatistics': json.dumps([
dict(statisticType='min', onStatisticField=oid_field_name, outStatisticFieldName='THE_MIN'),
dict(statisticType='max', onStatisticField=oid_field_name, outStatisticFieldName='THE_MAX'),
], separators=(',', ':'))
})
query_args = self._build_query_args({
'where': '{} = {} OR {} = {}'.format(
oid_field_name,
min_value,
oid_field_name,
max_value
),
'returnIdsOnly': 'true',
'f': 'json',
})
headers = self._build_headers()
url = self._build_url('/query')
response = self._request('GET', url, params=query_args, headers=headers)
oid_data = self._handle_esri_errors(response, "Could not check min/max values")
if not oid_data or not oid_data.get('objectIds') or min_value not in oid_data['objectIds'] or max_value not in oid_data['objectIds']:
raise EsriDownloadError('Server returned invalid min/max')
return (min_value, max_value) | [
"def",
"_get_layer_min_max",
"(",
"self",
",",
"oid_field_name",
")",
":",
"query_args",
"=",
"self",
".",
"_build_query_args",
"(",
"{",
"'f'",
":",
"'json'",
",",
"'outFields'",
":",
"''",
",",
"'outStatistics'",
":",
"json",
".",
"dumps",
"(",
"[",
"dic... | Find the min and max values for the OID field. | [
"Find",
"the",
"min",
"and",
"max",
"values",
"for",
"the",
"OID",
"field",
"."
] | 378155816559134b8d2b3de0d0f2fddc74f23fcd | https://github.com/openaddresses/pyesridump/blob/378155816559134b8d2b3de0d0f2fddc74f23fcd/esridump/dumper.py#L166-L211 | train | 50,271 |
mdsol/rwslib | rwslib/rws_requests/__init__.py | make_url | def make_url(*args, **kwargs):
"""Makes a URL from component parts"""
base = "/".join(args)
if kwargs:
return "%s?%s" % (base, urlencode(kwargs))
else:
return base | python | def make_url(*args, **kwargs):
"""Makes a URL from component parts"""
base = "/".join(args)
if kwargs:
return "%s?%s" % (base, urlencode(kwargs))
else:
return base | [
"def",
"make_url",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"base",
"=",
"\"/\"",
".",
"join",
"(",
"args",
")",
"if",
"kwargs",
":",
"return",
"\"%s?%s\"",
"%",
"(",
"base",
",",
"urlencode",
"(",
"kwargs",
")",
")",
"else",
":",
"re... | Makes a URL from component parts | [
"Makes",
"a",
"URL",
"from",
"component",
"parts"
] | 1a86bc072d408c009ed1de8bf6e98a1769f54d18 | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/rws_requests/__init__.py#L56-L62 | train | 50,272 |
mdsol/rwslib | rwslib/rws_requests/__init__.py | QueryOptionGetRequest._querystring | def _querystring(self):
"""Get additional keyword arguments"""
kw = {}
for key in self.KNOWN_QUERY_OPTIONS:
val = getattr(self, key)
if val is not None:
kw[key] = val
return kw | python | def _querystring(self):
"""Get additional keyword arguments"""
kw = {}
for key in self.KNOWN_QUERY_OPTIONS:
val = getattr(self, key)
if val is not None:
kw[key] = val
return kw | [
"def",
"_querystring",
"(",
"self",
")",
":",
"kw",
"=",
"{",
"}",
"for",
"key",
"in",
"self",
".",
"KNOWN_QUERY_OPTIONS",
":",
"val",
"=",
"getattr",
"(",
"self",
",",
"key",
")",
"if",
"val",
"is",
"not",
"None",
":",
"kw",
"[",
"key",
"]",
"="... | Get additional keyword arguments | [
"Get",
"additional",
"keyword",
"arguments"
] | 1a86bc072d408c009ed1de8bf6e98a1769f54d18 | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/rws_requests/__init__.py#L130-L138 | train | 50,273 |
mdsol/rwslib | rwslib/rws_requests/biostats_gateway.py | check_dataset_format | def check_dataset_format(ds_format):
"""
Ensure dataset format is XML or CSV
:param str ds_format: Format of the Dataset (expected to be one of `csv` or `xml`)
"""
if ds_format.lower() not in DATASET_FORMATS.keys():
raise ValueError(
"dataset_format is expected to be one of %s. '%s' is not valid"
% (", ".join(DATASET_FORMATS.keys()), ds_format)
) | python | def check_dataset_format(ds_format):
"""
Ensure dataset format is XML or CSV
:param str ds_format: Format of the Dataset (expected to be one of `csv` or `xml`)
"""
if ds_format.lower() not in DATASET_FORMATS.keys():
raise ValueError(
"dataset_format is expected to be one of %s. '%s' is not valid"
% (", ".join(DATASET_FORMATS.keys()), ds_format)
) | [
"def",
"check_dataset_format",
"(",
"ds_format",
")",
":",
"if",
"ds_format",
".",
"lower",
"(",
")",
"not",
"in",
"DATASET_FORMATS",
".",
"keys",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"dataset_format is expected to be one of %s. '%s' is not valid\"",
"%",
"(... | Ensure dataset format is XML or CSV
:param str ds_format: Format of the Dataset (expected to be one of `csv` or `xml`) | [
"Ensure",
"dataset",
"format",
"is",
"XML",
"or",
"CSV"
] | 1a86bc072d408c009ed1de8bf6e98a1769f54d18 | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/rws_requests/biostats_gateway.py#L16-L26 | train | 50,274 |
mdsol/rwslib | rwslib/rws_requests/biostats_gateway.py | dataset_format_to_extension | def dataset_format_to_extension(ds_format):
"""
Get the preferred Dataset format extension
:param str ds_format: Format of the Dataset (expected to be one of `csv` or `xml`)
:rtype: str
"""
try:
return DATASET_FORMATS[ds_format]
except KeyError:
raise ValueError(
"dataset_format is expected to be one of %s. '%s' is not valid"
% (", ".join(DATASET_FORMATS.keys()), ds_format)
) | python | def dataset_format_to_extension(ds_format):
"""
Get the preferred Dataset format extension
:param str ds_format: Format of the Dataset (expected to be one of `csv` or `xml`)
:rtype: str
"""
try:
return DATASET_FORMATS[ds_format]
except KeyError:
raise ValueError(
"dataset_format is expected to be one of %s. '%s' is not valid"
% (", ".join(DATASET_FORMATS.keys()), ds_format)
) | [
"def",
"dataset_format_to_extension",
"(",
"ds_format",
")",
":",
"try",
":",
"return",
"DATASET_FORMATS",
"[",
"ds_format",
"]",
"except",
"KeyError",
":",
"raise",
"ValueError",
"(",
"\"dataset_format is expected to be one of %s. '%s' is not valid\"",
"%",
"(",
"\", \""... | Get the preferred Dataset format extension
:param str ds_format: Format of the Dataset (expected to be one of `csv` or `xml`)
:rtype: str | [
"Get",
"the",
"preferred",
"Dataset",
"format",
"extension"
] | 1a86bc072d408c009ed1de8bf6e98a1769f54d18 | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/rws_requests/biostats_gateway.py#L29-L42 | train | 50,275 |
mdsol/rwslib | rwslib/extras/rwscmd/rwscmd.py | get_data | def get_data(ctx, study, environment, subject):
"""
Call rwscmd_getdata custom dataset to retrieve currently enterable, empty fields
"""
cfg = GetDataConfigurableDataset(GET_DATA_DATASET,
study,
environment,
subject,
params=dict(IncludeIDs=0,
IncludeValues=0))
# path = "datasets/{}?StudyOID={}&SubjectKey={}" \
# "&IncludeIDs=0&IncludeValues=0".format(GET_DATA_DATASET, studyoid, subject)
# url = make_url(ctx.obj['RWS'].base_url, path)
if ctx.obj['VERBOSE']:
click.echo('Getting data list')
# Get the client instance
client = ctx.obj['RWS'] #: type: RWSConnection
# Client rolls in the base_url
resp = client.send_request(cfg)
# resp = requests.get(url, auth=HTTPBasicAuth(ctx.obj['USERNAME'], ctx.obj['PASSWORD']))
if client.last_result.status_code != 200:
click.echo(client.last_result.text)
return xml_pretty_print(resp) | python | def get_data(ctx, study, environment, subject):
"""
Call rwscmd_getdata custom dataset to retrieve currently enterable, empty fields
"""
cfg = GetDataConfigurableDataset(GET_DATA_DATASET,
study,
environment,
subject,
params=dict(IncludeIDs=0,
IncludeValues=0))
# path = "datasets/{}?StudyOID={}&SubjectKey={}" \
# "&IncludeIDs=0&IncludeValues=0".format(GET_DATA_DATASET, studyoid, subject)
# url = make_url(ctx.obj['RWS'].base_url, path)
if ctx.obj['VERBOSE']:
click.echo('Getting data list')
# Get the client instance
client = ctx.obj['RWS'] #: type: RWSConnection
# Client rolls in the base_url
resp = client.send_request(cfg)
# resp = requests.get(url, auth=HTTPBasicAuth(ctx.obj['USERNAME'], ctx.obj['PASSWORD']))
if client.last_result.status_code != 200:
click.echo(client.last_result.text)
return xml_pretty_print(resp) | [
"def",
"get_data",
"(",
"ctx",
",",
"study",
",",
"environment",
",",
"subject",
")",
":",
"cfg",
"=",
"GetDataConfigurableDataset",
"(",
"GET_DATA_DATASET",
",",
"study",
",",
"environment",
",",
"subject",
",",
"params",
"=",
"dict",
"(",
"IncludeIDs",
"="... | Call rwscmd_getdata custom dataset to retrieve currently enterable, empty fields | [
"Call",
"rwscmd_getdata",
"custom",
"dataset",
"to",
"retrieve",
"currently",
"enterable",
"empty",
"fields"
] | 1a86bc072d408c009ed1de8bf6e98a1769f54d18 | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/rwscmd/rwscmd.py#L66-L91 | train | 50,276 |
mdsol/rwslib | rwslib/extras/rwscmd/rwscmd.py | rws_call | def rws_call(ctx, method, default_attr=None):
"""Make request to RWS"""
try:
response = ctx.obj['RWS'].send_request(method)
if ctx.obj['RAW']: # use response from RWS
result = ctx.obj['RWS'].last_result.text
elif default_attr is not None: # human-readable summary
result = ""
for item in response:
result = result + item.__dict__[default_attr] + "\n"
else: # use response from RWS
result = ctx.obj['RWS'].last_result.text
if ctx.obj['OUTPUT']: # write to file
ctx.obj['OUTPUT'].write(result.encode('utf-8'))
else: # echo
click.echo(result)
except RWSException as e:
click.echo(str(e)) | python | def rws_call(ctx, method, default_attr=None):
"""Make request to RWS"""
try:
response = ctx.obj['RWS'].send_request(method)
if ctx.obj['RAW']: # use response from RWS
result = ctx.obj['RWS'].last_result.text
elif default_attr is not None: # human-readable summary
result = ""
for item in response:
result = result + item.__dict__[default_attr] + "\n"
else: # use response from RWS
result = ctx.obj['RWS'].last_result.text
if ctx.obj['OUTPUT']: # write to file
ctx.obj['OUTPUT'].write(result.encode('utf-8'))
else: # echo
click.echo(result)
except RWSException as e:
click.echo(str(e)) | [
"def",
"rws_call",
"(",
"ctx",
",",
"method",
",",
"default_attr",
"=",
"None",
")",
":",
"try",
":",
"response",
"=",
"ctx",
".",
"obj",
"[",
"'RWS'",
"]",
".",
"send_request",
"(",
"method",
")",
"if",
"ctx",
".",
"obj",
"[",
"'RAW'",
"]",
":",
... | Make request to RWS | [
"Make",
"request",
"to",
"RWS"
] | 1a86bc072d408c009ed1de8bf6e98a1769f54d18 | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/rwscmd/rwscmd.py#L94-L114 | train | 50,277 |
mdsol/rwslib | rwslib/extras/rwscmd/rwscmd.py | post | def post(ctx, odm):
"""Post ODM clinical data"""
try:
ctx.obj['RWS'].send_request(PostDataRequest(odm.read()))
if ctx.obj['RAW']:
click.echo(ctx.obj['RWS'].last_result.text)
except RWSException as e:
click.echo(e.message) | python | def post(ctx, odm):
"""Post ODM clinical data"""
try:
ctx.obj['RWS'].send_request(PostDataRequest(odm.read()))
if ctx.obj['RAW']:
click.echo(ctx.obj['RWS'].last_result.text)
except RWSException as e:
click.echo(e.message) | [
"def",
"post",
"(",
"ctx",
",",
"odm",
")",
":",
"try",
":",
"ctx",
".",
"obj",
"[",
"'RWS'",
"]",
".",
"send_request",
"(",
"PostDataRequest",
"(",
"odm",
".",
"read",
"(",
")",
")",
")",
"if",
"ctx",
".",
"obj",
"[",
"'RAW'",
"]",
":",
"click... | Post ODM clinical data | [
"Post",
"ODM",
"clinical",
"data"
] | 1a86bc072d408c009ed1de8bf6e98a1769f54d18 | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/rwscmd/rwscmd.py#L150-L157 | train | 50,278 |
mdsol/rwslib | rwslib/extras/rwscmd/rwscmd.py | direct | def direct(ctx, path):
"""Make direct call to RWS, bypassing rwslib"""
try:
url = make_url(ctx.obj['RWS'].base_url, path)
resp = requests.get(url, auth=HTTPBasicAuth(ctx.obj['USERNAME'], ctx.obj['PASSWORD']))
click.echo(resp.text)
except RWSException as e:
click.echo(e.message)
except requests.exceptions.HTTPError as e:
click.echo(e.message) | python | def direct(ctx, path):
"""Make direct call to RWS, bypassing rwslib"""
try:
url = make_url(ctx.obj['RWS'].base_url, path)
resp = requests.get(url, auth=HTTPBasicAuth(ctx.obj['USERNAME'], ctx.obj['PASSWORD']))
click.echo(resp.text)
except RWSException as e:
click.echo(e.message)
except requests.exceptions.HTTPError as e:
click.echo(e.message) | [
"def",
"direct",
"(",
"ctx",
",",
"path",
")",
":",
"try",
":",
"url",
"=",
"make_url",
"(",
"ctx",
".",
"obj",
"[",
"'RWS'",
"]",
".",
"base_url",
",",
"path",
")",
"resp",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"auth",
"=",
"HTTPBasicAut... | Make direct call to RWS, bypassing rwslib | [
"Make",
"direct",
"call",
"to",
"RWS",
"bypassing",
"rwslib"
] | 1a86bc072d408c009ed1de8bf6e98a1769f54d18 | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/rwscmd/rwscmd.py#L183-L192 | train | 50,279 |
mdsol/rwslib | rwslib/extras/rwscmd/rwscmd.py | autofill | def autofill(ctx, steps, metadata, fixed, study, environment, subject):
"""Request enterable data for a subject, generate data values and post back to Rave.
Requires 'rwscmd_getdata' configurable dataset to be installed on the Rave URL."""
if metadata is not None: # Read metadata from file, if supplied
odm_metadata = metadata.read()
meta_v = etree.fromstring(odm_metadata).find('.//' + E_ODM.METADATA_VERSION.value).get(A_ODM.OID.value)
else:
odm_metadata = None
meta_v = None
fixed_values = {}
if fixed is not None: # Read fixed values from file, if supplied
for f in fixed:
oid, value = f.decode().split(',')
fixed_values[oid] = value
if ctx.obj['VERBOSE']:
click.echo('Fixing {} to value: {}'.format(oid, value))
try:
for n in range(0, steps):
if ctx.obj['VERBOSE']:
click.echo('Step {}'.format(str(n + 1)))
# Get currently enterable fields for this subject
subject_data = get_data(ctx, study, environment, subject)
subject_data_odm = etree.fromstring(subject_data)
if subject_data_odm.find('.//' + E_ODM.CLINICAL_DATA.value) is None:
if ctx.obj['VERBOSE']:
click.echo('No data found')
break
# Get the metadata version for the subject
subject_meta_v = subject_data_odm.find('.//' + E_ODM.CLINICAL_DATA.value).get(
A_ODM.METADATA_VERSION_OID.value)
if subject_meta_v is None:
if ctx.obj['VERBOSE']:
click.echo('Subject not found')
break
# If no metadata supplied, or versions don't match, retrieve metadata from RWS
if meta_v != subject_meta_v:
if ctx.obj['VERBOSE']:
click.echo('Getting metadata version {}'.format(subject_meta_v))
ctx.obj['RWS'].send_request(StudyVersionRequest(study, subject_meta_v))
odm_metadata = ctx.obj['RWS'].last_result.text
meta_v = subject_meta_v
# Generate data values to fill in empty fields
if ctx.obj['VERBOSE']:
click.echo('Generating data')
scr = Scramble(odm_metadata)
odm = scr.fill_empty(fixed_values, subject_data)
# If new data values, post to RWS
if etree.fromstring(odm).find('.//' + E_ODM.ITEM_DATA.value) is None:
if ctx.obj['VERBOSE']:
click.echo('No data to send')
break
ctx.obj['RWS'].send_request(PostDataRequest(odm))
if ctx.obj['RAW']:
click.echo(ctx.obj['RWS'].last_result.text)
except RWSException as e:
click.echo(e.rws_error)
except requests.exceptions.HTTPError as e:
click.echo(e.strerror) | python | def autofill(ctx, steps, metadata, fixed, study, environment, subject):
"""Request enterable data for a subject, generate data values and post back to Rave.
Requires 'rwscmd_getdata' configurable dataset to be installed on the Rave URL."""
if metadata is not None: # Read metadata from file, if supplied
odm_metadata = metadata.read()
meta_v = etree.fromstring(odm_metadata).find('.//' + E_ODM.METADATA_VERSION.value).get(A_ODM.OID.value)
else:
odm_metadata = None
meta_v = None
fixed_values = {}
if fixed is not None: # Read fixed values from file, if supplied
for f in fixed:
oid, value = f.decode().split(',')
fixed_values[oid] = value
if ctx.obj['VERBOSE']:
click.echo('Fixing {} to value: {}'.format(oid, value))
try:
for n in range(0, steps):
if ctx.obj['VERBOSE']:
click.echo('Step {}'.format(str(n + 1)))
# Get currently enterable fields for this subject
subject_data = get_data(ctx, study, environment, subject)
subject_data_odm = etree.fromstring(subject_data)
if subject_data_odm.find('.//' + E_ODM.CLINICAL_DATA.value) is None:
if ctx.obj['VERBOSE']:
click.echo('No data found')
break
# Get the metadata version for the subject
subject_meta_v = subject_data_odm.find('.//' + E_ODM.CLINICAL_DATA.value).get(
A_ODM.METADATA_VERSION_OID.value)
if subject_meta_v is None:
if ctx.obj['VERBOSE']:
click.echo('Subject not found')
break
# If no metadata supplied, or versions don't match, retrieve metadata from RWS
if meta_v != subject_meta_v:
if ctx.obj['VERBOSE']:
click.echo('Getting metadata version {}'.format(subject_meta_v))
ctx.obj['RWS'].send_request(StudyVersionRequest(study, subject_meta_v))
odm_metadata = ctx.obj['RWS'].last_result.text
meta_v = subject_meta_v
# Generate data values to fill in empty fields
if ctx.obj['VERBOSE']:
click.echo('Generating data')
scr = Scramble(odm_metadata)
odm = scr.fill_empty(fixed_values, subject_data)
# If new data values, post to RWS
if etree.fromstring(odm).find('.//' + E_ODM.ITEM_DATA.value) is None:
if ctx.obj['VERBOSE']:
click.echo('No data to send')
break
ctx.obj['RWS'].send_request(PostDataRequest(odm))
if ctx.obj['RAW']:
click.echo(ctx.obj['RWS'].last_result.text)
except RWSException as e:
click.echo(e.rws_error)
except requests.exceptions.HTTPError as e:
click.echo(e.strerror) | [
"def",
"autofill",
"(",
"ctx",
",",
"steps",
",",
"metadata",
",",
"fixed",
",",
"study",
",",
"environment",
",",
"subject",
")",
":",
"if",
"metadata",
"is",
"not",
"None",
":",
"# Read metadata from file, if supplied",
"odm_metadata",
"=",
"metadata",
".",
... | Request enterable data for a subject, generate data values and post back to Rave.
Requires 'rwscmd_getdata' configurable dataset to be installed on the Rave URL. | [
"Request",
"enterable",
"data",
"for",
"a",
"subject",
"generate",
"data",
"values",
"and",
"post",
"back",
"to",
"Rave",
".",
"Requires",
"rwscmd_getdata",
"configurable",
"dataset",
"to",
"be",
"installed",
"on",
"the",
"Rave",
"URL",
"."
] | 1a86bc072d408c009ed1de8bf6e98a1769f54d18 | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/rwscmd/rwscmd.py#L205-L274 | train | 50,280 |
mdsol/rwslib | rwslib/builders/metadata.py | MdsolCheckAction.check_action_type | def check_action_type(self, value):
"""Set the value for the CheckActionType, validating input"""
if value is not None:
if not isinstance(value, ActionType):
raise AttributeError("Invalid check action %s" % value)
self._check_action_type = value | python | def check_action_type(self, value):
"""Set the value for the CheckActionType, validating input"""
if value is not None:
if not isinstance(value, ActionType):
raise AttributeError("Invalid check action %s" % value)
self._check_action_type = value | [
"def",
"check_action_type",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"ActionType",
")",
":",
"raise",
"AttributeError",
"(",
"\"Invalid check action %s\"",
"%",
"value",
")",
... | Set the value for the CheckActionType, validating input | [
"Set",
"the",
"value",
"for",
"the",
"CheckActionType",
"validating",
"input"
] | 1a86bc072d408c009ed1de8bf6e98a1769f54d18 | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/builders/metadata.py#L2180-L2185 | train | 50,281 |
mdsol/rwslib | rwslib/builders/clinicaldata.py | Annotation.annotation_id | def annotation_id(self, value):
"""Set ID for Annotation"""
if value in [None, ''] or str(value).strip() == '':
raise AttributeError("Invalid ID value supplied")
self._id = value | python | def annotation_id(self, value):
"""Set ID for Annotation"""
if value in [None, ''] or str(value).strip() == '':
raise AttributeError("Invalid ID value supplied")
self._id = value | [
"def",
"annotation_id",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"in",
"[",
"None",
",",
"''",
"]",
"or",
"str",
"(",
"value",
")",
".",
"strip",
"(",
")",
"==",
"''",
":",
"raise",
"AttributeError",
"(",
"\"Invalid ID value supplied\"",
")"... | Set ID for Annotation | [
"Set",
"ID",
"for",
"Annotation"
] | 1a86bc072d408c009ed1de8bf6e98a1769f54d18 | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/builders/clinicaldata.py#L571-L575 | train | 50,282 |
mdsol/rwslib | rwslib/builders/clinicaldata.py | Comment.sponsor_or_site | def sponsor_or_site(self, value):
"""Set Originator with validation of input"""
if value not in Comment.VALID_SPONSOR_OR_SITE_RESPONSES:
raise AttributeError("%s sponsor_or_site value of %s is not valid" % (self.__class__.__name__,
value))
self._sponsor_or_site = value | python | def sponsor_or_site(self, value):
"""Set Originator with validation of input"""
if value not in Comment.VALID_SPONSOR_OR_SITE_RESPONSES:
raise AttributeError("%s sponsor_or_site value of %s is not valid" % (self.__class__.__name__,
value))
self._sponsor_or_site = value | [
"def",
"sponsor_or_site",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"not",
"in",
"Comment",
".",
"VALID_SPONSOR_OR_SITE_RESPONSES",
":",
"raise",
"AttributeError",
"(",
"\"%s sponsor_or_site value of %s is not valid\"",
"%",
"(",
"self",
".",
"__class__",
... | Set Originator with validation of input | [
"Set",
"Originator",
"with",
"validation",
"of",
"input"
] | 1a86bc072d408c009ed1de8bf6e98a1769f54d18 | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/builders/clinicaldata.py#L704-L709 | train | 50,283 |
mdsol/rwslib | rwslib/builders/clinicaldata.py | MdsolQuery.status | def status(self, value):
"""Set Query Status"""
if value is not None:
if not isinstance(value, QueryStatusType):
raise AttributeError("%s action type is invalid in mdsol:Query." % (value,))
self._status = value | python | def status(self, value):
"""Set Query Status"""
if value is not None:
if not isinstance(value, QueryStatusType):
raise AttributeError("%s action type is invalid in mdsol:Query." % (value,))
self._status = value | [
"def",
"status",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"QueryStatusType",
")",
":",
"raise",
"AttributeError",
"(",
"\"%s action type is invalid in mdsol:Query.\"",
"%",
"(",... | Set Query Status | [
"Set",
"Query",
"Status"
] | 1a86bc072d408c009ed1de8bf6e98a1769f54d18 | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/builders/clinicaldata.py#L1216-L1221 | train | 50,284 |
mdsol/rwslib | rwslib/builders/core.py | ODM.getroot | def getroot(self):
"""Build XML object, return the root"""
builder = ET.TreeBuilder()
self.build(builder)
return builder.close() | python | def getroot(self):
"""Build XML object, return the root"""
builder = ET.TreeBuilder()
self.build(builder)
return builder.close() | [
"def",
"getroot",
"(",
"self",
")",
":",
"builder",
"=",
"ET",
".",
"TreeBuilder",
"(",
")",
"self",
".",
"build",
"(",
"builder",
")",
"return",
"builder",
".",
"close",
"(",
")"
] | Build XML object, return the root | [
"Build",
"XML",
"object",
"return",
"the",
"root"
] | 1a86bc072d408c009ed1de8bf6e98a1769f54d18 | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/builders/core.py#L78-L82 | train | 50,285 |
mdsol/rwslib | rwslib/builders/core.py | ODM.build | def build(self, builder):
"""Build XML object, return the root, this is a copy for consistency and testing"""
params = dict(ODMVersion="1.3",
FileType=self.filetype,
CreationDateTime=self.creationdatetime,
Originator=self.originator,
FileOID=self.fileoid,
xmlns="http://www.cdisc.org/ns/odm/v1.3",
)
if self.granularity_type:
params['Granularity'] = self.granularity_type.value
if self.source_system:
params['SourceSystem'] = self.source_system
if self.source_system_version:
params['SourceSystemVersion'] = self.source_system_version
params['xmlns:mdsol'] = "http://www.mdsol.com/ns/odm/metadata"
if self.description:
params['Description'] = self.description
builder.start("ODM", params)
# Ask the children
if self.study is not None:
self.study.build(builder)
if self.clinical_data:
for clinical_data in self.clinical_data:
clinical_data.build(builder)
if self.admindata is not None:
self.admindata.build(builder)
builder.end("ODM")
return builder.close() | python | def build(self, builder):
"""Build XML object, return the root, this is a copy for consistency and testing"""
params = dict(ODMVersion="1.3",
FileType=self.filetype,
CreationDateTime=self.creationdatetime,
Originator=self.originator,
FileOID=self.fileoid,
xmlns="http://www.cdisc.org/ns/odm/v1.3",
)
if self.granularity_type:
params['Granularity'] = self.granularity_type.value
if self.source_system:
params['SourceSystem'] = self.source_system
if self.source_system_version:
params['SourceSystemVersion'] = self.source_system_version
params['xmlns:mdsol'] = "http://www.mdsol.com/ns/odm/metadata"
if self.description:
params['Description'] = self.description
builder.start("ODM", params)
# Ask the children
if self.study is not None:
self.study.build(builder)
if self.clinical_data:
for clinical_data in self.clinical_data:
clinical_data.build(builder)
if self.admindata is not None:
self.admindata.build(builder)
builder.end("ODM")
return builder.close() | [
"def",
"build",
"(",
"self",
",",
"builder",
")",
":",
"params",
"=",
"dict",
"(",
"ODMVersion",
"=",
"\"1.3\"",
",",
"FileType",
"=",
"self",
".",
"filetype",
",",
"CreationDateTime",
"=",
"self",
".",
"creationdatetime",
",",
"Originator",
"=",
"self",
... | Build XML object, return the root, this is a copy for consistency and testing | [
"Build",
"XML",
"object",
"return",
"the",
"root",
"this",
"is",
"a",
"copy",
"for",
"consistency",
"and",
"testing"
] | 1a86bc072d408c009ed1de8bf6e98a1769f54d18 | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/builders/core.py#L84-L119 | train | 50,286 |
mdsol/rwslib | rwslib/builders/modm.py | MODMMixin.add_attribute | def add_attribute(self, attribute, value):
"""
Add an attribute to the current instance
:param str attribute: Attribute name
:type value: Union[datetime,bool,str]
:param value: Attribute value
"""
class_name = self.__class__.__name__
if class_name.startswith('ItemData'):
# ItemData* Elements
class_name = 'ItemData'
if attribute not in MODMExtensionRegistry[class_name].value:
raise ValueError("Can't add {} to {}".format(attribute, self.__class__.__name__))
self.attributes.append(MODMAttribute(attribute, value)) | python | def add_attribute(self, attribute, value):
"""
Add an attribute to the current instance
:param str attribute: Attribute name
:type value: Union[datetime,bool,str]
:param value: Attribute value
"""
class_name = self.__class__.__name__
if class_name.startswith('ItemData'):
# ItemData* Elements
class_name = 'ItemData'
if attribute not in MODMExtensionRegistry[class_name].value:
raise ValueError("Can't add {} to {}".format(attribute, self.__class__.__name__))
self.attributes.append(MODMAttribute(attribute, value)) | [
"def",
"add_attribute",
"(",
"self",
",",
"attribute",
",",
"value",
")",
":",
"class_name",
"=",
"self",
".",
"__class__",
".",
"__name__",
"if",
"class_name",
".",
"startswith",
"(",
"'ItemData'",
")",
":",
"# ItemData* Elements",
"class_name",
"=",
"'ItemDa... | Add an attribute to the current instance
:param str attribute: Attribute name
:type value: Union[datetime,bool,str]
:param value: Attribute value | [
"Add",
"an",
"attribute",
"to",
"the",
"current",
"instance"
] | 1a86bc072d408c009ed1de8bf6e98a1769f54d18 | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/builders/modm.py#L103-L117 | train | 50,287 |
mdsol/rwslib | rwslib/builders/modm.py | MODMMixin.mixin_params | def mixin_params(self, params):
"""
Merge in the MdsolAttribute for the passed parameter
:param dict params: dictionary of object parameters
"""
if not isinstance(params, (dict,)):
raise AttributeError("Cannot mixin to object of type {}".format(type(params)))
for attribute in self.attributes:
params.update({attribute.tag: attribute.value}) | python | def mixin_params(self, params):
"""
Merge in the MdsolAttribute for the passed parameter
:param dict params: dictionary of object parameters
"""
if not isinstance(params, (dict,)):
raise AttributeError("Cannot mixin to object of type {}".format(type(params)))
for attribute in self.attributes:
params.update({attribute.tag: attribute.value}) | [
"def",
"mixin_params",
"(",
"self",
",",
"params",
")",
":",
"if",
"not",
"isinstance",
"(",
"params",
",",
"(",
"dict",
",",
")",
")",
":",
"raise",
"AttributeError",
"(",
"\"Cannot mixin to object of type {}\"",
".",
"format",
"(",
"type",
"(",
"params",
... | Merge in the MdsolAttribute for the passed parameter
:param dict params: dictionary of object parameters | [
"Merge",
"in",
"the",
"MdsolAttribute",
"for",
"the",
"passed",
"parameter"
] | 1a86bc072d408c009ed1de8bf6e98a1769f54d18 | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/builders/modm.py#L122-L131 | train | 50,288 |
mdsol/rwslib | rwslib/builders/modm.py | LastUpdateMixin.last_update_time | def last_update_time(self, value):
"""
Setter for the last_update_time attribute
:param datetime.datetime value: value to set for the element
"""
if isinstance(value, (datetime.datetime,)):
self._last_update_time = value
else:
raise ValueError("Expect last_update_time to be a datetime") | python | def last_update_time(self, value):
"""
Setter for the last_update_time attribute
:param datetime.datetime value: value to set for the element
"""
if isinstance(value, (datetime.datetime,)):
self._last_update_time = value
else:
raise ValueError("Expect last_update_time to be a datetime") | [
"def",
"last_update_time",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"datetime",
".",
"datetime",
",",
")",
")",
":",
"self",
".",
"_last_update_time",
"=",
"value",
"else",
":",
"raise",
"ValueError",
"(",
"\"Expec... | Setter for the last_update_time attribute
:param datetime.datetime value: value to set for the element | [
"Setter",
"for",
"the",
"last_update_time",
"attribute"
] | 1a86bc072d408c009ed1de8bf6e98a1769f54d18 | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/builders/modm.py#L151-L160 | train | 50,289 |
mdsol/rwslib | rwslib/rwsobjects.py | RWSStudyListItem.fromElement | def fromElement(cls, elem):
"""
Read properties from an XML Element to build a StudyList Item
:param lxml.etree.Element elem: The source Study XML Element
.. code-block:: xml
<Study OID="Fixitol(Dev)" mdsol:ProjectType="GlobalLibraryVolume">
<GlobalVariables>
<StudyName>Fixitol (Dev)</StudyName>
<StudyDescription/>
<ProtocolName>Fixitol</ProtocolName>
</GlobalVariables>
</Study>
"""
e_global_variables = elem.find(ODM_NS + "GlobalVariables")
studyname = e_global_variables.find(ODM_NS + "StudyName").text
protocolname = e_global_variables.find(ODM_NS + "ProtocolName").text
self = cls(
oid=elem.get("OID"),
projecttype=elem.get(MEDI_NS + "ProjectType", "Project"),
studyname=studyname,
protocolname=protocolname,
environment=getEnvironmentFromNameAndProtocol(studyname, protocolname),
)
return self | python | def fromElement(cls, elem):
"""
Read properties from an XML Element to build a StudyList Item
:param lxml.etree.Element elem: The source Study XML Element
.. code-block:: xml
<Study OID="Fixitol(Dev)" mdsol:ProjectType="GlobalLibraryVolume">
<GlobalVariables>
<StudyName>Fixitol (Dev)</StudyName>
<StudyDescription/>
<ProtocolName>Fixitol</ProtocolName>
</GlobalVariables>
</Study>
"""
e_global_variables = elem.find(ODM_NS + "GlobalVariables")
studyname = e_global_variables.find(ODM_NS + "StudyName").text
protocolname = e_global_variables.find(ODM_NS + "ProtocolName").text
self = cls(
oid=elem.get("OID"),
projecttype=elem.get(MEDI_NS + "ProjectType", "Project"),
studyname=studyname,
protocolname=protocolname,
environment=getEnvironmentFromNameAndProtocol(studyname, protocolname),
)
return self | [
"def",
"fromElement",
"(",
"cls",
",",
"elem",
")",
":",
"e_global_variables",
"=",
"elem",
".",
"find",
"(",
"ODM_NS",
"+",
"\"GlobalVariables\"",
")",
"studyname",
"=",
"e_global_variables",
".",
"find",
"(",
"ODM_NS",
"+",
"\"StudyName\"",
")",
".",
"text... | Read properties from an XML Element to build a StudyList Item
:param lxml.etree.Element elem: The source Study XML Element
.. code-block:: xml
<Study OID="Fixitol(Dev)" mdsol:ProjectType="GlobalLibraryVolume">
<GlobalVariables>
<StudyName>Fixitol (Dev)</StudyName>
<StudyDescription/>
<ProtocolName>Fixitol</ProtocolName>
</GlobalVariables>
</Study> | [
"Read",
"properties",
"from",
"an",
"XML",
"Element",
"to",
"build",
"a",
"StudyList",
"Item"
] | 1a86bc072d408c009ed1de8bf6e98a1769f54d18 | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/rwsobjects.py#L307-L335 | train | 50,290 |
mdsol/rwslib | rwslib/rwsobjects.py | MetaDataVersion.fromElement | def fromElement(cls, elem):
"""
Read properties from a MetaDataVersion element
:param lxml.etree._Element elem: Source etree Element
"""
self = cls()
self.oid = elem.get("OID")
self.name = elem.get("Name")
return self | python | def fromElement(cls, elem):
"""
Read properties from a MetaDataVersion element
:param lxml.etree._Element elem: Source etree Element
"""
self = cls()
self.oid = elem.get("OID")
self.name = elem.get("Name")
return self | [
"def",
"fromElement",
"(",
"cls",
",",
"elem",
")",
":",
"self",
"=",
"cls",
"(",
")",
"self",
".",
"oid",
"=",
"elem",
".",
"get",
"(",
"\"OID\"",
")",
"self",
".",
"name",
"=",
"elem",
".",
"get",
"(",
"\"Name\"",
")",
"return",
"self"
] | Read properties from a MetaDataVersion element
:param lxml.etree._Element elem: Source etree Element | [
"Read",
"properties",
"from",
"a",
"MetaDataVersion",
"element"
] | 1a86bc072d408c009ed1de8bf6e98a1769f54d18 | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/rwsobjects.py#L391-L402 | train | 50,291 |
mdsol/rwslib | rwslib/rwsobjects.py | RWSSubjectListItem.fromElement | def fromElement(cls, elem):
"""
Read properties from an XML Element
"""
self = cls()
self.studyoid = elem.get("StudyOID")
self.metadataversionoid = elem.get("MetaDataVersionOID")
e_subjectdata = elem.findall(ODM_NS + "SubjectData")[0]
self.subjectkey = e_subjectdata.get("SubjectKey")
e_siteref = e_subjectdata.findall(ODM_NS + "SiteRef")[0]
self.locationoid = e_siteref.get("LocationOID")
e_links = e_subjectdata.findall(MEDI_NS + "Link")
for e_link in e_links:
self.links.append(e_link.get(XLINK_NS + "href"))
decodes = {"yes": True, "no": False, "": None}
for prop in RWSSubjectListItem.STATUS_PROPERTIES:
val = e_subjectdata.get(MEDI_NS + prop, "").lower()
setattr(self, prop.lower(), decodes.get(val, val))
# By default we only get back active and non-deleted subjects
self.active = decodes[
e_subjectdata.get(MEDI_NS + "SubjectActive", "yes").lower()
]
self.deleted = decodes[e_subjectdata.get(MEDI_NS + "Deleted", "no").lower()]
return self | python | def fromElement(cls, elem):
"""
Read properties from an XML Element
"""
self = cls()
self.studyoid = elem.get("StudyOID")
self.metadataversionoid = elem.get("MetaDataVersionOID")
e_subjectdata = elem.findall(ODM_NS + "SubjectData")[0]
self.subjectkey = e_subjectdata.get("SubjectKey")
e_siteref = e_subjectdata.findall(ODM_NS + "SiteRef")[0]
self.locationoid = e_siteref.get("LocationOID")
e_links = e_subjectdata.findall(MEDI_NS + "Link")
for e_link in e_links:
self.links.append(e_link.get(XLINK_NS + "href"))
decodes = {"yes": True, "no": False, "": None}
for prop in RWSSubjectListItem.STATUS_PROPERTIES:
val = e_subjectdata.get(MEDI_NS + prop, "").lower()
setattr(self, prop.lower(), decodes.get(val, val))
# By default we only get back active and non-deleted subjects
self.active = decodes[
e_subjectdata.get(MEDI_NS + "SubjectActive", "yes").lower()
]
self.deleted = decodes[e_subjectdata.get(MEDI_NS + "Deleted", "no").lower()]
return self | [
"def",
"fromElement",
"(",
"cls",
",",
"elem",
")",
":",
"self",
"=",
"cls",
"(",
")",
"self",
".",
"studyoid",
"=",
"elem",
".",
"get",
"(",
"\"StudyOID\"",
")",
"self",
".",
"metadataversionoid",
"=",
"elem",
".",
"get",
"(",
"\"MetaDataVersionOID\"",
... | Read properties from an XML Element | [
"Read",
"properties",
"from",
"an",
"XML",
"Element"
] | 1a86bc072d408c009ed1de8bf6e98a1769f54d18 | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/rwsobjects.py#L573-L600 | train | 50,292 |
mdsol/rwslib | rwslib/builders/common.py | make_element | def make_element(builder, tag, content):
"""Make an element with this tag and text content"""
builder.start(tag, {})
builder.data(content) # Must be UTF-8 encoded
builder.end(tag) | python | def make_element(builder, tag, content):
"""Make an element with this tag and text content"""
builder.start(tag, {})
builder.data(content) # Must be UTF-8 encoded
builder.end(tag) | [
"def",
"make_element",
"(",
"builder",
",",
"tag",
",",
"content",
")",
":",
"builder",
".",
"start",
"(",
"tag",
",",
"{",
"}",
")",
"builder",
".",
"data",
"(",
"content",
")",
"# Must be UTF-8 encoded",
"builder",
".",
"end",
"(",
"tag",
")"
] | Make an element with this tag and text content | [
"Make",
"an",
"element",
"with",
"this",
"tag",
"and",
"text",
"content"
] | 1a86bc072d408c009ed1de8bf6e98a1769f54d18 | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/builders/common.py#L56-L60 | train | 50,293 |
mdsol/rwslib | rwslib/builders/common.py | ODMElement.set_single_attribute | def set_single_attribute(self, other, trigger_klass, property_name):
"""Used to set guard the setting of an attribute which is singular and can't be set twice"""
if isinstance(other, trigger_klass):
# Check property exists
if not hasattr(self, property_name):
raise AttributeError("%s has no property %s" % (self.__class__.__name__, property_name))
if getattr(self, property_name) is None:
setattr(self, property_name, other)
else:
raise ValueError(
'%s already has a %s element set.' % (self.__class__.__name__, other.__class__.__name__,)) | python | def set_single_attribute(self, other, trigger_klass, property_name):
"""Used to set guard the setting of an attribute which is singular and can't be set twice"""
if isinstance(other, trigger_klass):
# Check property exists
if not hasattr(self, property_name):
raise AttributeError("%s has no property %s" % (self.__class__.__name__, property_name))
if getattr(self, property_name) is None:
setattr(self, property_name, other)
else:
raise ValueError(
'%s already has a %s element set.' % (self.__class__.__name__, other.__class__.__name__,)) | [
"def",
"set_single_attribute",
"(",
"self",
",",
"other",
",",
"trigger_klass",
",",
"property_name",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"trigger_klass",
")",
":",
"# Check property exists",
"if",
"not",
"hasattr",
"(",
"self",
",",
"property_name"... | Used to set guard the setting of an attribute which is singular and can't be set twice | [
"Used",
"to",
"set",
"guard",
"the",
"setting",
"of",
"an",
"attribute",
"which",
"is",
"singular",
"and",
"can",
"t",
"be",
"set",
"twice"
] | 1a86bc072d408c009ed1de8bf6e98a1769f54d18 | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/builders/common.py#L93-L106 | train | 50,294 |
mdsol/rwslib | rwslib/builders/common.py | ODMElement.set_list_attribute | def set_list_attribute(self, other, trigger_klass, property_name):
"""Used to set guard the setting of a list attribute, ensuring the same element is not added twice."""
# Check property exists
if isinstance(other, trigger_klass):
if not hasattr(self, property_name):
raise AttributeError("%s has no property %s" % (self.__class__.__name__, property_name))
val = getattr(self, property_name, [])
if other in val:
raise ValueError("%s already exists in %s" % (other.__class__.__name__, self.__class__.__name__))
else:
val.append(other)
setattr(self, property_name, val) | python | def set_list_attribute(self, other, trigger_klass, property_name):
"""Used to set guard the setting of a list attribute, ensuring the same element is not added twice."""
# Check property exists
if isinstance(other, trigger_klass):
if not hasattr(self, property_name):
raise AttributeError("%s has no property %s" % (self.__class__.__name__, property_name))
val = getattr(self, property_name, [])
if other in val:
raise ValueError("%s already exists in %s" % (other.__class__.__name__, self.__class__.__name__))
else:
val.append(other)
setattr(self, property_name, val) | [
"def",
"set_list_attribute",
"(",
"self",
",",
"other",
",",
"trigger_klass",
",",
"property_name",
")",
":",
"# Check property exists",
"if",
"isinstance",
"(",
"other",
",",
"trigger_klass",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"property_name",
... | Used to set guard the setting of a list attribute, ensuring the same element is not added twice. | [
"Used",
"to",
"set",
"guard",
"the",
"setting",
"of",
"a",
"list",
"attribute",
"ensuring",
"the",
"same",
"element",
"is",
"not",
"added",
"twice",
"."
] | 1a86bc072d408c009ed1de8bf6e98a1769f54d18 | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/builders/common.py#L108-L121 | train | 50,295 |
mdsol/rwslib | rwslib/extras/audit_event/main.py | ODMAdapter.get_next_start_id | def get_next_start_id(self):
"""If link for next result set has been passed, extract it and get the next set start id"""
link = self.rws_connection.last_result.links.get("next", None)
if link:
link = link['url']
p = urlparse(link)
start_id = int(parse_qs(p.query)['startid'][0])
return start_id
return None | python | def get_next_start_id(self):
"""If link for next result set has been passed, extract it and get the next set start id"""
link = self.rws_connection.last_result.links.get("next", None)
if link:
link = link['url']
p = urlparse(link)
start_id = int(parse_qs(p.query)['startid'][0])
return start_id
return None | [
"def",
"get_next_start_id",
"(",
"self",
")",
":",
"link",
"=",
"self",
".",
"rws_connection",
".",
"last_result",
".",
"links",
".",
"get",
"(",
"\"next\"",
",",
"None",
")",
"if",
"link",
":",
"link",
"=",
"link",
"[",
"'url'",
"]",
"p",
"=",
"urlp... | If link for next result set has been passed, extract it and get the next set start id | [
"If",
"link",
"for",
"next",
"result",
"set",
"has",
"been",
"passed",
"extract",
"it",
"and",
"get",
"the",
"next",
"set",
"start",
"id"
] | 1a86bc072d408c009ed1de8bf6e98a1769f54d18 | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/audit_event/main.py#L19-L28 | train | 50,296 |
mdsol/rwslib | rwslib/builders_example.py | example_clinical_data | def example_clinical_data(study_name, environment):
"""Test demonstrating building clinical data"""
odm = ODM("test system")(
ClinicalData("Mediflex", "DEV")(
SubjectData("MDSOL", "IJS TEST4", transaction_type="Insert")(
StudyEventData("SUBJECT")(
FormData("EN", transaction_type="Update")(
# Although Signature is ODM1.3.1 RWS does not support it inbound currently
# RWSBuilders do support outbound generation of Signature at FormData level
# Signature()(
# UserRef("isparks"),
# LocationRef("MDSOL"),
# SignatureRef("APPROVED"),
# DateTimeStamp(datetime(2015, 9, 11, 10, 15, 22, 80))
# ),
ItemGroupData()(
ItemData("SUBJINIT", "AAA")(
AuditRecord(edit_point=AuditRecord.EDIT_DATA_MANAGEMENT,
used_imputation_method= False,
identifier='X2011',
include_file_oid=False)(
UserRef("isparks"),
LocationRef("MDSOL"),
ReasonForChange("Data Entry Error"),
DateTimeStamp(datetime(2015, 9, 11, 10, 15, 22, 80))
),
MdsolQuery(value="Subject initials should be 2 chars only.", recipient="Site from System",
status=QueryStatusType.Open)
),
ItemData("SUBJID", '001')
)
)
)
)
)
)
return odm | python | def example_clinical_data(study_name, environment):
"""Test demonstrating building clinical data"""
odm = ODM("test system")(
ClinicalData("Mediflex", "DEV")(
SubjectData("MDSOL", "IJS TEST4", transaction_type="Insert")(
StudyEventData("SUBJECT")(
FormData("EN", transaction_type="Update")(
# Although Signature is ODM1.3.1 RWS does not support it inbound currently
# RWSBuilders do support outbound generation of Signature at FormData level
# Signature()(
# UserRef("isparks"),
# LocationRef("MDSOL"),
# SignatureRef("APPROVED"),
# DateTimeStamp(datetime(2015, 9, 11, 10, 15, 22, 80))
# ),
ItemGroupData()(
ItemData("SUBJINIT", "AAA")(
AuditRecord(edit_point=AuditRecord.EDIT_DATA_MANAGEMENT,
used_imputation_method= False,
identifier='X2011',
include_file_oid=False)(
UserRef("isparks"),
LocationRef("MDSOL"),
ReasonForChange("Data Entry Error"),
DateTimeStamp(datetime(2015, 9, 11, 10, 15, 22, 80))
),
MdsolQuery(value="Subject initials should be 2 chars only.", recipient="Site from System",
status=QueryStatusType.Open)
),
ItemData("SUBJID", '001')
)
)
)
)
)
)
return odm | [
"def",
"example_clinical_data",
"(",
"study_name",
",",
"environment",
")",
":",
"odm",
"=",
"ODM",
"(",
"\"test system\"",
")",
"(",
"ClinicalData",
"(",
"\"Mediflex\"",
",",
"\"DEV\"",
")",
"(",
"SubjectData",
"(",
"\"MDSOL\"",
",",
"\"IJS TEST4\"",
",",
"tr... | Test demonstrating building clinical data | [
"Test",
"demonstrating",
"building",
"clinical",
"data"
] | 1a86bc072d408c009ed1de8bf6e98a1769f54d18 | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/builders_example.py#L9-L46 | train | 50,297 |
mdsol/rwslib | rwslib/extras/local_cv.py | BaseDBAdapter.getCSVReader | def getCSVReader(data, reader_type=csv.DictReader):
"""Take a Rave CSV output ending with a line with just EOF on it and return a DictReader"""
f = StringIO(data[:-4]) # Remove \nEOF
return reader_type(f) | python | def getCSVReader(data, reader_type=csv.DictReader):
"""Take a Rave CSV output ending with a line with just EOF on it and return a DictReader"""
f = StringIO(data[:-4]) # Remove \nEOF
return reader_type(f) | [
"def",
"getCSVReader",
"(",
"data",
",",
"reader_type",
"=",
"csv",
".",
"DictReader",
")",
":",
"f",
"=",
"StringIO",
"(",
"data",
"[",
":",
"-",
"4",
"]",
")",
"# Remove \\nEOF",
"return",
"reader_type",
"(",
"f",
")"
] | Take a Rave CSV output ending with a line with just EOF on it and return a DictReader | [
"Take",
"a",
"Rave",
"CSV",
"output",
"ending",
"with",
"a",
"line",
"with",
"just",
"EOF",
"on",
"it",
"and",
"return",
"a",
"DictReader"
] | 1a86bc072d408c009ed1de8bf6e98a1769f54d18 | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/local_cv.py#L51-L54 | train | 50,298 |
mdsol/rwslib | rwslib/extras/local_cv.py | BaseDBAdapter._setDatasets | def _setDatasets(self, metadata):
"""Extract dataset definitions from CSV metadata"""
# Pull the lot into a list
cols = list(self.getCSVReader(metadata))
# sort the cols by view name and ordinal (they come sorted, but lets be sure)
cols.sort(key=lambda x: [x['viewname'], int(x['ordinal'])])
# Now group them by their viewname
for key, grp in groupby(cols, key=lambda x: x["viewname"]):
self.datasets[key] = list(grp) | python | def _setDatasets(self, metadata):
"""Extract dataset definitions from CSV metadata"""
# Pull the lot into a list
cols = list(self.getCSVReader(metadata))
# sort the cols by view name and ordinal (they come sorted, but lets be sure)
cols.sort(key=lambda x: [x['viewname'], int(x['ordinal'])])
# Now group them by their viewname
for key, grp in groupby(cols, key=lambda x: x["viewname"]):
self.datasets[key] = list(grp) | [
"def",
"_setDatasets",
"(",
"self",
",",
"metadata",
")",
":",
"# Pull the lot into a list",
"cols",
"=",
"list",
"(",
"self",
".",
"getCSVReader",
"(",
"metadata",
")",
")",
"# sort the cols by view name and ordinal (they come sorted, but lets be sure)",
"cols",
".",
"... | Extract dataset definitions from CSV metadata | [
"Extract",
"dataset",
"definitions",
"from",
"CSV",
"metadata"
] | 1a86bc072d408c009ed1de8bf6e98a1769f54d18 | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/local_cv.py#L63-L73 | train | 50,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.