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 = "{}".... | 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)
... | 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
-----------
... | 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 ... | 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... | 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
--... | 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 sor... | 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/e... | 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 `tor... | 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 retu... | 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
... | 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... | 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 +... | 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 conveni... | 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.... | 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... | 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.
... | 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 do... | 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... | 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 - min... | 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... | 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
... | 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.__... | 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 enumera... | 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 cor... | 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 == 'd... | 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
... | 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 s... | 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(... | 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: Git... | 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
... | 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 t... | 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:
... | 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 v... | 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 ... | 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 ... | 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 mu... | 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.],
... | 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:
scalab... | 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.r... | 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 _... | 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
... | 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 f... | 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_na... | 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)
ret... | 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)... | 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, c... | 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)
... | 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 = ... | 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.
"""
i... | 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) = [... | 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_fi... | 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_sta... | 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_fi... | 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 ra... | 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 <colle... | 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 searchdo... | 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, bu... | 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... | 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 l... | 8f3830bc78b0e9fb6182f130e38acea4bd189c86 | 13,920 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.