code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
append_breadcrumb(context, label, viewname, args, kwargs) return ''
def breadcrumb_raw_safe(context, label, viewname, *args, **kwargs)
Same as breadcrumb but label is not escaped and translated.
7.073186
7.760274
0.911461
try: template_path = args[0] except IndexError: template_path = getattr(settings, 'BREADCRUMBS_TEMPLATE', 'django_bootstrap_breadcrumbs/bootstrap2.html') links = [] for (label, viewname, view_args, view_kwargs) in context[ 'request'].MET...
def render_breadcrumbs(context, *args)
Render breadcrumbs html using bootstrap css classes.
2.718705
2.6765
1.015769
split = int(ratio * len(examples)) return examples[:split], examples[split:]
def split(examples, ratio=0.8)
Utility function that can be used within the parse() implementation of sub classes to split a list of example into two lists for training and testing.
3.432548
4.726696
0.726205
if not hasattr(module, name) and fallback: return self._find_symbol(module, fallback, None) return getattr(module, name)
def _find_symbol(self, module, name, fallback=None)
Find the symbol of the specified name inside the module or raise an exception.
3.225691
3.05382
1.056281
assert threading.current_thread() == threading.main_thread() assert not self.state.running self.state.running = True self.thread = threading.Thread(target=work, args=(self.state,)) self.thread.start() while self.state.running: try: bef...
def start(self, work)
Hand the main thread to the window and continue work in the provided function. A state is passed as the first argument that contains a `running` flag. The function is expected to exit if the flag becomes false. The flag can also be set to false to stop the window event loop and continue ...
2.553129
2.350165
1.086362
assert threading.current_thread() == self.thread assert self.state.running self.state.running = False
def stop(self)
Close the window and stops the worker thread. The main thread will resume with the next command after the `start()` call.
6.603026
5.582798
1.182745
assert threading.current_thread() == threading.main_thread() for axis, line, interface in self.interfaces: line.set_xdata(interface.xdata) line.set_ydata(interface.ydata) axis.set_xlim(0, interface.width or 1, emit=False) axis.set_ylim(0, interfac...
def update(self)
Redraw the figure to show changed data. This is automatically called after `start()` was run.
3.596125
3.16764
1.135269
assert len(incoming) == self.size self.incoming = incoming outgoing = self.activation(self.incoming) assert len(outgoing) == self.size self.outgoing = outgoing
def apply(self, incoming)
Store the incoming activation, apply the activation function and store the result as outgoing activation.
3.425554
2.456709
1.394367
return self.activation.delta(self.incoming, self.outgoing, above)
def delta(self, above)
The derivative of the activation function at the current state.
13.981588
7.810621
1.790074
assert len(data) == self.layers[0].size self.layers[0].apply(data) # Propagate trough the remaining layers. connections = zip(self.layers[:-1], weights, self.layers[1:]) for previous, weight, current in connections: incoming = self.forward(weight, previous.ou...
def feed(self, weights, data)
Evaluate the network with alternative weights on the input data and return the output activation.
4.057935
4.067484
0.997652
self.network = Network(self.problem.layers) self.weights = Matrices(self.network.shapes) if self.load: loaded = np.load(self.load) assert loaded.shape == self.weights.shape, ( 'weights to load must match problem definition') self.weigh...
def _init_network(self)
Define model and initialize weights.
4.22022
4.05842
1.039868
# pylint: disable=redefined-variable-type if self.check: self.backprop = CheckedBackprop(self.network, self.problem.cost) else: self.backprop = BatchBackprop(self.network, self.problem.cost) self.momentum = Momentum() self.decent = GradientDecent(...
def _init_training(self)
Classes needed during training.
5.482538
5.139723
1.066699
current = index * step_size step = current // times * times reached = current >= step overshot = current >= step + step_size return current and reached and not overshot
def _every(times, step_size, index)
Given a loop over batches of an iterable and an operation that should be performed every few elements. Determine whether the operation should be called for the current index.
9.833618
9.151864
1.074493
if "S" in tax_lvl: if "G" in tax_lvl and tax_lvl["S"].startswith(tax_lvl["G"]): tax_lvl["S"] = tax_lvl["S"][len(tax_lvl["G"])+1:] if "SS" in tax_lvl: if "S" in tax_lvl and tax_lvl["SS"].startswith(tax_lvl["S"]): tax_lvl["SS"] = tax_lvl["SS"][len(tax_lvl["S"])+1:] ...
def tax_fmt(tax_lvl, end)
Create a string representation of a taxonomic hierarchy (QIIME for now). :type tax_lvl: dict :param tax_lvl: Keyed on the entries in ranks :type end: int :param end: The end rank index (0-based indexing). If end == 3 then the returned string will contain K, P, C, and O. >>> tax...
5.202361
5.016357
1.037079
# How deep in the hierarchy are we currently? Each two spaces of # indentation is one level deeper. Also parse the scientific name at this # level. depth_and_name = re.match('^( *)(.*)', entry['sci_name']) depth = len(depth_and_name.group(1))//2 name = depth_and_name.group(2) # Remove...
def parse_tax_lvl(entry, tax_lvl_depth=[])
Parse a single kraken-report entry and return a dictionary of taxa for its named ranks. :type entry: dict :param entry: attributes of a single kraken-report row. :type tax_lvl_depth: list :param tax_lvl_depth: running record of taxon levels encountered in previous calls.
5.516833
5.588934
0.987099
# map between NCBI taxonomy IDs and the string rep. of the hierarchy taxa = OrderedDict() # the master collection of read counts (keyed on NCBI ID) counts = OrderedDict() # current rank r = 0 max_rank_idx = ranks.index(max_rank) min_rank_idx = ranks.index(min_rank) for entry in...
def parse_kraken_report(kdata, max_rank, min_rank)
Parse a single output file from the kraken-report tool. Return a list of counts at each of the acceptable taxonomic levels, and a list of NCBI IDs and a formatted string representing their taxonomic hierarchies. :type kdata: str :param kdata: Contents of the kraken report file.
5.051889
4.929511
1.024826
taxa = OrderedDict() sample_counts = OrderedDict() for krep_fp in kraken_reports_fp: if not osp.isfile(krep_fp): raise RuntimeError("ERROR: File '{}' not found.".format(krep_fp)) # use the kraken report filename as the sample ID sample_id = osp.splitext(osp.split(kr...
def process_samples(kraken_reports_fp, max_rank, min_rank)
Parse all kraken-report data files into sample counts dict and store global taxon id -> taxonomy data
3.090297
2.99839
1.030652
data = [[0 if taxid not in sample_counts[sid] else sample_counts[sid][taxid] for sid in sample_counts] for taxid in taxa] data = np.array(data, dtype=int) tax_meta = [{'taxonomy': taxa[taxid]} for taxid in taxa] gen_str = "kraken-biom v{} ({})".format(__version_...
def create_biom_table(sample_counts, taxa)
Create a BIOM table from sample counts and taxonomy metadata. :type sample_counts: dict :param sample_counts: A dictionary of dictionaries with the first level keyed on sample ID, and the second level keyed on taxon ID with counts as values. :type taxa: d...
4.820326
4.851032
0.99367
opener = open mode = 'w' if gzip and fmt != "hdf5": if not output_fp.endswith(".gz"): output_fp += ".gz" opener = gzip_open mode = 'wt' # HDF5 BIOM files are gzipped by default if fmt == "hdf5": opener = h5py.File with opener(output_fp, mode) as...
def write_biom(biomT, output_fp, fmt="hdf5", gzip=False)
Write the BIOM table to a file. :type biomT: biom.table.Table :param biomT: A BIOM table containing the per-sample OTU counts and metadata to be written out to file. :type output_fp str :param output_fp: Path to the BIOM-format file that will be written. :type fmt: str :param ...
2.733597
2.903777
0.941394
fpdir = osp.split(fp)[0] if not fpdir == "" and not osp.isdir(fpdir): raise RuntimeError("Specified path does not exist: {}".format(fpdir)) with open(fp, 'wt') as outf: outf.write('\n'.join(otu_ids))
def write_otu_file(otu_ids, fp)
Write out a file containing only the list of OTU IDs from the kraken data. One line per ID. :type otu_ids: list or iterable :param otu_ids: The OTU identifiers that will be written to file. :type fp: str :param fp: The path to the output file.
3.56665
4.04089
0.88264
if self.fill_missing: X = self.filler.complete(X) return {'X': X}
def transform(self, X)
Args: X: DataFrame with NaN's Returns: Dictionary with one key - 'X' corresponding to given DataFrame but without nan's
7.104065
7.89081
0.900296
self.categorical_encoder = self.encoder_class(cols=list(X)) self.categorical_encoder.fit(X) return self
def fit(self, X)
Args: X: DataFrame of categorical features to encode
5.089026
4.336029
1.173661
features = numerical_feature_list + categorical_feature_list for feature in features: feature = self._format_target(feature) feature.set_index(self.id_column, drop=True, inplace=True) features = pd.concat(features, axis=1).astype(np.float32).reset_index() ...
def transform(self, numerical_feature_list, categorical_feature_list)
Args: numerical_feature_list: list of numerical features categorical_feature_list: list of categorical features Returns: Dictionary with following keys: features: DataFrame with concatenated features feature_names: list of features names ...
2.991592
2.86197
1.045291
assert len(np.shape(X)) == 2, 'X must be 2-dimensional, got {}-D instead.'.format(len(np.shape(X))) assert np.shape(X)[0] > 1, 'X must contain predictions from at least two models. ' \ 'Got {} instead'.format(np.shape(X)[0]) assert np.shape(X)[1] == l...
def fit(self, X, y, step_size=0.1, init_weights=None, warm_start: bool=False)
Fit the weights on the given predictions. Args: X (array-like): Predictions of different models for the labels. y (array-like): Labels. step_size (float): Step size for optimizing the weights. Smaller step sizes most likely improve resulting sc...
2.444185
2.387282
1.023836
assert np.shape(X)[0] == len(self._weights), ( 'BlendingOptimizer: Number of models to blend its predictions and weights does not match: ' 'n_models={}, weights_len={}'.format(np.shape(X)[0], len(self._weights))) blended_predictions = np.average(np.power(X, self._power),...
def transform(self, X)
Performs predictions blending using the trained weights. Args: X (array-like): Predictions of different models. Returns: dict with blended predictions (key is 'y_pred').
4.676694
3.774679
1.238965
self.fit(X=X, y=y, step_size=step_size, init_weights=init_weights, warm_start=warm_start) return self.transform(X=X)
def fit_transform(self, X, y, step_size=0.1, init_weights=None, warm_start=False)
Fit optimizer to X, then transforms X. See `fit` and `transform` for further explanation.
1.962109
1.844314
1.063869
input_text = Input(shape=(maxlen,)) if embedding_matrix is not None: embedding = Embedding(max_features, embedding_size, weights=[embedding_matrix], trainable=trainable_embedding)(input_text) else: embedding = Embedding(max_features, embedding_size)(input_...
def dpcnn(embedding_matrix, embedding_size, trainable_embedding, maxlen, max_features, filter_nr, kernel_size, repeat_block, dense_size, repeat_dense, output_size, output_activation, max_pooling, mean_pooling, weighted_average_attention, concat_mode, dropout_embedding, conv_dropout, dense_...
Note: Implementation of http://ai.tencent.com/ailab/media/publications/ACL3-Brady.pdf post activation is used instead of pre-activation, could be worth exploring
1.636851
1.647625
0.993461
input_text = Input(shape=(maxlen,)) x = Embedding(input_dim=max_features, output_dim=embedding_size)(input_text) x = dropout_block(dropout_embedding, dropout_mode)(x) x = convolutional_block(filter_nr, kernel_size, use_batch_norm, use_prelu, conv_dropout, dropout_mode, ...
def vdcnn(embedding_size, maxlen, max_features, filter_nr, kernel_size, repeat_block, dense_size, repeat_dense, output_size, output_activation, max_pooling, mean_pooling, weighted_average_attention, concat_mode, dropout_embedding, conv_dropout, dense_dropout, dropout_mode, conv_k...
Note: Implementation of http://www.aclweb.org/anthology/E17-1104 We didn't use k-max pooling but GlobalMaxPool1D at the end and didn't explore it in the intermediate layers.
1.505217
1.517903
0.991642
# 1. escape everything value = conditional_escape(value) # 2. Reenable certain tags if valid_tags: # TODO: precompile somewhere once? tag_re = re.compile(r'<(\s*/?\s*(%s))(.*?\s*)>' % '|'.join(re.escape(tag) for tag in valid_tags)) value = ...
def escape_tags(value, valid_tags)
Strips text from the given html string, leaving only tags. This functionality requires BeautifulSoup, nothing will be done otherwise. This isn't perfect. Someone could put javascript in here: <a onClick="alert('hi');">test</a> So if you use valid_tags, you still need to trust your data ent...
5.360963
5.57685
0.961289
try: return [ContentType.objects.get_for_model(m).id for m in seo_models] except Exception: # previously caught DatabaseError # Return an empty list if this is called too early return []
def _get_seo_content_types(seo_models)
Returns a list of content types from the models defined in settings.
6.290242
6.023999
1.044197
if metadata_class._meta.use_sites: path_admin = SitePathMetadataAdmin model_instance_admin = SiteModelInstanceMetadataAdmin model_admin = SiteModelMetadataAdmin view_admin = SiteViewMetadataAdmin else: path_admin = PathMetadataAdmin model_instance_admin = Mo...
def register_seo_admin(admin_site, metadata_class)
Register the backends specified in Meta.backends with the admin.
1.823649
1.823378
1.000148
form = super(MetadataFormset, self)._construct_form(i, **kwargs) # Monkey patch the form to always force a save. # It's unfortunate, but necessary because we always want an instance # Affect on performance shouldn't be too great, because ther is only # ever one metadata ...
def _construct_form(self, i, **kwargs)
Override the method to change the form attribute empty_permitted.
10.368158
10.253942
1.011139
bits = list(token.split_contents()) tag_name = bits[0] bits = bits[1:] metadata_name = None args = {'as': None, 'for': None, 'in': None, 'on': None} # If there are an even number of bits, # a metadata name has been provided. if len(bits) % 2: metadata_name = bits[0] ...
def do_get_metadata(parser, token)
Retrieve an object which can produce (and format) metadata. {% get_metadata [for my_path] [in my_language] [on my_site] [as my_variable] %} or if you have multiple metadata classes: {% get_metadata MyClass [for my_path] [in my_language] [on my_site] [as my_variable] %}
3.518159
3.312001
1.062246
try: return super(WebSocketRpcRequest, self)._handle_exception(exception) except Exception: if not isinstance(exception, (odoo.exceptions.Warning, odoo.http.SessionExpiredException, odoo.exceptions.except_orm)): _logger.exception("Exception during JSON re...
def _handle_exception(self, exception)
Called within an except block to allow converting exceptions to arbitrary responses. Anything returned (except None) will be used as response.
3.258076
3.106052
1.048944
if name is not None: try: return registry[name] except KeyError: if len(registry) == 1: valid_names = 'Try using the name "%s" or simply leaving it '\ 'out altogether.' % list(registry)[0] else: va...
def _get_metadata_model(name=None)
Find registered Metadata object.
3.923884
3.770282
1.04074
for instance in model.objects.all(): create_metadata_instance(MetadataClass, instance)
def populate_metadata(model, MetadataClass)
For a given model and metadata class, ensure there is metadata for every instance.
4.969525
4.244185
1.170902
seo_models = [] for model_name in value: if "." in model_name: app_label, model_name = model_name.split(".", 1) model = apps.get_model(app_label, model_name) if model: seo_models.append(model) else: ...
def _set_seo_models(self, value)
Gets the actual models to be used.
1.72203
1.650209
1.043522
name = str(name) if name in self._metadata._meta.elements: element = self._metadata._meta.elements[name] # Look in instances for an explicit value if element.editable: value = getattr(self, name) if value: ...
def _resolve_value(self, name)
Returns an appropriate value for the given name.
3.32194
3.182157
1.043927
if isinstance(value, string_types) and "{" in value: if context is None: context = Context() if model_instance is not None: context[model_instance._meta.model_name] = model_instance value = Template(value).render(context) retur...
def _resolve_template(value, model_instance=None, context=None)
Resolves any template references in the given value.
2.460819
2.189928
1.123699
if urls is None: # prevent circular import from .urls import urlpatterns urls = [url.name for url in urlpatterns if getattr(url, 'name', None)] urls = dict(zip(urls, [get_uri_template(url) for url in urls])) urls.update(getattr(settings, 'LEAFLET_STORAGE_EXTRA_URLS', {})) re...
def _urls_for_js(urls=None)
Return templated URLs prepared for javascript.
3.8769
3.651312
1.061783
def decorate(urls, func): for url in urls: if isinstance(url, RegexURLPattern): url.__class__ = DecoratedURLPattern if not hasattr(url, "_decorate_with"): setattr(url, "_decorate_with", []) url._decorate_with.append(func) ...
def decorated_patterns(func, *urls)
Utility function to decorate a group of url in urls.py Taken from http://djangosnippets.org/snippets/532/ + comments See also http://friendpaste.com/6afByRiBB9CMwPft3a6lym Example: urlpatterns = [ url(r'^language/(?P<lang_code>[a-z]+)$', views.MyView, name='name'), ] + decorated_patterns(l...
2.072178
2.082816
0.994893
can = False if request and not self.owner: if (getattr(settings, "LEAFLET_STORAGE_ALLOW_ANONYMOUS", False) and self.is_anonymous_owner(request)): can = True if user and user.is_authenticated(): # if user is auth...
def can_edit(self, user=None, request=None)
Define if a user can edit or not the instance, according to his account or the request.
3.992288
4.039574
0.988294
return CustomField.objects.filter( content_type=ContentType.objects.get_for_model(self))
def get_custom_fields(self)
Return a list of custom fields for this model
3.799066
3.118686
1.218162
return CustomField.objects.filter( content_type=ContentType.objects.get_for_model(self))
def get_model_custom_fields(self)
Return a list of custom fields for this model, directly callable without an instance. Use like Foo.get_model_custom_fields(Foo)
3.625242
2.950797
1.228564
content_type = ContentType.objects.get_for_model(self) return CustomField.objects.get( content_type=content_type, name=field_name)
def get_custom_field(self, field_name)
Get a custom field object for this model field_name - Name of the custom field you want.
2.640313
2.492433
1.059332
custom_field = self.get_custom_field(field_name) return CustomFieldValue.objects.get_or_create( field=custom_field, object_id=self.id)[0].value
def get_custom_value(self, field_name)
Get a value for a specified custom field field_name - Name of the custom field you want.
3.354596
3.32108
1.010092
custom_field = self.get_custom_field(field_name) custom_value = CustomFieldValue.objects.get_or_create( field=custom_field, object_id=self.id)[0] custom_value.value = value custom_value.save()
def set_custom_value(self, field_name, value)
Set a value for a specified custom field field_name - Name of the custom field you want. value - Value to set it to
2.28492
2.48831
0.918262
# Preliminary check for simply missing file or modified entry-point file. if super(BrowserifyCompiler, self).is_outdated(infile, outfile): return True # Otherwise we need to see what dependencies there are now, and if they're modified. tool, args, e...
def is_outdated(self, infile, outfile)
Check if the input file is outdated. The difficulty with the default implementation is that any file that is `require`d from the entry-point file will not trigger a recompile if it is modified. This overloaded version of the method corrects this by generating a list of all requi...
4.776705
4.147529
1.151699
# only proceed if we got sensible input if count <= 1: raise ClusteringError("When clustering, you need to ask for at " "least two clusters! " "You asked for %d" % count) # return the data straight away if...
def getclusters(self, count)
Generates *count* clusters. :param count: The amount of clusters that should be generated. count must be greater than ``1``. :raises ClusteringError: if *count* is out of bounds.
5.210154
4.860966
1.071835
closest_cluster = origin for cluster in self.__clusters: if self.distance(item, centroid(cluster)) < self.distance( item, centroid(closest_cluster)): closest_cluster = cluster if id(closest_cluster) != id(origin): self.move_it...
def assign_item(self, item, origin)
Assigns an item from a given cluster to the closest located cluster. :param item: the item to be moved. :param origin: the originating cluster.
3.237108
3.191825
1.014187
if self.equality: item_index = 0 for i, element in enumerate(origin): if self.equality(element, item): item_index = i break else: item_index = origin.index(item) destination.append(origin.pop(it...
def move_item(self, item, origin, destination)
Moves an item from one cluster to anoter cluster. :param item: the item to be moved. :param origin: the originating cluster. :param destination: the target cluster.
2.835068
3.146247
0.901095
# initialise the clusters with empty lists self.__clusters = [] for _ in range(clustercount): self.__clusters.append([]) # distribute the items into the clusters count = 0 for item in input_: self.__clusters[count % clustercount].append(i...
def initialise_clusters(self, input_, clustercount)
Initialises the clusters by distributing the items from the data. evenly across n clusters :param input_: the data set (a list of tuples). :param clustercount: the amount of clusters (n).
2.920491
2.70141
1.081099
if self.progress_callback: self.progress_callback(total, current)
def publish_progress(self, total, current)
If a progress function was supplied, this will call that function with the total number of elements, and the remaining number of elements. :param total: The total number of elements. :param remaining: The remaining number of elements.
3.261869
4.4901
0.726458
if method == 'single': self.linkage = single elif method == 'complete': self.linkage = complete elif method == 'average': self.linkage = average elif method == 'uclus': self.linkage = uclus elif hasattr(method, '__call__'):...
def set_linkage_method(self, method)
Sets the method to determine the distance between two clusters. :param method: The method to use. It can be one of ``'single'``, ``'complete'``, ``'average'`` or ``'uclus'``, or a callable. The callable should take two collections as parameters and return a distance value be...
2.529848
2.092008
1.209292
logger.info("Performing cluster()") if matrix is None: # create level 0, first iteration (sequence) level = 0 sequence = 0 matrix = [] # if the matrix only has two rows left, we are done linkage = partial(self.linkage, distance_f...
def cluster(self, matrix=None, level=None, sequence=None)
Perform hierarchical clustering. :param matrix: The 2D list that is currently under processing. The matrix contains the distances of each item with each other :param level: The current level of clustering :param sequence: The sequence number of the clustering
5.497398
5.449458
1.008797
# if it's not worth clustering, just return the data if len(self._input) <= 1: return self._input # initialize the cluster if not yet done if not self.__cluster_created: self.cluster() return self._data[0].getlevel(threshold)
def getlevel(self, threshold)
Returns all clusters with a maximum distance of *threshold* in between each other :param threshold: the maximum distance between clusters. See :py:meth:`~cluster.cluster.Cluster.getlevel`
7.373918
7.514298
0.981318
if not isinstance(L, list): return [L] if L == []: return L return flatten(L[0]) + flatten(L[1:])
def flatten(L)
Flattens a list. Example: >>> flatten([a,b,[c,d,[e,f]]]) [a,b,c,d,e,f]
2.439469
3.641557
0.669897
flattened_items = [] for item in container: if hasattr(item, 'items'): flattened_items = flattened_items + fullyflatten(item.items) else: flattened_items.append(item) return flattened_items
def fullyflatten(container)
Completely flattens out a cluster and returns a one-dimensional set containing the cluster's items. This is useful in cases where some items of the cluster are clusters in their own right and you only want the items. :param container: the container to flatten.
1.99747
2.274717
0.878118
# Sort the list and take the middle element. n = len(numbers) copy = sorted(numbers) if n & 1: # There is an odd number of elements return copy[n // 2] else: return (copy[n // 2 - 1] + copy[n // 2]) / 2.0
def median(numbers)
Return the median of the list of numbers. see: http://mail.python.org/pipermail/python-list/2004-December/294990.html
2.55318
2.41436
1.057498
from math import pow assert len(y) == len(x) assert len(x) >= 1 sum = 0 for i in range(len(x)): sum += abs(x[i] - y[i]) ** p return pow(sum, 1.0 / float(p))
def minkowski_distance(x, y, p=2)
Calculates the minkowski distance between two points. :param x: the first point :param y: the second point :param p: the order of the minkowski algorithm. If *p=1* it is equal to the manhatten distance, if *p=2* it is equal to the euclidian distance. The higher the order, the closer it conv...
2.596455
2.799577
0.927445
"calculates the magnitude of a vecor" from math import sqrt sum = 0 for coord in a: sum += coord ** 2 return sqrt(sum)
def magnitude(a)
calculates the magnitude of a vecor
5.048819
4.867166
1.037322
"Calculates the dotproduct between two vecors" assert(len(a) == len(b)) out = 0 for i in range(len(a)): out += a[i] * b[i] return out
def dotproduct(a, b)
Calculates the dotproduct between two vecors
3.159402
2.709747
1.16594
"returns the central vector of a list of vectors" out = [] for i in range(len(data[0])): out.append(method([x[i] for x in data])) return tuple(out)
def centroid(data, method=median)
returns the central vector of a list of vectors
3.96395
2.967069
1.335982
print(depth * " " + "[level %s]" % self.level) for item in self.items: if isinstance(item, Cluster): item.display(depth + 1) else: print(depth * " " + "%s" % item)
def display(self, depth=0)
Pretty-prints this cluster. Useful for debuging.
3.008594
2.458457
1.223773
left = self.items[0] right = self.items[1] if isinstance(left, Cluster): first = left.topology() else: first = left if isinstance(right, Cluster): second = right.topology() else: second = right return fi...
def topology(self)
Returns the structure (topology) of the cluster as tuples. Output from cl.data:: [<Cluster@0.833333333333(['CVS', <Cluster@0.818181818182(['34.xls', <Cluster@0.789473684211([<Cluster@0.555555555556(['0.txt', <Cluster@0.181818181818(['ChangeLog...
2.895769
2.731423
1.060168
left = self.items[0] right = self.items[1] # if this object itself is below the threshold value we only need to # return it's contents as a list if self.level <= threshold: return [fullyflatten(self.items)] # if this cluster's level is higher than ...
def getlevel(self, threshold)
Retrieve all clusters up to a specific level threshold. This level-threshold represents the maximum distance between two clusters. So the lower you set this threshold, the more clusters you will receive and the higher you set it, you will receive less but bigger clusters. :param...
3.126634
3.066123
1.019736
if not is_3: if cStringIO and not isinstance(js, unicode): # strings can use cStringIO for a 3x performance # improvement, but unicode (in python2) cannot klass = cStringIO.StringIO else: klass = StringIO.StringIO else: klass =...
def jsmin(js, **kwargs)
returns a minified version of the javascript string
5.206263
5.071194
1.026634
_cache = {} @wraps(fun) def newfun(a, b, distance_function): frozen_a = frozenset(a) frozen_b = frozenset(b) if (frozen_a, frozen_b) not in _cache: result = fun(a, b, distance_function) _cache[(frozen_a, frozen_b)] = result return _cache[(frozen...
def cached(fun)
memoizing decorator for linkage functions. Parameters have been hardcoded (no ``*args``, ``**kwargs`` magic), because, the way this is coded (interchangingly using sets and frozensets) is true for this specific case. For other cases that is not necessarily guaranteed.
2.318352
2.255346
1.027936
left_a, right_a = min(a), max(a) left_b, right_b = min(b), max(b) result = min(distance_function(left_a, right_b), distance_function(left_b, right_a)) return result
def single(a, b, distance_function)
Given two collections ``a`` and ``b``, this will return the distance of the points which are closest together. ``distance_function`` is used to determine the distance between two elements. Example:: >>> single([1, 2], [3, 4], lambda x, y: abs(x-y)) 1 # (distance between 2 and 3)
2.224526
2.770853
0.802831
distances = [distance_function(x, y) for x in a for y in b] return sum(distances) / len(distances)
def average(a, b, distance_function)
Given two collections ``a`` and ``b``, this will return the mean of all distances. ``distance_function`` is used to determine the distance between two elements. Example:: >>> single([1, 2], [3, 100], lambda x, y: abs(x-y)) 26
2.765058
4.609185
0.599902
distances = sorted([distance_function(x, y) for x in a for y in b]) midpoint, rest = len(distances) // 2, len(distances) % 2 if not rest: return sum(distances[midpoint-1:midpoint+1]) / 2 else: return distances[midpoint]
def uclus(a, b, distance_function)
Given two collections ``a`` and ``b``, this will return the *median* of all distances. ``distance_function`` is used to determine the distance between two elements. Example:: >>> single([1, 2], [3, 100], lambda x, y: abs(x-y)) 2.5
2.888154
3.321872
0.869436
encapsulated_item = None if ( not hasattr(item, '__iter__') or isinstance(item, tuple) or isinstance(item, str) ): encapsulated_item = [item] else: encapsulated_item = item logging.debug( "item class:%s encapsulated as:%s ", item.__class_...
def _encapsulate_item_for_combinfunc(item)
This function has been extracted in order to make Github issue #28 easier to investigate. It replaces the following two lines of code, which occur twice in method genmatrix, just before the invocation of combinfunc. if not hasattr(item, '__iter__') or isinstance(item, tuple): item ...
3.259478
2.761956
1.180134
tasks_completed = 0 for task in iter(self.task_queue.get, 'STOP'): col_index, item, item2 = task if not hasattr(item, '__iter__') or isinstance(item, tuple): item = [item] if not hasattr(item2, '__iter__') or isinstance(item2, tuple): ...
def worker(self)
Multiprocessing task function run by worker processes
3.26945
3.088906
1.058449
use_multiprocessing = num_processes > 1 if use_multiprocessing: self.task_queue = Queue() self.done_queue = Queue() self.matrix = [] logger.info("Generating matrix for %s items - O(n^2)", len(self.data)) if use_multiprocessing: logger...
def genmatrix(self, num_processes=1)
Actually generate the matrix :param num_processes: If you want to use multiprocessing to split up the work and run ``combinfunc()`` in parallel, specify ``num_processes > 1`` and this number of workers will be spun up, the work is split up amongst them evenly.
3.27894
3.19817
1.025255
validation = { "errors": [], "warnings": [] } for line in _process(fname): kind, message = _determine(line) if kind in validation: validation[kind].append(message) return validation
def validate(fname)
This function uses dciodvfy to generate a list of warnings and errors discovered within the DICOM file. :param fname: Location and filename of DICOM file.
4.65516
6.491317
0.717137
# load GDCM's image reading functionality image_reader = gdcm.ImageReader() image_reader.SetFileName(self.fname) if not image_reader.Read(): raise IOError("Could not read DICOM image") pixel_array = self._gdcm_to_numpy(image_reader.GetImage()) return ...
def numpy(self)
Grabs image data and converts it to a numpy array
4.738135
4.631292
1.02307
gdcm_typemap = { gdcm.PixelFormat.INT8: numpy.int8, gdcm.PixelFormat.UINT8: numpy.uint8, gdcm.PixelFormat.UINT16: numpy.uint16, gdcm.PixelFormat.INT16: numpy.int16, gdcm.PixelFormat.UINT32: numpy.uint32, gdcm.PixelFor...
def _gdcm_to_numpy(self, image)
Converts a GDCM image to a numpy array. :param image: GDCM.ImageReader.GetImage()
2.763576
2.741642
1.008001
from matplotlib.backends.backend_agg \ import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure from pylab import cm if pixel_array is None: pixel_array = self.numpy if cmap is None: cmap = cm.bone fig = Figure...
def save_as_plt(self, fname, pixel_array=None, vmin=None, vmax=None, cmap=None, format=None, origin=None)
This method saves the image from a numpy array using matplotlib :param fname: Location and name of the image file to be saved. :param pixel_array: Numpy pixel array, i.e. ``numpy()`` return value :param vmin: matplotlib vmin :param vmax: matplotlib vmax :param cmap: matplotlib c...
2.217465
2.368418
0.936265
if pixel_array is None: pixel_array = self.numpy from PIL import Image as pillow pil_image = pillow.fromarray(pixel_array.astype('uint8')) pil_image.save(fname) return True
def save_as_pil(self, fname, pixel_array=None)
This method saves the image from a numpy array using Pillow (PIL fork) :param fname: Location and name of the image file to be saved. :param pixel_array: Numpy pixel array, i.e. ``numpy()`` return value This method will return True if successful
2.740078
2.886039
0.949425
def ds(data_element): value = self._str_filter.ToStringPair(data_element.GetTag()) if value[1]: return DataElement(data_element, value[0].strip(), value[1].strip()) results = [data for data in self.walk(ds) if data is not None] return results
def read(self)
Returns array of dictionaries containing all the data elements in the DICOM file.
9.399738
7.894374
1.190688
if not hasattr(fn, "__call__"): raise TypeError() dataset = self._dataset iterator = dataset.GetDES().begin() while (not iterator.equal(dataset.GetDES().end())): data_element = iterator.next() yield fn(data_element) header = self._he...
def walk(self, fn)
Loops through all data elements and allows a function to interact with each data element. Uses a generator to improve iteration. :param fn: Function that interacts with each DICOM element
3.707018
3.746052
0.98958
results = self.read() if name is not None: def find_name(data_element): return data_element.name.lower() == name.lower() return filter(find_name, results) if group is not None: def find_group(data_element): return (da...
def find(self, group=None, element=None, name=None, VR=None)
Searches for data elements in the DICOM file given the filters supplied to this method. :param group: Hex decimal for the group of a DICOM element e.g. 0x002 :param element: Hex decimal for the element value of a DICOM element e.g. 0x0010 :param name: Name of the DICOM element, e.g. "Mo...
1.701248
1.730145
0.983298
self._anon_obj = gdcm.Anonymizer() self._anon_obj.SetFile(self._file) self._anon_obj.RemoveGroupLength() if self._anon_tags is None: self._anon_tags = get_anon_tags() for tag in self._anon_tags: cur_tag = tag['Tag'].replace("(", "") ...
def anonymize(self)
According to PS 3.15-2008, basic application level De-Indentification of a DICOM file requires replacing the values of a set of data elements
4.605949
4.377916
1.052087
writer = gdcm.Writer() writer.SetFileName(fname) if obj is None and self._anon_obj: obj = self._anon_obj else: raise ValueError("Need DICOM object, e.g. obj=gdcm.Anonymizer()") writer.SetFile(obj.GetFile()) if not writer.Write(): ...
def save_as(self, fname, obj=None)
Save DICOM file given a GDCM DICOM object. Examples of a GDCM DICOM object: * gdcm.Writer() * gdcm.Reader() * gdcm.Anonymizer() :param fname: DICOM file name to be saved :param obj: DICOM object to be saved, if None, Anonymizer() is used
5.247118
3.26101
1.609047
if self._image is None: self._image = Image(self.fname) return self._image
def image(self)
Read the loaded DICOM image data
4.816928
4.754831
1.01306
value_repr = { "AE": "Application Entity", "AS": "Age String", "AT": "Attribute Tag", "CS": "Code String", "DA": "Date", "DS": "Decimal String", "DT": "Date/Time", "FL": "Floating Point Single (4 bytes)", "FD": "Floating Point Double (8 by...
def VR(VR=None, description=None)
Value Representation (VR) <-> Description lookup. :param VR: Takes the VR and returns its description :param description: Take the description of a VR and returns the VR
2.140339
1.879749
1.13863
transfer_syntax = { "1.2.840.10008.1.2": "Implicit VR Endian: Default Transfer Syntax for DICOM", "1.2.840.10008.1.2.1": "Explicit VR Little Endian", "1.2.840.10008.1.2.1.99": "Deflated Explicit VR Big Endian", "1.2.840.10008.1.2.2": "Explicit VR Big Endian", "1.2.840.10...
def transfer_syntax(UID=None, description=None)
Transfer Syntax UID <-> Description lookup. :param UID: Transfer Syntax UID, returns description :param description: Take the description of a transfer syntax and return its UID
1.620034
1.629593
0.994134
# Available operations : def curate_password(message): return message.replace(self.password, '********') def errorout(message): LOG.error(curate_password(message)) raise NYnabConnectionError(message) json_request_dict = json.dumps(request_d...
def dorequest(self, request_dic, opname)
:param request_dic: a dictionary containing parameters for the request :param opname: An API operation name, available are: loginUser,getInitialUserData,logoutUser,createNewBudget, freshStartABudget,cloneBudget,deleteTombstonedBudgets,syncCatalogData,syncBudgetData,getInstitutionList, getInstitu...
4.550883
4.672173
0.97404
ds = [[x.repo_name] for x in self.repos] df = pd.DataFrame(ds, columns=['repository']) return df
def repo_name(self)
Returns a DataFrame of the repo names present in this project directory :return: DataFrame
7.562503
6.746408
1.120967
df = pd.DataFrame(columns=['filename', 'lines_covered', 'total_lines', 'coverage', 'repository']) for repo in self.repos: try: cov = repo.coverage() cov['repository'] = repo.repo_name df = df.append(cov) except GitCommand...
def coverage(self)
Will return a DataFrame with coverage information (if available) for each repo in the project). If there is a .coverage file available, this will attempt to form a DataFrame with that information in it, which will contain the columns: * repository * filename * lines_covered ...
4.686693
3.616805
1.29581
columns = ['unique_committers', 'abs_rate_of_change', 'net_rate_of_change', 'net_change', 'abs_change', 'edit_rate', 'repository'] if coverage: columns += ['lines_covered', 'total_lines', 'coverage'] df = pd.DataFrame(columns=columns) for repo in self.repos: ...
def file_change_rates(self, branch='master', limit=None, coverage=False, days=None, ignore_globs=None, include_globs=None)
This function will return a DataFrame containing some basic aggregations of the file change history data, and optionally test coverage data from a coverage_data.py .coverage file. The aim here is to identify files in the project which have abnormal edit rates, or the rate of changes without growing the...
3.00471
3.009421
0.998435
if limit is not None: limit = int(limit / len(self.repo_dirs)) if committer: com = 'committer' else: com = 'author' df = pd.DataFrame(columns=[com, 'hours', 'repository']) for repo in self.repos: try: ch...
def hours_estimate(self, branch='master', grouping_window=0.5, single_commit_hours=0.5, limit=None, days=None, committer=True, by=None, ignore_globs=None, include_globs=None)
inspired by: https://github.com/kimmobrunfeldt/git-hours/blob/8aaeee237cb9d9028e7a2592a25ad8468b1f45e4/index.js#L114-L143 Iterates through the commit history of repo to estimate the time commitement of each author or committer over the course of time indicated by limit/extensions/days/etc. :pa...
2.337143
2.364887
0.988268
if limit is not None: limit = int(limit / len(self.repo_dirs)) df = pd.DataFrame(columns=['author', 'committer', 'message', 'lines', 'insertions', 'deletions', 'net']) for repo in self.repos: try: ch = repo.commit_history(branch, limit=limit, d...
def commit_history(self, branch, limit=None, days=None, ignore_globs=None, include_globs=None)
Returns a pandas DataFrame containing all of the commits for a given branch. The results from all repositories are appended to each other, resulting in one large data frame of size <limit>. If a limit is provided, it is divided by the number of repositories in the project directory to find out how many...
3.210172
2.38392
1.346594
df = None for repo in self.repos: try: if df is None: df = repo.blame(committer=committer, by=by, ignore_globs=ignore_globs, include_globs=include_globs) else: df = df.append(repo.blame(committer=committer, by...
def blame(self, committer=True, by='repository', ignore_globs=None, include_globs=None)
Returns the blame from the current HEAD of the repositories as a DataFrame. The DataFrame is grouped by committer name, so it will be the sum of all contributions to all repositories by each committer. As with the commit history method, extensions and ignore_dirs parameters can be passed to exclude cer...
1.883727
1.793234
1.050464
df = None for repo in self.repos: try: if df is None: df = repo.file_detail(ignore_globs=ignore_globs, include_globs=include_globs, committer=committer, rev=rev) df['repository'] = repo.repo_name else: ...
def file_detail(self, rev='HEAD', committer=True, ignore_globs=None, include_globs=None)
Returns a table of all current files in the repos, with some high level information about each file (total LOC, file owner, extension, most recent edit date, etc.). :param ignore_globs: (optional, default=None) a list of globs to ignore, default none excludes nothing :param include_globs: (opti...
2.403745
2.457393
0.978169
df = pd.DataFrame(columns=['repository', 'local', 'branch']) if _has_joblib: ds = Parallel(n_jobs=-1, backend='threading', verbose=0)( delayed(_branches_func) (x) for x in self.repos ) for d in ds: df = df.app...
def branches(self)
Returns a data frame of all branches in origin. The DataFrame will have the columns: * repository * local * branch :returns: DataFrame
4.163355
3.68945
1.128449
if limit is not None: limit = math.floor(float(limit) / len(self.repos)) if num_datapoints is not None: num_datapoints = math.floor(float(num_datapoints) / len(self.repos)) df = pd.DataFrame(columns=['repository', 'rev']) if _has_joblib: d...
def revs(self, branch='master', limit=None, skip=None, num_datapoints=None)
Returns a dataframe of all revision tags and their timestamps for each project. It will have the columns: * date * repository * rev :param branch: (optional, default 'master') the branch to work in :param limit: (optional, default None), the maximum number of revisions to re...
2.515149
2.512409
1.00109
data = [[repo.git_dir, repo.repo.branches, repo.repo.bare, repo.repo.remotes, repo.repo.description, repo.repo.references, repo.repo.heads, repo.repo.submodules, repo...
def repo_information(self)
Returns a DataFrame with the properties of all repositories in the project directory. The returned DataFrame will have the columns: * local_directory * branches * bare * remotes * description * references * heads * submodules * ta...
2.558284
1.765753
1.448834
if by == 'file': raise NotImplementedError('File-wise bus factor') elif by == 'projectd': blame = self.blame(ignore_globs=ignore_globs, include_globs=include_globs, by='repository') blame = blame.sort_values(by=['loc'], ascending=False) total = ...
def bus_factor(self, ignore_globs=None, include_globs=None, by='projectd')
An experimental heuristic for truck factor of a repository calculated by the current distribution of blame in the repository's primary branch. The factor is the fewest number of contributors whose contributions make up at least 50% of the codebase's LOC :param ignore_globs: (optional, default=...
3.080071
2.912369
1.057583
df = pd.DataFrame() if by == 'repository': repo_by = None else: repo_by = by for repo in self.repos: try: chunk = repo.punchcard( branch=branch, limit=limit, days=d...
def punchcard(self, branch='master', limit=None, days=None, by=None, normalize=None, ignore_globs=None, include_globs=None)
Returns a pandas DataFrame containing all of the data for a punchcard. * day_of_week * hour_of_day * author / committer * lines * insertions * deletions * net :param branch: the branch to return commits for :param limit: (optional, default...
2.422749
2.157617
1.122882