id int32 0 252k | 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 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
1,700 | fracpete/python-weka-wrapper3 | python/weka/flow/source.py | DataGenerator.from_config | def from_config(self, k, v):
"""
Hook method that allows converting values from the dictionary.
:param k: the key in the dictionary
:type k: str
:param v: the value
:type v: object
:return: the potentially parsed value
:rtype: object
"""
i... | python | def from_config(self, k, v):
if k == "setup":
return from_commandline(v, classname=to_commandline(datagen.DataGenerator()))
return super(DataGenerator, self).from_config(k, v) | [
"def",
"from_config",
"(",
"self",
",",
"k",
",",
"v",
")",
":",
"if",
"k",
"==",
"\"setup\"",
":",
"return",
"from_commandline",
"(",
"v",
",",
"classname",
"=",
"to_commandline",
"(",
"datagen",
".",
"DataGenerator",
"(",
")",
")",
")",
"return",
"su... | Hook method that allows converting values from the dictionary.
:param k: the key in the dictionary
:type k: str
:param v: the value
:type v: object
:return: the potentially parsed value
:rtype: object | [
"Hook",
"method",
"that",
"allows",
"converting",
"values",
"from",
"the",
"dictionary",
"."
] | d850ab1bdb25fbd5a8d86e99f34a397975425838 | https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/flow/source.py#L613-L626 |
1,701 | fracpete/python-weka-wrapper3 | python/weka/experiments.py | SimpleExperiment.configure_splitevaluator | def configure_splitevaluator(self):
"""
Configures and returns the SplitEvaluator and Classifier instance as tuple.
:return: evaluator and classifier
:rtype: tuple
"""
if self.classification:
speval = javabridge.make_instance("weka/experiment/ClassifierSplitE... | python | def configure_splitevaluator(self):
if self.classification:
speval = javabridge.make_instance("weka/experiment/ClassifierSplitEvaluator", "()V")
else:
speval = javabridge.make_instance("weka/experiment/RegressionSplitEvaluator", "()V")
classifier = javabridge.call(speval,... | [
"def",
"configure_splitevaluator",
"(",
"self",
")",
":",
"if",
"self",
".",
"classification",
":",
"speval",
"=",
"javabridge",
".",
"make_instance",
"(",
"\"weka/experiment/ClassifierSplitEvaluator\"",
",",
"\"()V\"",
")",
"else",
":",
"speval",
"=",
"javabridge",... | Configures and returns the SplitEvaluator and Classifier instance as tuple.
:return: evaluator and classifier
:rtype: tuple | [
"Configures",
"and",
"returns",
"the",
"SplitEvaluator",
"and",
"Classifier",
"instance",
"as",
"tuple",
"."
] | d850ab1bdb25fbd5a8d86e99f34a397975425838 | https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/experiments.py#L86-L98 |
1,702 | fracpete/python-weka-wrapper3 | python/weka/experiments.py | SimpleExperiment.setup | def setup(self):
"""
Initializes the experiment.
"""
# basic options
javabridge.call(
self.jobject, "setPropertyArray", "(Ljava/lang/Object;)V",
javabridge.get_env().make_object_array(0, javabridge.get_env().find_class("weka/classifiers/Classifier")))
... | python | def setup(self):
# basic options
javabridge.call(
self.jobject, "setPropertyArray", "(Ljava/lang/Object;)V",
javabridge.get_env().make_object_array(0, javabridge.get_env().find_class("weka/classifiers/Classifier")))
javabridge.call(
self.jobject, "setUseProper... | [
"def",
"setup",
"(",
"self",
")",
":",
"# basic options",
"javabridge",
".",
"call",
"(",
"self",
".",
"jobject",
",",
"\"setPropertyArray\"",
",",
"\"(Ljava/lang/Object;)V\"",
",",
"javabridge",
".",
"get_env",
"(",
")",
".",
"make_object_array",
"(",
"0",
",... | Initializes the experiment. | [
"Initializes",
"the",
"experiment",
"."
] | d850ab1bdb25fbd5a8d86e99f34a397975425838 | https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/experiments.py#L109-L164 |
1,703 | fracpete/python-weka-wrapper3 | python/weka/experiments.py | SimpleExperiment.run | def run(self):
"""
Executes the experiment.
"""
logger.info("Initializing...")
javabridge.call(self.jobject, "initialize", "()V")
logger.info("Running...")
javabridge.call(self.jobject, "runExperiment", "()V")
logger.info("Finished...")
javabridge.... | python | def run(self):
logger.info("Initializing...")
javabridge.call(self.jobject, "initialize", "()V")
logger.info("Running...")
javabridge.call(self.jobject, "runExperiment", "()V")
logger.info("Finished...")
javabridge.call(self.jobject, "postProcess", "()V") | [
"def",
"run",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"\"Initializing...\"",
")",
"javabridge",
".",
"call",
"(",
"self",
".",
"jobject",
",",
"\"initialize\"",
",",
"\"()V\"",
")",
"logger",
".",
"info",
"(",
"\"Running...\"",
")",
"javabridge"... | Executes the experiment. | [
"Executes",
"the",
"experiment",
"."
] | d850ab1bdb25fbd5a8d86e99f34a397975425838 | https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/experiments.py#L166-L175 |
1,704 | fracpete/python-weka-wrapper3 | python/weka/experiments.py | SimpleExperiment.load | def load(cls, filename):
"""
Loads the experiment from disk.
:param filename: the filename of the experiment to load
:type filename: str
:return: the experiment
:rtype: Experiment
"""
jobject = javabridge.static_call(
"weka/experiment/Experime... | python | def load(cls, filename):
jobject = javabridge.static_call(
"weka/experiment/Experiment", "read", "(Ljava/lang/String;)Lweka/experiment/Experiment;",
filename)
return Experiment(jobject=jobject) | [
"def",
"load",
"(",
"cls",
",",
"filename",
")",
":",
"jobject",
"=",
"javabridge",
".",
"static_call",
"(",
"\"weka/experiment/Experiment\"",
",",
"\"read\"",
",",
"\"(Ljava/lang/String;)Lweka/experiment/Experiment;\"",
",",
"filename",
")",
"return",
"Experiment",
"... | Loads the experiment from disk.
:param filename: the filename of the experiment to load
:type filename: str
:return: the experiment
:rtype: Experiment | [
"Loads",
"the",
"experiment",
"from",
"disk",
"."
] | d850ab1bdb25fbd5a8d86e99f34a397975425838 | https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/experiments.py#L190-L202 |
1,705 | fracpete/python-weka-wrapper3 | python/weka/experiments.py | SimpleRandomSplitExperiment.configure_resultproducer | def configure_resultproducer(self):
"""
Configures and returns the ResultProducer and PropertyPath as tuple.
:return: producer and property path
:rtype: tuple
"""
rproducer = javabridge.make_instance("weka/experiment/RandomSplitResultProducer", "()V")
javabridge.... | python | def configure_resultproducer(self):
rproducer = javabridge.make_instance("weka/experiment/RandomSplitResultProducer", "()V")
javabridge.call(rproducer, "setRandomizeData", "(Z)V", not self.preserve_order)
javabridge.call(rproducer, "setTrainPercent", "(D)V", self.percentage)
speval, clas... | [
"def",
"configure_resultproducer",
"(",
"self",
")",
":",
"rproducer",
"=",
"javabridge",
".",
"make_instance",
"(",
"\"weka/experiment/RandomSplitResultProducer\"",
",",
"\"()V\"",
")",
"javabridge",
".",
"call",
"(",
"rproducer",
",",
"\"setRandomizeData\"",
",",
"\... | Configures and returns the ResultProducer and PropertyPath as tuple.
:return: producer and property path
:rtype: tuple | [
"Configures",
"and",
"returns",
"the",
"ResultProducer",
"and",
"PropertyPath",
"as",
"tuple",
"."
] | d850ab1bdb25fbd5a8d86e99f34a397975425838 | https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/experiments.py#L336-L365 |
1,706 | fracpete/python-weka-wrapper3 | python/weka/experiments.py | ResultMatrix.set_row_name | def set_row_name(self, index, name):
"""
Sets the row name.
:param index: the 0-based row index
:type index: int
:param name: the name of the row
:type name: str
"""
javabridge.call(self.jobject, "setRowName", "(ILjava/lang/String;)V", index, name) | python | def set_row_name(self, index, name):
javabridge.call(self.jobject, "setRowName", "(ILjava/lang/String;)V", index, name) | [
"def",
"set_row_name",
"(",
"self",
",",
"index",
",",
"name",
")",
":",
"javabridge",
".",
"call",
"(",
"self",
".",
"jobject",
",",
"\"setRowName\"",
",",
"\"(ILjava/lang/String;)V\"",
",",
"index",
",",
"name",
")"
] | Sets the row name.
:param index: the 0-based row index
:type index: int
:param name: the name of the row
:type name: str | [
"Sets",
"the",
"row",
"name",
"."
] | d850ab1bdb25fbd5a8d86e99f34a397975425838 | https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/experiments.py#L478-L487 |
1,707 | fracpete/python-weka-wrapper3 | python/weka/experiments.py | ResultMatrix.set_col_name | def set_col_name(self, index, name):
"""
Sets the column name.
:param index: the 0-based row index
:type index: int
:param name: the name of the column
:type name: str
"""
javabridge.call(self.jobject, "setColName", "(ILjava/lang/String;)V", index, name) | python | def set_col_name(self, index, name):
javabridge.call(self.jobject, "setColName", "(ILjava/lang/String;)V", index, name) | [
"def",
"set_col_name",
"(",
"self",
",",
"index",
",",
"name",
")",
":",
"javabridge",
".",
"call",
"(",
"self",
".",
"jobject",
",",
"\"setColName\"",
",",
"\"(ILjava/lang/String;)V\"",
",",
"index",
",",
"name",
")"
] | Sets the column name.
:param index: the 0-based row index
:type index: int
:param name: the name of the column
:type name: str | [
"Sets",
"the",
"column",
"name",
"."
] | d850ab1bdb25fbd5a8d86e99f34a397975425838 | https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/experiments.py#L500-L509 |
1,708 | redcap-tools/PyCap | redcap/request.py | RCRequest.validate | def validate(self):
"""Checks that at least required params exist"""
required = ['token', 'content']
valid_data = {
'exp_record': (['type', 'format'], 'record',
'Exporting record but content is not record'),
'imp_record': (['type', 'overwriteBehavior', 'da... | python | def validate(self):
required = ['token', 'content']
valid_data = {
'exp_record': (['type', 'format'], 'record',
'Exporting record but content is not record'),
'imp_record': (['type', 'overwriteBehavior', 'data', 'format'],
'record', 'Importing reco... | [
"def",
"validate",
"(",
"self",
")",
":",
"required",
"=",
"[",
"'token'",
",",
"'content'",
"]",
"valid_data",
"=",
"{",
"'exp_record'",
":",
"(",
"[",
"'type'",
",",
"'format'",
"]",
",",
"'record'",
",",
"'Exporting record but content is not record'",
")",
... | Checks that at least required params exist | [
"Checks",
"that",
"at",
"least",
"required",
"params",
"exist"
] | f44c9b62a4f62675aa609c06608663f37e12097e | https://github.com/redcap-tools/PyCap/blob/f44c9b62a4f62675aa609c06608663f37e12097e/redcap/request.py#L64-L107 |
1,709 | redcap-tools/PyCap | redcap/request.py | RCRequest.execute | def execute(self, **kwargs):
"""Execute the API request and return data
Parameters
----------
kwargs :
passed to requests.post()
Returns
-------
response : list, str
data object from JSON decoding process if format=='json',
el... | python | def execute(self, **kwargs):
r = post(self.url, data=self.payload, **kwargs)
# Raise if we need to
self.raise_for_status(r)
content = self.get_content(r)
return content, r.headers | [
"def",
"execute",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"r",
"=",
"post",
"(",
"self",
".",
"url",
",",
"data",
"=",
"self",
".",
"payload",
",",
"*",
"*",
"kwargs",
")",
"# Raise if we need to",
"self",
".",
"raise_for_status",
"(",
"r",
... | Execute the API request and return data
Parameters
----------
kwargs :
passed to requests.post()
Returns
-------
response : list, str
data object from JSON decoding process if format=='json',
else return raw string (ie format=='csv'|'... | [
"Execute",
"the",
"API",
"request",
"and",
"return",
"data"
] | f44c9b62a4f62675aa609c06608663f37e12097e | https://github.com/redcap-tools/PyCap/blob/f44c9b62a4f62675aa609c06608663f37e12097e/redcap/request.py#L109-L127 |
1,710 | redcap-tools/PyCap | redcap/request.py | RCRequest.get_content | def get_content(self, r):
"""Abstraction for grabbing content from a returned response"""
if self.type == 'exp_file':
# don't use the decoded r.text
return r.content
elif self.type == 'version':
return r.content
else:
if self.fmt == 'json':... | python | def get_content(self, r):
if self.type == 'exp_file':
# don't use the decoded r.text
return r.content
elif self.type == 'version':
return r.content
else:
if self.fmt == 'json':
content = {}
# Decode
t... | [
"def",
"get_content",
"(",
"self",
",",
"r",
")",
":",
"if",
"self",
".",
"type",
"==",
"'exp_file'",
":",
"# don't use the decoded r.text",
"return",
"r",
".",
"content",
"elif",
"self",
".",
"type",
"==",
"'version'",
":",
"return",
"r",
".",
"content",
... | Abstraction for grabbing content from a returned response | [
"Abstraction",
"for",
"grabbing",
"content",
"from",
"a",
"returned",
"response"
] | f44c9b62a4f62675aa609c06608663f37e12097e | https://github.com/redcap-tools/PyCap/blob/f44c9b62a4f62675aa609c06608663f37e12097e/redcap/request.py#L129-L150 |
1,711 | redcap-tools/PyCap | redcap/request.py | RCRequest.raise_for_status | def raise_for_status(self, r):
"""Given a response, raise for bad status for certain actions
Some redcap api methods don't return error messages
that the user could test for or otherwise use. Therefore, we
need to do the testing ourself
Raising for everything wouldn't let the u... | python | def raise_for_status(self, r):
if self.type in ('metadata', 'exp_file', 'imp_file', 'del_file'):
r.raise_for_status()
# see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
# specifically 10.5
if 500 <= r.status_code < 600:
raise RedcapError(r.content) | [
"def",
"raise_for_status",
"(",
"self",
",",
"r",
")",
":",
"if",
"self",
".",
"type",
"in",
"(",
"'metadata'",
",",
"'exp_file'",
",",
"'imp_file'",
",",
"'del_file'",
")",
":",
"r",
".",
"raise_for_status",
"(",
")",
"# see http://www.w3.org/Protocols/rfc261... | Given a response, raise for bad status for certain actions
Some redcap api methods don't return error messages
that the user could test for or otherwise use. Therefore, we
need to do the testing ourself
Raising for everything wouldn't let the user see the
(hopefully helpful) er... | [
"Given",
"a",
"response",
"raise",
"for",
"bad",
"status",
"for",
"certain",
"actions"
] | f44c9b62a4f62675aa609c06608663f37e12097e | https://github.com/redcap-tools/PyCap/blob/f44c9b62a4f62675aa609c06608663f37e12097e/redcap/request.py#L156-L170 |
1,712 | redcap-tools/PyCap | redcap/project.py | Project.__basepl | def __basepl(self, content, rec_type='flat', format='json'):
"""Return a dictionary which can be used as is or added to for
payloads"""
d = {'token': self.token, 'content': content, 'format': format}
if content not in ['metadata', 'file']:
d['type'] = rec_type
return ... | python | def __basepl(self, content, rec_type='flat', format='json'):
d = {'token': self.token, 'content': content, 'format': format}
if content not in ['metadata', 'file']:
d['type'] = rec_type
return d | [
"def",
"__basepl",
"(",
"self",
",",
"content",
",",
"rec_type",
"=",
"'flat'",
",",
"format",
"=",
"'json'",
")",
":",
"d",
"=",
"{",
"'token'",
":",
"self",
".",
"token",
",",
"'content'",
":",
"content",
",",
"'format'",
":",
"format",
"}",
"if",
... | Return a dictionary which can be used as is or added to for
payloads | [
"Return",
"a",
"dictionary",
"which",
"can",
"be",
"used",
"as",
"is",
"or",
"added",
"to",
"for",
"payloads"
] | f44c9b62a4f62675aa609c06608663f37e12097e | https://github.com/redcap-tools/PyCap/blob/f44c9b62a4f62675aa609c06608663f37e12097e/redcap/project.py#L95-L101 |
1,713 | redcap-tools/PyCap | redcap/project.py | Project.filter_metadata | def filter_metadata(self, key):
"""
Return a list of values for the metadata key from each field
of the project's metadata.
Parameters
----------
key: str
A known key in the metadata structure
Returns
-------
filtered :
at... | python | def filter_metadata(self, key):
filtered = [field[key] for field in self.metadata if key in field]
if len(filtered) == 0:
raise KeyError("Key not found in metadata")
return filtered | [
"def",
"filter_metadata",
"(",
"self",
",",
"key",
")",
":",
"filtered",
"=",
"[",
"field",
"[",
"key",
"]",
"for",
"field",
"in",
"self",
".",
"metadata",
"if",
"key",
"in",
"field",
"]",
"if",
"len",
"(",
"filtered",
")",
"==",
"0",
":",
"raise",... | Return a list of values for the metadata key from each field
of the project's metadata.
Parameters
----------
key: str
A known key in the metadata structure
Returns
-------
filtered :
attribute list from each field | [
"Return",
"a",
"list",
"of",
"values",
"for",
"the",
"metadata",
"key",
"from",
"each",
"field",
"of",
"the",
"project",
"s",
"metadata",
"."
] | f44c9b62a4f62675aa609c06608663f37e12097e | https://github.com/redcap-tools/PyCap/blob/f44c9b62a4f62675aa609c06608663f37e12097e/redcap/project.py#L125-L143 |
1,714 | redcap-tools/PyCap | redcap/project.py | Project.export_fem | def export_fem(self, arms=None, format='json', df_kwargs=None):
"""
Export the project's form to event mapping
Parameters
----------
arms : list
Limit exported form event mappings to these arm numbers
format : (``'json'``), ``'csv'``, ``'xml'``
Re... | python | def export_fem(self, arms=None, format='json', df_kwargs=None):
ret_format = format
if format == 'df':
from pandas import read_csv
ret_format = 'csv'
pl = self.__basepl('formEventMapping', format=ret_format)
to_add = [arms]
str_add = ['arms']
for k... | [
"def",
"export_fem",
"(",
"self",
",",
"arms",
"=",
"None",
",",
"format",
"=",
"'json'",
",",
"df_kwargs",
"=",
"None",
")",
":",
"ret_format",
"=",
"format",
"if",
"format",
"==",
"'df'",
":",
"from",
"pandas",
"import",
"read_csv",
"ret_format",
"=",
... | Export the project's form to event mapping
Parameters
----------
arms : list
Limit exported form event mappings to these arm numbers
format : (``'json'``), ``'csv'``, ``'xml'``
Return the form event mappings in native objects,
csv or xml, ``'df''`` wi... | [
"Export",
"the",
"project",
"s",
"form",
"to",
"event",
"mapping"
] | f44c9b62a4f62675aa609c06608663f37e12097e | https://github.com/redcap-tools/PyCap/blob/f44c9b62a4f62675aa609c06608663f37e12097e/redcap/project.py#L157-L194 |
1,715 | redcap-tools/PyCap | redcap/project.py | Project.export_metadata | def export_metadata(self, fields=None, forms=None, format='json',
df_kwargs=None):
"""
Export the project's metadata
Parameters
----------
fields : list
Limit exported metadata to these fields
forms : list
Limit exported metadata to th... | python | def export_metadata(self, fields=None, forms=None, format='json',
df_kwargs=None):
ret_format = format
if format == 'df':
from pandas import read_csv
ret_format = 'csv'
pl = self.__basepl('metadata', format=ret_format)
to_add = [fields, forms]
... | [
"def",
"export_metadata",
"(",
"self",
",",
"fields",
"=",
"None",
",",
"forms",
"=",
"None",
",",
"format",
"=",
"'json'",
",",
"df_kwargs",
"=",
"None",
")",
":",
"ret_format",
"=",
"format",
"if",
"format",
"==",
"'df'",
":",
"from",
"pandas",
"impo... | Export the project's metadata
Parameters
----------
fields : list
Limit exported metadata to these fields
forms : list
Limit exported metadata to these forms
format : (``'json'``), ``'csv'``, ``'xml'``, ``'df'``
Return the metadata in native o... | [
"Export",
"the",
"project",
"s",
"metadata"
] | f44c9b62a4f62675aa609c06608663f37e12097e | https://github.com/redcap-tools/PyCap/blob/f44c9b62a4f62675aa609c06608663f37e12097e/redcap/project.py#L196-L236 |
1,716 | redcap-tools/PyCap | redcap/project.py | Project.export_records | def export_records(self, records=None, fields=None, forms=None,
events=None, raw_or_label='raw', event_name='label',
format='json', export_survey_fields=False,
export_data_access_groups=False, df_kwargs=None,
export_checkbox_labels=False, filter_logic=None):
"""
Export data from the REDC... | python | def export_records(self, records=None, fields=None, forms=None,
events=None, raw_or_label='raw', event_name='label',
format='json', export_survey_fields=False,
export_data_access_groups=False, df_kwargs=None,
export_checkbox_labels=False, filter_logic=None):
ret_format = format
if format... | [
"def",
"export_records",
"(",
"self",
",",
"records",
"=",
"None",
",",
"fields",
"=",
"None",
",",
"forms",
"=",
"None",
",",
"events",
"=",
"None",
",",
"raw_or_label",
"=",
"'raw'",
",",
"event_name",
"=",
"'label'",
",",
"format",
"=",
"'json'",
",... | Export data from the REDCap project.
Parameters
----------
records : list
array of record names specifying specific records to export.
by default, all records are exported
fields : list
array of field names specifying specific fields to pull
... | [
"Export",
"data",
"from",
"the",
"REDCap",
"project",
"."
] | f44c9b62a4f62675aa609c06608663f37e12097e | https://github.com/redcap-tools/PyCap/blob/f44c9b62a4f62675aa609c06608663f37e12097e/redcap/project.py#L238-L335 |
1,717 | redcap-tools/PyCap | redcap/project.py | Project.__meta_metadata | def __meta_metadata(self, field, key):
"""Return the value for key for the field in the metadata"""
mf = ''
try:
mf = str([f[key] for f in self.metadata
if f['field_name'] == field][0])
except IndexError:
print("%s not in metadata field:%s" % ... | python | def __meta_metadata(self, field, key):
mf = ''
try:
mf = str([f[key] for f in self.metadata
if f['field_name'] == field][0])
except IndexError:
print("%s not in metadata field:%s" % (key, field))
return mf
else:
return ... | [
"def",
"__meta_metadata",
"(",
"self",
",",
"field",
",",
"key",
")",
":",
"mf",
"=",
"''",
"try",
":",
"mf",
"=",
"str",
"(",
"[",
"f",
"[",
"key",
"]",
"for",
"f",
"in",
"self",
".",
"metadata",
"if",
"f",
"[",
"'field_name'",
"]",
"==",
"fie... | Return the value for key for the field in the metadata | [
"Return",
"the",
"value",
"for",
"key",
"for",
"the",
"field",
"in",
"the",
"metadata"
] | f44c9b62a4f62675aa609c06608663f37e12097e | https://github.com/redcap-tools/PyCap/blob/f44c9b62a4f62675aa609c06608663f37e12097e/redcap/project.py#L342-L352 |
1,718 | redcap-tools/PyCap | redcap/project.py | Project.filter | def filter(self, query, output_fields=None):
"""Query the database and return subject information for those
who match the query logic
Parameters
----------
query: Query or QueryGroup
Query(Group) object to process
output_fields: list
The fields de... | python | def filter(self, query, output_fields=None):
query_keys = query.fields()
if not set(query_keys).issubset(set(self.field_names)):
raise ValueError("One or more query keys not in project keys")
query_keys.append(self.def_field)
data = self.export_records(fields=query_keys)
... | [
"def",
"filter",
"(",
"self",
",",
"query",
",",
"output_fields",
"=",
"None",
")",
":",
"query_keys",
"=",
"query",
".",
"fields",
"(",
")",
"if",
"not",
"set",
"(",
"query_keys",
")",
".",
"issubset",
"(",
"set",
"(",
"self",
".",
"field_names",
")... | Query the database and return subject information for those
who match the query logic
Parameters
----------
query: Query or QueryGroup
Query(Group) object to process
output_fields: list
The fields desired for matching subjects
Returns
---... | [
"Query",
"the",
"database",
"and",
"return",
"subject",
"information",
"for",
"those",
"who",
"match",
"the",
"query",
"logic"
] | f44c9b62a4f62675aa609c06608663f37e12097e | https://github.com/redcap-tools/PyCap/blob/f44c9b62a4f62675aa609c06608663f37e12097e/redcap/project.py#L384-L420 |
1,719 | redcap-tools/PyCap | redcap/project.py | Project.names_labels | def names_labels(self, do_print=False):
"""Simple helper function to get all field names and labels """
if do_print:
for name, label in zip(self.field_names, self.field_labels):
print('%s --> %s' % (str(name), str(label)))
return self.field_names, self.field_labels | python | def names_labels(self, do_print=False):
if do_print:
for name, label in zip(self.field_names, self.field_labels):
print('%s --> %s' % (str(name), str(label)))
return self.field_names, self.field_labels | [
"def",
"names_labels",
"(",
"self",
",",
"do_print",
"=",
"False",
")",
":",
"if",
"do_print",
":",
"for",
"name",
",",
"label",
"in",
"zip",
"(",
"self",
".",
"field_names",
",",
"self",
".",
"field_labels",
")",
":",
"print",
"(",
"'%s --> %s'",
"%",... | Simple helper function to get all field names and labels | [
"Simple",
"helper",
"function",
"to",
"get",
"all",
"field",
"names",
"and",
"labels"
] | f44c9b62a4f62675aa609c06608663f37e12097e | https://github.com/redcap-tools/PyCap/blob/f44c9b62a4f62675aa609c06608663f37e12097e/redcap/project.py#L422-L427 |
1,720 | redcap-tools/PyCap | redcap/project.py | Project.import_records | def import_records(self, to_import, overwrite='normal', format='json',
return_format='json', return_content='count',
date_format='YMD', force_auto_number=False):
"""
Import data into the RedCap Project
Parameters
----------
to_import : array of dicts, csv/xml str... | python | def import_records(self, to_import, overwrite='normal', format='json',
return_format='json', return_content='count',
date_format='YMD', force_auto_number=False):
pl = self.__basepl('record')
if hasattr(to_import, 'to_csv'):
# We'll assume it's a df
buf = StringIO(... | [
"def",
"import_records",
"(",
"self",
",",
"to_import",
",",
"overwrite",
"=",
"'normal'",
",",
"format",
"=",
"'json'",
",",
"return_format",
"=",
"'json'",
",",
"return_content",
"=",
"'count'",
",",
"date_format",
"=",
"'YMD'",
",",
"force_auto_number",
"="... | Import data into the RedCap Project
Parameters
----------
to_import : array of dicts, csv/xml string, ``pandas.DataFrame``
:note:
If you pass a csv or xml string, you should use the
``format`` parameter appropriately.
:note:
... | [
"Import",
"data",
"into",
"the",
"RedCap",
"Project"
] | f44c9b62a4f62675aa609c06608663f37e12097e | https://github.com/redcap-tools/PyCap/blob/f44c9b62a4f62675aa609c06608663f37e12097e/redcap/project.py#L429-L501 |
1,721 | redcap-tools/PyCap | redcap/project.py | Project.export_file | def export_file(self, record, field, event=None, return_format='json'):
"""
Export the contents of a file stored for a particular record
Notes
-----
Unlike other export methods, this works on a single record.
Parameters
----------
record : str
... | python | def export_file(self, record, field, event=None, return_format='json'):
self._check_file_field(field)
# load up payload
pl = self.__basepl(content='file', format=return_format)
# there's no format field in this call
del pl['format']
pl['returnFormat'] = return_format
... | [
"def",
"export_file",
"(",
"self",
",",
"record",
",",
"field",
",",
"event",
"=",
"None",
",",
"return_format",
"=",
"'json'",
")",
":",
"self",
".",
"_check_file_field",
"(",
"field",
")",
"# load up payload",
"pl",
"=",
"self",
".",
"__basepl",
"(",
"... | Export the contents of a file stored for a particular record
Notes
-----
Unlike other export methods, this works on a single record.
Parameters
----------
record : str
record ID
field : str
field name containing the file to be exported.
... | [
"Export",
"the",
"contents",
"of",
"a",
"file",
"stored",
"for",
"a",
"particular",
"record"
] | f44c9b62a4f62675aa609c06608663f37e12097e | https://github.com/redcap-tools/PyCap/blob/f44c9b62a4f62675aa609c06608663f37e12097e/redcap/project.py#L503-L549 |
1,722 | redcap-tools/PyCap | redcap/project.py | Project.import_file | def import_file(self, record, field, fname, fobj, event=None,
return_format='json'):
"""
Import the contents of a file represented by fobj to a
particular records field
Parameters
----------
record : str
record ID
field : str
f... | python | def import_file(self, record, field, fname, fobj, event=None,
return_format='json'):
self._check_file_field(field)
# load up payload
pl = self.__basepl(content='file', format=return_format)
# no format in this call
del pl['format']
pl['returnFormat'] = return_... | [
"def",
"import_file",
"(",
"self",
",",
"record",
",",
"field",
",",
"fname",
",",
"fobj",
",",
"event",
"=",
"None",
",",
"return_format",
"=",
"'json'",
")",
":",
"self",
".",
"_check_file_field",
"(",
"field",
")",
"# load up payload",
"pl",
"=",
"sel... | Import the contents of a file represented by fobj to a
particular records field
Parameters
----------
record : str
record ID
field : str
field name where the file will go
fname : str
file name visible in REDCap UI
fobj : file o... | [
"Import",
"the",
"contents",
"of",
"a",
"file",
"represented",
"by",
"fobj",
"to",
"a",
"particular",
"records",
"field"
] | f44c9b62a4f62675aa609c06608663f37e12097e | https://github.com/redcap-tools/PyCap/blob/f44c9b62a4f62675aa609c06608663f37e12097e/redcap/project.py#L551-L589 |
1,723 | redcap-tools/PyCap | redcap/project.py | Project.delete_file | def delete_file(self, record, field, return_format='json', event=None):
"""
Delete a file from REDCap
Notes
-----
There is no undo button to this.
Parameters
----------
record : str
record ID
field : str
field name
... | python | def delete_file(self, record, field, return_format='json', event=None):
self._check_file_field(field)
# Load up payload
pl = self.__basepl(content='file', format=return_format)
del pl['format']
pl['returnFormat'] = return_format
pl['action'] = 'delete'
pl['record'... | [
"def",
"delete_file",
"(",
"self",
",",
"record",
",",
"field",
",",
"return_format",
"=",
"'json'",
",",
"event",
"=",
"None",
")",
":",
"self",
".",
"_check_file_field",
"(",
"field",
")",
"# Load up payload",
"pl",
"=",
"self",
".",
"__basepl",
"(",
"... | Delete a file from REDCap
Notes
-----
There is no undo button to this.
Parameters
----------
record : str
record ID
field : str
field name
return_format : (``'json'``), ``'csv'``, ``'xml'``
return format for error mess... | [
"Delete",
"a",
"file",
"from",
"REDCap"
] | f44c9b62a4f62675aa609c06608663f37e12097e | https://github.com/redcap-tools/PyCap/blob/f44c9b62a4f62675aa609c06608663f37e12097e/redcap/project.py#L591-L625 |
1,724 | redcap-tools/PyCap | redcap/project.py | Project._check_file_field | def _check_file_field(self, field):
"""Check that field exists and is a file field"""
is_field = field in self.field_names
is_file = self.__meta_metadata(field, 'field_type') == 'file'
if not (is_field and is_file):
msg = "'%s' is not a field or not a 'file' field" % field
... | python | def _check_file_field(self, field):
is_field = field in self.field_names
is_file = self.__meta_metadata(field, 'field_type') == 'file'
if not (is_field and is_file):
msg = "'%s' is not a field or not a 'file' field" % field
raise ValueError(msg)
else:
... | [
"def",
"_check_file_field",
"(",
"self",
",",
"field",
")",
":",
"is_field",
"=",
"field",
"in",
"self",
".",
"field_names",
"is_file",
"=",
"self",
".",
"__meta_metadata",
"(",
"field",
",",
"'field_type'",
")",
"==",
"'file'",
"if",
"not",
"(",
"is_field... | Check that field exists and is a file field | [
"Check",
"that",
"field",
"exists",
"and",
"is",
"a",
"file",
"field"
] | f44c9b62a4f62675aa609c06608663f37e12097e | https://github.com/redcap-tools/PyCap/blob/f44c9b62a4f62675aa609c06608663f37e12097e/redcap/project.py#L627-L635 |
1,725 | redcap-tools/PyCap | redcap/project.py | Project.export_users | def export_users(self, format='json'):
"""
Export the users of the Project
Notes
-----
Each user will have the following keys:
* ``'firstname'`` : User's first name
* ``'lastname'`` : User's last name
* ``'email'`` : Email address
... | python | def export_users(self, format='json'):
pl = self.__basepl(content='user', format=format)
return self._call_api(pl, 'exp_user')[0] | [
"def",
"export_users",
"(",
"self",
",",
"format",
"=",
"'json'",
")",
":",
"pl",
"=",
"self",
".",
"__basepl",
"(",
"content",
"=",
"'user'",
",",
"format",
"=",
"format",
")",
"return",
"self",
".",
"_call_api",
"(",
"pl",
",",
"'exp_user'",
")",
"... | Export the users of the Project
Notes
-----
Each user will have the following keys:
* ``'firstname'`` : User's first name
* ``'lastname'`` : User's last name
* ``'email'`` : Email address
* ``'username'`` : User's username
* ``'expira... | [
"Export",
"the",
"users",
"of",
"the",
"Project"
] | f44c9b62a4f62675aa609c06608663f37e12097e | https://github.com/redcap-tools/PyCap/blob/f44c9b62a4f62675aa609c06608663f37e12097e/redcap/project.py#L637-L671 |
1,726 | redcap-tools/PyCap | redcap/project.py | Project.export_survey_participant_list | def export_survey_participant_list(self, instrument, event=None, format='json'):
"""
Export the Survey Participant List
Notes
-----
The passed instrument must be set up as a survey instrument.
Parameters
----------
instrument: str
Name of ins... | python | def export_survey_participant_list(self, instrument, event=None, format='json'):
pl = self.__basepl(content='participantList', format=format)
pl['instrument'] = instrument
if event:
pl['event'] = event
return self._call_api(pl, 'exp_survey_participant_list') | [
"def",
"export_survey_participant_list",
"(",
"self",
",",
"instrument",
",",
"event",
"=",
"None",
",",
"format",
"=",
"'json'",
")",
":",
"pl",
"=",
"self",
".",
"__basepl",
"(",
"content",
"=",
"'participantList'",
",",
"format",
"=",
"format",
")",
"pl... | Export the Survey Participant List
Notes
-----
The passed instrument must be set up as a survey instrument.
Parameters
----------
instrument: str
Name of instrument as seen in second column of Data Dictionary.
event: str
Unique event name... | [
"Export",
"the",
"Survey",
"Participant",
"List"
] | f44c9b62a4f62675aa609c06608663f37e12097e | https://github.com/redcap-tools/PyCap/blob/f44c9b62a4f62675aa609c06608663f37e12097e/redcap/project.py#L673-L694 |
1,727 | quentinsf/qhue | qhue/qhue.py | create_new_username | def create_new_username(ip, devicetype=None, timeout=_DEFAULT_TIMEOUT):
"""Interactive helper function to generate a new anonymous username.
Args:
ip: ip address of the bridge
devicetype (optional): devicetype to register with the bridge. If
unprovided, generates a device type based... | python | def create_new_username(ip, devicetype=None, timeout=_DEFAULT_TIMEOUT):
res = Resource(_api_url(ip), timeout)
prompt = "Press the Bridge button, then press Return: "
# Deal with one of the sillier python3 changes
if sys.version_info.major == 2:
_ = raw_input(prompt)
else:
_ = input(p... | [
"def",
"create_new_username",
"(",
"ip",
",",
"devicetype",
"=",
"None",
",",
"timeout",
"=",
"_DEFAULT_TIMEOUT",
")",
":",
"res",
"=",
"Resource",
"(",
"_api_url",
"(",
"ip",
")",
",",
"timeout",
")",
"prompt",
"=",
"\"Press the Bridge button, then press Return... | Interactive helper function to generate a new anonymous username.
Args:
ip: ip address of the bridge
devicetype (optional): devicetype to register with the bridge. If
unprovided, generates a device type based on the local hostname.
timeout (optional, default=5): request timeout ... | [
"Interactive",
"helper",
"function",
"to",
"generate",
"a",
"new",
"anonymous",
"username",
"."
] | faddc49de844134784f4742f4783066976d76c08 | https://github.com/quentinsf/qhue/blob/faddc49de844134784f4742f4783066976d76c08/qhue/qhue.py#L73-L99 |
1,728 | spotify/gordon | gordon/router.py | GordonRouter.run | async def run(self):
"""Entrypoint to route messages between plugins."""
logging.info('Starting message router...')
coroutines = set()
while True:
coro = self._poll_channel()
coroutines.add(coro)
_, coroutines = await asyncio.wait(coroutines, timeout=... | python | async def run(self):
logging.info('Starting message router...')
coroutines = set()
while True:
coro = self._poll_channel()
coroutines.add(coro)
_, coroutines = await asyncio.wait(coroutines, timeout=0.1) | [
"async",
"def",
"run",
"(",
"self",
")",
":",
"logging",
".",
"info",
"(",
"'Starting message router...'",
")",
"coroutines",
"=",
"set",
"(",
")",
"while",
"True",
":",
"coro",
"=",
"self",
".",
"_poll_channel",
"(",
")",
"coroutines",
".",
"add",
"(",
... | Entrypoint to route messages between plugins. | [
"Entrypoint",
"to",
"route",
"messages",
"between",
"plugins",
"."
] | 8dbf54a032cfaa8f003264682456236b6a69c039 | https://github.com/spotify/gordon/blob/8dbf54a032cfaa8f003264682456236b6a69c039/gordon/router.py#L193-L201 |
1,729 | spotify/gordon | gordon/main.py | shutdown | async def shutdown(sig, loop):
"""Gracefully cancel current tasks when app receives a shutdown signal."""
logging.info(f'Received exit signal {sig.name}...')
tasks = [task for task in asyncio.Task.all_tasks() if task is not
asyncio.tasks.Task.current_task()]
for task in tasks:
logg... | python | async def shutdown(sig, loop):
logging.info(f'Received exit signal {sig.name}...')
tasks = [task for task in asyncio.Task.all_tasks() if task is not
asyncio.tasks.Task.current_task()]
for task in tasks:
logging.debug(f'Cancelling task: {task}')
task.cancel()
results = awai... | [
"async",
"def",
"shutdown",
"(",
"sig",
",",
"loop",
")",
":",
"logging",
".",
"info",
"(",
"f'Received exit signal {sig.name}...'",
")",
"tasks",
"=",
"[",
"task",
"for",
"task",
"in",
"asyncio",
".",
"Task",
".",
"all_tasks",
"(",
")",
"if",
"task",
"i... | Gracefully cancel current tasks when app receives a shutdown signal. | [
"Gracefully",
"cancel",
"current",
"tasks",
"when",
"app",
"receives",
"a",
"shutdown",
"signal",
"."
] | 8dbf54a032cfaa8f003264682456236b6a69c039 | https://github.com/spotify/gordon/blob/8dbf54a032cfaa8f003264682456236b6a69c039/gordon/main.py#L51-L65 |
1,730 | spotify/gordon | gordon/main.py | _deep_merge_dict | def _deep_merge_dict(a, b):
"""Additively merge right side dict into left side dict."""
for k, v in b.items():
if k in a and isinstance(a[k], dict) and isinstance(v, dict):
_deep_merge_dict(a[k], v)
else:
a[k] = v | python | def _deep_merge_dict(a, b):
for k, v in b.items():
if k in a and isinstance(a[k], dict) and isinstance(v, dict):
_deep_merge_dict(a[k], v)
else:
a[k] = v | [
"def",
"_deep_merge_dict",
"(",
"a",
",",
"b",
")",
":",
"for",
"k",
",",
"v",
"in",
"b",
".",
"items",
"(",
")",
":",
"if",
"k",
"in",
"a",
"and",
"isinstance",
"(",
"a",
"[",
"k",
"]",
",",
"dict",
")",
"and",
"isinstance",
"(",
"v",
",",
... | Additively merge right side dict into left side dict. | [
"Additively",
"merge",
"right",
"side",
"dict",
"into",
"left",
"side",
"dict",
"."
] | 8dbf54a032cfaa8f003264682456236b6a69c039 | https://github.com/spotify/gordon/blob/8dbf54a032cfaa8f003264682456236b6a69c039/gordon/main.py#L68-L74 |
1,731 | spotify/gordon | gordon/plugins_loader.py | load_plugins | def load_plugins(config, plugin_kwargs):
"""
Discover and instantiate plugins.
Args:
config (dict): loaded configuration for the Gordon service.
plugin_kwargs (dict): keyword arguments to give to plugins
during instantiation.
Returns:
Tuple of 3 lists: list of names ... | python | def load_plugins(config, plugin_kwargs):
installed_plugins = _gather_installed_plugins()
metrics_plugin = _get_metrics_plugin(config, installed_plugins)
if metrics_plugin:
plugin_kwargs['metrics'] = metrics_plugin
active_plugins = _get_activated_plugins(config, installed_plugins)
if not act... | [
"def",
"load_plugins",
"(",
"config",
",",
"plugin_kwargs",
")",
":",
"installed_plugins",
"=",
"_gather_installed_plugins",
"(",
")",
"metrics_plugin",
"=",
"_get_metrics_plugin",
"(",
"config",
",",
"installed_plugins",
")",
"if",
"metrics_plugin",
":",
"plugin_kwar... | Discover and instantiate plugins.
Args:
config (dict): loaded configuration for the Gordon service.
plugin_kwargs (dict): keyword arguments to give to plugins
during instantiation.
Returns:
Tuple of 3 lists: list of names of plugins, list of
instantiated plugin objec... | [
"Discover",
"and",
"instantiate",
"plugins",
"."
] | 8dbf54a032cfaa8f003264682456236b6a69c039 | https://github.com/spotify/gordon/blob/8dbf54a032cfaa8f003264682456236b6a69c039/gordon/plugins_loader.py#L210-L237 |
1,732 | spotify/gordon | gordon/metrics/ffwd.py | UDPClientProtocol.connection_made | def connection_made(self, transport):
"""Create connection, use to send message and close.
Args:
transport (asyncio.DatagramTransport): Transport used for sending.
"""
self.transport = transport
self.transport.sendto(self.message)
self.transport.close() | python | def connection_made(self, transport):
self.transport = transport
self.transport.sendto(self.message)
self.transport.close() | [
"def",
"connection_made",
"(",
"self",
",",
"transport",
")",
":",
"self",
".",
"transport",
"=",
"transport",
"self",
".",
"transport",
".",
"sendto",
"(",
"self",
".",
"message",
")",
"self",
".",
"transport",
".",
"close",
"(",
")"
] | Create connection, use to send message and close.
Args:
transport (asyncio.DatagramTransport): Transport used for sending. | [
"Create",
"connection",
"use",
"to",
"send",
"message",
"and",
"close",
"."
] | 8dbf54a032cfaa8f003264682456236b6a69c039 | https://github.com/spotify/gordon/blob/8dbf54a032cfaa8f003264682456236b6a69c039/gordon/metrics/ffwd.py#L59-L67 |
1,733 | spotify/gordon | gordon/metrics/ffwd.py | UDPClient.send | async def send(self, metric):
"""Transform metric to JSON bytestring and send to server.
Args:
metric (dict): Complete metric to send as JSON.
"""
message = json.dumps(metric).encode('utf-8')
await self.loop.create_datagram_endpoint(
lambda: UDPClientProt... | python | async def send(self, metric):
message = json.dumps(metric).encode('utf-8')
await self.loop.create_datagram_endpoint(
lambda: UDPClientProtocol(message),
remote_addr=(self.ip, self.port)) | [
"async",
"def",
"send",
"(",
"self",
",",
"metric",
")",
":",
"message",
"=",
"json",
".",
"dumps",
"(",
"metric",
")",
".",
"encode",
"(",
"'utf-8'",
")",
"await",
"self",
".",
"loop",
".",
"create_datagram_endpoint",
"(",
"lambda",
":",
"UDPClientProto... | Transform metric to JSON bytestring and send to server.
Args:
metric (dict): Complete metric to send as JSON. | [
"Transform",
"metric",
"to",
"JSON",
"bytestring",
"and",
"send",
"to",
"server",
"."
] | 8dbf54a032cfaa8f003264682456236b6a69c039 | https://github.com/spotify/gordon/blob/8dbf54a032cfaa8f003264682456236b6a69c039/gordon/metrics/ffwd.py#L87-L96 |
1,734 | spotify/gordon | gordon/record_checker.py | RecordChecker.check_record | async def check_record(self, record, timeout=60):
"""Measures the time for a DNS record to become available.
Query a provided DNS server multiple times until the reply matches the
information in the record or until timeout is reached.
Args:
record (dict): DNS record as a di... | python | async def check_record(self, record, timeout=60):
start_time = time.time()
name, rr_data, r_type, ttl = self._extract_record_data(record)
r_type_code = async_dns.types.get_code(r_type)
resolvable_record = False
retries = 0
sleep_time = 5
while not resolvable_re... | [
"async",
"def",
"check_record",
"(",
"self",
",",
"record",
",",
"timeout",
"=",
"60",
")",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"name",
",",
"rr_data",
",",
"r_type",
",",
"ttl",
"=",
"self",
".",
"_extract_record_data",
"(",
"record... | Measures the time for a DNS record to become available.
Query a provided DNS server multiple times until the reply matches the
information in the record or until timeout is reached.
Args:
record (dict): DNS record as a dict with record properties.
timeout (int): Time th... | [
"Measures",
"the",
"time",
"for",
"a",
"DNS",
"record",
"to",
"become",
"available",
"."
] | 8dbf54a032cfaa8f003264682456236b6a69c039 | https://github.com/spotify/gordon/blob/8dbf54a032cfaa8f003264682456236b6a69c039/gordon/record_checker.py#L54-L94 |
1,735 | spotify/gordon | gordon/record_checker.py | RecordChecker._check_resolver_ans | async def _check_resolver_ans(
self, dns_answer_list, record_name,
record_data_list, record_ttl, record_type_code):
"""Check if resolver answer is equal to record data.
Args:
dns_answer_list (list): DNS answer list contains record objects.
record_name (st... | python | async def _check_resolver_ans(
self, dns_answer_list, record_name,
record_data_list, record_ttl, record_type_code):
type_filtered_list = [
ans for ans in dns_answer_list if ans.qtype == record_type_code
]
# check to see that type_filtered_lst has
# th... | [
"async",
"def",
"_check_resolver_ans",
"(",
"self",
",",
"dns_answer_list",
",",
"record_name",
",",
"record_data_list",
",",
"record_ttl",
",",
"record_type_code",
")",
":",
"type_filtered_list",
"=",
"[",
"ans",
"for",
"ans",
"in",
"dns_answer_list",
"if",
"ans"... | Check if resolver answer is equal to record data.
Args:
dns_answer_list (list): DNS answer list contains record objects.
record_name (str): Record name.
record_data_list (list): List of data values for the record.
record_ttl (int): Record time-to-live info.
... | [
"Check",
"if",
"resolver",
"answer",
"is",
"equal",
"to",
"record",
"data",
"."
] | 8dbf54a032cfaa8f003264682456236b6a69c039 | https://github.com/spotify/gordon/blob/8dbf54a032cfaa8f003264682456236b6a69c039/gordon/record_checker.py#L96-L131 |
1,736 | spotify/gordon | gordon/metrics/log.py | LoggerAdapter.log | def log(self, metric):
"""Format and output metric.
Args:
metric (dict): Complete metric.
"""
message = self.LOGFMT.format(**metric)
if metric['context']:
message += ' context: {context}'.format(context=metric['context'])
self._logger.log(self.lev... | python | def log(self, metric):
message = self.LOGFMT.format(**metric)
if metric['context']:
message += ' context: {context}'.format(context=metric['context'])
self._logger.log(self.level, message) | [
"def",
"log",
"(",
"self",
",",
"metric",
")",
":",
"message",
"=",
"self",
".",
"LOGFMT",
".",
"format",
"(",
"*",
"*",
"metric",
")",
"if",
"metric",
"[",
"'context'",
"]",
":",
"message",
"+=",
"' context: {context}'",
".",
"format",
"(",
"context",... | Format and output metric.
Args:
metric (dict): Complete metric. | [
"Format",
"and",
"output",
"metric",
"."
] | 8dbf54a032cfaa8f003264682456236b6a69c039 | https://github.com/spotify/gordon/blob/8dbf54a032cfaa8f003264682456236b6a69c039/gordon/metrics/log.py#L89-L98 |
1,737 | jameslyons/pycipher | pycipher/atbash.py | Atbash.encipher | def encipher(self,string,keep_punct=False):
"""Encipher string using Atbash cipher.
Example::
ciphertext = Atbash().encipher(plaintext)
:param string: The string to encipher.
:param keep_punct: if true, punctuation and spacing are retained. If false, it is all removed... | python | def encipher(self,string,keep_punct=False):
if not keep_punct: string = self.remove_punctuation(string)
ret = ''
for c in string.upper():
if c.isalpha(): ret += self.key[self.a2i(c)]
else: ret += c
return ret | [
"def",
"encipher",
"(",
"self",
",",
"string",
",",
"keep_punct",
"=",
"False",
")",
":",
"if",
"not",
"keep_punct",
":",
"string",
"=",
"self",
".",
"remove_punctuation",
"(",
"string",
")",
"ret",
"=",
"''",
"for",
"c",
"in",
"string",
".",
"upper",
... | Encipher string using Atbash cipher.
Example::
ciphertext = Atbash().encipher(plaintext)
:param string: The string to encipher.
:param keep_punct: if true, punctuation and spacing are retained. If false, it is all removed. Default is False.
:returns: The enciphered s... | [
"Encipher",
"string",
"using",
"Atbash",
"cipher",
"."
] | 8f1d7cf3cba4e12171e27d9ce723ad890194de19 | https://github.com/jameslyons/pycipher/blob/8f1d7cf3cba4e12171e27d9ce723ad890194de19/pycipher/atbash.py#L16-L32 |
1,738 | jameslyons/pycipher | pycipher/polybius.py | PolybiusSquare.encipher | def encipher(self,string):
"""Encipher string using Polybius square cipher according to initialised key.
Example::
ciphertext = Polybius('APCZWRLFBDKOTYUQGENHXMIVS',5,'MKSBU').encipher(plaintext)
:param string: The string to encipher.
:returns: The enciphered string. ... | python | def encipher(self,string):
string = self.remove_punctuation(string)#,filter='[^'+self.key+']')
ret = ''
for c in range(0,len(string)):
ret += self.encipher_char(string[c])
return ret | [
"def",
"encipher",
"(",
"self",
",",
"string",
")",
":",
"string",
"=",
"self",
".",
"remove_punctuation",
"(",
"string",
")",
"#,filter='[^'+self.key+']')",
"ret",
"=",
"''",
"for",
"c",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"string",
")",
")",
":... | Encipher string using Polybius square cipher according to initialised key.
Example::
ciphertext = Polybius('APCZWRLFBDKOTYUQGENHXMIVS',5,'MKSBU').encipher(plaintext)
:param string: The string to encipher.
:returns: The enciphered string. The ciphertext will be twice the lengt... | [
"Encipher",
"string",
"using",
"Polybius",
"square",
"cipher",
"according",
"to",
"initialised",
"key",
"."
] | 8f1d7cf3cba4e12171e27d9ce723ad890194de19 | https://github.com/jameslyons/pycipher/blob/8f1d7cf3cba4e12171e27d9ce723ad890194de19/pycipher/polybius.py#L36-L50 |
1,739 | jameslyons/pycipher | pycipher/polybius.py | PolybiusSquare.decipher | def decipher(self,string):
"""Decipher string using Polybius square cipher according to initialised key.
Example::
plaintext = Polybius('APCZWRLFBDKOTYUQGENHXMIVS',5,'MKSBU').decipher(ciphertext)
:param string: The string to decipher.
:returns: The deciphered string. ... | python | def decipher(self,string):
string = self.remove_punctuation(string)#,filter='[^'+self.chars+']')
ret = ''
for i in range(0,len(string),2):
ret += self.decipher_pair(string[i:i+2])
return ret | [
"def",
"decipher",
"(",
"self",
",",
"string",
")",
":",
"string",
"=",
"self",
".",
"remove_punctuation",
"(",
"string",
")",
"#,filter='[^'+self.chars+']')",
"ret",
"=",
"''",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"string",
")",
",",
... | Decipher string using Polybius square cipher according to initialised key.
Example::
plaintext = Polybius('APCZWRLFBDKOTYUQGENHXMIVS',5,'MKSBU').decipher(ciphertext)
:param string: The string to decipher.
:returns: The deciphered string. The plaintext will be half the length ... | [
"Decipher",
"string",
"using",
"Polybius",
"square",
"cipher",
"according",
"to",
"initialised",
"key",
"."
] | 8f1d7cf3cba4e12171e27d9ce723ad890194de19 | https://github.com/jameslyons/pycipher/blob/8f1d7cf3cba4e12171e27d9ce723ad890194de19/pycipher/polybius.py#L52-L66 |
1,740 | jameslyons/pycipher | pycipher/adfgvx.py | ADFGVX.decipher | def decipher(self,string):
"""Decipher string using ADFGVX cipher according to initialised key information. Punctuation and whitespace
are removed from the input.
Example::
plaintext = ADFGVX('ph0qg64mea1yl2nofdxkr3cvs5zw7bj9uti8','HELLO').decipher(ciphertext)
... | python | def decipher(self,string):
step2 = ColTrans(self.keyword).decipher(string)
step1 = PolybiusSquare(self.key,size=6,chars='ADFGVX').decipher(step2)
return step1 | [
"def",
"decipher",
"(",
"self",
",",
"string",
")",
":",
"step2",
"=",
"ColTrans",
"(",
"self",
".",
"keyword",
")",
".",
"decipher",
"(",
"string",
")",
"step1",
"=",
"PolybiusSquare",
"(",
"self",
".",
"key",
",",
"size",
"=",
"6",
",",
"chars",
... | Decipher string using ADFGVX cipher according to initialised key information. Punctuation and whitespace
are removed from the input.
Example::
plaintext = ADFGVX('ph0qg64mea1yl2nofdxkr3cvs5zw7bj9uti8','HELLO').decipher(ciphertext)
:param string: The string to decipher.... | [
"Decipher",
"string",
"using",
"ADFGVX",
"cipher",
"according",
"to",
"initialised",
"key",
"information",
".",
"Punctuation",
"and",
"whitespace",
"are",
"removed",
"from",
"the",
"input",
"."
] | 8f1d7cf3cba4e12171e27d9ce723ad890194de19 | https://github.com/jameslyons/pycipher/blob/8f1d7cf3cba4e12171e27d9ce723ad890194de19/pycipher/adfgvx.py#L40-L53 |
1,741 | jameslyons/pycipher | pycipher/enigma.py | Enigma.encipher | def encipher(self,string):
"""Encipher string using Enigma M3 cipher according to initialised key. Punctuation and whitespace
are removed from the input.
Example::
ciphertext = Enigma(settings=('A','A','A'),rotors=(1,2,3),reflector='B',
ringstellung=('F','V'... | python | def encipher(self,string):
string = self.remove_punctuation(string)
ret = ''
for c in string.upper():
if c.isalpha(): ret += self.encipher_char(c)
else: ret += c
return ret | [
"def",
"encipher",
"(",
"self",
",",
"string",
")",
":",
"string",
"=",
"self",
".",
"remove_punctuation",
"(",
"string",
")",
"ret",
"=",
"''",
"for",
"c",
"in",
"string",
".",
"upper",
"(",
")",
":",
"if",
"c",
".",
"isalpha",
"(",
")",
":",
"r... | Encipher string using Enigma M3 cipher according to initialised key. Punctuation and whitespace
are removed from the input.
Example::
ciphertext = Enigma(settings=('A','A','A'),rotors=(1,2,3),reflector='B',
ringstellung=('F','V','N'),steckers=[('P','O'),('M','L'),
... | [
"Encipher",
"string",
"using",
"Enigma",
"M3",
"cipher",
"according",
"to",
"initialised",
"key",
".",
"Punctuation",
"and",
"whitespace",
"are",
"removed",
"from",
"the",
"input",
"."
] | 8f1d7cf3cba4e12171e27d9ce723ad890194de19 | https://github.com/jameslyons/pycipher/blob/8f1d7cf3cba4e12171e27d9ce723ad890194de19/pycipher/enigma.py#L128-L147 |
1,742 | jameslyons/pycipher | pycipher/util.py | ic | def ic(ctext):
''' takes ciphertext, calculates index of coincidence.'''
counts = ngram_count(ctext,N=1)
icval = 0
for k in counts.keys():
icval += counts[k]*(counts[k]-1)
icval /= (len(ctext)*(len(ctext)-1))
return icval | python | def ic(ctext):
''' takes ciphertext, calculates index of coincidence.'''
counts = ngram_count(ctext,N=1)
icval = 0
for k in counts.keys():
icval += counts[k]*(counts[k]-1)
icval /= (len(ctext)*(len(ctext)-1))
return icval | [
"def",
"ic",
"(",
"ctext",
")",
":",
"counts",
"=",
"ngram_count",
"(",
"ctext",
",",
"N",
"=",
"1",
")",
"icval",
"=",
"0",
"for",
"k",
"in",
"counts",
".",
"keys",
"(",
")",
":",
"icval",
"+=",
"counts",
"[",
"k",
"]",
"*",
"(",
"counts",
"... | takes ciphertext, calculates index of coincidence. | [
"takes",
"ciphertext",
"calculates",
"index",
"of",
"coincidence",
"."
] | 8f1d7cf3cba4e12171e27d9ce723ad890194de19 | https://github.com/jameslyons/pycipher/blob/8f1d7cf3cba4e12171e27d9ce723ad890194de19/pycipher/util.py#L7-L14 |
1,743 | jameslyons/pycipher | pycipher/util.py | restore_punctuation | def restore_punctuation(original,modified):
''' If punctuation was accidently removed, use this function to restore it.
requires the orignial string with punctuation. '''
ret = ''
count = 0
try:
for c in original:
if c.isalpha():
ret+=modified[count]
... | python | def restore_punctuation(original,modified):
''' If punctuation was accidently removed, use this function to restore it.
requires the orignial string with punctuation. '''
ret = ''
count = 0
try:
for c in original:
if c.isalpha():
ret+=modified[count]
... | [
"def",
"restore_punctuation",
"(",
"original",
",",
"modified",
")",
":",
"ret",
"=",
"''",
"count",
"=",
"0",
"try",
":",
"for",
"c",
"in",
"original",
":",
"if",
"c",
".",
"isalpha",
"(",
")",
":",
"ret",
"+=",
"modified",
"[",
"count",
"]",
"cou... | If punctuation was accidently removed, use this function to restore it.
requires the orignial string with punctuation. | [
"If",
"punctuation",
"was",
"accidently",
"removed",
"use",
"this",
"function",
"to",
"restore",
"it",
".",
"requires",
"the",
"orignial",
"string",
"with",
"punctuation",
"."
] | 8f1d7cf3cba4e12171e27d9ce723ad890194de19 | https://github.com/jameslyons/pycipher/blob/8f1d7cf3cba4e12171e27d9ce723ad890194de19/pycipher/util.py#L44-L58 |
1,744 | jameslyons/pycipher | pycipher/playfair.py | Playfair.encipher | def encipher(self, string):
"""Encipher string using Playfair cipher according to initialised key. Punctuation and whitespace
are removed from the input. If the input plaintext is not an even number of characters, an 'X' will be appended.
Example::
ciphertext = Playfair(key='zgptfo... | python | def encipher(self, string):
string = self.remove_punctuation(string)
string = re.sub(r'[J]', 'I', string)
if len(string) % 2 == 1:
string += 'X'
ret = ''
for c in range(0, len(string), 2):
ret += self.encipher_pair(string[c], string[c + 1])
retur... | [
"def",
"encipher",
"(",
"self",
",",
"string",
")",
":",
"string",
"=",
"self",
".",
"remove_punctuation",
"(",
"string",
")",
"string",
"=",
"re",
".",
"sub",
"(",
"r'[J]'",
",",
"'I'",
",",
"string",
")",
"if",
"len",
"(",
"string",
")",
"%",
"2"... | Encipher string using Playfair cipher according to initialised key. Punctuation and whitespace
are removed from the input. If the input plaintext is not an even number of characters, an 'X' will be appended.
Example::
ciphertext = Playfair(key='zgptfoihmuwdrcnykeqaxvsbl').encipher(plaintex... | [
"Encipher",
"string",
"using",
"Playfair",
"cipher",
"according",
"to",
"initialised",
"key",
".",
"Punctuation",
"and",
"whitespace",
"are",
"removed",
"from",
"the",
"input",
".",
"If",
"the",
"input",
"plaintext",
"is",
"not",
"an",
"even",
"number",
"of",
... | 8f1d7cf3cba4e12171e27d9ce723ad890194de19 | https://github.com/jameslyons/pycipher/blob/8f1d7cf3cba4e12171e27d9ce723ad890194de19/pycipher/playfair.py#L44-L62 |
1,745 | jameslyons/pycipher | pycipher/playfair.py | Playfair.decipher | def decipher(self, string):
"""Decipher string using Playfair cipher according to initialised key. Punctuation and whitespace
are removed from the input. The ciphertext should be an even number of characters. If the input ciphertext is not an even number of characters, an 'X' will be appended.
... | python | def decipher(self, string):
string = self.remove_punctuation(string)
if len(string) % 2 == 1:
string += 'X'
ret = ''
for c in range(0, len(string), 2):
ret += self.decipher_pair(string[c], string[c + 1])
return ret | [
"def",
"decipher",
"(",
"self",
",",
"string",
")",
":",
"string",
"=",
"self",
".",
"remove_punctuation",
"(",
"string",
")",
"if",
"len",
"(",
"string",
")",
"%",
"2",
"==",
"1",
":",
"string",
"+=",
"'X'",
"ret",
"=",
"''",
"for",
"c",
"in",
"... | Decipher string using Playfair cipher according to initialised key. Punctuation and whitespace
are removed from the input. The ciphertext should be an even number of characters. If the input ciphertext is not an even number of characters, an 'X' will be appended.
Example::
plaintext = Play... | [
"Decipher",
"string",
"using",
"Playfair",
"cipher",
"according",
"to",
"initialised",
"key",
".",
"Punctuation",
"and",
"whitespace",
"are",
"removed",
"from",
"the",
"input",
".",
"The",
"ciphertext",
"should",
"be",
"an",
"even",
"number",
"of",
"characters",... | 8f1d7cf3cba4e12171e27d9ce723ad890194de19 | https://github.com/jameslyons/pycipher/blob/8f1d7cf3cba4e12171e27d9ce723ad890194de19/pycipher/playfair.py#L64-L81 |
1,746 | jameslyons/pycipher | pycipher/delastelle.py | Delastelle.encipher | def encipher(self,string):
"""Encipher string using Delastelle cipher according to initialised key.
Example::
ciphertext = Delastelle('APCZ WRLFBDKOTYUQGENHXMIVS').encipher(plaintext)
:param string: The string to encipher.
:returns: The enciphered string. The cipherte... | python | def encipher(self,string):
string = self.remove_punctuation(string,filter='[^'+self.key+']')
ctext = ""
for c in string:
ctext += ''.join([str(i) for i in L2IND[c]])
return ctext | [
"def",
"encipher",
"(",
"self",
",",
"string",
")",
":",
"string",
"=",
"self",
".",
"remove_punctuation",
"(",
"string",
",",
"filter",
"=",
"'[^'",
"+",
"self",
".",
"key",
"+",
"']'",
")",
"ctext",
"=",
"\"\"",
"for",
"c",
"in",
"string",
":",
"... | Encipher string using Delastelle cipher according to initialised key.
Example::
ciphertext = Delastelle('APCZ WRLFBDKOTYUQGENHXMIVS').encipher(plaintext)
:param string: The string to encipher.
:returns: The enciphered string. The ciphertext will be 3 times the length of the p... | [
"Encipher",
"string",
"using",
"Delastelle",
"cipher",
"according",
"to",
"initialised",
"key",
"."
] | 8f1d7cf3cba4e12171e27d9ce723ad890194de19 | https://github.com/jameslyons/pycipher/blob/8f1d7cf3cba4e12171e27d9ce723ad890194de19/pycipher/delastelle.py#L26-L40 |
1,747 | jameslyons/pycipher | pycipher/delastelle.py | Delastelle.decipher | def decipher(self,string):
"""Decipher string using Delastelle cipher according to initialised key.
Example::
plaintext = Delastelle('APCZ WRLFBDKOTYUQGENHXMIVS').decipher(ciphertext)
:param string: The string to decipher.
:returns: The deciphered string. The plaintex... | python | def decipher(self,string):
string = self.remove_punctuation(string,filter='[^'+self.chars+']')
ret = ''
for i in range(0,len(string),3):
ind = tuple([int(string[i+k]) for k in [0,1,2]])
ret += IND2L[ind]
return ret | [
"def",
"decipher",
"(",
"self",
",",
"string",
")",
":",
"string",
"=",
"self",
".",
"remove_punctuation",
"(",
"string",
",",
"filter",
"=",
"'[^'",
"+",
"self",
".",
"chars",
"+",
"']'",
")",
"ret",
"=",
"''",
"for",
"i",
"in",
"range",
"(",
"0",... | Decipher string using Delastelle cipher according to initialised key.
Example::
plaintext = Delastelle('APCZ WRLFBDKOTYUQGENHXMIVS').decipher(ciphertext)
:param string: The string to decipher.
:returns: The deciphered string. The plaintext will be 1/3 the length of the cipher... | [
"Decipher",
"string",
"using",
"Delastelle",
"cipher",
"according",
"to",
"initialised",
"key",
"."
] | 8f1d7cf3cba4e12171e27d9ce723ad890194de19 | https://github.com/jameslyons/pycipher/blob/8f1d7cf3cba4e12171e27d9ce723ad890194de19/pycipher/delastelle.py#L42-L57 |
1,748 | jameslyons/pycipher | pycipher/foursquare.py | Foursquare.encipher | def encipher(self,string):
"""Encipher string using Foursquare cipher according to initialised key. Punctuation and whitespace
are removed from the input. If the input plaintext is not an even number of characters, an 'X' will be appended.
Example::
ciphertext = Foursquare(key1='zg... | python | def encipher(self,string):
string = self.remove_punctuation(string)
if len(string)%2 == 1: string = string + 'X'
ret = ''
for c in range(0,len(string.upper()),2):
a,b = self.encipher_pair(string[c],string[c+1])
ret += a + b
return ret | [
"def",
"encipher",
"(",
"self",
",",
"string",
")",
":",
"string",
"=",
"self",
".",
"remove_punctuation",
"(",
"string",
")",
"if",
"len",
"(",
"string",
")",
"%",
"2",
"==",
"1",
":",
"string",
"=",
"string",
"+",
"'X'",
"ret",
"=",
"''",
"for",
... | Encipher string using Foursquare cipher according to initialised key. Punctuation and whitespace
are removed from the input. If the input plaintext is not an even number of characters, an 'X' will be appended.
Example::
ciphertext = Foursquare(key1='zgptfoihmuwdrcnykeqaxvsbl',key2='mfnbdcr... | [
"Encipher",
"string",
"using",
"Foursquare",
"cipher",
"according",
"to",
"initialised",
"key",
".",
"Punctuation",
"and",
"whitespace",
"are",
"removed",
"from",
"the",
"input",
".",
"If",
"the",
"input",
"plaintext",
"is",
"not",
"an",
"even",
"number",
"of"... | 8f1d7cf3cba4e12171e27d9ce723ad890194de19 | https://github.com/jameslyons/pycipher/blob/8f1d7cf3cba4e12171e27d9ce723ad890194de19/pycipher/foursquare.py#L34-L51 |
1,749 | jameslyons/pycipher | pycipher/foursquare.py | Foursquare.decipher | def decipher(self,string):
"""Decipher string using Foursquare cipher according to initialised key. Punctuation and whitespace
are removed from the input. The ciphertext should be an even number of characters. If the input ciphertext is not an even number of characters, an 'X' will be appended.
... | python | def decipher(self,string):
string = self.remove_punctuation(string)
if len(string)%2 == 1: string = string + 'X'
ret = ''
for c in range(0,len(string.upper()),2):
a,b = self.decipher_pair(string[c],string[c+1])
ret += a + b
return ret | [
"def",
"decipher",
"(",
"self",
",",
"string",
")",
":",
"string",
"=",
"self",
".",
"remove_punctuation",
"(",
"string",
")",
"if",
"len",
"(",
"string",
")",
"%",
"2",
"==",
"1",
":",
"string",
"=",
"string",
"+",
"'X'",
"ret",
"=",
"''",
"for",
... | Decipher string using Foursquare cipher according to initialised key. Punctuation and whitespace
are removed from the input. The ciphertext should be an even number of characters. If the input ciphertext is not an even number of characters, an 'X' will be appended.
Example::
plaintext = Fo... | [
"Decipher",
"string",
"using",
"Foursquare",
"cipher",
"according",
"to",
"initialised",
"key",
".",
"Punctuation",
"and",
"whitespace",
"are",
"removed",
"from",
"the",
"input",
".",
"The",
"ciphertext",
"should",
"be",
"an",
"even",
"number",
"of",
"characters... | 8f1d7cf3cba4e12171e27d9ce723ad890194de19 | https://github.com/jameslyons/pycipher/blob/8f1d7cf3cba4e12171e27d9ce723ad890194de19/pycipher/foursquare.py#L53-L70 |
1,750 | jameslyons/pycipher | pycipher/rot13.py | Rot13.encipher | def encipher(self,string,keep_punct=False):
r"""Encipher string using rot13 cipher.
Example::
ciphertext = Rot13().encipher(plaintext)
:param string: The string to encipher.
:param keep_punct: if true, punctuation and spacing are retained. If false, it is all removed.... | python | def encipher(self,string,keep_punct=False):
r"""Encipher string using rot13 cipher.
Example::
ciphertext = Rot13().encipher(plaintext)
:param string: The string to encipher.
:param keep_punct: if true, punctuation and spacing are retained. If false, it is all removed.... | [
"def",
"encipher",
"(",
"self",
",",
"string",
",",
"keep_punct",
"=",
"False",
")",
":",
"if",
"not",
"keep_punct",
":",
"string",
"=",
"self",
".",
"remove_punctuation",
"(",
"string",
")",
"ret",
"=",
"''",
"for",
"c",
"in",
"string",
":",
"if",
"... | r"""Encipher string using rot13 cipher.
Example::
ciphertext = Rot13().encipher(plaintext)
:param string: The string to encipher.
:param keep_punct: if true, punctuation and spacing are retained. If false, it is all removed. Default is False.
:returns: The enciphered... | [
"r",
"Encipher",
"string",
"using",
"rot13",
"cipher",
"."
] | 8f1d7cf3cba4e12171e27d9ce723ad890194de19 | https://github.com/jameslyons/pycipher/blob/8f1d7cf3cba4e12171e27d9ce723ad890194de19/pycipher/rot13.py#L20-L36 |
1,751 | jameslyons/pycipher | pycipher/porta.py | Porta.encipher | def encipher(self,string):
"""Encipher string using Porta cipher according to initialised key. Punctuation and whitespace
are removed from the input.
Example::
ciphertext = Porta('HELLO').encipher(plaintext)
:param string: The string to encipher.
:retur... | python | def encipher(self,string):
string = self.remove_punctuation(string)
ret = ''
for (i,c) in enumerate(string):
i = i%len(self.key)
if self.key[i] in 'AB': ret += 'NOPQRSTUVWXYZABCDEFGHIJKLM'[self.a2i(c)]
elif self.key[i] in 'YZ': ret += 'ZNOPQRSTUVWXYBCDEFGHIJ... | [
"def",
"encipher",
"(",
"self",
",",
"string",
")",
":",
"string",
"=",
"self",
".",
"remove_punctuation",
"(",
"string",
")",
"ret",
"=",
"''",
"for",
"(",
"i",
",",
"c",
")",
"in",
"enumerate",
"(",
"string",
")",
":",
"i",
"=",
"i",
"%",
"len"... | Encipher string using Porta cipher according to initialised key. Punctuation and whitespace
are removed from the input.
Example::
ciphertext = Porta('HELLO').encipher(plaintext)
:param string: The string to encipher.
:returns: The enciphered string. | [
"Encipher",
"string",
"using",
"Porta",
"cipher",
"according",
"to",
"initialised",
"key",
".",
"Punctuation",
"and",
"whitespace",
"are",
"removed",
"from",
"the",
"input",
"."
] | 8f1d7cf3cba4e12171e27d9ce723ad890194de19 | https://github.com/jameslyons/pycipher/blob/8f1d7cf3cba4e12171e27d9ce723ad890194de19/pycipher/porta.py#L17-L45 |
1,752 | jameslyons/pycipher | pycipher/m209.py | M209.encipher | def encipher(self,message):
"""Encipher string using M209 cipher according to initialised key. Punctuation and whitespace
are removed from the input.
Example (continuing from the example above)::
ciphertext = m.encipher(plaintext)
:param string: The str... | python | def encipher(self,message):
message = self.remove_punctuation(message)
effective_ch = [0,0,0,0,0,0,0] # these are the wheels which are effective currently, 1 for yes, 0 no
# -the zero at the beginning is extra, indicates lug was in pos 0
ret = ''
... | [
"def",
"encipher",
"(",
"self",
",",
"message",
")",
":",
"message",
"=",
"self",
".",
"remove_punctuation",
"(",
"message",
")",
"effective_ch",
"=",
"[",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
"]",
"# these are the wheels ... | Encipher string using M209 cipher according to initialised key. Punctuation and whitespace
are removed from the input.
Example (continuing from the example above)::
ciphertext = m.encipher(plaintext)
:param string: The string to encipher.
:returns: The ... | [
"Encipher",
"string",
"using",
"M209",
"cipher",
"according",
"to",
"initialised",
"key",
".",
"Punctuation",
"and",
"whitespace",
"are",
"removed",
"from",
"the",
"input",
"."
] | 8f1d7cf3cba4e12171e27d9ce723ad890194de19 | https://github.com/jameslyons/pycipher/blob/8f1d7cf3cba4e12171e27d9ce723ad890194de19/pycipher/m209.py#L59-L90 |
1,753 | jameslyons/pycipher | pycipher/fracmorse.py | FracMorse.encipher | def encipher(self,string):
"""Encipher string using FracMorse cipher according to initialised key.
Example::
ciphertext = FracMorse('ROUNDTABLECFGHIJKMPQSVWXYZ').encipher(plaintext)
:param string: The string to encipher.
:returns: The enciphered string.
""" ... | python | def encipher(self,string):
string = string.upper()
#print string
morsestr = self.enmorse(string)
# make sure the morse string is a multiple of 3 in length
if len(morsestr) % 3 == 1:
morsestr = morsestr[0:-1]
elif len(morsestr) % 3 == 2:
morsestr =... | [
"def",
"encipher",
"(",
"self",
",",
"string",
")",
":",
"string",
"=",
"string",
".",
"upper",
"(",
")",
"#print string",
"morsestr",
"=",
"self",
".",
"enmorse",
"(",
"string",
")",
"# make sure the morse string is a multiple of 3 in length",
"if",
"len",
"(",... | Encipher string using FracMorse cipher according to initialised key.
Example::
ciphertext = FracMorse('ROUNDTABLECFGHIJKMPQSVWXYZ').encipher(plaintext)
:param string: The string to encipher.
:returns: The enciphered string. | [
"Encipher",
"string",
"using",
"FracMorse",
"cipher",
"according",
"to",
"initialised",
"key",
"."
] | 8f1d7cf3cba4e12171e27d9ce723ad890194de19 | https://github.com/jameslyons/pycipher/blob/8f1d7cf3cba4e12171e27d9ce723ad890194de19/pycipher/fracmorse.py#L21-L44 |
1,754 | jameslyons/pycipher | pycipher/fracmorse.py | FracMorse.decipher | def decipher(self,string):
"""Decipher string using FracMorse cipher according to initialised key.
Example::
plaintext = FracMorse('ROUNDTABLECFGHIJKMPQSVWXYZ').decipher(ciphertext)
:param string: The string to decipher.
:returns: The enciphered string.
""" ... | python | def decipher(self,string):
string = string.upper()
mapping = dict(zip(self.key,self.table))
ptext = ""
for i in string:
ptext += mapping[i]
return self.demorse(ptext) | [
"def",
"decipher",
"(",
"self",
",",
"string",
")",
":",
"string",
"=",
"string",
".",
"upper",
"(",
")",
"mapping",
"=",
"dict",
"(",
"zip",
"(",
"self",
".",
"key",
",",
"self",
".",
"table",
")",
")",
"ptext",
"=",
"\"\"",
"for",
"i",
"in",
... | Decipher string using FracMorse cipher according to initialised key.
Example::
plaintext = FracMorse('ROUNDTABLECFGHIJKMPQSVWXYZ').decipher(ciphertext)
:param string: The string to decipher.
:returns: The enciphered string. | [
"Decipher",
"string",
"using",
"FracMorse",
"cipher",
"according",
"to",
"initialised",
"key",
"."
] | 8f1d7cf3cba4e12171e27d9ce723ad890194de19 | https://github.com/jameslyons/pycipher/blob/8f1d7cf3cba4e12171e27d9ce723ad890194de19/pycipher/fracmorse.py#L46-L61 |
1,755 | jameslyons/pycipher | pycipher/columnartransposition.py | ColTrans.encipher | def encipher(self,string):
"""Encipher string using Columnar Transposition cipher according to initialised key. Punctuation and whitespace
are removed from the input.
Example::
ciphertext = ColTrans('GERMAN').encipher(plaintext)
:param string: The string to enc... | python | def encipher(self,string):
string = self.remove_punctuation(string)
ret = ''
ind = self.sortind(self.keyword)
for i in range(len(self.keyword)):
ret += string[ind.index(i)::len(self.keyword)]
return ret | [
"def",
"encipher",
"(",
"self",
",",
"string",
")",
":",
"string",
"=",
"self",
".",
"remove_punctuation",
"(",
"string",
")",
"ret",
"=",
"''",
"ind",
"=",
"self",
".",
"sortind",
"(",
"self",
".",
"keyword",
")",
"for",
"i",
"in",
"range",
"(",
"... | Encipher string using Columnar Transposition cipher according to initialised key. Punctuation and whitespace
are removed from the input.
Example::
ciphertext = ColTrans('GERMAN').encipher(plaintext)
:param string: The string to encipher.
:returns: The enciphere... | [
"Encipher",
"string",
"using",
"Columnar",
"Transposition",
"cipher",
"according",
"to",
"initialised",
"key",
".",
"Punctuation",
"and",
"whitespace",
"are",
"removed",
"from",
"the",
"input",
"."
] | 8f1d7cf3cba4e12171e27d9ce723ad890194de19 | https://github.com/jameslyons/pycipher/blob/8f1d7cf3cba4e12171e27d9ce723ad890194de19/pycipher/columnartransposition.py#L32-L48 |
1,756 | jameslyons/pycipher | pycipher/columnartransposition.py | ColTrans.decipher | def decipher(self,string):
'''Decipher string using Columnar Transposition cipher according to initialised key. Punctuation and whitespace
are removed from the input.
Example::
plaintext = ColTrans('GERMAN').decipher(ciphertext)
:param string: The string to decipher.
... | python | def decipher(self,string):
'''Decipher string using Columnar Transposition cipher according to initialised key. Punctuation and whitespace
are removed from the input.
Example::
plaintext = ColTrans('GERMAN').decipher(ciphertext)
:param string: The string to decipher.
... | [
"def",
"decipher",
"(",
"self",
",",
"string",
")",
":",
"string",
"=",
"self",
".",
"remove_punctuation",
"(",
"string",
")",
"ret",
"=",
"[",
"'_'",
"]",
"*",
"len",
"(",
"string",
")",
"L",
",",
"M",
"=",
"len",
"(",
"string",
")",
",",
"len",... | Decipher string using Columnar Transposition cipher according to initialised key. Punctuation and whitespace
are removed from the input.
Example::
plaintext = ColTrans('GERMAN').decipher(ciphertext)
:param string: The string to decipher.
:returns: The deciphered strin... | [
"Decipher",
"string",
"using",
"Columnar",
"Transposition",
"cipher",
"according",
"to",
"initialised",
"key",
".",
"Punctuation",
"and",
"whitespace",
"are",
"removed",
"from",
"the",
"input",
"."
] | 8f1d7cf3cba4e12171e27d9ce723ad890194de19 | https://github.com/jameslyons/pycipher/blob/8f1d7cf3cba4e12171e27d9ce723ad890194de19/pycipher/columnartransposition.py#L51-L72 |
1,757 | jameslyons/pycipher | pycipher/railfence.py | Railfence.encipher | def encipher(self,string,keep_punct=False):
"""Encipher string using Railfence cipher according to initialised key.
Example::
ciphertext = Railfence(3).encipher(plaintext)
:param string: The string to encipher.
:param keep_punct: if true, punctuation and spaci... | python | def encipher(self,string,keep_punct=False):
if not keep_punct: string = self.remove_punctuation(string)
return ''.join(self.buildfence(string, self.key)) | [
"def",
"encipher",
"(",
"self",
",",
"string",
",",
"keep_punct",
"=",
"False",
")",
":",
"if",
"not",
"keep_punct",
":",
"string",
"=",
"self",
".",
"remove_punctuation",
"(",
"string",
")",
"return",
"''",
".",
"join",
"(",
"self",
".",
"buildfence",
... | Encipher string using Railfence cipher according to initialised key.
Example::
ciphertext = Railfence(3).encipher(plaintext)
:param string: The string to encipher.
:param keep_punct: if true, punctuation and spacing are retained. If false, it is all removed. Default i... | [
"Encipher",
"string",
"using",
"Railfence",
"cipher",
"according",
"to",
"initialised",
"key",
"."
] | 8f1d7cf3cba4e12171e27d9ce723ad890194de19 | https://github.com/jameslyons/pycipher/blob/8f1d7cf3cba4e12171e27d9ce723ad890194de19/pycipher/railfence.py#L20-L32 |
1,758 | jameslyons/pycipher | pycipher/railfence.py | Railfence.decipher | def decipher(self,string,keep_punct=False):
"""Decipher string using Railfence cipher according to initialised key.
Example::
plaintext = Railfence(3).decipher(ciphertext)
:param string: The string to decipher.
:param keep_punct: if true, punctuation and spaci... | python | def decipher(self,string,keep_punct=False):
if not keep_punct: string = self.remove_punctuation(string)
ind = range(len(string))
pos = self.buildfence(ind, self.key)
return ''.join(string[pos.index(i)] for i in ind) | [
"def",
"decipher",
"(",
"self",
",",
"string",
",",
"keep_punct",
"=",
"False",
")",
":",
"if",
"not",
"keep_punct",
":",
"string",
"=",
"self",
".",
"remove_punctuation",
"(",
"string",
")",
"ind",
"=",
"range",
"(",
"len",
"(",
"string",
")",
")",
... | Decipher string using Railfence cipher according to initialised key.
Example::
plaintext = Railfence(3).decipher(ciphertext)
:param string: The string to decipher.
:param keep_punct: if true, punctuation and spacing are retained. If false, it is all removed. Default i... | [
"Decipher",
"string",
"using",
"Railfence",
"cipher",
"according",
"to",
"initialised",
"key",
"."
] | 8f1d7cf3cba4e12171e27d9ce723ad890194de19 | https://github.com/jameslyons/pycipher/blob/8f1d7cf3cba4e12171e27d9ce723ad890194de19/pycipher/railfence.py#L34-L48 |
1,759 | jameslyons/pycipher | pycipher/affine.py | Affine.decipher | def decipher(self,string,keep_punct=False):
"""Decipher string using affine cipher according to initialised key.
Example::
plaintext = Affine(a,b).decipher(ciphertext)
:param string: The string to decipher.
:param keep_punct: if true, punctuation and spacing a... | python | def decipher(self,string,keep_punct=False):
if not keep_punct: string = self.remove_punctuation(string)
ret = ''
for c in string:
if c.isalpha(): ret += self.i2a(self.inva*(self.a2i(c) - self.b))
else: ret += c
return ret | [
"def",
"decipher",
"(",
"self",
",",
"string",
",",
"keep_punct",
"=",
"False",
")",
":",
"if",
"not",
"keep_punct",
":",
"string",
"=",
"self",
".",
"remove_punctuation",
"(",
"string",
")",
"ret",
"=",
"''",
"for",
"c",
"in",
"string",
":",
"if",
"... | Decipher string using affine cipher according to initialised key.
Example::
plaintext = Affine(a,b).decipher(ciphertext)
:param string: The string to decipher.
:param keep_punct: if true, punctuation and spacing are retained. If false, it is all removed. Default is Fa... | [
"Decipher",
"string",
"using",
"affine",
"cipher",
"according",
"to",
"initialised",
"key",
"."
] | 8f1d7cf3cba4e12171e27d9ce723ad890194de19 | https://github.com/jameslyons/pycipher/blob/8f1d7cf3cba4e12171e27d9ce723ad890194de19/pycipher/affine.py#L50-L66 |
1,760 | jameslyons/pycipher | pycipher/autokey.py | Autokey.encipher | def encipher(self,string):
"""Encipher string using Autokey cipher according to initialised key. Punctuation and whitespace
are removed from the input.
Example::
ciphertext = Autokey('HELLO').encipher(plaintext)
:param string: The string to encipher.
:r... | python | def encipher(self,string):
string = self.remove_punctuation(string)
ret = ''
for (i,c) in enumerate(string):
if i<len(self.key): offset = self.a2i(self.key[i])
else: offset = self.a2i(string[i-len(self.key)])
ret += self.i2a(self.a2i(c)+offset)
re... | [
"def",
"encipher",
"(",
"self",
",",
"string",
")",
":",
"string",
"=",
"self",
".",
"remove_punctuation",
"(",
"string",
")",
"ret",
"=",
"''",
"for",
"(",
"i",
",",
"c",
")",
"in",
"enumerate",
"(",
"string",
")",
":",
"if",
"i",
"<",
"len",
"(... | Encipher string using Autokey cipher according to initialised key. Punctuation and whitespace
are removed from the input.
Example::
ciphertext = Autokey('HELLO').encipher(plaintext)
:param string: The string to encipher.
:returns: The enciphered string. | [
"Encipher",
"string",
"using",
"Autokey",
"cipher",
"according",
"to",
"initialised",
"key",
".",
"Punctuation",
"and",
"whitespace",
"are",
"removed",
"from",
"the",
"input",
"."
] | 8f1d7cf3cba4e12171e27d9ce723ad890194de19 | https://github.com/jameslyons/pycipher/blob/8f1d7cf3cba4e12171e27d9ce723ad890194de19/pycipher/autokey.py#L19-L36 |
1,761 | jameslyons/pycipher | pycipher/bifid.py | Bifid.encipher | def encipher(self,string):
"""Encipher string using Bifid cipher according to initialised key. Punctuation and whitespace
are removed from the input.
Example::
ciphertext = Bifid('phqgmeaylnofdxkrcvszwbuti',5).encipher(plaintext)
:param string: The string to en... | python | def encipher(self,string):
string = self.remove_punctuation(string)
step1 = self.pb.encipher(string)
evens = step1[::2]
odds = step1[1::2]
step2 = []
for i in range(0,len(string),self.period):
step2 += evens[i:int(i+self.period)]
step2 += odds[i:in... | [
"def",
"encipher",
"(",
"self",
",",
"string",
")",
":",
"string",
"=",
"self",
".",
"remove_punctuation",
"(",
"string",
")",
"step1",
"=",
"self",
".",
"pb",
".",
"encipher",
"(",
"string",
")",
"evens",
"=",
"step1",
"[",
":",
":",
"2",
"]",
"od... | Encipher string using Bifid cipher according to initialised key. Punctuation and whitespace
are removed from the input.
Example::
ciphertext = Bifid('phqgmeaylnofdxkrcvszwbuti',5).encipher(plaintext)
:param string: The string to encipher.
:returns: The encipher... | [
"Encipher",
"string",
"using",
"Bifid",
"cipher",
"according",
"to",
"initialised",
"key",
".",
"Punctuation",
"and",
"whitespace",
"are",
"removed",
"from",
"the",
"input",
"."
] | 8f1d7cf3cba4e12171e27d9ce723ad890194de19 | https://github.com/jameslyons/pycipher/blob/8f1d7cf3cba4e12171e27d9ce723ad890194de19/pycipher/bifid.py#L25-L44 |
1,762 | jameslyons/pycipher | pycipher/bifid.py | Bifid.decipher | def decipher(self,string):
"""Decipher string using Bifid cipher according to initialised key. Punctuation and whitespace
are removed from the input.
Example::
plaintext = Bifid('phqgmeaylnofdxkrcvszwbuti',5).decipher(ciphertext)
:param string: The string to decipher.... | python | def decipher(self,string):
ret = ''
string = string.upper()
rowseq,colseq = [],[]
# take blocks of length period, reform rowseq,colseq from them
for i in range(0,len(string),self.period):
tempseq = []
for j in range(0,self.period):
if i+j >... | [
"def",
"decipher",
"(",
"self",
",",
"string",
")",
":",
"ret",
"=",
"''",
"string",
"=",
"string",
".",
"upper",
"(",
")",
"rowseq",
",",
"colseq",
"=",
"[",
"]",
",",
"[",
"]",
"# take blocks of length period, reform rowseq,colseq from them",
"for",
"i",
... | Decipher string using Bifid cipher according to initialised key. Punctuation and whitespace
are removed from the input.
Example::
plaintext = Bifid('phqgmeaylnofdxkrcvszwbuti',5).decipher(ciphertext)
:param string: The string to decipher.
:returns: The deciphered stri... | [
"Decipher",
"string",
"using",
"Bifid",
"cipher",
"according",
"to",
"initialised",
"key",
".",
"Punctuation",
"and",
"whitespace",
"are",
"removed",
"from",
"the",
"input",
"."
] | 8f1d7cf3cba4e12171e27d9ce723ad890194de19 | https://github.com/jameslyons/pycipher/blob/8f1d7cf3cba4e12171e27d9ce723ad890194de19/pycipher/bifid.py#L46-L71 |
1,763 | jameslyons/pycipher | pycipher/simplesubstitution.py | SimpleSubstitution.decipher | def decipher(self,string,keep_punct=False):
"""Decipher string using Simple Substitution cipher according to initialised key.
Example::
plaintext = SimpleSubstitution('AJPCZWRLFBDKOTYUQGENHXMIVS').decipher(ciphertext)
:param string: The string to decipher.
:param keep... | python | def decipher(self,string,keep_punct=False):
# if we have not yet calculated the inverse key, calculate it now
if self.invkey == '':
for i in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
self.invkey += self.i2a(self.key.index(i))
if not keep_punct: string = self.remove_punctuation(s... | [
"def",
"decipher",
"(",
"self",
",",
"string",
",",
"keep_punct",
"=",
"False",
")",
":",
"# if we have not yet calculated the inverse key, calculate it now",
"if",
"self",
".",
"invkey",
"==",
"''",
":",
"for",
"i",
"in",
"'ABCDEFGHIJKLMNOPQRSTUVWXYZ'",
":",
"self"... | Decipher string using Simple Substitution cipher according to initialised key.
Example::
plaintext = SimpleSubstitution('AJPCZWRLFBDKOTYUQGENHXMIVS').decipher(ciphertext)
:param string: The string to decipher.
:param keep_punct: if true, punctuation and spacing are retained. ... | [
"Decipher",
"string",
"using",
"Simple",
"Substitution",
"cipher",
"according",
"to",
"initialised",
"key",
"."
] | 8f1d7cf3cba4e12171e27d9ce723ad890194de19 | https://github.com/jameslyons/pycipher/blob/8f1d7cf3cba4e12171e27d9ce723ad890194de19/pycipher/simplesubstitution.py#L45-L65 |
1,764 | oseledets/ttpy | tt/core/tools.py | kron | def kron(a, b):
"""Kronecker product of two TT-matrices or two TT-vectors"""
if hasattr(a, '__kron__'):
return a.__kron__(b)
if a is None:
return b
else:
raise ValueError(
'Kron is waiting for two TT-vectors or two TT-matrices') | python | def kron(a, b):
if hasattr(a, '__kron__'):
return a.__kron__(b)
if a is None:
return b
else:
raise ValueError(
'Kron is waiting for two TT-vectors or two TT-matrices') | [
"def",
"kron",
"(",
"a",
",",
"b",
")",
":",
"if",
"hasattr",
"(",
"a",
",",
"'__kron__'",
")",
":",
"return",
"a",
".",
"__kron__",
"(",
"b",
")",
"if",
"a",
"is",
"None",
":",
"return",
"b",
"else",
":",
"raise",
"ValueError",
"(",
"'Kron is wa... | Kronecker product of two TT-matrices or two TT-vectors | [
"Kronecker",
"product",
"of",
"two",
"TT",
"-",
"matrices",
"or",
"two",
"TT",
"-",
"vectors"
] | b440f6299a6338de4aea67f3d839d613f4ef1374 | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/core/tools.py#L127-L135 |
1,765 | oseledets/ttpy | tt/core/tools.py | dot | def dot(a, b):
"""Dot product of two TT-matrices or two TT-vectors"""
if hasattr(a, '__dot__'):
return a.__dot__(b)
if a is None:
return b
else:
raise ValueError(
'Dot is waiting for two TT-vectors or two TT- matrices') | python | def dot(a, b):
if hasattr(a, '__dot__'):
return a.__dot__(b)
if a is None:
return b
else:
raise ValueError(
'Dot is waiting for two TT-vectors or two TT- matrices') | [
"def",
"dot",
"(",
"a",
",",
"b",
")",
":",
"if",
"hasattr",
"(",
"a",
",",
"'__dot__'",
")",
":",
"return",
"a",
".",
"__dot__",
"(",
"b",
")",
"if",
"a",
"is",
"None",
":",
"return",
"b",
"else",
":",
"raise",
"ValueError",
"(",
"'Dot is waitin... | Dot product of two TT-matrices or two TT-vectors | [
"Dot",
"product",
"of",
"two",
"TT",
"-",
"matrices",
"or",
"two",
"TT",
"-",
"vectors"
] | b440f6299a6338de4aea67f3d839d613f4ef1374 | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/core/tools.py#L138-L146 |
1,766 | oseledets/ttpy | tt/core/tools.py | mkron | def mkron(a, *args):
"""Kronecker product of all the arguments"""
if not isinstance(a, list):
a = [a]
a = list(a) # copy list
for i in args:
if isinstance(i, list):
a.extend(i)
else:
a.append(i)
c = _vector.vector()
c.d = 0
c.n = _np.array([]... | python | def mkron(a, *args):
if not isinstance(a, list):
a = [a]
a = list(a) # copy list
for i in args:
if isinstance(i, list):
a.extend(i)
else:
a.append(i)
c = _vector.vector()
c.d = 0
c.n = _np.array([], dtype=_np.int32)
c.r = _np.array([], dtype=... | [
"def",
"mkron",
"(",
"a",
",",
"*",
"args",
")",
":",
"if",
"not",
"isinstance",
"(",
"a",
",",
"list",
")",
":",
"a",
"=",
"[",
"a",
"]",
"a",
"=",
"list",
"(",
"a",
")",
"# copy list",
"for",
"i",
"in",
"args",
":",
"if",
"isinstance",
"(",... | Kronecker product of all the arguments | [
"Kronecker",
"product",
"of",
"all",
"the",
"arguments"
] | b440f6299a6338de4aea67f3d839d613f4ef1374 | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/core/tools.py#L157-L182 |
1,767 | oseledets/ttpy | tt/core/tools.py | concatenate | def concatenate(*args):
"""Concatenates given TT-vectors.
For two tensors :math:`X(i_1,\\ldots,i_d),Y(i_1,\\ldots,i_d)` returns :math:`(d+1)`-dimensional
tensor :math:`Z(i_0,i_1,\\ldots,i_d)`, :math:`i_0=\\overline{0,1}`, such that
.. math::
Z(0, i_1, \\ldots, i_d) = X(i_1, \\ldots, i_d),
... | python | def concatenate(*args):
tmp = _np.array([[1] + [0] * (len(args) - 1)])
result = kron(_vector.vector(tmp), args[0])
for i in range(1, len(args)):
result += kron(_vector.vector(_np.array([[0] * i +
[1] + [0] * (len(args) - i - 1)])), args[i])
return... | [
"def",
"concatenate",
"(",
"*",
"args",
")",
":",
"tmp",
"=",
"_np",
".",
"array",
"(",
"[",
"[",
"1",
"]",
"+",
"[",
"0",
"]",
"*",
"(",
"len",
"(",
"args",
")",
"-",
"1",
")",
"]",
")",
"result",
"=",
"kron",
"(",
"_vector",
".",
"vector"... | Concatenates given TT-vectors.
For two tensors :math:`X(i_1,\\ldots,i_d),Y(i_1,\\ldots,i_d)` returns :math:`(d+1)`-dimensional
tensor :math:`Z(i_0,i_1,\\ldots,i_d)`, :math:`i_0=\\overline{0,1}`, such that
.. math::
Z(0, i_1, \\ldots, i_d) = X(i_1, \\ldots, i_d),
Z(1, i_1, \\ldots, i_d) = Y(... | [
"Concatenates",
"given",
"TT",
"-",
"vectors",
"."
] | b440f6299a6338de4aea67f3d839d613f4ef1374 | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/core/tools.py#L254-L271 |
1,768 | oseledets/ttpy | tt/core/tools.py | sum | def sum(a, axis=-1):
"""Sum TT-vector over specified axes"""
d = a.d
crs = _vector.vector.to_list(a.tt if isinstance(a, _matrix.matrix) else a)
if axis < 0:
axis = range(a.d)
elif isinstance(axis, int):
axis = [axis]
axis = list(axis)[::-1]
for ax in axis:
crs[ax] = _... | python | def sum(a, axis=-1):
d = a.d
crs = _vector.vector.to_list(a.tt if isinstance(a, _matrix.matrix) else a)
if axis < 0:
axis = range(a.d)
elif isinstance(axis, int):
axis = [axis]
axis = list(axis)[::-1]
for ax in axis:
crs[ax] = _np.sum(crs[ax], axis=1)
rleft, rrigh... | [
"def",
"sum",
"(",
"a",
",",
"axis",
"=",
"-",
"1",
")",
":",
"d",
"=",
"a",
".",
"d",
"crs",
"=",
"_vector",
".",
"vector",
".",
"to_list",
"(",
"a",
".",
"tt",
"if",
"isinstance",
"(",
"a",
",",
"_matrix",
".",
"matrix",
")",
"else",
"a",
... | Sum TT-vector over specified axes | [
"Sum",
"TT",
"-",
"vector",
"over",
"specified",
"axes"
] | b440f6299a6338de4aea67f3d839d613f4ef1374 | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/core/tools.py#L274-L294 |
1,769 | oseledets/ttpy | tt/core/tools.py | ones | def ones(n, d=None):
""" Creates a TT-vector of all ones"""
c = _vector.vector()
if d is None:
c.n = _np.array(n, dtype=_np.int32)
c.d = c.n.size
else:
c.n = _np.array([n] * d, dtype=_np.int32)
c.d = d
c.r = _np.ones((c.d + 1,), dtype=_np.int32)
c.get_ps()
c.c... | python | def ones(n, d=None):
c = _vector.vector()
if d is None:
c.n = _np.array(n, dtype=_np.int32)
c.d = c.n.size
else:
c.n = _np.array([n] * d, dtype=_np.int32)
c.d = d
c.r = _np.ones((c.d + 1,), dtype=_np.int32)
c.get_ps()
c.core = _np.ones(c.ps[c.d] - 1)
return c | [
"def",
"ones",
"(",
"n",
",",
"d",
"=",
"None",
")",
":",
"c",
"=",
"_vector",
".",
"vector",
"(",
")",
"if",
"d",
"is",
"None",
":",
"c",
".",
"n",
"=",
"_np",
".",
"array",
"(",
"n",
",",
"dtype",
"=",
"_np",
".",
"int32",
")",
"c",
"."... | Creates a TT-vector of all ones | [
"Creates",
"a",
"TT",
"-",
"vector",
"of",
"all",
"ones"
] | b440f6299a6338de4aea67f3d839d613f4ef1374 | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/core/tools.py#L300-L312 |
1,770 | oseledets/ttpy | tt/core/tools.py | rand | def rand(n, d=None, r=2, samplefunc=_np.random.randn):
"""Generate a random d-dimensional TT-vector with ranks ``r``.
Distribution to sample cores is provided by the samplefunc.
Default is to sample from normal distribution.
"""
n0 = _np.asanyarray(n, dtype=_np.int32)
r0 = _np.asanyarray(r, dtyp... | python | def rand(n, d=None, r=2, samplefunc=_np.random.randn):
n0 = _np.asanyarray(n, dtype=_np.int32)
r0 = _np.asanyarray(r, dtype=_np.int32)
if d is None:
d = n.size
if n0.size is 1:
n0 = _np.ones((d,), dtype=_np.int32) * n0
if r0.size is 1:
r0 = _np.ones((d + 1,), dtype=_np.int32)... | [
"def",
"rand",
"(",
"n",
",",
"d",
"=",
"None",
",",
"r",
"=",
"2",
",",
"samplefunc",
"=",
"_np",
".",
"random",
".",
"randn",
")",
":",
"n0",
"=",
"_np",
".",
"asanyarray",
"(",
"n",
",",
"dtype",
"=",
"_np",
".",
"int32",
")",
"r0",
"=",
... | Generate a random d-dimensional TT-vector with ranks ``r``.
Distribution to sample cores is provided by the samplefunc.
Default is to sample from normal distribution. | [
"Generate",
"a",
"random",
"d",
"-",
"dimensional",
"TT",
"-",
"vector",
"with",
"ranks",
"r",
".",
"Distribution",
"to",
"sample",
"cores",
"is",
"provided",
"by",
"the",
"samplefunc",
".",
"Default",
"is",
"to",
"sample",
"from",
"normal",
"distribution",
... | b440f6299a6338de4aea67f3d839d613f4ef1374 | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/core/tools.py#L315-L336 |
1,771 | oseledets/ttpy | tt/core/tools.py | eye | def eye(n, d=None):
""" Creates an identity TT-matrix"""
c = _matrix.matrix()
c.tt = _vector.vector()
if d is None:
n0 = _np.asanyarray(n, dtype=_np.int32)
c.tt.d = n0.size
else:
n0 = _np.asanyarray([n] * d, dtype=_np.int32)
c.tt.d = d
c.n = n0.copy()
c.m = n0... | python | def eye(n, d=None):
c = _matrix.matrix()
c.tt = _vector.vector()
if d is None:
n0 = _np.asanyarray(n, dtype=_np.int32)
c.tt.d = n0.size
else:
n0 = _np.asanyarray([n] * d, dtype=_np.int32)
c.tt.d = d
c.n = n0.copy()
c.m = n0.copy()
c.tt.n = (c.n) * (c.m)
c.... | [
"def",
"eye",
"(",
"n",
",",
"d",
"=",
"None",
")",
":",
"c",
"=",
"_matrix",
".",
"matrix",
"(",
")",
"c",
".",
"tt",
"=",
"_vector",
".",
"vector",
"(",
")",
"if",
"d",
"is",
"None",
":",
"n0",
"=",
"_np",
".",
"asanyarray",
"(",
"n",
","... | Creates an identity TT-matrix | [
"Creates",
"an",
"identity",
"TT",
"-",
"matrix"
] | b440f6299a6338de4aea67f3d839d613f4ef1374 | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/core/tools.py#L340-L364 |
1,772 | oseledets/ttpy | tt/riemannian/riemannian.py | cores_orthogonalization_step | def cores_orthogonalization_step(coresX, dim, left_to_right=True):
"""TT-Tensor X orthogonalization step.
The function can change the shape of some cores.
"""
cc = coresX[dim]
r1, n, r2 = cc.shape
if left_to_right:
# Left to right orthogonalization step.
assert(0 <= dim < len(co... | python | def cores_orthogonalization_step(coresX, dim, left_to_right=True):
cc = coresX[dim]
r1, n, r2 = cc.shape
if left_to_right:
# Left to right orthogonalization step.
assert(0 <= dim < len(coresX) - 1)
cc, rr = np.linalg.qr(reshape(cc, (-1, r2)))
r2 = cc.shape[1]
coresX[d... | [
"def",
"cores_orthogonalization_step",
"(",
"coresX",
",",
"dim",
",",
"left_to_right",
"=",
"True",
")",
":",
"cc",
"=",
"coresX",
"[",
"dim",
"]",
"r1",
",",
"n",
",",
"r2",
"=",
"cc",
".",
"shape",
"if",
"left_to_right",
":",
"# Left to right orthogonal... | TT-Tensor X orthogonalization step.
The function can change the shape of some cores. | [
"TT",
"-",
"Tensor",
"X",
"orthogonalization",
"step",
"."
] | b440f6299a6338de4aea67f3d839d613f4ef1374 | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/riemannian/riemannian.py#L16-L37 |
1,773 | oseledets/ttpy | tt/riemannian/riemannian.py | unfolding | def unfolding(tens, i):
"""Compute the i-th unfolding of a tensor."""
return reshape(tens.full(), (np.prod(tens.n[0:(i+1)]), -1)) | python | def unfolding(tens, i):
return reshape(tens.full(), (np.prod(tens.n[0:(i+1)]), -1)) | [
"def",
"unfolding",
"(",
"tens",
",",
"i",
")",
":",
"return",
"reshape",
"(",
"tens",
".",
"full",
"(",
")",
",",
"(",
"np",
".",
"prod",
"(",
"tens",
".",
"n",
"[",
"0",
":",
"(",
"i",
"+",
"1",
")",
"]",
")",
",",
"-",
"1",
")",
")"
] | Compute the i-th unfolding of a tensor. | [
"Compute",
"the",
"i",
"-",
"th",
"unfolding",
"of",
"a",
"tensor",
"."
] | b440f6299a6338de4aea67f3d839d613f4ef1374 | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/riemannian/riemannian.py#L66-L68 |
1,774 | oseledets/ttpy | tt/core/utils.py | gcd | def gcd(a, b):
'''Greatest common divider'''
f = _np.frompyfunc(_fractions.gcd, 2, 1)
return f(a, b) | python | def gcd(a, b):
'''Greatest common divider'''
f = _np.frompyfunc(_fractions.gcd, 2, 1)
return f(a, b) | [
"def",
"gcd",
"(",
"a",
",",
"b",
")",
":",
"f",
"=",
"_np",
".",
"frompyfunc",
"(",
"_fractions",
".",
"gcd",
",",
"2",
",",
"1",
")",
"return",
"f",
"(",
"a",
",",
"b",
")"
] | Greatest common divider | [
"Greatest",
"common",
"divider"
] | b440f6299a6338de4aea67f3d839d613f4ef1374 | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/core/utils.py#L27-L30 |
1,775 | oseledets/ttpy | tt/ksl/ksl.py | ksl | def ksl(A, y0, tau, verb=1, scheme='symm', space=8, rmax=2000, use_normest=1):
""" Dynamical tensor-train approximation based on projector splitting
This function performs one step of dynamical tensor-train approximation
for the equation
.. math ::
\\frac{dy}{dt} = A y, \\quad y... | python | def ksl(A, y0, tau, verb=1, scheme='symm', space=8, rmax=2000, use_normest=1):
y0 = y0.round(1e-14) # This will fix ranks
# to be no more than maximal reasonable.
# Fortran part doesn't handle excessive ranks
ry = y0.r.copy()
if scheme is 'symm':
... | [
"def",
"ksl",
"(",
"A",
",",
"y0",
",",
"tau",
",",
"verb",
"=",
"1",
",",
"scheme",
"=",
"'symm'",
",",
"space",
"=",
"8",
",",
"rmax",
"=",
"2000",
",",
"use_normest",
"=",
"1",
")",
":",
"y0",
"=",
"y0",
".",
"round",
"(",
"1e-14",
")",
... | Dynamical tensor-train approximation based on projector splitting
This function performs one step of dynamical tensor-train approximation
for the equation
.. math ::
\\frac{dy}{dt} = A y, \\quad y(0) = y_0
and outputs approximation for :math:`y(\\tau)`
:References:
... | [
"Dynamical",
"tensor",
"-",
"train",
"approximation",
"based",
"on",
"projector",
"splitting",
"This",
"function",
"performs",
"one",
"step",
"of",
"dynamical",
"tensor",
"-",
"train",
"approximation",
"for",
"the",
"equation"
] | b440f6299a6338de4aea67f3d839d613f4ef1374 | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/ksl/ksl.py#L7-L123 |
1,776 | oseledets/ttpy | tt/ksl/ksl.py | diag_ksl | def diag_ksl(A, y0, tau, verb=1, scheme='symm', space=8, rmax=2000):
""" Dynamical tensor-train approximation based on projector splitting
This function performs one step of dynamical tensor-train approximation with diagonal matrix, i.e. it solves the equation
for the equation
.. math ::
... | python | def diag_ksl(A, y0, tau, verb=1, scheme='symm', space=8, rmax=2000):
y0 = y0.round(1e-14) # This will fix ranks
# to be no more than maximal reasonable.
# Fortran part doesn't handle excessive ranks
ry = y0.r.copy()
if scheme is 'symm':
tp ... | [
"def",
"diag_ksl",
"(",
"A",
",",
"y0",
",",
"tau",
",",
"verb",
"=",
"1",
",",
"scheme",
"=",
"'symm'",
",",
"space",
"=",
"8",
",",
"rmax",
"=",
"2000",
")",
":",
"y0",
"=",
"y0",
".",
"round",
"(",
"1e-14",
")",
"# This will fix ranks",
"# to ... | Dynamical tensor-train approximation based on projector splitting
This function performs one step of dynamical tensor-train approximation with diagonal matrix, i.e. it solves the equation
for the equation
.. math ::
\\frac{dy}{dt} = V y, \\quad y(0) = y_0
and outputs approx... | [
"Dynamical",
"tensor",
"-",
"train",
"approximation",
"based",
"on",
"projector",
"splitting",
"This",
"function",
"performs",
"one",
"step",
"of",
"dynamical",
"tensor",
"-",
"train",
"approximation",
"with",
"diagonal",
"matrix",
"i",
".",
"e",
".",
"it",
"s... | b440f6299a6338de4aea67f3d839d613f4ef1374 | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/ksl/ksl.py#L126-L231 |
1,777 | oseledets/ttpy | tt/core/matrix.py | matrix.T | def T(self):
"""Transposed TT-matrix"""
mycrs = matrix.to_list(self)
trans_crs = []
for cr in mycrs:
trans_crs.append(_np.transpose(cr, [0, 2, 1, 3]))
return matrix.from_list(trans_crs) | python | def T(self):
mycrs = matrix.to_list(self)
trans_crs = []
for cr in mycrs:
trans_crs.append(_np.transpose(cr, [0, 2, 1, 3]))
return matrix.from_list(trans_crs) | [
"def",
"T",
"(",
"self",
")",
":",
"mycrs",
"=",
"matrix",
".",
"to_list",
"(",
"self",
")",
"trans_crs",
"=",
"[",
"]",
"for",
"cr",
"in",
"mycrs",
":",
"trans_crs",
".",
"append",
"(",
"_np",
".",
"transpose",
"(",
"cr",
",",
"[",
"0",
",",
"... | Transposed TT-matrix | [
"Transposed",
"TT",
"-",
"matrix"
] | b440f6299a6338de4aea67f3d839d613f4ef1374 | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/core/matrix.py#L126-L132 |
1,778 | oseledets/ttpy | tt/core/matrix.py | matrix.real | def real(self):
"""Return real part of a matrix."""
return matrix(self.tt.real(), n=self.n, m=self.m) | python | def real(self):
return matrix(self.tt.real(), n=self.n, m=self.m) | [
"def",
"real",
"(",
"self",
")",
":",
"return",
"matrix",
"(",
"self",
".",
"tt",
".",
"real",
"(",
")",
",",
"n",
"=",
"self",
".",
"n",
",",
"m",
"=",
"self",
".",
"m",
")"
] | Return real part of a matrix. | [
"Return",
"real",
"part",
"of",
"a",
"matrix",
"."
] | b440f6299a6338de4aea67f3d839d613f4ef1374 | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/core/matrix.py#L134-L136 |
1,779 | oseledets/ttpy | tt/core/matrix.py | matrix.imag | def imag(self):
"""Return imaginary part of a matrix."""
return matrix(self.tt.imag(), n=self.n, m=self.m) | python | def imag(self):
return matrix(self.tt.imag(), n=self.n, m=self.m) | [
"def",
"imag",
"(",
"self",
")",
":",
"return",
"matrix",
"(",
"self",
".",
"tt",
".",
"imag",
"(",
")",
",",
"n",
"=",
"self",
".",
"n",
",",
"m",
"=",
"self",
".",
"m",
")"
] | Return imaginary part of a matrix. | [
"Return",
"imaginary",
"part",
"of",
"a",
"matrix",
"."
] | b440f6299a6338de4aea67f3d839d613f4ef1374 | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/core/matrix.py#L138-L140 |
1,780 | oseledets/ttpy | tt/core/matrix.py | matrix.c2r | def c2r(self):
"""Get real matrix from complex one suitable for solving complex linear system with real solver.
For matrix :math:`M(i_1,j_1,\\ldots,i_d,j_d) = \\Re M + i\\Im M` returns (d+1)-dimensional matrix
:math:`\\tilde{M}(i_1,j_1,\\ldots,i_d,j_d,i_{d+1},j_{d+1})` of form
:math:`\\... | python | def c2r(self):
return matrix(a=self.tt.__complex_op('M'), n=_np.concatenate(
(self.n, [2])), m=_np.concatenate((self.m, [2]))) | [
"def",
"c2r",
"(",
"self",
")",
":",
"return",
"matrix",
"(",
"a",
"=",
"self",
".",
"tt",
".",
"__complex_op",
"(",
"'M'",
")",
",",
"n",
"=",
"_np",
".",
"concatenate",
"(",
"(",
"self",
".",
"n",
",",
"[",
"2",
"]",
")",
")",
",",
"m",
"... | Get real matrix from complex one suitable for solving complex linear system with real solver.
For matrix :math:`M(i_1,j_1,\\ldots,i_d,j_d) = \\Re M + i\\Im M` returns (d+1)-dimensional matrix
:math:`\\tilde{M}(i_1,j_1,\\ldots,i_d,j_d,i_{d+1},j_{d+1})` of form
:math:`\\begin{bmatrix}\\Re M & -\\... | [
"Get",
"real",
"matrix",
"from",
"complex",
"one",
"suitable",
"for",
"solving",
"complex",
"linear",
"system",
"with",
"real",
"solver",
"."
] | b440f6299a6338de4aea67f3d839d613f4ef1374 | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/core/matrix.py#L142-L159 |
1,781 | oseledets/ttpy | tt/core/matrix.py | matrix.round | def round(self, eps=1e-14, rmax=100000):
""" Computes an approximation to a
TT-matrix in with accuracy EPS
"""
c = matrix()
c.tt = self.tt.round(eps, rmax)
c.n = self.n.copy()
c.m = self.m.copy()
return c | python | def round(self, eps=1e-14, rmax=100000):
c = matrix()
c.tt = self.tt.round(eps, rmax)
c.n = self.n.copy()
c.m = self.m.copy()
return c | [
"def",
"round",
"(",
"self",
",",
"eps",
"=",
"1e-14",
",",
"rmax",
"=",
"100000",
")",
":",
"c",
"=",
"matrix",
"(",
")",
"c",
".",
"tt",
"=",
"self",
".",
"tt",
".",
"round",
"(",
"eps",
",",
"rmax",
")",
"c",
".",
"n",
"=",
"self",
".",
... | Computes an approximation to a
TT-matrix in with accuracy EPS | [
"Computes",
"an",
"approximation",
"to",
"a",
"TT",
"-",
"matrix",
"in",
"with",
"accuracy",
"EPS"
] | b440f6299a6338de4aea67f3d839d613f4ef1374 | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/core/matrix.py#L317-L325 |
1,782 | oseledets/ttpy | tt/core/matrix.py | matrix.copy | def copy(self):
""" Creates a copy of the TT-matrix """
c = matrix()
c.tt = self.tt.copy()
c.n = self.n.copy()
c.m = self.m.copy()
return c | python | def copy(self):
c = matrix()
c.tt = self.tt.copy()
c.n = self.n.copy()
c.m = self.m.copy()
return c | [
"def",
"copy",
"(",
"self",
")",
":",
"c",
"=",
"matrix",
"(",
")",
"c",
".",
"tt",
"=",
"self",
".",
"tt",
".",
"copy",
"(",
")",
"c",
".",
"n",
"=",
"self",
".",
"n",
".",
"copy",
"(",
")",
"c",
".",
"m",
"=",
"self",
".",
"m",
".",
... | Creates a copy of the TT-matrix | [
"Creates",
"a",
"copy",
"of",
"the",
"TT",
"-",
"matrix"
] | b440f6299a6338de4aea67f3d839d613f4ef1374 | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/core/matrix.py#L327-L333 |
1,783 | oseledets/ttpy | tt/core/matrix.py | matrix.full | def full(self):
""" Transforms a TT-matrix into a full matrix"""
N = self.n.prod()
M = self.m.prod()
a = self.tt.full()
d = self.tt.d
sz = _np.vstack((self.n, self.m)).flatten('F')
a = a.reshape(sz, order='F')
# Design a permutation
prm = _np.arang... | python | def full(self):
N = self.n.prod()
M = self.m.prod()
a = self.tt.full()
d = self.tt.d
sz = _np.vstack((self.n, self.m)).flatten('F')
a = a.reshape(sz, order='F')
# Design a permutation
prm = _np.arange(2 * d)
prm = prm.reshape((d, 2), order='F')
... | [
"def",
"full",
"(",
"self",
")",
":",
"N",
"=",
"self",
".",
"n",
".",
"prod",
"(",
")",
"M",
"=",
"self",
".",
"m",
".",
"prod",
"(",
")",
"a",
"=",
"self",
".",
"tt",
".",
"full",
"(",
")",
"d",
"=",
"self",
".",
"tt",
".",
"d",
"sz",... | Transforms a TT-matrix into a full matrix | [
"Transforms",
"a",
"TT",
"-",
"matrix",
"into",
"a",
"full",
"matrix"
] | b440f6299a6338de4aea67f3d839d613f4ef1374 | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/core/matrix.py#L355-L374 |
1,784 | oseledets/ttpy | tt/core/vector.py | vector.from_list | def from_list(a, order='F'):
"""Generate TT-vectorr object from given TT cores.
:param a: List of TT cores.
:type a: list
:returns: vector -- TT-vector constructed from the given cores.
"""
d = len(a) # Number of cores
res = vector()
n = _np.zeros(d, dt... | python | def from_list(a, order='F'):
d = len(a) # Number of cores
res = vector()
n = _np.zeros(d, dtype=_np.int32)
r = _np.zeros(d+1, dtype=_np.int32)
cr = _np.array([])
for i in xrange(d):
cr = _np.concatenate((cr, a[i].flatten(order)))
r[i] = a[i].shape... | [
"def",
"from_list",
"(",
"a",
",",
"order",
"=",
"'F'",
")",
":",
"d",
"=",
"len",
"(",
"a",
")",
"# Number of cores",
"res",
"=",
"vector",
"(",
")",
"n",
"=",
"_np",
".",
"zeros",
"(",
"d",
",",
"dtype",
"=",
"_np",
".",
"int32",
")",
"r",
... | Generate TT-vectorr object from given TT cores.
:param a: List of TT cores.
:type a: list
:returns: vector -- TT-vector constructed from the given cores. | [
"Generate",
"TT",
"-",
"vectorr",
"object",
"from",
"given",
"TT",
"cores",
"."
] | b440f6299a6338de4aea67f3d839d613f4ef1374 | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/core/vector.py#L82-L105 |
1,785 | oseledets/ttpy | tt/core/vector.py | vector.erank | def erank(self):
""" Effective rank of the TT-vector """
r = self.r
n = self.n
d = self.d
if d <= 1:
er = 0e0
else:
sz = _np.dot(n * r[0:d], r[1:])
if sz == 0:
er = 0e0
else:
b = r[0] * n[0] +... | python | def erank(self):
r = self.r
n = self.n
d = self.d
if d <= 1:
er = 0e0
else:
sz = _np.dot(n * r[0:d], r[1:])
if sz == 0:
er = 0e0
else:
b = r[0] * n[0] + n[d - 1] * r[d]
if d is 2:
... | [
"def",
"erank",
"(",
"self",
")",
":",
"r",
"=",
"self",
".",
"r",
"n",
"=",
"self",
".",
"n",
"d",
"=",
"self",
".",
"d",
"if",
"d",
"<=",
"1",
":",
"er",
"=",
"0e0",
"else",
":",
"sz",
"=",
"_np",
".",
"dot",
"(",
"n",
"*",
"r",
"[",
... | Effective rank of the TT-vector | [
"Effective",
"rank",
"of",
"the",
"TT",
"-",
"vector"
] | b440f6299a6338de4aea67f3d839d613f4ef1374 | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/core/vector.py#L127-L145 |
1,786 | oseledets/ttpy | tt/core/vector.py | vector.rmean | def rmean(self):
""" Calculates the mean rank of a TT-vector."""
if not _np.all(self.n):
return 0
# Solving quadratic equation ar^2 + br + c = 0;
a = _np.sum(self.n[1:-1])
b = self.n[0] + self.n[-1]
c = - _np.sum(self.n * self.r[1:] * self.r[:-1])
D = ... | python | def rmean(self):
if not _np.all(self.n):
return 0
# Solving quadratic equation ar^2 + br + c = 0;
a = _np.sum(self.n[1:-1])
b = self.n[0] + self.n[-1]
c = - _np.sum(self.n * self.r[1:] * self.r[:-1])
D = b ** 2 - 4 * a * c
r = 0.5 * (-b + _np.sqrt(D)) ... | [
"def",
"rmean",
"(",
"self",
")",
":",
"if",
"not",
"_np",
".",
"all",
"(",
"self",
".",
"n",
")",
":",
"return",
"0",
"# Solving quadratic equation ar^2 + br + c = 0;",
"a",
"=",
"_np",
".",
"sum",
"(",
"self",
".",
"n",
"[",
"1",
":",
"-",
"1",
"... | Calculates the mean rank of a TT-vector. | [
"Calculates",
"the",
"mean",
"rank",
"of",
"a",
"TT",
"-",
"vector",
"."
] | b440f6299a6338de4aea67f3d839d613f4ef1374 | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/core/vector.py#L568-L578 |
1,787 | oseledets/ttpy | tt/eigb/eigb.py | eigb | def eigb(A, y0, eps, rmax=150, nswp=20, max_full_size=1000, verb=1):
""" Approximate computation of minimal eigenvalues in tensor train format
This function uses alternating least-squares algorithm for the computation of several
minimal eigenvalues. If you want maximal eigenvalues, just send -A to the funct... | python | def eigb(A, y0, eps, rmax=150, nswp=20, max_full_size=1000, verb=1):
ry = y0.r.copy()
lam = tt_eigb.tt_block_eig.tt_eigb(y0.d, A.n, A.m, A.tt.r, A.tt.core, y0.core, ry, eps,
rmax, ry[y0.d], 0, nswp, max_full_size, verb)
y = tensor()
y.d = y0.d
y.n = A.n.copy()
... | [
"def",
"eigb",
"(",
"A",
",",
"y0",
",",
"eps",
",",
"rmax",
"=",
"150",
",",
"nswp",
"=",
"20",
",",
"max_full_size",
"=",
"1000",
",",
"verb",
"=",
"1",
")",
":",
"ry",
"=",
"y0",
".",
"r",
".",
"copy",
"(",
")",
"lam",
"=",
"tt_eigb",
".... | Approximate computation of minimal eigenvalues in tensor train format
This function uses alternating least-squares algorithm for the computation of several
minimal eigenvalues. If you want maximal eigenvalues, just send -A to the function.
:Reference:
S. V. Dolgov, B. N. Khoromskij, I. V. Oselede... | [
"Approximate",
"computation",
"of",
"minimal",
"eigenvalues",
"in",
"tensor",
"train",
"format",
"This",
"function",
"uses",
"alternating",
"least",
"-",
"squares",
"algorithm",
"for",
"the",
"computation",
"of",
"several",
"minimal",
"eigenvalues",
".",
"If",
"yo... | b440f6299a6338de4aea67f3d839d613f4ef1374 | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/eigb/eigb.py#L7-L65 |
1,788 | Infinidat/infi.systray | src/infi/systray/win32_adapter.py | encode_for_locale | def encode_for_locale(s):
"""
Encode text items for system locale. If encoding fails, fall back to ASCII.
"""
try:
return s.encode(LOCALE_ENCODING, 'ignore')
except (AttributeError, UnicodeDecodeError):
return s.decode('ascii', 'ignore').encode(LOCALE_ENCODING) | python | def encode_for_locale(s):
try:
return s.encode(LOCALE_ENCODING, 'ignore')
except (AttributeError, UnicodeDecodeError):
return s.decode('ascii', 'ignore').encode(LOCALE_ENCODING) | [
"def",
"encode_for_locale",
"(",
"s",
")",
":",
"try",
":",
"return",
"s",
".",
"encode",
"(",
"LOCALE_ENCODING",
",",
"'ignore'",
")",
"except",
"(",
"AttributeError",
",",
"UnicodeDecodeError",
")",
":",
"return",
"s",
".",
"decode",
"(",
"'ascii'",
",",... | Encode text items for system locale. If encoding fails, fall back to ASCII. | [
"Encode",
"text",
"items",
"for",
"system",
"locale",
".",
"If",
"encoding",
"fails",
"fall",
"back",
"to",
"ASCII",
"."
] | 209a6f8e5313122b35fdd2774aeceeaf9ce7c16d | https://github.com/Infinidat/infi.systray/blob/209a6f8e5313122b35fdd2774aeceeaf9ce7c16d/src/infi/systray/win32_adapter.py#L86-L93 |
1,789 | pbrady/fastcache | scripts/threadsafety.py | fib | def fib(n):
"""Terrible Fibonacci number generator."""
v = n.value
return v if v < 2 else fib2(PythonInt(v-1)) + fib(PythonInt(v-2)) | python | def fib(n):
v = n.value
return v if v < 2 else fib2(PythonInt(v-1)) + fib(PythonInt(v-2)) | [
"def",
"fib",
"(",
"n",
")",
":",
"v",
"=",
"n",
".",
"value",
"return",
"v",
"if",
"v",
"<",
"2",
"else",
"fib2",
"(",
"PythonInt",
"(",
"v",
"-",
"1",
")",
")",
"+",
"fib",
"(",
"PythonInt",
"(",
"v",
"-",
"2",
")",
")"
] | Terrible Fibonacci number generator. | [
"Terrible",
"Fibonacci",
"number",
"generator",
"."
] | c216def5d29808585123562b56a9a083ea337cad | https://github.com/pbrady/fastcache/blob/c216def5d29808585123562b56a9a083ea337cad/scripts/threadsafety.py#L43-L46 |
1,790 | aichaos/rivescript-python | rivescript/brain.py | Brain.format_message | def format_message(self, msg, botreply=False):
"""Format a user's message for safe processing.
This runs substitutions on the message and strips out any remaining
symbols (depending on UTF-8 mode).
:param str msg: The user's message.
:param bool botreply: Whether this formattin... | python | def format_message(self, msg, botreply=False):
# Make sure the string is Unicode for Python 2.
if sys.version_info[0] < 3 and isinstance(msg, str):
msg = msg.decode()
# Lowercase it.
msg = msg.lower()
# Run substitutions on it.
msg = self.substitute(msg, "su... | [
"def",
"format_message",
"(",
"self",
",",
"msg",
",",
"botreply",
"=",
"False",
")",
":",
"# Make sure the string is Unicode for Python 2.",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
"<",
"3",
"and",
"isinstance",
"(",
"msg",
",",
"str",
")",
":",
... | Format a user's message for safe processing.
This runs substitutions on the message and strips out any remaining
symbols (depending on UTF-8 mode).
:param str msg: The user's message.
:param bool botreply: Whether this formatting is being done for the
bot's last reply (e.g.... | [
"Format",
"a",
"user",
"s",
"message",
"for",
"safe",
"processing",
"."
] | b55c820cf02a194605fd66af1f070e239f84ed31 | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/brain.py#L104-L141 |
1,791 | aichaos/rivescript-python | rivescript/brain.py | Brain.do_expand_array | def do_expand_array(self, array_name, depth=0):
"""Do recurrent array expansion, returning a set of keywords.
Exception is thrown when there are cyclical dependencies between
arrays or if the ``@array`` name references an undefined array.
:param str array_name: The name of the array to... | python | def do_expand_array(self, array_name, depth=0):
if depth > self.master._depth:
raise Exception("deep recursion detected")
if not array_name in self.master._array:
raise Exception("array '%s' not defined" % (array_name))
ret = list(self.master._array[array_name])
f... | [
"def",
"do_expand_array",
"(",
"self",
",",
"array_name",
",",
"depth",
"=",
"0",
")",
":",
"if",
"depth",
">",
"self",
".",
"master",
".",
"_depth",
":",
"raise",
"Exception",
"(",
"\"deep recursion detected\"",
")",
"if",
"not",
"array_name",
"in",
"self... | Do recurrent array expansion, returning a set of keywords.
Exception is thrown when there are cyclical dependencies between
arrays or if the ``@array`` name references an undefined array.
:param str array_name: The name of the array to expand.
:param int depth: The recursion depth coun... | [
"Do",
"recurrent",
"array",
"expansion",
"returning",
"a",
"set",
"of",
"keywords",
"."
] | b55c820cf02a194605fd66af1f070e239f84ed31 | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/brain.py#L509-L531 |
1,792 | aichaos/rivescript-python | rivescript/brain.py | Brain.expand_array | def expand_array(self, array_name):
"""Expand variables and return a set of keywords.
:param str array_name: The name of the array to expand.
:return list: The final array contents.
Warning is issued when exceptions occur."""
ret = self.master._array[array_name] if array_name ... | python | def expand_array(self, array_name):
ret = self.master._array[array_name] if array_name in self.master._array else []
try:
ret = self.do_expand_array(array_name)
except Exception as e:
self.warn("Error expanding array '%s': %s" % (array_name, str(e)))
return ret | [
"def",
"expand_array",
"(",
"self",
",",
"array_name",
")",
":",
"ret",
"=",
"self",
".",
"master",
".",
"_array",
"[",
"array_name",
"]",
"if",
"array_name",
"in",
"self",
".",
"master",
".",
"_array",
"else",
"[",
"]",
"try",
":",
"ret",
"=",
"self... | Expand variables and return a set of keywords.
:param str array_name: The name of the array to expand.
:return list: The final array contents.
Warning is issued when exceptions occur. | [
"Expand",
"variables",
"and",
"return",
"a",
"set",
"of",
"keywords",
"."
] | b55c820cf02a194605fd66af1f070e239f84ed31 | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/brain.py#L533-L546 |
1,793 | aichaos/rivescript-python | rivescript/brain.py | Brain.substitute | def substitute(self, msg, kind):
"""Run a kind of substitution on a message.
:param str msg: The message to run substitutions against.
:param str kind: The kind of substitution to run,
one of ``subs`` or ``person``.
"""
# Safety checking.
if 'lists' not in s... | python | def substitute(self, msg, kind):
# Safety checking.
if 'lists' not in self.master._sorted:
raise RepliesNotSortedError("You must call sort_replies() once you are done loading RiveScript documents")
if kind not in self.master._sorted["lists"]:
raise RepliesNotSortedError("... | [
"def",
"substitute",
"(",
"self",
",",
"msg",
",",
"kind",
")",
":",
"# Safety checking.",
"if",
"'lists'",
"not",
"in",
"self",
".",
"master",
".",
"_sorted",
":",
"raise",
"RepliesNotSortedError",
"(",
"\"You must call sort_replies() once you are done loading RiveSc... | Run a kind of substitution on a message.
:param str msg: The message to run substitutions against.
:param str kind: The kind of substitution to run,
one of ``subs`` or ``person``. | [
"Run",
"a",
"kind",
"of",
"substitution",
"on",
"a",
"message",
"."
] | b55c820cf02a194605fd66af1f070e239f84ed31 | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/brain.py#L784-L830 |
1,794 | aichaos/rivescript-python | rivescript/python.py | PyRiveObjects.load | def load(self, name, code):
"""Prepare a Python code object given by the RiveScript interpreter.
:param str name: The name of the Python object macro.
:param []str code: The Python source code for the object macro.
"""
# We need to make a dynamic Python method.
source = ... | python | def load(self, name, code):
# We need to make a dynamic Python method.
source = "def RSOBJ(rs, args):\n"
for line in code:
source = source + "\t" + line + "\n"
source += "self._objects[name] = RSOBJ\n"
try:
exec(source)
# self._objects[name] ... | [
"def",
"load",
"(",
"self",
",",
"name",
",",
"code",
")",
":",
"# We need to make a dynamic Python method.",
"source",
"=",
"\"def RSOBJ(rs, args):\\n\"",
"for",
"line",
"in",
"code",
":",
"source",
"=",
"source",
"+",
"\"\\t\"",
"+",
"line",
"+",
"\"\\n\"",
... | Prepare a Python code object given by the RiveScript interpreter.
:param str name: The name of the Python object macro.
:param []str code: The Python source code for the object macro. | [
"Prepare",
"a",
"Python",
"code",
"object",
"given",
"by",
"the",
"RiveScript",
"interpreter",
"."
] | b55c820cf02a194605fd66af1f070e239f84ed31 | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/python.py#L41-L59 |
1,795 | aichaos/rivescript-python | rivescript/python.py | PyRiveObjects.call | def call(self, rs, name, user, fields):
"""Invoke a previously loaded object.
:param RiveScript rs: the parent RiveScript instance.
:param str name: The name of the object macro to be called.
:param str user: The user ID invoking the object macro.
:param []str fields: Array of w... | python | def call(self, rs, name, user, fields):
# Call the dynamic method.
if name not in self._objects:
return '[ERR: Object Not Found]'
func = self._objects[name]
reply = ''
try:
reply = func(rs, fields)
if reply is None:
reply = ''
... | [
"def",
"call",
"(",
"self",
",",
"rs",
",",
"name",
",",
"user",
",",
"fields",
")",
":",
"# Call the dynamic method.",
"if",
"name",
"not",
"in",
"self",
".",
"_objects",
":",
"return",
"'[ERR: Object Not Found]'",
"func",
"=",
"self",
".",
"_objects",
"[... | Invoke a previously loaded object.
:param RiveScript rs: the parent RiveScript instance.
:param str name: The name of the object macro to be called.
:param str user: The user ID invoking the object macro.
:param []str fields: Array of words sent as the object's arguments.
:retu... | [
"Invoke",
"a",
"previously",
"loaded",
"object",
"."
] | b55c820cf02a194605fd66af1f070e239f84ed31 | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/python.py#L61-L82 |
1,796 | aichaos/rivescript-python | rivescript/inheritance.py | get_topic_triggers | def get_topic_triggers(rs, topic, thats, depth=0, inheritance=0, inherited=False):
"""Recursively scan a topic and return a list of all triggers.
Arguments:
rs (RiveScript): A reference to the parent RiveScript instance.
topic (str): The original topic name.
thats (bool): Are we getting... | python | def get_topic_triggers(rs, topic, thats, depth=0, inheritance=0, inherited=False):
# Break if we're in too deep.
if depth > rs._depth:
rs._warn("Deep recursion while scanning topic inheritance")
# Keep in mind here that there is a difference between 'includes' and
# 'inherits' -- topics that in... | [
"def",
"get_topic_triggers",
"(",
"rs",
",",
"topic",
",",
"thats",
",",
"depth",
"=",
"0",
",",
"inheritance",
"=",
"0",
",",
"inherited",
"=",
"False",
")",
":",
"# Break if we're in too deep.",
"if",
"depth",
">",
"rs",
".",
"_depth",
":",
"rs",
".",
... | Recursively scan a topic and return a list of all triggers.
Arguments:
rs (RiveScript): A reference to the parent RiveScript instance.
topic (str): The original topic name.
thats (bool): Are we getting triggers for 'previous' replies?
depth (int): Recursion step counter.
inh... | [
"Recursively",
"scan",
"a",
"topic",
"and",
"return",
"a",
"list",
"of",
"all",
"triggers",
"."
] | b55c820cf02a194605fd66af1f070e239f84ed31 | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/inheritance.py#L8-L113 |
1,797 | aichaos/rivescript-python | rivescript/utils.py | word_count | def word_count(trigger, all=False):
"""Count the words that aren't wildcards or options in a trigger.
:param str trigger: The trigger to count words for.
:param bool all: Count purely based on whitespace separators, or
consider wildcards not to be their own words.
:return int: The word count."... | python | def word_count(trigger, all=False):
words = []
if all:
words = re.split(RE.ws, trigger)
else:
words = re.split(RE.wilds_and_optionals, trigger)
wc = 0 # Word count
for word in words:
if len(word) > 0:
wc += 1
return wc | [
"def",
"word_count",
"(",
"trigger",
",",
"all",
"=",
"False",
")",
":",
"words",
"=",
"[",
"]",
"if",
"all",
":",
"words",
"=",
"re",
".",
"split",
"(",
"RE",
".",
"ws",
",",
"trigger",
")",
"else",
":",
"words",
"=",
"re",
".",
"split",
"(",
... | Count the words that aren't wildcards or options in a trigger.
:param str trigger: The trigger to count words for.
:param bool all: Count purely based on whitespace separators, or
consider wildcards not to be their own words.
:return int: The word count. | [
"Count",
"the",
"words",
"that",
"aren",
"t",
"wildcards",
"or",
"options",
"in",
"a",
"trigger",
"."
] | b55c820cf02a194605fd66af1f070e239f84ed31 | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/utils.py#L14-L33 |
1,798 | aichaos/rivescript-python | eg/perl-objects/perl.py | PerlObject.load | def load(self, name, code):
"""Prepare a Perl code object given by the RS interpreter."""
source = "\n".join(code)
self._objects[name] = source | python | def load(self, name, code):
source = "\n".join(code)
self._objects[name] = source | [
"def",
"load",
"(",
"self",
",",
"name",
",",
"code",
")",
":",
"source",
"=",
"\"\\n\"",
".",
"join",
"(",
"code",
")",
"self",
".",
"_objects",
"[",
"name",
"]",
"=",
"source"
] | Prepare a Perl code object given by the RS interpreter. | [
"Prepare",
"a",
"Perl",
"code",
"object",
"given",
"by",
"the",
"RS",
"interpreter",
"."
] | b55c820cf02a194605fd66af1f070e239f84ed31 | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/eg/perl-objects/perl.py#L13-L17 |
1,799 | aichaos/rivescript-python | eg/twilio/app.py | hello_rivescript | def hello_rivescript():
"""Receive an inbound SMS and send a reply from RiveScript."""
from_number = request.values.get("From", "unknown")
message = request.values.get("Body")
reply = "(Internal error)"
# Get a reply from RiveScript.
if message:
reply = bot.reply(from_number,... | python | def hello_rivescript():
from_number = request.values.get("From", "unknown")
message = request.values.get("Body")
reply = "(Internal error)"
# Get a reply from RiveScript.
if message:
reply = bot.reply(from_number, message)
# Send the response.
resp = twilio.twiml.Response... | [
"def",
"hello_rivescript",
"(",
")",
":",
"from_number",
"=",
"request",
".",
"values",
".",
"get",
"(",
"\"From\"",
",",
"\"unknown\"",
")",
"message",
"=",
"request",
".",
"values",
".",
"get",
"(",
"\"Body\"",
")",
"reply",
"=",
"\"(Internal error)\"",
... | Receive an inbound SMS and send a reply from RiveScript. | [
"Receive",
"an",
"inbound",
"SMS",
"and",
"send",
"a",
"reply",
"from",
"RiveScript",
"."
] | b55c820cf02a194605fd66af1f070e239f84ed31 | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/eg/twilio/app.py#L28-L42 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.