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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
VikParuchuri/percept | percept/workflows/base.py | BaseWorkflow.read_input | def read_input(self, input_cls, filename, **kwargs):
"""
Read in input and do some minimal preformatting
input_cls - the class to use to read the input
filename - input filename
"""
input_inst = input_cls()
input_inst.read_input(filename)
return input_inst.get_data() | python | def read_input(self, input_cls, filename, **kwargs):
"""
Read in input and do some minimal preformatting
input_cls - the class to use to read the input
filename - input filename
"""
input_inst = input_cls()
input_inst.read_input(filename)
return input_inst.get_data() | [
"def",
"read_input",
"(",
"self",
",",
"input_cls",
",",
"filename",
",",
"*",
"*",
"kwargs",
")",
":",
"input_inst",
"=",
"input_cls",
"(",
")",
"input_inst",
".",
"read_input",
"(",
"filename",
")",
"return",
"input_inst",
".",
"get_data",
"(",
")"
] | Read in input and do some minimal preformatting
input_cls - the class to use to read the input
filename - input filename | [
"Read",
"in",
"input",
"and",
"do",
"some",
"minimal",
"preformatting",
"input_cls",
"-",
"the",
"class",
"to",
"use",
"to",
"read",
"the",
"input",
"filename",
"-",
"input",
"filename"
] | 90304ba82053e2a9ad2bacaab3479403d3923bcf | https://github.com/VikParuchuri/percept/blob/90304ba82053e2a9ad2bacaab3479403d3923bcf/percept/workflows/base.py#L138-L146 | train | 54,700 |
VikParuchuri/percept | percept/workflows/base.py | BaseWorkflow.reformat_file | def reformat_file(self, input_file, input_format, output_format):
"""
Reformat input data files to a format the tasks can use
"""
#Return none if input_file or input_format do not exist
if input_file is None or input_format is None:
return None
#Find the needed input class and read the input stream
try:
input_cls = self.find_input(input_format)
input_inst = input_cls()
except TypeError:
#Return none if input_cls is a Nonetype
return None
#If the input file cannot be found, return None
try:
input_inst.read_input(self.absolute_filepath(input_file))
except IOError:
return None
formatter = find_needed_formatter(input_format, output_format)
if formatter is None:
raise Exception("Cannot find a formatter that can convert from {0} to {1}".format(self.input_format, output_format))
formatter_inst = formatter()
formatter_inst.read_input(input_inst.get_data(), input_format)
data = formatter_inst.get_data(output_format)
return data | python | def reformat_file(self, input_file, input_format, output_format):
"""
Reformat input data files to a format the tasks can use
"""
#Return none if input_file or input_format do not exist
if input_file is None or input_format is None:
return None
#Find the needed input class and read the input stream
try:
input_cls = self.find_input(input_format)
input_inst = input_cls()
except TypeError:
#Return none if input_cls is a Nonetype
return None
#If the input file cannot be found, return None
try:
input_inst.read_input(self.absolute_filepath(input_file))
except IOError:
return None
formatter = find_needed_formatter(input_format, output_format)
if formatter is None:
raise Exception("Cannot find a formatter that can convert from {0} to {1}".format(self.input_format, output_format))
formatter_inst = formatter()
formatter_inst.read_input(input_inst.get_data(), input_format)
data = formatter_inst.get_data(output_format)
return data | [
"def",
"reformat_file",
"(",
"self",
",",
"input_file",
",",
"input_format",
",",
"output_format",
")",
":",
"#Return none if input_file or input_format do not exist",
"if",
"input_file",
"is",
"None",
"or",
"input_format",
"is",
"None",
":",
"return",
"None",
"#Find ... | Reformat input data files to a format the tasks can use | [
"Reformat",
"input",
"data",
"files",
"to",
"a",
"format",
"the",
"tasks",
"can",
"use"
] | 90304ba82053e2a9ad2bacaab3479403d3923bcf | https://github.com/VikParuchuri/percept/blob/90304ba82053e2a9ad2bacaab3479403d3923bcf/percept/workflows/base.py#L148-L174 | train | 54,701 |
VikParuchuri/percept | percept/workflows/base.py | BaseWorkflow.reformat_input | def reformat_input(self, **kwargs):
"""
Reformat input data
"""
reformatted_input = {}
needed_formats = []
for task_cls in self.tasks:
needed_formats.append(task_cls.data_format)
self.needed_formats = list(set(needed_formats))
for output_format in self.needed_formats:
reformatted_input.update(
{
output_format :
{
'data' : self.reformat_file(self.input_file, self.input_format, output_format),
'target' : self.reformat_file(self.target_file, self.target_format, output_format)
}
}
)
return reformatted_input | python | def reformat_input(self, **kwargs):
"""
Reformat input data
"""
reformatted_input = {}
needed_formats = []
for task_cls in self.tasks:
needed_formats.append(task_cls.data_format)
self.needed_formats = list(set(needed_formats))
for output_format in self.needed_formats:
reformatted_input.update(
{
output_format :
{
'data' : self.reformat_file(self.input_file, self.input_format, output_format),
'target' : self.reformat_file(self.target_file, self.target_format, output_format)
}
}
)
return reformatted_input | [
"def",
"reformat_input",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"reformatted_input",
"=",
"{",
"}",
"needed_formats",
"=",
"[",
"]",
"for",
"task_cls",
"in",
"self",
".",
"tasks",
":",
"needed_formats",
".",
"append",
"(",
"task_cls",
".",
"data... | Reformat input data | [
"Reformat",
"input",
"data"
] | 90304ba82053e2a9ad2bacaab3479403d3923bcf | https://github.com/VikParuchuri/percept/blob/90304ba82053e2a9ad2bacaab3479403d3923bcf/percept/workflows/base.py#L196-L216 | train | 54,702 |
dpnova/python-xprintidle | xprintidle.py | _create_modulename | def _create_modulename(cdef_sources, source, sys_version):
"""
This is the same as CFFI's create modulename except we don't include the
CFFI version.
"""
key = '\x00'.join([sys_version[:3], source, cdef_sources])
key = key.encode('utf-8')
k1 = hex(binascii.crc32(key[0::2]) & 0xffffffff)
k1 = k1.lstrip('0x').rstrip('L')
k2 = hex(binascii.crc32(key[1::2]) & 0xffffffff)
k2 = k2.lstrip('0').rstrip('L')
return '_xprintidle_cffi_{0}{1}'.format(k1, k2) | python | def _create_modulename(cdef_sources, source, sys_version):
"""
This is the same as CFFI's create modulename except we don't include the
CFFI version.
"""
key = '\x00'.join([sys_version[:3], source, cdef_sources])
key = key.encode('utf-8')
k1 = hex(binascii.crc32(key[0::2]) & 0xffffffff)
k1 = k1.lstrip('0x').rstrip('L')
k2 = hex(binascii.crc32(key[1::2]) & 0xffffffff)
k2 = k2.lstrip('0').rstrip('L')
return '_xprintidle_cffi_{0}{1}'.format(k1, k2) | [
"def",
"_create_modulename",
"(",
"cdef_sources",
",",
"source",
",",
"sys_version",
")",
":",
"key",
"=",
"'\\x00'",
".",
"join",
"(",
"[",
"sys_version",
"[",
":",
"3",
"]",
",",
"source",
",",
"cdef_sources",
"]",
")",
"key",
"=",
"key",
".",
"encod... | This is the same as CFFI's create modulename except we don't include the
CFFI version. | [
"This",
"is",
"the",
"same",
"as",
"CFFI",
"s",
"create",
"modulename",
"except",
"we",
"don",
"t",
"include",
"the",
"CFFI",
"version",
"."
] | cc8f3c13a5dd578073d20f3d42208fcb8e1983b8 | https://github.com/dpnova/python-xprintidle/blob/cc8f3c13a5dd578073d20f3d42208fcb8e1983b8/xprintidle.py#L10-L21 | train | 54,703 |
liip/requests_gpgauthlib | requests_gpgauthlib/gpgauth_session.py | GPGAuthSession.is_authenticated_with_token | def is_authenticated_with_token(self):
""" GPGAuth Stage 2 """
""" Send back the token to the server to get auth cookie """
server_login_response = post_log_in(
self,
keyid=self.user_fingerprint,
user_token_result=self.user_auth_token
)
if not check_server_login_stage2_response(server_login_response):
raise GPGAuthStage2Exception("Login endpoint wrongly formatted")
self.cookies.save(ignore_discard=True)
logger.info('is_authenticated_with_token: OK')
return True | python | def is_authenticated_with_token(self):
""" GPGAuth Stage 2 """
""" Send back the token to the server to get auth cookie """
server_login_response = post_log_in(
self,
keyid=self.user_fingerprint,
user_token_result=self.user_auth_token
)
if not check_server_login_stage2_response(server_login_response):
raise GPGAuthStage2Exception("Login endpoint wrongly formatted")
self.cookies.save(ignore_discard=True)
logger.info('is_authenticated_with_token: OK')
return True | [
"def",
"is_authenticated_with_token",
"(",
"self",
")",
":",
"\"\"\" Send back the token to the server to get auth cookie \"\"\"",
"server_login_response",
"=",
"post_log_in",
"(",
"self",
",",
"keyid",
"=",
"self",
".",
"user_fingerprint",
",",
"user_token_result",
"=",
"s... | GPGAuth Stage 2 | [
"GPGAuth",
"Stage",
"2"
] | 017711dfff6cc74cc4cb78ee05dec5e38564987e | https://github.com/liip/requests_gpgauthlib/blob/017711dfff6cc74cc4cb78ee05dec5e38564987e/requests_gpgauthlib/gpgauth_session.py#L208-L222 | train | 54,704 |
VikParuchuri/percept | percept/utils/workflow.py | WorkflowLoader.save | def save(self, obj, run_id):
"""
Save a workflow
obj - instance of a workflow to save
run_id - unique id to give the run
"""
id_code = self.generate_save_identifier(obj, run_id)
self.store.save(obj, id_code) | python | def save(self, obj, run_id):
"""
Save a workflow
obj - instance of a workflow to save
run_id - unique id to give the run
"""
id_code = self.generate_save_identifier(obj, run_id)
self.store.save(obj, id_code) | [
"def",
"save",
"(",
"self",
",",
"obj",
",",
"run_id",
")",
":",
"id_code",
"=",
"self",
".",
"generate_save_identifier",
"(",
"obj",
",",
"run_id",
")",
"self",
".",
"store",
".",
"save",
"(",
"obj",
",",
"id_code",
")"
] | Save a workflow
obj - instance of a workflow to save
run_id - unique id to give the run | [
"Save",
"a",
"workflow",
"obj",
"-",
"instance",
"of",
"a",
"workflow",
"to",
"save",
"run_id",
"-",
"unique",
"id",
"to",
"give",
"the",
"run"
] | 90304ba82053e2a9ad2bacaab3479403d3923bcf | https://github.com/VikParuchuri/percept/blob/90304ba82053e2a9ad2bacaab3479403d3923bcf/percept/utils/workflow.py#L30-L37 | train | 54,705 |
VikParuchuri/percept | percept/utils/workflow.py | WorkflowWrapper.setup_tasks | def setup_tasks(self, tasks):
"""
Find task classes from category.namespace.name strings
tasks - list of strings
"""
task_classes = []
for task in tasks:
category, namespace, name = task.split(".")
try:
cls = find_in_registry(category=category, namespace=namespace, name=name)[0]
except TypeError:
log.error("Could not find the task with category.namespace.name {0}".format(task))
raise TypeError
task_classes.append(cls)
self.tasks = task_classes | python | def setup_tasks(self, tasks):
"""
Find task classes from category.namespace.name strings
tasks - list of strings
"""
task_classes = []
for task in tasks:
category, namespace, name = task.split(".")
try:
cls = find_in_registry(category=category, namespace=namespace, name=name)[0]
except TypeError:
log.error("Could not find the task with category.namespace.name {0}".format(task))
raise TypeError
task_classes.append(cls)
self.tasks = task_classes | [
"def",
"setup_tasks",
"(",
"self",
",",
"tasks",
")",
":",
"task_classes",
"=",
"[",
"]",
"for",
"task",
"in",
"tasks",
":",
"category",
",",
"namespace",
",",
"name",
"=",
"task",
".",
"split",
"(",
"\".\"",
")",
"try",
":",
"cls",
"=",
"find_in_reg... | Find task classes from category.namespace.name strings
tasks - list of strings | [
"Find",
"task",
"classes",
"from",
"category",
".",
"namespace",
".",
"name",
"strings",
"tasks",
"-",
"list",
"of",
"strings"
] | 90304ba82053e2a9ad2bacaab3479403d3923bcf | https://github.com/VikParuchuri/percept/blob/90304ba82053e2a9ad2bacaab3479403d3923bcf/percept/utils/workflow.py#L100-L114 | train | 54,706 |
VikParuchuri/percept | percept/utils/workflow.py | WorkflowWrapper.initialize_workflow | def initialize_workflow(self, workflow):
"""
Create a workflow
workflow - a workflow class
"""
self.workflow = workflow()
self.workflow.tasks = self.tasks
self.workflow.input_file = self.input_file
self.workflow.input_format = self.input_format
self.workflow.target_file = self.target_file
self.workflow.target_format = self.target_format
self.workflow.run_id = self.run_id
self.workflow.setup() | python | def initialize_workflow(self, workflow):
"""
Create a workflow
workflow - a workflow class
"""
self.workflow = workflow()
self.workflow.tasks = self.tasks
self.workflow.input_file = self.input_file
self.workflow.input_format = self.input_format
self.workflow.target_file = self.target_file
self.workflow.target_format = self.target_format
self.workflow.run_id = self.run_id
self.workflow.setup() | [
"def",
"initialize_workflow",
"(",
"self",
",",
"workflow",
")",
":",
"self",
".",
"workflow",
"=",
"workflow",
"(",
")",
"self",
".",
"workflow",
".",
"tasks",
"=",
"self",
".",
"tasks",
"self",
".",
"workflow",
".",
"input_file",
"=",
"self",
".",
"i... | Create a workflow
workflow - a workflow class | [
"Create",
"a",
"workflow",
"workflow",
"-",
"a",
"workflow",
"class"
] | 90304ba82053e2a9ad2bacaab3479403d3923bcf | https://github.com/VikParuchuri/percept/blob/90304ba82053e2a9ad2bacaab3479403d3923bcf/percept/utils/workflow.py#L116-L130 | train | 54,707 |
VikParuchuri/percept | percept/utils/workflow.py | WorkflowWrapper.reformat_filepath | def reformat_filepath(self, config_file, filename):
"""
Convert relative paths in config file to absolute
"""
if not filename.startswith("/"):
filename = self.config_file_format.format(config_file, filename)
return filename | python | def reformat_filepath(self, config_file, filename):
"""
Convert relative paths in config file to absolute
"""
if not filename.startswith("/"):
filename = self.config_file_format.format(config_file, filename)
return filename | [
"def",
"reformat_filepath",
"(",
"self",
",",
"config_file",
",",
"filename",
")",
":",
"if",
"not",
"filename",
".",
"startswith",
"(",
"\"/\"",
")",
":",
"filename",
"=",
"self",
".",
"config_file_format",
".",
"format",
"(",
"config_file",
",",
"filename"... | Convert relative paths in config file to absolute | [
"Convert",
"relative",
"paths",
"in",
"config",
"file",
"to",
"absolute"
] | 90304ba82053e2a9ad2bacaab3479403d3923bcf | https://github.com/VikParuchuri/percept/blob/90304ba82053e2a9ad2bacaab3479403d3923bcf/percept/utils/workflow.py#L132-L138 | train | 54,708 |
studionow/pybrightcove | pybrightcove/connection.py | item_lister | def item_lister(command, _connection, page_size, page_number, sort_by,
sort_order, item_class, result_set, **kwargs):
"""
A generator function for listing Video and Playlist objects.
"""
# pylint: disable=R0913
page = page_number
while True:
item_collection = _connection.get_list(command,
page_size=page_size,
page_number=page,
sort_by=sort_by,
sort_order=sort_order,
item_class=item_class,
**kwargs)
result_set.total_count = item_collection.total_count
result_set.page_number = page
for item in item_collection.items:
yield item
if item_collection.total_count < 0 or item_collection.page_size == 0:
break
if len(item_collection.items) > 0:
page += 1
else:
break | python | def item_lister(command, _connection, page_size, page_number, sort_by,
sort_order, item_class, result_set, **kwargs):
"""
A generator function for listing Video and Playlist objects.
"""
# pylint: disable=R0913
page = page_number
while True:
item_collection = _connection.get_list(command,
page_size=page_size,
page_number=page,
sort_by=sort_by,
sort_order=sort_order,
item_class=item_class,
**kwargs)
result_set.total_count = item_collection.total_count
result_set.page_number = page
for item in item_collection.items:
yield item
if item_collection.total_count < 0 or item_collection.page_size == 0:
break
if len(item_collection.items) > 0:
page += 1
else:
break | [
"def",
"item_lister",
"(",
"command",
",",
"_connection",
",",
"page_size",
",",
"page_number",
",",
"sort_by",
",",
"sort_order",
",",
"item_class",
",",
"result_set",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=R0913",
"page",
"=",
"page_number",
"... | A generator function for listing Video and Playlist objects. | [
"A",
"generator",
"function",
"for",
"listing",
"Video",
"and",
"Playlist",
"objects",
"."
] | 19c946b689a80156e070fe9bc35589c4b768e614 | https://github.com/studionow/pybrightcove/blob/19c946b689a80156e070fe9bc35589c4b768e614/pybrightcove/connection.py#L281-L305 | train | 54,709 |
studionow/pybrightcove | pybrightcove/connection.py | FTPConnection.get_manifest | def get_manifest(self, asset_xml):
"""
Construct and return the xml manifest to deliver along with video file.
"""
# pylint: disable=E1101
manifest = '<?xml version="1.0" encoding="utf-8"?>'
manifest += '<publisher-upload-manifest publisher-id="%s" ' % \
self.publisher_id
manifest += 'preparer="%s" ' % self.preparer
if self.report_success:
manifest += 'report-success="TRUE">\n'
for notify in self.notifications:
manifest += '<notify email="%s"/>' % notify
if self.callback:
manifest += '<callback entity-url="%s"/>' % self.callback
manifest += asset_xml
manifest += '</publisher-upload-manifest>'
return manifest | python | def get_manifest(self, asset_xml):
"""
Construct and return the xml manifest to deliver along with video file.
"""
# pylint: disable=E1101
manifest = '<?xml version="1.0" encoding="utf-8"?>'
manifest += '<publisher-upload-manifest publisher-id="%s" ' % \
self.publisher_id
manifest += 'preparer="%s" ' % self.preparer
if self.report_success:
manifest += 'report-success="TRUE">\n'
for notify in self.notifications:
manifest += '<notify email="%s"/>' % notify
if self.callback:
manifest += '<callback entity-url="%s"/>' % self.callback
manifest += asset_xml
manifest += '</publisher-upload-manifest>'
return manifest | [
"def",
"get_manifest",
"(",
"self",
",",
"asset_xml",
")",
":",
"# pylint: disable=E1101",
"manifest",
"=",
"'<?xml version=\"1.0\" encoding=\"utf-8\"?>'",
"manifest",
"+=",
"'<publisher-upload-manifest publisher-id=\"%s\" '",
"%",
"self",
".",
"publisher_id",
"manifest",
"+=... | Construct and return the xml manifest to deliver along with video file. | [
"Construct",
"and",
"return",
"the",
"xml",
"manifest",
"to",
"deliver",
"along",
"with",
"video",
"file",
"."
] | 19c946b689a80156e070fe9bc35589c4b768e614 | https://github.com/studionow/pybrightcove/blob/19c946b689a80156e070fe9bc35589c4b768e614/pybrightcove/connection.py#L103-L120 | train | 54,710 |
studionow/pybrightcove | pybrightcove/connection.py | FTPConnection._send_file | def _send_file(self, filename):
"""
Sends a file via FTP.
"""
# pylint: disable=E1101
ftp = ftplib.FTP(host=self.host)
ftp.login(user=self.user, passwd=self.password)
ftp.set_pasv(True)
ftp.storbinary("STOR %s" % os.path.basename(filename),
file(filename, 'rb')) | python | def _send_file(self, filename):
"""
Sends a file via FTP.
"""
# pylint: disable=E1101
ftp = ftplib.FTP(host=self.host)
ftp.login(user=self.user, passwd=self.password)
ftp.set_pasv(True)
ftp.storbinary("STOR %s" % os.path.basename(filename),
file(filename, 'rb')) | [
"def",
"_send_file",
"(",
"self",
",",
"filename",
")",
":",
"# pylint: disable=E1101",
"ftp",
"=",
"ftplib",
".",
"FTP",
"(",
"host",
"=",
"self",
".",
"host",
")",
"ftp",
".",
"login",
"(",
"user",
"=",
"self",
".",
"user",
",",
"passwd",
"=",
"sel... | Sends a file via FTP. | [
"Sends",
"a",
"file",
"via",
"FTP",
"."
] | 19c946b689a80156e070fe9bc35589c4b768e614 | https://github.com/studionow/pybrightcove/blob/19c946b689a80156e070fe9bc35589c4b768e614/pybrightcove/connection.py#L122-L131 | train | 54,711 |
studionow/pybrightcove | pybrightcove/connection.py | APIConnection._post | def _post(self, data, file_to_upload=None):
"""
Make the POST request.
"""
# pylint: disable=E1101
params = {"JSONRPC": simplejson.dumps(data)}
req = None
if file_to_upload:
req = http_core.HttpRequest(self.write_url)
req.method = 'POST'
req.add_body_part("JSONRPC", simplejson.dumps(data), 'text/plain')
upload = file(file_to_upload, "rb")
req.add_body_part("filePath", upload, 'application/octet-stream')
req.end_of_parts()
content_type = "multipart/form-data; boundary=%s" % \
http_core.MIME_BOUNDARY
req.headers['Content-Type'] = content_type
req.headers['User-Agent'] = config.USER_AGENT
req = http_core.ProxiedHttpClient().request(req)
else:
msg = urllib.urlencode({'json': params['JSONRPC']})
req = urllib2.urlopen(self.write_url, msg)
if req:
result = simplejson.loads(req.read())
if 'error' in result and result['error']:
exceptions.BrightcoveError.raise_exception(
result['error'])
return result['result'] | python | def _post(self, data, file_to_upload=None):
"""
Make the POST request.
"""
# pylint: disable=E1101
params = {"JSONRPC": simplejson.dumps(data)}
req = None
if file_to_upload:
req = http_core.HttpRequest(self.write_url)
req.method = 'POST'
req.add_body_part("JSONRPC", simplejson.dumps(data), 'text/plain')
upload = file(file_to_upload, "rb")
req.add_body_part("filePath", upload, 'application/octet-stream')
req.end_of_parts()
content_type = "multipart/form-data; boundary=%s" % \
http_core.MIME_BOUNDARY
req.headers['Content-Type'] = content_type
req.headers['User-Agent'] = config.USER_AGENT
req = http_core.ProxiedHttpClient().request(req)
else:
msg = urllib.urlencode({'json': params['JSONRPC']})
req = urllib2.urlopen(self.write_url, msg)
if req:
result = simplejson.loads(req.read())
if 'error' in result and result['error']:
exceptions.BrightcoveError.raise_exception(
result['error'])
return result['result'] | [
"def",
"_post",
"(",
"self",
",",
"data",
",",
"file_to_upload",
"=",
"None",
")",
":",
"# pylint: disable=E1101",
"params",
"=",
"{",
"\"JSONRPC\"",
":",
"simplejson",
".",
"dumps",
"(",
"data",
")",
"}",
"req",
"=",
"None",
"if",
"file_to_upload",
":",
... | Make the POST request. | [
"Make",
"the",
"POST",
"request",
"."
] | 19c946b689a80156e070fe9bc35589c4b768e614 | https://github.com/studionow/pybrightcove/blob/19c946b689a80156e070fe9bc35589c4b768e614/pybrightcove/connection.py#L181-L210 | train | 54,712 |
studionow/pybrightcove | pybrightcove/connection.py | APIConnection._get_response | def _get_response(self, **kwargs):
"""
Make the GET request.
"""
# pylint: disable=E1101
url = self.read_url + "?output=JSON&token=%s" % self.read_token
for key in kwargs:
if key and kwargs[key]:
val = kwargs[key]
if isinstance(val, (list, tuple)):
val = ",".join(val)
url += "&%s=%s" % (key, val)
self._api_url = url
req = urllib2.urlopen(url)
data = simplejson.loads(req.read())
self._api_raw_data = data
if data and data.get('error', None):
exceptions.BrightcoveError.raise_exception(
data['error'])
if data == None:
raise exceptions.NoDataFoundError(
"No data found for %s" % repr(kwargs))
return data | python | def _get_response(self, **kwargs):
"""
Make the GET request.
"""
# pylint: disable=E1101
url = self.read_url + "?output=JSON&token=%s" % self.read_token
for key in kwargs:
if key and kwargs[key]:
val = kwargs[key]
if isinstance(val, (list, tuple)):
val = ",".join(val)
url += "&%s=%s" % (key, val)
self._api_url = url
req = urllib2.urlopen(url)
data = simplejson.loads(req.read())
self._api_raw_data = data
if data and data.get('error', None):
exceptions.BrightcoveError.raise_exception(
data['error'])
if data == None:
raise exceptions.NoDataFoundError(
"No data found for %s" % repr(kwargs))
return data | [
"def",
"_get_response",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=E1101",
"url",
"=",
"self",
".",
"read_url",
"+",
"\"?output=JSON&token=%s\"",
"%",
"self",
".",
"read_token",
"for",
"key",
"in",
"kwargs",
":",
"if",
"key",
"and",
... | Make the GET request. | [
"Make",
"the",
"GET",
"request",
"."
] | 19c946b689a80156e070fe9bc35589c4b768e614 | https://github.com/studionow/pybrightcove/blob/19c946b689a80156e070fe9bc35589c4b768e614/pybrightcove/connection.py#L212-L234 | train | 54,713 |
studionow/pybrightcove | pybrightcove/connection.py | APIConnection.get_list | def get_list(self, command, item_class, page_size, page_number, sort_by,
sort_order, **kwargs):
"""
Not intended to be called directly, but rather through an by the
ItemResultSet object iterator.
"""
# pylint: disable=R0913,W0221
data = self._get_response(command=command,
page_size=page_size,
page_number=page_number,
sort_by=sort_by,
sort_order=sort_order,
video_fields=None,
get_item_count="true",
**kwargs)
return ItemCollection(data=data,
item_class=item_class,
_connection=self) | python | def get_list(self, command, item_class, page_size, page_number, sort_by,
sort_order, **kwargs):
"""
Not intended to be called directly, but rather through an by the
ItemResultSet object iterator.
"""
# pylint: disable=R0913,W0221
data = self._get_response(command=command,
page_size=page_size,
page_number=page_number,
sort_by=sort_by,
sort_order=sort_order,
video_fields=None,
get_item_count="true",
**kwargs)
return ItemCollection(data=data,
item_class=item_class,
_connection=self) | [
"def",
"get_list",
"(",
"self",
",",
"command",
",",
"item_class",
",",
"page_size",
",",
"page_number",
",",
"sort_by",
",",
"sort_order",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=R0913,W0221",
"data",
"=",
"self",
".",
"_get_response",
"(",
"c... | Not intended to be called directly, but rather through an by the
ItemResultSet object iterator. | [
"Not",
"intended",
"to",
"be",
"called",
"directly",
"but",
"rather",
"through",
"an",
"by",
"the",
"ItemResultSet",
"object",
"iterator",
"."
] | 19c946b689a80156e070fe9bc35589c4b768e614 | https://github.com/studionow/pybrightcove/blob/19c946b689a80156e070fe9bc35589c4b768e614/pybrightcove/connection.py#L256-L273 | train | 54,714 |
VikParuchuri/percept | percept/datahandlers/formatters.py | BaseFormat.setup_formats | def setup_formats(self):
"""
Inspects its methods to see what it can convert from and to
"""
methods = self.get_methods()
for m in methods:
#Methods named "from_X" will be assumed to convert from format X to the common format
if m.startswith("from_"):
self.input_formats.append(re.sub("from_" , "",m))
#Methods named "to_X" will be assumed to convert from the common format to X
elif m.startswith("to_"):
self.output_formats.append(re.sub("to_","",m)) | python | def setup_formats(self):
"""
Inspects its methods to see what it can convert from and to
"""
methods = self.get_methods()
for m in methods:
#Methods named "from_X" will be assumed to convert from format X to the common format
if m.startswith("from_"):
self.input_formats.append(re.sub("from_" , "",m))
#Methods named "to_X" will be assumed to convert from the common format to X
elif m.startswith("to_"):
self.output_formats.append(re.sub("to_","",m)) | [
"def",
"setup_formats",
"(",
"self",
")",
":",
"methods",
"=",
"self",
".",
"get_methods",
"(",
")",
"for",
"m",
"in",
"methods",
":",
"#Methods named \"from_X\" will be assumed to convert from format X to the common format",
"if",
"m",
".",
"startswith",
"(",
"\"from... | Inspects its methods to see what it can convert from and to | [
"Inspects",
"its",
"methods",
"to",
"see",
"what",
"it",
"can",
"convert",
"from",
"and",
"to"
] | 90304ba82053e2a9ad2bacaab3479403d3923bcf | https://github.com/VikParuchuri/percept/blob/90304ba82053e2a9ad2bacaab3479403d3923bcf/percept/datahandlers/formatters.py#L45-L56 | train | 54,715 |
VikParuchuri/percept | percept/datahandlers/formatters.py | BaseFormat.get_data | def get_data(self, data_format):
"""
Reads the common format and converts to output data
data_format - the format of the output data. See utils.input.dataformats
"""
if data_format not in self.output_formats:
raise Exception("Output format {0} not available with this class. Available formats are {1}.".format(data_format, self.output_formats))
data_converter = getattr(self, "to_" + data_format)
return data_converter() | python | def get_data(self, data_format):
"""
Reads the common format and converts to output data
data_format - the format of the output data. See utils.input.dataformats
"""
if data_format not in self.output_formats:
raise Exception("Output format {0} not available with this class. Available formats are {1}.".format(data_format, self.output_formats))
data_converter = getattr(self, "to_" + data_format)
return data_converter() | [
"def",
"get_data",
"(",
"self",
",",
"data_format",
")",
":",
"if",
"data_format",
"not",
"in",
"self",
".",
"output_formats",
":",
"raise",
"Exception",
"(",
"\"Output format {0} not available with this class. Available formats are {1}.\"",
".",
"format",
"(",
"data_fo... | Reads the common format and converts to output data
data_format - the format of the output data. See utils.input.dataformats | [
"Reads",
"the",
"common",
"format",
"and",
"converts",
"to",
"output",
"data",
"data_format",
"-",
"the",
"format",
"of",
"the",
"output",
"data",
".",
"See",
"utils",
".",
"input",
".",
"dataformats"
] | 90304ba82053e2a9ad2bacaab3479403d3923bcf | https://github.com/VikParuchuri/percept/blob/90304ba82053e2a9ad2bacaab3479403d3923bcf/percept/datahandlers/formatters.py#L69-L77 | train | 54,716 |
VikParuchuri/percept | percept/datahandlers/formatters.py | JSONFormat.from_csv | def from_csv(self, input_data):
"""
Reads csv format input data and converts to json.
"""
reformatted_data = []
for (i,row) in enumerate(input_data):
if i==0:
headers = row
else:
data_row = {}
for (j,h) in enumerate(headers):
data_row.update({h : row[j]})
reformatted_data.append(data_row)
return reformatted_data | python | def from_csv(self, input_data):
"""
Reads csv format input data and converts to json.
"""
reformatted_data = []
for (i,row) in enumerate(input_data):
if i==0:
headers = row
else:
data_row = {}
for (j,h) in enumerate(headers):
data_row.update({h : row[j]})
reformatted_data.append(data_row)
return reformatted_data | [
"def",
"from_csv",
"(",
"self",
",",
"input_data",
")",
":",
"reformatted_data",
"=",
"[",
"]",
"for",
"(",
"i",
",",
"row",
")",
"in",
"enumerate",
"(",
"input_data",
")",
":",
"if",
"i",
"==",
"0",
":",
"headers",
"=",
"row",
"else",
":",
"data_r... | Reads csv format input data and converts to json. | [
"Reads",
"csv",
"format",
"input",
"data",
"and",
"converts",
"to",
"json",
"."
] | 90304ba82053e2a9ad2bacaab3479403d3923bcf | https://github.com/VikParuchuri/percept/blob/90304ba82053e2a9ad2bacaab3479403d3923bcf/percept/datahandlers/formatters.py#L90-L103 | train | 54,717 |
VikParuchuri/percept | percept/datahandlers/formatters.py | JSONFormat.to_dataframe | def to_dataframe(self):
"""
Reads the common format self.data and writes out to a dataframe.
"""
keys = self.data[0].keys()
column_list =[]
for k in keys:
key_list = []
for i in xrange(0,len(self.data)):
key_list.append(self.data[i][k])
column_list.append(key_list)
df = DataFrame(np.asarray(column_list).transpose(), columns=keys)
for i in xrange(0,df.shape[1]):
if is_number(df.iloc[:,i]):
df.iloc[:,i] = df.iloc[:,i].astype(float)
return df | python | def to_dataframe(self):
"""
Reads the common format self.data and writes out to a dataframe.
"""
keys = self.data[0].keys()
column_list =[]
for k in keys:
key_list = []
for i in xrange(0,len(self.data)):
key_list.append(self.data[i][k])
column_list.append(key_list)
df = DataFrame(np.asarray(column_list).transpose(), columns=keys)
for i in xrange(0,df.shape[1]):
if is_number(df.iloc[:,i]):
df.iloc[:,i] = df.iloc[:,i].astype(float)
return df | [
"def",
"to_dataframe",
"(",
"self",
")",
":",
"keys",
"=",
"self",
".",
"data",
"[",
"0",
"]",
".",
"keys",
"(",
")",
"column_list",
"=",
"[",
"]",
"for",
"k",
"in",
"keys",
":",
"key_list",
"=",
"[",
"]",
"for",
"i",
"in",
"xrange",
"(",
"0",
... | Reads the common format self.data and writes out to a dataframe. | [
"Reads",
"the",
"common",
"format",
"self",
".",
"data",
"and",
"writes",
"out",
"to",
"a",
"dataframe",
"."
] | 90304ba82053e2a9ad2bacaab3479403d3923bcf | https://github.com/VikParuchuri/percept/blob/90304ba82053e2a9ad2bacaab3479403d3923bcf/percept/datahandlers/formatters.py#L105-L120 | train | 54,718 |
smarie/python-parsyfiles | parsyfiles/parsing_core_api.py | check_extensions | def check_extensions(extensions: Set[str], allow_multifile: bool = False):
"""
Utility method to check that all extensions in the provided set are valid
:param extensions:
:param allow_multifile:
:return:
"""
check_var(extensions, var_types=set, var_name='extensions')
# -- check them one by one
for ext in extensions:
check_extension(ext, allow_multifile=allow_multifile) | python | def check_extensions(extensions: Set[str], allow_multifile: bool = False):
"""
Utility method to check that all extensions in the provided set are valid
:param extensions:
:param allow_multifile:
:return:
"""
check_var(extensions, var_types=set, var_name='extensions')
# -- check them one by one
for ext in extensions:
check_extension(ext, allow_multifile=allow_multifile) | [
"def",
"check_extensions",
"(",
"extensions",
":",
"Set",
"[",
"str",
"]",
",",
"allow_multifile",
":",
"bool",
"=",
"False",
")",
":",
"check_var",
"(",
"extensions",
",",
"var_types",
"=",
"set",
",",
"var_name",
"=",
"'extensions'",
")",
"# -- check them ... | Utility method to check that all extensions in the provided set are valid
:param extensions:
:param allow_multifile:
:return: | [
"Utility",
"method",
"to",
"check",
"that",
"all",
"extensions",
"in",
"the",
"provided",
"set",
"are",
"valid"
] | 344b37e1151e8d4e7c2ee49ae09d6568715ae64e | https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/parsing_core_api.py#L15-L27 | train | 54,719 |
smarie/python-parsyfiles | parsyfiles/parsing_core_api.py | _BaseParserDeclarationForRegistries.are_worth_chaining | def are_worth_chaining(parser, to_type: Type[S], converter: Converter[S, T]) -> bool:
"""
Utility method to check if it makes sense to chain this parser with the given destination type, and the given
converter to create a parsing chain. Returns True if it brings value to chain them.
To bring value,
* the converter's output should not be a parent class of the parser's output. Otherwise
the chain does not even make any progress :)
* The parser has to allow chaining (with converter.can_chain=True)
:param parser:
:param to_type:
:param converter:
:return:
"""
if not parser.can_chain:
# The base parser prevents chaining
return False
elif not is_any_type(to_type) and is_any_type(converter.to_type):
# we gain the capability to generate any type. So it is interesting.
return True
elif issubclass(to_type, converter.to_type):
# Not interesting : the outcome of the chain would be not better than one of the parser alone
return False
# Note: we dont say that chaining a generic parser with a converter is useless. Indeed it might unlock some
# capabilities for the user (new file extensions, etc.) that would not be available with the generic parser
# targetting to_type alone. For example parsing object A from its constructor then converting A to B might
# sometimes be interesting, rather than parsing B from its constructor
else:
# Interesting
return True | python | def are_worth_chaining(parser, to_type: Type[S], converter: Converter[S, T]) -> bool:
"""
Utility method to check if it makes sense to chain this parser with the given destination type, and the given
converter to create a parsing chain. Returns True if it brings value to chain them.
To bring value,
* the converter's output should not be a parent class of the parser's output. Otherwise
the chain does not even make any progress :)
* The parser has to allow chaining (with converter.can_chain=True)
:param parser:
:param to_type:
:param converter:
:return:
"""
if not parser.can_chain:
# The base parser prevents chaining
return False
elif not is_any_type(to_type) and is_any_type(converter.to_type):
# we gain the capability to generate any type. So it is interesting.
return True
elif issubclass(to_type, converter.to_type):
# Not interesting : the outcome of the chain would be not better than one of the parser alone
return False
# Note: we dont say that chaining a generic parser with a converter is useless. Indeed it might unlock some
# capabilities for the user (new file extensions, etc.) that would not be available with the generic parser
# targetting to_type alone. For example parsing object A from its constructor then converting A to B might
# sometimes be interesting, rather than parsing B from its constructor
else:
# Interesting
return True | [
"def",
"are_worth_chaining",
"(",
"parser",
",",
"to_type",
":",
"Type",
"[",
"S",
"]",
",",
"converter",
":",
"Converter",
"[",
"S",
",",
"T",
"]",
")",
"->",
"bool",
":",
"if",
"not",
"parser",
".",
"can_chain",
":",
"# The base parser prevents chaining"... | Utility method to check if it makes sense to chain this parser with the given destination type, and the given
converter to create a parsing chain. Returns True if it brings value to chain them.
To bring value,
* the converter's output should not be a parent class of the parser's output. Otherwise
the chain does not even make any progress :)
* The parser has to allow chaining (with converter.can_chain=True)
:param parser:
:param to_type:
:param converter:
:return: | [
"Utility",
"method",
"to",
"check",
"if",
"it",
"makes",
"sense",
"to",
"chain",
"this",
"parser",
"with",
"the",
"given",
"destination",
"type",
"and",
"the",
"given",
"converter",
"to",
"create",
"a",
"parsing",
"chain",
".",
"Returns",
"True",
"if",
"it... | 344b37e1151e8d4e7c2ee49ae09d6568715ae64e | https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/parsing_core_api.py#L190-L224 | train | 54,720 |
smarie/python-parsyfiles | parsyfiles/parsing_core_api.py | ParsingPlan._execute | def _execute(self, logger: Logger, options: Dict[str, Dict[str, Any]]) -> T:
"""
Implementing classes should perform the parsing here, possibly using custom methods of self.parser.
:param logger:
:param options:
:return:
"""
pass | python | def _execute(self, logger: Logger, options: Dict[str, Dict[str, Any]]) -> T:
"""
Implementing classes should perform the parsing here, possibly using custom methods of self.parser.
:param logger:
:param options:
:return:
"""
pass | [
"def",
"_execute",
"(",
"self",
",",
"logger",
":",
"Logger",
",",
"options",
":",
"Dict",
"[",
"str",
",",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
")",
"->",
"T",
":",
"pass"
] | Implementing classes should perform the parsing here, possibly using custom methods of self.parser.
:param logger:
:param options:
:return: | [
"Implementing",
"classes",
"should",
"perform",
"the",
"parsing",
"here",
"possibly",
"using",
"custom",
"methods",
"of",
"self",
".",
"parser",
"."
] | 344b37e1151e8d4e7c2ee49ae09d6568715ae64e | https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/parsing_core_api.py#L420-L428 | train | 54,721 |
smarie/python-parsyfiles | parsyfiles/parsing_core_api.py | Parser.create_parsing_plan | def create_parsing_plan(self, desired_type: Type[T], filesystem_object: PersistedObject, logger: Logger,
options: Dict[str, Dict[str, Any]]) -> ParsingPlan[T]:
"""
Creates a parsing plan to parse the given filesystem object into the given desired_type.
Implementing classes may wish to support additional parameters.
:param desired_type: the type of object that should be created as the output of parsing plan execution.
:param filesystem_object: the persisted object that should be parsed
:param logger: an optional logger to log all parsing plan creation and execution information
:param options: a dictionary additional implementation-specific parameters (one dict per parser id).
Implementing classes may use 'self._get_applicable_options()' to get the options that are of interest for this
parser.
:return:
"""
pass | python | def create_parsing_plan(self, desired_type: Type[T], filesystem_object: PersistedObject, logger: Logger,
options: Dict[str, Dict[str, Any]]) -> ParsingPlan[T]:
"""
Creates a parsing plan to parse the given filesystem object into the given desired_type.
Implementing classes may wish to support additional parameters.
:param desired_type: the type of object that should be created as the output of parsing plan execution.
:param filesystem_object: the persisted object that should be parsed
:param logger: an optional logger to log all parsing plan creation and execution information
:param options: a dictionary additional implementation-specific parameters (one dict per parser id).
Implementing classes may use 'self._get_applicable_options()' to get the options that are of interest for this
parser.
:return:
"""
pass | [
"def",
"create_parsing_plan",
"(",
"self",
",",
"desired_type",
":",
"Type",
"[",
"T",
"]",
",",
"filesystem_object",
":",
"PersistedObject",
",",
"logger",
":",
"Logger",
",",
"options",
":",
"Dict",
"[",
"str",
",",
"Dict",
"[",
"str",
",",
"Any",
"]",... | Creates a parsing plan to parse the given filesystem object into the given desired_type.
Implementing classes may wish to support additional parameters.
:param desired_type: the type of object that should be created as the output of parsing plan execution.
:param filesystem_object: the persisted object that should be parsed
:param logger: an optional logger to log all parsing plan creation and execution information
:param options: a dictionary additional implementation-specific parameters (one dict per parser id).
Implementing classes may use 'self._get_applicable_options()' to get the options that are of interest for this
parser.
:return: | [
"Creates",
"a",
"parsing",
"plan",
"to",
"parse",
"the",
"given",
"filesystem",
"object",
"into",
"the",
"given",
"desired_type",
".",
"Implementing",
"classes",
"may",
"wish",
"to",
"support",
"additional",
"parameters",
"."
] | 344b37e1151e8d4e7c2ee49ae09d6568715ae64e | https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/parsing_core_api.py#L481-L495 | train | 54,722 |
KvasirSecurity/kvasirapi-python | KvasirAPI/jsonrpc/hosts.py | Hosts.add | def add(self, f_ipaddr, f_macaddr, f_hostname, f_netbios_name, f_engineer, f_asset_group, f_confirmed):
"""
Add a t_hosts record
:param f_ipaddr: IP address
:param f_macaddr: MAC Address
:param f_hostname: Hostname
:param f_netbios_name: NetBIOS Name
:param f_engineer: Engineer username
:param f_asset_group: Asset group
:param f_confirmed: Confirmed boolean
:return: (True/False, t_hosts.id or response message)
"""
return self.send.host_add(f_ipaddr, f_macaddr, f_hostname, f_netbios_name, f_engineer,
f_asset_group, f_confirmed) | python | def add(self, f_ipaddr, f_macaddr, f_hostname, f_netbios_name, f_engineer, f_asset_group, f_confirmed):
"""
Add a t_hosts record
:param f_ipaddr: IP address
:param f_macaddr: MAC Address
:param f_hostname: Hostname
:param f_netbios_name: NetBIOS Name
:param f_engineer: Engineer username
:param f_asset_group: Asset group
:param f_confirmed: Confirmed boolean
:return: (True/False, t_hosts.id or response message)
"""
return self.send.host_add(f_ipaddr, f_macaddr, f_hostname, f_netbios_name, f_engineer,
f_asset_group, f_confirmed) | [
"def",
"add",
"(",
"self",
",",
"f_ipaddr",
",",
"f_macaddr",
",",
"f_hostname",
",",
"f_netbios_name",
",",
"f_engineer",
",",
"f_asset_group",
",",
"f_confirmed",
")",
":",
"return",
"self",
".",
"send",
".",
"host_add",
"(",
"f_ipaddr",
",",
"f_macaddr",
... | Add a t_hosts record
:param f_ipaddr: IP address
:param f_macaddr: MAC Address
:param f_hostname: Hostname
:param f_netbios_name: NetBIOS Name
:param f_engineer: Engineer username
:param f_asset_group: Asset group
:param f_confirmed: Confirmed boolean
:return: (True/False, t_hosts.id or response message) | [
"Add",
"a",
"t_hosts",
"record"
] | ec8c5818bd5913f3afd150f25eaec6e7cc732f4c | https://github.com/KvasirSecurity/kvasirapi-python/blob/ec8c5818bd5913f3afd150f25eaec6e7cc732f4c/KvasirAPI/jsonrpc/hosts.py#L28-L42 | train | 54,723 |
polyledger/lattice | lattice/optimize.py | Allocator.retrieve_data | def retrieve_data(self):
"""
Retrives data as a DataFrame.
"""
#==== Retrieve data ====#
df = self.manager.get_historic_data(self.start.date(), self.end.date())
df.replace(0, np.nan, inplace=True)
return df | python | def retrieve_data(self):
"""
Retrives data as a DataFrame.
"""
#==== Retrieve data ====#
df = self.manager.get_historic_data(self.start.date(), self.end.date())
df.replace(0, np.nan, inplace=True)
return df | [
"def",
"retrieve_data",
"(",
"self",
")",
":",
"#==== Retrieve data ====#",
"df",
"=",
"self",
".",
"manager",
".",
"get_historic_data",
"(",
"self",
".",
"start",
".",
"date",
"(",
")",
",",
"self",
".",
"end",
".",
"date",
"(",
")",
")",
"df",
".",
... | Retrives data as a DataFrame. | [
"Retrives",
"data",
"as",
"a",
"DataFrame",
"."
] | d68d27c93b1634ee29f5c1a1dbcd67397481323b | https://github.com/polyledger/lattice/blob/d68d27c93b1634ee29f5c1a1dbcd67397481323b/lattice/optimize.py#L33-L42 | train | 54,724 |
polyledger/lattice | lattice/optimize.py | Allocator.get_min_risk | def get_min_risk(self, weights, cov_matrix):
"""
Minimizes the variance of a portfolio.
"""
def func(weights):
"""The objective function that minimizes variance."""
return np.matmul(np.matmul(weights.transpose(), cov_matrix), weights)
def func_deriv(weights):
"""The derivative of the objective function."""
return (
np.matmul(weights.transpose(), cov_matrix.transpose()) +
np.matmul(weights.transpose(), cov_matrix)
)
constraints = ({'type': 'eq', 'fun': lambda weights: (weights.sum() - 1)})
solution = self.solve_minimize(func, weights, constraints, func_deriv=func_deriv)
# NOTE: `min_risk` is unused, but may be helpful later.
# min_risk = solution.fun
allocation = solution.x
return allocation | python | def get_min_risk(self, weights, cov_matrix):
"""
Minimizes the variance of a portfolio.
"""
def func(weights):
"""The objective function that minimizes variance."""
return np.matmul(np.matmul(weights.transpose(), cov_matrix), weights)
def func_deriv(weights):
"""The derivative of the objective function."""
return (
np.matmul(weights.transpose(), cov_matrix.transpose()) +
np.matmul(weights.transpose(), cov_matrix)
)
constraints = ({'type': 'eq', 'fun': lambda weights: (weights.sum() - 1)})
solution = self.solve_minimize(func, weights, constraints, func_deriv=func_deriv)
# NOTE: `min_risk` is unused, but may be helpful later.
# min_risk = solution.fun
allocation = solution.x
return allocation | [
"def",
"get_min_risk",
"(",
"self",
",",
"weights",
",",
"cov_matrix",
")",
":",
"def",
"func",
"(",
"weights",
")",
":",
"\"\"\"The objective function that minimizes variance.\"\"\"",
"return",
"np",
".",
"matmul",
"(",
"np",
".",
"matmul",
"(",
"weights",
".",... | Minimizes the variance of a portfolio. | [
"Minimizes",
"the",
"variance",
"of",
"a",
"portfolio",
"."
] | d68d27c93b1634ee29f5c1a1dbcd67397481323b | https://github.com/polyledger/lattice/blob/d68d27c93b1634ee29f5c1a1dbcd67397481323b/lattice/optimize.py#L44-L66 | train | 54,725 |
polyledger/lattice | lattice/optimize.py | Allocator.get_max_return | def get_max_return(self, weights, returns):
"""
Maximizes the returns of a portfolio.
"""
def func(weights):
"""The objective function that maximizes returns."""
return np.dot(weights, returns.values) * -1
constraints = ({'type': 'eq', 'fun': lambda weights: (weights.sum() - 1)})
solution = self.solve_minimize(func, weights, constraints)
max_return = solution.fun * -1
# NOTE: `max_risk` is not used anywhere, but may be helpful in the future.
# allocation = solution.x
# max_risk = np.matmul(
# np.matmul(allocation.transpose(), cov_matrix), allocation
# )
return max_return | python | def get_max_return(self, weights, returns):
"""
Maximizes the returns of a portfolio.
"""
def func(weights):
"""The objective function that maximizes returns."""
return np.dot(weights, returns.values) * -1
constraints = ({'type': 'eq', 'fun': lambda weights: (weights.sum() - 1)})
solution = self.solve_minimize(func, weights, constraints)
max_return = solution.fun * -1
# NOTE: `max_risk` is not used anywhere, but may be helpful in the future.
# allocation = solution.x
# max_risk = np.matmul(
# np.matmul(allocation.transpose(), cov_matrix), allocation
# )
return max_return | [
"def",
"get_max_return",
"(",
"self",
",",
"weights",
",",
"returns",
")",
":",
"def",
"func",
"(",
"weights",
")",
":",
"\"\"\"The objective function that maximizes returns.\"\"\"",
"return",
"np",
".",
"dot",
"(",
"weights",
",",
"returns",
".",
"values",
")",... | Maximizes the returns of a portfolio. | [
"Maximizes",
"the",
"returns",
"of",
"a",
"portfolio",
"."
] | d68d27c93b1634ee29f5c1a1dbcd67397481323b | https://github.com/polyledger/lattice/blob/d68d27c93b1634ee29f5c1a1dbcd67397481323b/lattice/optimize.py#L68-L87 | train | 54,726 |
polyledger/lattice | lattice/optimize.py | Allocator.efficient_frontier | def efficient_frontier(
self,
returns,
cov_matrix,
min_return,
max_return,
count
):
"""
Returns a DataFrame of efficient portfolio allocations for `count` risk
indices.
"""
columns = [coin for coin in self.SUPPORTED_COINS]
# columns.append('Return')
# columns.append('Risk')
values = pd.DataFrame(columns=columns)
weights = [1/len(self.SUPPORTED_COINS)] * len(self.SUPPORTED_COINS)
def func(weights):
"""The objective function that minimizes variance."""
return np.matmul(np.matmul(weights.transpose(), cov_matrix), weights)
def func_deriv(weights):
"""The derivative of the objective function."""
return (
np.matmul(weights.transpose(), cov_matrix.transpose()) +
np.matmul(weights.transpose(), cov_matrix)
)
for point in np.linspace(min_return, max_return, count):
constraints = (
{'type': 'eq', 'fun': lambda weights: (weights.sum() - 1)},
{'type': 'ineq', 'fun': lambda weights, i=point: (
np.dot(weights, returns.values) - i
)}
)
solution = self.solve_minimize(func, weights, constraints, func_deriv=func_deriv)
columns = {}
for index, coin in enumerate(self.SUPPORTED_COINS):
columns[coin] = math.floor(solution.x[index] * 100 * 100) / 100
# NOTE: These lines could be helpful, but are commented out right now.
# columns['Return'] = round(np.dot(solution.x, returns), 6)
# columns['Risk'] = round(solution.fun, 6)
values = values.append(columns, ignore_index=True)
return values | python | def efficient_frontier(
self,
returns,
cov_matrix,
min_return,
max_return,
count
):
"""
Returns a DataFrame of efficient portfolio allocations for `count` risk
indices.
"""
columns = [coin for coin in self.SUPPORTED_COINS]
# columns.append('Return')
# columns.append('Risk')
values = pd.DataFrame(columns=columns)
weights = [1/len(self.SUPPORTED_COINS)] * len(self.SUPPORTED_COINS)
def func(weights):
"""The objective function that minimizes variance."""
return np.matmul(np.matmul(weights.transpose(), cov_matrix), weights)
def func_deriv(weights):
"""The derivative of the objective function."""
return (
np.matmul(weights.transpose(), cov_matrix.transpose()) +
np.matmul(weights.transpose(), cov_matrix)
)
for point in np.linspace(min_return, max_return, count):
constraints = (
{'type': 'eq', 'fun': lambda weights: (weights.sum() - 1)},
{'type': 'ineq', 'fun': lambda weights, i=point: (
np.dot(weights, returns.values) - i
)}
)
solution = self.solve_minimize(func, weights, constraints, func_deriv=func_deriv)
columns = {}
for index, coin in enumerate(self.SUPPORTED_COINS):
columns[coin] = math.floor(solution.x[index] * 100 * 100) / 100
# NOTE: These lines could be helpful, but are commented out right now.
# columns['Return'] = round(np.dot(solution.x, returns), 6)
# columns['Risk'] = round(solution.fun, 6)
values = values.append(columns, ignore_index=True)
return values | [
"def",
"efficient_frontier",
"(",
"self",
",",
"returns",
",",
"cov_matrix",
",",
"min_return",
",",
"max_return",
",",
"count",
")",
":",
"columns",
"=",
"[",
"coin",
"for",
"coin",
"in",
"self",
".",
"SUPPORTED_COINS",
"]",
"# columns.append('Return')",
"# c... | Returns a DataFrame of efficient portfolio allocations for `count` risk
indices. | [
"Returns",
"a",
"DataFrame",
"of",
"efficient",
"portfolio",
"allocations",
"for",
"count",
"risk",
"indices",
"."
] | d68d27c93b1634ee29f5c1a1dbcd67397481323b | https://github.com/polyledger/lattice/blob/d68d27c93b1634ee29f5c1a1dbcd67397481323b/lattice/optimize.py#L89-L139 | train | 54,727 |
polyledger/lattice | lattice/optimize.py | Allocator.solve_minimize | def solve_minimize(
self,
func,
weights,
constraints,
lower_bound=0.0,
upper_bound=1.0,
func_deriv=False
):
"""
Returns the solution to a minimization problem.
"""
bounds = ((lower_bound, upper_bound), ) * len(self.SUPPORTED_COINS)
return minimize(
fun=func, x0=weights, jac=func_deriv, bounds=bounds,
constraints=constraints, method='SLSQP', options={'disp': False}
) | python | def solve_minimize(
self,
func,
weights,
constraints,
lower_bound=0.0,
upper_bound=1.0,
func_deriv=False
):
"""
Returns the solution to a minimization problem.
"""
bounds = ((lower_bound, upper_bound), ) * len(self.SUPPORTED_COINS)
return minimize(
fun=func, x0=weights, jac=func_deriv, bounds=bounds,
constraints=constraints, method='SLSQP', options={'disp': False}
) | [
"def",
"solve_minimize",
"(",
"self",
",",
"func",
",",
"weights",
",",
"constraints",
",",
"lower_bound",
"=",
"0.0",
",",
"upper_bound",
"=",
"1.0",
",",
"func_deriv",
"=",
"False",
")",
":",
"bounds",
"=",
"(",
"(",
"lower_bound",
",",
"upper_bound",
... | Returns the solution to a minimization problem. | [
"Returns",
"the",
"solution",
"to",
"a",
"minimization",
"problem",
"."
] | d68d27c93b1634ee29f5c1a1dbcd67397481323b | https://github.com/polyledger/lattice/blob/d68d27c93b1634ee29f5c1a1dbcd67397481323b/lattice/optimize.py#L141-L158 | train | 54,728 |
polyledger/lattice | lattice/optimize.py | Allocator.allocate | def allocate(self):
"""
Returns an efficient portfolio allocation for the given risk index.
"""
df = self.manager.get_historic_data()[self.SUPPORTED_COINS]
#==== Calculate the daily changes ====#
change_columns = []
for column in df:
if column in self.SUPPORTED_COINS:
change_column = '{}_change'.format(column)
values = pd.Series(
(df[column].shift(-1) - df[column]) /
-df[column].shift(-1)
).values
df[change_column] = values
change_columns.append(change_column)
# print(df.head())
# print(df.tail())
#==== Variances and returns ====#
columns = change_columns
# NOTE: `risks` is not used, but may be used in the future
risks = df[columns].apply(np.nanvar, axis=0)
# print('\nVariance:\n{}\n'.format(risks))
returns = df[columns].apply(np.nanmean, axis=0)
# print('\nExpected returns:\n{}\n'.format(returns))
#==== Calculate risk and expected return ====#
cov_matrix = df[columns].cov()
# NOTE: The diagonal variances weren't calculated correctly, so here is a fix.
cov_matrix.values[[np.arange(len(self.SUPPORTED_COINS))] * 2] = df[columns].apply(np.nanvar, axis=0)
weights = np.array([1/len(self.SUPPORTED_COINS)] * len(self.SUPPORTED_COINS)).reshape(len(self.SUPPORTED_COINS), 1)
#==== Calculate portfolio with the minimum risk ====#
min_risk = self.get_min_risk(weights, cov_matrix)
min_return = np.dot(min_risk, returns.values)
#==== Calculate portfolio with the maximum return ====#
max_return = self.get_max_return(weights, returns)
#==== Calculate efficient frontier ====#
frontier = self.efficient_frontier(
returns, cov_matrix, min_return, max_return, 6
)
return frontier | python | def allocate(self):
"""
Returns an efficient portfolio allocation for the given risk index.
"""
df = self.manager.get_historic_data()[self.SUPPORTED_COINS]
#==== Calculate the daily changes ====#
change_columns = []
for column in df:
if column in self.SUPPORTED_COINS:
change_column = '{}_change'.format(column)
values = pd.Series(
(df[column].shift(-1) - df[column]) /
-df[column].shift(-1)
).values
df[change_column] = values
change_columns.append(change_column)
# print(df.head())
# print(df.tail())
#==== Variances and returns ====#
columns = change_columns
# NOTE: `risks` is not used, but may be used in the future
risks = df[columns].apply(np.nanvar, axis=0)
# print('\nVariance:\n{}\n'.format(risks))
returns = df[columns].apply(np.nanmean, axis=0)
# print('\nExpected returns:\n{}\n'.format(returns))
#==== Calculate risk and expected return ====#
cov_matrix = df[columns].cov()
# NOTE: The diagonal variances weren't calculated correctly, so here is a fix.
cov_matrix.values[[np.arange(len(self.SUPPORTED_COINS))] * 2] = df[columns].apply(np.nanvar, axis=0)
weights = np.array([1/len(self.SUPPORTED_COINS)] * len(self.SUPPORTED_COINS)).reshape(len(self.SUPPORTED_COINS), 1)
#==== Calculate portfolio with the minimum risk ====#
min_risk = self.get_min_risk(weights, cov_matrix)
min_return = np.dot(min_risk, returns.values)
#==== Calculate portfolio with the maximum return ====#
max_return = self.get_max_return(weights, returns)
#==== Calculate efficient frontier ====#
frontier = self.efficient_frontier(
returns, cov_matrix, min_return, max_return, 6
)
return frontier | [
"def",
"allocate",
"(",
"self",
")",
":",
"df",
"=",
"self",
".",
"manager",
".",
"get_historic_data",
"(",
")",
"[",
"self",
".",
"SUPPORTED_COINS",
"]",
"#==== Calculate the daily changes ====#",
"change_columns",
"=",
"[",
"]",
"for",
"column",
"in",
"df",
... | Returns an efficient portfolio allocation for the given risk index. | [
"Returns",
"an",
"efficient",
"portfolio",
"allocation",
"for",
"the",
"given",
"risk",
"index",
"."
] | d68d27c93b1634ee29f5c1a1dbcd67397481323b | https://github.com/polyledger/lattice/blob/d68d27c93b1634ee29f5c1a1dbcd67397481323b/lattice/optimize.py#L160-L206 | train | 54,729 |
VikParuchuri/percept | percept/management/commands.py | handle_default_options | def handle_default_options(options):
"""
Pass in a Values instance from OptionParser. Handle settings and pythonpath
options - Values from OptionParser
"""
if options.settings:
#Set the percept_settings_module (picked up by settings in conf.base)
os.environ['PERCEPT_SETTINGS_MODULE'] = options.settings
if options.pythonpath:
#Append the pythonpath and the directory one up from the pythonpath to sys.path for importing
options.pythonpath = os.path.abspath(os.path.expanduser(options.pythonpath))
up_one_path = os.path.abspath(os.path.join(options.pythonpath, ".."))
sys.path.append(options.pythonpath)
sys.path.append(up_one_path)
return options | python | def handle_default_options(options):
"""
Pass in a Values instance from OptionParser. Handle settings and pythonpath
options - Values from OptionParser
"""
if options.settings:
#Set the percept_settings_module (picked up by settings in conf.base)
os.environ['PERCEPT_SETTINGS_MODULE'] = options.settings
if options.pythonpath:
#Append the pythonpath and the directory one up from the pythonpath to sys.path for importing
options.pythonpath = os.path.abspath(os.path.expanduser(options.pythonpath))
up_one_path = os.path.abspath(os.path.join(options.pythonpath, ".."))
sys.path.append(options.pythonpath)
sys.path.append(up_one_path)
return options | [
"def",
"handle_default_options",
"(",
"options",
")",
":",
"if",
"options",
".",
"settings",
":",
"#Set the percept_settings_module (picked up by settings in conf.base)",
"os",
".",
"environ",
"[",
"'PERCEPT_SETTINGS_MODULE'",
"]",
"=",
"options",
".",
"settings",
"if",
... | Pass in a Values instance from OptionParser. Handle settings and pythonpath
options - Values from OptionParser | [
"Pass",
"in",
"a",
"Values",
"instance",
"from",
"OptionParser",
".",
"Handle",
"settings",
"and",
"pythonpath",
"options",
"-",
"Values",
"from",
"OptionParser"
] | 90304ba82053e2a9ad2bacaab3479403d3923bcf | https://github.com/VikParuchuri/percept/blob/90304ba82053e2a9ad2bacaab3479403d3923bcf/percept/management/commands.py#L11-L26 | train | 54,730 |
VikParuchuri/percept | percept/management/commands.py | BaseCommand.create_parser | def create_parser(self, prog_name, subcommand):
"""
Create an OptionParser
prog_name - Name of a command
subcommand - Name of a subcommand
"""
parser = OptionParser(prog=prog_name,
usage=self.usage(subcommand),
option_list=self.option_list)
return parser | python | def create_parser(self, prog_name, subcommand):
"""
Create an OptionParser
prog_name - Name of a command
subcommand - Name of a subcommand
"""
parser = OptionParser(prog=prog_name,
usage=self.usage(subcommand),
option_list=self.option_list)
return parser | [
"def",
"create_parser",
"(",
"self",
",",
"prog_name",
",",
"subcommand",
")",
":",
"parser",
"=",
"OptionParser",
"(",
"prog",
"=",
"prog_name",
",",
"usage",
"=",
"self",
".",
"usage",
"(",
"subcommand",
")",
",",
"option_list",
"=",
"self",
".",
"opti... | Create an OptionParser
prog_name - Name of a command
subcommand - Name of a subcommand | [
"Create",
"an",
"OptionParser",
"prog_name",
"-",
"Name",
"of",
"a",
"command",
"subcommand",
"-",
"Name",
"of",
"a",
"subcommand"
] | 90304ba82053e2a9ad2bacaab3479403d3923bcf | https://github.com/VikParuchuri/percept/blob/90304ba82053e2a9ad2bacaab3479403d3923bcf/percept/management/commands.py#L49-L58 | train | 54,731 |
frascoweb/frasco | frasco/decorators.py | hook | def hook(name=None, *args, **kwargs):
"""Decorator to register the function as a hook
"""
def decorator(f):
if not hasattr(f, "hooks"):
f.hooks = []
f.hooks.append((name or f.__name__, args, kwargs))
return f
return decorator | python | def hook(name=None, *args, **kwargs):
"""Decorator to register the function as a hook
"""
def decorator(f):
if not hasattr(f, "hooks"):
f.hooks = []
f.hooks.append((name or f.__name__, args, kwargs))
return f
return decorator | [
"def",
"hook",
"(",
"name",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"if",
"not",
"hasattr",
"(",
"f",
",",
"\"hooks\"",
")",
":",
"f",
".",
"hooks",
"=",
"[",
"]",
"f",
".",
... | Decorator to register the function as a hook | [
"Decorator",
"to",
"register",
"the",
"function",
"as",
"a",
"hook"
] | ea519d69dd5ca6deaf3650175692ee4a1a02518f | https://github.com/frascoweb/frasco/blob/ea519d69dd5ca6deaf3650175692ee4a1a02518f/frasco/decorators.py#L10-L18 | train | 54,732 |
frascoweb/frasco | frasco/decorators.py | expose | def expose(rule, **options):
"""Decorator to add an url rule to a function
"""
def decorator(f):
if not hasattr(f, "urls"):
f.urls = []
if isinstance(rule, (list, tuple)):
f.urls.extend(rule)
else:
f.urls.append((rule, options))
return f
return decorator | python | def expose(rule, **options):
"""Decorator to add an url rule to a function
"""
def decorator(f):
if not hasattr(f, "urls"):
f.urls = []
if isinstance(rule, (list, tuple)):
f.urls.extend(rule)
else:
f.urls.append((rule, options))
return f
return decorator | [
"def",
"expose",
"(",
"rule",
",",
"*",
"*",
"options",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"if",
"not",
"hasattr",
"(",
"f",
",",
"\"urls\"",
")",
":",
"f",
".",
"urls",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"rule",
",",
"(",
... | Decorator to add an url rule to a function | [
"Decorator",
"to",
"add",
"an",
"url",
"rule",
"to",
"a",
"function"
] | ea519d69dd5ca6deaf3650175692ee4a1a02518f | https://github.com/frascoweb/frasco/blob/ea519d69dd5ca6deaf3650175692ee4a1a02518f/frasco/decorators.py#L101-L112 | train | 54,733 |
matgrioni/betacode | betacode/conv.py | _create_unicode_map | def _create_unicode_map():
"""
Create the inverse map from unicode to betacode.
Returns:
The hash map to convert unicode characters to the beta code representation.
"""
unicode_map = {}
for beta, uni in _map.BETACODE_MAP.items():
# Include decomposed equivalent where necessary.
norm = unicodedata.normalize('NFC', uni)
unicode_map[norm] = beta
unicode_map[uni] = beta
# Add the final sigmas.
final_sigma_norm = unicodedata.normalize('NFC', _FINAL_LC_SIGMA)
unicode_map[final_sigma_norm] = 's'
unicode_map[_FINAL_LC_SIGMA] = 's'
return unicode_map | python | def _create_unicode_map():
"""
Create the inverse map from unicode to betacode.
Returns:
The hash map to convert unicode characters to the beta code representation.
"""
unicode_map = {}
for beta, uni in _map.BETACODE_MAP.items():
# Include decomposed equivalent where necessary.
norm = unicodedata.normalize('NFC', uni)
unicode_map[norm] = beta
unicode_map[uni] = beta
# Add the final sigmas.
final_sigma_norm = unicodedata.normalize('NFC', _FINAL_LC_SIGMA)
unicode_map[final_sigma_norm] = 's'
unicode_map[_FINAL_LC_SIGMA] = 's'
return unicode_map | [
"def",
"_create_unicode_map",
"(",
")",
":",
"unicode_map",
"=",
"{",
"}",
"for",
"beta",
",",
"uni",
"in",
"_map",
".",
"BETACODE_MAP",
".",
"items",
"(",
")",
":",
"# Include decomposed equivalent where necessary.",
"norm",
"=",
"unicodedata",
".",
"normalize"... | Create the inverse map from unicode to betacode.
Returns:
The hash map to convert unicode characters to the beta code representation. | [
"Create",
"the",
"inverse",
"map",
"from",
"unicode",
"to",
"betacode",
"."
] | 2f8b439c0de9cdf451b0b390161752cac9879137 | https://github.com/matgrioni/betacode/blob/2f8b439c0de9cdf451b0b390161752cac9879137/betacode/conv.py#L17-L37 | train | 54,734 |
matgrioni/betacode | betacode/conv.py | _create_conversion_trie | def _create_conversion_trie(strict):
"""
Create the trie for betacode conversion.
Args:
text: The beta code text to convert. All of this text must be betacode.
strict: Flag to allow for flexible diacritic order on input.
Returns:
The trie for conversion.
"""
t = pygtrie.CharTrie()
for beta, uni in _map.BETACODE_MAP.items():
if strict:
t[beta] = uni
else:
# The order of accents is very strict and weak. Allow for many orders of
# accents between asterisk and letter or after letter. This does not
# introduce ambiguity since each betacode token only has one letter and
# either starts with a asterisk or a letter.
diacritics = beta[1:]
perms = itertools.permutations(diacritics)
for perm in perms:
perm_str = beta[0] + ''.join(perm)
t[perm_str.lower()] = uni
t[perm_str.upper()] = uni
return t | python | def _create_conversion_trie(strict):
"""
Create the trie for betacode conversion.
Args:
text: The beta code text to convert. All of this text must be betacode.
strict: Flag to allow for flexible diacritic order on input.
Returns:
The trie for conversion.
"""
t = pygtrie.CharTrie()
for beta, uni in _map.BETACODE_MAP.items():
if strict:
t[beta] = uni
else:
# The order of accents is very strict and weak. Allow for many orders of
# accents between asterisk and letter or after letter. This does not
# introduce ambiguity since each betacode token only has one letter and
# either starts with a asterisk or a letter.
diacritics = beta[1:]
perms = itertools.permutations(diacritics)
for perm in perms:
perm_str = beta[0] + ''.join(perm)
t[perm_str.lower()] = uni
t[perm_str.upper()] = uni
return t | [
"def",
"_create_conversion_trie",
"(",
"strict",
")",
":",
"t",
"=",
"pygtrie",
".",
"CharTrie",
"(",
")",
"for",
"beta",
",",
"uni",
"in",
"_map",
".",
"BETACODE_MAP",
".",
"items",
"(",
")",
":",
"if",
"strict",
":",
"t",
"[",
"beta",
"]",
"=",
"... | Create the trie for betacode conversion.
Args:
text: The beta code text to convert. All of this text must be betacode.
strict: Flag to allow for flexible diacritic order on input.
Returns:
The trie for conversion. | [
"Create",
"the",
"trie",
"for",
"betacode",
"conversion",
"."
] | 2f8b439c0de9cdf451b0b390161752cac9879137 | https://github.com/matgrioni/betacode/blob/2f8b439c0de9cdf451b0b390161752cac9879137/betacode/conv.py#L42-L71 | train | 54,735 |
matgrioni/betacode | betacode/conv.py | _find_max_beta_token_len | def _find_max_beta_token_len():
"""
Finds the maximum length of a single betacode token.
Returns:
The length of the longest key in the betacode map, which corresponds to the
longest single betacode token.
"""
max_beta_len = -1
for beta, uni in _map.BETACODE_MAP.items():
if len(beta) > max_beta_len:
max_beta_len = len(beta)
return max_beta_len | python | def _find_max_beta_token_len():
"""
Finds the maximum length of a single betacode token.
Returns:
The length of the longest key in the betacode map, which corresponds to the
longest single betacode token.
"""
max_beta_len = -1
for beta, uni in _map.BETACODE_MAP.items():
if len(beta) > max_beta_len:
max_beta_len = len(beta)
return max_beta_len | [
"def",
"_find_max_beta_token_len",
"(",
")",
":",
"max_beta_len",
"=",
"-",
"1",
"for",
"beta",
",",
"uni",
"in",
"_map",
".",
"BETACODE_MAP",
".",
"items",
"(",
")",
":",
"if",
"len",
"(",
"beta",
")",
">",
"max_beta_len",
":",
"max_beta_len",
"=",
"l... | Finds the maximum length of a single betacode token.
Returns:
The length of the longest key in the betacode map, which corresponds to the
longest single betacode token. | [
"Finds",
"the",
"maximum",
"length",
"of",
"a",
"single",
"betacode",
"token",
"."
] | 2f8b439c0de9cdf451b0b390161752cac9879137 | https://github.com/matgrioni/betacode/blob/2f8b439c0de9cdf451b0b390161752cac9879137/betacode/conv.py#L74-L87 | train | 54,736 |
matgrioni/betacode | betacode/conv.py | beta_to_uni | def beta_to_uni(text, strict=False):
"""
Converts the given text from betacode to unicode.
Args:
text: The beta code text to convert. All of this text must be betacode.
strict: Flag to allow for flexible diacritic order on input.
Returns:
The converted text.
"""
# Check if the requested configuration for conversion already has a trie
# stored otherwise convert it.
param_key = (strict,)
try:
t = _BETA_CONVERSION_TRIES[param_key]
except KeyError:
t = _create_conversion_trie(*param_key)
_BETA_CONVERSION_TRIES[param_key] = t
transform = []
idx = 0
possible_word_boundary = False
while idx < len(text):
if possible_word_boundary and _penultimate_sigma_word_final(transform):
transform[-2] = _FINAL_LC_SIGMA
step = t.longest_prefix(text[idx:idx + _MAX_BETA_TOKEN_LEN])
if step:
possible_word_boundary = text[idx] in _BETA_PUNCTUATION
key, value = step
transform.append(value)
idx += len(key)
else:
possible_word_boundary = True
transform.append(text[idx])
idx += 1
# Check one last time in case there is some whitespace or punctuation at the
# end and check if the last character is a sigma.
if possible_word_boundary and _penultimate_sigma_word_final(transform):
transform[-2] = _FINAL_LC_SIGMA
elif len(transform) > 0 and transform[-1] == _MEDIAL_LC_SIGMA:
transform[-1] = _FINAL_LC_SIGMA
converted = ''.join(transform)
return converted | python | def beta_to_uni(text, strict=False):
"""
Converts the given text from betacode to unicode.
Args:
text: The beta code text to convert. All of this text must be betacode.
strict: Flag to allow for flexible diacritic order on input.
Returns:
The converted text.
"""
# Check if the requested configuration for conversion already has a trie
# stored otherwise convert it.
param_key = (strict,)
try:
t = _BETA_CONVERSION_TRIES[param_key]
except KeyError:
t = _create_conversion_trie(*param_key)
_BETA_CONVERSION_TRIES[param_key] = t
transform = []
idx = 0
possible_word_boundary = False
while idx < len(text):
if possible_word_boundary and _penultimate_sigma_word_final(transform):
transform[-2] = _FINAL_LC_SIGMA
step = t.longest_prefix(text[idx:idx + _MAX_BETA_TOKEN_LEN])
if step:
possible_word_boundary = text[idx] in _BETA_PUNCTUATION
key, value = step
transform.append(value)
idx += len(key)
else:
possible_word_boundary = True
transform.append(text[idx])
idx += 1
# Check one last time in case there is some whitespace or punctuation at the
# end and check if the last character is a sigma.
if possible_word_boundary and _penultimate_sigma_word_final(transform):
transform[-2] = _FINAL_LC_SIGMA
elif len(transform) > 0 and transform[-1] == _MEDIAL_LC_SIGMA:
transform[-1] = _FINAL_LC_SIGMA
converted = ''.join(transform)
return converted | [
"def",
"beta_to_uni",
"(",
"text",
",",
"strict",
"=",
"False",
")",
":",
"# Check if the requested configuration for conversion already has a trie",
"# stored otherwise convert it.",
"param_key",
"=",
"(",
"strict",
",",
")",
"try",
":",
"t",
"=",
"_BETA_CONVERSION_TRIES... | Converts the given text from betacode to unicode.
Args:
text: The beta code text to convert. All of this text must be betacode.
strict: Flag to allow for flexible diacritic order on input.
Returns:
The converted text. | [
"Converts",
"the",
"given",
"text",
"from",
"betacode",
"to",
"unicode",
"."
] | 2f8b439c0de9cdf451b0b390161752cac9879137 | https://github.com/matgrioni/betacode/blob/2f8b439c0de9cdf451b0b390161752cac9879137/betacode/conv.py#L97-L147 | train | 54,737 |
matgrioni/betacode | betacode/conv.py | uni_to_beta | def uni_to_beta(text):
"""
Convert unicode text to a betacode equivalent.
This method can handle tónos or oxeîa characters in the input.
Args:
text: The text to convert to betacode. This text does not have to all be
Greek polytonic text, and only Greek characters will be converted. Note
that in this case, you cannot convert to beta and then back to unicode.
Returns:
The betacode equivalent of the inputted text where applicable.
"""
u = _UNICODE_MAP
transform = []
for ch in text:
try:
conv = u[ch]
except KeyError:
conv = ch
transform.append(conv)
converted = ''.join(transform)
return converted | python | def uni_to_beta(text):
"""
Convert unicode text to a betacode equivalent.
This method can handle tónos or oxeîa characters in the input.
Args:
text: The text to convert to betacode. This text does not have to all be
Greek polytonic text, and only Greek characters will be converted. Note
that in this case, you cannot convert to beta and then back to unicode.
Returns:
The betacode equivalent of the inputted text where applicable.
"""
u = _UNICODE_MAP
transform = []
for ch in text:
try:
conv = u[ch]
except KeyError:
conv = ch
transform.append(conv)
converted = ''.join(transform)
return converted | [
"def",
"uni_to_beta",
"(",
"text",
")",
":",
"u",
"=",
"_UNICODE_MAP",
"transform",
"=",
"[",
"]",
"for",
"ch",
"in",
"text",
":",
"try",
":",
"conv",
"=",
"u",
"[",
"ch",
"]",
"except",
"KeyError",
":",
"conv",
"=",
"ch",
"transform",
".",
"append... | Convert unicode text to a betacode equivalent.
This method can handle tónos or oxeîa characters in the input.
Args:
text: The text to convert to betacode. This text does not have to all be
Greek polytonic text, and only Greek characters will be converted. Note
that in this case, you cannot convert to beta and then back to unicode.
Returns:
The betacode equivalent of the inputted text where applicable. | [
"Convert",
"unicode",
"text",
"to",
"a",
"betacode",
"equivalent",
"."
] | 2f8b439c0de9cdf451b0b390161752cac9879137 | https://github.com/matgrioni/betacode/blob/2f8b439c0de9cdf451b0b390161752cac9879137/betacode/conv.py#L149-L176 | train | 54,738 |
toumorokoshi/sprinter | sprinter/lib/dependencytree.py | DependencyTree.__calculate_order | def __calculate_order(self, node_dict):
"""
Determine a valid ordering of the nodes in which a node is not called before all of it's dependencies.
Raise an error if there is a cycle, or nodes are missing.
"""
if len(node_dict.keys()) != len(set(node_dict.keys())):
raise DependencyTreeException("Duplicate Keys Exist in node dictionary!")
valid_order = [node for node, dependencies in node_dict.items() if len(dependencies) == 0]
remaining_nodes = [node for node in node_dict.keys() if node not in valid_order]
while len(remaining_nodes) > 0:
node_added = False
for node in remaining_nodes:
dependencies = [d for d in node_dict[node] if d not in valid_order]
if len(dependencies) == 0:
valid_order.append(node)
remaining_nodes.remove(node)
node_added = True
if not node_added:
# the tree must be invalid, as it was not possible to remove a node.
# it's hard to find all the errors, so just spit out the first one you can find.
invalid_node = remaining_nodes[0]
invalid_dependency = ', '.join(node_dict[invalid_node])
if invalid_dependency not in remaining_nodes:
raise DependencyTreeException(
"Missing dependency! One or more of ({dependency}) are missing for {dependant}.".format(
dependant=invalid_node, dependency=invalid_dependency))
else:
raise DependencyTreeException("The dependency %s is cyclic or dependent on a cyclic dependency" % invalid_dependency)
return valid_order | python | def __calculate_order(self, node_dict):
"""
Determine a valid ordering of the nodes in which a node is not called before all of it's dependencies.
Raise an error if there is a cycle, or nodes are missing.
"""
if len(node_dict.keys()) != len(set(node_dict.keys())):
raise DependencyTreeException("Duplicate Keys Exist in node dictionary!")
valid_order = [node for node, dependencies in node_dict.items() if len(dependencies) == 0]
remaining_nodes = [node for node in node_dict.keys() if node not in valid_order]
while len(remaining_nodes) > 0:
node_added = False
for node in remaining_nodes:
dependencies = [d for d in node_dict[node] if d not in valid_order]
if len(dependencies) == 0:
valid_order.append(node)
remaining_nodes.remove(node)
node_added = True
if not node_added:
# the tree must be invalid, as it was not possible to remove a node.
# it's hard to find all the errors, so just spit out the first one you can find.
invalid_node = remaining_nodes[0]
invalid_dependency = ', '.join(node_dict[invalid_node])
if invalid_dependency not in remaining_nodes:
raise DependencyTreeException(
"Missing dependency! One or more of ({dependency}) are missing for {dependant}.".format(
dependant=invalid_node, dependency=invalid_dependency))
else:
raise DependencyTreeException("The dependency %s is cyclic or dependent on a cyclic dependency" % invalid_dependency)
return valid_order | [
"def",
"__calculate_order",
"(",
"self",
",",
"node_dict",
")",
":",
"if",
"len",
"(",
"node_dict",
".",
"keys",
"(",
")",
")",
"!=",
"len",
"(",
"set",
"(",
"node_dict",
".",
"keys",
"(",
")",
")",
")",
":",
"raise",
"DependencyTreeException",
"(",
... | Determine a valid ordering of the nodes in which a node is not called before all of it's dependencies.
Raise an error if there is a cycle, or nodes are missing. | [
"Determine",
"a",
"valid",
"ordering",
"of",
"the",
"nodes",
"in",
"which",
"a",
"node",
"is",
"not",
"called",
"before",
"all",
"of",
"it",
"s",
"dependencies",
"."
] | 846697a7a087e69c61d075232e754d6975a64152 | https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/lib/dependencytree.py#L24-L53 | train | 54,739 |
smarie/python-parsyfiles | parsyfiles/parsing_fw.py | warn_import_error | def warn_import_error(type_of_obj_support: str, caught: ImportError):
"""
Utility method to print a warning message about failed import of some modules
:param type_of_obj_support:
:param caught:
:return:
"""
msg = StringIO()
msg.writelines('Import Error while trying to add support for ' + type_of_obj_support + '. You may continue but '
'the associated parsers and converters wont be available : \n')
traceback.print_tb(caught.__traceback__, file=msg)
msg.writelines(str(caught.__class__.__name__) + ' : ' + str(caught) + '\n')
warn(msg.getvalue()) | python | def warn_import_error(type_of_obj_support: str, caught: ImportError):
"""
Utility method to print a warning message about failed import of some modules
:param type_of_obj_support:
:param caught:
:return:
"""
msg = StringIO()
msg.writelines('Import Error while trying to add support for ' + type_of_obj_support + '. You may continue but '
'the associated parsers and converters wont be available : \n')
traceback.print_tb(caught.__traceback__, file=msg)
msg.writelines(str(caught.__class__.__name__) + ' : ' + str(caught) + '\n')
warn(msg.getvalue()) | [
"def",
"warn_import_error",
"(",
"type_of_obj_support",
":",
"str",
",",
"caught",
":",
"ImportError",
")",
":",
"msg",
"=",
"StringIO",
"(",
")",
"msg",
".",
"writelines",
"(",
"'Import Error while trying to add support for '",
"+",
"type_of_obj_support",
"+",
"'. ... | Utility method to print a warning message about failed import of some modules
:param type_of_obj_support:
:param caught:
:return: | [
"Utility",
"method",
"to",
"print",
"a",
"warning",
"message",
"about",
"failed",
"import",
"of",
"some",
"modules"
] | 344b37e1151e8d4e7c2ee49ae09d6568715ae64e | https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/parsing_fw.py#L33-L46 | train | 54,740 |
smarie/python-parsyfiles | parsyfiles/parsing_fw.py | create_parser_options | def create_parser_options(lazy_mfcollection_parsing: bool = False) -> Dict[str, Dict[str, Any]]:
"""
Utility method to create a default options structure with the lazy parsing inside
:param lazy_mfcollection_parsing:
:return: the options structure filled with lazyparsing option (for the MultifileCollectionParser)
"""
return {MultifileCollectionParser.__name__: {'lazy_parsing': lazy_mfcollection_parsing}} | python | def create_parser_options(lazy_mfcollection_parsing: bool = False) -> Dict[str, Dict[str, Any]]:
"""
Utility method to create a default options structure with the lazy parsing inside
:param lazy_mfcollection_parsing:
:return: the options structure filled with lazyparsing option (for the MultifileCollectionParser)
"""
return {MultifileCollectionParser.__name__: {'lazy_parsing': lazy_mfcollection_parsing}} | [
"def",
"create_parser_options",
"(",
"lazy_mfcollection_parsing",
":",
"bool",
"=",
"False",
")",
"->",
"Dict",
"[",
"str",
",",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"return",
"{",
"MultifileCollectionParser",
".",
"__name__",
":",
"{",
"'lazy_pars... | Utility method to create a default options structure with the lazy parsing inside
:param lazy_mfcollection_parsing:
:return: the options structure filled with lazyparsing option (for the MultifileCollectionParser) | [
"Utility",
"method",
"to",
"create",
"a",
"default",
"options",
"structure",
"with",
"the",
"lazy",
"parsing",
"inside"
] | 344b37e1151e8d4e7c2ee49ae09d6568715ae64e | https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/parsing_fw.py#L49-L56 | train | 54,741 |
smarie/python-parsyfiles | parsyfiles/parsing_fw.py | register_default_plugins | def register_default_plugins(root_parser: ParserRegistryWithConverters):
"""
Utility method to register all default plugins on the given parser+converter registry
:param root_parser:
:return:
"""
# -------------------- CORE ---------------------------
try:
# -- primitive types
from parsyfiles.plugins_base.support_for_primitive_types import get_default_primitive_parsers, \
get_default_primitive_converters
root_parser.register_parsers(get_default_primitive_parsers())
root_parser.register_converters(get_default_primitive_converters())
except ImportError as e:
warn_import_error('primitive types', e)
try:
# -- collections
from parsyfiles.plugins_base.support_for_collections import get_default_collection_parsers, \
get_default_collection_converters
root_parser.register_parsers(get_default_collection_parsers(root_parser, root_parser))
root_parser.register_converters(get_default_collection_converters(root_parser))
except ImportError as e:
warn_import_error('dict', e)
try:
# -- objects
from parsyfiles.plugins_base.support_for_objects import get_default_object_parsers, \
get_default_object_converters
root_parser.register_parsers(get_default_object_parsers(root_parser, root_parser))
root_parser.register_converters(get_default_object_converters(root_parser))
except ImportError as e:
warn_import_error('objects', e)
try:
# -- config
from parsyfiles.plugins_base.support_for_configparser import get_default_config_parsers, \
get_default_config_converters
root_parser.register_parsers(get_default_config_parsers())
root_parser.register_converters(get_default_config_converters(root_parser))
except ImportError as e:
warn_import_error('config', e)
# ------------------------- OPTIONAL -----------------
try:
# -- jprops
from parsyfiles.plugins_optional.support_for_jprops import get_default_jprops_parsers
root_parser.register_parsers(get_default_jprops_parsers(root_parser, root_parser))
# root_parser.register_converters()
except ImportError as e:
warn_import_error('jprops', e)
try:
# -- yaml
from parsyfiles.plugins_optional.support_for_yaml import get_default_yaml_parsers
root_parser.register_parsers(get_default_yaml_parsers(root_parser, root_parser))
# root_parser.register_converters()
except ImportError as e:
warn_import_error('yaml', e)
try:
# -- numpy
from parsyfiles.plugins_optional.support_for_numpy import get_default_np_parsers, get_default_np_converters
root_parser.register_parsers(get_default_np_parsers())
root_parser.register_converters(get_default_np_converters())
except ImportError as e:
warn_import_error('numpy', e)
try:
# -- pandas
from parsyfiles.plugins_optional.support_for_pandas import get_default_pandas_parsers, \
get_default_pandas_converters
root_parser.register_parsers(get_default_pandas_parsers())
root_parser.register_converters(get_default_pandas_converters())
except ImportError as e:
warn_import_error('pandas', e) | python | def register_default_plugins(root_parser: ParserRegistryWithConverters):
"""
Utility method to register all default plugins on the given parser+converter registry
:param root_parser:
:return:
"""
# -------------------- CORE ---------------------------
try:
# -- primitive types
from parsyfiles.plugins_base.support_for_primitive_types import get_default_primitive_parsers, \
get_default_primitive_converters
root_parser.register_parsers(get_default_primitive_parsers())
root_parser.register_converters(get_default_primitive_converters())
except ImportError as e:
warn_import_error('primitive types', e)
try:
# -- collections
from parsyfiles.plugins_base.support_for_collections import get_default_collection_parsers, \
get_default_collection_converters
root_parser.register_parsers(get_default_collection_parsers(root_parser, root_parser))
root_parser.register_converters(get_default_collection_converters(root_parser))
except ImportError as e:
warn_import_error('dict', e)
try:
# -- objects
from parsyfiles.plugins_base.support_for_objects import get_default_object_parsers, \
get_default_object_converters
root_parser.register_parsers(get_default_object_parsers(root_parser, root_parser))
root_parser.register_converters(get_default_object_converters(root_parser))
except ImportError as e:
warn_import_error('objects', e)
try:
# -- config
from parsyfiles.plugins_base.support_for_configparser import get_default_config_parsers, \
get_default_config_converters
root_parser.register_parsers(get_default_config_parsers())
root_parser.register_converters(get_default_config_converters(root_parser))
except ImportError as e:
warn_import_error('config', e)
# ------------------------- OPTIONAL -----------------
try:
# -- jprops
from parsyfiles.plugins_optional.support_for_jprops import get_default_jprops_parsers
root_parser.register_parsers(get_default_jprops_parsers(root_parser, root_parser))
# root_parser.register_converters()
except ImportError as e:
warn_import_error('jprops', e)
try:
# -- yaml
from parsyfiles.plugins_optional.support_for_yaml import get_default_yaml_parsers
root_parser.register_parsers(get_default_yaml_parsers(root_parser, root_parser))
# root_parser.register_converters()
except ImportError as e:
warn_import_error('yaml', e)
try:
# -- numpy
from parsyfiles.plugins_optional.support_for_numpy import get_default_np_parsers, get_default_np_converters
root_parser.register_parsers(get_default_np_parsers())
root_parser.register_converters(get_default_np_converters())
except ImportError as e:
warn_import_error('numpy', e)
try:
# -- pandas
from parsyfiles.plugins_optional.support_for_pandas import get_default_pandas_parsers, \
get_default_pandas_converters
root_parser.register_parsers(get_default_pandas_parsers())
root_parser.register_converters(get_default_pandas_converters())
except ImportError as e:
warn_import_error('pandas', e) | [
"def",
"register_default_plugins",
"(",
"root_parser",
":",
"ParserRegistryWithConverters",
")",
":",
"# -------------------- CORE ---------------------------",
"try",
":",
"# -- primitive types",
"from",
"parsyfiles",
".",
"plugins_base",
".",
"support_for_primitive_types",
"imp... | Utility method to register all default plugins on the given parser+converter registry
:param root_parser:
:return: | [
"Utility",
"method",
"to",
"register",
"all",
"default",
"plugins",
"on",
"the",
"given",
"parser",
"+",
"converter",
"registry"
] | 344b37e1151e8d4e7c2ee49ae09d6568715ae64e | https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/parsing_fw.py#L75-L145 | train | 54,742 |
smarie/python-parsyfiles | parsyfiles/parsing_fw.py | RootParser.parse_collection | def parse_collection(self, item_file_prefix: str, base_item_type: Type[T], item_name_for_log: str = None,
file_mapping_conf: FileMappingConfiguration = None,
options: Dict[str, Dict[str, Any]] = None) -> Dict[str, T]:
"""
Main method to parse a collection of items of type 'base_item_type'.
:param item_file_prefix:
:param base_item_type:
:param item_name_for_log:
:param file_mapping_conf:
:param options:
:return:
"""
# -- item_name_for_log
item_name_for_log = item_name_for_log or ''
check_var(item_name_for_log, var_types=str, var_name='item_name_for_log')
# creating the wrapping dictionary type
collection_type = Dict[str, base_item_type]
if len(item_name_for_log) > 0:
item_name_for_log = item_name_for_log + ' '
self.logger.debug('**** Starting to parse ' + item_name_for_log + 'collection of <'
+ get_pretty_type_str(base_item_type) + '> at location ' + item_file_prefix +' ****')
# common steps
return self._parse__item(collection_type, item_file_prefix, file_mapping_conf, options=options) | python | def parse_collection(self, item_file_prefix: str, base_item_type: Type[T], item_name_for_log: str = None,
file_mapping_conf: FileMappingConfiguration = None,
options: Dict[str, Dict[str, Any]] = None) -> Dict[str, T]:
"""
Main method to parse a collection of items of type 'base_item_type'.
:param item_file_prefix:
:param base_item_type:
:param item_name_for_log:
:param file_mapping_conf:
:param options:
:return:
"""
# -- item_name_for_log
item_name_for_log = item_name_for_log or ''
check_var(item_name_for_log, var_types=str, var_name='item_name_for_log')
# creating the wrapping dictionary type
collection_type = Dict[str, base_item_type]
if len(item_name_for_log) > 0:
item_name_for_log = item_name_for_log + ' '
self.logger.debug('**** Starting to parse ' + item_name_for_log + 'collection of <'
+ get_pretty_type_str(base_item_type) + '> at location ' + item_file_prefix +' ****')
# common steps
return self._parse__item(collection_type, item_file_prefix, file_mapping_conf, options=options) | [
"def",
"parse_collection",
"(",
"self",
",",
"item_file_prefix",
":",
"str",
",",
"base_item_type",
":",
"Type",
"[",
"T",
"]",
",",
"item_name_for_log",
":",
"str",
"=",
"None",
",",
"file_mapping_conf",
":",
"FileMappingConfiguration",
"=",
"None",
",",
"opt... | Main method to parse a collection of items of type 'base_item_type'.
:param item_file_prefix:
:param base_item_type:
:param item_name_for_log:
:param file_mapping_conf:
:param options:
:return: | [
"Main",
"method",
"to",
"parse",
"a",
"collection",
"of",
"items",
"of",
"type",
"base_item_type",
"."
] | 344b37e1151e8d4e7c2ee49ae09d6568715ae64e | https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/parsing_fw.py#L226-L251 | train | 54,743 |
smarie/python-parsyfiles | parsyfiles/parsing_fw.py | RootParser.parse_item | def parse_item(self, location: str, item_type: Type[T], item_name_for_log: str = None,
file_mapping_conf: FileMappingConfiguration = None, options: Dict[str, Dict[str, Any]] = None) -> T:
"""
Main method to parse an item of type item_type
:param location:
:param item_type:
:param item_name_for_log:
:param file_mapping_conf:
:param options:
:return:
"""
# -- item_name_for_log
item_name_for_log = item_name_for_log or ''
check_var(item_name_for_log, var_types=str, var_name='item_name_for_log')
if len(item_name_for_log) > 0:
item_name_for_log = item_name_for_log + ' '
self.logger.debug('**** Starting to parse single object ' + item_name_for_log + 'of type <'
+ get_pretty_type_str(item_type) + '> at location ' + location + ' ****')
# common steps
return self._parse__item(item_type, location, file_mapping_conf, options=options) | python | def parse_item(self, location: str, item_type: Type[T], item_name_for_log: str = None,
file_mapping_conf: FileMappingConfiguration = None, options: Dict[str, Dict[str, Any]] = None) -> T:
"""
Main method to parse an item of type item_type
:param location:
:param item_type:
:param item_name_for_log:
:param file_mapping_conf:
:param options:
:return:
"""
# -- item_name_for_log
item_name_for_log = item_name_for_log or ''
check_var(item_name_for_log, var_types=str, var_name='item_name_for_log')
if len(item_name_for_log) > 0:
item_name_for_log = item_name_for_log + ' '
self.logger.debug('**** Starting to parse single object ' + item_name_for_log + 'of type <'
+ get_pretty_type_str(item_type) + '> at location ' + location + ' ****')
# common steps
return self._parse__item(item_type, location, file_mapping_conf, options=options) | [
"def",
"parse_item",
"(",
"self",
",",
"location",
":",
"str",
",",
"item_type",
":",
"Type",
"[",
"T",
"]",
",",
"item_name_for_log",
":",
"str",
"=",
"None",
",",
"file_mapping_conf",
":",
"FileMappingConfiguration",
"=",
"None",
",",
"options",
":",
"Di... | Main method to parse an item of type item_type
:param location:
:param item_type:
:param item_name_for_log:
:param file_mapping_conf:
:param options:
:return: | [
"Main",
"method",
"to",
"parse",
"an",
"item",
"of",
"type",
"item_type"
] | 344b37e1151e8d4e7c2ee49ae09d6568715ae64e | https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/parsing_fw.py#L253-L276 | train | 54,744 |
smarie/python-parsyfiles | parsyfiles/parsing_fw.py | RootParser._parse__item | def _parse__item(self, item_type: Type[T], item_file_prefix: str,
file_mapping_conf: FileMappingConfiguration = None,
options: Dict[str, Dict[str, Any]] = None) -> T:
"""
Common parsing steps to parse an item
:param item_type:
:param item_file_prefix:
:param file_mapping_conf:
:param options:
:return:
"""
# for consistency : if options is None, default to the default values of create_parser_options
options = options or create_parser_options()
# creating the persisted object (this performs required checks)
file_mapping_conf = file_mapping_conf or WrappedFileMappingConfiguration()
obj = file_mapping_conf.create_persisted_object(item_file_prefix, logger=self.logger)
# print('')
self.logger.debug('')
# create the parsing plan
pp = self.create_parsing_plan(item_type, obj, logger=self.logger)
# print('')
self.logger.debug('')
# parse
res = pp.execute(logger=self.logger, options=options)
# print('')
self.logger.debug('')
return res | python | def _parse__item(self, item_type: Type[T], item_file_prefix: str,
file_mapping_conf: FileMappingConfiguration = None,
options: Dict[str, Dict[str, Any]] = None) -> T:
"""
Common parsing steps to parse an item
:param item_type:
:param item_file_prefix:
:param file_mapping_conf:
:param options:
:return:
"""
# for consistency : if options is None, default to the default values of create_parser_options
options = options or create_parser_options()
# creating the persisted object (this performs required checks)
file_mapping_conf = file_mapping_conf or WrappedFileMappingConfiguration()
obj = file_mapping_conf.create_persisted_object(item_file_prefix, logger=self.logger)
# print('')
self.logger.debug('')
# create the parsing plan
pp = self.create_parsing_plan(item_type, obj, logger=self.logger)
# print('')
self.logger.debug('')
# parse
res = pp.execute(logger=self.logger, options=options)
# print('')
self.logger.debug('')
return res | [
"def",
"_parse__item",
"(",
"self",
",",
"item_type",
":",
"Type",
"[",
"T",
"]",
",",
"item_file_prefix",
":",
"str",
",",
"file_mapping_conf",
":",
"FileMappingConfiguration",
"=",
"None",
",",
"options",
":",
"Dict",
"[",
"str",
",",
"Dict",
"[",
"str",... | Common parsing steps to parse an item
:param item_type:
:param item_file_prefix:
:param file_mapping_conf:
:param options:
:return: | [
"Common",
"parsing",
"steps",
"to",
"parse",
"an",
"item"
] | 344b37e1151e8d4e7c2ee49ae09d6568715ae64e | https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/parsing_fw.py#L278-L310 | train | 54,745 |
bniemczyk/automata | automata/fuzzystring.py | FuzzyStringUtility.SpamsumDistance | def SpamsumDistance(ssA, ssB):
'''
returns the spamsum distance between ssA and ssB
if they use a different block size, assume maximum distance
otherwise returns the LevDistance
'''
mA = re.match('^(\d+)[:](.*)$', ssA)
mB = re.match('^(\d+)[:](.*)$', ssB)
if mA == None or mB == None:
raise "do not appear to be spamsum signatures"
if mA.group(1) != mB.group(1):
return max([len(mA.group(2)), len(mB.group(2))])
else:
return LevDistance(mA.group(2), mB.group(2)) | python | def SpamsumDistance(ssA, ssB):
'''
returns the spamsum distance between ssA and ssB
if they use a different block size, assume maximum distance
otherwise returns the LevDistance
'''
mA = re.match('^(\d+)[:](.*)$', ssA)
mB = re.match('^(\d+)[:](.*)$', ssB)
if mA == None or mB == None:
raise "do not appear to be spamsum signatures"
if mA.group(1) != mB.group(1):
return max([len(mA.group(2)), len(mB.group(2))])
else:
return LevDistance(mA.group(2), mB.group(2)) | [
"def",
"SpamsumDistance",
"(",
"ssA",
",",
"ssB",
")",
":",
"mA",
"=",
"re",
".",
"match",
"(",
"'^(\\d+)[:](.*)$'",
",",
"ssA",
")",
"mB",
"=",
"re",
".",
"match",
"(",
"'^(\\d+)[:](.*)$'",
",",
"ssB",
")",
"if",
"mA",
"==",
"None",
"or",
"mB",
"=... | returns the spamsum distance between ssA and ssB
if they use a different block size, assume maximum distance
otherwise returns the LevDistance | [
"returns",
"the",
"spamsum",
"distance",
"between",
"ssA",
"and",
"ssB",
"if",
"they",
"use",
"a",
"different",
"block",
"size",
"assume",
"maximum",
"distance",
"otherwise",
"returns",
"the",
"LevDistance"
] | b4e21ba8b881f2cb1a07a813a4011209a3f1e017 | https://github.com/bniemczyk/automata/blob/b4e21ba8b881f2cb1a07a813a4011209a3f1e017/automata/fuzzystring.py#L49-L64 | train | 54,746 |
bioidiap/bob.ip.facedetect | bob/ip/facedetect/train/TrainingSet.py | TrainingSet.add_image | def add_image(self, image_path, annotations):
"""Adds an image and its bounding boxes to the current list of files
The bounding boxes are automatically estimated based on the given annotations.
**Parameters:**
``image_path`` : str
The file name of the image, including its full path
``annotations`` : [dict]
A list of annotations, i.e., where each annotation can be anything that :py:func:`bounding_box_from_annotation` can handle; this list can be empty, in case the image does not contain any faces
"""
self.image_paths.append(image_path)
self.bounding_boxes.append([bounding_box_from_annotation(**a) for a in annotations]) | python | def add_image(self, image_path, annotations):
"""Adds an image and its bounding boxes to the current list of files
The bounding boxes are automatically estimated based on the given annotations.
**Parameters:**
``image_path`` : str
The file name of the image, including its full path
``annotations`` : [dict]
A list of annotations, i.e., where each annotation can be anything that :py:func:`bounding_box_from_annotation` can handle; this list can be empty, in case the image does not contain any faces
"""
self.image_paths.append(image_path)
self.bounding_boxes.append([bounding_box_from_annotation(**a) for a in annotations]) | [
"def",
"add_image",
"(",
"self",
",",
"image_path",
",",
"annotations",
")",
":",
"self",
".",
"image_paths",
".",
"append",
"(",
"image_path",
")",
"self",
".",
"bounding_boxes",
".",
"append",
"(",
"[",
"bounding_box_from_annotation",
"(",
"*",
"*",
"a",
... | Adds an image and its bounding boxes to the current list of files
The bounding boxes are automatically estimated based on the given annotations.
**Parameters:**
``image_path`` : str
The file name of the image, including its full path
``annotations`` : [dict]
A list of annotations, i.e., where each annotation can be anything that :py:func:`bounding_box_from_annotation` can handle; this list can be empty, in case the image does not contain any faces | [
"Adds",
"an",
"image",
"and",
"its",
"bounding",
"boxes",
"to",
"the",
"current",
"list",
"of",
"files"
] | 601da5141ca7302ad36424d1421b33190ba46779 | https://github.com/bioidiap/bob.ip.facedetect/blob/601da5141ca7302ad36424d1421b33190ba46779/bob/ip/facedetect/train/TrainingSet.py#L47-L61 | train | 54,747 |
bioidiap/bob.ip.facedetect | bob/ip/facedetect/train/TrainingSet.py | TrainingSet.save | def save(self, list_file):
"""Saves the current list of annotations to the given file.
**Parameters:**
``list_file`` : str
The name of a list file to write the currently stored list into
"""
bob.io.base.create_directories_safe(os.path.dirname(list_file))
with open(list_file, 'w') as f:
for i in range(len(self.image_paths)):
f.write(self.image_paths[i])
for bbx in self.bounding_boxes[i]:
f.write("\t[%f %f %f %f]" % (bbx.top_f, bbx.left_f, bbx.size_f[0], bbx.size_f[1]))
f.write("\n") | python | def save(self, list_file):
"""Saves the current list of annotations to the given file.
**Parameters:**
``list_file`` : str
The name of a list file to write the currently stored list into
"""
bob.io.base.create_directories_safe(os.path.dirname(list_file))
with open(list_file, 'w') as f:
for i in range(len(self.image_paths)):
f.write(self.image_paths[i])
for bbx in self.bounding_boxes[i]:
f.write("\t[%f %f %f %f]" % (bbx.top_f, bbx.left_f, bbx.size_f[0], bbx.size_f[1]))
f.write("\n") | [
"def",
"save",
"(",
"self",
",",
"list_file",
")",
":",
"bob",
".",
"io",
".",
"base",
".",
"create_directories_safe",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"list_file",
")",
")",
"with",
"open",
"(",
"list_file",
",",
"'w'",
")",
"as",
"f",
... | Saves the current list of annotations to the given file.
**Parameters:**
``list_file`` : str
The name of a list file to write the currently stored list into | [
"Saves",
"the",
"current",
"list",
"of",
"annotations",
"to",
"the",
"given",
"file",
"."
] | 601da5141ca7302ad36424d1421b33190ba46779 | https://github.com/bioidiap/bob.ip.facedetect/blob/601da5141ca7302ad36424d1421b33190ba46779/bob/ip/facedetect/train/TrainingSet.py#L79-L93 | train | 54,748 |
bioidiap/bob.ip.facedetect | bob/ip/facedetect/train/TrainingSet.py | TrainingSet._feature_file | def _feature_file(self, parallel = None, index = None):
"""Returns the name of an intermediate file for storing features."""
if index is None:
index = 0 if parallel is None or "SGE_TASK_ID" not in os.environ else int(os.environ["SGE_TASK_ID"])
return os.path.join(self.feature_directory, "Features_%02d.hdf5" % index) | python | def _feature_file(self, parallel = None, index = None):
"""Returns the name of an intermediate file for storing features."""
if index is None:
index = 0 if parallel is None or "SGE_TASK_ID" not in os.environ else int(os.environ["SGE_TASK_ID"])
return os.path.join(self.feature_directory, "Features_%02d.hdf5" % index) | [
"def",
"_feature_file",
"(",
"self",
",",
"parallel",
"=",
"None",
",",
"index",
"=",
"None",
")",
":",
"if",
"index",
"is",
"None",
":",
"index",
"=",
"0",
"if",
"parallel",
"is",
"None",
"or",
"\"SGE_TASK_ID\"",
"not",
"in",
"os",
".",
"environ",
"... | Returns the name of an intermediate file for storing features. | [
"Returns",
"the",
"name",
"of",
"an",
"intermediate",
"file",
"for",
"storing",
"features",
"."
] | 601da5141ca7302ad36424d1421b33190ba46779 | https://github.com/bioidiap/bob.ip.facedetect/blob/601da5141ca7302ad36424d1421b33190ba46779/bob/ip/facedetect/train/TrainingSet.py#L146-L150 | train | 54,749 |
toumorokoshi/sprinter | sprinter/core/featureconfig.py | FeatureConfig.get | def get(self, param, default=EMPTY):
"""
Returns the nparam value, and returns the default if it doesn't exist.
If default is none, an exception will be raised instead.
the returned parameter will have been specialized against the global context
"""
if not self.has(param):
if default is not EMPTY:
return default
raise ParamNotFoundException("value for %s not found" % param)
context_dict = copy.deepcopy(self.manifest.get_context_dict())
for k, v in self.raw_dict.items():
context_dict["%s:%s" % (self.feature_name, k)] = v
cur_value = self.raw_dict[param]
prev_value = None
max_depth = 5
# apply the context until doing so does not change the value
while cur_value != prev_value and max_depth > 0:
prev_value = cur_value
try:
cur_value = str(prev_value) % context_dict
except KeyError:
e = sys.exc_info()[1]
key = e.args[0]
if key.startswith('config:'):
missing_key = key.split(':')[1]
if self.manifest.inputs.is_input(missing_key):
val = self.manifest.inputs.get_input(missing_key)
context_dict[key] = val
else:
logger.warn("Could not specialize %s! Error: %s" % (self.raw_dict[param], e))
return self.raw_dict[param]
except ValueError:
# this is an esoteric error, and this implementation
# forces a terrible solution. Sorry.
# using the standard escaping syntax in python is a mistake.
# if a value has a "%" inside (e.g. a password), a ValueError
# is raised, causing an issue
return cur_value
max_depth -= 1
return cur_value | python | def get(self, param, default=EMPTY):
"""
Returns the nparam value, and returns the default if it doesn't exist.
If default is none, an exception will be raised instead.
the returned parameter will have been specialized against the global context
"""
if not self.has(param):
if default is not EMPTY:
return default
raise ParamNotFoundException("value for %s not found" % param)
context_dict = copy.deepcopy(self.manifest.get_context_dict())
for k, v in self.raw_dict.items():
context_dict["%s:%s" % (self.feature_name, k)] = v
cur_value = self.raw_dict[param]
prev_value = None
max_depth = 5
# apply the context until doing so does not change the value
while cur_value != prev_value and max_depth > 0:
prev_value = cur_value
try:
cur_value = str(prev_value) % context_dict
except KeyError:
e = sys.exc_info()[1]
key = e.args[0]
if key.startswith('config:'):
missing_key = key.split(':')[1]
if self.manifest.inputs.is_input(missing_key):
val = self.manifest.inputs.get_input(missing_key)
context_dict[key] = val
else:
logger.warn("Could not specialize %s! Error: %s" % (self.raw_dict[param], e))
return self.raw_dict[param]
except ValueError:
# this is an esoteric error, and this implementation
# forces a terrible solution. Sorry.
# using the standard escaping syntax in python is a mistake.
# if a value has a "%" inside (e.g. a password), a ValueError
# is raised, causing an issue
return cur_value
max_depth -= 1
return cur_value | [
"def",
"get",
"(",
"self",
",",
"param",
",",
"default",
"=",
"EMPTY",
")",
":",
"if",
"not",
"self",
".",
"has",
"(",
"param",
")",
":",
"if",
"default",
"is",
"not",
"EMPTY",
":",
"return",
"default",
"raise",
"ParamNotFoundException",
"(",
"\"value ... | Returns the nparam value, and returns the default if it doesn't exist.
If default is none, an exception will be raised instead.
the returned parameter will have been specialized against the global context | [
"Returns",
"the",
"nparam",
"value",
"and",
"returns",
"the",
"default",
"if",
"it",
"doesn",
"t",
"exist",
".",
"If",
"default",
"is",
"none",
"an",
"exception",
"will",
"be",
"raised",
"instead",
"."
] | 846697a7a087e69c61d075232e754d6975a64152 | https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/core/featureconfig.py#L27-L68 | train | 54,750 |
toumorokoshi/sprinter | sprinter/core/featureconfig.py | FeatureConfig.set | def set(self, param, value):
""" sets the param to the value provided """
self.raw_dict[param] = value
self.manifest.set(self.feature_name, param, value) | python | def set(self, param, value):
""" sets the param to the value provided """
self.raw_dict[param] = value
self.manifest.set(self.feature_name, param, value) | [
"def",
"set",
"(",
"self",
",",
"param",
",",
"value",
")",
":",
"self",
".",
"raw_dict",
"[",
"param",
"]",
"=",
"value",
"self",
".",
"manifest",
".",
"set",
"(",
"self",
".",
"feature_name",
",",
"param",
",",
"value",
")"
] | sets the param to the value provided | [
"sets",
"the",
"param",
"to",
"the",
"value",
"provided"
] | 846697a7a087e69c61d075232e754d6975a64152 | https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/core/featureconfig.py#L74-L77 | train | 54,751 |
toumorokoshi/sprinter | sprinter/core/featureconfig.py | FeatureConfig.remove | def remove(self, param):
""" Remove a parameter from the manifest """
if self.has(param):
del(self.raw_dict[param])
self.manifest.remove_option(self.feature_name, param) | python | def remove(self, param):
""" Remove a parameter from the manifest """
if self.has(param):
del(self.raw_dict[param])
self.manifest.remove_option(self.feature_name, param) | [
"def",
"remove",
"(",
"self",
",",
"param",
")",
":",
"if",
"self",
".",
"has",
"(",
"param",
")",
":",
"del",
"(",
"self",
".",
"raw_dict",
"[",
"param",
"]",
")",
"self",
".",
"manifest",
".",
"remove_option",
"(",
"self",
".",
"feature_name",
",... | Remove a parameter from the manifest | [
"Remove",
"a",
"parameter",
"from",
"the",
"manifest"
] | 846697a7a087e69c61d075232e754d6975a64152 | https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/core/featureconfig.py#L79-L83 | train | 54,752 |
toumorokoshi/sprinter | sprinter/core/featureconfig.py | FeatureConfig.set_if_empty | def set_if_empty(self, param, default):
""" Set the parameter to the default if it doesn't exist """
if not self.has(param):
self.set(param, default) | python | def set_if_empty(self, param, default):
""" Set the parameter to the default if it doesn't exist """
if not self.has(param):
self.set(param, default) | [
"def",
"set_if_empty",
"(",
"self",
",",
"param",
",",
"default",
")",
":",
"if",
"not",
"self",
".",
"has",
"(",
"param",
")",
":",
"self",
".",
"set",
"(",
"param",
",",
"default",
")"
] | Set the parameter to the default if it doesn't exist | [
"Set",
"the",
"parameter",
"to",
"the",
"default",
"if",
"it",
"doesn",
"t",
"exist"
] | 846697a7a087e69c61d075232e754d6975a64152 | https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/core/featureconfig.py#L92-L95 | train | 54,753 |
toumorokoshi/sprinter | sprinter/core/featureconfig.py | FeatureConfig.to_dict | def to_dict(self):
""" Returns the context, fully specialized, as a dictionary """
return dict((k, str(self.get(k))) for k in self.raw_dict) | python | def to_dict(self):
""" Returns the context, fully specialized, as a dictionary """
return dict((k, str(self.get(k))) for k in self.raw_dict) | [
"def",
"to_dict",
"(",
"self",
")",
":",
"return",
"dict",
"(",
"(",
"k",
",",
"str",
"(",
"self",
".",
"get",
"(",
"k",
")",
")",
")",
"for",
"k",
"in",
"self",
".",
"raw_dict",
")"
] | Returns the context, fully specialized, as a dictionary | [
"Returns",
"the",
"context",
"fully",
"specialized",
"as",
"a",
"dictionary"
] | 846697a7a087e69c61d075232e754d6975a64152 | https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/core/featureconfig.py#L97-L99 | train | 54,754 |
toumorokoshi/sprinter | sprinter/core/featureconfig.py | FeatureConfig.write_to_manifest | def write_to_manifest(self):
""" Overwrites the section of the manifest with the featureconfig's value """
self.manifest.remove_section(self.feature_name)
self.manifest.add_section(self.feature_name)
for k, v in self.raw_dict.items():
self.manifest.set(self.feature_name, k, v) | python | def write_to_manifest(self):
""" Overwrites the section of the manifest with the featureconfig's value """
self.manifest.remove_section(self.feature_name)
self.manifest.add_section(self.feature_name)
for k, v in self.raw_dict.items():
self.manifest.set(self.feature_name, k, v) | [
"def",
"write_to_manifest",
"(",
"self",
")",
":",
"self",
".",
"manifest",
".",
"remove_section",
"(",
"self",
".",
"feature_name",
")",
"self",
".",
"manifest",
".",
"add_section",
"(",
"self",
".",
"feature_name",
")",
"for",
"k",
",",
"v",
"in",
"sel... | Overwrites the section of the manifest with the featureconfig's value | [
"Overwrites",
"the",
"section",
"of",
"the",
"manifest",
"with",
"the",
"featureconfig",
"s",
"value"
] | 846697a7a087e69c61d075232e754d6975a64152 | https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/core/featureconfig.py#L101-L106 | train | 54,755 |
Chilipp/psy-simple | psy_simple/plotters.py | round_to_05 | def round_to_05(n, exp=None, mode='s'):
"""
Round to the next 0.5-value.
This function applies the round function `func` to round `n` to the
next 0.5-value with respect to its exponent with base 10 (i.e.
1.3e-4 will be rounded to 1.5e-4) if `exp` is None or with respect
to the given exponent in `exp`.
Parameters
----------
n: numpy.ndarray
number to round
exp: int or numpy.ndarray
Exponent for rounding. If None, it will be computed from `n` to be the
exponents for base 10.
mode: {'s', 'l'}
rounding mode. If 's', it will be rounded to value whose absolute
value is below `n`, if 'l' it will rounded to the value whose absolute
value is above `n`.
Returns
-------
numpy.ndarray
rounded `n`
Examples
--------
The effects of the different parameters are show in the example below::
>>> from psyplot.plotter.simple import round_to_05
>>> a = [-100.3, 40.6, 8.7, -0.00023]
>>>round_to_05(a, mode='s')
array([ -1.00000000e+02, 4.00000000e+01, 8.50000000e+00,
-2.00000000e-04])
>>> round_to_05(a, mode='l')
array([ -1.50000000e+02, 4.50000000e+01, 9.00000000e+00,
-2.50000000e-04])"""
n = np.asarray(n)
if exp is None:
exp = np.floor(np.log10(np.abs(n))) # exponent for base 10
ntmp = np.abs(n)/10.**exp # mantissa for base 10
if mode == 's':
n1 = ntmp
s = 1.
n2 = nret = np.floor(ntmp)
else:
n1 = nret = np.ceil(ntmp)
s = -1.
n2 = ntmp
return np.where(n1 - n2 > 0.5, np.sign(n)*(nret + s*0.5)*10.**exp,
np.sign(n)*nret*10.**exp) | python | def round_to_05(n, exp=None, mode='s'):
"""
Round to the next 0.5-value.
This function applies the round function `func` to round `n` to the
next 0.5-value with respect to its exponent with base 10 (i.e.
1.3e-4 will be rounded to 1.5e-4) if `exp` is None or with respect
to the given exponent in `exp`.
Parameters
----------
n: numpy.ndarray
number to round
exp: int or numpy.ndarray
Exponent for rounding. If None, it will be computed from `n` to be the
exponents for base 10.
mode: {'s', 'l'}
rounding mode. If 's', it will be rounded to value whose absolute
value is below `n`, if 'l' it will rounded to the value whose absolute
value is above `n`.
Returns
-------
numpy.ndarray
rounded `n`
Examples
--------
The effects of the different parameters are show in the example below::
>>> from psyplot.plotter.simple import round_to_05
>>> a = [-100.3, 40.6, 8.7, -0.00023]
>>>round_to_05(a, mode='s')
array([ -1.00000000e+02, 4.00000000e+01, 8.50000000e+00,
-2.00000000e-04])
>>> round_to_05(a, mode='l')
array([ -1.50000000e+02, 4.50000000e+01, 9.00000000e+00,
-2.50000000e-04])"""
n = np.asarray(n)
if exp is None:
exp = np.floor(np.log10(np.abs(n))) # exponent for base 10
ntmp = np.abs(n)/10.**exp # mantissa for base 10
if mode == 's':
n1 = ntmp
s = 1.
n2 = nret = np.floor(ntmp)
else:
n1 = nret = np.ceil(ntmp)
s = -1.
n2 = ntmp
return np.where(n1 - n2 > 0.5, np.sign(n)*(nret + s*0.5)*10.**exp,
np.sign(n)*nret*10.**exp) | [
"def",
"round_to_05",
"(",
"n",
",",
"exp",
"=",
"None",
",",
"mode",
"=",
"'s'",
")",
":",
"n",
"=",
"np",
".",
"asarray",
"(",
"n",
")",
"if",
"exp",
"is",
"None",
":",
"exp",
"=",
"np",
".",
"floor",
"(",
"np",
".",
"log10",
"(",
"np",
"... | Round to the next 0.5-value.
This function applies the round function `func` to round `n` to the
next 0.5-value with respect to its exponent with base 10 (i.e.
1.3e-4 will be rounded to 1.5e-4) if `exp` is None or with respect
to the given exponent in `exp`.
Parameters
----------
n: numpy.ndarray
number to round
exp: int or numpy.ndarray
Exponent for rounding. If None, it will be computed from `n` to be the
exponents for base 10.
mode: {'s', 'l'}
rounding mode. If 's', it will be rounded to value whose absolute
value is below `n`, if 'l' it will rounded to the value whose absolute
value is above `n`.
Returns
-------
numpy.ndarray
rounded `n`
Examples
--------
The effects of the different parameters are show in the example below::
>>> from psyplot.plotter.simple import round_to_05
>>> a = [-100.3, 40.6, 8.7, -0.00023]
>>>round_to_05(a, mode='s')
array([ -1.00000000e+02, 4.00000000e+01, 8.50000000e+00,
-2.00000000e-04])
>>> round_to_05(a, mode='l')
array([ -1.50000000e+02, 4.50000000e+01, 9.00000000e+00,
-2.50000000e-04]) | [
"Round",
"to",
"the",
"next",
"0",
".",
"5",
"-",
"value",
"."
] | 7d916406a6d3c3c27c0b7102f98fef07a4da0a61 | https://github.com/Chilipp/psy-simple/blob/7d916406a6d3c3c27c0b7102f98fef07a4da0a61/psy_simple/plotters.py#L41-L93 | train | 54,756 |
Chilipp/psy-simple | psy_simple/plotters.py | convert_radian | def convert_radian(coord, *variables):
"""Convert the given coordinate from radian to degree
Parameters
----------
coord: xr.Variable
The variable to transform
``*variables``
The variables that are on the same unit.
Returns
-------
xr.Variable
The transformed variable if one of the given `variables` has units in
radian"""
if any(v.attrs.get('units') == 'radian' for v in variables):
return coord * 180. / np.pi
return coord | python | def convert_radian(coord, *variables):
"""Convert the given coordinate from radian to degree
Parameters
----------
coord: xr.Variable
The variable to transform
``*variables``
The variables that are on the same unit.
Returns
-------
xr.Variable
The transformed variable if one of the given `variables` has units in
radian"""
if any(v.attrs.get('units') == 'radian' for v in variables):
return coord * 180. / np.pi
return coord | [
"def",
"convert_radian",
"(",
"coord",
",",
"*",
"variables",
")",
":",
"if",
"any",
"(",
"v",
".",
"attrs",
".",
"get",
"(",
"'units'",
")",
"==",
"'radian'",
"for",
"v",
"in",
"variables",
")",
":",
"return",
"coord",
"*",
"180.",
"/",
"np",
".",... | Convert the given coordinate from radian to degree
Parameters
----------
coord: xr.Variable
The variable to transform
``*variables``
The variables that are on the same unit.
Returns
-------
xr.Variable
The transformed variable if one of the given `variables` has units in
radian | [
"Convert",
"the",
"given",
"coordinate",
"from",
"radian",
"to",
"degree"
] | 7d916406a6d3c3c27c0b7102f98fef07a4da0a61 | https://github.com/Chilipp/psy-simple/blob/7d916406a6d3c3c27c0b7102f98fef07a4da0a61/psy_simple/plotters.py#L96-L113 | train | 54,757 |
Chilipp/psy-simple | psy_simple/plotters.py | AlternativeXCoord.replace_coord | def replace_coord(self, i):
"""Replace the coordinate for the data array at the given position
Parameters
----------
i: int
The number of the data array in the raw data (if the raw data is
not an interactive list, use 0)
Returns
xarray.DataArray
The data array with the replaced coordinate"""
da = next(islice(self.data_iterator, i, i+1))
name, coord = self.get_alternative_coord(da, i)
other_coords = {key: da.coords[key]
for key in set(da.coords).difference(da.dims)}
ret = da.rename({da.dims[-1]: name}).assign_coords(
**{name: coord}).assign_coords(**other_coords)
return ret | python | def replace_coord(self, i):
"""Replace the coordinate for the data array at the given position
Parameters
----------
i: int
The number of the data array in the raw data (if the raw data is
not an interactive list, use 0)
Returns
xarray.DataArray
The data array with the replaced coordinate"""
da = next(islice(self.data_iterator, i, i+1))
name, coord = self.get_alternative_coord(da, i)
other_coords = {key: da.coords[key]
for key in set(da.coords).difference(da.dims)}
ret = da.rename({da.dims[-1]: name}).assign_coords(
**{name: coord}).assign_coords(**other_coords)
return ret | [
"def",
"replace_coord",
"(",
"self",
",",
"i",
")",
":",
"da",
"=",
"next",
"(",
"islice",
"(",
"self",
".",
"data_iterator",
",",
"i",
",",
"i",
"+",
"1",
")",
")",
"name",
",",
"coord",
"=",
"self",
".",
"get_alternative_coord",
"(",
"da",
",",
... | Replace the coordinate for the data array at the given position
Parameters
----------
i: int
The number of the data array in the raw data (if the raw data is
not an interactive list, use 0)
Returns
xarray.DataArray
The data array with the replaced coordinate | [
"Replace",
"the",
"coordinate",
"for",
"the",
"data",
"array",
"at",
"the",
"given",
"position"
] | 7d916406a6d3c3c27c0b7102f98fef07a4da0a61 | https://github.com/Chilipp/psy-simple/blob/7d916406a6d3c3c27c0b7102f98fef07a4da0a61/psy_simple/plotters.py#L201-L219 | train | 54,758 |
Chilipp/psy-simple | psy_simple/plotters.py | AxisColor.value2pickle | def value2pickle(self):
"""Return the current axis colors"""
return {key: s.get_edgecolor() for key, s in self.ax.spines.items()} | python | def value2pickle(self):
"""Return the current axis colors"""
return {key: s.get_edgecolor() for key, s in self.ax.spines.items()} | [
"def",
"value2pickle",
"(",
"self",
")",
":",
"return",
"{",
"key",
":",
"s",
".",
"get_edgecolor",
"(",
")",
"for",
"key",
",",
"s",
"in",
"self",
".",
"ax",
".",
"spines",
".",
"items",
"(",
")",
"}"
] | Return the current axis colors | [
"Return",
"the",
"current",
"axis",
"colors"
] | 7d916406a6d3c3c27c0b7102f98fef07a4da0a61 | https://github.com/Chilipp/psy-simple/blob/7d916406a6d3c3c27c0b7102f98fef07a4da0a61/psy_simple/plotters.py#L296-L298 | train | 54,759 |
Chilipp/psy-simple | psy_simple/plotters.py | TickLabels.set_default_formatters | def set_default_formatters(self, which=None):
"""Sets the default formatters that is used for updating to None
Parameters
----------
which: {None, 'minor', 'major'}
Specify which locator shall be set"""
if which is None or which == 'minor':
self.default_formatters['minor'] = self.axis.get_minor_formatter()
if which is None or which == 'major':
self.default_formatters['major'] = self.axis.get_major_formatter() | python | def set_default_formatters(self, which=None):
"""Sets the default formatters that is used for updating to None
Parameters
----------
which: {None, 'minor', 'major'}
Specify which locator shall be set"""
if which is None or which == 'minor':
self.default_formatters['minor'] = self.axis.get_minor_formatter()
if which is None or which == 'major':
self.default_formatters['major'] = self.axis.get_major_formatter() | [
"def",
"set_default_formatters",
"(",
"self",
",",
"which",
"=",
"None",
")",
":",
"if",
"which",
"is",
"None",
"or",
"which",
"==",
"'minor'",
":",
"self",
".",
"default_formatters",
"[",
"'minor'",
"]",
"=",
"self",
".",
"axis",
".",
"get_minor_formatter... | Sets the default formatters that is used for updating to None
Parameters
----------
which: {None, 'minor', 'major'}
Specify which locator shall be set | [
"Sets",
"the",
"default",
"formatters",
"that",
"is",
"used",
"for",
"updating",
"to",
"None"
] | 7d916406a6d3c3c27c0b7102f98fef07a4da0a61 | https://github.com/Chilipp/psy-simple/blob/7d916406a6d3c3c27c0b7102f98fef07a4da0a61/psy_simple/plotters.py#L879-L889 | train | 54,760 |
Chilipp/psy-simple | psy_simple/plotters.py | LinePlot.plotted_data | def plotted_data(self):
"""The data that is shown to the user"""
return InteractiveList(
[arr for arr, val in zip(self.iter_data,
cycle(slist(self.value)))
if val is not None]) | python | def plotted_data(self):
"""The data that is shown to the user"""
return InteractiveList(
[arr for arr, val in zip(self.iter_data,
cycle(slist(self.value)))
if val is not None]) | [
"def",
"plotted_data",
"(",
"self",
")",
":",
"return",
"InteractiveList",
"(",
"[",
"arr",
"for",
"arr",
",",
"val",
"in",
"zip",
"(",
"self",
".",
"iter_data",
",",
"cycle",
"(",
"slist",
"(",
"self",
".",
"value",
")",
")",
")",
"if",
"val",
"is... | The data that is shown to the user | [
"The",
"data",
"that",
"is",
"shown",
"to",
"the",
"user"
] | 7d916406a6d3c3c27c0b7102f98fef07a4da0a61 | https://github.com/Chilipp/psy-simple/blob/7d916406a6d3c3c27c0b7102f98fef07a4da0a61/psy_simple/plotters.py#L1746-L1751 | train | 54,761 |
Chilipp/psy-simple | psy_simple/plotters.py | CbarOptions.axis | def axis(self):
"""axis of the colorbar with the ticks. Will be overwritten during
update process."""
return getattr(
self.colorbar.ax, self.axis_locations[self.position] + 'axis') | python | def axis(self):
"""axis of the colorbar with the ticks. Will be overwritten during
update process."""
return getattr(
self.colorbar.ax, self.axis_locations[self.position] + 'axis') | [
"def",
"axis",
"(",
"self",
")",
":",
"return",
"getattr",
"(",
"self",
".",
"colorbar",
".",
"ax",
",",
"self",
".",
"axis_locations",
"[",
"self",
".",
"position",
"]",
"+",
"'axis'",
")"
] | axis of the colorbar with the ticks. Will be overwritten during
update process. | [
"axis",
"of",
"the",
"colorbar",
"with",
"the",
"ticks",
".",
"Will",
"be",
"overwritten",
"during",
"update",
"process",
"."
] | 7d916406a6d3c3c27c0b7102f98fef07a4da0a61 | https://github.com/Chilipp/psy-simple/blob/7d916406a6d3c3c27c0b7102f98fef07a4da0a61/psy_simple/plotters.py#L3913-L3917 | train | 54,762 |
Chilipp/psy-simple | psy_simple/plotters.py | CTickLabels.default_formatters | def default_formatters(self):
"""Default locator of the axis of the colorbars"""
if self._default_formatters:
return self._default_formatters
else:
self.set_default_formatters()
return self._default_formatters | python | def default_formatters(self):
"""Default locator of the axis of the colorbars"""
if self._default_formatters:
return self._default_formatters
else:
self.set_default_formatters()
return self._default_formatters | [
"def",
"default_formatters",
"(",
"self",
")",
":",
"if",
"self",
".",
"_default_formatters",
":",
"return",
"self",
".",
"_default_formatters",
"else",
":",
"self",
".",
"set_default_formatters",
"(",
")",
"return",
"self",
".",
"_default_formatters"
] | Default locator of the axis of the colorbars | [
"Default",
"locator",
"of",
"the",
"axis",
"of",
"the",
"colorbars"
] | 7d916406a6d3c3c27c0b7102f98fef07a4da0a61 | https://github.com/Chilipp/psy-simple/blob/7d916406a6d3c3c27c0b7102f98fef07a4da0a61/psy_simple/plotters.py#L4050-L4056 | train | 54,763 |
Chilipp/psy-simple | psy_simple/plotters.py | VectorPlot.get_xyz_2d | def get_xyz_2d(self, xcoord, x, ycoord, y, u, v):
"""Get closest x, y and z for the given `x` and `y` in `data` for
2d coords"""
xy = xcoord.values.ravel() + 1j * ycoord.values.ravel()
dist = np.abs(xy - (x + 1j * y))
imin = np.nanargmin(dist)
xy_min = xy[imin]
return (xy_min.real, xy_min.imag, u.values.ravel()[imin],
v.values.ravel()[imin]) | python | def get_xyz_2d(self, xcoord, x, ycoord, y, u, v):
"""Get closest x, y and z for the given `x` and `y` in `data` for
2d coords"""
xy = xcoord.values.ravel() + 1j * ycoord.values.ravel()
dist = np.abs(xy - (x + 1j * y))
imin = np.nanargmin(dist)
xy_min = xy[imin]
return (xy_min.real, xy_min.imag, u.values.ravel()[imin],
v.values.ravel()[imin]) | [
"def",
"get_xyz_2d",
"(",
"self",
",",
"xcoord",
",",
"x",
",",
"ycoord",
",",
"y",
",",
"u",
",",
"v",
")",
":",
"xy",
"=",
"xcoord",
".",
"values",
".",
"ravel",
"(",
")",
"+",
"1j",
"*",
"ycoord",
".",
"values",
".",
"ravel",
"(",
")",
"di... | Get closest x, y and z for the given `x` and `y` in `data` for
2d coords | [
"Get",
"closest",
"x",
"y",
"and",
"z",
"for",
"the",
"given",
"x",
"and",
"y",
"in",
"data",
"for",
"2d",
"coords"
] | 7d916406a6d3c3c27c0b7102f98fef07a4da0a61 | https://github.com/Chilipp/psy-simple/blob/7d916406a6d3c3c27c0b7102f98fef07a4da0a61/psy_simple/plotters.py#L4605-L4613 | train | 54,764 |
Chilipp/psy-simple | psy_simple/plotters.py | NormedHist2D.hist2d | def hist2d(self, da, **kwargs):
"""Make the two dimensional histogram
Parameters
----------
da: xarray.DataArray
The data source"""
if self.value is None or self.value == 'counts':
normed = False
else:
normed = True
y = da.values
x = da.coords[da.dims[0]].values
counts, xedges, yedges = np.histogram2d(
x, y, normed=normed, **kwargs)
if self.value == 'counts':
counts = counts / counts.sum().astype(float)
return counts, xedges, yedges | python | def hist2d(self, da, **kwargs):
"""Make the two dimensional histogram
Parameters
----------
da: xarray.DataArray
The data source"""
if self.value is None or self.value == 'counts':
normed = False
else:
normed = True
y = da.values
x = da.coords[da.dims[0]].values
counts, xedges, yedges = np.histogram2d(
x, y, normed=normed, **kwargs)
if self.value == 'counts':
counts = counts / counts.sum().astype(float)
return counts, xedges, yedges | [
"def",
"hist2d",
"(",
"self",
",",
"da",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"value",
"is",
"None",
"or",
"self",
".",
"value",
"==",
"'counts'",
":",
"normed",
"=",
"False",
"else",
":",
"normed",
"=",
"True",
"y",
"=",
"da",
... | Make the two dimensional histogram
Parameters
----------
da: xarray.DataArray
The data source | [
"Make",
"the",
"two",
"dimensional",
"histogram"
] | 7d916406a6d3c3c27c0b7102f98fef07a4da0a61 | https://github.com/Chilipp/psy-simple/blob/7d916406a6d3c3c27c0b7102f98fef07a4da0a61/psy_simple/plotters.py#L5122-L5139 | train | 54,765 |
Chilipp/psy-simple | psy_simple/plotters.py | PointDensity._statsmodels_bivariate_kde | def _statsmodels_bivariate_kde(self, x, y, bws, xsize, ysize, xyranges):
"""Compute a bivariate kde using statsmodels.
This function is mainly motivated through
seaborn.distributions._statsmodels_bivariate_kde"""
import statsmodels.nonparametric.api as smnp
for i, (coord, bw) in enumerate(zip([x, y], bws)):
if isinstance(bw, six.string_types):
bw_func = getattr(smnp.bandwidths, "bw_" + bw)
bws[i] = bw_func(coord)
kde = smnp.KDEMultivariate([x, y], "cc", bws)
x_support = np.linspace(xyranges[0][0], xyranges[0][1], xsize)
y_support = np.linspace(xyranges[1][0], xyranges[1][1], ysize)
xx, yy = np.meshgrid(x_support, y_support)
z = kde.pdf([xx.ravel(), yy.ravel()]).reshape(xx.shape)
return x_support, y_support, z | python | def _statsmodels_bivariate_kde(self, x, y, bws, xsize, ysize, xyranges):
"""Compute a bivariate kde using statsmodels.
This function is mainly motivated through
seaborn.distributions._statsmodels_bivariate_kde"""
import statsmodels.nonparametric.api as smnp
for i, (coord, bw) in enumerate(zip([x, y], bws)):
if isinstance(bw, six.string_types):
bw_func = getattr(smnp.bandwidths, "bw_" + bw)
bws[i] = bw_func(coord)
kde = smnp.KDEMultivariate([x, y], "cc", bws)
x_support = np.linspace(xyranges[0][0], xyranges[0][1], xsize)
y_support = np.linspace(xyranges[1][0], xyranges[1][1], ysize)
xx, yy = np.meshgrid(x_support, y_support)
z = kde.pdf([xx.ravel(), yy.ravel()]).reshape(xx.shape)
return x_support, y_support, z | [
"def",
"_statsmodels_bivariate_kde",
"(",
"self",
",",
"x",
",",
"y",
",",
"bws",
",",
"xsize",
",",
"ysize",
",",
"xyranges",
")",
":",
"import",
"statsmodels",
".",
"nonparametric",
".",
"api",
"as",
"smnp",
"for",
"i",
",",
"(",
"coord",
",",
"bw",
... | Compute a bivariate kde using statsmodels.
This function is mainly motivated through
seaborn.distributions._statsmodels_bivariate_kde | [
"Compute",
"a",
"bivariate",
"kde",
"using",
"statsmodels",
".",
"This",
"function",
"is",
"mainly",
"motivated",
"through",
"seaborn",
".",
"distributions",
".",
"_statsmodels_bivariate_kde"
] | 7d916406a6d3c3c27c0b7102f98fef07a4da0a61 | https://github.com/Chilipp/psy-simple/blob/7d916406a6d3c3c27c0b7102f98fef07a4da0a61/psy_simple/plotters.py#L5210-L5224 | train | 54,766 |
memphis-iis/GLUDB | gludb/versioning.py | append_diff_hist | def append_diff_hist(diff, diff_hist=list()):
"""Given a diff as generated by record_diff, append a diff record to the
list of diff_hist records."""
diff, diff_hist = _norm_json_params(diff, diff_hist)
if not diff_hist:
diff_hist = list()
diff_hist.append({'diff': diff, 'diff_date': now_field()})
return diff_hist | python | def append_diff_hist(diff, diff_hist=list()):
"""Given a diff as generated by record_diff, append a diff record to the
list of diff_hist records."""
diff, diff_hist = _norm_json_params(diff, diff_hist)
if not diff_hist:
diff_hist = list()
diff_hist.append({'diff': diff, 'diff_date': now_field()})
return diff_hist | [
"def",
"append_diff_hist",
"(",
"diff",
",",
"diff_hist",
"=",
"list",
"(",
")",
")",
":",
"diff",
",",
"diff_hist",
"=",
"_norm_json_params",
"(",
"diff",
",",
"diff_hist",
")",
"if",
"not",
"diff_hist",
":",
"diff_hist",
"=",
"list",
"(",
")",
"diff_hi... | Given a diff as generated by record_diff, append a diff record to the
list of diff_hist records. | [
"Given",
"a",
"diff",
"as",
"generated",
"by",
"record_diff",
"append",
"a",
"diff",
"record",
"to",
"the",
"list",
"of",
"diff_hist",
"records",
"."
] | 25692528ff6fe8184a3570f61f31f1a90088a388 | https://github.com/memphis-iis/GLUDB/blob/25692528ff6fe8184a3570f61f31f1a90088a388/gludb/versioning.py#L55-L64 | train | 54,767 |
studionow/pybrightcove | pybrightcove/video.py | Video._find_video | def _find_video(self):
"""
Lookup and populate ``pybrightcove.video.Video`` object given a video
id or reference_id.
"""
data = None
if self.id:
data = self.connection.get_item(
'find_video_by_id', video_id=self.id)
elif self.reference_id:
data = self.connection.get_item(
'find_video_by_reference_id', reference_id=self.reference_id)
if data:
self._load(data) | python | def _find_video(self):
"""
Lookup and populate ``pybrightcove.video.Video`` object given a video
id or reference_id.
"""
data = None
if self.id:
data = self.connection.get_item(
'find_video_by_id', video_id=self.id)
elif self.reference_id:
data = self.connection.get_item(
'find_video_by_reference_id', reference_id=self.reference_id)
if data:
self._load(data) | [
"def",
"_find_video",
"(",
"self",
")",
":",
"data",
"=",
"None",
"if",
"self",
".",
"id",
":",
"data",
"=",
"self",
".",
"connection",
".",
"get_item",
"(",
"'find_video_by_id'",
",",
"video_id",
"=",
"self",
".",
"id",
")",
"elif",
"self",
".",
"re... | Lookup and populate ``pybrightcove.video.Video`` object given a video
id or reference_id. | [
"Lookup",
"and",
"populate",
"pybrightcove",
".",
"video",
".",
"Video",
"object",
"given",
"a",
"video",
"id",
"or",
"reference_id",
"."
] | 19c946b689a80156e070fe9bc35589c4b768e614 | https://github.com/studionow/pybrightcove/blob/19c946b689a80156e070fe9bc35589c4b768e614/pybrightcove/video.py#L297-L311 | train | 54,768 |
studionow/pybrightcove | pybrightcove/video.py | Video.to_xml | def to_xml(self):
# pylint: disable=R0912
"""
Converts object into an XML string.
"""
xml = ''
for asset in self.assets:
xml += '<asset filename="%s" ' % \
os.path.basename(asset['filename'])
xml += ' refid="%(refid)s"' % asset
xml += ' size="%(size)s"' % asset
xml += ' hash-code="%s"' % asset['hash-code']
xml += ' type="%(type)s"' % asset
if asset.get('encoding-rate', None):
xml += ' encoding-rate="%s"' % asset['encoding-rate']
if asset.get('frame-width', None):
xml += ' frame-width="%s"' % asset['frame-width']
if asset.get('frame-height', None):
xml += ' frame-height="%s"' % asset['frame-height']
if asset.get('display-name', None):
xml += ' display-name="%s"' % asset['display-name']
if asset.get('encode-to', None):
xml += ' encode-to="%s"' % asset['encode-to']
if asset.get('encode-multiple', None):
xml += ' encode-multiple="%s"' % asset['encode-multiple']
if asset.get('h264-preserve-as-rendition', None):
xml += ' h264-preserve-as-rendition="%s"' % \
asset['h264-preserve-as-rendition']
if asset.get('h264-no-processing', None):
xml += ' h264-no-processing="%s"' % asset['h264-no-processing']
xml += ' />\n'
xml += '<title name="%(name)s" refid="%(referenceId)s" active="TRUE" '
if self.start_date:
xml += 'start-date="%(start_date)s" '
if self.end_date:
xml += 'end-date="%(end_date)s" '
for asset in self.assets:
if asset.get('encoding-rate', None) == None:
choice = enums.AssetTypeEnum
if asset.get('type', None) == choice.VIDEO_FULL:
xml += 'video-full-refid="%s" ' % asset.get('refid')
if asset.get('type', None) == choice.THUMBNAIL:
xml += 'thumbnail-refid="%s" ' % asset.get('refid')
if asset.get('type', None) == choice.VIDEO_STILL:
xml += 'video-still-refid="%s" ' % asset.get('refid')
if asset.get('type', None) == choice.FLV_BUMPER:
xml += 'flash-prebumper-refid="%s" ' % asset.get('refid')
xml += '>\n'
if self.short_description:
xml += '<short-description><![CDATA[%(shortDescription)s]]>'
xml += '</short-description>\n'
if self.long_description:
xml += '<long-description><![CDATA[%(longDescription)s]]>'
xml += '</long-description>\n'
for tag in self.tags:
xml += '<tag><![CDATA[%s]]></tag>\n' % tag
for asset in self.assets:
if asset.get('encoding-rate', None):
xml += '<rendition-refid>%s</rendition-refid>\n' % \
asset['refid']
for meta in self.metadata:
xml += '<custom-%s-value name="%s">%s</custom-%s-value>' % \
(meta['type'], meta['key'], meta['value'], meta['type'])
xml += '</title>'
xml = xml % self._to_dict()
return xml | python | def to_xml(self):
# pylint: disable=R0912
"""
Converts object into an XML string.
"""
xml = ''
for asset in self.assets:
xml += '<asset filename="%s" ' % \
os.path.basename(asset['filename'])
xml += ' refid="%(refid)s"' % asset
xml += ' size="%(size)s"' % asset
xml += ' hash-code="%s"' % asset['hash-code']
xml += ' type="%(type)s"' % asset
if asset.get('encoding-rate', None):
xml += ' encoding-rate="%s"' % asset['encoding-rate']
if asset.get('frame-width', None):
xml += ' frame-width="%s"' % asset['frame-width']
if asset.get('frame-height', None):
xml += ' frame-height="%s"' % asset['frame-height']
if asset.get('display-name', None):
xml += ' display-name="%s"' % asset['display-name']
if asset.get('encode-to', None):
xml += ' encode-to="%s"' % asset['encode-to']
if asset.get('encode-multiple', None):
xml += ' encode-multiple="%s"' % asset['encode-multiple']
if asset.get('h264-preserve-as-rendition', None):
xml += ' h264-preserve-as-rendition="%s"' % \
asset['h264-preserve-as-rendition']
if asset.get('h264-no-processing', None):
xml += ' h264-no-processing="%s"' % asset['h264-no-processing']
xml += ' />\n'
xml += '<title name="%(name)s" refid="%(referenceId)s" active="TRUE" '
if self.start_date:
xml += 'start-date="%(start_date)s" '
if self.end_date:
xml += 'end-date="%(end_date)s" '
for asset in self.assets:
if asset.get('encoding-rate', None) == None:
choice = enums.AssetTypeEnum
if asset.get('type', None) == choice.VIDEO_FULL:
xml += 'video-full-refid="%s" ' % asset.get('refid')
if asset.get('type', None) == choice.THUMBNAIL:
xml += 'thumbnail-refid="%s" ' % asset.get('refid')
if asset.get('type', None) == choice.VIDEO_STILL:
xml += 'video-still-refid="%s" ' % asset.get('refid')
if asset.get('type', None) == choice.FLV_BUMPER:
xml += 'flash-prebumper-refid="%s" ' % asset.get('refid')
xml += '>\n'
if self.short_description:
xml += '<short-description><![CDATA[%(shortDescription)s]]>'
xml += '</short-description>\n'
if self.long_description:
xml += '<long-description><![CDATA[%(longDescription)s]]>'
xml += '</long-description>\n'
for tag in self.tags:
xml += '<tag><![CDATA[%s]]></tag>\n' % tag
for asset in self.assets:
if asset.get('encoding-rate', None):
xml += '<rendition-refid>%s</rendition-refid>\n' % \
asset['refid']
for meta in self.metadata:
xml += '<custom-%s-value name="%s">%s</custom-%s-value>' % \
(meta['type'], meta['key'], meta['value'], meta['type'])
xml += '</title>'
xml = xml % self._to_dict()
return xml | [
"def",
"to_xml",
"(",
"self",
")",
":",
"# pylint: disable=R0912",
"xml",
"=",
"''",
"for",
"asset",
"in",
"self",
".",
"assets",
":",
"xml",
"+=",
"'<asset filename=\"%s\" '",
"%",
"os",
".",
"path",
".",
"basename",
"(",
"asset",
"[",
"'filename'",
"]",
... | Converts object into an XML string. | [
"Converts",
"object",
"into",
"an",
"XML",
"string",
"."
] | 19c946b689a80156e070fe9bc35589c4b768e614 | https://github.com/studionow/pybrightcove/blob/19c946b689a80156e070fe9bc35589c4b768e614/pybrightcove/video.py#L345-L410 | train | 54,769 |
studionow/pybrightcove | pybrightcove/video.py | Video._load | def _load(self, data):
"""
Deserialize a dictionary of data into a ``pybrightcove.video.Video``
object.
"""
self.raw_data = data
self.creation_date = _convert_tstamp(data['creationDate'])
self.economics = data['economics']
self.id = data['id']
self.last_modified_date = _convert_tstamp(data['lastModifiedDate'])
self.length = data['length']
self.link_text = data['linkText']
self.link_url = data['linkURL']
self.long_description = data['longDescription']
self.name = data['name']
self.plays_total = data['playsTotal']
self.plays_trailing_week = data['playsTrailingWeek']
self.published_date = _convert_tstamp(data['publishedDate'])
self.start_date = _convert_tstamp(data.get('startDate', None))
self.end_date = _convert_tstamp(data.get('endDate', None))
self.reference_id = data['referenceId']
self.short_description = data['shortDescription']
self.tags = []
for tag in data['tags']:
self.tags.append(tag)
self.thumbnail_url = data['thumbnailURL']
self.video_still_url = data['videoStillURL'] | python | def _load(self, data):
"""
Deserialize a dictionary of data into a ``pybrightcove.video.Video``
object.
"""
self.raw_data = data
self.creation_date = _convert_tstamp(data['creationDate'])
self.economics = data['economics']
self.id = data['id']
self.last_modified_date = _convert_tstamp(data['lastModifiedDate'])
self.length = data['length']
self.link_text = data['linkText']
self.link_url = data['linkURL']
self.long_description = data['longDescription']
self.name = data['name']
self.plays_total = data['playsTotal']
self.plays_trailing_week = data['playsTrailingWeek']
self.published_date = _convert_tstamp(data['publishedDate'])
self.start_date = _convert_tstamp(data.get('startDate', None))
self.end_date = _convert_tstamp(data.get('endDate', None))
self.reference_id = data['referenceId']
self.short_description = data['shortDescription']
self.tags = []
for tag in data['tags']:
self.tags.append(tag)
self.thumbnail_url = data['thumbnailURL']
self.video_still_url = data['videoStillURL'] | [
"def",
"_load",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"raw_data",
"=",
"data",
"self",
".",
"creation_date",
"=",
"_convert_tstamp",
"(",
"data",
"[",
"'creationDate'",
"]",
")",
"self",
".",
"economics",
"=",
"data",
"[",
"'economics'",
"]",
... | Deserialize a dictionary of data into a ``pybrightcove.video.Video``
object. | [
"Deserialize",
"a",
"dictionary",
"of",
"data",
"into",
"a",
"pybrightcove",
".",
"video",
".",
"Video",
"object",
"."
] | 19c946b689a80156e070fe9bc35589c4b768e614 | https://github.com/studionow/pybrightcove/blob/19c946b689a80156e070fe9bc35589c4b768e614/pybrightcove/video.py#L412-L438 | train | 54,770 |
studionow/pybrightcove | pybrightcove/video.py | Video.get_custom_metadata | def get_custom_metadata(self):
"""
Fetches custom metadta for an already exisiting Video.
"""
if self.id is not None:
data = self.connection.get_item(
'find_video_by_id',
video_id=self.id,
video_fields="customFields"
)
for key in data.get("customFields", {}).keys():
val = data["customFields"].get(key)
if val is not None:
self.add_custom_metadata(key, val) | python | def get_custom_metadata(self):
"""
Fetches custom metadta for an already exisiting Video.
"""
if self.id is not None:
data = self.connection.get_item(
'find_video_by_id',
video_id=self.id,
video_fields="customFields"
)
for key in data.get("customFields", {}).keys():
val = data["customFields"].get(key)
if val is not None:
self.add_custom_metadata(key, val) | [
"def",
"get_custom_metadata",
"(",
"self",
")",
":",
"if",
"self",
".",
"id",
"is",
"not",
"None",
":",
"data",
"=",
"self",
".",
"connection",
".",
"get_item",
"(",
"'find_video_by_id'",
",",
"video_id",
"=",
"self",
".",
"id",
",",
"video_fields",
"=",... | Fetches custom metadta for an already exisiting Video. | [
"Fetches",
"custom",
"metadta",
"for",
"an",
"already",
"exisiting",
"Video",
"."
] | 19c946b689a80156e070fe9bc35589c4b768e614 | https://github.com/studionow/pybrightcove/blob/19c946b689a80156e070fe9bc35589c4b768e614/pybrightcove/video.py#L472-L485 | train | 54,771 |
studionow/pybrightcove | pybrightcove/video.py | Video.add_custom_metadata | def add_custom_metadata(self, key, value, meta_type=None):
"""
Add custom metadata to the Video. meta_type is required for XML API.
"""
self.metadata.append({'key': key, 'value': value, 'type': meta_type}) | python | def add_custom_metadata(self, key, value, meta_type=None):
"""
Add custom metadata to the Video. meta_type is required for XML API.
"""
self.metadata.append({'key': key, 'value': value, 'type': meta_type}) | [
"def",
"add_custom_metadata",
"(",
"self",
",",
"key",
",",
"value",
",",
"meta_type",
"=",
"None",
")",
":",
"self",
".",
"metadata",
".",
"append",
"(",
"{",
"'key'",
":",
"key",
",",
"'value'",
":",
"value",
",",
"'type'",
":",
"meta_type",
"}",
"... | Add custom metadata to the Video. meta_type is required for XML API. | [
"Add",
"custom",
"metadata",
"to",
"the",
"Video",
".",
"meta_type",
"is",
"required",
"for",
"XML",
"API",
"."
] | 19c946b689a80156e070fe9bc35589c4b768e614 | https://github.com/studionow/pybrightcove/blob/19c946b689a80156e070fe9bc35589c4b768e614/pybrightcove/video.py#L487-L491 | train | 54,772 |
studionow/pybrightcove | pybrightcove/video.py | Video.add_asset | def add_asset(self, filename, asset_type, display_name,
encoding_rate=None, frame_width=None, frame_height=None,
encode_to=None, encode_multiple=False,
h264_preserve_as_rendition=False, h264_no_processing=False):
"""
Add an asset to the Video object.
"""
m = hashlib.md5()
fp = file(filename, 'rb')
bits = fp.read(262144) ## 256KB
while bits:
m.update(bits)
bits = fp.read(262144)
fp.close()
hash_code = m.hexdigest()
refid = "%s-%s" % (os.path.basename(filename), hash_code)
asset = {
'filename': filename,
'type': asset_type,
'size': os.path.getsize(filename),
'refid': refid,
'hash-code': hash_code}
if encoding_rate:
asset.update({'encoding-rate': encoding_rate})
if frame_width:
asset.update({'frame-width': frame_width})
if frame_height:
asset.update({'frame-height': frame_height})
if display_name:
asset.update({'display-name': display_name})
if encode_to:
asset.update({'encode-to': encode_to})
asset.update({'encode-multiple': encode_multiple})
if encode_multiple and h264_preserve_as_rendition:
asset.update({
'h264-preserve-as-rendition': h264_preserve_as_rendition})
else:
if h264_no_processing:
asset.update({'h264-no-processing': h264_no_processing})
self.assets.append(asset) | python | def add_asset(self, filename, asset_type, display_name,
encoding_rate=None, frame_width=None, frame_height=None,
encode_to=None, encode_multiple=False,
h264_preserve_as_rendition=False, h264_no_processing=False):
"""
Add an asset to the Video object.
"""
m = hashlib.md5()
fp = file(filename, 'rb')
bits = fp.read(262144) ## 256KB
while bits:
m.update(bits)
bits = fp.read(262144)
fp.close()
hash_code = m.hexdigest()
refid = "%s-%s" % (os.path.basename(filename), hash_code)
asset = {
'filename': filename,
'type': asset_type,
'size': os.path.getsize(filename),
'refid': refid,
'hash-code': hash_code}
if encoding_rate:
asset.update({'encoding-rate': encoding_rate})
if frame_width:
asset.update({'frame-width': frame_width})
if frame_height:
asset.update({'frame-height': frame_height})
if display_name:
asset.update({'display-name': display_name})
if encode_to:
asset.update({'encode-to': encode_to})
asset.update({'encode-multiple': encode_multiple})
if encode_multiple and h264_preserve_as_rendition:
asset.update({
'h264-preserve-as-rendition': h264_preserve_as_rendition})
else:
if h264_no_processing:
asset.update({'h264-no-processing': h264_no_processing})
self.assets.append(asset) | [
"def",
"add_asset",
"(",
"self",
",",
"filename",
",",
"asset_type",
",",
"display_name",
",",
"encoding_rate",
"=",
"None",
",",
"frame_width",
"=",
"None",
",",
"frame_height",
"=",
"None",
",",
"encode_to",
"=",
"None",
",",
"encode_multiple",
"=",
"False... | Add an asset to the Video object. | [
"Add",
"an",
"asset",
"to",
"the",
"Video",
"object",
"."
] | 19c946b689a80156e070fe9bc35589c4b768e614 | https://github.com/studionow/pybrightcove/blob/19c946b689a80156e070fe9bc35589c4b768e614/pybrightcove/video.py#L493-L535 | train | 54,773 |
studionow/pybrightcove | pybrightcove/video.py | Video.save | def save(self, create_multiple_renditions=True,
preserve_source_rendition=True,
encode_to=enums.EncodeToEnum.FLV):
"""
Creates or updates the video
"""
if is_ftp_connection(self.connection) and len(self.assets) > 0:
self.connection.post(xml=self.to_xml(), assets=self.assets)
elif not self.id and self._filename:
self.id = self.connection.post('create_video', self._filename,
create_multiple_renditions=create_multiple_renditions,
preserve_source_rendition=preserve_source_rendition,
encode_to=encode_to,
video=self._to_dict())
elif not self.id and len(self.renditions) > 0:
self.id = self.connection.post('create_video',
video=self._to_dict())
elif self.id:
data = self.connection.post('update_video', video=self._to_dict())
if data:
self._load(data) | python | def save(self, create_multiple_renditions=True,
preserve_source_rendition=True,
encode_to=enums.EncodeToEnum.FLV):
"""
Creates or updates the video
"""
if is_ftp_connection(self.connection) and len(self.assets) > 0:
self.connection.post(xml=self.to_xml(), assets=self.assets)
elif not self.id and self._filename:
self.id = self.connection.post('create_video', self._filename,
create_multiple_renditions=create_multiple_renditions,
preserve_source_rendition=preserve_source_rendition,
encode_to=encode_to,
video=self._to_dict())
elif not self.id and len(self.renditions) > 0:
self.id = self.connection.post('create_video',
video=self._to_dict())
elif self.id:
data = self.connection.post('update_video', video=self._to_dict())
if data:
self._load(data) | [
"def",
"save",
"(",
"self",
",",
"create_multiple_renditions",
"=",
"True",
",",
"preserve_source_rendition",
"=",
"True",
",",
"encode_to",
"=",
"enums",
".",
"EncodeToEnum",
".",
"FLV",
")",
":",
"if",
"is_ftp_connection",
"(",
"self",
".",
"connection",
")"... | Creates or updates the video | [
"Creates",
"or",
"updates",
"the",
"video"
] | 19c946b689a80156e070fe9bc35589c4b768e614 | https://github.com/studionow/pybrightcove/blob/19c946b689a80156e070fe9bc35589c4b768e614/pybrightcove/video.py#L537-L557 | train | 54,774 |
studionow/pybrightcove | pybrightcove/video.py | Video.delete | def delete(self, cascade=False, delete_shares=False):
"""
Deletes the video.
"""
if self.id:
self.connection.post('delete_video', video_id=self.id,
cascade=cascade, delete_shares=delete_shares)
self.id = None | python | def delete(self, cascade=False, delete_shares=False):
"""
Deletes the video.
"""
if self.id:
self.connection.post('delete_video', video_id=self.id,
cascade=cascade, delete_shares=delete_shares)
self.id = None | [
"def",
"delete",
"(",
"self",
",",
"cascade",
"=",
"False",
",",
"delete_shares",
"=",
"False",
")",
":",
"if",
"self",
".",
"id",
":",
"self",
".",
"connection",
".",
"post",
"(",
"'delete_video'",
",",
"video_id",
"=",
"self",
".",
"id",
",",
"casc... | Deletes the video. | [
"Deletes",
"the",
"video",
"."
] | 19c946b689a80156e070fe9bc35589c4b768e614 | https://github.com/studionow/pybrightcove/blob/19c946b689a80156e070fe9bc35589c4b768e614/pybrightcove/video.py#L559-L566 | train | 54,775 |
studionow/pybrightcove | pybrightcove/video.py | Video.get_upload_status | def get_upload_status(self):
"""
Get the status of the video that has been uploaded.
"""
if self.id:
return self.connection.post('get_upload_status', video_id=self.id) | python | def get_upload_status(self):
"""
Get the status of the video that has been uploaded.
"""
if self.id:
return self.connection.post('get_upload_status', video_id=self.id) | [
"def",
"get_upload_status",
"(",
"self",
")",
":",
"if",
"self",
".",
"id",
":",
"return",
"self",
".",
"connection",
".",
"post",
"(",
"'get_upload_status'",
",",
"video_id",
"=",
"self",
".",
"id",
")"
] | Get the status of the video that has been uploaded. | [
"Get",
"the",
"status",
"of",
"the",
"video",
"that",
"has",
"been",
"uploaded",
"."
] | 19c946b689a80156e070fe9bc35589c4b768e614 | https://github.com/studionow/pybrightcove/blob/19c946b689a80156e070fe9bc35589c4b768e614/pybrightcove/video.py#L568-L573 | train | 54,776 |
studionow/pybrightcove | pybrightcove/video.py | Video.share | def share(self, accounts):
"""
Create a share
"""
if not isinstance(accounts, (list, tuple)):
msg = "Video.share expects an iterable argument"
raise exceptions.PyBrightcoveError(msg)
raise exceptions.PyBrightcoveError("Not yet implemented") | python | def share(self, accounts):
"""
Create a share
"""
if not isinstance(accounts, (list, tuple)):
msg = "Video.share expects an iterable argument"
raise exceptions.PyBrightcoveError(msg)
raise exceptions.PyBrightcoveError("Not yet implemented") | [
"def",
"share",
"(",
"self",
",",
"accounts",
")",
":",
"if",
"not",
"isinstance",
"(",
"accounts",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"msg",
"=",
"\"Video.share expects an iterable argument\"",
"raise",
"exceptions",
".",
"PyBrightcoveError",
"(",... | Create a share | [
"Create",
"a",
"share"
] | 19c946b689a80156e070fe9bc35589c4b768e614 | https://github.com/studionow/pybrightcove/blob/19c946b689a80156e070fe9bc35589c4b768e614/pybrightcove/video.py#L575-L582 | train | 54,777 |
studionow/pybrightcove | pybrightcove/video.py | Video.set_image | def set_image(self, image, filename=None, resize=False):
"""
Set the poster or thumbnail of a this Vidoe.
"""
if self.id:
data = self.connection.post('add_image', filename,
video_id=self.id, image=image.to_dict(), resize=resize)
if data:
self.image = Image(data=data) | python | def set_image(self, image, filename=None, resize=False):
"""
Set the poster or thumbnail of a this Vidoe.
"""
if self.id:
data = self.connection.post('add_image', filename,
video_id=self.id, image=image.to_dict(), resize=resize)
if data:
self.image = Image(data=data) | [
"def",
"set_image",
"(",
"self",
",",
"image",
",",
"filename",
"=",
"None",
",",
"resize",
"=",
"False",
")",
":",
"if",
"self",
".",
"id",
":",
"data",
"=",
"self",
".",
"connection",
".",
"post",
"(",
"'add_image'",
",",
"filename",
",",
"video_id... | Set the poster or thumbnail of a this Vidoe. | [
"Set",
"the",
"poster",
"or",
"thumbnail",
"of",
"a",
"this",
"Vidoe",
"."
] | 19c946b689a80156e070fe9bc35589c4b768e614 | https://github.com/studionow/pybrightcove/blob/19c946b689a80156e070fe9bc35589c4b768e614/pybrightcove/video.py#L584-L592 | train | 54,778 |
studionow/pybrightcove | pybrightcove/video.py | Video.find_related | def find_related(self, _connection=None, page_size=100, page_number=0):
"""
List all videos that are related to this one.
"""
if self.id:
return connection.ItemResultSet('find_related_videos',
Video, _connection, page_size, page_number, None, None,
video_id=self.id) | python | def find_related(self, _connection=None, page_size=100, page_number=0):
"""
List all videos that are related to this one.
"""
if self.id:
return connection.ItemResultSet('find_related_videos',
Video, _connection, page_size, page_number, None, None,
video_id=self.id) | [
"def",
"find_related",
"(",
"self",
",",
"_connection",
"=",
"None",
",",
"page_size",
"=",
"100",
",",
"page_number",
"=",
"0",
")",
":",
"if",
"self",
".",
"id",
":",
"return",
"connection",
".",
"ItemResultSet",
"(",
"'find_related_videos'",
",",
"Video... | List all videos that are related to this one. | [
"List",
"all",
"videos",
"that",
"are",
"related",
"to",
"this",
"one",
"."
] | 19c946b689a80156e070fe9bc35589c4b768e614 | https://github.com/studionow/pybrightcove/blob/19c946b689a80156e070fe9bc35589c4b768e614/pybrightcove/video.py#L594-L601 | train | 54,779 |
studionow/pybrightcove | pybrightcove/video.py | Video.delete_video | def delete_video(video_id, cascade=False, delete_shares=False,
_connection=None):
"""
Delete the video represented by the ``video_id`` parameter.
"""
c = _connection
if not c:
c = connection.APIConnection()
c.post('delete_video', video_id=video_id, cascade=cascade,
delete_shares=delete_shares) | python | def delete_video(video_id, cascade=False, delete_shares=False,
_connection=None):
"""
Delete the video represented by the ``video_id`` parameter.
"""
c = _connection
if not c:
c = connection.APIConnection()
c.post('delete_video', video_id=video_id, cascade=cascade,
delete_shares=delete_shares) | [
"def",
"delete_video",
"(",
"video_id",
",",
"cascade",
"=",
"False",
",",
"delete_shares",
"=",
"False",
",",
"_connection",
"=",
"None",
")",
":",
"c",
"=",
"_connection",
"if",
"not",
"c",
":",
"c",
"=",
"connection",
".",
"APIConnection",
"(",
")",
... | Delete the video represented by the ``video_id`` parameter. | [
"Delete",
"the",
"video",
"represented",
"by",
"the",
"video_id",
"parameter",
"."
] | 19c946b689a80156e070fe9bc35589c4b768e614 | https://github.com/studionow/pybrightcove/blob/19c946b689a80156e070fe9bc35589c4b768e614/pybrightcove/video.py#L611-L620 | train | 54,780 |
studionow/pybrightcove | pybrightcove/video.py | Video.get_status | def get_status(video_id, _connection=None):
"""
Get the status of a video given the ``video_id`` parameter.
"""
c = _connection
if not c:
c = connection.APIConnection()
return c.post('get_upload_status', video_id=video_id) | python | def get_status(video_id, _connection=None):
"""
Get the status of a video given the ``video_id`` parameter.
"""
c = _connection
if not c:
c = connection.APIConnection()
return c.post('get_upload_status', video_id=video_id) | [
"def",
"get_status",
"(",
"video_id",
",",
"_connection",
"=",
"None",
")",
":",
"c",
"=",
"_connection",
"if",
"not",
"c",
":",
"c",
"=",
"connection",
".",
"APIConnection",
"(",
")",
"return",
"c",
".",
"post",
"(",
"'get_upload_status'",
",",
"video_i... | Get the status of a video given the ``video_id`` parameter. | [
"Get",
"the",
"status",
"of",
"a",
"video",
"given",
"the",
"video_id",
"parameter",
"."
] | 19c946b689a80156e070fe9bc35589c4b768e614 | https://github.com/studionow/pybrightcove/blob/19c946b689a80156e070fe9bc35589c4b768e614/pybrightcove/video.py#L623-L630 | train | 54,781 |
studionow/pybrightcove | pybrightcove/video.py | Video.activate | def activate(video_id, _connection=None):
"""
Mark a video as Active
"""
c = _connection
if not c:
c = connection.APIConnection()
data = c.post('update_video', video={
'id': video_id,
'itemState': enums.ItemStateEnum.ACTIVE})
return Video(data=data, _connection=c) | python | def activate(video_id, _connection=None):
"""
Mark a video as Active
"""
c = _connection
if not c:
c = connection.APIConnection()
data = c.post('update_video', video={
'id': video_id,
'itemState': enums.ItemStateEnum.ACTIVE})
return Video(data=data, _connection=c) | [
"def",
"activate",
"(",
"video_id",
",",
"_connection",
"=",
"None",
")",
":",
"c",
"=",
"_connection",
"if",
"not",
"c",
":",
"c",
"=",
"connection",
".",
"APIConnection",
"(",
")",
"data",
"=",
"c",
".",
"post",
"(",
"'update_video'",
",",
"video",
... | Mark a video as Active | [
"Mark",
"a",
"video",
"as",
"Active"
] | 19c946b689a80156e070fe9bc35589c4b768e614 | https://github.com/studionow/pybrightcove/blob/19c946b689a80156e070fe9bc35589c4b768e614/pybrightcove/video.py#L633-L643 | train | 54,782 |
studionow/pybrightcove | pybrightcove/video.py | Video.find_modified | def find_modified(since, filter_list=None, _connection=None, page_size=25,
page_number=0, sort_by=enums.DEFAULT_SORT_BY,
sort_order=enums.DEFAULT_SORT_ORDER):
"""
List all videos modified since a certain date.
"""
filters = []
if filter_list is not None:
filters = filter_list
if not isinstance(since, datetime):
msg = 'The parameter "since" must be a datetime object.'
raise exceptions.PyBrightcoveError(msg)
fdate = int(since.strftime("%s")) / 60 ## Minutes since UNIX time
return connection.ItemResultSet('find_modified_videos',
Video, _connection, page_size, page_number, sort_by, sort_order,
from_date=fdate, filter=filters) | python | def find_modified(since, filter_list=None, _connection=None, page_size=25,
page_number=0, sort_by=enums.DEFAULT_SORT_BY,
sort_order=enums.DEFAULT_SORT_ORDER):
"""
List all videos modified since a certain date.
"""
filters = []
if filter_list is not None:
filters = filter_list
if not isinstance(since, datetime):
msg = 'The parameter "since" must be a datetime object.'
raise exceptions.PyBrightcoveError(msg)
fdate = int(since.strftime("%s")) / 60 ## Minutes since UNIX time
return connection.ItemResultSet('find_modified_videos',
Video, _connection, page_size, page_number, sort_by, sort_order,
from_date=fdate, filter=filters) | [
"def",
"find_modified",
"(",
"since",
",",
"filter_list",
"=",
"None",
",",
"_connection",
"=",
"None",
",",
"page_size",
"=",
"25",
",",
"page_number",
"=",
"0",
",",
"sort_by",
"=",
"enums",
".",
"DEFAULT_SORT_BY",
",",
"sort_order",
"=",
"enums",
".",
... | List all videos modified since a certain date. | [
"List",
"all",
"videos",
"modified",
"since",
"a",
"certain",
"date",
"."
] | 19c946b689a80156e070fe9bc35589c4b768e614 | https://github.com/studionow/pybrightcove/blob/19c946b689a80156e070fe9bc35589c4b768e614/pybrightcove/video.py#L646-L661 | train | 54,783 |
studionow/pybrightcove | pybrightcove/video.py | Video.find_all | def find_all(_connection=None, page_size=100, page_number=0,
sort_by=enums.DEFAULT_SORT_BY, sort_order=enums.DEFAULT_SORT_ORDER):
"""
List all videos.
"""
return connection.ItemResultSet('find_all_videos', Video,
_connection, page_size, page_number, sort_by, sort_order) | python | def find_all(_connection=None, page_size=100, page_number=0,
sort_by=enums.DEFAULT_SORT_BY, sort_order=enums.DEFAULT_SORT_ORDER):
"""
List all videos.
"""
return connection.ItemResultSet('find_all_videos', Video,
_connection, page_size, page_number, sort_by, sort_order) | [
"def",
"find_all",
"(",
"_connection",
"=",
"None",
",",
"page_size",
"=",
"100",
",",
"page_number",
"=",
"0",
",",
"sort_by",
"=",
"enums",
".",
"DEFAULT_SORT_BY",
",",
"sort_order",
"=",
"enums",
".",
"DEFAULT_SORT_ORDER",
")",
":",
"return",
"connection"... | List all videos. | [
"List",
"all",
"videos",
"."
] | 19c946b689a80156e070fe9bc35589c4b768e614 | https://github.com/studionow/pybrightcove/blob/19c946b689a80156e070fe9bc35589c4b768e614/pybrightcove/video.py#L664-L670 | train | 54,784 |
studionow/pybrightcove | pybrightcove/video.py | Video.find_by_tags | def find_by_tags(and_tags=None, or_tags=None, _connection=None,
page_size=100, page_number=0, sort_by=enums.DEFAULT_SORT_BY,
sort_order=enums.DEFAULT_SORT_ORDER):
"""
List videos given a certain set of tags.
"""
err = None
if not and_tags and not or_tags:
err = "You must supply at least one of either and_tags or or_tags."
if and_tags and not isinstance(and_tags, (tuple, list)):
err = "The and_tags argument for Video.find_by_tags must an "
err += "iterable"
if or_tags and not isinstance(or_tags, (tuple, list)):
err = "The or_tags argument for Video.find_by_tags must an "
err += "iterable"
if err:
raise exceptions.PyBrightcoveError(err)
atags = None
otags = None
if and_tags:
atags = ','.join([str(t) for t in and_tags])
if or_tags:
otags = ','.join([str(t) for t in or_tags])
return connection.ItemResultSet('find_videos_by_tags',
Video, _connection, page_size, page_number, sort_by, sort_order,
and_tags=atags, or_tags=otags) | python | def find_by_tags(and_tags=None, or_tags=None, _connection=None,
page_size=100, page_number=0, sort_by=enums.DEFAULT_SORT_BY,
sort_order=enums.DEFAULT_SORT_ORDER):
"""
List videos given a certain set of tags.
"""
err = None
if not and_tags and not or_tags:
err = "You must supply at least one of either and_tags or or_tags."
if and_tags and not isinstance(and_tags, (tuple, list)):
err = "The and_tags argument for Video.find_by_tags must an "
err += "iterable"
if or_tags and not isinstance(or_tags, (tuple, list)):
err = "The or_tags argument for Video.find_by_tags must an "
err += "iterable"
if err:
raise exceptions.PyBrightcoveError(err)
atags = None
otags = None
if and_tags:
atags = ','.join([str(t) for t in and_tags])
if or_tags:
otags = ','.join([str(t) for t in or_tags])
return connection.ItemResultSet('find_videos_by_tags',
Video, _connection, page_size, page_number, sort_by, sort_order,
and_tags=atags, or_tags=otags) | [
"def",
"find_by_tags",
"(",
"and_tags",
"=",
"None",
",",
"or_tags",
"=",
"None",
",",
"_connection",
"=",
"None",
",",
"page_size",
"=",
"100",
",",
"page_number",
"=",
"0",
",",
"sort_by",
"=",
"enums",
".",
"DEFAULT_SORT_BY",
",",
"sort_order",
"=",
"... | List videos given a certain set of tags. | [
"List",
"videos",
"given",
"a",
"certain",
"set",
"of",
"tags",
"."
] | 19c946b689a80156e070fe9bc35589c4b768e614 | https://github.com/studionow/pybrightcove/blob/19c946b689a80156e070fe9bc35589c4b768e614/pybrightcove/video.py#L673-L698 | train | 54,785 |
studionow/pybrightcove | pybrightcove/video.py | Video.find_by_text | def find_by_text(text, _connection=None, page_size=100, page_number=0,
sort_by=enums.DEFAULT_SORT_BY, sort_order=enums.DEFAULT_SORT_ORDER):
"""
List videos that match the ``text`` in title or description.
"""
return connection.ItemResultSet('find_videos_by_text',
Video, _connection, page_size, page_number, sort_by, sort_order,
text=text) | python | def find_by_text(text, _connection=None, page_size=100, page_number=0,
sort_by=enums.DEFAULT_SORT_BY, sort_order=enums.DEFAULT_SORT_ORDER):
"""
List videos that match the ``text`` in title or description.
"""
return connection.ItemResultSet('find_videos_by_text',
Video, _connection, page_size, page_number, sort_by, sort_order,
text=text) | [
"def",
"find_by_text",
"(",
"text",
",",
"_connection",
"=",
"None",
",",
"page_size",
"=",
"100",
",",
"page_number",
"=",
"0",
",",
"sort_by",
"=",
"enums",
".",
"DEFAULT_SORT_BY",
",",
"sort_order",
"=",
"enums",
".",
"DEFAULT_SORT_ORDER",
")",
":",
"re... | List videos that match the ``text`` in title or description. | [
"List",
"videos",
"that",
"match",
"the",
"text",
"in",
"title",
"or",
"description",
"."
] | 19c946b689a80156e070fe9bc35589c4b768e614 | https://github.com/studionow/pybrightcove/blob/19c946b689a80156e070fe9bc35589c4b768e614/pybrightcove/video.py#L701-L708 | train | 54,786 |
studionow/pybrightcove | pybrightcove/video.py | Video.find_by_campaign | def find_by_campaign(campaign_id, _connection=None, page_size=100,
page_number=0, sort_by=enums.DEFAULT_SORT_BY,
sort_order=enums.DEFAULT_SORT_ORDER):
"""
List all videos for a given campaign.
"""
return connection.ItemResultSet(
'find_videos_by_campaign_id', Video, _connection, page_size,
page_number, sort_by, sort_order, campaign_id=campaign_id) | python | def find_by_campaign(campaign_id, _connection=None, page_size=100,
page_number=0, sort_by=enums.DEFAULT_SORT_BY,
sort_order=enums.DEFAULT_SORT_ORDER):
"""
List all videos for a given campaign.
"""
return connection.ItemResultSet(
'find_videos_by_campaign_id', Video, _connection, page_size,
page_number, sort_by, sort_order, campaign_id=campaign_id) | [
"def",
"find_by_campaign",
"(",
"campaign_id",
",",
"_connection",
"=",
"None",
",",
"page_size",
"=",
"100",
",",
"page_number",
"=",
"0",
",",
"sort_by",
"=",
"enums",
".",
"DEFAULT_SORT_BY",
",",
"sort_order",
"=",
"enums",
".",
"DEFAULT_SORT_ORDER",
")",
... | List all videos for a given campaign. | [
"List",
"all",
"videos",
"for",
"a",
"given",
"campaign",
"."
] | 19c946b689a80156e070fe9bc35589c4b768e614 | https://github.com/studionow/pybrightcove/blob/19c946b689a80156e070fe9bc35589c4b768e614/pybrightcove/video.py#L711-L719 | train | 54,787 |
studionow/pybrightcove | pybrightcove/video.py | Video.find_by_user | def find_by_user(user_id, _connection=None, page_size=100, page_number=0,
sort_by=enums.DEFAULT_SORT_BY, sort_order=enums.DEFAULT_SORT_ORDER):
"""
List all videos uploaded by a certain user.
"""
return connection.ItemResultSet('find_videos_by_user_id',
Video, _connection, page_size, page_number, sort_by, sort_order,
user_id=user_id) | python | def find_by_user(user_id, _connection=None, page_size=100, page_number=0,
sort_by=enums.DEFAULT_SORT_BY, sort_order=enums.DEFAULT_SORT_ORDER):
"""
List all videos uploaded by a certain user.
"""
return connection.ItemResultSet('find_videos_by_user_id',
Video, _connection, page_size, page_number, sort_by, sort_order,
user_id=user_id) | [
"def",
"find_by_user",
"(",
"user_id",
",",
"_connection",
"=",
"None",
",",
"page_size",
"=",
"100",
",",
"page_number",
"=",
"0",
",",
"sort_by",
"=",
"enums",
".",
"DEFAULT_SORT_BY",
",",
"sort_order",
"=",
"enums",
".",
"DEFAULT_SORT_ORDER",
")",
":",
... | List all videos uploaded by a certain user. | [
"List",
"all",
"videos",
"uploaded",
"by",
"a",
"certain",
"user",
"."
] | 19c946b689a80156e070fe9bc35589c4b768e614 | https://github.com/studionow/pybrightcove/blob/19c946b689a80156e070fe9bc35589c4b768e614/pybrightcove/video.py#L722-L729 | train | 54,788 |
studionow/pybrightcove | pybrightcove/video.py | Video.find_by_reference_ids | def find_by_reference_ids(reference_ids, _connection=None, page_size=100,
page_number=0, sort_by=enums.DEFAULT_SORT_BY,
sort_order=enums.DEFAULT_SORT_ORDER):
"""
List all videos identified by a list of reference ids
"""
if not isinstance(reference_ids, (list, tuple)):
err = "Video.find_by_reference_ids expects an iterable argument"
raise exceptions.PyBrightcoveError(err)
ids = ','.join(reference_ids)
return connection.ItemResultSet(
'find_videos_by_reference_ids', Video, _connection, page_size,
page_number, sort_by, sort_order, reference_ids=ids) | python | def find_by_reference_ids(reference_ids, _connection=None, page_size=100,
page_number=0, sort_by=enums.DEFAULT_SORT_BY,
sort_order=enums.DEFAULT_SORT_ORDER):
"""
List all videos identified by a list of reference ids
"""
if not isinstance(reference_ids, (list, tuple)):
err = "Video.find_by_reference_ids expects an iterable argument"
raise exceptions.PyBrightcoveError(err)
ids = ','.join(reference_ids)
return connection.ItemResultSet(
'find_videos_by_reference_ids', Video, _connection, page_size,
page_number, sort_by, sort_order, reference_ids=ids) | [
"def",
"find_by_reference_ids",
"(",
"reference_ids",
",",
"_connection",
"=",
"None",
",",
"page_size",
"=",
"100",
",",
"page_number",
"=",
"0",
",",
"sort_by",
"=",
"enums",
".",
"DEFAULT_SORT_BY",
",",
"sort_order",
"=",
"enums",
".",
"DEFAULT_SORT_ORDER",
... | List all videos identified by a list of reference ids | [
"List",
"all",
"videos",
"identified",
"by",
"a",
"list",
"of",
"reference",
"ids"
] | 19c946b689a80156e070fe9bc35589c4b768e614 | https://github.com/studionow/pybrightcove/blob/19c946b689a80156e070fe9bc35589c4b768e614/pybrightcove/video.py#L732-L744 | train | 54,789 |
studionow/pybrightcove | pybrightcove/video.py | Video.find_by_ids | def find_by_ids(ids, _connection=None, page_size=100, page_number=0,
sort_by=enums.DEFAULT_SORT_BY, sort_order=enums.DEFAULT_SORT_ORDER):
"""
List all videos identified by a list of Brightcove video ids
"""
if not isinstance(ids, (list, tuple)):
err = "Video.find_by_ids expects an iterable argument"
raise exceptions.PyBrightcoveError(err)
ids = ','.join([str(i) for i in ids])
return connection.ItemResultSet('find_videos_by_ids',
Video, _connection, page_size, page_number, sort_by, sort_order,
video_ids=ids) | python | def find_by_ids(ids, _connection=None, page_size=100, page_number=0,
sort_by=enums.DEFAULT_SORT_BY, sort_order=enums.DEFAULT_SORT_ORDER):
"""
List all videos identified by a list of Brightcove video ids
"""
if not isinstance(ids, (list, tuple)):
err = "Video.find_by_ids expects an iterable argument"
raise exceptions.PyBrightcoveError(err)
ids = ','.join([str(i) for i in ids])
return connection.ItemResultSet('find_videos_by_ids',
Video, _connection, page_size, page_number, sort_by, sort_order,
video_ids=ids) | [
"def",
"find_by_ids",
"(",
"ids",
",",
"_connection",
"=",
"None",
",",
"page_size",
"=",
"100",
",",
"page_number",
"=",
"0",
",",
"sort_by",
"=",
"enums",
".",
"DEFAULT_SORT_BY",
",",
"sort_order",
"=",
"enums",
".",
"DEFAULT_SORT_ORDER",
")",
":",
"if",... | List all videos identified by a list of Brightcove video ids | [
"List",
"all",
"videos",
"identified",
"by",
"a",
"list",
"of",
"Brightcove",
"video",
"ids"
] | 19c946b689a80156e070fe9bc35589c4b768e614 | https://github.com/studionow/pybrightcove/blob/19c946b689a80156e070fe9bc35589c4b768e614/pybrightcove/video.py#L747-L758 | train | 54,790 |
bmcfee/presets | presets/__init__.py | Preset.__wrap | def __wrap(self, func):
'''This decorator overrides the default arguments of a function.
For each keyword argument in the function, the decorator first checks
if the argument has been overridden by the caller, and uses that value instead if so.
If not, the decorator consults the Preset object for an override value.
If both of the above cases fail, the decorator reverts to the function's native
default parameter value.
'''
def deffunc(*args, **kwargs):
'''The decorated function'''
# Get the list of function arguments
if hasattr(inspect, 'signature'):
# Python 3.5
function_args = inspect.signature(func).parameters
else:
function_args = inspect.getargspec(func).args
# Construct a dict of those kwargs which appear in the function
filtered_kwargs = kwargs.copy()
# look at all relevant keyword arguments for this function
for param in function_args:
if param in kwargs:
# Did the user override the default?
filtered_kwargs[param] = kwargs[param]
elif param in self._defaults:
# Do we have a clobbering value in the default dict?
filtered_kwargs[param] = self._defaults[param]
# Call the function with the supplied args and the filtered kwarg dict
return func(*args, **filtered_kwargs) # pylint: disable=W0142
wrapped = functools.update_wrapper(deffunc, func)
# force-mangle the docstring here
wrapped.__doc__ = ('WARNING: this function has been modified by the Presets '
'package.\nDefault parameter values described in the '
'documentation below may be inaccurate.\n\n{}'.format(wrapped.__doc__))
return wrapped | python | def __wrap(self, func):
'''This decorator overrides the default arguments of a function.
For each keyword argument in the function, the decorator first checks
if the argument has been overridden by the caller, and uses that value instead if so.
If not, the decorator consults the Preset object for an override value.
If both of the above cases fail, the decorator reverts to the function's native
default parameter value.
'''
def deffunc(*args, **kwargs):
'''The decorated function'''
# Get the list of function arguments
if hasattr(inspect, 'signature'):
# Python 3.5
function_args = inspect.signature(func).parameters
else:
function_args = inspect.getargspec(func).args
# Construct a dict of those kwargs which appear in the function
filtered_kwargs = kwargs.copy()
# look at all relevant keyword arguments for this function
for param in function_args:
if param in kwargs:
# Did the user override the default?
filtered_kwargs[param] = kwargs[param]
elif param in self._defaults:
# Do we have a clobbering value in the default dict?
filtered_kwargs[param] = self._defaults[param]
# Call the function with the supplied args and the filtered kwarg dict
return func(*args, **filtered_kwargs) # pylint: disable=W0142
wrapped = functools.update_wrapper(deffunc, func)
# force-mangle the docstring here
wrapped.__doc__ = ('WARNING: this function has been modified by the Presets '
'package.\nDefault parameter values described in the '
'documentation below may be inaccurate.\n\n{}'.format(wrapped.__doc__))
return wrapped | [
"def",
"__wrap",
"(",
"self",
",",
"func",
")",
":",
"def",
"deffunc",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"'''The decorated function'''",
"# Get the list of function arguments",
"if",
"hasattr",
"(",
"inspect",
",",
"'signature'",
")",
":",
... | This decorator overrides the default arguments of a function.
For each keyword argument in the function, the decorator first checks
if the argument has been overridden by the caller, and uses that value instead if so.
If not, the decorator consults the Preset object for an override value.
If both of the above cases fail, the decorator reverts to the function's native
default parameter value. | [
"This",
"decorator",
"overrides",
"the",
"default",
"arguments",
"of",
"a",
"function",
"."
] | 07d81fa10d87ab71ef0a8b587d3f36df2829d4a5 | https://github.com/bmcfee/presets/blob/07d81fa10d87ab71ef0a8b587d3f36df2829d4a5/presets/__init__.py#L56-L101 | train | 54,791 |
StarlitGhost/pyhedrals | pyhedrals/pyhedrals.py | DiceParser._sumDiceRolls | def _sumDiceRolls(self, rollList):
"""convert from dice roll structure to a single integer result"""
if isinstance(rollList, RollList):
self.rolls.append(rollList)
return rollList.sum()
else:
return rollList | python | def _sumDiceRolls(self, rollList):
"""convert from dice roll structure to a single integer result"""
if isinstance(rollList, RollList):
self.rolls.append(rollList)
return rollList.sum()
else:
return rollList | [
"def",
"_sumDiceRolls",
"(",
"self",
",",
"rollList",
")",
":",
"if",
"isinstance",
"(",
"rollList",
",",
"RollList",
")",
":",
"self",
".",
"rolls",
".",
"append",
"(",
"rollList",
")",
"return",
"rollList",
".",
"sum",
"(",
")",
"else",
":",
"return"... | convert from dice roll structure to a single integer result | [
"convert",
"from",
"dice",
"roll",
"structure",
"to",
"a",
"single",
"integer",
"result"
] | 74b3a48ecc2b73a27ded913e4152273cd5ba9cc7 | https://github.com/StarlitGhost/pyhedrals/blob/74b3a48ecc2b73a27ded913e4152273cd5ba9cc7/pyhedrals/pyhedrals.py#L442-L448 | train | 54,792 |
mdickinson/refcycle | refcycle/annotations.py | annotated_references | def annotated_references(obj):
"""
Return known information about references held by the given object.
Returns a mapping from referents to lists of descriptions. Note that there
may be more than one edge leading to any particular referent; hence the
need for a list. Descriptions are currently strings.
"""
references = KeyTransformDict(transform=id, default_factory=list)
for type_ in type(obj).__mro__:
if type_ in type_based_references:
type_based_references[type_](obj, references)
add_attr(obj, "__dict__", references)
add_attr(obj, "__class__", references)
if isinstance(obj, type):
add_attr(obj, "__mro__", references)
return references | python | def annotated_references(obj):
"""
Return known information about references held by the given object.
Returns a mapping from referents to lists of descriptions. Note that there
may be more than one edge leading to any particular referent; hence the
need for a list. Descriptions are currently strings.
"""
references = KeyTransformDict(transform=id, default_factory=list)
for type_ in type(obj).__mro__:
if type_ in type_based_references:
type_based_references[type_](obj, references)
add_attr(obj, "__dict__", references)
add_attr(obj, "__class__", references)
if isinstance(obj, type):
add_attr(obj, "__mro__", references)
return references | [
"def",
"annotated_references",
"(",
"obj",
")",
":",
"references",
"=",
"KeyTransformDict",
"(",
"transform",
"=",
"id",
",",
"default_factory",
"=",
"list",
")",
"for",
"type_",
"in",
"type",
"(",
"obj",
")",
".",
"__mro__",
":",
"if",
"type_",
"in",
"t... | Return known information about references held by the given object.
Returns a mapping from referents to lists of descriptions. Note that there
may be more than one edge leading to any particular referent; hence the
need for a list. Descriptions are currently strings. | [
"Return",
"known",
"information",
"about",
"references",
"held",
"by",
"the",
"given",
"object",
"."
] | 627fad74c74efc601209c96405f8118cd99b2241 | https://github.com/mdickinson/refcycle/blob/627fad74c74efc601209c96405f8118cd99b2241/refcycle/annotations.py#L134-L153 | train | 54,793 |
mdickinson/refcycle | refcycle/annotations.py | object_annotation | def object_annotation(obj):
"""
Return a string to be used for Graphviz nodes. The string
should be short but as informative as possible.
"""
# For basic types, use the repr.
if isinstance(obj, BASE_TYPES):
return repr(obj)
if type(obj).__name__ == 'function':
return "function\\n{}".format(obj.__name__)
elif isinstance(obj, types.MethodType):
if six.PY2:
im_class = obj.im_class
if im_class is None:
im_class_name = "<None>"
else:
im_class_name = im_class.__name__
try:
func_name = obj.__func__.__name__
except AttributeError:
func_name = "<anonymous>"
return "instancemethod\\n{}.{}".format(
im_class_name,
func_name,
)
else:
try:
func_name = obj.__func__.__qualname__
except AttributeError:
func_name = "<anonymous>"
return "instancemethod\\n{}".format(func_name)
elif isinstance(obj, list):
return "list[{}]".format(len(obj))
elif isinstance(obj, tuple):
return "tuple[{}]".format(len(obj))
elif isinstance(obj, dict):
return "dict[{}]".format(len(obj))
elif isinstance(obj, types.ModuleType):
return "module\\n{}".format(obj.__name__)
elif isinstance(obj, type):
return "type\\n{}".format(obj.__name__)
elif six.PY2 and isinstance(obj, types.InstanceType):
return "instance\\n{}".format(obj.__class__.__name__)
elif isinstance(obj, weakref.ref):
referent = obj()
if referent is None:
return "weakref (dead referent)"
else:
return "weakref to id 0x{:x}".format(id(referent))
elif isinstance(obj, types.FrameType):
filename = obj.f_code.co_filename
if len(filename) > FRAME_FILENAME_LIMIT:
filename = "..." + filename[-(FRAME_FILENAME_LIMIT-3):]
return "frame\\n{}:{}".format(
filename,
obj.f_lineno,
)
else:
return "object\\n{}.{}".format(
type(obj).__module__,
type(obj).__name__,
) | python | def object_annotation(obj):
"""
Return a string to be used for Graphviz nodes. The string
should be short but as informative as possible.
"""
# For basic types, use the repr.
if isinstance(obj, BASE_TYPES):
return repr(obj)
if type(obj).__name__ == 'function':
return "function\\n{}".format(obj.__name__)
elif isinstance(obj, types.MethodType):
if six.PY2:
im_class = obj.im_class
if im_class is None:
im_class_name = "<None>"
else:
im_class_name = im_class.__name__
try:
func_name = obj.__func__.__name__
except AttributeError:
func_name = "<anonymous>"
return "instancemethod\\n{}.{}".format(
im_class_name,
func_name,
)
else:
try:
func_name = obj.__func__.__qualname__
except AttributeError:
func_name = "<anonymous>"
return "instancemethod\\n{}".format(func_name)
elif isinstance(obj, list):
return "list[{}]".format(len(obj))
elif isinstance(obj, tuple):
return "tuple[{}]".format(len(obj))
elif isinstance(obj, dict):
return "dict[{}]".format(len(obj))
elif isinstance(obj, types.ModuleType):
return "module\\n{}".format(obj.__name__)
elif isinstance(obj, type):
return "type\\n{}".format(obj.__name__)
elif six.PY2 and isinstance(obj, types.InstanceType):
return "instance\\n{}".format(obj.__class__.__name__)
elif isinstance(obj, weakref.ref):
referent = obj()
if referent is None:
return "weakref (dead referent)"
else:
return "weakref to id 0x{:x}".format(id(referent))
elif isinstance(obj, types.FrameType):
filename = obj.f_code.co_filename
if len(filename) > FRAME_FILENAME_LIMIT:
filename = "..." + filename[-(FRAME_FILENAME_LIMIT-3):]
return "frame\\n{}:{}".format(
filename,
obj.f_lineno,
)
else:
return "object\\n{}.{}".format(
type(obj).__module__,
type(obj).__name__,
) | [
"def",
"object_annotation",
"(",
"obj",
")",
":",
"# For basic types, use the repr.",
"if",
"isinstance",
"(",
"obj",
",",
"BASE_TYPES",
")",
":",
"return",
"repr",
"(",
"obj",
")",
"if",
"type",
"(",
"obj",
")",
".",
"__name__",
"==",
"'function'",
":",
"... | Return a string to be used for Graphviz nodes. The string
should be short but as informative as possible. | [
"Return",
"a",
"string",
"to",
"be",
"used",
"for",
"Graphviz",
"nodes",
".",
"The",
"string",
"should",
"be",
"short",
"but",
"as",
"informative",
"as",
"possible",
"."
] | 627fad74c74efc601209c96405f8118cd99b2241 | https://github.com/mdickinson/refcycle/blob/627fad74c74efc601209c96405f8118cd99b2241/refcycle/annotations.py#L165-L228 | train | 54,794 |
wheeler-microfluidics/dmf-control-board-firmware | site_scons/site_tools/disttar/disttar.py | disttar | def disttar(target, source, env):
"""tar archive builder"""
import tarfile
env_dict = env.Dictionary()
if env_dict.get("DISTTAR_FORMAT") in ["gz", "bz2"]:
tar_format = env_dict["DISTTAR_FORMAT"]
else:
tar_format = ""
# split the target directory, filename, and stuffix
base_name = str(target[0]).split('.tar')[0]
(target_dir, dir_name) = os.path.split(base_name)
# create the target directory if it does not exist
if target_dir and not os.path.exists(target_dir):
os.makedirs(target_dir)
# open our tar file for writing
print >> sys.stderr, 'DistTar: Writing %s' % str(target[0])
print >> sys.stderr, ' with contents: %s' % [str(s) for s in source]
tar = tarfile.open(str(target[0]), "w:%s" % tar_format)
# write sources to our tar file
for item in source:
item = str(item)
sys.stderr.write(".")
#print "Adding to TAR file: %s/%s" % (dir_name,item)
tar.add(item,'%s/%s' % (dir_name,item))
# all done
sys.stderr.write("\n") #print "Closing TAR file"
tar.close() | python | def disttar(target, source, env):
"""tar archive builder"""
import tarfile
env_dict = env.Dictionary()
if env_dict.get("DISTTAR_FORMAT") in ["gz", "bz2"]:
tar_format = env_dict["DISTTAR_FORMAT"]
else:
tar_format = ""
# split the target directory, filename, and stuffix
base_name = str(target[0]).split('.tar')[0]
(target_dir, dir_name) = os.path.split(base_name)
# create the target directory if it does not exist
if target_dir and not os.path.exists(target_dir):
os.makedirs(target_dir)
# open our tar file for writing
print >> sys.stderr, 'DistTar: Writing %s' % str(target[0])
print >> sys.stderr, ' with contents: %s' % [str(s) for s in source]
tar = tarfile.open(str(target[0]), "w:%s" % tar_format)
# write sources to our tar file
for item in source:
item = str(item)
sys.stderr.write(".")
#print "Adding to TAR file: %s/%s" % (dir_name,item)
tar.add(item,'%s/%s' % (dir_name,item))
# all done
sys.stderr.write("\n") #print "Closing TAR file"
tar.close() | [
"def",
"disttar",
"(",
"target",
",",
"source",
",",
"env",
")",
":",
"import",
"tarfile",
"env_dict",
"=",
"env",
".",
"Dictionary",
"(",
")",
"if",
"env_dict",
".",
"get",
"(",
"\"DISTTAR_FORMAT\"",
")",
"in",
"[",
"\"gz\"",
",",
"\"bz2\"",
"]",
":",... | tar archive builder | [
"tar",
"archive",
"builder"
] | 1cd8cc9a148d530f9a11f634f2dbfe73f08aa27c | https://github.com/wheeler-microfluidics/dmf-control-board-firmware/blob/1cd8cc9a148d530f9a11f634f2dbfe73f08aa27c/site_scons/site_tools/disttar/disttar.py#L79-L113 | train | 54,795 |
wheeler-microfluidics/dmf-control-board-firmware | site_scons/site_tools/disttar/disttar.py | disttar_suffix | def disttar_suffix(env, sources):
"""tar archive suffix generator"""
env_dict = env.Dictionary()
if env_dict.has_key("DISTTAR_FORMAT") and env_dict["DISTTAR_FORMAT"] in ["gz", "bz2"]:
return ".tar." + env_dict["DISTTAR_FORMAT"]
else:
return ".tar" | python | def disttar_suffix(env, sources):
"""tar archive suffix generator"""
env_dict = env.Dictionary()
if env_dict.has_key("DISTTAR_FORMAT") and env_dict["DISTTAR_FORMAT"] in ["gz", "bz2"]:
return ".tar." + env_dict["DISTTAR_FORMAT"]
else:
return ".tar" | [
"def",
"disttar_suffix",
"(",
"env",
",",
"sources",
")",
":",
"env_dict",
"=",
"env",
".",
"Dictionary",
"(",
")",
"if",
"env_dict",
".",
"has_key",
"(",
"\"DISTTAR_FORMAT\"",
")",
"and",
"env_dict",
"[",
"\"DISTTAR_FORMAT\"",
"]",
"in",
"[",
"\"gz\"",
",... | tar archive suffix generator | [
"tar",
"archive",
"suffix",
"generator"
] | 1cd8cc9a148d530f9a11f634f2dbfe73f08aa27c | https://github.com/wheeler-microfluidics/dmf-control-board-firmware/blob/1cd8cc9a148d530f9a11f634f2dbfe73f08aa27c/site_scons/site_tools/disttar/disttar.py#L115-L122 | train | 54,796 |
wheeler-microfluidics/dmf-control-board-firmware | site_scons/site_tools/disttar/disttar.py | generate | def generate(env):
"""
Add builders and construction variables for the DistTar builder.
"""
disttar_action=SCons.Action.Action(disttar, disttar_string)
env['BUILDERS']['DistTar'] = Builder(
action=disttar_action
, emitter=disttar_emitter
, suffix = disttar_suffix
, target_factory = env.fs.Entry
)
env.AppendUnique(
DISTTAR_FORMAT = 'gz'
) | python | def generate(env):
"""
Add builders and construction variables for the DistTar builder.
"""
disttar_action=SCons.Action.Action(disttar, disttar_string)
env['BUILDERS']['DistTar'] = Builder(
action=disttar_action
, emitter=disttar_emitter
, suffix = disttar_suffix
, target_factory = env.fs.Entry
)
env.AppendUnique(
DISTTAR_FORMAT = 'gz'
) | [
"def",
"generate",
"(",
"env",
")",
":",
"disttar_action",
"=",
"SCons",
".",
"Action",
".",
"Action",
"(",
"disttar",
",",
"disttar_string",
")",
"env",
"[",
"'BUILDERS'",
"]",
"[",
"'DistTar'",
"]",
"=",
"Builder",
"(",
"action",
"=",
"disttar_action",
... | Add builders and construction variables for the DistTar builder. | [
"Add",
"builders",
"and",
"construction",
"variables",
"for",
"the",
"DistTar",
"builder",
"."
] | 1cd8cc9a148d530f9a11f634f2dbfe73f08aa27c | https://github.com/wheeler-microfluidics/dmf-control-board-firmware/blob/1cd8cc9a148d530f9a11f634f2dbfe73f08aa27c/site_scons/site_tools/disttar/disttar.py#L124-L139 | train | 54,797 |
memphis-iis/GLUDB | gludb/backends/postgresql.py | Backend.find_one | def find_one(self, cls, id):
"""Find single keyed row - as per the gludb spec."""
found = self.find_by_index(cls, 'id', id)
return found[0] if found else None | python | def find_one(self, cls, id):
"""Find single keyed row - as per the gludb spec."""
found = self.find_by_index(cls, 'id', id)
return found[0] if found else None | [
"def",
"find_one",
"(",
"self",
",",
"cls",
",",
"id",
")",
":",
"found",
"=",
"self",
".",
"find_by_index",
"(",
"cls",
",",
"'id'",
",",
"id",
")",
"return",
"found",
"[",
"0",
"]",
"if",
"found",
"else",
"None"
] | Find single keyed row - as per the gludb spec. | [
"Find",
"single",
"keyed",
"row",
"-",
"as",
"per",
"the",
"gludb",
"spec",
"."
] | 25692528ff6fe8184a3570f61f31f1a90088a388 | https://github.com/memphis-iis/GLUDB/blob/25692528ff6fe8184a3570f61f31f1a90088a388/gludb/backends/postgresql.py#L64-L67 | train | 54,798 |
memphis-iis/GLUDB | gludb/backends/postgresql.py | Backend.save | def save(self, obj):
"""Save current instance - as per the gludb spec."""
cur = self._conn().cursor()
tabname = obj.__class__.get_table_name()
index_names = obj.__class__.index_names() or []
col_names = ['id', 'value'] + index_names
value_holders = ['%s'] * len(col_names)
updates = ['%s = EXCLUDED.%s' % (cn, cn) for cn in col_names[1:]]
if not obj.id:
id = uuid()
obj.id = id
query = 'insert into {0} ({1}) values ({2}) on conflict(id) do update set {3};'.format(
tabname,
','.join(col_names),
','.join(value_holders),
','.join(updates),
)
values = [obj.id, obj.to_data()]
index_vals = obj.indexes() or {}
values += [index_vals.get(name, 'NULL') for name in index_names]
with self._conn() as conn:
with conn.cursor() as cur:
cur.execute(query, tuple(values)) | python | def save(self, obj):
"""Save current instance - as per the gludb spec."""
cur = self._conn().cursor()
tabname = obj.__class__.get_table_name()
index_names = obj.__class__.index_names() or []
col_names = ['id', 'value'] + index_names
value_holders = ['%s'] * len(col_names)
updates = ['%s = EXCLUDED.%s' % (cn, cn) for cn in col_names[1:]]
if not obj.id:
id = uuid()
obj.id = id
query = 'insert into {0} ({1}) values ({2}) on conflict(id) do update set {3};'.format(
tabname,
','.join(col_names),
','.join(value_holders),
','.join(updates),
)
values = [obj.id, obj.to_data()]
index_vals = obj.indexes() or {}
values += [index_vals.get(name, 'NULL') for name in index_names]
with self._conn() as conn:
with conn.cursor() as cur:
cur.execute(query, tuple(values)) | [
"def",
"save",
"(",
"self",
",",
"obj",
")",
":",
"cur",
"=",
"self",
".",
"_conn",
"(",
")",
".",
"cursor",
"(",
")",
"tabname",
"=",
"obj",
".",
"__class__",
".",
"get_table_name",
"(",
")",
"index_names",
"=",
"obj",
".",
"__class__",
".",
"inde... | Save current instance - as per the gludb spec. | [
"Save",
"current",
"instance",
"-",
"as",
"per",
"the",
"gludb",
"spec",
"."
] | 25692528ff6fe8184a3570f61f31f1a90088a388 | https://github.com/memphis-iis/GLUDB/blob/25692528ff6fe8184a3570f61f31f1a90088a388/gludb/backends/postgresql.py#L96-L126 | train | 54,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.