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:
... | 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 != ".*"):
pat... | 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 =... | 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.st... | 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:
o... | 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] = "... | 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.isfi... | 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"
... | 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._o... | 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 "\
... | 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))
... | 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 i... | 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"
... | 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"... | 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_relati... | 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_o... | 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 no... | 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 no... | 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("outfil... | 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
app... | 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/... | 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, "setUsePropertyIterat... | 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_spl... | 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 cont... | 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'|'... | 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:
... | 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) er... | 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:
... | 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''`` wi... | 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):
... | 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 o... | 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,... | 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
... | 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 =... | 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... | 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, sel... | 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
---... | 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']... | 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:
... | 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
... | 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.
... | 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'] ... | 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 o... | 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:
... | 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 mess... | 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
* ``'expira... | 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... | 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#{}".f... | 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 ... | 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, r... | 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 [], [], ... | 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 objec... | 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 > retr... | 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 th... | 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
... | 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.
... | 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 s... | 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 lengt... | 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 ... | 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.... | 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'),
... | 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(... | 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 flo... | 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(t... | 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
... | 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(plaintex... | 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 = Play... | 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 p... | 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 cipher... | 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='mfnbdcr... | 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 = Fo... | 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... | 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'[... | 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 n... | 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 ... | 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 = morses... | 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 enciphere... | 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.