code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
---|---|---|---|---|---|
return "dir: " + str(self.config["dir"]) \
+ ", files: " + str(self.config["list_files"]) \
+ ", dirs: " + str(self.resolve_option("list_dirs")) \
+ ", recursive: " + str(self.config["recursive"]) | def quickinfo(self) | Returns a short string describing some of the options of the actor.
:return: the info, None if not available
:rtype: str | 4.586586 | 4.83251 | 0.949111 |
options = super(ListFiles, self).fix_config(options)
opt = "dir"
if opt not in options:
options[opt] = "."
if opt not in self.help:
self.help[opt] = "The directory to search (string)."
opt = "recursive"
if opt not in options:
options[opt] = False
if opt not in self.help:
self.help[opt] = "Whether to search recursively (bool)."
opt = "list_files"
if opt not in options:
options[opt] = True
if opt not in self.help:
self.help[opt] = "Whether to include files (bool)."
opt = "list_dirs"
if opt not in options:
options[opt] = False
if opt not in self.help:
self.help[opt] = "Whether to include directories (bool)."
opt = "regexp"
if opt not in options:
options[opt] = ".*"
if opt not in self.help:
self.help[opt] = "The regular expression that files/dirs must match (string)."
return options | def fix_config(self, options) | Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict | 1.834038 | 1.899685 | 0.965443 |
list_files = self.resolve_option("list_files")
list_dirs = self.resolve_option("list_dirs")
recursive = self.resolve_option("recursive")
spattern = str(self.resolve_option("regexp"))
pattern = None
if (spattern is not None) and (spattern != ".*"):
pattern = re.compile(spattern)
try:
items = os.listdir(path)
for item in items:
fp = path + os.sep + item
if list_files and os.path.isfile(fp):
if (pattern is None) or pattern.match(item):
collected.append(fp)
if list_dirs and os.path.isdir(fp):
if (pattern is None) or pattern.match(item):
collected.append(fp)
if recursive and os.path.isdir(fp):
self._list(fp, collected)
except Exception as e:
return "Error listing '" + path + "': " + str(e) | def _list(self, path, collected) | Lists all the files/dirs in directory that match the pattern.
:param path: the directory to search
:type path: str
:param collected: the files/dirs collected so far (full path)
:type collected: list
:return: None if successful, error otherwise
:rtype: str | 2.222301 | 2.270455 | 0.978791 |
directory = str(self.resolve_option("dir"))
if not os.path.exists(directory):
return "Directory '" + directory + "' does not exist!"
if not os.path.isdir(directory):
return "Location '" + directory + "' is not a directory!"
collected = []
result = self._list(directory, collected)
if result is None:
for c in collected:
self._output.append(Token(c))
return result | def do_execute(self) | The actual execution of the actor.
:return: None if successful, otherwise error message
:rtype: str | 4.486608 | 4.414887 | 1.016245 |
options = super(GetStorageValue, self).fix_config(options)
opt = "storage_name"
if opt not in options:
options[opt] = "unknown"
if opt not in self.help:
self.help[opt] = "The name of the storage value to retrieve (string)."
return options | def fix_config(self, options) | Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict | 5.104459 | 5.897116 | 0.865586 |
if self.storagehandler is None:
return "No storage handler available!"
sname = str(self.resolve_option("storage_name"))
if sname not in self.storagehandler.storage:
return "No storage item called '" + sname + "' present!"
self._output.append(Token(self.storagehandler.storage[sname]))
return None | def do_execute(self) | The actual execution of the actor.
:return: None if successful, otherwise error message
:rtype: str | 6.774808 | 6.534309 | 1.036806 |
options = super(ForLoop, self).fix_config(options)
opt = "min"
if opt not in options:
options[opt] = 1
if opt not in self.help:
self.help[opt] = "The minimum for the loop (included, int)."
opt = "max"
if opt not in options:
options[opt] = 10
if opt not in self.help:
self.help[opt] = "The maximum for the loop (included, int)."
opt = "step"
if opt not in options:
options[opt] = 1
if opt not in self.help:
self.help[opt] = "The step size (int)."
return options | def fix_config(self, options) | Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict | 2.279399 | 2.335729 | 0.975883 |
for i in range(
int(self.resolve_option("min")),
int(self.resolve_option("max")) + 1,
int(self.resolve_option("step"))):
self._output.append(Token(i))
return None | def do_execute(self) | The actual execution of the actor.
:return: None if successful, otherwise error message
:rtype: str | 5.374179 | 5.466762 | 0.983064 |
opt = "db_url"
if opt not in options:
options[opt] = "jdbc:mysql://somehost:3306/somedatabase"
if opt not in self.help:
self.help[opt] = "The JDBC database URL to connect to (str)."
opt = "user"
if opt not in options:
options[opt] = "user"
if opt not in self.help:
self.help[opt] = "The database user to use for connecting (str)."
opt = "password"
if opt not in options:
options[opt] = "secret"
if opt not in self.help:
self.help[opt] = "The password for the database user (str)."
opt = "query"
if opt not in options:
options[opt] = "SELECT * FROM table"
if opt not in self.help:
self.help[opt] = "The SQL query for generating the dataset (str)."
opt = "sparse"
if opt not in options:
options[opt] = False
if opt not in self.help:
self.help[opt] = "Whether to return the data in sparse format (bool)."
opt = "custom_props"
if opt not in options:
options[opt] = ""
if opt not in self.help:
self.help[opt] = "Custom properties filename (str)."
return super(LoadDatabase, self).fix_config(options) | def fix_config(self, options) | Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict | 2.126395 | 2.159485 | 0.984677 |
iquery = InstanceQuery()
iquery.db_url = str(self.resolve_option("db_url"))
iquery.user = str(self.resolve_option("user"))
iquery.password = str(self.resolve_option("password"))
props = str(self.resolve_option("custom_props"))
if (len(props) > 0) and os.path.isfile(props):
iquery.custom_properties = props
iquery.query = str(self.resolve_option("query"))
data = iquery.retrieve_instances()
self._output.append(Token(data))
return None | def do_execute(self) | The actual execution of the actor.
:return: None if successful, otherwise error message
:rtype: str | 3.8621 | 3.831719 | 1.007929 |
opt = "setup"
if opt not in options:
options[opt] = datagen.DataGenerator(classname="weka.datagenerators.classifiers.classification.Agrawal")
if opt not in self.help:
self.help[opt] = "The data generator to use (DataGenerator)."
opt = "incremental"
if opt not in options:
options[opt] = False
if opt not in self.help:
self.help[opt] = "Whether to output the data incrementally, in case the generator supports that (bool)."
return super(DataGenerator, self).fix_config(options) | def fix_config(self, options) | Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict | 4.999303 | 4.968476 | 1.006205 |
if k == "setup":
return base.to_commandline(v)
return super(DataGenerator, self).to_config(k, v) | def to_config(self, k, v) | Hook method that allows conversion of individual options.
:param k: the key of the option
:type k: str
:param v: the value
:type v: object
:return: the potentially processed value
:rtype: object | 7.444757 | 9.038914 | 0.823634 |
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) | 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 | 9.527073 | 11.928812 | 0.798661 |
generator = datagen.DataGenerator.make_copy(self.resolve_option("setup"))
generator.dataset_format = generator.define_data_format()
if bool(self.resolve_option("incremental")) and generator.single_mode_flag:
for i in range(generator.num_examples_act):
self._output.append(Token(generator.generate_example()))
else:
data = generator.generate_examples()
self._output.append(Token(data))
return None | def do_execute(self) | The actual execution of the actor.
:return: None if successful, otherwise error message
:rtype: str | 9.070274 | 9.115243 | 0.995067 |
options = super(CombineStorage, self).fix_config(options)
opt = "format"
if opt not in options:
options[opt] = ""
if opt not in self.help:
self.help[opt] = "The format to use for generating the combined string; use '@{blah}' for accessing "\
"storage item 'blah' (string)."
return options | def fix_config(self, options) | Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict | 9.907729 | 11.06297 | 0.895576 |
formatstr = str(self.resolve_option("format"))
expanded = self.storagehandler.expand(formatstr)
self._output.append(Token(expanded))
return None | def do_execute(self) | The actual execution of the actor.
:return: None if successful, otherwise error message
:rtype: str | 21.70269 | 22.075062 | 0.983132 |
options = super(StringConstants, self).fix_config(options)
opt = "strings"
if opt not in options:
options[opt] = []
if opt not in self.help:
self.help[opt] = "The strings to output (list of string)."
return options | def fix_config(self, options) | Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict | 5.469515 | 6.32073 | 0.86533 |
for s in self.resolve_option("strings"):
self._output.append(Token(s))
return None | def do_execute(self) | The actual execution of the actor.
:return: None if successful, otherwise error message
:rtype: str | 24.463732 | 25.995251 | 0.941085 |
result = super(Sink, self).post_execute()
if result is None:
self._input = None
return result | def post_execute(self) | Gets executed after the actual execution.
:return: None if successful, otherwise error message
:rtype: str | 7.328916 | 8.110748 | 0.903605 |
options = super(Console, self).fix_config(options)
opt = "prefix"
if opt not in options:
options[opt] = ""
if opt not in self.help:
self.help[opt] = "The prefix for the output (string)."
return options | def fix_config(self, options) | Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict | 4.678596 | 5.211709 | 0.897709 |
options = super(FileOutputSink, self).fix_config(options)
opt = "output"
if opt not in options:
options[opt] = "."
if opt not in self.help:
self.help[opt] = "The file to write to (string)."
return options | def fix_config(self, options) | Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict | 5.045625 | 5.911604 | 0.853512 |
options = super(DumpFile, self).fix_config(options)
opt = "append"
if opt not in options:
options[opt] = False
if opt not in self.help:
self.help[opt] = "Whether to append to the file or overwrite (bool)."
return options | def fix_config(self, options) | Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict | 4.840782 | 5.588987 | 0.866129 |
result = None
f = None
try:
if bool(self.resolve_option("append")):
f = open(str(self.resolve_option("output")), "a")
else:
f = open(str(self.resolve_option("output")), "w")
f.write(str(self.input.payload))
f.write("\n")
except Exception as e:
result = self.full_name + "\n" + traceback.format_exc()
finally:
if f is not None:
f.close()
return result | def do_execute(self) | The actual execution of the actor.
:return: None if successful, otherwise error message
:rtype: str | 3.190384 | 2.988695 | 1.067484 |
if not isinstance(token.payload, ModelContainer):
raise Exception(self.full_name + ": Input token is not a ModelContainer!") | def check_input(self, token) | Performs checks on the input token. Raises an exception if unsupported.
:param token: the token to check
:type token: Token | 12.015512 | 14.060963 | 0.85453 |
result = None
cont = self.input.payload
serialization.write_all(
str(self.resolve_option("output")),
[cont.get("Model").jobject, cont.get("Header").jobject])
return result | def do_execute(self) | The actual execution of the actor.
:return: None if successful, otherwise error message
:rtype: str | 23.920528 | 21.615364 | 1.106645 |
options = super(MatrixPlot, self).fix_config(options)
opt = "percent"
if opt not in options:
options[opt] = 100.0
if opt not in self.help:
self.help[opt] = "The percentage of the data to display (0-100, float)."
opt = "seed"
if opt not in options:
options[opt] = 1
if opt not in self.help:
self.help[opt] = "The seed value for randomizing the plot when viewing a subset (int)."
opt = "size"
if opt not in options:
options[opt] = 10
if opt not in self.help:
self.help[opt] = "The size of the circles in the plot (int)."
opt = "title"
if opt not in options:
options[opt] = None
if opt not in self.help:
self.help[opt] = "The title for the plot (str)."
opt = "outfile"
if opt not in options:
options[opt] = None
if opt not in self.help:
self.help[opt] = "The file to store the plot in (str)."
opt = "wait"
if opt not in options:
options[opt] = True
if opt not in self.help:
self.help[opt] = "Whether to wait for user to close the plot window (bool)."
return options | def fix_config(self, options) | Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict | 2.025046 | 2.084896 | 0.971293 |
options = super(LinePlot, self).fix_config(options)
opt = "attributes"
if opt not in options:
options[opt] = None
if opt not in self.help:
self.help[opt] = "The list of 0-based attribute indices to print; None for all (int)."
opt = "percent"
if opt not in options:
options[opt] = 100.0
if opt not in self.help:
self.help[opt] = "The percentage of the data to display (0-100, float)."
opt = "seed"
if opt not in options:
options[opt] = 1
if opt not in self.help:
self.help[opt] = "The seed value for randomizing the plot when viewing a subset (int)."
opt = "title"
if opt not in options:
options[opt] = None
if opt not in self.help:
self.help[opt] = "The title for the plot (str)."
opt = "outfile"
if opt not in options:
options[opt] = None
if opt not in self.help:
self.help[opt] = "The file to store the plot in (str)."
opt = "wait"
if opt not in options:
options[opt] = True
if opt not in self.help:
self.help[opt] = "Whether to wait for user to close the plot window (bool)."
return options | def fix_config(self, options) | Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict | 2.264987 | 2.35652 | 0.961158 |
result = None
data = self.input.payload
pltdataset.line_plot(
data,
atts=self.resolve_option("attributes"),
percent=float(self.resolve_option("percent")),
seed=int(self.resolve_option("seed")),
title=self.resolve_option("title"),
outfile=self.resolve_option("outfile"),
wait=bool(self.resolve_option("wait")))
return result | def do_execute(self) | The actual execution of the actor.
:return: None if successful, otherwise error message
:rtype: str | 6.322665 | 6.204335 | 1.019072 |
options = super(ClassifierErrors, self).fix_config(options)
opt = "absolute"
if opt not in options:
options[opt] = True
if opt not in self.help:
self.help[opt] = "Whether to use absolute errors as size or relative ones (bool)."
opt = "max_relative_size"
if opt not in options:
options[opt] = 50
if opt not in self.help:
self.help[opt] = "The maximum size in point in case of relative mode (int)."
opt = "absolute_size"
if opt not in options:
options[opt] = 50
if opt not in self.help:
self.help[opt] = "The size in point in case of absolute mode (int)."
opt = "title"
if opt not in options:
options[opt] = None
if opt not in self.help:
self.help[opt] = "The title for the plot (str)."
opt = "outfile"
if opt not in options:
options[opt] = None
if opt not in self.help:
self.help[opt] = "The file to store the plot in (str)."
opt = "wait"
if opt not in options:
options[opt] = True
if opt not in self.help:
self.help[opt] = "Whether to wait for user to close the plot window (bool)."
return options | def fix_config(self, options) | Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict | 2.133651 | 2.183335 | 0.977244 |
if not isinstance(token.payload, Evaluation):
raise Exception(self.full_name + ": Input token is not an Evaluation object!") | def check_input(self, token) | Performs checks on the input token. Raises an exception if unsupported.
:param token: the token to check
:type token: Token | 12.965484 | 15.089693 | 0.859228 |
result = None
evl = self.input.payload
pltclassifier.plot_classifier_errors(
evl.predictions,
absolute=bool(self.resolve_option("absolute")),
max_relative_size=int(self.resolve_option("max_relative_size")),
absolute_size=int(self.resolve_option("absolute_size")),
title=self.resolve_option("title"),
outfile=self.resolve_option("outfile"),
wait=bool(self.resolve_option("wait")))
return result | def do_execute(self) | The actual execution of the actor.
:return: None if successful, otherwise error message
:rtype: str | 6.033694 | 5.996435 | 1.006213 |
options = super(ROC, self).fix_config(options)
opt = "class_index"
if opt not in options:
options[opt] = [0]
if opt not in self.help:
self.help[opt] = "The list of 0-based class-label indices to display (list)."
opt = "key_loc"
if opt not in options:
options[opt] = "lower right"
if opt not in self.help:
self.help[opt] = "The location of the key in the plot (str)."
opt = "title"
if opt not in options:
options[opt] = None
if opt not in self.help:
self.help[opt] = "The title for the plot (str)."
opt = "outfile"
if opt not in options:
options[opt] = None
if opt not in self.help:
self.help[opt] = "The file to store the plot in (str)."
opt = "wait"
if opt not in options:
options[opt] = True
if opt not in self.help:
self.help[opt] = "Whether to wait for user to close the plot window (bool)."
return options | def fix_config(self, options) | Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict | 2.229239 | 2.332136 | 0.955879 |
options = super(PRC, self).fix_config(options)
opt = "class_index"
if opt not in options:
options[opt] = [0]
if opt not in self.help:
self.help[opt] = "The list of 0-based class-label indices to display (list)."
opt = "key_loc"
if opt not in options:
options[opt] = "lower center"
if opt not in self.help:
self.help[opt] = "The location of the key in the plot (str)."
opt = "title"
if opt not in options:
options[opt] = None
if opt not in self.help:
self.help[opt] = "The title for the plot (str)."
opt = "outfile"
if opt not in options:
options[opt] = None
if opt not in self.help:
self.help[opt] = "The file to store the plot in (str)."
opt = "wait"
if opt not in options:
options[opt] = True
if opt not in self.help:
self.help[opt] = "Whether to wait for user to close the plot window (bool)."
return options | def fix_config(self, options) | Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict | 2.257967 | 2.348779 | 0.961337 |
result = None
evl = self.input.payload
pltclassifier.plot_prc(
evl,
class_index=self.resolve_option("class_index"),
title=self.resolve_option("title"),
key_loc=self.resolve_option("key_loc"),
outfile=self.resolve_option("outfile"),
wait=bool(self.resolve_option("wait")))
return result | def do_execute(self) | The actual execution of the actor.
:return: None if successful, otherwise error message
:rtype: str | 7.845672 | 8.013375 | 0.979072 |
result = None
data = self.input.payload
if isinstance(self._input.payload, Instance):
inst = self.input.payload
data = inst.dataset
elif isinstance(self.input.payload, Instances):
data = self.input.payload
inst = None
append = True
if self._header is None or (self._header.equal_headers(data) is not None):
self._header = Instances.template_instances(data, 0)
outstr = str(data)
append = False
elif inst is not None:
outstr = str(inst)
else:
outstr = str(data)
f = None
try:
if append:
f = open(str(self.resolve_option("output")), "a")
else:
f = open(str(self.resolve_option("output")), "w")
f.write(outstr)
f.write("\n")
except Exception as e:
result = self.full_name + "\n" + traceback.format_exc()
finally:
if f is not None:
f.close()
return result | def do_execute(self) | The actual execution of the actor.
:return: None if successful, otherwise error message
:rtype: str | 3.880408 | 3.786462 | 1.024811 |
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) | Configures and returns the SplitEvaluator and Classifier instance as tuple.
:return: evaluator and classifier
:rtype: tuple | 3.328075 | 3.267534 | 1.018528 |
# 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) | Initializes the experiment. | 2.165128 | 2.152083 | 1.006062 |
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) | Executes the experiment. | 3.411167 | 3.039342 | 1.122337 |
jobject = javabridge.static_call(
"weka/experiment/Experiment", "read", "(Ljava/lang/String;)Lweka/experiment/Experiment;",
filename)
return Experiment(jobject=jobject) | 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 | 5.436683 | 5.315521 | 1.022794 |
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) | Configures and returns the ResultProducer and PropertyPath as tuple.
:return: producer and property path
:rtype: tuple | 2.307375 | 2.245021 | 1.027775 |
javabridge.call(self.jobject, "setRowName", "(ILjava/lang/String;)V", index, 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 | 4.06458 | 4.05179 | 1.003157 |
javabridge.call(self.jobject, "setColName", "(ILjava/lang/String;)V", index, 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 | 4.194018 | 4.223117 | 0.99311 |
return javabridge.call(self.jobject, "getMean", "(II)D", col, row) | def get_mean(self, col, row) | Returns the mean at this location (if valid location).
:param col: the 0-based column index
:type col: int
:param row: the 0-based row index
:type row: int
:return: the mean
:rtype: float | 5.775783 | 5.961674 | 0.968819 |
javabridge.call(self.jobject, "setMean", "(IID)V", col, row, mean) | def set_mean(self, col, row, mean) | Sets the mean at this location (if valid location).
:param col: the 0-based column index
:type col: int
:param row: the 0-based row index
:type row: int
:param mean: the mean to set
:type mean: float | 5.78529 | 5.897328 | 0.981002 |
return javabridge.call(self.jobject, "getStdDev", "(II)D", col, row) | def get_stdev(self, col, row) | Returns the standard deviation at this location (if valid location).
:param col: the 0-based column index
:type col: int
:param row: the 0-based row index
:type row: int
:return: the standard deviation
:rtype: float | 5.667764 | 5.963448 | 0.950417 |
javabridge.call(self.jobject, "setStdDev", "(IID)V", col, row, stdev) | def set_stdev(self, col, row, stdev) | Sets the standard deviation at this location (if valid location).
:param col: the 0-based column index
:type col: int
:param row: the 0-based row index
:type row: int
:param stdev: the standard deviation to set
:type stdev: float | 5.862227 | 5.69185 | 1.029934 |
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) | Checks that at least required params exist | 3.920292 | 3.839576 | 1.021022 |
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) | 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') | 4.989601 | 5.489159 | 0.908992 |
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) | Abstraction for grabbing content from a returned response | 6.368833 | 6.405096 | 0.994338 |
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) | 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 | 4.243107 | 4.084573 | 1.038813 |
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') | Return a dictionary which can be used as is or added to for
payloads | 5.301429 | 4.951056 | 1.070767 |
return len(self.events) > 0 and \
len(self.arm_nums) > 0 and \
len(self.arm_names) > 0 | def is_longitudinal(self) | Returns
-------
boolean :
longitudinal status of this project | 5.23194 | 6.218283 | 0.84138 |
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) | 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 | 3.785403 | 3.828297 | 0.988796 |
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) | 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 | 4.402174 | 4.272166 | 1.030431 |
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) | 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. | 3.427099 | 3.444124 | 0.995057 |
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) | 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 | 3.301558 | 3.033665 | 1.088307 |
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) | Return the value for key for the field in the metadata | 4.768062 | 4.520652 | 1.054729 |
if forms and not fields:
new_fields = [self.def_field]
elif fields and self.def_field not in fields:
new_fields = list(fields)
if self.def_field not in fields:
new_fields.append(self.def_field)
elif not fields:
new_fields = self.field_names
else:
new_fields = list(fields)
return new_fields | def backfill_fields(self, fields, forms) | Properly backfill fields to explicitly request specific
keys. The issue is that >6.X servers *only* return requested fields
so to improve backwards compatiblity for PyCap clients, add specific fields
when required.
Parameters
----------
fields: list
requested fields
forms: list
requested forms
Returns
-------
new fields, forms | 2.482528 | 2.749152 | 0.903016 |
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 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. | 4.493304 | 4.454881 | 1.008625 |
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) | Simple helper function to get all field names and labels | 2.372611 | 2.075127 | 1.143357 |
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) | 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'`` | 3.126214 | 3.156391 | 0.99044 |
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') | 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 | 4.944016 | 4.848618 | 1.019675 |
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') | 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`` | 5.601684 | 6.340606 | 0.883462 |
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) | 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 | 5.030388 | 6.389164 | 0.787331 |
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) | Check that field exists and is a file field | 4.048696 | 3.632187 | 1.114672 |
pl = self.__basepl(content='user', format=format)
return self._call_api(pl, 'exp_user')[0] | 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 | 18.126373 | 35.156281 | 0.515594 |
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') | 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 | 6.528719 | 8.687018 | 0.751549 |
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) | 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). | 9.151263 | 7.069972 | 1.294385 |
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) | Entrypoint to route messages between plugins. | 6.29088 | 5.367689 | 1.17199 |
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) | Gracefully cancel current tasks when app receives a shutdown signal. | 2.388511 | 2.264215 | 1.054896 |
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) | Additively merge right side dict into left side dict. | 1.554427 | 1.450016 | 1.072007 |
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) | 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. | 3.093756 | 2.989541 | 1.03486 |
self.transport = transport
self.transport.sendto(self.message)
self.transport.close() | def connection_made(self, transport) | Create connection, use to send message and close.
Args:
transport (asyncio.DatagramTransport): Transport used for sending. | 3.928038 | 3.620686 | 1.084888 |
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) | Transform metric to JSON bytestring and send to server.
Args:
metric (dict): Complete metric to send as JSON. | 3.078286 | 3.226395 | 0.954095 |
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) | 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. | 4.360099 | 4.262062 | 1.023002 |
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) | 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. | 3.265658 | 3.635214 | 0.89834 |
encoding = kwargs.get('encoding', 'utf-8')
sep = kwargs.get('sep', '\n')
buf = []
for fl in filenames:
with codecs.open(os.path.join(HERE, fl), 'rb', encoding) as f:
buf.append(f.read())
return sep.join(buf) | def read(*filenames, **kwargs) | Build an absolute path from ``*filenames``, and return contents of
resulting file. Defaults to UTF-8 encoding. | 2.242411 | 2.269715 | 0.98797 |
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) | Format and output metric.
Args:
metric (dict): Complete metric. | 5.370247 | 6.723957 | 0.798674 |
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) | 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. | 3.023229 | 3.72123 | 0.812427 |
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) | 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. | 5.751228 | 6.766154 | 0.85 |
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) | 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. | 5.014334 | 5.679571 | 0.882872 |
step2 = ColTrans(self.keyword).decipher(string)
step1 = PolybiusSquare(self.key,size=6,chars='ADFGVX').decipher(step2)
return step1 | 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. | 14.401917 | 14.112472 | 1.02051 |
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) | 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. | 3.2733 | 3.624214 | 0.903175 |
''' 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) | takes ciphertext, calculates index of coincidence. | 4.378196 | 3.453188 | 1.267871 |
''' if N=1, return a dict containing each letter along with how many times the letter occurred.
if N=2, returns a dict containing counts of each bigram (pair of letters)
etc.
There is an option to remove all spaces and punctuation prior to processing '''
if not keep_punct: text = re.sub('[^A-Z]','',text.upper())
count = {}
for i in range(len(text)-N+1):
c = text[i:i+N]
if c in count: count[c] += 1
else: count[c] = 1.0
return count | def ngram_count(text,N=1,keep_punct=False) | if N=1, return a dict containing each letter along with how many times the letter occurred.
if N=2, returns a dict containing counts of each bigram (pair of letters)
etc.
There is an option to remove all spaces and punctuation prior to processing | 4.379215 | 1.894717 | 2.311277 |
''' returns the n-gram frequencies of all n-grams encountered in text.
Option to return log probabilities or standard probabilities.
Note that only n-grams occurring in 'text' will have probabilities.
For the probability of not-occurring n-grams, use freq['floor'].
This is set to floor/len(text) '''
freq = ngram_count(text,N)
L = 1.0*(len(text)-N+1)
for c in freq.keys():
if log: freq[c] = math.log10(freq[c]/L)
else: freq[c] = freq[c]/L
if log: freq['floor'] = math.log10(floor/L)
else: freq['floor'] = floor/L
return freq | def ngram_freq(text,N=1,log=False,floor=0.01) | returns the n-gram frequencies of all n-grams encountered in text.
Option to return log probabilities or standard probabilities.
Note that only n-grams occurring in 'text' will have probabilities.
For the probability of not-occurring n-grams, use freq['floor'].
This is set to floor/len(text) | 4.462799 | 1.850268 | 2.411974 |
''' 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) | If punctuation was accidently removed, use this function to restore it.
requires the orignial string with punctuation. | 6.398579 | 4.033292 | 1.586441 |
''' convert a key word to a key by appending on the other letters of the alphabet.
e.g. MONARCHY -> MONARCHYBDEFGIJKLPQSTUVWXZ
'''
ret = ''
word = (word + alphabet).upper()
for i in word:
if i in ret: continue
ret += i
return ret | def keyword_to_key(word,alphabet='ABCDEFGHIJKLMNOPQRSTUVWXYZ') | convert a key word to a key by appending on the other letters of the alphabet.
e.g. MONARCHY -> MONARCHYBDEFGIJKLPQSTUVWXZ | 10.065548 | 2.828178 | 3.559022 |
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) | 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. | 3.056269 | 3.089787 | 0.989152 |
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) | 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. | 2.818997 | 2.752597 | 1.024123 |
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) | 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. | 8.644608 | 9.565595 | 0.903719 |
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) | 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. | 5.659142 | 6.049271 | 0.935508 |
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) | 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. | 3.393305 | 3.424036 | 0.991025 |
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) | 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. | 3.475384 | 3.61619 | 0.961062 |
r
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) | 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. | 4.221045 | 3.912865 | 1.078761 |
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) | 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. | 2.038419 | 2.05923 | 0.989894 |
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) | 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. | 5.024487 | 5.208415 | 0.964686 |
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) | 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. | 2.867544 | 2.973396 | 0.9644 |
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) | 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. | 5.050065 | 6.144127 | 0.821934 |
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) | 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. | 6.250831 | 7.095693 | 0.880933 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.