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
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | 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
"""
if k == "setup":
return from_commandline(v, classname=to_commandline(datagen.DataGenerator()))
return super(DataGenerator, self).from_config(k, v) | 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",
"super",
"(",
"DataGenerator",
",",
"self",
")",
".",
"from_config",
"(",
"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 | [
"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/ClassifierSplitEvaluator", "()V")
else:
speval = javabridge.make_instance("weka/experiment/RegressionSplitEvaluator", "()V")
classifier = javabridge.call(speval, "getClassifier", "()Lweka/classifiers/Classifier;")
return speval, classifier | 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, "getClassifier", "()Lweka/classifiers/Classifier;")
return speval, classifier | [
"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",
",",
"\"getClassifier\"",
",",
"\"()Lweka/classifiers/Classifier;\"",
")",
"return",
"speval",
",",
"classifier"
] | 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")))
javabridge.call(
self.jobject, "setUsePropertyIterator", "(Z)V", True)
javabridge.call(
self.jobject, "setRunLower", "(I)V", 1)
javabridge.call(
self.jobject, "setRunUpper", "(I)V", self.runs)
# setup result producer
rproducer, prop_path = self.configure_resultproducer()
javabridge.call(
self.jobject, "setResultProducer", "(Lweka/experiment/ResultProducer;)V", rproducer)
javabridge.call(
self.jobject, "setPropertyPath", "([Lweka/experiment/PropertyNode;)V", prop_path)
# classifiers
classifiers = javabridge.get_env().make_object_array(
len(self.classifiers), javabridge.get_env().find_class("weka/classifiers/Classifier"))
for i, classifier in enumerate(self.classifiers):
if type(classifier) is Classifier:
javabridge.get_env().set_object_array_element(
classifiers, i, classifier.jobject)
else:
javabridge.get_env().set_object_array_element(
classifiers, i, from_commandline(classifier).jobject)
javabridge.call(
self.jobject, "setPropertyArray", "(Ljava/lang/Object;)V",
classifiers)
# datasets
datasets = javabridge.make_instance("javax/swing/DefaultListModel", "()V")
for dataset in self.datasets:
f = javabridge.make_instance("java/io/File", "(Ljava/lang/String;)V", dataset)
javabridge.call(datasets, "addElement", "(Ljava/lang/Object;)V", f)
javabridge.call(
self.jobject, "setDatasets", "(Ljavax/swing/DefaultListModel;)V", datasets)
# output file
if str(self.result).lower().endswith(".arff"):
rlistener = javabridge.make_instance("weka/experiment/InstancesResultListener", "()V")
elif str(self.result).lower().endswith(".csv"):
rlistener = javabridge.make_instance("weka/experiment/CSVResultListener", "()V")
else:
raise Exception("Unhandled output format for results: " + self.result)
rfile = javabridge.make_instance("java/io/File", "(Ljava/lang/String;)V", self.result)
javabridge.call(
rlistener, "setOutputFile", "(Ljava/io/File;)V", rfile)
javabridge.call(
self.jobject, "setResultListener", "(Lweka/experiment/ResultListener;)V", rlistener) | 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, "setUsePropertyIterator", "(Z)V", True)
javabridge.call(
self.jobject, "setRunLower", "(I)V", 1)
javabridge.call(
self.jobject, "setRunUpper", "(I)V", self.runs)
# setup result producer
rproducer, prop_path = self.configure_resultproducer()
javabridge.call(
self.jobject, "setResultProducer", "(Lweka/experiment/ResultProducer;)V", rproducer)
javabridge.call(
self.jobject, "setPropertyPath", "([Lweka/experiment/PropertyNode;)V", prop_path)
# classifiers
classifiers = javabridge.get_env().make_object_array(
len(self.classifiers), javabridge.get_env().find_class("weka/classifiers/Classifier"))
for i, classifier in enumerate(self.classifiers):
if type(classifier) is Classifier:
javabridge.get_env().set_object_array_element(
classifiers, i, classifier.jobject)
else:
javabridge.get_env().set_object_array_element(
classifiers, i, from_commandline(classifier).jobject)
javabridge.call(
self.jobject, "setPropertyArray", "(Ljava/lang/Object;)V",
classifiers)
# datasets
datasets = javabridge.make_instance("javax/swing/DefaultListModel", "()V")
for dataset in self.datasets:
f = javabridge.make_instance("java/io/File", "(Ljava/lang/String;)V", dataset)
javabridge.call(datasets, "addElement", "(Ljava/lang/Object;)V", f)
javabridge.call(
self.jobject, "setDatasets", "(Ljavax/swing/DefaultListModel;)V", datasets)
# output file
if str(self.result).lower().endswith(".arff"):
rlistener = javabridge.make_instance("weka/experiment/InstancesResultListener", "()V")
elif str(self.result).lower().endswith(".csv"):
rlistener = javabridge.make_instance("weka/experiment/CSVResultListener", "()V")
else:
raise Exception("Unhandled output format for results: " + self.result)
rfile = javabridge.make_instance("java/io/File", "(Ljava/lang/String;)V", self.result)
javabridge.call(
rlistener, "setOutputFile", "(Ljava/io/File;)V", rfile)
javabridge.call(
self.jobject, "setResultListener", "(Lweka/experiment/ResultListener;)V", rlistener) | [
"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",
",",
"\"setUsePropertyIterator\"",
",",
"\"(Z)V\"",
",",
"True",
")",
"javabridge",
".",
"call",
"(",
"self",
".",
"jobject",
",",
"\"setRunLower\"",
",",
"\"(I)V\"",
",",
"1",
")",
"javabridge",
".",
"call",
"(",
"self",
".",
"jobject",
",",
"\"setRunUpper\"",
",",
"\"(I)V\"",
",",
"self",
".",
"runs",
")",
"# setup result producer",
"rproducer",
",",
"prop_path",
"=",
"self",
".",
"configure_resultproducer",
"(",
")",
"javabridge",
".",
"call",
"(",
"self",
".",
"jobject",
",",
"\"setResultProducer\"",
",",
"\"(Lweka/experiment/ResultProducer;)V\"",
",",
"rproducer",
")",
"javabridge",
".",
"call",
"(",
"self",
".",
"jobject",
",",
"\"setPropertyPath\"",
",",
"\"([Lweka/experiment/PropertyNode;)V\"",
",",
"prop_path",
")",
"# classifiers",
"classifiers",
"=",
"javabridge",
".",
"get_env",
"(",
")",
".",
"make_object_array",
"(",
"len",
"(",
"self",
".",
"classifiers",
")",
",",
"javabridge",
".",
"get_env",
"(",
")",
".",
"find_class",
"(",
"\"weka/classifiers/Classifier\"",
")",
")",
"for",
"i",
",",
"classifier",
"in",
"enumerate",
"(",
"self",
".",
"classifiers",
")",
":",
"if",
"type",
"(",
"classifier",
")",
"is",
"Classifier",
":",
"javabridge",
".",
"get_env",
"(",
")",
".",
"set_object_array_element",
"(",
"classifiers",
",",
"i",
",",
"classifier",
".",
"jobject",
")",
"else",
":",
"javabridge",
".",
"get_env",
"(",
")",
".",
"set_object_array_element",
"(",
"classifiers",
",",
"i",
",",
"from_commandline",
"(",
"classifier",
")",
".",
"jobject",
")",
"javabridge",
".",
"call",
"(",
"self",
".",
"jobject",
",",
"\"setPropertyArray\"",
",",
"\"(Ljava/lang/Object;)V\"",
",",
"classifiers",
")",
"# datasets",
"datasets",
"=",
"javabridge",
".",
"make_instance",
"(",
"\"javax/swing/DefaultListModel\"",
",",
"\"()V\"",
")",
"for",
"dataset",
"in",
"self",
".",
"datasets",
":",
"f",
"=",
"javabridge",
".",
"make_instance",
"(",
"\"java/io/File\"",
",",
"\"(Ljava/lang/String;)V\"",
",",
"dataset",
")",
"javabridge",
".",
"call",
"(",
"datasets",
",",
"\"addElement\"",
",",
"\"(Ljava/lang/Object;)V\"",
",",
"f",
")",
"javabridge",
".",
"call",
"(",
"self",
".",
"jobject",
",",
"\"setDatasets\"",
",",
"\"(Ljavax/swing/DefaultListModel;)V\"",
",",
"datasets",
")",
"# output file",
"if",
"str",
"(",
"self",
".",
"result",
")",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"\".arff\"",
")",
":",
"rlistener",
"=",
"javabridge",
".",
"make_instance",
"(",
"\"weka/experiment/InstancesResultListener\"",
",",
"\"()V\"",
")",
"elif",
"str",
"(",
"self",
".",
"result",
")",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"\".csv\"",
")",
":",
"rlistener",
"=",
"javabridge",
".",
"make_instance",
"(",
"\"weka/experiment/CSVResultListener\"",
",",
"\"()V\"",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"Unhandled output format for results: \"",
"+",
"self",
".",
"result",
")",
"rfile",
"=",
"javabridge",
".",
"make_instance",
"(",
"\"java/io/File\"",
",",
"\"(Ljava/lang/String;)V\"",
",",
"self",
".",
"result",
")",
"javabridge",
".",
"call",
"(",
"rlistener",
",",
"\"setOutputFile\"",
",",
"\"(Ljava/io/File;)V\"",
",",
"rfile",
")",
"javabridge",
".",
"call",
"(",
"self",
".",
"jobject",
",",
"\"setResultListener\"",
",",
"\"(Lweka/experiment/ResultListener;)V\"",
",",
"rlistener",
")"
] | 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.call(self.jobject, "postProcess", "()V") | 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",
".",
"call",
"(",
"self",
".",
"jobject",
",",
"\"runExperiment\"",
",",
"\"()V\"",
")",
"logger",
".",
"info",
"(",
"\"Finished...\"",
")",
"javabridge",
".",
"call",
"(",
"self",
".",
"jobject",
",",
"\"postProcess\"",
",",
"\"()V\"",
")"
] | 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/Experiment", "read", "(Ljava/lang/String;)Lweka/experiment/Experiment;",
filename)
return Experiment(jobject=jobject) | 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",
"(",
"jobject",
"=",
"jobject",
")"
] | 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.call(rproducer, "setRandomizeData", "(Z)V", not self.preserve_order)
javabridge.call(rproducer, "setTrainPercent", "(D)V", self.percentage)
speval, classifier = self.configure_splitevaluator()
javabridge.call(rproducer, "setSplitEvaluator", "(Lweka/experiment/SplitEvaluator;)V", speval)
prop_path = javabridge.get_env().make_object_array(
2, javabridge.get_env().find_class("weka/experiment/PropertyNode"))
cls = javabridge.get_env().find_class("weka/experiment/RandomSplitResultProducer")
desc = javabridge.make_instance(
"java/beans/PropertyDescriptor", "(Ljava/lang/String;Ljava/lang/Class;)V", "splitEvaluator", cls)
node = javabridge.make_instance(
"weka/experiment/PropertyNode", "(Ljava/lang/Object;Ljava/beans/PropertyDescriptor;Ljava/lang/Class;)V",
speval, desc, cls)
javabridge.get_env().set_object_array_element(prop_path, 0, node)
cls = javabridge.get_env().get_object_class(speval)
desc = javabridge.make_instance(
"java/beans/PropertyDescriptor", "(Ljava/lang/String;Ljava/lang/Class;)V", "classifier", cls)
node = javabridge.make_instance(
"weka/experiment/PropertyNode", "(Ljava/lang/Object;Ljava/beans/PropertyDescriptor;Ljava/lang/Class;)V",
javabridge.call(speval, "getClass", "()Ljava/lang/Class;"), desc, cls)
javabridge.get_env().set_object_array_element(prop_path, 1, node)
return rproducer, prop_path | 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, classifier = self.configure_splitevaluator()
javabridge.call(rproducer, "setSplitEvaluator", "(Lweka/experiment/SplitEvaluator;)V", speval)
prop_path = javabridge.get_env().make_object_array(
2, javabridge.get_env().find_class("weka/experiment/PropertyNode"))
cls = javabridge.get_env().find_class("weka/experiment/RandomSplitResultProducer")
desc = javabridge.make_instance(
"java/beans/PropertyDescriptor", "(Ljava/lang/String;Ljava/lang/Class;)V", "splitEvaluator", cls)
node = javabridge.make_instance(
"weka/experiment/PropertyNode", "(Ljava/lang/Object;Ljava/beans/PropertyDescriptor;Ljava/lang/Class;)V",
speval, desc, cls)
javabridge.get_env().set_object_array_element(prop_path, 0, node)
cls = javabridge.get_env().get_object_class(speval)
desc = javabridge.make_instance(
"java/beans/PropertyDescriptor", "(Ljava/lang/String;Ljava/lang/Class;)V", "classifier", cls)
node = javabridge.make_instance(
"weka/experiment/PropertyNode", "(Ljava/lang/Object;Ljava/beans/PropertyDescriptor;Ljava/lang/Class;)V",
javabridge.call(speval, "getClass", "()Ljava/lang/Class;"), desc, cls)
javabridge.get_env().set_object_array_element(prop_path, 1, node)
return rproducer, prop_path | [
"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",
",",
"classifier",
"=",
"self",
".",
"configure_splitevaluator",
"(",
")",
"javabridge",
".",
"call",
"(",
"rproducer",
",",
"\"setSplitEvaluator\"",
",",
"\"(Lweka/experiment/SplitEvaluator;)V\"",
",",
"speval",
")",
"prop_path",
"=",
"javabridge",
".",
"get_env",
"(",
")",
".",
"make_object_array",
"(",
"2",
",",
"javabridge",
".",
"get_env",
"(",
")",
".",
"find_class",
"(",
"\"weka/experiment/PropertyNode\"",
")",
")",
"cls",
"=",
"javabridge",
".",
"get_env",
"(",
")",
".",
"find_class",
"(",
"\"weka/experiment/RandomSplitResultProducer\"",
")",
"desc",
"=",
"javabridge",
".",
"make_instance",
"(",
"\"java/beans/PropertyDescriptor\"",
",",
"\"(Ljava/lang/String;Ljava/lang/Class;)V\"",
",",
"\"splitEvaluator\"",
",",
"cls",
")",
"node",
"=",
"javabridge",
".",
"make_instance",
"(",
"\"weka/experiment/PropertyNode\"",
",",
"\"(Ljava/lang/Object;Ljava/beans/PropertyDescriptor;Ljava/lang/Class;)V\"",
",",
"speval",
",",
"desc",
",",
"cls",
")",
"javabridge",
".",
"get_env",
"(",
")",
".",
"set_object_array_element",
"(",
"prop_path",
",",
"0",
",",
"node",
")",
"cls",
"=",
"javabridge",
".",
"get_env",
"(",
")",
".",
"get_object_class",
"(",
"speval",
")",
"desc",
"=",
"javabridge",
".",
"make_instance",
"(",
"\"java/beans/PropertyDescriptor\"",
",",
"\"(Ljava/lang/String;Ljava/lang/Class;)V\"",
",",
"\"classifier\"",
",",
"cls",
")",
"node",
"=",
"javabridge",
".",
"make_instance",
"(",
"\"weka/experiment/PropertyNode\"",
",",
"\"(Ljava/lang/Object;Ljava/beans/PropertyDescriptor;Ljava/lang/Class;)V\"",
",",
"javabridge",
".",
"call",
"(",
"speval",
",",
"\"getClass\"",
",",
"\"()Ljava/lang/Class;\"",
")",
",",
"desc",
",",
"cls",
")",
"javabridge",
".",
"get_env",
"(",
")",
".",
"set_object_array_element",
"(",
"prop_path",
",",
"1",
",",
"node",
")",
"return",
"rproducer",
",",
"prop_path"
] | 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', 'data', 'format'],
'record', 'Importing record but content is not record'),
'metadata': (['format'], 'metadata',
'Requesting metadata but content != metadata'),
'exp_file': (['action', 'record', 'field'], 'file',
'Exporting file but content is not file'),
'imp_file': (['action', 'record', 'field'], 'file',
'Importing file but content is not file'),
'del_file': (['action', 'record', 'field'], 'file',
'Deleteing file but content is not file'),
'exp_event': (['format'], 'event',
'Exporting events but content is not event'),
'exp_arm': (['format'], 'arm',
'Exporting arms but content is not arm'),
'exp_fem': (['format'], 'formEventMapping',
'Exporting form-event mappings but content != formEventMapping'),
'exp_user': (['format'], 'user',
'Exporting users but content is not user'),
'exp_survey_participant_list': (['instrument'], 'participantList',
'Exporting Survey Participant List but content != participantList'),
'version': (['format'], 'version',
'Requesting version but content != version')
}
extra, req_content, err_msg = valid_data[self.type]
required.extend(extra)
required = set(required)
pl_keys = set(self.payload.keys())
# if req is not subset of payload keys, this call is wrong
if not set(required) <= pl_keys:
# what is not in pl_keys?
not_pre = required - pl_keys
raise RCAPIError("Required keys: %s" % ', '.join(not_pre))
# Check content, raise with err_msg if not good
try:
if self.payload['content'] != req_content:
raise RCAPIError(err_msg)
except KeyError:
raise RCAPIError('content not in payload') | 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 record but content is not record'),
'metadata': (['format'], 'metadata',
'Requesting metadata but content != metadata'),
'exp_file': (['action', 'record', 'field'], 'file',
'Exporting file but content is not file'),
'imp_file': (['action', 'record', 'field'], 'file',
'Importing file but content is not file'),
'del_file': (['action', 'record', 'field'], 'file',
'Deleteing file but content is not file'),
'exp_event': (['format'], 'event',
'Exporting events but content is not event'),
'exp_arm': (['format'], 'arm',
'Exporting arms but content is not arm'),
'exp_fem': (['format'], 'formEventMapping',
'Exporting form-event mappings but content != formEventMapping'),
'exp_user': (['format'], 'user',
'Exporting users but content is not user'),
'exp_survey_participant_list': (['instrument'], 'participantList',
'Exporting Survey Participant List but content != participantList'),
'version': (['format'], 'version',
'Requesting version but content != version')
}
extra, req_content, err_msg = valid_data[self.type]
required.extend(extra)
required = set(required)
pl_keys = set(self.payload.keys())
# if req is not subset of payload keys, this call is wrong
if not set(required) <= pl_keys:
# what is not in pl_keys?
not_pre = required - pl_keys
raise RCAPIError("Required keys: %s" % ', '.join(not_pre))
# Check content, raise with err_msg if not good
try:
if self.payload['content'] != req_content:
raise RCAPIError(err_msg)
except KeyError:
raise RCAPIError('content not in payload') | [
"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 record but content is not record'",
")",
",",
"'metadata'",
":",
"(",
"[",
"'format'",
"]",
",",
"'metadata'",
",",
"'Requesting metadata but content != metadata'",
")",
",",
"'exp_file'",
":",
"(",
"[",
"'action'",
",",
"'record'",
",",
"'field'",
"]",
",",
"'file'",
",",
"'Exporting file but content is not file'",
")",
",",
"'imp_file'",
":",
"(",
"[",
"'action'",
",",
"'record'",
",",
"'field'",
"]",
",",
"'file'",
",",
"'Importing file but content is not file'",
")",
",",
"'del_file'",
":",
"(",
"[",
"'action'",
",",
"'record'",
",",
"'field'",
"]",
",",
"'file'",
",",
"'Deleteing file but content is not file'",
")",
",",
"'exp_event'",
":",
"(",
"[",
"'format'",
"]",
",",
"'event'",
",",
"'Exporting events but content is not event'",
")",
",",
"'exp_arm'",
":",
"(",
"[",
"'format'",
"]",
",",
"'arm'",
",",
"'Exporting arms but content is not arm'",
")",
",",
"'exp_fem'",
":",
"(",
"[",
"'format'",
"]",
",",
"'formEventMapping'",
",",
"'Exporting form-event mappings but content != formEventMapping'",
")",
",",
"'exp_user'",
":",
"(",
"[",
"'format'",
"]",
",",
"'user'",
",",
"'Exporting users but content is not user'",
")",
",",
"'exp_survey_participant_list'",
":",
"(",
"[",
"'instrument'",
"]",
",",
"'participantList'",
",",
"'Exporting Survey Participant List but content != participantList'",
")",
",",
"'version'",
":",
"(",
"[",
"'format'",
"]",
",",
"'version'",
",",
"'Requesting version but content != version'",
")",
"}",
"extra",
",",
"req_content",
",",
"err_msg",
"=",
"valid_data",
"[",
"self",
".",
"type",
"]",
"required",
".",
"extend",
"(",
"extra",
")",
"required",
"=",
"set",
"(",
"required",
")",
"pl_keys",
"=",
"set",
"(",
"self",
".",
"payload",
".",
"keys",
"(",
")",
")",
"# if req is not subset of payload keys, this call is wrong",
"if",
"not",
"set",
"(",
"required",
")",
"<=",
"pl_keys",
":",
"# what is not in pl_keys?",
"not_pre",
"=",
"required",
"-",
"pl_keys",
"raise",
"RCAPIError",
"(",
"\"Required keys: %s\"",
"%",
"', '",
".",
"join",
"(",
"not_pre",
")",
")",
"# Check content, raise with err_msg if not good",
"try",
":",
"if",
"self",
".",
"payload",
"[",
"'content'",
"]",
"!=",
"req_content",
":",
"raise",
"RCAPIError",
"(",
"err_msg",
")",
"except",
"KeyError",
":",
"raise",
"RCAPIError",
"(",
"'content not in payload'",
")"
] | 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',
else return raw string (ie format=='csv'|'xml')
"""
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 | 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",
")",
"content",
"=",
"self",
".",
"get_content",
"(",
"r",
")",
"return",
"content",
",",
"r",
".",
"headers"
] | 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'|'xml') | [
"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':
content = {}
# Decode
try:
# Watch out for bad/empty json
content = json.loads(r.text, strict=False)
except ValueError as e:
if not self.expect_empty_json():
# reraise for requests that shouldn't send empty json
raise ValueError(e)
finally:
return content
else:
return r.text | 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
try:
# Watch out for bad/empty json
content = json.loads(r.text, strict=False)
except ValueError as e:
if not self.expect_empty_json():
# reraise for requests that shouldn't send empty json
raise ValueError(e)
finally:
return content
else:
return r.text | [
"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",
"try",
":",
"# Watch out for bad/empty json",
"content",
"=",
"json",
".",
"loads",
"(",
"r",
".",
"text",
",",
"strict",
"=",
"False",
")",
"except",
"ValueError",
"as",
"e",
":",
"if",
"not",
"self",
".",
"expect_empty_json",
"(",
")",
":",
"# reraise for requests that shouldn't send empty json",
"raise",
"ValueError",
"(",
"e",
")",
"finally",
":",
"return",
"content",
"else",
":",
"return",
"r",
".",
"text"
] | 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 user see the
(hopefully helpful) error message"""
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) | 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/rfc2616/rfc2616-sec10.html",
"# specifically 10.5",
"if",
"500",
"<=",
"r",
".",
"status_code",
"<",
"600",
":",
"raise",
"RedcapError",
"(",
"r",
".",
"content",
")"
] | 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) error message | [
"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 d | 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",
"content",
"not",
"in",
"[",
"'metadata'",
",",
"'file'",
"]",
":",
"d",
"[",
"'type'",
"]",
"=",
"rec_type",
"return",
"d"
] | 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 :
attribute list from each field
"""
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 | 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",
"KeyError",
"(",
"\"Key not found in metadata\"",
")",
"return",
"filtered"
] | 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'``
Return the form event mappings in native objects,
csv or xml, ``'df''`` will return a ``pandas.DataFrame``
df_kwargs : dict
Passed to pandas.read_csv to control construction of
returned DataFrame
Returns
-------
fem : list, str, ``pandas.DataFrame``
form-event mapping for the project
"""
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 key, data in zip(str_add, to_add):
if data:
pl[key] = ','.join(data)
response, _ = self._call_api(pl, 'exp_fem')
if format in ('json', 'csv', 'xml'):
return response
elif format == 'df':
if not df_kwargs:
return read_csv(StringIO(response))
else:
return read_csv(StringIO(response), **df_kwargs) | 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 key, data in zip(str_add, to_add):
if data:
pl[key] = ','.join(data)
response, _ = self._call_api(pl, 'exp_fem')
if format in ('json', 'csv', 'xml'):
return response
elif format == 'df':
if not df_kwargs:
return read_csv(StringIO(response))
else:
return read_csv(StringIO(response), **df_kwargs) | [
"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",
"key",
",",
"data",
"in",
"zip",
"(",
"str_add",
",",
"to_add",
")",
":",
"if",
"data",
":",
"pl",
"[",
"key",
"]",
"=",
"','",
".",
"join",
"(",
"data",
")",
"response",
",",
"_",
"=",
"self",
".",
"_call_api",
"(",
"pl",
",",
"'exp_fem'",
")",
"if",
"format",
"in",
"(",
"'json'",
",",
"'csv'",
",",
"'xml'",
")",
":",
"return",
"response",
"elif",
"format",
"==",
"'df'",
":",
"if",
"not",
"df_kwargs",
":",
"return",
"read_csv",
"(",
"StringIO",
"(",
"response",
")",
")",
"else",
":",
"return",
"read_csv",
"(",
"StringIO",
"(",
"response",
")",
",",
"*",
"*",
"df_kwargs",
")"
] | 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''`` will return a ``pandas.DataFrame``
df_kwargs : dict
Passed to pandas.read_csv to control construction of
returned DataFrame
Returns
-------
fem : list, str, ``pandas.DataFrame``
form-event mapping for the project | [
"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 these forms
format : (``'json'``), ``'csv'``, ``'xml'``, ``'df'``
Return the metadata in native objects, csv or xml.
``'df'`` will return a ``pandas.DataFrame``.
df_kwargs : dict
Passed to ``pandas.read_csv`` to control construction of
returned DataFrame.
by default ``{'index_col': 'field_name'}``
Returns
-------
metadata : list, str, ``pandas.DataFrame``
metadata sttructure for the project.
"""
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]
str_add = ['fields', 'forms']
for key, data in zip(str_add, to_add):
if data:
pl[key] = ','.join(data)
response, _ = self._call_api(pl, 'metadata')
if format in ('json', 'csv', 'xml'):
return response
elif format == 'df':
if not df_kwargs:
df_kwargs = {'index_col': 'field_name'}
return read_csv(StringIO(response), **df_kwargs) | 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]
str_add = ['fields', 'forms']
for key, data in zip(str_add, to_add):
if data:
pl[key] = ','.join(data)
response, _ = self._call_api(pl, 'metadata')
if format in ('json', 'csv', 'xml'):
return response
elif format == 'df':
if not df_kwargs:
df_kwargs = {'index_col': 'field_name'}
return read_csv(StringIO(response), **df_kwargs) | [
"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",
"]",
"str_add",
"=",
"[",
"'fields'",
",",
"'forms'",
"]",
"for",
"key",
",",
"data",
"in",
"zip",
"(",
"str_add",
",",
"to_add",
")",
":",
"if",
"data",
":",
"pl",
"[",
"key",
"]",
"=",
"','",
".",
"join",
"(",
"data",
")",
"response",
",",
"_",
"=",
"self",
".",
"_call_api",
"(",
"pl",
",",
"'metadata'",
")",
"if",
"format",
"in",
"(",
"'json'",
",",
"'csv'",
",",
"'xml'",
")",
":",
"return",
"response",
"elif",
"format",
"==",
"'df'",
":",
"if",
"not",
"df_kwargs",
":",
"df_kwargs",
"=",
"{",
"'index_col'",
":",
"'field_name'",
"}",
"return",
"read_csv",
"(",
"StringIO",
"(",
"response",
")",
",",
"*",
"*",
"df_kwargs",
")"
] | 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 objects, csv or xml.
``'df'`` will return a ``pandas.DataFrame``.
df_kwargs : dict
Passed to ``pandas.read_csv`` to control construction of
returned DataFrame.
by default ``{'index_col': 'field_name'}``
Returns
-------
metadata : list, str, ``pandas.DataFrame``
metadata sttructure for the project. | [
"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 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
by default, all fields are exported
forms : list
array of form names to export. If in the web UI, the form
name has a space in it, replace the space with an underscore
by default, all forms are exported
events : list
an array of unique event names from which to export records
:note: this only applies to longitudinal projects
raw_or_label : (``'raw'``), ``'label'``, ``'both'``
export the raw coded values or labels for the options of
multiple choice fields, or both
event_name : (``'label'``), ``'unique'``
export the unique event name or the event label
format : (``'json'``), ``'csv'``, ``'xml'``, ``'df'``
Format of returned data. ``'json'`` returns json-decoded
objects while ``'csv'`` and ``'xml'`` return other formats.
``'df'`` will attempt to return a ``pandas.DataFrame``.
export_survey_fields : (``False``), True
specifies whether or not to export the survey identifier
field (e.g., "redcap_survey_identifier") or survey timestamp
fields (e.g., form_name+"_timestamp") when surveys are
utilized in the project.
export_data_access_groups : (``False``), ``True``
specifies whether or not to export the
``"redcap_data_access_group"`` field when data access groups
are utilized in the project.
:note: This flag is only viable if the user whose token is
being used to make the API request is *not* in a data
access group. If the user is in a group, then this flag
will revert to its default value.
df_kwargs : dict
Passed to ``pandas.read_csv`` to control construction of
returned DataFrame.
by default, ``{'index_col': self.def_field}``
export_checkbox_labels : (``False``), ``True``
specify whether to export checkbox values as their label on
export.
filter_logic : string
specify the filterLogic to be sent to the API.
Returns
-------
data : list, str, ``pandas.DataFrame``
exported data
"""
ret_format = format
if format == 'df':
from pandas import read_csv
ret_format = 'csv'
pl = self.__basepl('record', format=ret_format)
fields = self.backfill_fields(fields, forms)
keys_to_add = (records, fields, forms, events,
raw_or_label, event_name, export_survey_fields,
export_data_access_groups, export_checkbox_labels)
str_keys = ('records', 'fields', 'forms', 'events', 'rawOrLabel',
'eventName', 'exportSurveyFields', 'exportDataAccessGroups',
'exportCheckboxLabel')
for key, data in zip(str_keys, keys_to_add):
if data:
# Make a url-ok string
if key in ('fields', 'records', 'forms', 'events'):
pl[key] = ','.join(data)
else:
pl[key] = data
if filter_logic:
pl["filterLogic"] = filter_logic
response, _ = self._call_api(pl, 'exp_record')
if format in ('json', 'csv', 'xml'):
return response
elif format == 'df':
if not df_kwargs:
if self.is_longitudinal():
df_kwargs = {'index_col': [self.def_field,
'redcap_event_name']}
else:
df_kwargs = {'index_col': self.def_field}
buf = StringIO(response)
df = read_csv(buf, **df_kwargs)
buf.close()
return df | 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 == 'df':
from pandas import read_csv
ret_format = 'csv'
pl = self.__basepl('record', format=ret_format)
fields = self.backfill_fields(fields, forms)
keys_to_add = (records, fields, forms, events,
raw_or_label, event_name, export_survey_fields,
export_data_access_groups, export_checkbox_labels)
str_keys = ('records', 'fields', 'forms', 'events', 'rawOrLabel',
'eventName', 'exportSurveyFields', 'exportDataAccessGroups',
'exportCheckboxLabel')
for key, data in zip(str_keys, keys_to_add):
if data:
# Make a url-ok string
if key in ('fields', 'records', 'forms', 'events'):
pl[key] = ','.join(data)
else:
pl[key] = data
if filter_logic:
pl["filterLogic"] = filter_logic
response, _ = self._call_api(pl, 'exp_record')
if format in ('json', 'csv', 'xml'):
return response
elif format == 'df':
if not df_kwargs:
if self.is_longitudinal():
df_kwargs = {'index_col': [self.def_field,
'redcap_event_name']}
else:
df_kwargs = {'index_col': self.def_field}
buf = StringIO(response)
df = read_csv(buf, **df_kwargs)
buf.close()
return df | [
"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",
"==",
"'df'",
":",
"from",
"pandas",
"import",
"read_csv",
"ret_format",
"=",
"'csv'",
"pl",
"=",
"self",
".",
"__basepl",
"(",
"'record'",
",",
"format",
"=",
"ret_format",
")",
"fields",
"=",
"self",
".",
"backfill_fields",
"(",
"fields",
",",
"forms",
")",
"keys_to_add",
"=",
"(",
"records",
",",
"fields",
",",
"forms",
",",
"events",
",",
"raw_or_label",
",",
"event_name",
",",
"export_survey_fields",
",",
"export_data_access_groups",
",",
"export_checkbox_labels",
")",
"str_keys",
"=",
"(",
"'records'",
",",
"'fields'",
",",
"'forms'",
",",
"'events'",
",",
"'rawOrLabel'",
",",
"'eventName'",
",",
"'exportSurveyFields'",
",",
"'exportDataAccessGroups'",
",",
"'exportCheckboxLabel'",
")",
"for",
"key",
",",
"data",
"in",
"zip",
"(",
"str_keys",
",",
"keys_to_add",
")",
":",
"if",
"data",
":",
"# Make a url-ok string",
"if",
"key",
"in",
"(",
"'fields'",
",",
"'records'",
",",
"'forms'",
",",
"'events'",
")",
":",
"pl",
"[",
"key",
"]",
"=",
"','",
".",
"join",
"(",
"data",
")",
"else",
":",
"pl",
"[",
"key",
"]",
"=",
"data",
"if",
"filter_logic",
":",
"pl",
"[",
"\"filterLogic\"",
"]",
"=",
"filter_logic",
"response",
",",
"_",
"=",
"self",
".",
"_call_api",
"(",
"pl",
",",
"'exp_record'",
")",
"if",
"format",
"in",
"(",
"'json'",
",",
"'csv'",
",",
"'xml'",
")",
":",
"return",
"response",
"elif",
"format",
"==",
"'df'",
":",
"if",
"not",
"df_kwargs",
":",
"if",
"self",
".",
"is_longitudinal",
"(",
")",
":",
"df_kwargs",
"=",
"{",
"'index_col'",
":",
"[",
"self",
".",
"def_field",
",",
"'redcap_event_name'",
"]",
"}",
"else",
":",
"df_kwargs",
"=",
"{",
"'index_col'",
":",
"self",
".",
"def_field",
"}",
"buf",
"=",
"StringIO",
"(",
"response",
")",
"df",
"=",
"read_csv",
"(",
"buf",
",",
"*",
"*",
"df_kwargs",
")",
"buf",
".",
"close",
"(",
")",
"return",
"df"
] | 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
by default, all fields are exported
forms : list
array of form names to export. If in the web UI, the form
name has a space in it, replace the space with an underscore
by default, all forms are exported
events : list
an array of unique event names from which to export records
:note: this only applies to longitudinal projects
raw_or_label : (``'raw'``), ``'label'``, ``'both'``
export the raw coded values or labels for the options of
multiple choice fields, or both
event_name : (``'label'``), ``'unique'``
export the unique event name or the event label
format : (``'json'``), ``'csv'``, ``'xml'``, ``'df'``
Format of returned data. ``'json'`` returns json-decoded
objects while ``'csv'`` and ``'xml'`` return other formats.
``'df'`` will attempt to return a ``pandas.DataFrame``.
export_survey_fields : (``False``), True
specifies whether or not to export the survey identifier
field (e.g., "redcap_survey_identifier") or survey timestamp
fields (e.g., form_name+"_timestamp") when surveys are
utilized in the project.
export_data_access_groups : (``False``), ``True``
specifies whether or not to export the
``"redcap_data_access_group"`` field when data access groups
are utilized in the project.
:note: This flag is only viable if the user whose token is
being used to make the API request is *not* in a data
access group. If the user is in a group, then this flag
will revert to its default value.
df_kwargs : dict
Passed to ``pandas.read_csv`` to control construction of
returned DataFrame.
by default, ``{'index_col': self.def_field}``
export_checkbox_labels : (``False``), ``True``
specify whether to export checkbox values as their label on
export.
filter_logic : string
specify the filterLogic to be sent to the API.
Returns
-------
data : list, str, ``pandas.DataFrame``
exported data | [
"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" % (key, field))
return mf
else:
return mf | 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 mf | [
"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",
"mf"
] | 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 desired for matching subjects
Returns
-------
A list of dictionaries whose keys contains at least the default field
and at most each key passed in with output_fields, each dictionary
representing a surviving row in the database.
"""
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)
matches = query.filter(data, self.def_field)
if matches:
# if output_fields is empty, we'll download all fields, which is
# not desired, so we limit download to def_field
if not output_fields:
output_fields = [self.def_field]
# But if caller passed a string and not list, we need to listify
if isinstance(output_fields, basestring):
output_fields = [output_fields]
return self.export_records(records=matches, fields=output_fields)
else:
# If there are no matches, then sending an empty list to
# export_records will actually return all rows, which is not
# what we want
return [] | 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)
matches = query.filter(data, self.def_field)
if matches:
# if output_fields is empty, we'll download all fields, which is
# not desired, so we limit download to def_field
if not output_fields:
output_fields = [self.def_field]
# But if caller passed a string and not list, we need to listify
if isinstance(output_fields, basestring):
output_fields = [output_fields]
return self.export_records(records=matches, fields=output_fields)
else:
# If there are no matches, then sending an empty list to
# export_records will actually return all rows, which is not
# what we want
return [] | [
"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",
")",
"matches",
"=",
"query",
".",
"filter",
"(",
"data",
",",
"self",
".",
"def_field",
")",
"if",
"matches",
":",
"# if output_fields is empty, we'll download all fields, which is",
"# not desired, so we limit download to def_field",
"if",
"not",
"output_fields",
":",
"output_fields",
"=",
"[",
"self",
".",
"def_field",
"]",
"# But if caller passed a string and not list, we need to listify",
"if",
"isinstance",
"(",
"output_fields",
",",
"basestring",
")",
":",
"output_fields",
"=",
"[",
"output_fields",
"]",
"return",
"self",
".",
"export_records",
"(",
"records",
"=",
"matches",
",",
"fields",
"=",
"output_fields",
")",
"else",
":",
"# If there are no matches, then sending an empty list to",
"# export_records will actually return all rows, which is not",
"# what we want",
"return",
"[",
"]"
] | 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
-------
A list of dictionaries whose keys contains at least the default field
and at most each key passed in with output_fields, each dictionary
representing a surviving row in the database. | [
"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'",
"%",
"(",
"str",
"(",
"name",
")",
",",
"str",
"(",
"label",
")",
")",
")",
"return",
"self",
".",
"field_names",
",",
"self",
".",
"field_labels"
] | 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 string, ``pandas.DataFrame``
:note:
If you pass a csv or xml string, you should use the
``format`` parameter appropriately.
:note:
Keys of the dictionaries should be subset of project's,
fields, but this isn't a requirement. If you provide keys
that aren't defined fields, the returned response will
contain an ``'error'`` key.
overwrite : ('normal'), 'overwrite'
``'overwrite'`` will erase values previously stored in the
database if not specified in the to_import dictionaries.
format : ('json'), 'xml', 'csv'
Format of incoming data. By default, to_import will be json-encoded
return_format : ('json'), 'csv', 'xml'
Response format. By default, response will be json-decoded.
return_content : ('count'), 'ids', 'nothing'
By default, the response contains a 'count' key with the number of
records just imported. By specifying 'ids', a list of ids
imported will be returned. 'nothing' will only return
the HTTP status code and no message.
date_format : ('YMD'), 'DMY', 'MDY'
Describes the formatting of dates. By default, date strings
are formatted as 'YYYY-MM-DD' corresponding to 'YMD'. If date
strings are formatted as 'MM/DD/YYYY' set this parameter as
'MDY' and if formatted as 'DD/MM/YYYY' set as 'DMY'. No
other formattings are allowed.
force_auto_number : ('False') Enables automatic assignment of record IDs
of imported records by REDCap. If this is set to true, and auto-numbering
for records is enabled for the project, auto-numbering of imported records
will be enabled.
Returns
-------
response : dict, str
response from REDCap API, json-decoded if ``return_format`` == ``'json'``
"""
pl = self.__basepl('record')
if hasattr(to_import, 'to_csv'):
# We'll assume it's a df
buf = StringIO()
if self.is_longitudinal():
csv_kwargs = {'index_label': [self.def_field,
'redcap_event_name']}
else:
csv_kwargs = {'index_label': self.def_field}
to_import.to_csv(buf, **csv_kwargs)
pl['data'] = buf.getvalue()
buf.close()
format = 'csv'
elif format == 'json':
pl['data'] = json.dumps(to_import, separators=(',', ':'))
else:
# don't do anything to csv/xml
pl['data'] = to_import
pl['overwriteBehavior'] = overwrite
pl['format'] = format
pl['returnFormat'] = return_format
pl['returnContent'] = return_content
pl['dateFormat'] = date_format
pl['forceAutoNumber'] = force_auto_number
response = self._call_api(pl, 'imp_record')[0]
if 'error' in response:
raise RedcapError(str(response))
return response | 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()
if self.is_longitudinal():
csv_kwargs = {'index_label': [self.def_field,
'redcap_event_name']}
else:
csv_kwargs = {'index_label': self.def_field}
to_import.to_csv(buf, **csv_kwargs)
pl['data'] = buf.getvalue()
buf.close()
format = 'csv'
elif format == 'json':
pl['data'] = json.dumps(to_import, separators=(',', ':'))
else:
# don't do anything to csv/xml
pl['data'] = to_import
pl['overwriteBehavior'] = overwrite
pl['format'] = format
pl['returnFormat'] = return_format
pl['returnContent'] = return_content
pl['dateFormat'] = date_format
pl['forceAutoNumber'] = force_auto_number
response = self._call_api(pl, 'imp_record')[0]
if 'error' in response:
raise RedcapError(str(response))
return response | [
"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",
"(",
")",
"if",
"self",
".",
"is_longitudinal",
"(",
")",
":",
"csv_kwargs",
"=",
"{",
"'index_label'",
":",
"[",
"self",
".",
"def_field",
",",
"'redcap_event_name'",
"]",
"}",
"else",
":",
"csv_kwargs",
"=",
"{",
"'index_label'",
":",
"self",
".",
"def_field",
"}",
"to_import",
".",
"to_csv",
"(",
"buf",
",",
"*",
"*",
"csv_kwargs",
")",
"pl",
"[",
"'data'",
"]",
"=",
"buf",
".",
"getvalue",
"(",
")",
"buf",
".",
"close",
"(",
")",
"format",
"=",
"'csv'",
"elif",
"format",
"==",
"'json'",
":",
"pl",
"[",
"'data'",
"]",
"=",
"json",
".",
"dumps",
"(",
"to_import",
",",
"separators",
"=",
"(",
"','",
",",
"':'",
")",
")",
"else",
":",
"# don't do anything to csv/xml",
"pl",
"[",
"'data'",
"]",
"=",
"to_import",
"pl",
"[",
"'overwriteBehavior'",
"]",
"=",
"overwrite",
"pl",
"[",
"'format'",
"]",
"=",
"format",
"pl",
"[",
"'returnFormat'",
"]",
"=",
"return_format",
"pl",
"[",
"'returnContent'",
"]",
"=",
"return_content",
"pl",
"[",
"'dateFormat'",
"]",
"=",
"date_format",
"pl",
"[",
"'forceAutoNumber'",
"]",
"=",
"force_auto_number",
"response",
"=",
"self",
".",
"_call_api",
"(",
"pl",
",",
"'imp_record'",
")",
"[",
"0",
"]",
"if",
"'error'",
"in",
"response",
":",
"raise",
"RedcapError",
"(",
"str",
"(",
"response",
")",
")",
"return",
"response"
] | 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:
Keys of the dictionaries should be subset of project's,
fields, but this isn't a requirement. If you provide keys
that aren't defined fields, the returned response will
contain an ``'error'`` key.
overwrite : ('normal'), 'overwrite'
``'overwrite'`` will erase values previously stored in the
database if not specified in the to_import dictionaries.
format : ('json'), 'xml', 'csv'
Format of incoming data. By default, to_import will be json-encoded
return_format : ('json'), 'csv', 'xml'
Response format. By default, response will be json-decoded.
return_content : ('count'), 'ids', 'nothing'
By default, the response contains a 'count' key with the number of
records just imported. By specifying 'ids', a list of ids
imported will be returned. 'nothing' will only return
the HTTP status code and no message.
date_format : ('YMD'), 'DMY', 'MDY'
Describes the formatting of dates. By default, date strings
are formatted as 'YYYY-MM-DD' corresponding to 'YMD'. If date
strings are formatted as 'MM/DD/YYYY' set this parameter as
'MDY' and if formatted as 'DD/MM/YYYY' set as 'DMY'. No
other formattings are allowed.
force_auto_number : ('False') Enables automatic assignment of record IDs
of imported records by REDCap. If this is set to true, and auto-numbering
for records is enabled for the project, auto-numbering of imported records
will be enabled.
Returns
-------
response : dict, str
response from REDCap API, json-decoded if ``return_format`` == ``'json'`` | [
"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
record ID
field : str
field name containing the file to be exported.
event: str
for longitudinal projects, specify the unique event here
return_format: ('json'), 'csv', 'xml'
format of error message
Returns
-------
content : bytes
content of the file
content_map : dict
content-type dictionary
"""
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
pl['action'] = 'export'
pl['field'] = field
pl['record'] = record
if event:
pl['event'] = event
content, headers = self._call_api(pl, 'exp_file')
#REDCap adds some useful things in content-type
if 'content-type' in headers:
splat = [kv.strip() for kv in headers['content-type'].split(';')]
kv = [(kv.split('=')[0], kv.split('=')[1].replace('"', '')) for kv
in splat if '=' in kv]
content_map = dict(kv)
else:
content_map = {}
return content, content_map | 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
pl['action'] = 'export'
pl['field'] = field
pl['record'] = record
if event:
pl['event'] = event
content, headers = self._call_api(pl, 'exp_file')
#REDCap adds some useful things in content-type
if 'content-type' in headers:
splat = [kv.strip() for kv in headers['content-type'].split(';')]
kv = [(kv.split('=')[0], kv.split('=')[1].replace('"', '')) for kv
in splat if '=' in kv]
content_map = dict(kv)
else:
content_map = {}
return content, content_map | [
"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",
"pl",
"[",
"'action'",
"]",
"=",
"'export'",
"pl",
"[",
"'field'",
"]",
"=",
"field",
"pl",
"[",
"'record'",
"]",
"=",
"record",
"if",
"event",
":",
"pl",
"[",
"'event'",
"]",
"=",
"event",
"content",
",",
"headers",
"=",
"self",
".",
"_call_api",
"(",
"pl",
",",
"'exp_file'",
")",
"#REDCap adds some useful things in content-type",
"if",
"'content-type'",
"in",
"headers",
":",
"splat",
"=",
"[",
"kv",
".",
"strip",
"(",
")",
"for",
"kv",
"in",
"headers",
"[",
"'content-type'",
"]",
".",
"split",
"(",
"';'",
")",
"]",
"kv",
"=",
"[",
"(",
"kv",
".",
"split",
"(",
"'='",
")",
"[",
"0",
"]",
",",
"kv",
".",
"split",
"(",
"'='",
")",
"[",
"1",
"]",
".",
"replace",
"(",
"'\"'",
",",
"''",
")",
")",
"for",
"kv",
"in",
"splat",
"if",
"'='",
"in",
"kv",
"]",
"content_map",
"=",
"dict",
"(",
"kv",
")",
"else",
":",
"content_map",
"=",
"{",
"}",
"return",
"content",
",",
"content_map"
] | 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.
event: str
for longitudinal projects, specify the unique event here
return_format: ('json'), 'csv', 'xml'
format of error message
Returns
-------
content : bytes
content of the file
content_map : dict
content-type dictionary | [
"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
field name where the file will go
fname : str
file name visible in REDCap UI
fobj : file object
file object as returned by `open`
event : str
for longitudinal projects, specify the unique event here
return_format : ('json'), 'csv', 'xml'
format of error message
Returns
-------
response :
response from server as specified by ``return_format``
"""
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_format
pl['action'] = 'import'
pl['field'] = field
pl['record'] = record
if event:
pl['event'] = event
file_kwargs = {'files': {'file': (fname, fobj)}}
return self._call_api(pl, 'imp_file', **file_kwargs)[0] | 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_format
pl['action'] = 'import'
pl['field'] = field
pl['record'] = record
if event:
pl['event'] = event
file_kwargs = {'files': {'file': (fname, fobj)}}
return self._call_api(pl, 'imp_file', **file_kwargs)[0] | [
"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_format",
"pl",
"[",
"'action'",
"]",
"=",
"'import'",
"pl",
"[",
"'field'",
"]",
"=",
"field",
"pl",
"[",
"'record'",
"]",
"=",
"record",
"if",
"event",
":",
"pl",
"[",
"'event'",
"]",
"=",
"event",
"file_kwargs",
"=",
"{",
"'files'",
":",
"{",
"'file'",
":",
"(",
"fname",
",",
"fobj",
")",
"}",
"}",
"return",
"self",
".",
"_call_api",
"(",
"pl",
",",
"'imp_file'",
",",
"*",
"*",
"file_kwargs",
")",
"[",
"0",
"]"
] | 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 object
file object as returned by `open`
event : str
for longitudinal projects, specify the unique event here
return_format : ('json'), 'csv', 'xml'
format of error message
Returns
-------
response :
response from server as specified by ``return_format`` | [
"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
return_format : (``'json'``), ``'csv'``, ``'xml'``
return format for error message
event : str
If longitudinal project, event to delete file from
Returns
-------
response : dict, str
response from REDCap after deleting file
"""
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'] = record
pl['field'] = field
if event:
pl['event'] = event
return self._call_api(pl, 'del_file')[0] | 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'] = record
pl['field'] = field
if event:
pl['event'] = event
return self._call_api(pl, 'del_file')[0] | [
"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'",
"]",
"=",
"record",
"pl",
"[",
"'field'",
"]",
"=",
"field",
"if",
"event",
":",
"pl",
"[",
"'event'",
"]",
"=",
"event",
"return",
"self",
".",
"_call_api",
"(",
"pl",
",",
"'del_file'",
")",
"[",
"0",
"]"
] | 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 message
event : str
If longitudinal project, event to delete file from
Returns
-------
response : dict, str
response from REDCap after deleting file | [
"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
raise ValueError(msg)
else:
return True | 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:
return True | [
"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",
":",
"return",
"True"
] | 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
* ``'username'`` : User's username
* ``'expiration'`` : Project access expiration date
* ``'data_access_group'`` : data access group ID
* ``'data_export'`` : (0=no access, 2=De-Identified, 1=Full Data Set)
* ``'forms'`` : a list of dicts with a single key as the form name and
value is an integer describing that user's form rights,
where: 0=no access, 1=view records/responses and edit
records (survey responses are read-only), 2=read only, and
3=edit survey responses,
Parameters
----------
format : (``'json'``), ``'csv'``, ``'xml'``
response return format
Returns
-------
users: list, str
list of users dicts when ``'format'='json'``,
otherwise a string
"""
pl = self.__basepl(content='user', format=format)
return self._call_api(pl, 'exp_user')[0] | 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'",
")",
"[",
"0",
"]"
] | 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
* ``'expiration'`` : Project access expiration date
* ``'data_access_group'`` : data access group ID
* ``'data_export'`` : (0=no access, 2=De-Identified, 1=Full Data Set)
* ``'forms'`` : a list of dicts with a single key as the form name and
value is an integer describing that user's form rights,
where: 0=no access, 1=view records/responses and edit
records (survey responses are read-only), 2=read only, and
3=edit survey responses,
Parameters
----------
format : (``'json'``), ``'csv'``, ``'xml'``
response return format
Returns
-------
users: list, str
list of users dicts when ``'format'='json'``,
otherwise a string | [
"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 instrument as seen in second column of Data Dictionary.
event: str
Unique event name, only used in longitudinal projects
format: (json, xml, csv), json by default
Format of returned data
"""
pl = self.__basepl(content='participantList', format=format)
pl['instrument'] = instrument
if event:
pl['event'] = event
return self._call_api(pl, 'exp_survey_participant_list') | 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",
"[",
"'instrument'",
"]",
"=",
"instrument",
"if",
"event",
":",
"pl",
"[",
"'event'",
"]",
"=",
"event",
"return",
"self",
".",
"_call_api",
"(",
"pl",
",",
"'exp_survey_participant_list'",
")"
] | 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, only used in longitudinal projects
format: (json, xml, csv), json by default
Format of returned data | [
"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 on the local hostname.
timeout (optional, default=5): request timeout in seconds
Raises:
QhueException if something went wrong with username generation (for
example, if the bridge button wasn't pressed).
"""
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(prompt)
if devicetype is None:
devicetype = "qhue#{}".format(getfqdn())
# raises QhueException if something went wrong
response = res(devicetype=devicetype, http_method="post")
return response[0]["success"]["username"] | 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(prompt)
if devicetype is None:
devicetype = "qhue#{}".format(getfqdn())
# raises QhueException if something went wrong
response = res(devicetype=devicetype, http_method="post")
return response[0]["success"]["username"] | [
"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",
"(",
"prompt",
")",
"if",
"devicetype",
"is",
"None",
":",
"devicetype",
"=",
"\"qhue#{}\"",
".",
"format",
"(",
"getfqdn",
"(",
")",
")",
"# raises QhueException if something went wrong",
"response",
"=",
"res",
"(",
"devicetype",
"=",
"devicetype",
",",
"http_method",
"=",
"\"post\"",
")",
"return",
"response",
"[",
"0",
"]",
"[",
"\"success\"",
"]",
"[",
"\"username\"",
"]"
] | 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 in seconds
Raises:
QhueException if something went wrong with username generation (for
example, if the bridge button wasn't pressed). | [
"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=0.1) | 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",
"(",
"coro",
")",
"_",
",",
"coroutines",
"=",
"await",
"asyncio",
".",
"wait",
"(",
"coroutines",
",",
"timeout",
"=",
"0.1",
")"
] | 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:
logging.debug(f'Cancelling task: {task}')
task.cancel()
results = await asyncio.gather(*tasks, return_exceptions=True)
logging.debug(f'Done awaiting cancelled tasks, results: {results}')
loop.stop()
logging.info('Shutdown complete.') | 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 = await asyncio.gather(*tasks, return_exceptions=True)
logging.debug(f'Done awaiting cancelled tasks, results: {results}')
loop.stop()
logging.info('Shutdown complete.') | [
"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",
"=",
"await",
"asyncio",
".",
"gather",
"(",
"*",
"tasks",
",",
"return_exceptions",
"=",
"True",
")",
"logging",
".",
"debug",
"(",
"f'Done awaiting cancelled tasks, results: {results}'",
")",
"loop",
".",
"stop",
"(",
")",
"logging",
".",
"info",
"(",
"'Shutdown complete.'",
")"
] | 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",
",",
"dict",
")",
":",
"_deep_merge_dict",
"(",
"a",
"[",
"k",
"]",
",",
"v",
")",
"else",
":",
"a",
"[",
"k",
"]",
"=",
"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 of plugins, list of
instantiated plugin objects, and any errors encountered while
loading/instantiating plugins. A tuple of three empty lists is
returned if there are no plugins found or activated in gordon
config.
"""
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 active_plugins:
return [], [], [], None
plugin_namespaces = _get_plugin_config_keys(active_plugins)
plugin_configs = _load_plugin_configs(plugin_namespaces, config)
plugin_names, plugins, errors = _init_plugins(
active_plugins, installed_plugins, plugin_configs, plugin_kwargs)
return plugin_names, plugins, errors, plugin_kwargs | 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 active_plugins:
return [], [], [], None
plugin_namespaces = _get_plugin_config_keys(active_plugins)
plugin_configs = _load_plugin_configs(plugin_namespaces, config)
plugin_names, plugins, errors = _init_plugins(
active_plugins, installed_plugins, plugin_configs, plugin_kwargs)
return plugin_names, plugins, errors, plugin_kwargs | [
"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",
"active_plugins",
":",
"return",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
",",
"None",
"plugin_namespaces",
"=",
"_get_plugin_config_keys",
"(",
"active_plugins",
")",
"plugin_configs",
"=",
"_load_plugin_configs",
"(",
"plugin_namespaces",
",",
"config",
")",
"plugin_names",
",",
"plugins",
",",
"errors",
"=",
"_init_plugins",
"(",
"active_plugins",
",",
"installed_plugins",
",",
"plugin_configs",
",",
"plugin_kwargs",
")",
"return",
"plugin_names",
",",
"plugins",
",",
"errors",
",",
"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 of plugins, list of
instantiated plugin objects, and any errors encountered while
loading/instantiating plugins. A tuple of three empty lists is
returned if there are no plugins found or activated in gordon
config. | [
"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: UDPClientProtocol(message),
remote_addr=(self.ip, self.port)) | 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",
":",
"UDPClientProtocol",
"(",
"message",
")",
",",
"remote_addr",
"=",
"(",
"self",
".",
"ip",
",",
"self",
".",
"port",
")",
")"
] | 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 dict with record properties.
timeout (int): Time threshold to query the DNS server.
"""
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_record and \
timeout > retries * sleep_time:
retries += 1
resolver_res = await self._resolver.query(name, r_type_code)
possible_ans = resolver_res.an
resolvable_record = \
await self._check_resolver_ans(possible_ans, name,
rr_data, ttl, r_type_code)
if not resolvable_record:
await asyncio.sleep(sleep_time)
if not resolvable_record:
logging.info(
f'Sending metric record-checker-failed: {record}.')
else:
final_time = float(time.time() - start_time)
success_msg = (f'This record: {record} took {final_time} to '
'register.')
logging.info(success_msg) | 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_record and \
timeout > retries * sleep_time:
retries += 1
resolver_res = await self._resolver.query(name, r_type_code)
possible_ans = resolver_res.an
resolvable_record = \
await self._check_resolver_ans(possible_ans, name,
rr_data, ttl, r_type_code)
if not resolvable_record:
await asyncio.sleep(sleep_time)
if not resolvable_record:
logging.info(
f'Sending metric record-checker-failed: {record}.')
else:
final_time = float(time.time() - start_time)
success_msg = (f'This record: {record} took {final_time} to '
'register.')
logging.info(success_msg) | [
"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_record",
"and",
"timeout",
">",
"retries",
"*",
"sleep_time",
":",
"retries",
"+=",
"1",
"resolver_res",
"=",
"await",
"self",
".",
"_resolver",
".",
"query",
"(",
"name",
",",
"r_type_code",
")",
"possible_ans",
"=",
"resolver_res",
".",
"an",
"resolvable_record",
"=",
"await",
"self",
".",
"_check_resolver_ans",
"(",
"possible_ans",
",",
"name",
",",
"rr_data",
",",
"ttl",
",",
"r_type_code",
")",
"if",
"not",
"resolvable_record",
":",
"await",
"asyncio",
".",
"sleep",
"(",
"sleep_time",
")",
"if",
"not",
"resolvable_record",
":",
"logging",
".",
"info",
"(",
"f'Sending metric record-checker-failed: {record}.'",
")",
"else",
":",
"final_time",
"=",
"float",
"(",
"time",
".",
"time",
"(",
")",
"-",
"start_time",
")",
"success_msg",
"=",
"(",
"f'This record: {record} took {final_time} to '",
"'register.'",
")",
"logging",
".",
"info",
"(",
"success_msg",
")"
] | 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 threshold to query the DNS server. | [
"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 (str): Record name.
record_data_list (list): List of data values for the record.
record_ttl (int): Record time-to-live info.
record_type_code (int): Record type code.
Returns:
boolean indicating if DNS answer data is equal to record data.
"""
type_filtered_list = [
ans for ans in dns_answer_list if ans.qtype == record_type_code
]
# check to see that type_filtered_lst has
# the same number of records as record_data_list
if len(type_filtered_list) != len(record_data_list):
return False
# check each record data is equal to the given data
for rec in type_filtered_list:
conditions = [rec.name == record_name,
rec.ttl == record_ttl,
rec.data in record_data_list]
# if ans record data is not equal
# to the given data return False
if not all(conditions):
return False
return True | 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
# the same number of records as record_data_list
if len(type_filtered_list) != len(record_data_list):
return False
# check each record data is equal to the given data
for rec in type_filtered_list:
conditions = [rec.name == record_name,
rec.ttl == record_ttl,
rec.data in record_data_list]
# if ans record data is not equal
# to the given data return False
if not all(conditions):
return False
return True | [
"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",
"# the same number of records as record_data_list",
"if",
"len",
"(",
"type_filtered_list",
")",
"!=",
"len",
"(",
"record_data_list",
")",
":",
"return",
"False",
"# check each record data is equal to the given data",
"for",
"rec",
"in",
"type_filtered_list",
":",
"conditions",
"=",
"[",
"rec",
".",
"name",
"==",
"record_name",
",",
"rec",
".",
"ttl",
"==",
"record_ttl",
",",
"rec",
".",
"data",
"in",
"record_data_list",
"]",
"# if ans record data is not equal",
"# to the given data return False",
"if",
"not",
"all",
"(",
"conditions",
")",
":",
"return",
"False",
"return",
"True"
] | 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.
record_type_code (int): Record type code.
Returns:
boolean indicating if DNS answer data is equal to record data. | [
"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.level, message) | 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",
"=",
"metric",
"[",
"'context'",
"]",
")",
"self",
".",
"_logger",
".",
"log",
"(",
"self",
".",
"level",
",",
"message",
")"
] | 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. Default is False.
:returns: The enciphered string.
"""
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 | 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",
"(",
")",
":",
"if",
"c",
".",
"isalpha",
"(",
")",
":",
"ret",
"+=",
"self",
".",
"key",
"[",
"self",
".",
"a2i",
"(",
"c",
")",
"]",
"else",
":",
"ret",
"+=",
"c",
"return",
"ret"
] | 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 string. | [
"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. The ciphertext will be twice the length of the plaintext.
"""
string = self.remove_punctuation(string)#,filter='[^'+self.key+']')
ret = ''
for c in range(0,len(string)):
ret += self.encipher_char(string[c])
return ret | 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",
")",
")",
":",
"ret",
"+=",
"self",
".",
"encipher_char",
"(",
"string",
"[",
"c",
"]",
")",
"return",
"ret"
] | 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 length of the plaintext. | [
"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. The plaintext will be half the length of the ciphertext.
"""
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 | 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",
")",
",",
"2",
")",
":",
"ret",
"+=",
"self",
".",
"decipher_pair",
"(",
"string",
"[",
"i",
":",
"i",
"+",
"2",
"]",
")",
"return",
"ret"
] | 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 of the ciphertext. | [
"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)
:param string: The string to decipher.
:returns: The enciphered string.
"""
step2 = ColTrans(self.keyword).decipher(string)
step1 = PolybiusSquare(self.key,size=6,chars='ADFGVX').decipher(step2)
return step1 | 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",
"=",
"'ADFGVX'",
")",
".",
"decipher",
"(",
"step2",
")",
"return",
"step1"
] | 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.
:returns: The enciphered string. | [
"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','N'),steckers=[('P','O'),('M','L'),
('I','U'),('K','J'),('N','H'),('Y','T'),('G','B'),('V','F'),
('R','E'),('D','C')])).encipher(plaintext)
:param string: The string to encipher.
:returns: The enciphered 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 | 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",
"(",
")",
":",
"ret",
"+=",
"self",
".",
"encipher_char",
"(",
"c",
")",
"else",
":",
"ret",
"+=",
"c",
"return",
"ret"
] | 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'),
('I','U'),('K','J'),('N','H'),('Y','T'),('G','B'),('V','F'),
('R','E'),('D','C')])).encipher(plaintext)
:param string: The string to encipher.
:returns: The enciphered string. | [
"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",
"[",
"k",
"]",
"-",
"1",
")",
"icval",
"/=",
"(",
"len",
"(",
"ctext",
")",
"*",
"(",
"len",
"(",
"ctext",
")",
"-",
"1",
")",
")",
"return",
"icval"
] | 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]
count+=1
else: ret+=c
except IndexError:
print('restore_punctuation: strings must have same number of alphabetic chars')
raise
return ret | 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]
count+=1
else: ret+=c
except IndexError:
print('restore_punctuation: strings must have same number of alphabetic chars')
raise
return ret | [
"def",
"restore_punctuation",
"(",
"original",
",",
"modified",
")",
":",
"ret",
"=",
"''",
"count",
"=",
"0",
"try",
":",
"for",
"c",
"in",
"original",
":",
"if",
"c",
".",
"isalpha",
"(",
")",
":",
"ret",
"+=",
"modified",
"[",
"count",
"]",
"count",
"+=",
"1",
"else",
":",
"ret",
"+=",
"c",
"except",
"IndexError",
":",
"print",
"(",
"'restore_punctuation: strings must have same number of alphabetic chars'",
")",
"raise",
"return",
"ret"
] | 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='zgptfoihmuwdrcnykeqaxvsbl').encipher(plaintext)
:param string: The string to encipher.
:returns: The enciphered 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])
return ret | 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])
return ret | [
"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",
"]",
")",
"return",
"ret"
] | 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(plaintext)
:param string: The string to encipher.
:returns: The enciphered 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",
"."
] | 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.
Example::
plaintext = Playfair(key='zgptfoihmuwdrcnykeqaxvsbl').decipher(ciphertext)
:param string: The string to decipher.
:returns: The deciphered 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 | 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",
"range",
"(",
"0",
",",
"len",
"(",
"string",
")",
",",
"2",
")",
":",
"ret",
"+=",
"self",
".",
"decipher_pair",
"(",
"string",
"[",
"c",
"]",
",",
"string",
"[",
"c",
"+",
"1",
"]",
")",
"return",
"ret"
] | 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 = Playfair(key='zgptfoihmuwdrcnykeqaxvsbl').decipher(ciphertext)
:param string: The string to decipher.
:returns: The deciphered 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",
"."
] | 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 ciphertext will be 3 times the length of the plaintext.
"""
string = self.remove_punctuation(string,filter='[^'+self.key+']')
ctext = ""
for c in string:
ctext += ''.join([str(i) for i in L2IND[c]])
return ctext | 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",
":",
"ctext",
"+=",
"''",
".",
"join",
"(",
"[",
"str",
"(",
"i",
")",
"for",
"i",
"in",
"L2IND",
"[",
"c",
"]",
"]",
")",
"return",
"ctext"
] | 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 plaintext. | [
"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 plaintext will be 1/3 the length of the ciphertext.
"""
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 | 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",
",",
"len",
"(",
"string",
")",
",",
"3",
")",
":",
"ind",
"=",
"tuple",
"(",
"[",
"int",
"(",
"string",
"[",
"i",
"+",
"k",
"]",
")",
"for",
"k",
"in",
"[",
"0",
",",
"1",
",",
"2",
"]",
"]",
")",
"ret",
"+=",
"IND2L",
"[",
"ind",
"]",
"return",
"ret"
] | 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 ciphertext. | [
"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='zgptfoihmuwdrcnykeqaxvsbl',key2='mfnbdcrhsaxyogvituewlqzkp').encipher(plaintext)
:param string: The string to encipher.
:returns: The enciphered 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 | 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",
"c",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"string",
".",
"upper",
"(",
")",
")",
",",
"2",
")",
":",
"a",
",",
"b",
"=",
"self",
".",
"encipher_pair",
"(",
"string",
"[",
"c",
"]",
",",
"string",
"[",
"c",
"+",
"1",
"]",
")",
"ret",
"+=",
"a",
"+",
"b",
"return",
"ret"
] | 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='mfnbdcrhsaxyogvituewlqzkp').encipher(plaintext)
:param string: The string to encipher.
:returns: The enciphered 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",
"."
] | 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.
Example::
plaintext = Foursquare(key1='zgptfoihmuwdrcnykeqaxvsbl',key2='mfnbdcrhsaxyogvituewlqzkp').decipher(ciphertext)
:param string: The string to decipher.
:returns: The deciphered 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 | 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",
"c",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"string",
".",
"upper",
"(",
")",
")",
",",
"2",
")",
":",
"a",
",",
"b",
"=",
"self",
".",
"decipher_pair",
"(",
"string",
"[",
"c",
"]",
",",
"string",
"[",
"c",
"+",
"1",
"]",
")",
"ret",
"+=",
"a",
"+",
"b",
"return",
"ret"
] | 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 = Foursquare(key1='zgptfoihmuwdrcnykeqaxvsbl',key2='mfnbdcrhsaxyogvituewlqzkp').decipher(ciphertext)
:param string: The string to decipher.
:returns: The deciphered 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",
"."
] | 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. Default is False.
:returns: The enciphered string.
"""
if not keep_punct: string = self.remove_punctuation(string)
ret = ''
for c in string:
if c.isalpha(): ret += self.i2a( self.a2i(c) + 13 )
else: ret += c
return ret | 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. Default is False.
:returns: The enciphered string.
"""
if not keep_punct: string = self.remove_punctuation(string)
ret = ''
for c in string:
if c.isalpha(): ret += self.i2a( self.a2i(c) + 13 )
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",
":",
"if",
"c",
".",
"isalpha",
"(",
")",
":",
"ret",
"+=",
"self",
".",
"i2a",
"(",
"self",
".",
"a2i",
"(",
"c",
")",
"+",
"13",
")",
"else",
":",
"ret",
"+=",
"c",
"return",
"ret"
] | 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 string. | [
"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.
:returns: The enciphered 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 += 'ZNOPQRSTUVWXYBCDEFGHIJKLMA'[self.a2i(c)]
elif self.key[i] in 'WX': ret += 'YZNOPQRSTUVWXCDEFGHIJKLMAB'[self.a2i(c)]
elif self.key[i] in 'UV': ret += 'XYZNOPQRSTUVWDEFGHIJKLMABC'[self.a2i(c)]
elif self.key[i] in 'ST': ret += 'WXYZNOPQRSTUVEFGHIJKLMABCD'[self.a2i(c)]
elif self.key[i] in 'QR': ret += 'VWXYZNOPQRSTUFGHIJKLMABCDE'[self.a2i(c)]
elif self.key[i] in 'OP': ret += 'UVWXYZNOPQRSTGHIJKLMABCDEF'[self.a2i(c)]
elif self.key[i] in 'MN': ret += 'TUVWXYZNOPQRSHIJKLMABCDEFG'[self.a2i(c)]
elif self.key[i] in 'KL': ret += 'STUVWXYZNOPQRIJKLMABCDEFGH'[self.a2i(c)]
elif self.key[i] in 'IJ': ret += 'RSTUVWXYZNOPQJKLMABCDEFGHI'[self.a2i(c)]
elif self.key[i] in 'GH': ret += 'QRSTUVWXYZNOPKLMABCDEFGHIJ'[self.a2i(c)]
elif self.key[i] in 'EF': ret += 'PQRSTUVWXYZNOLMABCDEFGHIJK'[self.a2i(c)]
elif self.key[i] in 'CD': ret += 'OPQRSTUVWXYZNMABCDEFGHIJKL'[self.a2i(c)]
return ret | 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 += 'ZNOPQRSTUVWXYBCDEFGHIJKLMA'[self.a2i(c)]
elif self.key[i] in 'WX': ret += 'YZNOPQRSTUVWXCDEFGHIJKLMAB'[self.a2i(c)]
elif self.key[i] in 'UV': ret += 'XYZNOPQRSTUVWDEFGHIJKLMABC'[self.a2i(c)]
elif self.key[i] in 'ST': ret += 'WXYZNOPQRSTUVEFGHIJKLMABCD'[self.a2i(c)]
elif self.key[i] in 'QR': ret += 'VWXYZNOPQRSTUFGHIJKLMABCDE'[self.a2i(c)]
elif self.key[i] in 'OP': ret += 'UVWXYZNOPQRSTGHIJKLMABCDEF'[self.a2i(c)]
elif self.key[i] in 'MN': ret += 'TUVWXYZNOPQRSHIJKLMABCDEFG'[self.a2i(c)]
elif self.key[i] in 'KL': ret += 'STUVWXYZNOPQRIJKLMABCDEFGH'[self.a2i(c)]
elif self.key[i] in 'IJ': ret += 'RSTUVWXYZNOPQJKLMABCDEFGHI'[self.a2i(c)]
elif self.key[i] in 'GH': ret += 'QRSTUVWXYZNOPKLMABCDEFGHIJ'[self.a2i(c)]
elif self.key[i] in 'EF': ret += 'PQRSTUVWXYZNOLMABCDEFGHIJK'[self.a2i(c)]
elif self.key[i] in 'CD': ret += 'OPQRSTUVWXYZNMABCDEFGHIJKL'[self.a2i(c)]
return ret | [
"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",
"+=",
"'ZNOPQRSTUVWXYBCDEFGHIJKLMA'",
"[",
"self",
".",
"a2i",
"(",
"c",
")",
"]",
"elif",
"self",
".",
"key",
"[",
"i",
"]",
"in",
"'WX'",
":",
"ret",
"+=",
"'YZNOPQRSTUVWXCDEFGHIJKLMAB'",
"[",
"self",
".",
"a2i",
"(",
"c",
")",
"]",
"elif",
"self",
".",
"key",
"[",
"i",
"]",
"in",
"'UV'",
":",
"ret",
"+=",
"'XYZNOPQRSTUVWDEFGHIJKLMABC'",
"[",
"self",
".",
"a2i",
"(",
"c",
")",
"]",
"elif",
"self",
".",
"key",
"[",
"i",
"]",
"in",
"'ST'",
":",
"ret",
"+=",
"'WXYZNOPQRSTUVEFGHIJKLMABCD'",
"[",
"self",
".",
"a2i",
"(",
"c",
")",
"]",
"elif",
"self",
".",
"key",
"[",
"i",
"]",
"in",
"'QR'",
":",
"ret",
"+=",
"'VWXYZNOPQRSTUFGHIJKLMABCDE'",
"[",
"self",
".",
"a2i",
"(",
"c",
")",
"]",
"elif",
"self",
".",
"key",
"[",
"i",
"]",
"in",
"'OP'",
":",
"ret",
"+=",
"'UVWXYZNOPQRSTGHIJKLMABCDEF'",
"[",
"self",
".",
"a2i",
"(",
"c",
")",
"]",
"elif",
"self",
".",
"key",
"[",
"i",
"]",
"in",
"'MN'",
":",
"ret",
"+=",
"'TUVWXYZNOPQRSHIJKLMABCDEFG'",
"[",
"self",
".",
"a2i",
"(",
"c",
")",
"]",
"elif",
"self",
".",
"key",
"[",
"i",
"]",
"in",
"'KL'",
":",
"ret",
"+=",
"'STUVWXYZNOPQRIJKLMABCDEFGH'",
"[",
"self",
".",
"a2i",
"(",
"c",
")",
"]",
"elif",
"self",
".",
"key",
"[",
"i",
"]",
"in",
"'IJ'",
":",
"ret",
"+=",
"'RSTUVWXYZNOPQJKLMABCDEFGHI'",
"[",
"self",
".",
"a2i",
"(",
"c",
")",
"]",
"elif",
"self",
".",
"key",
"[",
"i",
"]",
"in",
"'GH'",
":",
"ret",
"+=",
"'QRSTUVWXYZNOPKLMABCDEFGHIJ'",
"[",
"self",
".",
"a2i",
"(",
"c",
")",
"]",
"elif",
"self",
".",
"key",
"[",
"i",
"]",
"in",
"'EF'",
":",
"ret",
"+=",
"'PQRSTUVWXYZNOLMABCDEFGHIJK'",
"[",
"self",
".",
"a2i",
"(",
"c",
")",
"]",
"elif",
"self",
".",
"key",
"[",
"i",
"]",
"in",
"'CD'",
":",
"ret",
"+=",
"'OPQRSTUVWXYZNMABCDEFGHIJKL'",
"[",
"self",
".",
"a2i",
"(",
"c",
")",
"]",
"return",
"ret"
] | 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 string to encipher.
:returns: The enciphered string.
"""
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 = ''
# from now we no longer need the wheel starts, we can just increment the actual key
for j in range(len(message)):
shift = 0
effective_ch[0] = 0;
effective_ch[1] = self.wheel_1_settings[self.actual_key[0]]
effective_ch[2] = self.wheel_2_settings[self.actual_key[1]]
effective_ch[3] = self.wheel_3_settings[self.actual_key[2]]
effective_ch[4] = self.wheel_4_settings[self.actual_key[3]]
effective_ch[5] = self.wheel_5_settings[self.actual_key[4]]
effective_ch[6] = self.wheel_6_settings[self.actual_key[5]]
for i in range(0,27): # implements the cylindrical drum with lugs on it
if effective_ch[self.lug_positions[i][0]] or effective_ch[self.lug_positions[i][1]]: shift+=1
# shift has been found, now actually encrypt letter
ret += self.subst(message[j],key='ZYXWVUTSRQPONMLKJIHGFEDCBA',offset=-shift); # encrypt letter
self.advance_key(); # advance the key wheels
return ret | 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 = ''
# from now we no longer need the wheel starts, we can just increment the actual key
for j in range(len(message)):
shift = 0
effective_ch[0] = 0;
effective_ch[1] = self.wheel_1_settings[self.actual_key[0]]
effective_ch[2] = self.wheel_2_settings[self.actual_key[1]]
effective_ch[3] = self.wheel_3_settings[self.actual_key[2]]
effective_ch[4] = self.wheel_4_settings[self.actual_key[3]]
effective_ch[5] = self.wheel_5_settings[self.actual_key[4]]
effective_ch[6] = self.wheel_6_settings[self.actual_key[5]]
for i in range(0,27): # implements the cylindrical drum with lugs on it
if effective_ch[self.lug_positions[i][0]] or effective_ch[self.lug_positions[i][1]]: shift+=1
# shift has been found, now actually encrypt letter
ret += self.subst(message[j],key='ZYXWVUTSRQPONMLKJIHGFEDCBA',offset=-shift); # encrypt letter
self.advance_key(); # advance the key wheels
return ret | [
"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",
"=",
"''",
"# from now we no longer need the wheel starts, we can just increment the actual key",
"for",
"j",
"in",
"range",
"(",
"len",
"(",
"message",
")",
")",
":",
"shift",
"=",
"0",
"effective_ch",
"[",
"0",
"]",
"=",
"0",
"effective_ch",
"[",
"1",
"]",
"=",
"self",
".",
"wheel_1_settings",
"[",
"self",
".",
"actual_key",
"[",
"0",
"]",
"]",
"effective_ch",
"[",
"2",
"]",
"=",
"self",
".",
"wheel_2_settings",
"[",
"self",
".",
"actual_key",
"[",
"1",
"]",
"]",
"effective_ch",
"[",
"3",
"]",
"=",
"self",
".",
"wheel_3_settings",
"[",
"self",
".",
"actual_key",
"[",
"2",
"]",
"]",
"effective_ch",
"[",
"4",
"]",
"=",
"self",
".",
"wheel_4_settings",
"[",
"self",
".",
"actual_key",
"[",
"3",
"]",
"]",
"effective_ch",
"[",
"5",
"]",
"=",
"self",
".",
"wheel_5_settings",
"[",
"self",
".",
"actual_key",
"[",
"4",
"]",
"]",
"effective_ch",
"[",
"6",
"]",
"=",
"self",
".",
"wheel_6_settings",
"[",
"self",
".",
"actual_key",
"[",
"5",
"]",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"27",
")",
":",
"# implements the cylindrical drum with lugs on it",
"if",
"effective_ch",
"[",
"self",
".",
"lug_positions",
"[",
"i",
"]",
"[",
"0",
"]",
"]",
"or",
"effective_ch",
"[",
"self",
".",
"lug_positions",
"[",
"i",
"]",
"[",
"1",
"]",
"]",
":",
"shift",
"+=",
"1",
"# shift has been found, now actually encrypt letter",
"ret",
"+=",
"self",
".",
"subst",
"(",
"message",
"[",
"j",
"]",
",",
"key",
"=",
"'ZYXWVUTSRQPONMLKJIHGFEDCBA'",
",",
"offset",
"=",
"-",
"shift",
")",
"# encrypt letter",
"self",
".",
"advance_key",
"(",
")",
"# advance the key wheels",
"return",
"ret"
] | 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 enciphered string. | [
"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.
"""
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 = morsestr + 'x'
#print morsestr
mapping = dict(zip(self.table,self.key))
ctext = ""
for i in range(0,len(morsestr),3):
ctext += mapping[morsestr[i:i+3]]
return ctext | 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 = morsestr + 'x'
#print morsestr
mapping = dict(zip(self.table,self.key))
ctext = ""
for i in range(0,len(morsestr),3):
ctext += mapping[morsestr[i:i+3]]
return ctext | [
"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",
"=",
"morsestr",
"+",
"'x'",
"#print morsestr",
"mapping",
"=",
"dict",
"(",
"zip",
"(",
"self",
".",
"table",
",",
"self",
".",
"key",
")",
")",
"ctext",
"=",
"\"\"",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"morsestr",
")",
",",
"3",
")",
":",
"ctext",
"+=",
"mapping",
"[",
"morsestr",
"[",
"i",
":",
"i",
"+",
"3",
"]",
"]",
"return",
"ctext"
] | 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.
"""
string = string.upper()
mapping = dict(zip(self.key,self.table))
ptext = ""
for i in string:
ptext += mapping[i]
return self.demorse(ptext) | 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",
"string",
":",
"ptext",
"+=",
"mapping",
"[",
"i",
"]",
"return",
"self",
".",
"demorse",
"(",
"ptext",
")"
] | 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 encipher.
:returns: The enciphered 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 | 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",
"(",
"len",
"(",
"self",
".",
"keyword",
")",
")",
":",
"ret",
"+=",
"string",
"[",
"ind",
".",
"index",
"(",
"i",
")",
":",
":",
"len",
"(",
"self",
".",
"keyword",
")",
"]",
"return",
"ret"
] | 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 enciphered string. | [
"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.
:returns: The deciphered string.
'''
string = self.remove_punctuation(string)
ret = ['_']*len(string)
L,M = len(string),len(self.keyword)
ind = self.unsortind(self.keyword)
upto = 0
for i in range(len(self.keyword)):
thiscollen = (int)(L/M)
if ind[i]< L%M: thiscollen += 1
ret[ind[i]::M] = string[upto:upto+thiscollen]
upto += thiscollen
return ''.join(ret) | 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.
:returns: The deciphered string.
'''
string = self.remove_punctuation(string)
ret = ['_']*len(string)
L,M = len(string),len(self.keyword)
ind = self.unsortind(self.keyword)
upto = 0
for i in range(len(self.keyword)):
thiscollen = (int)(L/M)
if ind[i]< L%M: thiscollen += 1
ret[ind[i]::M] = string[upto:upto+thiscollen]
upto += thiscollen
return ''.join(ret) | [
"def",
"decipher",
"(",
"self",
",",
"string",
")",
":",
"string",
"=",
"self",
".",
"remove_punctuation",
"(",
"string",
")",
"ret",
"=",
"[",
"'_'",
"]",
"*",
"len",
"(",
"string",
")",
"L",
",",
"M",
"=",
"len",
"(",
"string",
")",
",",
"len",
"(",
"self",
".",
"keyword",
")",
"ind",
"=",
"self",
".",
"unsortind",
"(",
"self",
".",
"keyword",
")",
"upto",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"keyword",
")",
")",
":",
"thiscollen",
"=",
"(",
"int",
")",
"(",
"L",
"/",
"M",
")",
"if",
"ind",
"[",
"i",
"]",
"<",
"L",
"%",
"M",
":",
"thiscollen",
"+=",
"1",
"ret",
"[",
"ind",
"[",
"i",
"]",
":",
":",
"M",
"]",
"=",
"string",
"[",
"upto",
":",
"upto",
"+",
"thiscollen",
"]",
"upto",
"+=",
"thiscollen",
"return",
"''",
".",
"join",
"(",
"ret",
")"
] | 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 string. | [
"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 spacing are retained. If false, it is all removed. Default is False.
:returns: The enciphered string.
"""
if not keep_punct: string = self.remove_punctuation(string)
return ''.join(self.buildfence(string, self.key)) | 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",
"(",
"string",
",",
"self",
".",
"key",
")",
")"
] | 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 is False.
:returns: The enciphered string. | [
"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 spacing are retained. If false, it is all removed. Default is False.
:returns: The deciphered string.
"""
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) | 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",
")",
")",
"pos",
"=",
"self",
".",
"buildfence",
"(",
"ind",
",",
"self",
".",
"key",
")",
"return",
"''",
".",
"join",
"(",
"string",
"[",
"pos",
".",
"index",
"(",
"i",
")",
"]",
"for",
"i",
"in",
"ind",
")"
] | 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 is False.
:returns: The deciphered string. | [
"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 are retained. If false, it is all removed. Default is False.
:returns: The deciphered string.
"""
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 | 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",
"c",
".",
"isalpha",
"(",
")",
":",
"ret",
"+=",
"self",
".",
"i2a",
"(",
"self",
".",
"inva",
"*",
"(",
"self",
".",
"a2i",
"(",
"c",
")",
"-",
"self",
".",
"b",
")",
")",
"else",
":",
"ret",
"+=",
"c",
"return",
"ret"
] | 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 False.
:returns: The deciphered string. | [
"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.
:returns: The enciphered 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)
return ret | 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)
return ret | [
"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",
")",
"return",
"ret"
] | 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 encipher.
:returns: The enciphered 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:int(i+self.period)]
return self.pb.decipher(''.join(step2)) | 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:int(i+self.period)]
return self.pb.decipher(''.join(step2)) | [
"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",
":",
"int",
"(",
"i",
"+",
"self",
".",
"period",
")",
"]",
"return",
"self",
".",
"pb",
".",
"decipher",
"(",
"''",
".",
"join",
"(",
"step2",
")",
")"
] | 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 enciphered string. | [
"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.
:returns: The deciphered 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 >= len(string): continue
tempseq.append(int(self.key.index(string[i + j]) / 5))
tempseq.append(int(self.key.index(string[i + j]) % 5))
rowseq.extend(tempseq[0:int(len(tempseq)/2)])
colseq.extend(tempseq[int(len(tempseq)/2):])
for i in range(len(rowseq)):
ret += self.key[rowseq[i]*5 + colseq[i]]
return ret | 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 >= len(string): continue
tempseq.append(int(self.key.index(string[i + j]) / 5))
tempseq.append(int(self.key.index(string[i + j]) % 5))
rowseq.extend(tempseq[0:int(len(tempseq)/2)])
colseq.extend(tempseq[int(len(tempseq)/2):])
for i in range(len(rowseq)):
ret += self.key[rowseq[i]*5 + colseq[i]]
return ret | [
"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",
">=",
"len",
"(",
"string",
")",
":",
"continue",
"tempseq",
".",
"append",
"(",
"int",
"(",
"self",
".",
"key",
".",
"index",
"(",
"string",
"[",
"i",
"+",
"j",
"]",
")",
"/",
"5",
")",
")",
"tempseq",
".",
"append",
"(",
"int",
"(",
"self",
".",
"key",
".",
"index",
"(",
"string",
"[",
"i",
"+",
"j",
"]",
")",
"%",
"5",
")",
")",
"rowseq",
".",
"extend",
"(",
"tempseq",
"[",
"0",
":",
"int",
"(",
"len",
"(",
"tempseq",
")",
"/",
"2",
")",
"]",
")",
"colseq",
".",
"extend",
"(",
"tempseq",
"[",
"int",
"(",
"len",
"(",
"tempseq",
")",
"/",
"2",
")",
":",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"rowseq",
")",
")",
":",
"ret",
"+=",
"self",
".",
"key",
"[",
"rowseq",
"[",
"i",
"]",
"*",
"5",
"+",
"colseq",
"[",
"i",
"]",
"]",
"return",
"ret"
] | 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 string. | [
"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_punct: if true, punctuation and spacing are retained. If false, it is all removed. Default is False.
:returns: The deciphered string.
"""
# 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(string)
ret = ''
for c in string.upper():
if c.isalpha(): ret += self.invkey[self.a2i(c)]
else: ret += c
return ret | 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(string)
ret = ''
for c in string.upper():
if c.isalpha(): ret += self.invkey[self.a2i(c)]
else: ret += c
return ret | [
"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",
"(",
"string",
")",
"ret",
"=",
"''",
"for",
"c",
"in",
"string",
".",
"upper",
"(",
")",
":",
"if",
"c",
".",
"isalpha",
"(",
")",
":",
"ret",
"+=",
"self",
".",
"invkey",
"[",
"self",
".",
"a2i",
"(",
"c",
")",
"]",
"else",
":",
"ret",
"+=",
"c",
"return",
"ret"
] | 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. If false, it is all removed. Default is False.
:returns: The deciphered string. | [
"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 waiting for two TT-vectors or two TT-matrices'",
")"
] | 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 waiting for two TT-vectors or two TT- matrices'",
")"
] | 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([], dtype=_np.int32)
c.r = _np.array([], dtype=_np.int32)
c.core = []
for t in a:
thetensor = t.tt if isinstance(t, _matrix.matrix) else t
c.d += thetensor.d
c.n = _np.concatenate((c.n, thetensor.n))
c.r = _np.concatenate((c.r[:-1], thetensor.r))
c.core = _np.concatenate((c.core, thetensor.core))
c.get_ps()
return c | 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=_np.int32)
c.core = []
for t in a:
thetensor = t.tt if isinstance(t, _matrix.matrix) else t
c.d += thetensor.d
c.n = _np.concatenate((c.n, thetensor.n))
c.r = _np.concatenate((c.r[:-1], thetensor.r))
c.core = _np.concatenate((c.core, thetensor.core))
c.get_ps()
return c | [
"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",
"=",
"_np",
".",
"int32",
")",
"c",
".",
"core",
"=",
"[",
"]",
"for",
"t",
"in",
"a",
":",
"thetensor",
"=",
"t",
".",
"tt",
"if",
"isinstance",
"(",
"t",
",",
"_matrix",
".",
"matrix",
")",
"else",
"t",
"c",
".",
"d",
"+=",
"thetensor",
".",
"d",
"c",
".",
"n",
"=",
"_np",
".",
"concatenate",
"(",
"(",
"c",
".",
"n",
",",
"thetensor",
".",
"n",
")",
")",
"c",
".",
"r",
"=",
"_np",
".",
"concatenate",
"(",
"(",
"c",
".",
"r",
"[",
":",
"-",
"1",
"]",
",",
"thetensor",
".",
"r",
")",
")",
"c",
".",
"core",
"=",
"_np",
".",
"concatenate",
"(",
"(",
"c",
".",
"core",
",",
"thetensor",
".",
"core",
")",
")",
"c",
".",
"get_ps",
"(",
")",
"return",
"c"
] | 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),
Z(1, i_1, \\ldots, i_d) = Y(i_1, \\ldots, i_d).
"""
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 result | 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 result | [
"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",
"result"
] | 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(i_1, \\ldots, i_d). | [
"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] = _np.sum(crs[ax], axis=1)
rleft, rright = crs[ax].shape
if (rleft >= rright or rleft < rright and ax + 1 >= d) and ax > 0:
crs[ax - 1] = _np.tensordot(crs[ax - 1], crs[ax], axes=(2, 0))
elif ax + 1 < d:
crs[ax + 1] = _np.tensordot(crs[ax], crs[ax + 1], axes=(1, 0))
else:
return _np.sum(crs[ax])
crs.pop(ax)
d -= 1
return _vector.vector.from_list(crs) | 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, rright = crs[ax].shape
if (rleft >= rright or rleft < rright and ax + 1 >= d) and ax > 0:
crs[ax - 1] = _np.tensordot(crs[ax - 1], crs[ax], axes=(2, 0))
elif ax + 1 < d:
crs[ax + 1] = _np.tensordot(crs[ax], crs[ax + 1], axes=(1, 0))
else:
return _np.sum(crs[ax])
crs.pop(ax)
d -= 1
return _vector.vector.from_list(crs) | [
"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",
",",
"rright",
"=",
"crs",
"[",
"ax",
"]",
".",
"shape",
"if",
"(",
"rleft",
">=",
"rright",
"or",
"rleft",
"<",
"rright",
"and",
"ax",
"+",
"1",
">=",
"d",
")",
"and",
"ax",
">",
"0",
":",
"crs",
"[",
"ax",
"-",
"1",
"]",
"=",
"_np",
".",
"tensordot",
"(",
"crs",
"[",
"ax",
"-",
"1",
"]",
",",
"crs",
"[",
"ax",
"]",
",",
"axes",
"=",
"(",
"2",
",",
"0",
")",
")",
"elif",
"ax",
"+",
"1",
"<",
"d",
":",
"crs",
"[",
"ax",
"+",
"1",
"]",
"=",
"_np",
".",
"tensordot",
"(",
"crs",
"[",
"ax",
"]",
",",
"crs",
"[",
"ax",
"+",
"1",
"]",
",",
"axes",
"=",
"(",
"1",
",",
"0",
")",
")",
"else",
":",
"return",
"_np",
".",
"sum",
"(",
"crs",
"[",
"ax",
"]",
")",
"crs",
".",
"pop",
"(",
"ax",
")",
"d",
"-=",
"1",
"return",
"_vector",
".",
"vector",
".",
"from_list",
"(",
"crs",
")"
] | 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.core = _np.ones(c.ps[c.d] - 1)
return 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",
".",
"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"
] | 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, 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) * r0
r0[0] = 1
r0[d] = 1
c = _vector.vector()
c.d = d
c.n = n0
c.r = r0
c.get_ps()
c.core = samplefunc(c.ps[d] - 1)
return c | 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) * r0
r0[0] = 1
r0[d] = 1
c = _vector.vector()
c.d = d
c.n = n0
c.r = r0
c.get_ps()
c.core = samplefunc(c.ps[d] - 1)
return c | [
"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",
")",
"*",
"r0",
"r0",
"[",
"0",
"]",
"=",
"1",
"r0",
"[",
"d",
"]",
"=",
"1",
"c",
"=",
"_vector",
".",
"vector",
"(",
")",
"c",
".",
"d",
"=",
"d",
"c",
".",
"n",
"=",
"n0",
"c",
".",
"r",
"=",
"r0",
"c",
".",
"get_ps",
"(",
")",
"c",
".",
"core",
"=",
"samplefunc",
"(",
"c",
".",
"ps",
"[",
"d",
"]",
"-",
"1",
")",
"return",
"c"
] | 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.copy()
c.tt.n = (c.n) * (c.m)
c.tt.r = _np.ones((c.tt.d + 1,), dtype=_np.int32)
c.tt.get_ps()
c.tt.alloc_core()
for i in xrange(c.tt.d):
c.tt.core[
c.tt.ps[i] -
1:c.tt.ps[
i +
1] -
1] = _np.eye(
c.n[i]).flatten()
return c | 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.tt.r = _np.ones((c.tt.d + 1,), dtype=_np.int32)
c.tt.get_ps()
c.tt.alloc_core()
for i in xrange(c.tt.d):
c.tt.core[
c.tt.ps[i] -
1:c.tt.ps[
i +
1] -
1] = _np.eye(
c.n[i]).flatten()
return c | [
"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",
".",
"tt",
".",
"r",
"=",
"_np",
".",
"ones",
"(",
"(",
"c",
".",
"tt",
".",
"d",
"+",
"1",
",",
")",
",",
"dtype",
"=",
"_np",
".",
"int32",
")",
"c",
".",
"tt",
".",
"get_ps",
"(",
")",
"c",
".",
"tt",
".",
"alloc_core",
"(",
")",
"for",
"i",
"in",
"xrange",
"(",
"c",
".",
"tt",
".",
"d",
")",
":",
"c",
".",
"tt",
".",
"core",
"[",
"c",
".",
"tt",
".",
"ps",
"[",
"i",
"]",
"-",
"1",
":",
"c",
".",
"tt",
".",
"ps",
"[",
"i",
"+",
"1",
"]",
"-",
"1",
"]",
"=",
"_np",
".",
"eye",
"(",
"c",
".",
"n",
"[",
"i",
"]",
")",
".",
"flatten",
"(",
")",
"return",
"c"
] | 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(coresX) - 1)
cc, rr = np.linalg.qr(reshape(cc, (-1, r2)))
r2 = cc.shape[1]
coresX[dim] = reshape(cc, (r1, n, r2))
coresX[dim+1] = np.tensordot(rr, coresX[dim+1], 1)
else:
# Right to left orthogonalization step.
assert(0 < dim < len(coresX))
cc, rr = np.linalg.qr(reshape(cc, (r1, -1)).T)
r1 = cc.shape[1]
coresX[dim] = reshape(cc.T, (r1, n, r2))
coresX[dim-1] = np.tensordot(coresX[dim-1], rr.T, 1)
return coresX | 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[dim] = reshape(cc, (r1, n, r2))
coresX[dim+1] = np.tensordot(rr, coresX[dim+1], 1)
else:
# Right to left orthogonalization step.
assert(0 < dim < len(coresX))
cc, rr = np.linalg.qr(reshape(cc, (r1, -1)).T)
r1 = cc.shape[1]
coresX[dim] = reshape(cc.T, (r1, n, r2))
coresX[dim-1] = np.tensordot(coresX[dim-1], rr.T, 1)
return coresX | [
"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",
"[",
"dim",
"]",
"=",
"reshape",
"(",
"cc",
",",
"(",
"r1",
",",
"n",
",",
"r2",
")",
")",
"coresX",
"[",
"dim",
"+",
"1",
"]",
"=",
"np",
".",
"tensordot",
"(",
"rr",
",",
"coresX",
"[",
"dim",
"+",
"1",
"]",
",",
"1",
")",
"else",
":",
"# Right to left orthogonalization step.",
"assert",
"(",
"0",
"<",
"dim",
"<",
"len",
"(",
"coresX",
")",
")",
"cc",
",",
"rr",
"=",
"np",
".",
"linalg",
".",
"qr",
"(",
"reshape",
"(",
"cc",
",",
"(",
"r1",
",",
"-",
"1",
")",
")",
".",
"T",
")",
"r1",
"=",
"cc",
".",
"shape",
"[",
"1",
"]",
"coresX",
"[",
"dim",
"]",
"=",
"reshape",
"(",
"cc",
".",
"T",
",",
"(",
"r1",
",",
"n",
",",
"r2",
")",
")",
"coresX",
"[",
"dim",
"-",
"1",
"]",
"=",
"np",
".",
"tensordot",
"(",
"coresX",
"[",
"dim",
"-",
"1",
"]",
",",
"rr",
".",
"T",
",",
"1",
")",
"return",
"coresX"
] | 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(0) = y_0
and outputs approximation for :math:`y(\\tau)`
:References:
1. Christian Lubich, Ivan Oseledets, and Bart Vandereycken.
Time integration of tensor trains. arXiv preprint 1407.2042, 2014.
http://arxiv.org/abs/1407.2042
2. Christian Lubich and Ivan V. Oseledets. A projector-splitting integrator
for dynamical low-rank approximation. BIT, 54(1):171-188, 2014.
http://dx.doi.org/10.1007/s10543-013-0454-0
:param A: Matrix in the TT-format
:type A: matrix
:param y0: Initial condition in the TT-format,
:type y0: tensor
:param tau: Timestep
:type tau: float
:param scheme: The integration scheme, possible values: 'symm' -- second order, 'first' -- first order
:type scheme: str
:param space: Maximal dimension of the Krylov space for the local EXPOKIT solver.
:type space: int
:param use_normest: Use matrix norm estimation instead of the true 1-norm in KSL procedure. 0 -use true norm, 1 - Higham norm estimator, 2 - fixed norm=1.0 (for testing purposes only)
:type use_normest: int, default: 1
:rtype: tensor
:Example:
>>> import tt
>>> import tt.ksl
>>> import numpy as np
>>> d = 8
>>> a = tt.qlaplace_dd([d, d, d])
>>> y0, ev = tt.eigb.eigb(a, tt.rand(2 , 24, 2), 1e-6, verb=0)
Solving a block eigenvalue problem
Looking for 1 eigenvalues with accuracy 1E-06
swp: 1 er = 1.1408 rmax:2
swp: 2 er = 190.01 rmax:2
swp: 3 er = 2.72582E-08 rmax:2
Total number of matvecs: 0
>>> y1 = tt.ksl.ksl(a, y0, 1e-2)
Solving a real-valued dynamical problem with tau=1E-02
>>> print tt.dot(y1, y0) / (y1.norm() * y0.norm()) - 1 #Eigenvectors should not change
0.0
"""
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 = 2
else:
tp = 1
usenrm = int(use_normest)
# Check for dtype
y = tt.vector()
if np.iscomplex(A.tt.core).any() or np.iscomplex(y0.core).any():
dyn_tt.dyn_tt.ztt_ksl(
y0.d,
A.n,
A.m,
A.tt.r,
A.tt.core + 0j,
y0.core + 0j,
ry,
tau,
rmax,
0,
10,
verb,
tp,
space,
usenrm
)
y.core = dyn_tt.dyn_tt.zresult_core.copy()
else:
A.tt.core = np.real(A.tt.core)
y0.core = np.real(y0.core)
dyn_tt.dyn_tt.tt_ksl(
y0.d,
A.n,
A.m,
A.tt.r,
A.tt.core,
y0.core,
ry,
tau,
rmax,
0,
10,
verb,
tp,
space,
usenrm
)
y.core = dyn_tt.dyn_tt.dresult_core.copy()
dyn_tt.dyn_tt.deallocate_result()
y.d = y0.d
y.n = A.n.copy()
y.r = ry
y.get_ps()
return 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':
tp = 2
else:
tp = 1
usenrm = int(use_normest)
# Check for dtype
y = tt.vector()
if np.iscomplex(A.tt.core).any() or np.iscomplex(y0.core).any():
dyn_tt.dyn_tt.ztt_ksl(
y0.d,
A.n,
A.m,
A.tt.r,
A.tt.core + 0j,
y0.core + 0j,
ry,
tau,
rmax,
0,
10,
verb,
tp,
space,
usenrm
)
y.core = dyn_tt.dyn_tt.zresult_core.copy()
else:
A.tt.core = np.real(A.tt.core)
y0.core = np.real(y0.core)
dyn_tt.dyn_tt.tt_ksl(
y0.d,
A.n,
A.m,
A.tt.r,
A.tt.core,
y0.core,
ry,
tau,
rmax,
0,
10,
verb,
tp,
space,
usenrm
)
y.core = dyn_tt.dyn_tt.dresult_core.copy()
dyn_tt.dyn_tt.deallocate_result()
y.d = y0.d
y.n = A.n.copy()
y.r = ry
y.get_ps()
return y | [
"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'",
":",
"tp",
"=",
"2",
"else",
":",
"tp",
"=",
"1",
"usenrm",
"=",
"int",
"(",
"use_normest",
")",
"# Check for dtype",
"y",
"=",
"tt",
".",
"vector",
"(",
")",
"if",
"np",
".",
"iscomplex",
"(",
"A",
".",
"tt",
".",
"core",
")",
".",
"any",
"(",
")",
"or",
"np",
".",
"iscomplex",
"(",
"y0",
".",
"core",
")",
".",
"any",
"(",
")",
":",
"dyn_tt",
".",
"dyn_tt",
".",
"ztt_ksl",
"(",
"y0",
".",
"d",
",",
"A",
".",
"n",
",",
"A",
".",
"m",
",",
"A",
".",
"tt",
".",
"r",
",",
"A",
".",
"tt",
".",
"core",
"+",
"0j",
",",
"y0",
".",
"core",
"+",
"0j",
",",
"ry",
",",
"tau",
",",
"rmax",
",",
"0",
",",
"10",
",",
"verb",
",",
"tp",
",",
"space",
",",
"usenrm",
")",
"y",
".",
"core",
"=",
"dyn_tt",
".",
"dyn_tt",
".",
"zresult_core",
".",
"copy",
"(",
")",
"else",
":",
"A",
".",
"tt",
".",
"core",
"=",
"np",
".",
"real",
"(",
"A",
".",
"tt",
".",
"core",
")",
"y0",
".",
"core",
"=",
"np",
".",
"real",
"(",
"y0",
".",
"core",
")",
"dyn_tt",
".",
"dyn_tt",
".",
"tt_ksl",
"(",
"y0",
".",
"d",
",",
"A",
".",
"n",
",",
"A",
".",
"m",
",",
"A",
".",
"tt",
".",
"r",
",",
"A",
".",
"tt",
".",
"core",
",",
"y0",
".",
"core",
",",
"ry",
",",
"tau",
",",
"rmax",
",",
"0",
",",
"10",
",",
"verb",
",",
"tp",
",",
"space",
",",
"usenrm",
")",
"y",
".",
"core",
"=",
"dyn_tt",
".",
"dyn_tt",
".",
"dresult_core",
".",
"copy",
"(",
")",
"dyn_tt",
".",
"dyn_tt",
".",
"deallocate_result",
"(",
")",
"y",
".",
"d",
"=",
"y0",
".",
"d",
"y",
".",
"n",
"=",
"A",
".",
"n",
".",
"copy",
"(",
")",
"y",
".",
"r",
"=",
"ry",
"y",
".",
"get_ps",
"(",
")",
"return",
"y"
] | 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:
1. Christian Lubich, Ivan Oseledets, and Bart Vandereycken.
Time integration of tensor trains. arXiv preprint 1407.2042, 2014.
http://arxiv.org/abs/1407.2042
2. Christian Lubich and Ivan V. Oseledets. A projector-splitting integrator
for dynamical low-rank approximation. BIT, 54(1):171-188, 2014.
http://dx.doi.org/10.1007/s10543-013-0454-0
:param A: Matrix in the TT-format
:type A: matrix
:param y0: Initial condition in the TT-format,
:type y0: tensor
:param tau: Timestep
:type tau: float
:param scheme: The integration scheme, possible values: 'symm' -- second order, 'first' -- first order
:type scheme: str
:param space: Maximal dimension of the Krylov space for the local EXPOKIT solver.
:type space: int
:param use_normest: Use matrix norm estimation instead of the true 1-norm in KSL procedure. 0 -use true norm, 1 - Higham norm estimator, 2 - fixed norm=1.0 (for testing purposes only)
:type use_normest: int, default: 1
:rtype: tensor
:Example:
>>> import tt
>>> import tt.ksl
>>> import numpy as np
>>> d = 8
>>> a = tt.qlaplace_dd([d, d, d])
>>> y0, ev = tt.eigb.eigb(a, tt.rand(2 , 24, 2), 1e-6, verb=0)
Solving a block eigenvalue problem
Looking for 1 eigenvalues with accuracy 1E-06
swp: 1 er = 1.1408 rmax:2
swp: 2 er = 190.01 rmax:2
swp: 3 er = 2.72582E-08 rmax:2
Total number of matvecs: 0
>>> y1 = tt.ksl.ksl(a, y0, 1e-2)
Solving a real-valued dynamical problem with tau=1E-02
>>> print tt.dot(y1, y0) / (y1.norm() * y0.norm()) - 1 #Eigenvectors should not change
0.0 | [
"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 ::
\\frac{dy}{dt} = V y, \\quad y(0) = y_0
and outputs approximation for :math:`y(\\tau)`
:References:
1. Christian Lubich, Ivan Oseledets, and Bart Vandereycken.
Time integration of tensor trains. arXiv preprint 1407.2042, 2014.
http://arxiv.org/abs/1407.2042
2. Christian Lubich and Ivan V. Oseledets. A projector-splitting integrator
for dynamical low-rank approximation. BIT, 54(1):171-188, 2014.
http://dx.doi.org/10.1007/s10543-013-0454-0
:param A: Matrix in the TT-format
:type A: matrix
:param y0: Initial condition in the TT-format,
:type y0: tensor
:param tau: Timestep
:type tau: float
:param scheme: The integration scheme, possible values: 'symm' -- second order, 'first' -- first order
:type scheme: str
:param space: Maximal dimension of the Krylov space for the local EXPOKIT solver.
:type space: int
:rtype: tensor
:Example:
>>> import tt
>>> import tt.ksl
>>> import numpy as np
>>> d = 8
>>> a = tt.qlaplace_dd([d, d, d])
>>> y0, ev = tt.eigb.eigb(a, tt.rand(2 , 24, 2), 1e-6, verb=0)
Solving a block eigenvalue problem
Looking for 1 eigenvalues with accuracy 1E-06
swp: 1 er = 1.1408 rmax:2
swp: 2 er = 190.01 rmax:2
swp: 3 er = 2.72582E-08 rmax:2
Total number of matvecs: 0
>>> y1 = tt.ksl.ksl(a, y0, 1e-2)
Solving a real-valued dynamical problem with tau=1E-02
>>> print tt.dot(y1, y0) / (y1.norm() * y0.norm()) - 1 #Eigenvectors should not change
0.0
"""
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 = 2
else:
tp = 1
# Check for dtype
y = tt.vector()
if np.iscomplex(A.core).any() or np.iscomplex(y0.core).any():
dyn_tt.dyn_diag_tt.ztt_diag_ksl(
y0.d,
A.n,
A.r,
A.core + 0j,
y0.core + 0j,
ry,
tau,
rmax,
0,
10,
verb,
tp,
space)
y.core = dyn_tt.dyn_diag_tt.zresult_core.copy()
else:
A.core = np.real(A.core)
y0.core = np.real(y0.core)
dyn_tt.dyn_diag_tt.dtt_diag_ksl(
y0.d,
A.n,
A.r,
A.core,
y0.core,
ry,
tau,
rmax,
0,
10,
verb,
tp,
space)
y.core = dyn_tt.dyn_diag_tt.dresult_core.copy()
dyn_tt.dyn_diag_tt.deallocate_result()
y.d = y0.d
y.n = A.n.copy()
y.r = ry
y.get_ps()
return y | 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 = 2
else:
tp = 1
# Check for dtype
y = tt.vector()
if np.iscomplex(A.core).any() or np.iscomplex(y0.core).any():
dyn_tt.dyn_diag_tt.ztt_diag_ksl(
y0.d,
A.n,
A.r,
A.core + 0j,
y0.core + 0j,
ry,
tau,
rmax,
0,
10,
verb,
tp,
space)
y.core = dyn_tt.dyn_diag_tt.zresult_core.copy()
else:
A.core = np.real(A.core)
y0.core = np.real(y0.core)
dyn_tt.dyn_diag_tt.dtt_diag_ksl(
y0.d,
A.n,
A.r,
A.core,
y0.core,
ry,
tau,
rmax,
0,
10,
verb,
tp,
space)
y.core = dyn_tt.dyn_diag_tt.dresult_core.copy()
dyn_tt.dyn_diag_tt.deallocate_result()
y.d = y0.d
y.n = A.n.copy()
y.r = ry
y.get_ps()
return y | [
"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",
"=",
"2",
"else",
":",
"tp",
"=",
"1",
"# Check for dtype",
"y",
"=",
"tt",
".",
"vector",
"(",
")",
"if",
"np",
".",
"iscomplex",
"(",
"A",
".",
"core",
")",
".",
"any",
"(",
")",
"or",
"np",
".",
"iscomplex",
"(",
"y0",
".",
"core",
")",
".",
"any",
"(",
")",
":",
"dyn_tt",
".",
"dyn_diag_tt",
".",
"ztt_diag_ksl",
"(",
"y0",
".",
"d",
",",
"A",
".",
"n",
",",
"A",
".",
"r",
",",
"A",
".",
"core",
"+",
"0j",
",",
"y0",
".",
"core",
"+",
"0j",
",",
"ry",
",",
"tau",
",",
"rmax",
",",
"0",
",",
"10",
",",
"verb",
",",
"tp",
",",
"space",
")",
"y",
".",
"core",
"=",
"dyn_tt",
".",
"dyn_diag_tt",
".",
"zresult_core",
".",
"copy",
"(",
")",
"else",
":",
"A",
".",
"core",
"=",
"np",
".",
"real",
"(",
"A",
".",
"core",
")",
"y0",
".",
"core",
"=",
"np",
".",
"real",
"(",
"y0",
".",
"core",
")",
"dyn_tt",
".",
"dyn_diag_tt",
".",
"dtt_diag_ksl",
"(",
"y0",
".",
"d",
",",
"A",
".",
"n",
",",
"A",
".",
"r",
",",
"A",
".",
"core",
",",
"y0",
".",
"core",
",",
"ry",
",",
"tau",
",",
"rmax",
",",
"0",
",",
"10",
",",
"verb",
",",
"tp",
",",
"space",
")",
"y",
".",
"core",
"=",
"dyn_tt",
".",
"dyn_diag_tt",
".",
"dresult_core",
".",
"copy",
"(",
")",
"dyn_tt",
".",
"dyn_diag_tt",
".",
"deallocate_result",
"(",
")",
"y",
".",
"d",
"=",
"y0",
".",
"d",
"y",
".",
"n",
"=",
"A",
".",
"n",
".",
"copy",
"(",
")",
"y",
".",
"r",
"=",
"ry",
"y",
".",
"get_ps",
"(",
")",
"return",
"y"
] | 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 approximation for :math:`y(\\tau)`
:References:
1. Christian Lubich, Ivan Oseledets, and Bart Vandereycken.
Time integration of tensor trains. arXiv preprint 1407.2042, 2014.
http://arxiv.org/abs/1407.2042
2. Christian Lubich and Ivan V. Oseledets. A projector-splitting integrator
for dynamical low-rank approximation. BIT, 54(1):171-188, 2014.
http://dx.doi.org/10.1007/s10543-013-0454-0
:param A: Matrix in the TT-format
:type A: matrix
:param y0: Initial condition in the TT-format,
:type y0: tensor
:param tau: Timestep
:type tau: float
:param scheme: The integration scheme, possible values: 'symm' -- second order, 'first' -- first order
:type scheme: str
:param space: Maximal dimension of the Krylov space for the local EXPOKIT solver.
:type space: int
:rtype: tensor
:Example:
>>> import tt
>>> import tt.ksl
>>> import numpy as np
>>> d = 8
>>> a = tt.qlaplace_dd([d, d, d])
>>> y0, ev = tt.eigb.eigb(a, tt.rand(2 , 24, 2), 1e-6, verb=0)
Solving a block eigenvalue problem
Looking for 1 eigenvalues with accuracy 1E-06
swp: 1 er = 1.1408 rmax:2
swp: 2 er = 190.01 rmax:2
swp: 3 er = 2.72582E-08 rmax:2
Total number of matvecs: 0
>>> y1 = tt.ksl.ksl(a, y0, 1e-2)
Solving a real-valued dynamical problem with tau=1E-02
>>> print tt.dot(y1, y0) / (y1.norm() * y0.norm()) - 1 #Eigenvectors should not change
0.0 | [
"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"
] | 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",
",",
"2",
",",
"1",
",",
"3",
"]",
")",
")",
"return",
"matrix",
".",
"from_list",
"(",
"trans_crs",
")"
] | 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:`\\begin{bmatrix}\\Re M & -\\Im M \\\\ \\Im M & \\Re M \\end{bmatrix}`. This function
is useful for solving complex linear system :math:`\\mathcal{A}X = B` with real solver by
transforming it into
.. math::
\\begin{bmatrix}\\Re\\mathcal{A} & -\\Im\\mathcal{A} \\\\
\\Im\\mathcal{A} & \\Re\\mathcal{A} \\end{bmatrix}
\\begin{bmatrix}\\Re X \\\\ \\Im X\\end{bmatrix} =
\\begin{bmatrix}\\Re B \\\\ \\Im B\\end{bmatrix}.
"""
return matrix(a=self.tt.__complex_op('M'), n=_np.concatenate(
(self.n, [2])), m=_np.concatenate((self.m, [2]))) | 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",
"=",
"_np",
".",
"concatenate",
"(",
"(",
"self",
".",
"m",
",",
"[",
"2",
"]",
")",
")",
")"
] | 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 & -\\Im M \\\\ \\Im M & \\Re M \\end{bmatrix}`. This function
is useful for solving complex linear system :math:`\\mathcal{A}X = B` with real solver by
transforming it into
.. math::
\\begin{bmatrix}\\Re\\mathcal{A} & -\\Im\\mathcal{A} \\\\
\\Im\\mathcal{A} & \\Re\\mathcal{A} \\end{bmatrix}
\\begin{bmatrix}\\Re X \\\\ \\Im X\\end{bmatrix} =
\\begin{bmatrix}\\Re B \\\\ \\Im B\\end{bmatrix}. | [
"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",
".",
"n",
".",
"copy",
"(",
")",
"c",
".",
"m",
"=",
"self",
".",
"m",
".",
"copy",
"(",
")",
"return",
"c"
] | 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",
".",
"copy",
"(",
")",
"return",
"c"
] | 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.arange(2 * d)
prm = prm.reshape((d, 2), order='F')
prm = prm.transpose()
prm = prm.flatten('F')
# Get the inverse permutation
iprm = [0] * (2 * d)
for i in xrange(2 * d):
iprm[prm[i]] = i
a = a.transpose(iprm).reshape(N, M, order='F')
a = a.reshape(N, M)
return a | 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')
prm = prm.transpose()
prm = prm.flatten('F')
# Get the inverse permutation
iprm = [0] * (2 * d)
for i in xrange(2 * d):
iprm[prm[i]] = i
a = a.transpose(iprm).reshape(N, M, order='F')
a = a.reshape(N, M)
return a | [
"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'",
")",
"prm",
"=",
"prm",
".",
"transpose",
"(",
")",
"prm",
"=",
"prm",
".",
"flatten",
"(",
"'F'",
")",
"# Get the inverse permutation",
"iprm",
"=",
"[",
"0",
"]",
"*",
"(",
"2",
"*",
"d",
")",
"for",
"i",
"in",
"xrange",
"(",
"2",
"*",
"d",
")",
":",
"iprm",
"[",
"prm",
"[",
"i",
"]",
"]",
"=",
"i",
"a",
"=",
"a",
".",
"transpose",
"(",
"iprm",
")",
".",
"reshape",
"(",
"N",
",",
"M",
",",
"order",
"=",
"'F'",
")",
"a",
"=",
"a",
".",
"reshape",
"(",
"N",
",",
"M",
")",
"return",
"a"
] | 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, 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[0]
r[i+1] = a[i].shape[2]
n[i] = a[i].shape[1]
res.d = d
res.n = n
res.r = r
res.core = cr
res.get_ps()
return res | 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[0]
r[i+1] = a[i].shape[2]
n[i] = a[i].shape[1]
res.d = d
res.n = n
res.r = r
res.core = cr
res.get_ps()
return res | [
"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",
"[",
"0",
"]",
"r",
"[",
"i",
"+",
"1",
"]",
"=",
"a",
"[",
"i",
"]",
".",
"shape",
"[",
"2",
"]",
"n",
"[",
"i",
"]",
"=",
"a",
"[",
"i",
"]",
".",
"shape",
"[",
"1",
"]",
"res",
".",
"d",
"=",
"d",
"res",
".",
"n",
"=",
"n",
"res",
".",
"r",
"=",
"r",
"res",
".",
"core",
"=",
"cr",
"res",
".",
"get_ps",
"(",
")",
"return",
"res"
] | 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] + n[d - 1] * r[d]
if d is 2:
er = sz * 1.0 / b
else:
a = _np.sum(n[1:d - 1])
er = (_np.sqrt(b * b + 4 * a * sz) - b) / (2 * a)
return er | 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:
er = sz * 1.0 / b
else:
a = _np.sum(n[1:d - 1])
er = (_np.sqrt(b * b + 4 * a * sz) - b) / (2 * a)
return er | [
"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",
":",
"er",
"=",
"sz",
"*",
"1.0",
"/",
"b",
"else",
":",
"a",
"=",
"_np",
".",
"sum",
"(",
"n",
"[",
"1",
":",
"d",
"-",
"1",
"]",
")",
"er",
"=",
"(",
"_np",
".",
"sqrt",
"(",
"b",
"*",
"b",
"+",
"4",
"*",
"a",
"*",
"sz",
")",
"-",
"b",
")",
"/",
"(",
"2",
"*",
"a",
")",
"return",
"er"
] | 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 = b ** 2 - 4 * a * c
r = 0.5 * (-b + _np.sqrt(D)) / a
return r | 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)) / a
return r | [
"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",
")",
")",
"/",
"a",
"return",
"r"
] | 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 function.
:Reference:
S. V. Dolgov, B. N. Khoromskij, I. V. Oseledets, and D. V. Savostyanov.
Computation of extreme eigenvalues in higher dimensions using block tensor train format. Computer Phys. Comm.,
185(4):1207-1216, 2014. http://dx.doi.org/10.1016/j.cpc.2013.12.017
:param A: Matrix in the TT-format
:type A: matrix
:param y0: Initial guess in the block TT-format, r(d+1) is the number of eigenvalues sought
:type y0: tensor
:param eps: Accuracy required
:type eps: float
:param rmax: Maximal rank
:type rmax: int
:param kickrank: Addition rank, the larger the more robus the method,
:type kickrank: int
:rtype: A tuple (ev, tensor), where ev is a list of eigenvalues, tensor is an approximation to eigenvectors.
:Example:
>>> import tt
>>> import tt.eigb
>>> d = 8; f = 3
>>> r = [8] * (d * f + 1); r[d * f] = 8; r[0] = 1
>>> x = tt.rand(n, d * f, r)
>>> a = tt.qlaplace_dd([8, 8, 8])
>>> sol, ev = tt.eigb.eigb(a, x, 1e-6, verb=0)
Solving a block eigenvalue problem
Looking for 8 eigenvalues with accuracy 1E-06
swp: 1 er = 35.93 rmax:19
swp: 2 er = 4.51015E-04 rmax:18
swp: 3 er = 1.87584E-12 rmax:17
Total number of matvecs: 0
>>> print ev
[ 0.00044828 0.00089654 0.00089654 0.00089654 0.0013448 0.0013448
0.0013448 0.00164356]
"""
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()
y.r = ry
y.core = tt_eigb.tt_block_eig.result_core.copy()
tt_eigb.tt_block_eig.deallocate_result()
y.get_ps()
return y, lam | 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()
y.r = ry
y.core = tt_eigb.tt_block_eig.result_core.copy()
tt_eigb.tt_block_eig.deallocate_result()
y.get_ps()
return y, lam | [
"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",
"(",
")",
"y",
".",
"r",
"=",
"ry",
"y",
".",
"core",
"=",
"tt_eigb",
".",
"tt_block_eig",
".",
"result_core",
".",
"copy",
"(",
")",
"tt_eigb",
".",
"tt_block_eig",
".",
"deallocate_result",
"(",
")",
"y",
".",
"get_ps",
"(",
")",
"return",
"y",
",",
"lam"
] | 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. Oseledets, and D. V. Savostyanov.
Computation of extreme eigenvalues in higher dimensions using block tensor train format. Computer Phys. Comm.,
185(4):1207-1216, 2014. http://dx.doi.org/10.1016/j.cpc.2013.12.017
:param A: Matrix in the TT-format
:type A: matrix
:param y0: Initial guess in the block TT-format, r(d+1) is the number of eigenvalues sought
:type y0: tensor
:param eps: Accuracy required
:type eps: float
:param rmax: Maximal rank
:type rmax: int
:param kickrank: Addition rank, the larger the more robus the method,
:type kickrank: int
:rtype: A tuple (ev, tensor), where ev is a list of eigenvalues, tensor is an approximation to eigenvectors.
:Example:
>>> import tt
>>> import tt.eigb
>>> d = 8; f = 3
>>> r = [8] * (d * f + 1); r[d * f] = 8; r[0] = 1
>>> x = tt.rand(n, d * f, r)
>>> a = tt.qlaplace_dd([8, 8, 8])
>>> sol, ev = tt.eigb.eigb(a, x, 1e-6, verb=0)
Solving a block eigenvalue problem
Looking for 8 eigenvalues with accuracy 1E-06
swp: 1 er = 35.93 rmax:19
swp: 2 er = 4.51015E-04 rmax:18
swp: 3 er = 1.87584E-12 rmax:17
Total number of matvecs: 0
>>> print ev
[ 0.00044828 0.00089654 0.00089654 0.00089654 0.0013448 0.0013448
0.0013448 0.00164356] | [
"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",
"."
] | 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'",
",",
"'ignore'",
")",
".",
"encode",
"(",
"LOCALE_ENCODING",
")"
] | 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 formatting is being done for the
bot's last reply (e.g. in a ``%Previous`` command).
:return str: The formatted message.
"""
# 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, "sub")
# In UTF-8 mode, only strip metacharacters and HTML brackets
# (to protect from obvious XSS attacks).
if self.utf8:
msg = re.sub(RE.utf8_meta, '', msg)
msg = re.sub(self.master.unicode_punctuation, '', msg)
# For the bot's reply, also strip common punctuation.
if botreply:
msg = re.sub(RE.utf8_punct, '', msg)
else:
# For everything else, strip all non-alphanumerics.
msg = utils.strip_nasties(msg)
msg = msg.strip() # Strip leading and trailing white space
msg = RE.ws.sub(" ",msg) # Replace the multiple whitespaces by single whitespace
return msg | 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, "sub")
# In UTF-8 mode, only strip metacharacters and HTML brackets
# (to protect from obvious XSS attacks).
if self.utf8:
msg = re.sub(RE.utf8_meta, '', msg)
msg = re.sub(self.master.unicode_punctuation, '', msg)
# For the bot's reply, also strip common punctuation.
if botreply:
msg = re.sub(RE.utf8_punct, '', msg)
else:
# For everything else, strip all non-alphanumerics.
msg = utils.strip_nasties(msg)
msg = msg.strip() # Strip leading and trailing white space
msg = RE.ws.sub(" ",msg) # Replace the multiple whitespaces by single whitespace
return msg | [
"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",
",",
"\"sub\"",
")",
"# In UTF-8 mode, only strip metacharacters and HTML brackets",
"# (to protect from obvious XSS attacks).",
"if",
"self",
".",
"utf8",
":",
"msg",
"=",
"re",
".",
"sub",
"(",
"RE",
".",
"utf8_meta",
",",
"''",
",",
"msg",
")",
"msg",
"=",
"re",
".",
"sub",
"(",
"self",
".",
"master",
".",
"unicode_punctuation",
",",
"''",
",",
"msg",
")",
"# For the bot's reply, also strip common punctuation.",
"if",
"botreply",
":",
"msg",
"=",
"re",
".",
"sub",
"(",
"RE",
".",
"utf8_punct",
",",
"''",
",",
"msg",
")",
"else",
":",
"# For everything else, strip all non-alphanumerics.",
"msg",
"=",
"utils",
".",
"strip_nasties",
"(",
"msg",
")",
"msg",
"=",
"msg",
".",
"strip",
"(",
")",
"# Strip leading and trailing white space",
"msg",
"=",
"RE",
".",
"ws",
".",
"sub",
"(",
"\" \"",
",",
"msg",
")",
"# Replace the multiple whitespaces by single whitespace",
"return",
"msg"
] | 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. in a ``%Previous`` command).
:return str: The formatted message. | [
"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 expand.
:param int depth: The recursion depth counter.
:return set: The final set of array entries.
"""
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])
for array in self.master._array[array_name]:
if array.startswith('@'):
ret.remove(array)
expanded = self.do_expand_array(array[1:], depth+1)
ret.extend(expanded)
return set(ret) | 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])
for array in self.master._array[array_name]:
if array.startswith('@'):
ret.remove(array)
expanded = self.do_expand_array(array[1:], depth+1)
ret.extend(expanded)
return set(ret) | [
"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",
"]",
")",
"for",
"array",
"in",
"self",
".",
"master",
".",
"_array",
"[",
"array_name",
"]",
":",
"if",
"array",
".",
"startswith",
"(",
"'@'",
")",
":",
"ret",
".",
"remove",
"(",
"array",
")",
"expanded",
"=",
"self",
".",
"do_expand_array",
"(",
"array",
"[",
"1",
":",
"]",
",",
"depth",
"+",
"1",
")",
"ret",
".",
"extend",
"(",
"expanded",
")",
"return",
"set",
"(",
"ret",
")"
] | 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 counter.
:return set: The final set of array entries. | [
"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 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 | 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",
".",
"do_expand_array",
"(",
"array_name",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"warn",
"(",
"\"Error expanding array '%s': %s\"",
"%",
"(",
"array_name",
",",
"str",
"(",
"e",
")",
")",
")",
"return",
"ret"
] | 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 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("You must call sort_replies() once you are done loading RiveScript documents")
# Get the substitution map.
subs = None
if kind == 'sub':
subs = self.master._sub
else:
subs = self.master._person
# Make placeholders each time we substitute something.
ph = []
i = 0
for pattern in self.master._sorted["lists"][kind]:
result = subs[pattern]
# Make a placeholder.
ph.append(result)
placeholder = "\x00%d\x00" % i
i += 1
cache = self.master._regexc[kind][pattern]
msg = re.sub(cache["sub1"], placeholder, msg)
msg = re.sub(cache["sub2"], placeholder + r'\1', msg)
msg = re.sub(cache["sub3"], r'\1' + placeholder + r'\2', msg)
msg = re.sub(cache["sub4"], r'\1' + placeholder, msg)
placeholders = re.findall(RE.placeholder, msg)
for match in placeholders:
i = int(match)
result = ph[i]
msg = msg.replace('\x00' + match + '\x00', result)
# Strip & return.
return msg.strip() | 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("You must call sort_replies() once you are done loading RiveScript documents")
# Get the substitution map.
subs = None
if kind == 'sub':
subs = self.master._sub
else:
subs = self.master._person
# Make placeholders each time we substitute something.
ph = []
i = 0
for pattern in self.master._sorted["lists"][kind]:
result = subs[pattern]
# Make a placeholder.
ph.append(result)
placeholder = "\x00%d\x00" % i
i += 1
cache = self.master._regexc[kind][pattern]
msg = re.sub(cache["sub1"], placeholder, msg)
msg = re.sub(cache["sub2"], placeholder + r'\1', msg)
msg = re.sub(cache["sub3"], r'\1' + placeholder + r'\2', msg)
msg = re.sub(cache["sub4"], r'\1' + placeholder, msg)
placeholders = re.findall(RE.placeholder, msg)
for match in placeholders:
i = int(match)
result = ph[i]
msg = msg.replace('\x00' + match + '\x00', result)
# Strip & return.
return msg.strip() | [
"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",
"(",
"\"You must call sort_replies() once you are done loading RiveScript documents\"",
")",
"# Get the substitution map.",
"subs",
"=",
"None",
"if",
"kind",
"==",
"'sub'",
":",
"subs",
"=",
"self",
".",
"master",
".",
"_sub",
"else",
":",
"subs",
"=",
"self",
".",
"master",
".",
"_person",
"# Make placeholders each time we substitute something.",
"ph",
"=",
"[",
"]",
"i",
"=",
"0",
"for",
"pattern",
"in",
"self",
".",
"master",
".",
"_sorted",
"[",
"\"lists\"",
"]",
"[",
"kind",
"]",
":",
"result",
"=",
"subs",
"[",
"pattern",
"]",
"# Make a placeholder.",
"ph",
".",
"append",
"(",
"result",
")",
"placeholder",
"=",
"\"\\x00%d\\x00\"",
"%",
"i",
"i",
"+=",
"1",
"cache",
"=",
"self",
".",
"master",
".",
"_regexc",
"[",
"kind",
"]",
"[",
"pattern",
"]",
"msg",
"=",
"re",
".",
"sub",
"(",
"cache",
"[",
"\"sub1\"",
"]",
",",
"placeholder",
",",
"msg",
")",
"msg",
"=",
"re",
".",
"sub",
"(",
"cache",
"[",
"\"sub2\"",
"]",
",",
"placeholder",
"+",
"r'\\1'",
",",
"msg",
")",
"msg",
"=",
"re",
".",
"sub",
"(",
"cache",
"[",
"\"sub3\"",
"]",
",",
"r'\\1'",
"+",
"placeholder",
"+",
"r'\\2'",
",",
"msg",
")",
"msg",
"=",
"re",
".",
"sub",
"(",
"cache",
"[",
"\"sub4\"",
"]",
",",
"r'\\1'",
"+",
"placeholder",
",",
"msg",
")",
"placeholders",
"=",
"re",
".",
"findall",
"(",
"RE",
".",
"placeholder",
",",
"msg",
")",
"for",
"match",
"in",
"placeholders",
":",
"i",
"=",
"int",
"(",
"match",
")",
"result",
"=",
"ph",
"[",
"i",
"]",
"msg",
"=",
"msg",
".",
"replace",
"(",
"'\\x00'",
"+",
"match",
"+",
"'\\x00'",
",",
"result",
")",
"# Strip & return.",
"return",
"msg",
".",
"strip",
"(",
")"
] | 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 = "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] = RSOBJ
except Exception as e:
print("Failed to load code from object", name)
print("The error given was: ", e) | 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] = RSOBJ
except Exception as e:
print("Failed to load code from object", name)
print("The error given was: ", e) | [
"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] = RSOBJ",
"except",
"Exception",
"as",
"e",
":",
"print",
"(",
"\"Failed to load code from object\"",
",",
"name",
")",
"print",
"(",
"\"The error given was: \"",
",",
"e",
")"
] | 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 words sent as the object's arguments.
:return str: The output of the object macro.
"""
# 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 = ''
except Exception as e:
raise PythonObjectError("Error executing Python object: " + str(e))
return text_type(reply) | 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 = ''
except Exception as e:
raise PythonObjectError("Error executing Python object: " + str(e))
return text_type(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",
"[",
"name",
"]",
"reply",
"=",
"''",
"try",
":",
"reply",
"=",
"func",
"(",
"rs",
",",
"fields",
")",
"if",
"reply",
"is",
"None",
":",
"reply",
"=",
"''",
"except",
"Exception",
"as",
"e",
":",
"raise",
"PythonObjectError",
"(",
"\"Error executing Python object: \"",
"+",
"str",
"(",
"e",
")",
")",
"return",
"text_type",
"(",
"reply",
")"
] | 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.
:return str: The output of the object macro. | [
"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 triggers for 'previous' replies?
depth (int): Recursion step counter.
inheritance (int): The inheritance level counter, for topics that
inherit other topics.
inherited (bool): Whether the current topic is inherited by others.
Returns:
[]str: List of all triggers found.
"""
# 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 inherit other topics are able to OVERRIDE
# triggers that appear in the inherited topic. This means that if the top
# topic has a trigger of simply '*', then NO triggers are capable of
# matching in ANY inherited topic, because even though * has the lowest
# priority, it has an automatic priority over all inherited topics.
#
# The getTopicTriggers method takes this into account. All topics that
# inherit other topics will have their triggers prefixed with a fictional
# {inherits} tag, which would start at {inherits=0} and increment if this
# topic has other inheriting topics. So we can use this tag to make sure
# topics that inherit things will have their triggers always be on top of
# the stack, from inherits=0 to inherits=n.
# Important info about the depth vs inheritance params to this function:
# depth increments by 1 each time this function recursively calls itrs.
# inheritance increments by 1 only when this topic inherits another
# topic.
#
# This way, '> topic alpha includes beta inherits gamma' will have this
# effect:
# alpha and beta's triggers are combined together into one matching
# pool, and then those triggers have higher matching priority than
# gamma's.
#
# The inherited option is True if this is a recursive call, from a topic
# that inherits other topics. This forces the {inherits} tag to be added
# to the triggers. This only applies when the top topic 'includes'
# another topic.
rs._say("\tCollecting trigger list for topic " + topic + "(depth="
+ str(depth) + "; inheritance=" + str(inheritance) + "; "
+ "inherited=" + str(inherited) + ")")
# topic: the name of the topic
# depth: starts at 0 and ++'s with each recursion
# Topic doesn't exist?
if not topic in rs._topics:
rs._warn("Inherited or included topic {} doesn't exist or has no triggers".format(
topic
))
return []
# Collect an array of triggers to return.
triggers = []
# Get those that exist in this topic directly.
inThisTopic = []
if not thats:
# The non-that structure is {topic}->[array of triggers]
if topic in rs._topics:
for trigger in rs._topics[topic]:
inThisTopic.append([ trigger["trigger"], trigger ])
else:
# The 'that' structure is: {topic}->{cur trig}->{prev trig}->{trig info}
if topic in rs._thats.keys():
for curtrig in rs._thats[topic].keys():
for previous, pointer in rs._thats[topic][curtrig].items():
inThisTopic.append([ pointer["trigger"], pointer ])
# Does this topic include others?
if topic in rs._includes:
# Check every included topic.
for includes in rs._includes[topic]:
rs._say("\t\tTopic " + topic + " includes " + includes)
triggers.extend(get_topic_triggers(rs, includes, thats, (depth + 1), inheritance, True))
# Does this topic inherit others?
if topic in rs._lineage:
# Check every inherited topic.
for inherits in rs._lineage[topic]:
rs._say("\t\tTopic " + topic + " inherits " + inherits)
triggers.extend(get_topic_triggers(rs, inherits, thats, (depth + 1), (inheritance + 1), False))
# Collect the triggers for *this* topic. If this topic inherits any
# other topics, it means that this topic's triggers have higher
# priority than those in any inherited topics. Enforce this with an
# {inherits} tag.
if topic in rs._lineage or inherited:
for trigger in inThisTopic:
rs._say("\t\tPrefixing trigger with {inherits=" + str(inheritance) + "}" + trigger[0])
triggers.append(["{inherits=" + str(inheritance) + "}" + trigger[0], trigger[1]])
else:
triggers.extend(inThisTopic)
return triggers | 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 inherit other topics are able to OVERRIDE
# triggers that appear in the inherited topic. This means that if the top
# topic has a trigger of simply '*', then NO triggers are capable of
# matching in ANY inherited topic, because even though * has the lowest
# priority, it has an automatic priority over all inherited topics.
#
# The getTopicTriggers method takes this into account. All topics that
# inherit other topics will have their triggers prefixed with a fictional
# {inherits} tag, which would start at {inherits=0} and increment if this
# topic has other inheriting topics. So we can use this tag to make sure
# topics that inherit things will have their triggers always be on top of
# the stack, from inherits=0 to inherits=n.
# Important info about the depth vs inheritance params to this function:
# depth increments by 1 each time this function recursively calls itrs.
# inheritance increments by 1 only when this topic inherits another
# topic.
#
# This way, '> topic alpha includes beta inherits gamma' will have this
# effect:
# alpha and beta's triggers are combined together into one matching
# pool, and then those triggers have higher matching priority than
# gamma's.
#
# The inherited option is True if this is a recursive call, from a topic
# that inherits other topics. This forces the {inherits} tag to be added
# to the triggers. This only applies when the top topic 'includes'
# another topic.
rs._say("\tCollecting trigger list for topic " + topic + "(depth="
+ str(depth) + "; inheritance=" + str(inheritance) + "; "
+ "inherited=" + str(inherited) + ")")
# topic: the name of the topic
# depth: starts at 0 and ++'s with each recursion
# Topic doesn't exist?
if not topic in rs._topics:
rs._warn("Inherited or included topic {} doesn't exist or has no triggers".format(
topic
))
return []
# Collect an array of triggers to return.
triggers = []
# Get those that exist in this topic directly.
inThisTopic = []
if not thats:
# The non-that structure is {topic}->[array of triggers]
if topic in rs._topics:
for trigger in rs._topics[topic]:
inThisTopic.append([ trigger["trigger"], trigger ])
else:
# The 'that' structure is: {topic}->{cur trig}->{prev trig}->{trig info}
if topic in rs._thats.keys():
for curtrig in rs._thats[topic].keys():
for previous, pointer in rs._thats[topic][curtrig].items():
inThisTopic.append([ pointer["trigger"], pointer ])
# Does this topic include others?
if topic in rs._includes:
# Check every included topic.
for includes in rs._includes[topic]:
rs._say("\t\tTopic " + topic + " includes " + includes)
triggers.extend(get_topic_triggers(rs, includes, thats, (depth + 1), inheritance, True))
# Does this topic inherit others?
if topic in rs._lineage:
# Check every inherited topic.
for inherits in rs._lineage[topic]:
rs._say("\t\tTopic " + topic + " inherits " + inherits)
triggers.extend(get_topic_triggers(rs, inherits, thats, (depth + 1), (inheritance + 1), False))
# Collect the triggers for *this* topic. If this topic inherits any
# other topics, it means that this topic's triggers have higher
# priority than those in any inherited topics. Enforce this with an
# {inherits} tag.
if topic in rs._lineage or inherited:
for trigger in inThisTopic:
rs._say("\t\tPrefixing trigger with {inherits=" + str(inheritance) + "}" + trigger[0])
triggers.append(["{inherits=" + str(inheritance) + "}" + trigger[0], trigger[1]])
else:
triggers.extend(inThisTopic)
return triggers | [
"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 inherit other topics are able to OVERRIDE",
"# triggers that appear in the inherited topic. This means that if the top",
"# topic has a trigger of simply '*', then NO triggers are capable of",
"# matching in ANY inherited topic, because even though * has the lowest",
"# priority, it has an automatic priority over all inherited topics.",
"#",
"# The getTopicTriggers method takes this into account. All topics that",
"# inherit other topics will have their triggers prefixed with a fictional",
"# {inherits} tag, which would start at {inherits=0} and increment if this",
"# topic has other inheriting topics. So we can use this tag to make sure",
"# topics that inherit things will have their triggers always be on top of",
"# the stack, from inherits=0 to inherits=n.",
"# Important info about the depth vs inheritance params to this function:",
"# depth increments by 1 each time this function recursively calls itrs.",
"# inheritance increments by 1 only when this topic inherits another",
"# topic.",
"#",
"# This way, '> topic alpha includes beta inherits gamma' will have this",
"# effect:",
"# alpha and beta's triggers are combined together into one matching",
"# pool, and then those triggers have higher matching priority than",
"# gamma's.",
"#",
"# The inherited option is True if this is a recursive call, from a topic",
"# that inherits other topics. This forces the {inherits} tag to be added",
"# to the triggers. This only applies when the top topic 'includes'",
"# another topic.",
"rs",
".",
"_say",
"(",
"\"\\tCollecting trigger list for topic \"",
"+",
"topic",
"+",
"\"(depth=\"",
"+",
"str",
"(",
"depth",
")",
"+",
"\"; inheritance=\"",
"+",
"str",
"(",
"inheritance",
")",
"+",
"\"; \"",
"+",
"\"inherited=\"",
"+",
"str",
"(",
"inherited",
")",
"+",
"\")\"",
")",
"# topic: the name of the topic",
"# depth: starts at 0 and ++'s with each recursion",
"# Topic doesn't exist?",
"if",
"not",
"topic",
"in",
"rs",
".",
"_topics",
":",
"rs",
".",
"_warn",
"(",
"\"Inherited or included topic {} doesn't exist or has no triggers\"",
".",
"format",
"(",
"topic",
")",
")",
"return",
"[",
"]",
"# Collect an array of triggers to return.",
"triggers",
"=",
"[",
"]",
"# Get those that exist in this topic directly.",
"inThisTopic",
"=",
"[",
"]",
"if",
"not",
"thats",
":",
"# The non-that structure is {topic}->[array of triggers]",
"if",
"topic",
"in",
"rs",
".",
"_topics",
":",
"for",
"trigger",
"in",
"rs",
".",
"_topics",
"[",
"topic",
"]",
":",
"inThisTopic",
".",
"append",
"(",
"[",
"trigger",
"[",
"\"trigger\"",
"]",
",",
"trigger",
"]",
")",
"else",
":",
"# The 'that' structure is: {topic}->{cur trig}->{prev trig}->{trig info}",
"if",
"topic",
"in",
"rs",
".",
"_thats",
".",
"keys",
"(",
")",
":",
"for",
"curtrig",
"in",
"rs",
".",
"_thats",
"[",
"topic",
"]",
".",
"keys",
"(",
")",
":",
"for",
"previous",
",",
"pointer",
"in",
"rs",
".",
"_thats",
"[",
"topic",
"]",
"[",
"curtrig",
"]",
".",
"items",
"(",
")",
":",
"inThisTopic",
".",
"append",
"(",
"[",
"pointer",
"[",
"\"trigger\"",
"]",
",",
"pointer",
"]",
")",
"# Does this topic include others?",
"if",
"topic",
"in",
"rs",
".",
"_includes",
":",
"# Check every included topic.",
"for",
"includes",
"in",
"rs",
".",
"_includes",
"[",
"topic",
"]",
":",
"rs",
".",
"_say",
"(",
"\"\\t\\tTopic \"",
"+",
"topic",
"+",
"\" includes \"",
"+",
"includes",
")",
"triggers",
".",
"extend",
"(",
"get_topic_triggers",
"(",
"rs",
",",
"includes",
",",
"thats",
",",
"(",
"depth",
"+",
"1",
")",
",",
"inheritance",
",",
"True",
")",
")",
"# Does this topic inherit others?",
"if",
"topic",
"in",
"rs",
".",
"_lineage",
":",
"# Check every inherited topic.",
"for",
"inherits",
"in",
"rs",
".",
"_lineage",
"[",
"topic",
"]",
":",
"rs",
".",
"_say",
"(",
"\"\\t\\tTopic \"",
"+",
"topic",
"+",
"\" inherits \"",
"+",
"inherits",
")",
"triggers",
".",
"extend",
"(",
"get_topic_triggers",
"(",
"rs",
",",
"inherits",
",",
"thats",
",",
"(",
"depth",
"+",
"1",
")",
",",
"(",
"inheritance",
"+",
"1",
")",
",",
"False",
")",
")",
"# Collect the triggers for *this* topic. If this topic inherits any",
"# other topics, it means that this topic's triggers have higher",
"# priority than those in any inherited topics. Enforce this with an",
"# {inherits} tag.",
"if",
"topic",
"in",
"rs",
".",
"_lineage",
"or",
"inherited",
":",
"for",
"trigger",
"in",
"inThisTopic",
":",
"rs",
".",
"_say",
"(",
"\"\\t\\tPrefixing trigger with {inherits=\"",
"+",
"str",
"(",
"inheritance",
")",
"+",
"\"}\"",
"+",
"trigger",
"[",
"0",
"]",
")",
"triggers",
".",
"append",
"(",
"[",
"\"{inherits=\"",
"+",
"str",
"(",
"inheritance",
")",
"+",
"\"}\"",
"+",
"trigger",
"[",
"0",
"]",
",",
"trigger",
"[",
"1",
"]",
"]",
")",
"else",
":",
"triggers",
".",
"extend",
"(",
"inThisTopic",
")",
"return",
"triggers"
] | 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.
inheritance (int): The inheritance level counter, for topics that
inherit other topics.
inherited (bool): Whether the current topic is inherited by others.
Returns:
[]str: List of all triggers found. | [
"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."""
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 | 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",
"(",
"RE",
".",
"wilds_and_optionals",
",",
"trigger",
")",
"wc",
"=",
"0",
"# Word count",
"for",
"word",
"in",
"words",
":",
"if",
"len",
"(",
"word",
")",
">",
"0",
":",
"wc",
"+=",
"1",
"return",
"wc"
] | 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, message)
# Send the response.
resp = twilio.twiml.Response()
resp.message(reply)
return str(resp) | 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()
resp.message(reply)
return str(resp) | [
"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",
"(",
")",
"resp",
".",
"message",
"(",
"reply",
")",
"return",
"str",
"(",
"resp",
")"
] | 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.