code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if file_path is None:
return
if isinstance(file_path, six.binary_type):
file_path = file_path.decode(sys.getfilesystemencoding())
return file_path | def decode_path(file_path) | Turn a path name into unicode. | 2.508698 | 2.110691 | 1.188567 |
# Do a non-blocking read here so the demo can keep running if there is no data
comm = self.reader.byte(blocking=False)
if comm is None:
return False
cmds = {
SET_KEY: self.handle_set_key,
DELETE_KEY: self.handle_delete_key,
SET_RO... | def read_command(self) | Attempt to read the next command from the editor/server
:return: boolean. Did we actually read a command? | 4.487762 | 4.323418 | 1.038012 |
track_id = self.reader.int()
row = self.reader.int()
value = self.reader.float()
kind = self.reader.byte()
logger.info(" -> track=%s, row=%s, value=%s, type=%s", track_id, row, value, kind)
# Add or update track value
track = self.tracks.get_by_id(track_... | def handle_set_key(self) | Read incoming key from server | 3.937307 | 3.814206 | 1.032274 |
track_id = self.reader.int()
row = self.reader.int()
logger.info(" -> track=%s, row=%s", track_id, row)
# Delete the actual track value
track = self.tracks.get_by_id(track_id)
track.delete(row) | def handle_delete_key(self) | Read incoming delete key event from server | 5.975807 | 5.585773 | 1.069826 |
row = self.reader.int()
logger.info(" -> row: %s", row)
self.controller.row = row | def handle_set_row(self) | Read incoming row change from server | 10.874722 | 9.36916 | 1.160693 |
flag = self.reader.byte()
if flag > 0:
logger.info(" -> pause: on")
self.controller.playing = False
else:
logger.info(" -> pause: off")
self.controller.playing = True | def handle_pause(self) | Read pause signal from server | 6.318562 | 5.055294 | 1.24989 |
result = {}
apps = [item.model.split(' - ')[0] for item in TransModelLanguage.objects.all()]
qs = ContentType.objects.exclude(model__contains='translation').filter(app_label__in=apps).order_by(
'app_label', 'model'
)
for ct in qs:
if not issubcla... | def get_choices_for_models() | Get the select choices for models in optgroup mode
:return: | 3.293641 | 3.27284 | 1.006356 |
params = {
'latrange1': lat_range[0] if lat_range else "",
'latrange2': lat_range[1] if lat_range else "",
'longrange1': long_range[0] if long_range else "",
'longrange2': long_range[1] if long_range else "",
'variance': str(variance) if vari... | def search(self, lat_range=None, long_range=None, variance=None,
bssid=None, ssid=None,
last_update=None,
address=None, state=None, zipcode=None,
on_new_page=None, max_results=100) | Search the Wigle wifi database for matching entries. The following
criteria are supported:
Args:
lat_range ((float, float)): latitude range
long_range ((float, float)): longitude range
variance (float): radius tolerance in degrees
bssid (str): BSSID/MAC o... | 2.612807 | 2.745471 | 0.951679 |
super().save(force_insert, force_update, using, update_fields)
if self.main_language:
TransLanguage.objects.exclude(pk=self.pk).update(main_language=False) | def save(self, force_insert=False, force_update=False, using=None, update_fields=None) | Overwrite of the save method in order that when setting the language
as main we deactivate any other model selected as main before
:param force_insert:
:param force_update:
:param using:
:param update_fields:
:return: | 3.746876 | 3.38901 | 1.105596 |
active_orgs = apps.get_model("orgs", "Org").objects.filter(is_active=True)
for org in active_orgs:
sig = signature(task_name, args=[org.pk])
sig.apply_async(queue=queue)
logger.info("Requested task '%s' for %d active orgs" % (task_name, len(active_orgs))) | def trigger_org_task(task_name, queue="celery") | Triggers the given org task to be run for all active orgs
:param task_name: the full task name, e.g. 'myproj.myapp.tasks.do_stuff'
:param queue: the name of the queue to send org sub-tasks to | 3.145202 | 3.404167 | 0.923927 |
def _org_task(task_func):
def _decorator(org_id):
org = apps.get_model("orgs", "Org").objects.get(pk=org_id)
maybe_run_for_org(org, task_func, task_key, lock_timeout)
return shared_task(wraps(task_func)(_decorator))
return _org_task | def org_task(task_key, lock_timeout=None) | Decorator to create an org task.
:param task_key: the task key used for state storage and locking, e.g. 'do-stuff'
:param lock_timeout: the lock timeout in seconds | 4.244113 | 4.242439 | 1.000395 |
r = get_redis_connection()
key = TaskState.get_lock_key(org, task_key)
if r.get(key):
logger.warning("Skipping task %s for org #%d as it is still running" % (task_key, org.id))
else:
with r.lock(key, timeout=lock_timeout):
state = org.get_task_state(task_key)
... | def maybe_run_for_org(org, task_func, task_key, lock_timeout) | Runs the given task function for the specified org provided it's not already running
:param org: the org
:param task_func: the task function
:param task_key: the task key
:param lock_timeout: the lock timeout in seconds | 2.02311 | 2.073533 | 0.975683 |
metadata_type = self.column_metadata.get('type')
if self.type != metadata_type and metadata_type not in self.type:
raise ValueError('Types of transformer don\'t match') | def check_data_type(self) | Check the type of the transformer and column match.
Args:
column_metadata(dict): Metadata of the column.
Raises a ValueError if the types don't match | 7.844191 | 5.506505 | 1.424532 |
dates = self.safe_datetime_cast(col)
self.default_val = dates.groupby(dates).count().index[0].timestamp() * 1e9 | def fit(self, col) | Prepare the transformer to convert data.
Args:
col(pandas.DataFrame): Data to transform.
Returns:
None | 14.90696 | 17.714666 | 0.841504 |
out = pd.DataFrame()
out[self.col_name] = self.safe_datetime_cast(col)
out[self.col_name] = self.to_timestamp(out)
return out | def transform(self, col) | Prepare the transformer to convert data and return the processed table.
Args:
col(pandas.DataFrame): Data to transform.
Returns:
pandas.DataFrame | 6.207765 | 8.527958 | 0.727931 |
if isinstance(col, pd.Series):
col = col.to_frame()
output = pd.DataFrame(index=col.index)
output[self.col_name] = col.apply(self.safe_date, axis=1)
return output | def reverse_transform(self, col) | Converts data back into original format.
Args:
col(pandas.DataFrame): Data to transform.
Returns:
pandas.DataFrame | 3.905033 | 4.760665 | 0.82027 |
casted_dates = pd.to_datetime(col[self.col_name], format=self.date_format, errors='coerce')
if len(casted_dates[casted_dates.isnull()]):
# This will raise an error for bad formatted data
# but not for out of bonds or missing dates.
slice_ = casted_dates.isnu... | def safe_datetime_cast(self, col) | Parses string values into datetime.
Args:
col(pandas.DataFrame): Data to transform.
Returns:
pandas.Series | 5.341542 | 5.73086 | 0.932066 |
result = pd.Series(index=data.index)
_slice = ~data[self.col_name].isnull()
result[_slice] = data[_slice][self.col_name].astype('int64')
return result | def to_timestamp(self, data) | Transform a datetime series into linux epoch.
Args:
data(pandas.DataFrame): DataFrame containins a column named as `self.col_name`.
Returns:
pandas.Series | 4.559197 | 4.872874 | 0.935628 |
t = x[self.col_name]
if np.isnan(t):
return t
elif np.isposinf(t):
t = sys.maxsize
elif np.isneginf(t):
t = -sys.maxsize
tmp = time.localtime(float(t) / 1e9)
return time.strftime(self.date_format, tmp) | def safe_date(self, x) | Transform x[self.col_name] into a date string.
Args:
x(dict like / pandas.Series): Row containing data to cast safely.
Returns:
str | 3.470915 | 3.430509 | 1.011779 |
# use re.compile() for flags support in Python 2.6
pattern = re.compile(r'\n^\.\. start-badges.*^\.\. end-badges\n',
flags=re.M | re.S)
return pattern.sub('', read('README.rst')) | def long_description() | Return the contents of README.rst (with badging removed). | 5.387732 | 4.712175 | 1.143364 |
if not content:
return
with self._lock:
try:
message = "Message: %s to %s" % (content, id_service)
self.write_message(message)
self.stream.flush() # flush after each message
return "message_id"
... | def send_message(self, id_service, content) | Write all messages to the stream in a thread-safe way. | 5.052892 | 4.56441 | 1.10702 |
return [sequence[i:i + limit_length] for i in range(0, len(sequence), limit_length)] | def chop_sequence(sequence, limit_length) | Input sequence is divided on smaller non-overlapping sequences with set length. | 2.155728 | 1.928345 | 1.117916 |
hsp_string = ""
try:
hsp_list = [
{"length": self.align_length},
{"e-value": self.expect},
{"score": self.score},
{"identities": self.identities},
{"positives": self.positives},
{"bits":... | def get_tabular_str(self) | Creates table-like string from fields. | 2.439376 | 2.394809 | 1.01861 |
if len(self.hsp_list) > 0:
return round(float(self.hsp_list[0].identities) / float(self.hsp_list[0].align_length) * 100, 1) | def best_identities(self) | Returns identities of the best HSP in alignment. | 2.7519 | 2.104697 | 1.307504 |
return hash(str(self.title) + str(self.best_score()) + str(self.hit_def)) | def get_id(self) | Returns unique id of an alignment. | 14.714182 | 8.126753 | 1.810586 |
parts = template.split('/')
renderer = _get_renderer(parts[:-1])
return renderer.render(renderer.load_template(parts[-1:][0]), context) | def render_template(template, **context) | Renders a given template and context.
:param template: The template name
:param context: the variables that should be available in the
context of the template. | 5.379854 | 6.564193 | 0.819576 |
root = NCObject.open(pattern, read_only=read_only)
return root, root.is_new | def open(pattern, read_only=False) | Return a root descriptor to work with one or multiple NetCDF files.
Keyword arguments:
pattern -- a list of filenames or a string pattern. | 11.292158 | 17.050596 | 0.662274 |
return root.getvar(name, vtype, dimensions, digits, fill_value, source) | def getvar(root, name, vtype='', dimensions=(), digits=0, fill_value=None,
source=None) | Return a variable from a NCFile or NCPackage instance. If the variable
doesn't exists create it.
Keyword arguments:
root -- the root descriptor returned by the 'open' function
name -- the name of the variable
vtype -- the type of each value, ex ['f4', 'i4', 'i1', 'S1'] (default '')
dimensions -... | 2.553092 | 4.384773 | 0.582263 |
if dimensions:
root = tailor(pattern, dimensions, distributed_dim, read_only=read_only)
else:
root, _ = open(pattern, read_only=read_only)
yield root
root.close() | def loader(pattern, dimensions=None, distributed_dim='time', read_only=False) | It provide a root descriptor to be used inside a with statement. It
automatically close the root when the with statement finish.
Keyword arguments:
root -- the root descriptor returned by the 'open' function | 4.407073 | 4.567794 | 0.964814 |
"copy dict args, to avoid modifying caller's copy"
def proxy(*args, **kwargs):
new_args = []
new_kwargs = {}
for var in kwargs:
if isinstance(kwargs[var], dict):
new_kwargs[var] = dict(kwargs[var])
else:
new_kwargs[var] = kwargs[var... | def dict_copy(func) | copy dict args, to avoid modifying caller's copy | 2.170482 | 1.827112 | 1.187931 |
if isinstance(obj, (list, tuple, set)):
return True
return is_sequence(obj) | def is_listish(obj) | Check if something quacks like a list. | 3.528857 | 3.266933 | 1.080174 |
uniq = []
for item in lst:
if item not in uniq:
uniq.append(item)
return uniq | def unique_list(lst) | Make a list unique, retaining order of initial appearance. | 2.336653 | 2.15252 | 1.085543 |
try:
main_language = TransLanguage.objects.filter(main_language=True).get()
return main_language.code
except TransLanguage.DoesNotExist:
return 'es' | def _get_main_language() | returns the main language
:return: | 3.951339 | 4.222209 | 0.935846 |
fields = self._get_translated_field_names(elem)
elem_langs = elem.get_available_languages()
# if we don't have a translation for the destination lang we have to include the tuple
if destination_lang not in elem_langs:
return fields
# we have the translation... | def fields_need_translation(self, elem, destination_lang) | Detect if the tuple needs translation and which fields has to be translated
:param elem
:param destination_lang:
:return: | 4.434267 | 4.343817 | 1.020823 |
from collections import Iterable
if not isinstance(datasets, Iterable):
raise TypeError('Input must be an iterable '
'i.e. (list/tuple) of MLdataset/similar instances')
datasets = list(datasets) # to make it indexable if coming from a set
num_datasets = len(datase... | def check_compatibility(datasets, reqd_num_features=None) | Checks whether the given MLdataset instances are compatible
i.e. with same set of subjects, each beloning to the same class in all instances.
Checks the first dataset in the list against the rest, and returns a boolean array.
Parameters
----------
datasets : Iterable
A list of n datasets
... | 2.996656 | 2.702316 | 1.108921 |
path_list, meta_requested, summary_requested, add_path_list, out_path = parse_args()
# printing info if requested
if path_list:
for ds_path in path_list:
ds = MLDataset(ds_path)
if summary_requested:
print_info(ds, ds_path)
if meta_requested... | def cli_run() | Command line interface
This interface saves you coding effort to:
- display basic info (classes, sizes etc) about datasets
- display meta data (class membership) for samples
- perform basic arithmetic (add multiple classes or feature sets) | 4.515553 | 4.142298 | 1.090108 |
"Prints basic summary of a given dataset."
if ds_path is None:
bname = ''
else:
bname = basename(ds_path)
dashes = '-' * len(bname)
print('\n{}\n{}\n{:full}'.format(dashes, bname, ds))
return | def print_info(ds, ds_path=None) | Prints basic summary of a given dataset. | 6.545713 | 5.923412 | 1.105058 |
"Prints meta data for subjects in given dataset."
print('\n#' + ds_path)
for sub, cls in ds.classes.items():
print('{},{}'.format(sub, cls))
return | def print_meta(ds, ds_path=None) | Prints meta data for subjects in given dataset. | 10.989148 | 8.381867 | 1.311062 |
add_path_list = list(add_path_list)
# first one!
first_ds_path = add_path_list[0]
print('Starting with {}'.format(first_ds_path))
combined = MLDataset(first_ds_path)
for ds_path in add_path_list[1:]:
try:
combined = combined + MLDataset(ds_path)
except:
... | def combine_and_save(add_path_list, out_path) | Combines whatever datasets that can be combined,
and save the bigger dataset to a given location. | 3.121639 | 2.89396 | 1.078674 |
parser = argparse.ArgumentParser(prog='pyradigm')
parser.add_argument('path_list', nargs='*', action='store',
default=None, help='List of paths to display info about.')
parser.add_argument('-m', '--meta', action='store_true', dest='meta_requested',
req... | def get_parser() | Argument specifier. | 3.326321 | 3.236133 | 1.027869 |
parser = get_parser()
if len(sys.argv) < 2:
parser.print_help()
logging.warning('Too few arguments!')
parser.exit(1)
# parsing
try:
params = parser.parse_args()
except Exception as exc:
print(exc)
raise ValueError('Unable to parse command-line ... | def parse_args() | Arg parser. | 2.905199 | 2.874142 | 1.010806 |
sample_ids = np.array(self.keys)
label_dict = self.labels
matrix = np.full([self.num_samples, self.num_features], np.nan)
labels = np.full([self.num_samples, 1], np.nan)
for ix, sample in enumerate(sample_ids):
matrix[ix, :] = self.__data[sample]
... | def data_and_labels(self) | Dataset features and labels in a matrix form for learning.
Also returns sample_ids in the same order.
Returns
-------
data_matrix : ndarray
2D array of shape [num_samples, num_features]
with features corresponding row-wise to sample_ids
labels : ndarray
... | 2.922699 | 2.773899 | 1.053643 |
if isinstance(values, dict):
if self.__labels is not None and len(self.__labels) != len(values):
raise ValueError(
'number of samples do not match the previously assigned labels')
elif len(values) < 1:
raise ValueError('There m... | def data(self, values, feature_names=None) | Populates this dataset with the provided data.
Usage of this method is discourage (unless you know what you are doing).
Parameters
----------
values : dict
dict of features keyed in by sample ids.
feature_names : list of str
New feature names for the new... | 4.17048 | 4.099061 | 1.017423 |
if isinstance(values, dict):
if self.__data is not None and len(self.__data) != len(values):
raise ValueError(
'number of samples do not match the previously assigned data')
elif set(self.keys) != set(list(values)):
raise Value... | def labels(self, values) | Class labels (such as 1, 2, -1, 'A', 'B' etc.) for each sample in the dataset. | 4.541342 | 4.238508 | 1.071448 |
if isinstance(values, dict):
if self.__data is not None and len(self.__data) != len(values):
raise ValueError(
'number of samples do not match the previously assigned data')
elif set(self.keys) != set(list(values)):
raise Value... | def classes(self, values) | Classes setter. | 4.652046 | 4.417412 | 1.053116 |
"Stores the text labels for features"
if len(names) != self.num_features:
raise ValueError("Number of names do not match the number of features!")
if not isinstance(names, (Sequence, np.ndarray, np.generic)):
raise ValueError("Input is not a sequence. "
... | def feature_names(self, names) | Stores the text labels for features | 5.115086 | 4.730795 | 1.081232 |
nitems = max([1, min([nitems, self.num_samples - 1])])
return self.__take(nitems, iter(self.__data.items())) | def glance(self, nitems=5) | Quick and partial glance of the data matrix.
Parameters
----------
nitems : int
Number of items to glance from the dataset.
Default : 5
Returns
-------
dict | 7.547763 | 11.877232 | 0.635482 |
class_sizes = np.zeros(len(self.class_set))
for idx, cls in enumerate(self.class_set):
class_sizes[idx] = self.class_sizes[cls]
# TODO consider returning numeric label set e.g. for use in scikit-learn
return self.class_set, self.label_set, class_sizes | def summarize_classes(self) | Summary of classes: names, numeric labels and sizes
Returns
-------
tuple : class_set, label_set, class_sizes
class_set : list
List of names of all the classes
label_set : list
Label for each class in class_set
class_sizes : list
Size... | 4.737826 | 3.435599 | 1.379039 |
if not isinstance(features, np.ndarray):
features = np.asarray(features)
if features.size <= 0:
raise ValueError('provided features are empty.')
if features.ndim > 1:
features = np.ravel(features)
return features | def check_features(self, features) | Method to ensure data to be added is not empty and vectorized.
Parameters
----------
features : iterable
Any data that can be converted to a numpy array.
Returns
-------
features : numpy array
Flattened non-empty numpy array.
Raises
... | 3.284458 | 3.064256 | 1.071861 |
if sample_id in self.__data and not overwrite:
raise ValueError('{} already exists in this dataset!'.format(sample_id))
# ensuring there is always a class name, even when not provided by the user.
# this is needed, in order for __str__ method to work.
# TODO consid... | def add_sample(self, sample_id, features, label,
class_id=None,
overwrite=False,
feature_names=None) | Adds a new sample to the dataset with its features, label and class ID.
This is the preferred way to construct the dataset.
Parameters
----------
sample_id : str, int
The identifier that uniquely identifies this sample.
features : list, ndarray
The feat... | 3.92404 | 3.742348 | 1.04855 |
if sample_id not in self.__data:
warnings.warn('Sample to delete not found in the dataset - nothing to do.')
else:
self.__data.pop(sample_id)
self.__classes.pop(sample_id)
self.__labels.pop(sample_id)
print('{} removed.'.format(sample_... | def del_sample(self, sample_id) | Method to remove a sample from the dataset.
Parameters
----------
sample_id : str
sample id to be removed.
Raises
------
UserWarning
If sample id to delete was not found in the dataset. | 3.729376 | 3.529684 | 1.056575 |
subset_idx = np.asarray(subset_idx)
if not (max(subset_idx) < self.__num_features) and (min(subset_idx) >= 0):
raise UnboundLocalError('indices out of range for the dataset. '
'Max index: {} Min index : 0'.format(
self.__num_featu... | def get_feature_subset(self, subset_idx) | Returns the subset of features indexed numerically.
Parameters
----------
subset_idx : list, ndarray
List of indices to features to be returned
Returns
-------
MLDataset : MLDataset
with subset of features requested.
Raises
-----... | 4.294784 | 3.842779 | 1.117624 |
"Returns a subset of keys from the dict with the value supplied."
subset = [key for key in dictionary if dictionary[key] == value]
return subset | def keys_with_value(dictionary, value) | Returns a subset of keys from the dict with the value supplied. | 8.246322 | 3.959676 | 2.082575 |
if class_id in [None, '']:
raise ValueError("class id can not be empty or None.")
if isinstance(class_id, str):
class_ids = [class_id, ]
else:
class_ids = class_id
non_existent = set(self.class_set).intersection(set(class_ids))
if le... | def get_class(self, class_id) | Returns a smaller dataset belonging to the requested classes.
Parameters
----------
class_id : str or list
identifier(s) of the class(es) to be returned.
Returns
-------
MLDataset
With subset of samples belonging to the given class(es).
... | 3.016359 | 2.930031 | 1.029463 |
if not callable(func):
raise TypeError('Given function {} is not a callable'.format(func))
xfm_ds = MLDataset()
for sample, data in self.__data.items():
try:
xfm_data = func(data)
except:
print('Unable to transform fe... | def transform(self, func, func_description=None) | Applies a given a function to the features of each subject
and returns a new dataset with other info unchanged.
Parameters
----------
func : callable
A valid callable that takes in a single ndarray and returns a single ndarray.
Ensure the transformed dimensio... | 3.783777 | 3.581798 | 1.05639 |
class_sizes = self.class_sizes
subsets = list()
if count_per_class < 1:
warnings.warn('Atleast one sample must be selected from each class')
return list()
elif count_per_class >= self.num_samples:
warnings.warn('All samples requested - retur... | def random_subset_ids_by_count(self, count_per_class=1) | Returns a random subset of sample ids of specified size by count,
within each class.
Parameters
----------
count_per_class : int
Exact number of samples per each class.
Returns
-------
subset : list
Combined list of sample ids from al... | 3.503533 | 3.484857 | 1.005359 |
class_sizes = self.class_sizes
subsets = list()
if perc_per_class <= 0.0:
warnings.warn('Zero percentage requested - returning an empty dataset!')
return list()
elif perc_per_class >= 1.0:
warnings.warn('Full or a larger dataset requested - ... | def random_subset_ids(self, perc_per_class=0.5) | Returns a random subset of sample ids (size in percentage) within each class.
Parameters
----------
perc_per_class : float
Fraction of samples per class
Returns
-------
subset : list
Combined list of sample ids from all classes.
Raises
... | 3.349113 | 3.153978 | 1.061869 |
subsets = self.random_subset_ids(perc_in_class)
if len(subsets) > 0:
return self.get_subset(subsets)
else:
warnings.warn('Zero samples were selected. Returning an empty dataset!')
return MLDataset() | def random_subset(self, perc_in_class=0.5) | Returns a random sub-dataset (of specified size by percentage) within each class.
Parameters
----------
perc_in_class : float
Fraction of samples to be taken from each class.
Returns
-------
subdataset : MLDataset
random sub-dataset of specified ... | 4.254128 | 4.376101 | 0.972127 |
# subset_ids = [sid for sid in self.keys if self.classes[sid] == class_id]
subset_ids = self.keys_with_value(self.classes, class_id)
return subset_ids | def sample_ids_in_class(self, class_id) | Returns a list of sample ids belonging to a given class.
Parameters
----------
class_id : str
class id to query.
Returns
-------
subset_ids : list
List of sample ids belonging to a given class. | 4.088711 | 4.008497 | 1.020011 |
num_existing_keys = sum([1 for key in subset_ids if key in self.__data])
if subset_ids is not None and num_existing_keys > 0:
# ensure items are added to data, labels etc in the same order of sample IDs
# TODO come up with a way to do this even when not using OrderedDic... | def get_subset(self, subset_ids) | Returns a smaller dataset identified by their keys/sample IDs.
Parameters
----------
subset_ids : list
List od sample IDs to extracted from the dataset.
Returns
-------
sub-dataset : MLDataset
sub-dataset containing only requested sample IDs. | 5.314703 | 4.904525 | 1.083632 |
if len(subset_ids) < 1:
warnings.warn('subset must have atleast one ID - returning empty matrix!')
return np.empty((0, 0))
if isinstance(subset_ids, set):
raise TypeError('Input set is not ordered, hence can not guarantee order! '
... | def get_data_matrix_in_order(self, subset_ids) | Returns a numpy array of features, rows in the same order as subset_ids
Parameters
----------
subset_ids : list
List od sample IDs to extracted from the dataset.
Returns
-------
matrix : ndarray
Matrix of features, for each id in subset_ids, in o... | 3.586596 | 3.454263 | 1.03831 |
"Method like dict.get() which can return specified value if key not found"
if item in self.keys:
return self.__data[item]
else:
return not_found_value | def get(self, item, not_found_value=None) | Method like dict.get() which can return specified value if key not found | 7.317046 | 3.488623 | 2.097402 |
label_set = list()
for class_ in self.class_set:
samples_in_class = self.sample_ids_in_class(class_)
label_set.append(self.labels[samples_in_class[0]])
return label_set | def label_set(self) | Set of labels in the dataset corresponding to class_set. | 3.550891 | 2.660782 | 1.334529 |
if not isinstance(classes, dict):
raise TypeError('Input classes is not a dict!')
if not len(classes) == self.num_samples:
raise ValueError('Too few items - need {} keys'.format(self.num_samples))
if not all([key in self.keys for key in classes]):
rai... | def add_classes(self, classes) | Helper to rename the classes, if provided by a dict keyed in by the orignal keys
Parameters
----------
classes : dict
Dict of class named keyed in by sample IDs.
Raises
------
TypeError
If classes is not a dict.
ValueError
If ... | 4.272688 | 3.811373 | 1.121037 |
self.__data = copy.deepcopy(other.data)
self.__classes = copy.deepcopy(other.classes)
self.__labels = copy.deepcopy(other.labels)
self.__dtype = copy.deepcopy(other.dtype)
self.__description = copy.deepcopy(other.description)
self.__feature_names = copy.deepcopy(... | def __copy(self, other) | Copy constructor. | 2.100592 | 2.048615 | 1.025372 |
try:
path = os.path.abspath(path)
with open(path, 'rb') as df:
# loaded_dataset = pickle.load(df)
self.__data, self.__classes, self.__labels, \
self.__dtype, self.__description, \
self.__num_features, self.__feature... | def __load(self, path) | Method to load the serialized dataset from disk. | 3.753187 | 3.430108 | 1.094189 |
try:
from scipy.io.arff import loadarff
arff_data, arff_meta = loadarff(arff_path)
except:
raise ValueError('Error loading the ARFF dataset!')
attr_names = arff_meta.names()[:-1] # last column is class
attr_types = arff_meta.types()[:-1]
... | def __load_arff(self, arff_path, encode_nonnumeric=False) | Loads a given dataset saved in Weka's ARFF format. | 4.005807 | 3.998811 | 1.00175 |
# TODO need a file format that is flexible and efficient to allow the following:
# 1) being able to read just meta info without having to load the ENTIRE dataset
# i.e. use case: compatibility check with #subjects, ids and their classes
# 2) random access layout: bein... | def save(self, file_path) | Method to save the dataset to disk.
Parameters
----------
file_path : str
File path to save the current dataset to
Raises
------
IOError
If saving to disk is not successful. | 8.403019 | 8.525287 | 0.985658 |
"Validator of inputs."
if not isinstance(data, dict):
raise TypeError(
'data must be a dict! keys: sample ID or any unique identifier')
if not isinstance(labels, dict):
raise TypeError(
'labels must be a dict! keys: sample ID or any unique... | def __validate(data, classes, labels) | Validator of inputs. | 3.155755 | 3.014756 | 1.046769 |
if not isinstance(other, MLDataset):
raise TypeError('Incorrect type of dataset provided!')
# assert self.__dtype==other.dtype, TypeError('Incorrect data type of features!')
for sample in other.keys:
self.add_sample(sample, other.data[sample], other.labels[sampl... | def extend(self, other) | Method to extend the dataset vertically (add samples from anotehr dataset).
Parameters
----------
other : MLDataset
second dataset to be combined with the current
(different samples, but same dimensionality)
Raises
------
TypeError
i... | 8.151222 | 6.648713 | 1.225985 |
blast_min_int_word_size = BLAST_SETS.min_word_size
blast_max_int_word_size = BLAST_SETS.max_word_size
blast_word_size_error = BLAST_SETS.get_word_size_error()
try:
if len(word_size) <= 0:
raise forms.ValidationError(blast_word_size_error)
int_word_size = int(word_size... | def validate_word_size(word_size, BLAST_SETS) | Validate word size in blast/tblastn form. | 1.844388 | 1.778856 | 1.036839 |
tmp_seq = tempfile.NamedTemporaryFile(mode="wb+", delete=False)
if len(str(sequence).strip()) == 0:
raise forms.ValidationError(blast_settings.BLAST_CORRECT_SEQ_ERROR_MSG)
if str(sequence).strip()[0] != ">":
tmp_seq.write(">seq1\n".encode())
tmp_seq.write(sequence.encode())
... | def validate_sequence(sequence: str, sequence_is_as_nucleotide=True) | Validate sequence in blast/tblastn form. | 2.676805 | 2.589462 | 1.03373 |
# set of unique letters in sequence
seq_set = set(seq)
not_allowed_letters_in_seq = [x for x in seq_set if str(x).upper() not in allowed_letters_as_set]
if len(not_allowed_letters_in_seq) > 0:
raise forms.ValidationError(
"This sequence type cannot contain letters: " + ", ".j... | def check_allowed_letters(seq, allowed_letters_as_set) | Validate sequence: Rise an error if sequence contains undesirable letters. | 2.929989 | 2.8357 | 1.03325 |
@functools.wraps(func)
def wrapper(*args, **kwargs):
ret = None
while ret is None:
ret = func(*args, **kwargs)
return ret
return wrapper | def _repeat(func) | Repeats func(...) call until something other than None is returned. | 2.345076 | 2.032867 | 1.153581 |
# This requires some care because we can't be sure that a call to 'pandoc'
# will work. It could be 'pandoc-1.17.0.2' or some other name. Try
# checking the parent process first, and only make a call to 'pandoc' as
# a last resort.
global _PANDOCVERSION # pylint: disable=global-statement
... | def init(pandocversion=None, doc=None) | Sets or determines the pandoc version. This must be called.
The pandoc version is needed for multi-version support.
See: https://github.com/jgm/pandoc/issues/2640
Returns the pandoc version. | 3.568686 | 3.575078 | 0.998212 |
assert name in meta
data = meta[name]
if data['t'] in ['MetaString', 'MetaBool']:
return data['c']
elif data['t'] == 'MetaInlines':
# Handle bug in pandoc 2.2.3 and 2.2.3.1: Return boolean value rather
# than strings, as appropriate.
if len(data['c']) == 1 and data[... | def get_meta(meta, name) | Retrieves the metadata variable 'name' from the 'meta' dict. | 3.692013 | 3.599321 | 1.025753 |
el['c'] = list(el['c']) # The content should be a list, not tuple
return el
return Element | def elt(eltType, numargs): # pylint: disable=invalid-name
def Element(*value): # pylint: disable=invalid-name
el = _elt(eltType, numargs)(*value)
if isinstance(el['c'], tuple) | Returns Element(*value) to create pandoc json elements.
This should be used in place of pandocfilters.elt(). This version
ensures that the content is stored in a list, not a tuple. | 7.483111 | 10.278829 | 0.728012 |
if key in ['HorizontalRule', 'Null']:
return elt(key, 0)()
elif key in ['Plain', 'Para', 'BlockQuote', 'BulletList',
'DefinitionList', 'HorizontalRule', 'Null']:
return elt(key, 1)(value)
return elt(key, len(value))(*value) | def _getel(key, value) | Returns an element given a key and value. | 6.592906 | 6.734233 | 0.979014 |
def _quotify(key, value, fmt, meta): # pylint: disable=unused-argument
if key == 'Quoted':
ret = []
quote = '"' if value[0]['t'] == 'DoubleQuote' else "'"
if value[1][0]['t'] == 'Str':
value[1][0]['c'] = quote + value[1][0]['c']
... | def quotify(x) | Replaces Quoted elements in element list 'x' with quoted strings.
Pandoc uses the Quoted element in its json when --smart is enabled.
Output to TeX/pdf automatically triggers --smart.
stringify() ignores Quoted elements. Use quotify() first to replace
Quoted elements in 'x' with quoted strings. 'x' ... | 4.052093 | 3.363967 | 1.204558 |
def _dollarfy(key, value, fmt, meta): # pylint: disable=unused-argument
if key == 'Math':
return Str('$' + value[1] + '$')
return None
return walk(x, _dollarfy, '', {}) | def dollarfy(x) | Replaces Math elements in element list 'x' with a $-enclosed string.
stringify() passes through TeX math. Use dollarfy(x) first to replace
Math elements with math strings set in dollars. 'x' should be a deep copy
so that the underlying document is left untouched.
Returns 'x'. | 9.279732 | 8.010627 | 1.158428 |
# Check for the start of the attributes string
if not (x[n]['t'] == 'Str' and x[n]['c'].startswith('{')):
raise ValueError('Attributes not found.')
# It starts with {, so this *may* be an attributes list. Search for where
# the attributes end. Do not consider } in quoted elements.
... | def extract_attrs(x, n) | Extracts attributes from element list 'x' beginning at index 'n'.
The elements encapsulating the attributes (typically a series of Str and
Space elements) are removed from 'x'. Items before index 'n' are left
unchanged.
Returns the attributes in pandoc format. A ValueError is raised if
attribute... | 4.877982 | 4.436834 | 1.099429 |
for i in range(len(x)-1): # Process successive pairs of elements
if x[i]['t'] == 'Str' and x[i+1]['t'] == 'Str':
x[i]['c'] += x[i+1]['c']
del x[i+1] # In-place deletion of element from list
return None # Forces processing to repeat
return True | def _join_strings(x) | Joins adjacent Str elements found in the element list 'x'. | 4.93247 | 3.956048 | 1.246817 |
_join_strings(value)
elif key == 'Image':
_join_strings(value[-2])
elif key == 'Table':
_join_strings(value[-5]) | def join_strings(key, value, fmt, meta): # pylint: disable=unused-argument
if key in ['Para', 'Plain'] | Joins adjacent Str elements in the 'value' list. | 5.230607 | 4.914039 | 1.064421 |
# A link followed by a string may represent a broken reference
if key1 != 'Link' or key2 != 'Str':
return False
# Assemble the parts
n = 0 if _PANDOCVERSION < '1.16' else 1
if isinstance(value1[n][0]['c'], list):
# Occurs when there is quoted text in an actual link. This is no... | def _is_broken_ref(key1, value1, key2, value2) | True if this is a broken reference; False otherwise. | 9.221503 | 8.829599 | 1.044385 |
if _PANDOCVERSION is None:
raise RuntimeError('Module uninitialized. Please call init().')
# Scan the element list x
for i in range(len(x)-1):
# Check for broken references
if _is_broken_ref(x[i]['t'], x[i]['c'] if 'c' in x[i] else [],
x[i+1]['t'], ... | def _repair_refs(x) | Performs the repair on the element list 'x'. | 5.315874 | 4.9824 | 1.06693 |
return
# The problem spans multiple elements, and so can only be identified in
# element lists. Element lists are encapsulated in different ways. We
# must process them all.
if key in ('Para', 'Plain'):
_repair_refs(value)
elif key == 'Image':
_repair_refs(value[-2])
... | def repair_refs(key, value, fmt, meta): # pylint: disable=unused-argument
if _PANDOCVERSION >= '1.18' | Using "-f markdown+autolink_bare_uris" with pandoc < 1.18 splits a
reference like "{@fig:one}" into email Link and Str elements. This
function replaces the mess with the Cite and Str elements we normally
get. Call this before any reference processing. | 8.975638 | 8.718521 | 1.029491 |
global _cleveref_tex_flag # pylint: disable=global-statement
assert x[i]['t'] == 'Cite'
assert i > 0
# Check the previous element for a modifier in the last character
if x[i-1]['t'] == 'Str':
modifier = x[i-1]['c'][-1]
if not _cleveref_tex_flag and modifier in ['*', '+']:
... | def _extract_modifier(x, i, attrs) | Extracts the */+/! modifier in front of the Cite at index 'i' of the
element list 'x'. The modifier is stored in 'attrs'. Returns the updated
index 'i'. | 4.943947 | 3.961206 | 1.248091 |
assert x[i]['t'] == 'Cite'
assert i > 0 and i < len(x) - 1
# Check if the surrounding elements are strings
if not x[i-1]['t'] == x[i+1]['t'] == 'Str':
return
# Trim off curly brackets
if x[i-1]['c'].endswith('{') and x[i+1]['c'].startswith('}'):
if len(x[i+1]['c']) > 1:
... | def _remove_brackets(x, i) | Removes curly brackets surrounding the Cite element at index 'i' in
the element list 'x'. It is assumed that the modifier has been
extracted. Empty strings are deleted from 'x'. | 2.455778 | 2.078687 | 1.181408 |
# Scan the element list x for Cite elements with known labels
for i, v in enumerate(x):
if v['t'] == 'Cite' and len(v['c']) == 2 and \
_get_label(v['t'], v['c']) in labels:
# A new reference was found; create some empty attributes for it
attrs = ['', [], []]
... | def _process_refs(x, labels) | Strips surrounding curly braces and adds modifiers to the
attributes of Cite elements. Only references with labels in the 'labels'
list are processed. Repeats processing (via decorator) until no more
broken references are found. | 8.935964 | 7.368937 | 1.212653 |
# pylint: disable=unused-argument
def process_refs(key, value, fmt, meta):
# References may occur in a variety of places; we must process them
# all.
if key in ['Para', 'Plain']:
_process_refs(value, labels)
elif key == 'Image':
_process_re... | def process_refs_factory(labels) | Returns process_refs(key, value, fmt, meta) action that processes
text around a reference. Only references with labels found in the
'labels' list are processed.
Consider the markdown "{+@fig:1}", which represents a reference to a
figure. "@" denotes a reference, "fig:1" is the reference's label, and
... | 3.597426 | 3.008171 | 1.195885 |
# Get the name
name = f.__closure__[0].cell_contents
def _attach_attrs(x):
for i, v in enumerate(x):
if v and v['t'] == name: # Find where the attributes start
n = i+1
if allow_space and n < len(x) and x[n]['t'] == 'Space':
... | def attach_attrs_factory(f, extract_attrs=extract_attrs, allow_space=False) | Returns attach_attrs(key, value, fmt, meta) action that reads and
attaches attributes to unattributed elements generated by the
pandocfilters function f (e.g. pandocfilters.Math, etc).
The extract_attrs() function should read the attributes and raise a
ValueError or IndexError if attributes are not fou... | 5.098529 | 4.40677 | 1.156976 |
# Get the name and standard length
name = f.__closure__[0].cell_contents
n = f.__closure__[1].cell_contents
def detach_attrs(key, value, fmt, meta): # pylint: disable=unused-argument
if key == name:
assert len(value) <= n+1
if len(value) == n+1:
... | def detach_attrs_factory(f) | Returns detach_attrs(key, value, fmt, meta) action that detaches
attributes attached to elements of type f (e.g. pandocfilters.Math, etc).
Attributes provided natively by pandoc will be left as is. | 4.4933 | 3.94961 | 1.137657 |
# Get the name and standard length
name = f.__closure__[0].cell_contents
n = f.__closure__[1].cell_contents
def insert_secnos(key, value, fmt, meta): # pylint: disable=unused-argument
global sec # pylint: disable=global-statement
if 'xnos-number-sections' in meta and ... | def insert_secnos_factory(f) | Returns insert_secnos(key, value, fmt, meta) action that inserts
section numbers into the attributes of elements of type f. | 5.653756 | 5.121137 | 1.104004 |
# Get the name and standard length
name = f.__closure__[0].cell_contents
n = f.__closure__[1].cell_contents
def delete_secnos(key, value, fmt, meta): # pylint: disable=unused-argument
if 'xnos-number-sections' in meta and \
check_bool(get_meta(meta, 'xnos-number-sectio... | def delete_secnos_factory(f) | Returns delete_secnos(key, value, fmt, meta) action that deletes
section numbers from the attributes of elements of type f. | 5.455924 | 4.807304 | 1.134924 |
r
# pylint: disable=unused-argument
def insert_rawblocks(key, value, fmt, meta):
if not rawblocks:
return None
# Put the RawBlock elements in front of the first block element that
# isn't also a RawBlock.
if not key in ['Plain', 'Para', 'CodeBlock', '... | def insert_rawblocks_factory(rawblocks) | r"""Returns insert_rawblocks(key, value, fmt, meta) action that inserts
non-duplicate RawBlock elements. | 5.234915 | 4.61872 | 1.133413 |
path = self._get_path('search')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | def search(self, **kwargs) | Get movies that match the search query string from the API.
Args:
q (optional): plain text search query; remember to URI encode
page_limit (optional): number of search results to show per page,
default=30
page (optional): results page number, defa... | 5.470908 | 7.020842 | 0.779238 |
path = self._get_id_path('cast')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | def cast(self, **kwargs) | Get the cast for a movie specified by id from the API.
Returns:
A dict respresentation of the JSON returned from the API. | 6.88503 | 7.482069 | 0.920204 |
path = self._get_id_path('clips')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | def clips(self, **kwargs) | Get related clips and trailers for a movie specified by id
from the API.
Returns:
A dict respresentation of the JSON returned from the API. | 5.762368 | 6.908748 | 0.834068 |
print("%s %s: " % (type(value), value))
print(dir(value))
print('\n\n')
return '' | def debug(value) | Simple tag to debug output a variable;
Usage:
{% debug request %} | 6.385609 | 8.211462 | 0.777646 |
sequence_sample_in_fasta = None
with open(sample_file) as handle:
sequence_sample_in_fasta = handle.read()
return sequence_sample_in_fasta | def get_sample_data(sample_file) | Read and returns sample data to fill form with default sample sequence. | 3.958599 | 3.397316 | 1.165214 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.