content
stringlengths 39
14.9k
| sha1
stringlengths 40
40
| id
int64 0
710k
|
---|---|---|
def uvm_object_value_str(v):
"""
Function- uvm_object_value_str
Args:
v (object): Object to convert to string.
Returns:
str: Inst ID for `UVMObject`, otherwise uses str()
"""
if v is None:
return "<null>"
res = ""
if hasattr(v, 'get_inst_id'):
res = "{}".format(v.get_inst_id())
res = "@" + res
else:
res = str(v)
return res | e56bd12094923bf052b10dcb47c65a93a03142a2 | 13,558 |
def get_object_name(object):
""" Retrieves the name of object.
Parameters:
object (obj): Object to get name.
Returns:
str: Object name.
"""
if object.name[-5:-3] == '}.':
return object.name[:-4]
return object.name | fc695c8bf19817c3217bf6000358695c88de07aa | 13,565 |
def create_nine_digit_product(num):
""" Create a nine digit string resulting from the concatenation of
the product from num and multipliers (1, 2, 3,).... Return 0 if string
cannot be length 9.
"""
result = ''
counter = 1
while len(result) < 9:
result += str(num * counter)
counter += 1
if len(result) > 9:
result = 0
return result | 9c6765349edfa7e03dc8d2ffe7bf6a45155f3ad0 | 13,566 |
def peak_indices_to_times(time, picked_peaks):
"""
Converts peak indices to times.
Parameters
----------
time: ndarray
array of time, should match the indices.
picked_peaks: dict
dictionary containing list of indices of peak start, center, and end.
Returns
-----------
peak_features: list
list of lists containing times of peak start, center, and end.
"""
peak_features = []
for x in range(0, len(picked_peaks["Peak_indices"])):
rt_ind = picked_peaks["Peak_indices"][x]
start_ind = picked_peaks["Peak_start_indices"][x]
end_ind = picked_peaks["Peak_end_indices"][x]
retention_time = time[rt_ind]
start = time[start_ind]
end = time[end_ind]
peak_params = [start, retention_time, end]
peak_features.append(peak_params)
return peak_features | 99aa76fbc399b2b99d4dc9c8d3e4b67e4ee2d3af | 13,567 |
def evenFibSum(limit):
"""Sum even Fib numbers below 'limit'"""
sum = 0
a,b = 1,2
while b < limit:
if b % 2 == 0:
sum += b
a,b = b,a+b
return sum | cdf9cdb1cfb419713e794afff4d806945994692e | 13,570 |
def get_n_first(file_names, checksums, N_first):
"""
Given a list of file_names and a list of checksums, returns the 'N_first'
items from both lists as a zip object.
:param file_names: list of file names
:param checksums: list of sha256 checksums
:param N_first: int or None. If None, all items are returned
:return: zipped N_first first items of file_names and checksums
"""
zipped = list(zip(file_names, checksums))
N_first = int(N_first) if N_first is not None else len(file_names)
zipped = zipped[:N_first]
return zipped | 13a8157dcd55fa43b0cd71eb877abddc832ff143 | 13,571 |
def _is_new_prototype(caller):
"""Check if prototype is marked as new or was loaded from a saved one."""
return hasattr(caller.ndb._menutree, "olc_new") | 1282db1ce6ae2e5f0bb570b036d7166a53287229 | 13,581 |
def count_symbols(atoms, exclude=()):
"""Count symbols in atoms object, excluding a set of indices
Parameters:
atoms: Atoms object to be grouped
exclude: List of indices to be excluded from the counting
Returns:
Tuple of (symbols, symbolcount)
symbols: The unique symbols in the included list
symbolscount: Count of symbols in the included list
Example:
>>> from ase.build import bulk
>>> atoms = bulk('NaCl', crystalstructure='rocksalt', a=4.1, cubic=True)
>>> count_symbols(atoms)
(['Na', 'Cl'], {'Na': 4, 'Cl': 4})
>>> count_symbols(atoms, exclude=(1, 2, 3))
(['Na', 'Cl'], {'Na': 3, 'Cl': 2})
"""
symbols = []
symbolcount = {}
for m, symbol in enumerate(atoms.symbols):
if m in exclude:
continue
if symbol not in symbols:
symbols.append(symbol)
symbolcount[symbol] = 1
else:
symbolcount[symbol] += 1
return symbols, symbolcount | 31f7c116f07788171828f0e116ef28a43eb0e313 | 13,587 |
import ntpath
def lookup_folder(event, filesystem):
"""Lookup the parent folder in the filesystem content."""
for dirent in filesystem[event.parent_inode]:
if dirent.type == 'd' and dirent.allocated:
return ntpath.join(dirent.path, event.name) | e18df4610bba9cf71e85fe0038a5daf798822bd3 | 13,588 |
import datetime
import calendar
def getWeekday(year, month, day):
"""
input: integers year, month, day
output: name of the weekday on that date as a string
"""
date = datetime.date(year, month, day)
return calendar.day_name[date.weekday()] | ca5164b6d7243033f57c3a803301ff3c3ec13d29 | 13,603 |
from typing import List
import inspect
def get_function_parameters_list(func) -> List[str]:
"""
Get parameter list of function `func`.
Parameters
----------
func : Callable
A function to get parameter list.
Returns
-------
List[str]
Parameter list
Examples
--------
>>> def test_func(a, b) -> int:
... return a+1
>>> get_function_parameters_list(test_func)
['a', 'b']
"""
return inspect.getfullargspec(func).args | bff2ec37a5564b87e48abf964d0d42a55f809a16 | 13,608 |
def dp_make_weight(egg_weights, target_weight, memo={}):
"""
Find number of eggs to bring back, using the smallest number of eggs. Assumes there is
an infinite supply of eggs of each weight, and there is always a egg of value 1.
Parameters:
egg_weights - tuple of integers, available egg weights sorted from smallest to largest
value (1 = d1 < d2 < ... < dk)
target_weight - int, amount of weight we want to find eggs to fit
memo - dictionary, OPTIONAL parameter for memoization (you may not need to use this
parameter depending on your implementation)
Returns: int, smallest number of eggs needed to make target weight
"""
# This will be the key used to find answers in the memo
subproblem = (egg_weights, target_weight)
# If we've already stored this answer in the memo, return it
if subproblem in memo:
return memo[subproblem]
# If no eggs are left or no space is left on ship, there's nothing left to do
if egg_weights == () or target_weight == 0:
return 0
# If the next heaviest egg is too heavy to fit, consider subset of lighter eggs
elif egg_weights[-1] > target_weight:
result = dp_make_weight(egg_weights[:-1], target_weight, memo)
else:
# Find the minimum number of eggs by testing both taking heaviest egg and not
# taking heaviest egg.
this_egg = egg_weights[-1]
num_eggs_with_this_egg = 1 + dp_make_weight(
egg_weights,
target_weight - this_egg,
memo)
num_eggs_without_this_egg = dp_make_weight(egg_weights[:-1], target_weight, memo)
if num_eggs_without_this_egg != 0:
result = min(num_eggs_with_this_egg, num_eggs_without_this_egg)
else:
result = num_eggs_with_this_egg
# Store this answer in the memo for future use.
memo[subproblem] = result
return result | 8546ab2dd0394d2864c23a47ea14614df83ec2f7 | 13,612 |
def get_impact_dates(previous_model, updated_model, impact_date=None,
start=None, end=None, periods=None):
"""
Compute start/end periods and an index, often for impacts of data updates
Parameters
----------
previous_model : MLEModel
Model used to compute default start/end periods if None are given.
In the case of computing impacts of data updates, this would be the
model estimated with the previous dataset. Otherwise, can be the same
as `updated_model`.
updated_model : MLEModel
Model used to compute the index. In the case of computing impacts of
data updates, this would be the model estimated with the updated
dataset. Otherwise, can be the same as `previous_model`.
impact_date : {int, str, datetime}, optional
Specific individual impact date. Cannot be used in combination with
`start`, `end`, or `periods`.
start : {int, str, datetime}, optional
Starting point of the impact dates. If given, one of `end` or `periods`
must also be given. If a negative integer, will be computed relative to
the dates in the `updated_model` index. Cannot be used in combination
with `impact_date`.
end : {int, str, datetime}, optional
Ending point of the impact dates. If given, one of `start` or `periods`
must also be given. If a negative integer, will be computed relative to
the dates in the `updated_model` index. Cannot be used in combination
with `impact_date`.
periods : int, optional
Number of impact date periods. If given, one of `start` or `end`
must also be given. Cannot be used in combination with `impact_date`.
Returns
-------
start : int
Integer location of the first included impact dates.
end : int
Integer location of the last included impact dates (i.e. this integer
location is included in the returned `index`).
index : pd.Index
Index associated with `start` and `end`, as computed from the
`updated_model`'s index.
Notes
-----
This function is typically used as a helper for standardizing start and
end periods for a date range where the most sensible default values are
based on some initial dataset (here contained in the `previous_model`),
while index-related operations (especially relative start/end dates given
via negative integers) are most sensibly computed from an updated dataset
(here contained in the `updated_model`).
"""
# There doesn't seem to be any universal default that both (a) make
# sense for all data update combinations, and (b) work with both
# time-invariant and time-varying models. So we require that the user
# specify exactly two of start, end, periods.
if impact_date is not None:
if not (start is None and end is None and periods is None):
raise ValueError('Cannot use the `impact_date` argument in'
' combination with `start`, `end`, or'
' `periods`.')
start = impact_date
periods = 1
if start is None and end is None and periods is None:
start = previous_model.nobs - 1
end = previous_model.nobs - 1
if int(start is None) + int(end is None) + int(periods is None) != 1:
raise ValueError('Of the three parameters: start, end, and'
' periods, exactly two must be specified')
# If we have the `periods` object, we need to convert `start`/`end` to
# integers so that we can compute the other one. That's because
# _get_prediction_index doesn't support a `periods` argument
elif start is not None and periods is not None:
start, _, _, _ = updated_model._get_prediction_index(start, start)
end = start + (periods - 1)
elif end is not None and periods is not None:
_, end, _, _ = updated_model._get_prediction_index(end, end)
start = end - (periods - 1)
elif start is not None and end is not None:
pass
# Get the integer-based start, end and the prediction index
start, end, out_of_sample, prediction_index = (
updated_model._get_prediction_index(start, end))
end = end + out_of_sample
return start, end, prediction_index | b2e6966e0fe2213e504e913d8cd64dbe84fa815b | 13,613 |
def unwrap_value(metadata, attr, default=None):
"""Gets a value like dict.get() with unwrapping it."""
data = metadata.get(attr)
if data is None:
return default
return data[0] | fee5f12f0fba86e221fe722b5829a50706ccd5dc | 13,614 |
def getTimestamp(self):
"""Get timestamp (sec)"""
return self.seconds + self.picoseconds*1e-12 | 0c913fdcd9a3ce07e31a416208a8488bd41cea81 | 13,616 |
def test_id(id):
"""Convert a test id in JSON into an immutable object that
can be used as a dictionary key"""
if isinstance(id, list):
return tuple(id)
else:
return id | 11e18a57648cb09f680751d1596193020523e5e1 | 13,623 |
import re
def MakeHeaderToken(filename):
"""Generates a header guard token.
Args:
filename: the name of the header file
Returns:
the generated header guard token.
"""
return re.sub('[^A-Z0-9_]', '_', filename.upper()) + '__' | d29f756e30c3214aac174302175c52ca28cad6cb | 13,624 |
def check_byte(b):
"""
Clamp the supplied value to an integer between 0 and 255 inclusive
:param b:
A number
:return:
Integer representation of the number, limited to be between 0 and 255
"""
i = int(b)
if i < 0:
i = 0
elif i > 255:
i = 255
return i | 374e0ffbe1d0baa80c56cafd3650fba8441c5ea0 | 13,625 |
def insert(rcd, insert_at_junctions, genotype):
"""
Given the genotype (ie the junction that was chosen), returns the corresponding insert
"""
junctions = ["x", "y", "z"]
if genotype[1] != "-":
j = junctions.index(genotype[1])
return insert_at_junctions[j]
else:
return "-" | 1bf3d7e8bb84659c3992e55fc51490c19701cff0 | 13,628 |
def _convert_labels_for_svm(y):
"""
Convert labels from {0, 1} to {-1, 1}
"""
return 2.*y - 1.0 | eca685bea6fd991245a299999fcbe31cd3b1a9ad | 13,632 |
import math
def chunks(l, n):
"""Divide l into n approximately-even chunks."""
chunksize = int(math.ceil(len(l) / n))
return [l[i:i + chunksize] for i in range(0, len(l), chunksize)] | c7b395dec7939b863097b3da9cdd49fbe2a47740 | 13,634 |
import re
def isXML(file):
"""Return true if the file has the .xml extension."""
return re.search("\.xml$", file) != None | 7fcfbb105a59f7ed6b14aa8aa183aae3fdbe082d | 13,637 |
def aggPosition(x):
"""Aggregate position data inside a segment
Args:
x: Position values in a segment
Returns:
Aggregated position (single value)
"""
return x.mean() | e9305d26f05710cc467a7fa9fd7b87737b8aa915 | 13,641 |
from typing import Tuple
def empty_handler() -> Tuple[()]:
""" A stub function that represents a handler that does nothing
"""
return () | 1450ea04fefc4ad432e5d66a765bda0f5239b002 | 13,643 |
import torch
from typing import Tuple
from typing import Union
import warnings
def data_parallel(raw_model: torch.nn.Module, *args, **kwargs) -> Tuple[Union[torch.nn.Module, torch.nn.parallel.DataParallel], bool]:
"""
Make a `torch.nn.Module` data parallel
- Parameters:
- raw_model: A target `torch.nn.Module`
- Returns: A `tuple` of either data paralleled `torch.nn.parallel.DataParallel` model if CUDA is available or a raw model if not, and a `bool` flag of if the model data paralleled successfuly.
"""
if torch.cuda.is_available():
model = torch.nn.parallel.DataParallel(raw_model, *args, **kwargs)
return model, True
else:
warnings.warn(f"[Device Warning]: CUDA is not available, unable to use multi-GPUs.", ResourceWarning)
return raw_model, False | 5b98f0e7c67ac067aba9a9c5202cceded91827ac | 13,644 |
import colorsys
def scale_lightness(rgb, scale_l):
"""
Scales the lightness of a color. Takes in a color defined in RGB, converts to HLS, lightens
by a factor, and then converts back to RGB.
"""
# converts rgb to hls
h, l, s = colorsys.rgb_to_hls(*rgb)
# manipulates h, l, s values and returns as rgb
return colorsys.hls_to_rgb(h, min(1, l * scale_l), s = s) | 2fee635f26419cfe8abc21edb0092a8c916df6ef | 13,661 |
def early_stopping(cost, opt_cost, threshold, patience, count):
"""
Determines if you should stop gradient descent. Early stopping should
occur when the validation cost of the network has not decreased relative
to the optimal validation cost by more than the threshold over a specific
patience count
cost is the current validation cost of the neural network
opt_cost is the lowest recorded validation cost of the neural network
threshold is the threshold used for early stopping
patience is the patience count used for early stopping
count is the count of how long the threshold has not been met
Returns: a boolean of whether the network should be stopped early,
followed by the updated count
"""
if opt_cost - cost > threshold:
count = 0
else:
count += 1
if count == patience:
return True, count
else:
return False, count | 5baea9f867e8ca8326270f250327494a5c47af46 | 13,664 |
def _convertCtypeArrayToList(listCtype):
"""Returns a normal list from a ctypes list."""
return listCtype[:] | 89a408b796f2aba2f34bc20942574986abd66cd2 | 13,672 |
from typing import List
def get_cost_vector(counts: dict) -> List[float]:
"""
This function simply gives values that represent how far away from our desired goal we are. Said desired goal is that
we get as close to 0 counts for the states |00> and |11>, and as close to 50% of the total counts for |01> and |10>
each.
:param counts: Dictionary containing the count of each state
:return: List of ints that determine how far the count of each state is from the desired count for that state:
-First element corresponds to |00>
-Second element corresponds to |01>
-Third element corresponds to |10>
-Fourth element corresponds to |11>
"""
# First we get the counts of each state. Try-except blocks are to avoid errors when the count is 0.
try:
a = counts['00']
except KeyError:
a = 0
try:
b = counts['01']
except KeyError:
b = 0
try:
c = counts['10']
except KeyError:
c = 0
try:
d = counts['11']
except KeyError:
d = 0
# We then want the total number of shots to know what proportions we should expect
totalShots = a + b + c + d
# We return the absolute value of the difference of each state's observed and desired counts
# Other systems to determine how far each state count is from the goal exist, but this one is simple and works well
return [abs(a - 0), abs(b - totalShots / 2), abs(c - totalShots / 2), abs(d - 0)] | b7565de2e47ba99e93b387ba954fdc29f44805e8 | 13,673 |
def build_normalized_request_string(ts, nonce, http_method, host, port, request_path, ext):
"""Implements the notion of a normalized request string as described in
http://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-02#section-3.2.1"""
normalized_request_string = \
ts + '\n' + \
nonce + '\n' + \
http_method + '\n' + \
request_path + '\n' + \
host + '\n' + \
str(port) + '\n' + \
ext + '\n'
return normalized_request_string | 6a7f397738b852116cbaf249c846f58b482fdca1 | 13,675 |
def rivers_with_station(stations):
"""Given list of stations (MonitoringStation object), return the
names of the rivers that are being monitored"""
# Collect all the names of the rivers in a set to avoid duplicate entries
rivers = {station.river for station in stations}
# Return a list for convenience
return list(rivers) | c099af2eb0f869c6f1e3270ee089f54246779e2d | 13,677 |
import math
def get_deltas(radians):
"""
gets delta x and y for any angle in radians
"""
dx = math.sin(radians)
dy = -math.cos(radians)
return dx, dy | 032acb537373d0ee18b721f04c95e75bb1572b1b | 13,679 |
from typing import Dict
def mrr(benchmark: Dict, results: Dict, repo: str) -> float:
"""
Calculate the MRR of the prediction for a repo.
:param benchmark: dictionary with the real libraries from benchmark.
:param results: dictionary with the predicted libraries.
:param repo: full name of the repo.
:return: float of the MRR.
"""
true_libraries = benchmark[repo]
suggestions = results[repo]
for index, req in enumerate(suggestions):
if req in true_libraries:
return 1 / (index + 1)
return 0 | b057c93cc807244e4d5e8e94772877273ac1041c | 13,680 |
def elf_segment_names(elf):
"""Return a hash of elf segment names, indexed by segment number."""
table = {}
seg_names_sect = elf.find_section_named(".segment_names")
if seg_names_sect is not None:
names = seg_names_sect.get_strings()[1:]
for i in range(len(names)):
table[i] = names[i]
return table | 4af46fb35c9808f8f90509417d52e7ce4eb2770e | 13,682 |
def segment_spectrum_batch(spectra_mat, w=50, dw=25):
"""
Segment multiple raman spectra into overlapping windows
Args:
spectra_mat (2D numpy array): array of input raman spectrum
w (int, optional): length of window. Defaults to 50.
dw (int, optional): step size. Defaults to 25.
Returns:
list of numpy array: list containing arrays of segmented raman spectrum
"""
return [spectra_mat[:,i:i+w] for i in range(0,spectra_mat.shape[1]-w,dw) ] | 956791e2957f4810726d1d94549f79f3d83c8d21 | 13,684 |
def transform_url(private_urls):
"""
Transforms URL returned by removing the public/ (name of the local folder with all hugo html files)
into "real" documentation links for Algolia
:param private_urls: Array of file links in public/ to transform into doc links.
:return new_private_urls: A list of documentation URL links that correspond to private doc files.
"""
new_private_urls = []
for url in private_urls:
## We add /$ to all links in order to make them all "final", in fact
## Algolia stop_url parameter uses regex and not "perfect matching" link logic
new_private_urls.append(url.replace('public/','docs.datadoghq.com/') + '/$')
return new_private_urls | 17a5c720103294b7535c76d0e8994c433cfe7de3 | 13,688 |
from typing import List
from typing import Any
def get_last_key_from_integration_context_dict(feed_type: str, integration_context: List[Any] = []) -> \
str:
"""
To get last fetched key of feed from integration context.
:param feed_type: Type of feed to get last fetched key.
:param integration_context: Integration context.
:return: list of S3 object keys.
"""
feed_context = integration_context
for cached_feed in feed_context:
cached_key = cached_feed.get(feed_type, '')
if cached_key:
return cached_key
return '' | 64eeb53cf00636dfc73866c64c77e2964149209e | 13,692 |
import math
def _parseSeconds(data):
"""
Formats a number of seconds into format HH:MM:SS.XXXX
"""
total_seconds = data.total_seconds()
hours = math.floor(total_seconds / 3600)
minutes = math.floor((total_seconds - hours * 3600) / 60)
seconds = math.floor(total_seconds - hours * 3600 - minutes * 60)
remainder = total_seconds - 3600 * hours - 60 * minutes - seconds
return "%02d:%02d:%02d%s" % (
hours,
minutes,
seconds,
(".%s" % str(round(remainder, 8))[2:]) if remainder > 0 else "",
) | b01a66f66dc3cdc930aff29069c865cab5278d08 | 13,695 |
from typing import Optional
def code_block(text: str, language: Optional[str]) -> str:
"""Formats text for discord message as code block"""
return f"```{language or ''}\n" f"{text}" f"```" | c54d5b3e6f456745817efd03b89bd56d7fe4794e | 13,700 |
import math
def hypotenuse_length(leg_a, leg_b):
"""Find the length of a right triangle's hypotenuse
:param leg_a: length of one leg of triangle
:param leg_b: length of other leg of triangle
:return: length of hypotenuse
>>> hypotenuse_length(3, 4)
5
"""
return math.sqrt(leg_a**2 + leg_b**2) | 7a59ede73301f86a8b6ea1ad28490b151ffaa08b | 13,710 |
def commonPoints(lines):
"""
Given a list of lines, return dictionary - vertice -> count. Where count
specifies how many lines share the vertex.
"""
count = {}
for l in lines:
for c in l.coords:
count[c] = count.get(c, 0) + 1
return count | 1b838ddd4d6a2539b0270cd319a2197e90372c3a | 13,716 |
def isostring(dt):
"""Convert the datetime to ISO 8601 format with no microseconds. """
if dt:
return dt.replace(microsecond=0).isoformat() | db7326e53402c0982514c4516971b4460840aa20 | 13,720 |
def git_origin_url(git_repo): # pylint: disable=redefined-outer-name
"""
A fixture to fetch the URL of the online hosting for this repository. Yields
None if there is no origin defined for it, or if the target directory isn't
even a git repository.
"""
if git_repo is None:
return None
try:
origin = git_repo.remotes.origin
except ValueError:
# This local repository isn't linked to an online origin
return None
return origin.url | d1f301a31aca6fae2f687d2b58c742ee747c4114 | 13,724 |
def special_len(tup):
"""
comparison function that will sort a document:
(a) according to the number of segments
(b) according to its longer segment
"""
doc = tup[0] if type(tup) is tuple else tup
return (len(doc), len(max(doc, key=len))) | 81154c8e1b31dc37cffc43dfad608a5cd5281e4c | 13,730 |
from typing import Optional
def optional_arg_return(some_str: Optional[str]) -> Optional[int]:
"""Optional type in argument and return value."""
if not some_str:
return None # OK
# Mypy will infer the type of some_str to be str due to the check against None
return len(some_str) | 8125965fb1fe1f11f4f5045afc8107bcdfc95fc0 | 13,736 |
import cProfile
import time
import pstats
def profile(fn):
"""
Profile the decorated function, storing the profile output in /tmp
Inspired by
https://speakerdeck.com/rwarren/a-brief-intro-to-profiling-in-python
"""
def profiled_fn(*args, **kwargs):
filepath = "/tmp/%s.profile" % fn.__name__
prof = cProfile.Profile()
start = time.time()
result = prof.runcall(fn, *args, **kwargs)
duration = time.time() - start
print("Function ran in %.6f seconds - output written to %s" % (
duration, filepath))
prof.dump_stats(filepath)
print("Printing stats")
stats = pstats.Stats(filepath)
stats.sort_stats('cumulative')
stats.print_stats()
return result
return profiled_fn | aaf1711fefee698ff5456e120dcc06cbb8c22a8f | 13,739 |
def pwd(session, *_):
"""Prints the current directory"""
print(session.env.pwd)
return 0 | 0f63b0483453f30b9fbaf5f561cb8eb90f38e107 | 13,743 |
def feature_list_and_dict(features):
"""
Assign numerical indices to a global list of features
:param features: iterable of feature names
:return: sorted list of features, dict mapping features to their indices
"""
feature_list = sorted(features)
feature_dict = {feat:i for i, feat in enumerate(feature_list)}
return feature_list, feature_dict | 11006cdc4871c339cf3936a1734f012f21d92459 | 13,746 |
def compute_St(data):
"""
Given a dataset, computes the variance matrix of its features.
"""
n_datapoints, n_features = data.shape
# Computing the 'mean image'. A pixel at position (x,y) in this image is the
# mean of all the pixels at position (x,y) of the images in the dataset.
# This corresponds to the 'mu' we have seen in the lectures.
mu = data.mean(axis=0) # apply along the rows for each columns.
centered_data = data - mu
# Computing the covariance matrix
St = (1. / n_datapoints) * (centered_data.T * centered_data)
return St | 99f55de9c19f7304136e5737d9acba0e6de4d2fd | 13,748 |
def metamodel_to_swagger_type_converter(input_type):
"""
Converts API Metamodel type to their equivalent Swagger type.
A tuple is returned. first value of tuple is main type.
second value of tuple has 'format' information, if available.
"""
input_type = input_type.lower()
if input_type == 'date_time':
return 'string', 'date-time'
if input_type == 'secret':
return 'string', 'password'
if input_type == 'any_error':
return 'string', None
if input_type == 'opaque':
return 'object', None
if input_type == 'dynamic_structure':
return 'object', None
if input_type == 'uri':
return 'string', 'uri'
if input_type == 'id':
return 'string', None
if input_type == 'long':
return 'integer', 'int64'
if input_type == 'double':
return 'number', 'double'
if input_type == 'binary':
return 'string', 'binary'
return input_type, None | a1f01124546acc3035d3db3329b0194ac65c2f17 | 13,750 |
def is_instance(arg, types, allow_none=False):
"""
>>> is_instance(1, int)
True
>>> is_instance(3.5, float)
True
>>> is_instance('hello', str)
True
>>> is_instance([1, 2, 3], list)
True
>>> is_instance(1, (int, float))
True
>>> is_instance(3.5, (int, float))
True
>>> is_instance('hello', (str, list))
True
>>> is_instance([1, 2, 3], (str, list))
True
>>> is_instance(1, float)
False
>>> is_instance(3.5, int)
False
>>> is_instance('hello', list)
False
>>> is_instance([1, 2, 3], str)
False
>>> is_instance(1, (list, str))
False
>>> is_instance(3.5, (list, str))
False
>>> is_instance('hello', (int, float))
False
>>> is_instance([1, 2, 3], (int, float))
False
>>> is_instance(None, int)
False
>>> is_instance(None, float)
False
>>> is_instance(None, str)
False
>>> is_instance(None, list)
False
>>> is_instance(None, (int, float))
False
>>> is_instance(None, (int, float))
False
>>> is_instance(None, (str, list))
False
>>> is_instance(None, (str, list))
False
>>> is_instance(1, int, allow_none=True)
True
>>> is_instance(3.5, float, allow_none=True)
True
>>> is_instance('hello', str, allow_none=True)
True
>>> is_instance([1, 2, 3], list, allow_none=True)
True
>>> is_instance(1, (int, float), allow_none=True)
True
>>> is_instance(3.5, (int, float), allow_none=True)
True
>>> is_instance('hello', (str, list), allow_none=True)
True
>>> is_instance([1, 2, 3], (str, list), allow_none=True)
True
>>> is_instance(1, float, allow_none=True)
False
>>> is_instance(3.5, int, allow_none=True)
False
>>> is_instance('hello', list, allow_none=True)
False
>>> is_instance([1, 2, 3], str, allow_none=True)
False
>>> is_instance(1, (list, str), allow_none=True)
False
>>> is_instance(3.5, (list, str), allow_none=True)
False
>>> is_instance('hello', (int, float), allow_none=True)
False
>>> is_instance([1, 2, 3], (int, float), allow_none=True)
False
>>> is_instance(None, int, allow_none=True)
True
>>> is_instance(None, float, allow_none=True)
True
>>> is_instance(None, str, allow_none=True)
True
>>> is_instance(None, list, allow_none=True)
True
>>> is_instance(None, (int, float), allow_none=True)
True
>>> is_instance(None, (int, float), allow_none=True)
True
>>> is_instance(None, (str, list), allow_none=True)
True
>>> is_instance(None, (str, list), allow_none=True)
True
"""
return (allow_none and arg is None) or isinstance(arg, types) | 52149919b010909614c7dc83e189fa3b8a950393 | 13,752 |
def get_fire_mode(weapon):
"""Returns current fire mode for a weapon."""
return weapon['firemodes'][weapon['firemode']] | 691fc5e9b3ce40e51ab96930086f8d57e5fa6284 | 13,754 |
def depth_first_ordering(adjacency, root):
"""Compute depth-first ordering of connected vertices.
Parameters
----------
adjacency : dict
An adjacency dictionary. Each key represents a vertex
and maps to a list of neighboring vertex keys.
root : str
The vertex from which to start the depth-first search.
Returns
-------
list
A depth-first ordering of all vertices in the network.
Notes
-----
Return all nodes of a connected component containing 'root' of a network
represented by an adjacency dictionary.
This implementation uses a *to visit* stack. The principle of a stack
is LIFO. In Python, a list is a stack.
Initially only the root element is on the stack. While there are still
elements on the stack, the node on top of the stack is 'popped off' and if
this node was not already visited, its neighbors are added to the stack if
they hadn't already been visited themselves.
Since the last element on top of the stack is always popped off, the
algorithm goes deeper and deeper in the datastructure, until it reaches a
node without (unvisited) neighbors and then backtracks. Once a new node
with unvisited neighbors is found, there too it will go as deep as possible
before backtracking again, and so on. Once there are no more nodes on the
stack, the entire structure has been traversed.
Note that this returns a depth-first spanning tree of a connected component
of the network.
Examples
--------
>>> import compas
>>> from compas.datastructures import Network
>>> from compas.topology import depth_first_search as dfs
>>> network = Network.from_obj(compas.get('lines.obj'))
>>> print(dfs(network, network.get_any_vertex()))
See Also
--------
*
"""
adjacency = {key: set(nbrs) for key, nbrs in iter(adjacency.items())}
tovisit = [root]
visited = set()
ordering = []
while tovisit:
# pop the last added element from the stack
node = tovisit.pop()
if node not in visited:
# mark the node as visited
visited.add(node)
ordering.append(node)
# add the unvisited nbrs to the stack
tovisit.extend(adjacency[node] - visited)
return ordering | fcff465cfaa2e3a500e8d177e6b9e78cc66bc21d | 13,757 |
from typing import List
from typing import Tuple
from textwrap import dedent
def get_rt_object_to_complete_texts() -> List[Tuple[str, str]]:
"""Returns a list of tuples of riptable code object text with associated completion text."""
return [
(
dedent(
'''Dataset({_k: list(range(_i * 10, (_i + 1) * 10)) for _i, _k in enumerate(
["alpha", "beta", "gamma", "delta", "epsilon", "zeta", "eta", "theta", "iota", "kappa", "lambada", "mu",
"nu", "xi", "omnicron", "pi"])})'''
),
"dataset.",
),
(
dedent(
'''Struct({"alpha": 1, "beta": [2, 3], "gamma": ['2', '3'], "delta": arange(10),
"epsilon": Struct({
"theta": Struct({
"kappa": 3,
"zeta": 4,
}),
"iota": 2,
})
})'''
),
"struct.",
),
(
dedent(
'''Multiset(
{"ds_alpha": Dataset({k: list(range(i * 10, (i + 1) * 10)) for i, k in enumerate(
["alpha", "beta", "gamma", "delta", "epsilon", "zeta"])}),
"ds_beta": Dataset({k: list(range(i * 10, (i + 1) * 10)) for i, k in enumerate(
["eta", "theta", "iota", "kappa", "lambada", "mu"])}),
})'''
),
"multiset.",
),
] | 007d2291fd922aab5627783897a56cd5fd715f98 | 13,760 |
import token
import requests
def create_mirror(gitlab_repo, github_token, github_user):
"""Creates a push mirror of GitLab repository.
For more details see:
https://docs.gitlab.com/ee/user/project/repository/repository_mirroring.html#pushing-to-a-remote-repository-core
Args:
- gitlab_repo: GitLab repository to mirror.
- github_token: GitHub authentication token.
- github_user: GitHub username under whose namespace the mirror will be created (defaults to GitLab username if not provided).
Returns:
- JSON representation of created mirror.
"""
url = f'https://gitlab.com/api/v4/projects/{gitlab_repo["id"]}/remote_mirrors'
headers = {'Authorization': f'Bearer {token}'}
# If github-user is not provided use the gitlab username
if not github_user:
github_user = gitlab_repo['owner']['username']
data = {
'url': f'https://{github_user}:{github_token}@github.com/{github_user}/{gitlab_repo["path"]}.git',
'enabled': True
}
try:
r = requests.post(url, json=data, headers=headers)
r.raise_for_status()
except requests.exceptions.RequestException as e:
raise SystemExit(e)
return r.json() | 2a5d7e01ca04a6dcb09d42b5fc85092c3476af0d | 13,761 |
def genelist_mask(candidates, genelist, whitelist=True, split_on_dot=True):
"""Get a mask for genes on or off a list
Parameters
----------
candidates : pd.Series
Candidate genes (from matrix)
genelist : pd.Series
List of genes to filter against
whitelist : bool, default True
Is the gene list a whitelist (True), where only genes on it should
be kept or a blacklist (False) where all genes on it should be
excluded
split_on_dot : bool, default True
If True, remove part of gene identifier after '.'. We do this by
default because ENSEMBL IDs contain version numbers after periods.
Returns
-------
passing_mask : ndarray
boolean array of passing genes
"""
if split_on_dot:
candidates = candidates.str.split('.').str[0]
genelist = genelist.str.split('.').str[0]
if whitelist:
mask = candidates.isin(genelist)
else:
mask = ~candidates.isin(genelist)
return mask.values | 53e1f80de097311faddd4bfbff636729b076c984 | 13,762 |
def parse_releases(list):
"""
Parse releases from a MangaUpdate's search results page.
Parameters
----------
list : BeautifulSoup
BeautifulSoup object of the releases section of the search page.
Returns
-------
releases : list of dicts
List of recent releases found by the search.
::
[
{
'id': 'Series Id',
'name': 'Series name',
'chp': 'chapter number',
'vol': 'number' or None,
'date': '02/21/21', # Date in month/day/year
'group': {
'name': 'Scanlation Group',
'id': 'Scanlation Group Id'
}
}
]
"""
releases = list.find_all("div", class_="text")[:-1]
results = []
for i in range(0, len(releases), 5):
release = {}
release["date"] = str(releases[i].string)
series_link = releases[i + 1]
if series_link.a is None:
release["name"] = str(series_link.string)
else:
release["name"] = str(series_link.a.string)
release["id"] = series_link.a["href"].replace(
"https://www.mangaupdates.com/series.html?id=", ""
)
vol = releases[i + 2].get_text()
release["vol"] = vol if vol else None
release["chp"] = str(releases[i + 3].string)
release["group"] = {
"name": releases[i + 4].get_text(),
"id": releases[i + 4]
.a["href"]
.replace("https://www.mangaupdates.com/groups.html?id=", ""),
}
results.append(release)
return results | e7e93130732998b919bbd2ac69b7fc36c20dd62d | 13,764 |
def Sqrt(x):
"""Square root function."""
return x ** 0.5 | e726dfad946077826bcc19f44cd6a682c3b6410c | 13,774 |
def hello(friend_name):
"""Says 'Hello!' to a friend."""
return "Hello, {}!".format(friend_name.title()) | 706c5a2d3f7ebdf9c7b56e49bb0541655c191505 | 13,775 |
def count_digit(value):
"""Count the number of digits in the number passed into this function"""
digit_counter = 0
while value > 0:
digit_counter = digit_counter + 1
value = value // 10
return digit_counter | f9b1738804b0a40aa72283df96d2707bcfd7e74c | 13,790 |
import json
def parse_fio_output_file(fpath: str) -> dict:
""" Read and parse json from fio json outputs """
lines = []
with open(fpath, 'r') as fiof:
do_append = False
for l in fiof:
if l.startswith('{'):
do_append = True
if do_append:
lines.append(l)
if l.startswith('}'):
break
try:
return json.loads(''.join(lines))
except json.decoder.JSONDecodeError:
return {} | ce4efcd3f0508179971788a2c19a7f278d887a79 | 13,800 |
def get_full_name(participant):
"""Returns the full name of a given participant"""
return participant['fields']['First Name'].strip() + \
' ' + participant['fields']['Last Name'].strip() | 4292ea595d13e8093f6d221c40634e8fe74b8e91 | 13,802 |
def find_new_values(data, values, key):
"""Identify any new label/description values which could be added to an item.
@param data: the contents of the painting item
@type data: dict
@param values: the output of either make_labels or make_descriptions
@type values: dict
@param key: the type of values being processed (labels or descriptions)
@type key: string
@return lang-value pairs for new information
@rtype dict
"""
new_values = {}
for lang, value in values.iteritems():
if lang not in data.get(key).keys():
new_values[lang] = value['value']
return new_values | db56c07aedb38458be8aa0fc6bc4b5f4b49b4f4d | 13,804 |
def getattritem(o,a):
"""
Get either attribute or item `a` from a given object `o`. Supports multiple evaluations, for example
`getattritem(o,'one.two')` would get `o.one.two`, `o['one']['two']`, etc.
:param o: Object
:param a: Attribute or Item index. Can contain `.`, in which case the final value is obtained.
:return: Value
"""
flds = a.split('.')
for x in flds:
if x in dir(o):
o = getattr(o,x)
else:
o = o[x]
return o | 7b928b2405691dcb5fac26b7a3d7ebfcfa642f6d | 13,807 |
def wgan_generator_loss(gen_noise, gen_net, disc_net):
"""
Generator loss for Wasserstein GAN (same for WGAN-GP)
Inputs:
gen_noise (PyTorch Tensor): Noise to feed through generator
gen_net (PyTorch Module): Network to generate images from noise
disc_net (PyTorch Module): Network to determine whether images are real
or fake
Outputs:
loss (PyTorch scalar): Generator Loss
"""
# draw noise
gen_noise.data.normal_()
# get generated data
gen_data = gen_net(gen_noise)
# feed data through discriminator
disc_out = disc_net(gen_data)
# get loss
loss = -disc_out.mean()
return loss | 090de59ebc8e009b19e79047f132014f747972e7 | 13,809 |
def find_val_percent(minval, maxval, x):
"""Find the percentage of a value, x, between a min and max number.
minval -- The low number of the range.
maxval -- The high number of the range.
x -- A value between the min and max value."""
if not minval < x < maxval:
print("\n" + " ERROR: X must be between minval and maxval.")
print(" Defaulting to 50 percent because why not Zoidberg. (\/)ಠ,,,ಠ(\/)" + "\n")
return (x - minval) / (maxval - minval) * 100 | 13661bb2b6b230fa212ddd3ceb96c5b362d52f19 | 13,814 |
def name(who):
"""Return the name of player WHO, for player numbered 0 or 1."""
if who == 0:
return 'Player 0'
elif who == 1:
return 'Player 1'
else:
return 'An unknown player' | a553b64c7a03760e974b5ddeac170105dd5b8edd | 13,815 |
def mean(nums):
"""
Gets mean value of a list of numbers
:param nums: contains numbers to be averaged
:type nums: list
:return: average of nums
:rtype: float or int
"""
counter = 0
for i in nums:
counter += i
return counter / len(nums) | d3ea7af8792f4fdd503d5762b5c0e54765ce2d99 | 13,816 |
import torch
def compute_rank(predictions, targets):
"""Compute the rank (between 1 and n) of of the true target in ordered predictions
Example:
>>> import torch
>>> compute_rank(torch.tensor([[.1, .7, 0., 0., .2, 0., 0.],
... [.1, .7, 0., 0., .2, 0., 0.],
... [.7, .2, .1, 0., 0., 0., 0.]]),
... torch.tensor([4, 1, 3]))
tensor([2, 1, 5])
Args:
predictions (torch.Tensor): [n_pred, n_node]
targets (torch.Tensor): [n_pred]
"""
n_pred = predictions.shape[0]
range_ = torch.arange(n_pred, device=predictions.device, dtype=torch.long)
proba_targets = predictions[range_, targets]
target_rank_upper = (proba_targets.unsqueeze(1) < predictions).long().sum(dim=1) + 1
target_rank_lower = (proba_targets.unsqueeze(1) <= predictions).long().sum(dim=1)
# break tighs evenly by taking the mean rank
target_rank = (target_rank_upper + target_rank_lower) / 2
return target_rank | 0aed5b14ef9b0f318239e98aa02d0ee5ed9aa758 | 13,819 |
import json
def load_scalabel_frames( scalabel_frames_path ):
"""
Loads Scalabel frames from a file. Handles both raw sequences of Scalabel frames
as well as labels exported from Scalabel.ai's application.
Raises ValueError if the data read isn't of a known type.
Takes 1 argument:
scalabel_frames_path - Path to serialized Scalabel frames.
Returns 1 value:
scalabel_frames - A list of Scalabel frames.
"""
with open( scalabel_frames_path, "r" ) as scalabel_frames_fp:
scalabel_frames = json.load( scalabel_frames_fp )
# handle the case where we have exported labels from Scalabel.ai itself vs
# a list of frames.
if type( scalabel_frames ) == dict:
if "frames" in scalabel_frames:
return scalabel_frames["frames"]
elif type( scalabel_frames ) == list:
return scalabel_frames
raise ValueError( "Unknown structure read from '{:s}'.".format(
scalabel_frames_path ) ) | 7e5467d0f184dba1e3efc724391931ed4053a683 | 13,821 |
def ovs_version_str(host):
""" Retrieve OVS version and return it as a string """
mask_cmd = None
ovs_ver_cmd = "ovs-vsctl get Open_vSwitch . ovs_version"
with host.sudo():
if not host.exists("ovs-vsctl"):
raise Exception("Unable to find ovs-vsctl in PATH")
mask_cmd = host.run(ovs_ver_cmd)
if not mask_cmd or mask_cmd.failed or not mask_cmd.stdout:
raise Exception("Failed to get OVS version with command '{cmd}'"
.format(cmd=ovs_ver_cmd))
return mask_cmd.stdout.strip('"\n') | 607ffbb2ab1099e86254a90d7ce36d4a9ae260ed | 13,822 |
from typing import List
def csv_rows(s: str) -> List[List[str]]:
"""Returns a list of list of strings from comma-separated rows"""
return [row.split(',') for row in s.split('\n')] | 7a6ea8c0f69801cfb1c0369c238e050502813b63 | 13,824 |
import calendar
def create_disjunctive_constraints(solver, flat_vars):
"""
Create constrains that forbids multiple events from taking place at the same time.
Returns a list of `SequenceVar`s, one for each day. These are then used in the first
phase of the solver.
"""
events_for_day = [[] for _ in range(5)]
for v in flat_vars:
events_for_day[v.day].append(v)
sequences_for_day = []
for day_num, day in enumerate(events_for_day):
if not day:
# For empty arrays, OR-tools complains:
# "operations_research::Solver::MakeMax() was called with an empty list of variables."
continue
disj = solver.DisjunctiveConstraint(day, calendar.day_abbr[day_num])
solver.Add(disj)
sequences_for_day.append(disj.SequenceVar())
return sequences_for_day | f7f8592ac00c8cac9808bb80d425ff1c1cf10b9e | 13,827 |
import random
def filter_shuffle(seq):
"""
Basic shuffle filter
:param seq: list to be shuffled
:return: shuffled list
"""
try:
result = list(seq)
random.shuffle(result)
return result
except:
return seq | 3f2dce2133ba32d8c24d038afaecfa14d37cbd4e | 13,831 |
def get_package_list_from_file(path):
"""
Create a list of packages to install from a provided .txt file
Parameters
__________
path: Filepath to the text file (.txt) containing the list of packages to install.
Returns
______
List of filepaths to packages to install.
Notes
_____
.txt file should provide the full filepath to packages to install and be newline (\n) delimited.
"""
# Verify we have a text file
if not path.endswith('.txt'):
raise RuntimeError("Package List must be a newline(\n) delimited text file.")
# read lines of the file and strip whitespace
with open(path, 'r') as f:
pkg_list = [line.rstrip().rstrip("/") for line in f]
# Verify that we are not given an empty list
if not pkg_list:
raise RuntimeError("No packages found to be installed. "
"Please provide a file with a minimum of 1 package location.")
return pkg_list | 91ef3e634e98afd116d2be9c803620f672acd950 | 13,832 |
def parse_jcamp_line(line,f):
"""
Parse a single JCAMP-DX line
Extract the Bruker parameter name and value from a line from a JCAMP-DX
file. This may entail reading additional lines from the fileobj f if the
parameter value extends over multiple lines.
"""
# extract key= text from line
key = line[3:line.index("=")]
text = line[line.index("=")+1:].lstrip()
if "<" in text: # string
while ">" not in text: # grab additional text until ">" in string
text = text+"\n"+f.readline().rstrip()
value = text.replace("<","").replace(">","")
elif "(" in text: # array
num = int(line[line.index("..")+2:line.index(")")])+1
value = []
rline = line[line.index(")")+1:]
# extract value from remainer of line
for t in rline.split():
if "." in t or "e" in t:
value.append(float(t))
else:
value.append(int(t))
# parse additional lines as necessary
while len(value) < num:
nline = f.readline().rstrip()
for t in nline.split():
if "." in t or "e" in t:
value.append(float(t))
else:
value.append(int(t))
elif text == "yes":
value = True
elif text == "no":
value = False
else: # simple value
if "." in text or "e" in text:
value = float(text)
else:
value = int(text)
return key,value | 84061c3f4bc42a62e308d5f93877e5c55d85efc1 | 13,833 |
def getSubNode(prgNode, NodeName):
""" Find Sub-Node in Programm Node
Arguments:
prgNode {ua PrgNode} -- Programm node to scan
NodeName {[type]} -- Name of Sub-Node to find
Returns:
ua Node -- Sub-Node
"""
for child in prgNode.get_children():
if child.get_display_name().Text == NodeName:
return child | 2da431eff566d7e2c76d4ca4646e15f762c00d4d | 13,837 |
def stations_by_river(stations):
"""This function returns a Python dict (dictionary) that maps river
names (the key) to a list of station objects on a given river."""
y = {}
for n in stations:
if n.river not in y:
y[n.river] = [n.name]
else: y[n.river].append(n.name)
return y | 1e1023cdad87a3fdd5921d08448a4a2e9ceb311c | 13,840 |
def doTest(n):
"""Runs a test. returns score."""
score = 0
l = list(range(1,16))
for i in l:
if input("what is {} to the power of 3? ".format(i)) == str(i**3):
score += 1
print("Correct.")
else:
print("Wrong, the correct answer is {}".format(i**3))
return score | 83f32bec718e7459218b8863e229d5ecbd479d2c | 13,841 |
def preorder(root):
"""Preorder depth-first traverse a binary tree."""
ans = []
stack = [root]
while stack:
node = stack.pop()
if node:
ans.append(node.val)
stack.extend([node.right, node.left])
return ans | e322df77a973f30b0745b36540a0f66b2ce29e6d | 13,844 |
from typing import Counter
def percentile(data: list, p=0.5):
"""
:param data: origin list
:param p: frequency percentile
:return: the element at frequency percentile p
"""
assert 0 < p < 1
boundary = len(data) * p
counter = sorted(Counter(data).items(), key=lambda x: x[0])
keys, counts = zip(*counter)
accumulation = 0
for i, c in enumerate(counts):
accumulation += c
if accumulation > boundary:
return keys[i]
return None | ac0a3a4705579c1b6a5165b91e6dcad65afcd1f4 | 13,851 |
def _get_path_from_parent(self, parent):
"""
Return a list of PathInfos containing the path from the parent
model to the current model, or an empty list if parent is not a
parent of the current model.
"""
if hasattr(self, 'get_path_from_parent'):
return self.get_path_from_parent(parent)
if self.model is parent:
return []
model = self.concrete_model
# Get a reversed base chain including both the current and parent
# models.
chain = model._meta.get_base_chain(parent) or []
chain.reverse()
chain.append(model)
# Construct a list of the PathInfos between models in chain.
path = []
for i, ancestor in enumerate(chain[:-1]):
child = chain[i + 1]
link = child._meta.get_ancestor_link(ancestor)
path.extend(link.get_reverse_path_info())
return path | 8f213fcbe3612790d4922d53e0e2a4465b098fe6 | 13,852 |
def strdigit_normalize(digit):
"""Normalizes input to format '0x'. Example: '9' -> '09'"""
assert type(digit) is str, 'Invalid input. Must be a string.'
s = int(digit)
assert s >= 0, 'Invalid input. Must be string representing a positive number.'
if s < 10:
return '0' + str(s)
return digit | 41b119b4b8b19f978bf4445fc81273f7e62af59a | 13,853 |
import hashlib
def hash_file(pathname):
"""Returns a byte string that is the SHA-256 hash of the file at the given pathname."""
h = hashlib.sha256()
with open(pathname, 'rb') as ifile:
h.update(ifile.read())
return h.digest() | bdd82aa57abacee91a4631d401af35f0274eb804 | 13,859 |
import random
def is_prime(number, test_count):
"""
Uses the Miller-Rabin test for primality to determine, through TEST_COUNT
tests, whether or not NUMBER is prime.
"""
if number == 2 or number == 3:
return True
if number <= 1 or number % 2 == 0:
return False
d = 0
r = number - 1
while r % 2 == 1:
d += 1
r //= 2
for _1 in range(test_count):
a = random.randrange(2, number - 1)
x = pow(a, r, number)
if x != 1 and x != number - 1:
for _2 in range(d):
x = (x ** 2) % number
if x == 1:
return False
if x == number - 1:
break
if x != number - 1:
return False
return True | 49b0149dad5f053bbf813845a10267766784c775 | 13,864 |
import math
def data_to_sorted_xy(data, logx):
"""
Return a list of (x, y) pairs with distinct x values and sorted by x value.
Enter: data: a list of (x, y) or [x, y] values.
logx: True to return (log10(x), y) for each entry.
Exit: data: the sorted list with unique x values.
"""
if not logx:
if (len(data) <= 1 or (
data[0][0] < data[1][0] and (len(data) <= 2 or (
data[1][0] < data[2][0] and (len(data) <= 3 or (
data[2][0] < data[3][0] and len(data) == 4)))))):
return data
return sorted(dict(data).items())
return sorted({math.log10(x): y for x, y in data}.items()) | 7e84a3f684dc9a82bf5fd48256e5f5c18a5eedb6 | 13,870 |
def is_catalog_record_owner(catalog_record, user_id):
"""
Does user_id own catalog_record.
:param catalog_record:
:param user_id:
:return:
"""
if user_id and catalog_record.get('metadata_provider_user') == user_id:
return True
return False | bb5e649b4cfd38ee17f3ab83199b4736b374d312 | 13,871 |
import random
def init(size):
"""Creates a randomly ordered dataset."""
# use system time as seed
random.seed(None)
# set random order as accessor
order = [a for a in range(0, size)]
random.shuffle(order)
# init array with random data
data = [random.random() for a in order]
return (order, data) | 975ab66f4e759973d55a0c519609b6df7086d747 | 13,874 |
def bounding_rect(mask, pad=0):
"""Returns (r, b, l, r) boundaries so that all nonzero pixels in mask
have locations (i, j) with t <= i < b, and l <= j < r."""
nz = mask.nonzero()
if len(nz[0]) == 0:
# print('no pixels')
return (0, mask.shape[0], 0, mask.shape[1])
(t, b), (l, r) = [(max(0, p.min() - pad), min(s, p.max() + 1 + pad))
for p, s in zip(nz, mask.shape)]
return (t, b, l, r) | 850db378abb0a8e1675e0937b66dfb4061ced50b | 13,885 |
import csv
def get_return_fields(filepath):
"""Extract the returnable fields for results from the file with
description of filters in ENA as a dictionary with the key being the field
id and the value a list of returnable fields
filepath: path with csv with filter description
"""
returnable_fields = {}
with open(filepath, "r") as f:
reader = csv.DictReader(f, delimiter=';')
for row in reader:
returnable_fields.setdefault(
row["Result"],
row["Returnable fields"].split(", "))
return returnable_fields | d70efe68de8cbd100b66cee58baf6ca542cb81a8 | 13,887 |
import random
def roll_damage(dice_stacks, modifiers, critical=False):
"""
:param dice_stacks: Stacks of Dice to apply
:param modifiers: Total of modifiers affecting the roll
:param critical: If is a critical damage roll
:return: Total damage to apply.
"""
if critical:
for dice_stack in dice_stacks:
dice_stack.amount *= 2
total_dice_result = 0
for dice_stack in dice_stacks:
for i in range(0, dice_stack.amount):
total_dice_result += random.randint(1, dice_stack.dice.sides)
return total_dice_result + modifiers | 2627f1de0fe0754a4bfc802378ea1950b2b078a2 | 13,892 |
def get_audio_bitrate(bitrate):
"""
Get audio bitrate from bits to human easy readable format in kbits.
Arguments:
:param bitrate: integer -- audio bitrate in bits per seconds
:return: string
"""
return "%s kbps" %(bitrate/1000) | 847d74e08e8f75b24be1fc144fb3896f5e141daf | 13,893 |
import collections
def load_manifest(manifest_path):
"""Extract sample information from a manifest file.
"""
# pylint: disable=I0011,C0103
Sample = collections.namedtuple("Sample", "id status path")
samples = []
with open(manifest_path, "r") as manifest_file:
for line in manifest_file:
sample_id, status, path = line.split()
if status not in ["case", "control"]:
message = (
'Sample status must be either "case" or "control";'
' instead got "{}"'
)
raise Exception(message.format(status))
sample = Sample(id=sample_id, status=status, path=path)
samples.append(sample)
return samples | 21e15fa8de75d963f8d35c4b5f939d3fcee45c99 | 13,898 |
def _get_all_osc(centers, osc_low, osc_high):
"""Returns all the oscillations in a specified frequency band.
Parameters
----------
centers : 1d array
Vector of oscillation centers.
osc_low : int
Lower bound for frequency range.
osc_high : int
Upper bound for frequency range.
Returns
-------
osc_cens : 1d array
Osc centers in specified frequency band.
"""
# Get inds of desired oscs and pull out from input data
osc_inds = (centers >= osc_low) & (centers <= osc_high)
osc_cens = centers[osc_inds]
return osc_cens | 9199283080bd0111d8ca3cb74f4c0865de162027 | 13,903 |
from typing import OrderedDict
def load_section(cp, section, ordered=True):
"""
Returns a dict of the key/value pairs in a specified section of a configparser instance.
:param cp: the configparser instance.
:param section: the name of the INI section.
:param ordered: if True, will return a <collections.OrderedDictionary>; else a <dict>.
:param kwargs: passed through to the load_config_file() function.
:return: a dict containing the specified section's keys and values.
"""
items = cp.items(section=section)
if bool(ordered):
return OrderedDict(items)
else:
return dict(items) | 9b819efb75082138eb9e13405ac256908112c744 | 13,908 |
import json
def open_json(path):
"""Open the db from JSON file previously saved at given path."""
fd = open(path, 'r')
return json.load(fd) | c0c0c4857b4582091a145a71767bc0168808593a | 13,911 |
def convert_resolv_conf(nameservers, searchdomains):
"""Returns a string formatted for resolv.conf."""
result = []
if nameservers:
nslist = "DNS="
for ns in nameservers:
nslist = nslist + '%s ' % ns
nslist = nslist + '\n'
result.append(str(nslist))
if searchdomains:
sdlist = "Domains="
for sd in searchdomains:
sdlist = sdlist + '%s ' % sd
sdlist = sdlist + '\n'
result.append(str(sdlist))
return result | 47175fb2dddac151a94b99b1c51942a3e5ca66a1 | 13,915 |
def password_okay_by_char_count(pwd_row):
"""
Process list of rows from a file, where each row contains pwd policy and pwd.
Pwd is only valid if the indicated character is found between x and y times (inclusive) in the pwd.
E.g. 5-7 z: qhcgzzz
This pwd is invalid, since z is only found 3 times, but minimum is 5.
"""
# Each input row looks like "5-7 z: qhcgzzz"
# Convert each row to a list that looks like ['5-7 z', 'qhcgzzz']
pwd_policy_and_pwd = [item.strip() for item in pwd_row.split(":")]
#print(pwd_policy_and_pwd)
pwd = pwd_policy_and_pwd[1]
char_counts, _, char_match = pwd_policy_and_pwd[0].partition(" ")
min_chars, _, max_chars = char_counts.partition("-")
actual_char_count = pwd.count(char_match)
if (actual_char_count < int(min_chars)) or (actual_char_count > int(max_chars)):
return False
return True | 4571d1d6e47aef1c31257365cd0db4240db93d6c | 13,917 |
def _getSubjectivityFromScore( polarity_score ):
"""
Accepts the subjectivity score and returns the label
0.00 to 0.10 - Very Objective
0.10 to 0.45 - Objective
0.45 to 0.55 - Neutral
0.55 to 0.90 - Subjective
0.90 to 1.00 - Very Subjective
"""
status = "unknown"
if ( 0.00 <= polarity_score <= 0.10 ):
return "Very Objective"
elif( 0.10 < polarity_score < 0.45 ):
return "Objective"
elif( 0.45 <= polarity_score <= 0.55 ):
return "Neutral"
elif( 0.55 < polarity_score < 0.90 ):
return "Subjective"
elif( 0.90 <= polarity_score <= 1.00 ):
return "Very Subjective"
return status | 16e126032fea92d0eac2d4e6b35c9b6666196ad1 | 13,919 |
import base64
def extract_basic_auth(auth_header):
"""
extract username and password from a basic auth header
:param auth_header: content of the Authorization HTTP header
:return: username and password extracted from the header
"""
parts = auth_header.split(" ")
if parts[0] != "Basic" or len(parts) < 2:
return None, None
auth_parts = base64.b64decode(parts[1]).split(b":")
if len(auth_parts) < 2:
return None, None
return auth_parts[0].decode(), auth_parts[1].decode() | 8f3830bc78b0e9fb6182f130e38acea4bd189c86 | 13,920 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.