content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def concat_to_address(ip, port):
"""
ip: str for address to concat, like "127.0.0.1"
port: str for port, like "2379"
return: str like "127.0.0.1:2379"
return None if ip or port is None
"""
if ip is None or port is None:
return None
return ip.strip() + ":" + port.strip() | 6300064966bbafe549c42df4a8507c861ba5acad | 47,441 |
def split_function_name(fn):
"""
Given a method, return a tuple containing its fully-qualified
class name and the method name.
"""
qualname = fn.__qualname__
if '.' in qualname:
class_name, fn_name = qualname.rsplit('.', 1)
class_name = '%s.%s' % (fn.__module__, class_name)
e... | 0f525d93afdf72269da303c13b69cc8f29aa0661 | 47,442 |
import array
def toarr( data ):
"""Converts a string or byte array to a byte array.
"""
if isinstance( data, array.array ):
return data
else:
return array.array( 'B', data ) | 78c386c5efb124b6bc28d7e6980004076d4c220f | 47,443 |
import errno
def _GetUploadTrackerData(tracker_file_name, logger):
"""Reads tracker data from an upload tracker file if it exists.
Args:
tracker_file_name: Tracker file name for this upload.
logger: for outputting log messages.
Returns:
Serialization data if the tracker file already exists (resume... | ef769da5a2e27e5279e7519d622670cc5b7eaaf7 | 47,447 |
def names_from_results(response):
"""Returns card names from results as a list"""
return [x["name"] for x in response.json()["results"]] | c879b2cdb8f78150e50be3e115a5103992e93b79 | 47,450 |
import configparser
def _get_token(filename='token.cfg', key_ring='openweathermap'):
"""
read in API token
Parameters
----------
filename : str
local file with API token
key_ring : str
dictionary key, appearing within [] in token file
Returns
-------
str
A... | b5eabd3d222fa2cffae936e5fe38fa3cf312c30d | 47,454 |
def _fits_indexhdus(hdulist):
"""
Helper function for fits I/O.
Args:
hdulist: a list of hdus
Returns:
dictionary of table names
"""
tablenames = {}
for i in range(len(hdulist)):
try:
tablenames[hdulist[i].header['EXTNAME']] = i
except(KeyError):... | 031aed6610eacdaecc9215822746b7e70e083d92 | 47,455 |
from typing import List
import struct
def device_number_to_fields(device_number: int) -> List[int]:
"""
Splits the device number (16 bits) into two bytes
Example with device number 1000
Full bits: 0b0000001111101000
First 8 bits: 0b00000011 == 3
Last 8 bits: 0b11101000 == 232
T... | f22f277d9cb5ff8fadf6eaf15b5c8fb92e20b543 | 47,458 |
from typing import List
def is_using_stdin(paths: List[str]) -> bool:
"""Determine if we're going to read from stdin.
:param paths:
The paths that we're going to check.
:returns:
True if stdin (-) is in the path, otherwise False
"""
return "-" in paths | 9551c149dabdf1ca2ead2d74ed534f57fc5ea4ab | 47,459 |
def pass_quality_filter(s,cutoff):
"""
Check if sequence passes quality filter cutoff
Arguments:
s (str): sequence quality scores (PHRED+33)
cutoff (int): minimum quality value; all
quality scores must be equal to or greater
than this value for the filter to pass
Returns:
... | 781a5e3bea1ed20fc0f28fe16f6aa90a57d3372a | 47,460 |
def best_of_gen(population):
"""
Syntactic sugar to select the best individual in a population.
:param population: a list of individuals
:param context: optional `dict` of auxiliary state (ignored)
>>> from leap_ec.data import test_population
>>> print(best_of_gen(test_population))
[0 1 1 ... | b7efcb8d6a961843d88fe1864d129a1dc502ea33 | 47,461 |
import string
import random
def generatePRandomPW(pwlen=16, mix_case=1):
"""Generate a pseudo-random password.
Generate a pseudo-random password of given length, optionally
with mixed case. Warning: the randomness is not cryptographically
very strong.
"""
if mix_case:
cha... | bccc7b185f5e742d309a2e761a527c6b0bdccc6f | 47,463 |
def default_sum_all_losses(dataset_name, batch, loss_terms):
"""
Default loss is the sum of all loss terms
"""
sum_losses = 0.0
for name, loss_term in loss_terms.items():
loss = loss_term.get('loss')
if loss is not None:
# if the loss term doesn't contain a `loss` attribu... | d12eaa926ae5adbbb023acf316b9bf7854cdbd84 | 47,465 |
def _compute_segseg_intersection(segment1, segment2):
"""Algorithm to compute a segment to segment intersection.
Based on this article:
https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection
:param segment1: first segment (defined by two endpoints)
:type segment1: list
:param segment2... | e30f4227f499ce7eb3adab7674a46f2bdb05b0a5 | 47,466 |
def sortRemoveDupes(lst):
"""Sort the list, and remove duplicate symbols.
"""
if len(lst) == 0:
return lst
lst.sort()
lst = [lst[0]] + [lst[i] for i in range(1, len(lst))
if lst[i] != lst[i - 1]]
return lst | 8f50d6aeb706330302112064492761e97e2c1935 | 47,470 |
def mul_by_num(num):
"""
Returns a function that takes one argument and returns num
times that argument.
>>> x = mul_by_num(5)
>>> y = mul_by_num(2)
>>> x(3)
15
>>> y(-4)
-8
"""
def h(x):
return num * x
return h | 174859f0db6aabb0ece1bbd9b5a7fbe6e98b1253 | 47,471 |
import string
def remove_punctuation(input_string):
"""Return a str with punctuation chars stripped out"""
for element in input_string:
if element in string.punctuation:
input_string = input_string.replace(element, '')
return input_string | 2efb60ca06ba61ff45d2ad45f554b4a0fc971947 | 47,472 |
def get_node_set(g1,g2,method="union"):
"""
Returns the set of nodes that have to be considered in counting
transitions of the Markov chains. The input for the keyword
argument `method` controls the method used.
"""
if (method=="intersection"):
nodes = list(set(g1.nodes()) & set(g2.node... | ccecc822cc72eccaf7bc73f4b3512d8fa79519d6 | 47,477 |
def _clean_listlike(string: str) -> list:
"""Removes commas and semicolons from SQL list-like things. i,e id, number --> ['id', 'number'] """
cols = []
for item in string:
# Check if item is in list, or if user adds ; to the end of the query
if item[-1] == ',' or item[-1] == ';' or item[-1] ... | b7c92177982f7656a9d96d03ba6892e2d71056ac | 47,479 |
def to_seconds(hours, minutes, seconds):
"""Returns the amount of seconds in the given hours, minutes, and seconds."""
return hours*3600+minutes*60+seconds | bdfe64f2f261a70a4af8a63a2fb984c7b08127f1 | 47,489 |
import copy
def modify_tree_with_weights(tree, weights):
"""
Given an ete3 Tree object and a dictionary where keys are node names in the tree and values are multipliers (can
be generated with read_weights_file), returns a new tree where each branch in the weights dictionary is multiplied
by the multi... | 75da028d5f9fe8a55e94bd7b6074cc109ec2d79e | 47,495 |
def rotate_voxel(xmin, ymin, xmax, ymax):
"""
Given center position, rotate to the first quadrant
Parameters
----------
xmin: float
low point X position, mm
ymin: float
low point Y position, mm
xmax: float
high point X position, mm
ymax: float
... | 5291043c5cd8447d44c846953a68d11488ae60dd | 47,496 |
import attr
def attrib(*args, **kwargs):
"""Extend the attr.ib to include our metadata elements.
ATM we support additional keyword args which are then stored within
`metadata`:
- `doc` for documentation to describe the attribute (e.g. in --help)
Also, when the `default` argument of attr.ib is un... | bb7f48919a666eb362860f8fe965030d0fc8bc0e | 47,500 |
def pop(self, i):
"""
Remove the item at the given position in the list, and return it.
If no index is specified, a.pop() removes and returns the last item in the list.
"""
return self.list_output.pop(i) | b5c99ff7c0ec14fe39babd2a3e274a9355cffd38 | 47,501 |
import uuid
def new_aid() -> str:
"""Create a new, unique ari entry id."""
return uuid.uuid4().hex | d274c7616a525bda2062758622b3180f1a44b621 | 47,502 |
def are_all_0(lists, index):
"""Check if the values at the same index in different list are all to 0.
:param list lists: a list of lists to check the value in.
:param int index: the index of the values to check in the lists.
:returns: True if all the values at the index in the lists are set to 0, Fals... | 1fe4f8777618eed459907b2995170691be639e5b | 47,506 |
def modify(boxes, modifier_fns):
""" Modifies boxes according to the modifier functions.
Args:
boxes (dict or list): Dictionary containing box objects per image ``{"image_id": [box, box, ...], ...}`` or list of bounding boxes
modifier_fns (list): List of modifier functions that get applied
... | 386cb12b0b985a3702d0fe6a3dc7a38e712c7dc1 | 47,508 |
def remap_keys(key_func, d):
"""
Create a new dictionary by passing the keys from an old dictionary through a function.
"""
return dict((key_func(key), value) for key, value in d.items()) | be7125b7bab735522e684d766c75b4745a8c11b3 | 47,510 |
import re
def calculatedNormalisedDataForLines(lines):
""" Get normalised data for the lines of the file.
This function is intended as an example.
With the help of the function the velocity data of the file are normalized to the absolute value
of 1 to be able to measure the profile later wit... | adbde503fa0152da6ffcd7eaec985f21636d4f6e | 47,511 |
def is_time_invariant(ds):
"""Test if the dataset is time-invariant (has no time coordinate)
Args:
ds (xarray.Dataset or xarray.DataArray): Data
Return:
bool : True if no 'time' coordinate detected, False otherwise
"""
return 'time' not in list(ds.coords.keys()) | 06254dc660171f34f911ab4e99b9d14e7a789751 | 47,524 |
def merge_dict(d1, d2):
"""Merge two dictionaries, i.e. {**d1, **d2} in Python 3.5 onwards."""
d12 = d1.copy()
d12.update(d2)
return d12 | 26c1e1700873c40bec46f5513c7eb5dbc0595325 | 47,526 |
def crystal_search(crystals, histogram_type):
"""Creating a dictionary of values list divided into centering
types for a given histogram type.
Parameters
----------
crystals : list
A list of crystal.
histogram_type : unicode str (on py3)
Type of histogram e.g. 'a', 'gamma'.... | 406ff81a3865a594e43cb95e5e92330617af48df | 47,531 |
def mean(ls):
"""
Takes a list and returns the mean.
"""
return float(sum(ls))/len(ls) | 213632c6b905317175dbecbbf4f175392451af2e | 47,532 |
def is_iscsi_uid(uid):
"""Validate the iSCSI initiator format.
:param uid: format like iqn.yyyy-mm.naming-authority:unique
"""
return uid.startswith('iqn') | 8670c7970e1ee5e077de3de02f2fb754fa4352aa | 47,533 |
from typing import cast
from typing import Iterable
import itertools
def _test_for_equality_nestedly_and_block_implicit_bool_conversion(
o1: object, o2: object
) -> bool:
"""test objects, or sequences, for equality. sequences are tested recursively. Block
implicit conversion of values to bools.
>>> ... | 351fb24ec20f8967559ecfff54d1608213c04f8b | 47,539 |
def _get_duration_in_seconds(selected_duration):
"""
Converts hours/minutes to seconds
Args:
selected_duration (string): String with number followed by unit
(e.g. 3 hours, 2 minutes)
Returns:
int: duration in seconds
"""
num_time, num_unit = selected_duration.split(' ')... | 0f17f3f4ed678dfb9fdf0d4ed819cb2308311981 | 47,541 |
def check_sentence_quality(left_match_right):
"""
Take a tuple with the left and right side of the matched word
and check a few conditions to determine whether it's a good example or not
Args:
left_match_right (tuple): a tuple of three strings: the left side
of the NKJP match, the m... | 7a50e860d251e2f2ed2fd1f1c7e7ea406a7a4043 | 47,543 |
def toggle_legend_collapse(_, is_open):
"""Open or close legend view.
:param _: Toggle legend btn was clicked
:param is_open: Current visibility of legend
:return: New visbility for legend; opposite of ``is_open``
:rtype: bool
"""
return not is_open | 50aeccdeb79dde4a6941a94cdd05ee77494cd1b9 | 47,546 |
def multiples(m, n):
"""
Builds a list of the first m multiples of the real number n.
:param m: an positive integer value.
:param n: an real integer number.
:return: an array of the first m multiples of the real number n.
"""
return [n * x for x in range(1, m + 1)] | 3a182d95dafa1d56ce120ff1d04f108f9d9c5e37 | 47,547 |
import re
def get_version_string(init_file):
"""
Read __version__ string for an init file.
"""
with open(init_file, 'r') as fp:
content = fp.read()
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
content, re.M)
if version_matc... | 22a9faa0d6686106de7d5cb736762859cc9c483a | 47,549 |
import re
def compute(sample: str, substr: str) -> list[int]:
"""
Given two strings s and t, t is a substring of s if t is contained as a contiguous collection of symbols in s (as a result, t must be no longer than s). The position of a symbol in a string is the total number of symbols found to its left, incl... | ed3a157fa74e953e56d2ed1d13e0b757da23c135 | 47,552 |
def block_combine(arr, nrows, ncols):
"""Combine a list of blocks (m * n) into nrows * ncols 2D matrix.
Arguments:
arr {3D np.array} -- A list of blocks in the format:
arr[# of block][block row size][block column size]
nrows {int} -- The target row size after combination.
nc... | e6330606ea63eb16faee305d646b60b8327785ac | 47,557 |
import math
def get_interactions_stats(S_edgelist, embedding, target_adjacency):
""" Interactions are edges between chains that are connected in
the source adjacency.
Args:
S (iterable):
An iterable of label pairs representing the edges in the source graph.
embedding (dict):
... | 69b6f818b25a2cb164cf3e2d6f24a80fc7a73efc | 47,568 |
def fklist(self, kpoi="", lab="", **kwargs):
"""Lists the forces at keypoints.
APDL Command: FKLIST
Parameters
----------
kpoi
List forces at this keypoint. If ALL (default), list for all
selected keypoints [KSEL]. If KPOI = P, graphical picking is
enabled and all remaini... | dfcb4547520d8840763ba11fd4f993ffee70279d | 47,570 |
def taken(diff):
"""Convert a time diff to total number of microseconds"""
microseconds = diff.seconds * 1_000 + diff.microseconds
return abs(diff.days * 24 * 60 * 60 * 1_000 + microseconds) | 64e8022bb0a80fcccc1a755fffb79121e61cad17 | 47,571 |
from typing import List
from typing import Counter
def remove_rare(sentences: List[List[str]]) -> List[List[str]]:
"""
Remove rare words (those that appear at most once) from sentences.
Parameters
----------
sentences:
List of tokenized sentences.
"""
counts: Counter = Counter()
... | 1af60b7bb0393abf99db02abf6f4fea9d9529c15 | 47,572 |
def _general_direction(model_rxn1, model_rxn2):
"""
picks the more general of the two directions from reactions passed in
"""
r1d = model_rxn1.get_direction()
r2d = model_rxn2.get_direction()
if r1d == r2d:
return r1d
else:
return '<=>' | 362ee4a6f033323328f869ef6e5650cc9fef9fa3 | 47,574 |
def read_table(filename, usecols=(0, 1), sep='\t', comment='#', encoding='utf-8', skip=0):
"""Parse data files from the data directory
Parameters
----------
filename: string
Full path to file
usecols: list, default [0, 1]
A list of two elements representing the columns to be parsed... | 81e70a1db8530940d73cf8242b791c3cab473b9c | 47,585 |
import time
def time_it(func, *args, **kwargs):
"""Benchmarks a given function."""
start = time.time()
res = func(*args, **kwargs)
print(f'{func.__name__} t: {time.time() - start:.{8}f} s')
return res | 07023c77f29ca03171ac8f725e41212f605bcdaf | 47,586 |
def define_limit_offset(request):
""" Define limit and offset variables from request.args """
if request.args:
try:
limit = int(request.args['limit'])
offset = int(request.args['offset'])
except:
# Default limit and offset
limit = 12
offset = 0
else:
# Default limit and offset
limit = 12
of... | 31ef7fbc70ec67c0d646024c580b591238cfecbf | 47,591 |
def _dot(fqdn):
"""
Append a dot to a fully qualified domain name.
DNS and Designate expect FQDNs to end with a dot, but human's conventionally don't do that.
"""
return '{0}.'.format(fqdn) | 53ee7c41dab6b88523a68fd1ee387031c0314eb1 | 47,594 |
def intersect1D(min1, max1, min2, max2):
"""
Return the overlapping state on a 1 dimensional level.
:param int/float min1:
:param int/float max1:
:param int/float min2:
:param int/float max2:
:return: Overlapping state
:rtype: bool
"""
return min1 < max2 and min2 < max1 | 2ad6b9926614b3785aab2a28ee2afb088170d2b9 | 47,597 |
def add(g, start, end):
"""
Add edge information into g
@type: g, graph (2D array)
@param: g, adjacency list
@type: start, integer
@param: start, start vertex point for edge
@type: end, integer
@param: end, end vertex point for edge
"""
g[start].append(end)
g[end].append(start)
return g | 30032f20717034dce57b1e5adfb09e45ce2614be | 47,601 |
def file_size(file, unit):
"""
Convert the size from bytes to other units like KB, MB or GB
Adapted from:
https://thispointer.com/python-get-file-size-in-kb-mb-or-gb-human-readable-format/
"""
base = 1024
if unit == 'KB':
size = file.size/base
elif unit == 'MB':
size =... | cab5c01470489c126470c0c5179bb3da8d30072b | 47,602 |
def read_mappings_from_dict(index_mapping):
"""
Read event_class and event_type mappings from a python dict.
"""
evclass = [[], [], []]
evtype = [[], [], []]
for v in index_mapping['classes']:
evclass[0].append(v[0])
evclass[1].append(v[1])
evclass[2].append(v[2])
fo... | cdf2706fed3cdf5786cc238e090401eeae99a8c2 | 47,608 |
import torch
def top_p_filter(
logits: torch.Tensor,
top_p: float,
min_tokens_to_keep: int,
is_probs: bool = False
) -> torch.Tensor:
"""Helper function for nucleus sampling decoding, aka. top-p decoding.
:param logits:
:param top_p:
:param min_tokens_to_keep:
:param is_probs:
... | 7e54e5cc87afa4eb90ca7316e48b947f9647f210 | 47,610 |
def table_to_report(table, measure):
"""Return a report by taking arguments table and measure.
Args:
table: an instance generated by c.fetchall(). table is a list of tuples
and each tuple has only two values.
measure: a unit of measure in string format.
Returns:
A report in... | e3417b159cd7b826c856697d48c34aecd1a81719 | 47,612 |
def has_code(line: str) -> bool:
"""
Return True if there's code on the line
(so it's not a comment or an empty line).
"""
return not line.strip().startswith("#") or (line.strip() == "") | ef0975ee21deda1206a1bfc728f47d1119132c70 | 47,614 |
def PairsFromGroups(groups):
"""Returns dict such that d[(i,j)] exists iff i and j share a group.
groups must be a sequence of sequences, e.g a list of strings.
"""
result = {}
for group in groups:
for i in group:
for j in group:
result[(i, j)] = None
return ... | f449612579e54e1365da459d936e633f38d0ceac | 47,615 |
def set_focus_on_entry(entry):
"""sets focus on a given entry"""
entry.focus()
return "break" | 91657ec5613a95f11965f495b38248ca2ef9e23f | 47,617 |
def _version_to_tuple(version):
"""Converts the version string ``major.minor`` to ``(major, minor)`` int tuple."""
major, minor = version.split('.')
return (int(major), int(minor)) | 921a3855fd23a597f13dab27f660cf4b0113926b | 47,620 |
def parseExtn(extn=None):
"""
Parse a string representing a qualified fits extension name as in the
output of `parseFilename` and return a tuple ``(str(extname),
int(extver))``, which can be passed to `astropy.io.fits` functions using
the 'ext' kw.
Default return is the first extension in a fit... | ddbc2c3e16161431ce458eb2ff441ab8a21145ee | 47,622 |
def _report_body(*, image: str, repo: str, run: str, stacktrace: str) -> str:
"""Format the error report."""
return (
f"Repo: {repo}\n"
f"Run URL: {run}\n"
f"Image ID: {image}\n"
f"Stacktrace:\n```py\n{stacktrace}\n```\n"
) | a81ea924078f0225aba3ab441aef42c3393118cb | 47,637 |
import importlib
import time
def time_algo(call_string, module_name):
"""
Times the execution of a python call string.
:param call_string: str string that calls a python module and executes an
algorithm
:param module_name: str name of module from which function is called
:return run_time: floa... | f24e708c04a765487b3c009b7ef5f9929e4c885b | 47,638 |
def compute_columns(n_items, n_rows):
"""Compute the required number of columns given a number of items
n_items to be displayed in a grid n_rows x n_cols"""
if n_rows > n_items:
return n_items, 1
d = n_items // n_rows
n_cols = d + (1 if n_items % n_rows else 0)
return n_rows, n_cols | dbc4a87d0d335055ea8f8b6115289b94cb15a655 | 47,640 |
def resolve_from_path(path):
"""Resolve a module or object from a path of the form x.y.z."""
modname, field = path.rsplit(".", 1)
mod = __import__(modname, fromlist=[field])
return getattr(mod, field) | fffda7518a78c72a441547116f2b33ed459adb05 | 47,642 |
import math
def svo_angle(mean_allocation_self, mean_allocation_other):
"""
Calculate a person's social value orientation angle (based on the slider measure).
params: A mean allocation to self and a mean allocation to other, based on the six primary items of the SVO slider
returns: The person's socia... | 0b3f39309c44d6e3fee893debb54ef00786d321e | 47,643 |
def get_hosts(path, url):
"""
Creates windows host file config data
:param path:
:param url:
:return: string
"""
info = """
# host for %%path%%
127.0.0.1\t%%url%%
""".replace("%%url%%", url).replace("%%path%%", path)
return info | 5e606c6dd36706f5c0fe1e492143231c4bd229ee | 47,648 |
def _normalized_import_cycle(cycle_as_list, sort_candidates):
"""Given an import cycle specified as a list, return a normalized form.
You represent a cycle as a list like so: [A, B, C, A]. This is
equivalent to [B, C, A, B]: they're both the same cycle. But they
don't look the same to python `==`. S... | 328046069999c8f3f960cc526b277a21c7daab5d | 47,650 |
def expand_features_and_labels(x_feat, y_labels):
"""
Take features and labels and expand them into labelled examples for the
model.
"""
x_expanded = []
y_expanded = []
for x, y in zip(x_feat, y_labels):
for segment in x:
x_expanded.append(segment)
y_expanded.... | 5cd5dbe18285fdcbc633809cd95dde17e32dd82b | 47,651 |
def add_extension(file_name, ext='py'):
"""
adds an extension name to the file_name.
:param file_name: <str> the file name to check for extension.
:param ext: <str> add this extension to the file name.
:return: <str> file name with valid extension.
"""
if not file_name.endswith(ext):
... | 123a8a01c70cd3bf98f189c9582796fcdfa97ee3 | 47,654 |
def get_url_with_query_params(request, location, **kwargs):
"""
Returns link to given location with query params.
Usage:
get_url_with_query_params(request, location, query_param1=value1, query_param2=value2)
returns:
http(s)://host/location/?query_param1=value1&query_param2=value2&...
"""
... | 350003c0c86ff80db5f70ba16de6d86edadbf6e4 | 47,659 |
def is_hex_digit(char):
"""Checks whether char is hexadecimal digit"""
return '0' <= char <= '9' or 'a' <= char <= 'f' | 172ae4a57bd77e7e33237bec77831417e961babd | 47,660 |
def subtracttime(d1, d2):
"""Return the difference in two dates in seconds"""
dt = max(d1, d2) - min(d1, d2)
return 86400 * dt.days + dt.seconds | bae7668ef9b593c7ebe072d789e1b298f81cda3e | 47,667 |
def removeWords(answer):
"""Removes specific words from input or answer, to allow for more leniency."""
words = [' town', ' city', ' island', ' badge', 'professor ', 'team ']
answer = answer.lower()
for word in words:
answer = answer.replace(word, '')
return answer | 088debb26571dc31415591e5026972b057987229 | 47,671 |
def _adjust_n_months(other_day, n, reference_day):
"""Adjust the number of times a monthly offset is applied based
on the day of a given date, and the reference day provided.
"""
if n > 0 and other_day < reference_day:
n = n - 1
elif n <= 0 and other_day > reference_day:
n = n + 1
... | e7a46f8923fb57985e3f32a1130f34e703a58627 | 47,674 |
def mcf_to_boe(mcf=0, conversion_factor=6):
"""Converts mcf to barrels of oil equivalent using the standard 6 mcf/boe conversion factor."""
return (mcf/conversion_factor) | e7f7b984ec0e537512cf2b926c72c25c83a3507b | 47,675 |
def check_won (grid):
"""return True if a value>=32 is found in the grid; otherwise False"""
for i in range(4):
for j in range(4):
if grid[i][j] >= 32:
return True
return False | f93751aa8073bc3e1b3965bd598a17f0c98da967 | 47,680 |
import re
def any_char_matches(substring: str, mainString: str):
"""Scans the string for any matches a certain pattern.
Parameters
----------
substring : str
The string that is used to find matches from `mainString`.
mainString : str
The `mainstring` which contains the original s... | b0db76f9f7ed34cd45ba118c758944afbb7b0090 | 47,681 |
def getDens(mCM):
"""
return density based on type(mCM['dens'])
mCM['dens'] can be a number or a function
Parameters:
mCM, multi-component material dictionary - see init
"""
if type(mCM['dens']) in [float, int]:
dens = mCM['dens']
else:
dens = mCM['dens'](mCM)
... | 60e6baa70f5c6cd90cf4578bd9f348e947d18979 | 47,683 |
def parse_sqlplus_arg(database):
"""Parses an sqlplus connection string (user/passwd@host) unpacking the user, password and host.
:param database: sqlplus-like connection string
:return: (?user, ?password, ?host)
:raises: ValueError
when database is not of the form <user>/<?password>@<host>
... | 51bb3304458d4b3d3a69c694b13066e1d713a272 | 47,685 |
def is_palindrome(input_string):
"""
Checks if a string is a palindrome.
:param input_string: str, any string
:return: boolean, True if palindrome else False
>>> is_palindrome("madam")
True
>>> is_palindrome("aabb")
False
>>> is_palindrome("race car")
False
>>> is_palindrom... | 165df98dd983a2d84ad30bafbb70168d9599bd8d | 47,687 |
import codecs
import base64
def convert_r_hash_hex(r_hash_hex):
""" convert_r_hash_hex
>>> convert_r_hash_hex("f9e328f584da6488e425a71c95be8b614a1cc1ad2aedc8153813dfff469c9584")
'+eMo9YTaZIjkJacclb6LYUocwa0q7cgVOBPf/0aclYQ='
"""
r_hash = codecs.decode(r_hash_hex, 'hex')
r_hash_b64_bytes = ba... | 8980e43ff4f30e69e9cfc0ed7427f787ea97d701 | 47,688 |
import re
def contains_curse(sometext):
"""
Checks a particular string to see if it contains any
NSFW type words. curse words, things innapropriate
that you might find in lyrics or quotes
:param sometext: some text
:type sometext: Str
:returns: a boolean stating whether we have a curse word or not
:rtype:... | e979fec6ba2cd88191dde304445416129a7f5049 | 47,690 |
def drop_id_prefixes(item):
"""Rename keys ending in 'id', to just be 'id' for nested dicts.
"""
if isinstance(item, list):
return [drop_id_prefixes(i) for i in item]
if isinstance(item, dict):
return {
'id' if k.endswith('id') else k: drop_id_prefixes(v)
for k, v... | 6fc752fa49771a0fc6e7e28e889cf29941a95a10 | 47,696 |
def getDescendantsTopToBottom(node, **kwargs):
"""
Return a list of all the descendants of a node,
in hierarchical order, from top to bottom.
Args:
node (PyNode): A dag node with children
**kwargs: Kwargs given to the listRelatives command
"""
return reversed(node.listRelatives(... | bc7a7fb1ca1ab362943f024c3dd50ce40cfc0ab5 | 47,701 |
import string
import random
def random_string_generator(size=4, chars=string.ascii_lowercase + string.digits):
"""[Generates random string]
Args:
size (int, optional): [size of string to generate]. Defaults to 4.
chars ([str], optional): [characters to use]. Defaults to string.ascii_lowercase... | 617e20acd54f218f65f98d89b976efc1bebc095a | 47,703 |
import torch
def cross_entropy(targ, pred):
"""
Take the cross-entropy between predicted and target.
Args:
targ (torch.Tensor): target
pred (torch.Tensor): prediction
Returns:
diff (torch.Tensor): cross-entropy.
"""
targ = targ.to(torch.float)
fn = torch.nn.BCELoss... | 22f06a7caf58710208131620bbc773d968e3f910 | 47,705 |
import torch
def tilted_loss(y_pred, y, q=0.5):
"""
Loss function used to obtain quantile `q`.
Parameters:
- y_pred: Predicted Value
- y: Target
- q: Quantile
"""
e = (y - y_pred)
return q * torch.clamp_min(e, 0) + (1-q) * torch.clamp_min(-e, 0) | f43ebdee74ebe10776685634859628222a9bc9ce | 47,712 |
def generate_panel_arrays(nx, ny, panel_size, indentation, offset_x, offset_y):
"""Generate a rectangular array of nx-by-ny panels of the same panel_size
nx, ny: int, how many panels do you want in X-axis and Y-axis.
panel_size: (int, int), dimension of the panels
offset_x, offset_y: int, move around... | 4613b6d038856aca927f33b1bf60e8a3f6449406 | 47,713 |
def data_to_category_counts(df):
"""
Extracts opportunity category counts for each NAICS code.
"""
return (
df.groupby(['Opportunity_NAICS', 'Opportunity__r.Category__c'])
.count()
.iloc[:,0]
.to_frame()
.rename(columns={df.columns[0]: 'Count'})
.reset_ind... | fa57218d5a6f439789cb7e013892df09c8207a07 | 47,714 |
import re
def resolve_query_res(query):
"""
Extracts resource name from ``query`` string.
"""
# split by '(' for queries with arguments
# split by '{' for queries without arguments
# rather full query than empty resource name
return re.split('[({]', query, 1)[0].strip() or query | 9f5395c8dd416643c5d8460e0fbec2f83037e4fb | 47,717 |
def calculate_plane_point(plane, point):
"""Calculates the point on the 3D plane for a point with one value missing
:param plane: Coefficients of the plane equation (a, b, c, d)
:param point: 3D point with one value missing (e.g. [None, 1.0, 1.0])
:return: Valid point on the plane
"""
a, b, c,... | c086e5181a9d595af5a0ef493a221f2166e71423 | 47,718 |
def revert(vocab, indices):
"""Convert word indices into words
"""
return [vocab.get(i, 'X') for i in indices] | 457831d28d26c68b19a07585f0d4de9fe31b0203 | 47,720 |
def getSnpIndicesWithinGeneWindow(snp_chrom,snp_pos,gene_chrom,gene_start,gene_stop=None,window=0):
"""
computes for a given gene, a boolean vector indicating which SNPs are close to the gene
input:
snp_chrom : chromosomal position [F]
snp_pos : position [F]
gene_chrom : gene... | 1a87e20b8744c9d28e26bd189f7bdaa056238a2b | 47,722 |
import math
def scalarToVector(magnitude, angle):
"""
Converts a speed and vector into a vector array [x, y, z]
X is horizontal magnitude, Y is vertical magnitude, and Z is magnitude in/out of screen
arg magnitude - the magnitude of the vector
arg angle - the direction in radians of the vector
Returns an ar... | 4d82caed233a3b4df07ff42536fcffa8643e94bf | 47,724 |
from typing import Counter
def term_freq(tokens: list[str]) -> dict:
"""
Takes in a list of tokens (str) and return a dictionary of term frequency of each token
"""
term_count = Counter(tokens)
n = len(tokens)
return {term: count/n for term, count in term_count.items()} | 0567a08e9050d030b8411f662e4afb8560e525be | 47,736 |
def stag_temperature_ratio(M, gamma):
"""Stagnation temperature / static temperature ratio.
Arguments:
M (scalar): Mach number [units: dimensionless].
gamma (scalar): Heat capacity ratio [units: dimensionless].
Returns:
scalar: the stagnation temperature ratio :math:`T_0 / T` [unit... | 0677524c97a245d93f9eac33c6be885819ed14e5 | 47,742 |
def get_max_depth(es, *, index):
"""Find max depth of root lineage."""
body = {
"id": "max_nested_value",
"params": {"path": "lineage", "field": "node_depth"},
}
res = es.search_template(index=index, body=body)
max_depth = res["aggregations"]["depths"]["max_depth"]["value"]
retur... | 33eb318bcf20fb656b84edb349ff840ebefe07b0 | 47,743 |
def compute_gender(last_gender: str,
top_gender_male: int,
top_gender_female: int,
top_gender_7_days: str):
"""Computes the gender type of a visitor using a majority voting rule."""
def majority_voting(lst):
return max(set(lst), key=lst.count)
... | 387f04fae4b593de54894eeac017b7fe124706c9 | 47,744 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.