content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import re
def split_lines(source):
"""
Split selection lines in a version-agnostic way.
Python grammar only treats \r, \n, and \r\n as newlines.
But splitlines() in Python 3 has a much larger list: for example, it also includes \v, \f.
As such, this function will split lines across all Python ver... | df88d55a716a2050e30cdb75701f640ce18a8c99 | 115,551 |
def ema(df, window, targetcol='weightedAverage', colname='ema', **kwargs):
""" Calculates Expodential Moving Average on a 'targetcol' in a pandas
dataframe """
df[colname] = df[targetcol].ewm(
span=window,
min_periods=kwargs.get('min_periods', 1),
adjust=kwargs.get('adjust', True),
... | 20b1778d7aa947fd86d15f7669274721554bf186 | 115,554 |
def filter_fiona_metadata(dct):
"""Include only valid Fiona keywords for opening a feature collection"""
valid_keys = {"crs", "driver", "schema", "layer", "vfs"}
return {k: v for k, v in dct.items() if k in valid_keys} | af13aa61373e20edd023ebcf4b0987184ae868ee | 115,555 |
import json
def backup_luks2_token(module, device, token_id):
"""Backup LUKS2 token, as we may need to restore the metadata.
Return: <backup> <error>"""
args = ["cryptsetup", "token", "export", "--token-id", token_id, device]
ret, token, err = module.run_command(args)
if ret != 0:
return ... | b22fe828b8b6cbfd8befcfb64bcefc7fd7890588 | 115,561 |
def _geny(xx, func):
"""
Generates an array containing y-values corresponding to given x-coordinates
by using a function y = f(x).
Args:
xx (1darray): Array containing the x-values for which matching
y-values shall be computed.
func (callable object): The function used to ge... | 5de5ee7a83b76f51d85573099d710b06610e8c8e | 115,564 |
def isbool(s):
"""
Checks whether the string ``s`` represents a boolean.
The string requires Python capitalization (e.g. 'True', not 'true').
:param s: the candidate string to test
:type s: ``str``
:return: True if s is the string representation of a boolean
:rtype: ``bool``... | 678ff8b287ca6a83df933c9e96f5b01609b5d0ef | 115,566 |
from typing import Dict
from typing import Any
def is_compatible(assignment1: Dict[str, Any], assignment2: Dict[str, Any]):
"""
Check if two (potentially partial) assignments are compatible.
Compatible means that there is no disagreement on variable assignment.
:param assignment1: a dict var ->val
... | 80f366fa594b740e15062606cb3a2a5a63ad1933 | 115,570 |
def SetFieldValue(regValue, lsb, fsize, fieldValue):
"""
An internal utility function to assign a field value to a register value.
Perform range check on fieldValue using fsize.
:type regValue: ``int`` or ``long``
:param regValue: The value of the register to parse
:type lsb: ``int``
:par... | bedca3c707fd3600ec1e5e85fc12acdaaf6590fa | 115,571 |
import re
def clean_regex_string(s: str) -> str:
"""Converts regex string pattern for a path into OpenAPI format.
Example::
>>s = '^toy\\/^(?P<toyId>[a-zA-Z0-9-_]+)\\/details'
>>clean_regex_string(s)
'toy/{toyId}/details'
"""
s = s.replace("^", "").replace("\\", "")
rege... | d002992d7743d6a51b3b577f6a8c0a3656d6058f | 115,573 |
def check_nulls(df):
"""
Takes a data frame and returns a sorted list of the number
of null values each column has.
"""
return(df.isnull().sum().sort_values()) | bb6d718f45d0812292b2b09d5db520a657ccc494 | 115,575 |
import mimetypes
def get_mimetype(url):
"""
Guess based on the file extension.
Args:
url (text): Web url that was linked to by a reddit submission.
Returns:
modified_url (text): The url (or filename) that will be used when
constructing the command to run.
content_... | 3e46df184eedf03fabf95b0aa04ac6fc135af5cc | 115,582 |
import random
def generate_chunks(total, min_val, max_val, num_chunks=-1):
"""
Randomly generate a list of integers l such that sum(l) = total and for each x in l, min_val <= x <= max_val.
If num_chunks > 0, it is guaranteed that the list contains exactly num_chunks elements.
"""
if num_chunks <=... | a76c2f206801b339b203197249bc969cf91c7caa | 115,584 |
from typing import Union
from typing import List
import torch
from typing import Tuple
def exact_match_rate(
real_start: Union[List[List[torch.Tensor]], torch.Tensor],
real_end: Union[List[List[torch.Tensor]], torch.Tensor],
pred_start: torch.Tensor,
pred_end: torch.Tensor
) -> Tuple[i... | f916bbb1abf02a2ac36754740ff80c4793cce298 | 115,587 |
def allowed_file(filename):
"""Returns `True` if file extension is `.tar`"""
return '.' in filename and filename.rsplit('.', 1)[1] in ['tar'] | 7fc0b68130cd05aa29976f0692217e3fc6a04269 | 115,590 |
import colorsys
def get_hue(image):
"""Return the most common hue of the image."""
hues = [0 for x in range(256)]
# Iterate each pixel. Count each hue value in `hues`.
for pixel in image.getdata():
# Ignore greyscale pixels.
if pixel[0] == pixel[1] and pixel[1] == pixel[2]:
... | e4420bcdb5a6e13b784fb3d2d290206cb9183f47 | 115,591 |
def split(s, delimiter=','):
"""Split a string on given delimiter or newlines and return the results stripped of
whitespace"""
return [
item.strip() for item in s.replace(delimiter, '\n').splitlines() if item.strip()
] | 2a3b60488a6c2ef78aa3ff60b8365408b5cf7cd7 | 115,593 |
import pickle
def stop_idx_in_route(stop_times_file, FOLDER):
"""
This function saves a dictionary to provide easy access to index of a stop in a route.
Args:
stop_times_file (pandas.dataframe): stop_times.txt file in GTFS.
FOLDER (str): path to network folder.
Returns:
idx_by_... | ae2ee28f1035024a410829f96c1ee5fc5dc71245 | 115,595 |
def find_key_in_list(key, key_list):
"""
Look for the right corresponding key in a list.
key has to start with an given key from the list and the longest key
will be returned.
Parameters
----------
key : str
Given key.
key_list : list of str
Valid keys to be checked aga... | a0d921ea3d2ff1acf7df1fe6bdf22c4ca8ea9188 | 115,605 |
def get_suffix_base64(raw_base64):
"""
get suffix and base code
:param raw_base64: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA
:return: png, iVBORw0KGgoAAAANSUhEUgAA
"""
parts = raw_base64.split(',', 1)
code = parts[1]
splits = parts[0].split(';')[0].split('data:')[1].split('/')
s... | 2bcd1ed74c5f0c66d525d6d66647ed99a77ea1ee | 115,610 |
from typing import List
def make_squares(arr: List[int]) -> List[int]:
"""
Time Complexity: O(len(arr))
Space Complexity: O(len(arr))
:param arr: input array
:return: new array containing squares of all the number of the input array in the sorted order
"""
n = len(arr)
p1 = 0
p2 =... | d987e55ea93700fea64dd1ca92b752d611b0ce7b | 115,614 |
def read_taxonomies_to_design_for(fn):
"""Read different taxonomies to design for.
The columns must be, in order:
1) a taxonomic (e.g., species) ID from NCBI
2) a segment label, or 'None' if unsegmented
Args:
fn: path to TSV file, where each row corresponds to a taxonomy
Retur... | a2f170c820c5ad95149e27d7907886cd264aee70 | 115,616 |
import re
def identify_hypers(df_fit):
"""Identify hyperparameters.
Arguments:
df_fit: A pd.DataFrame of model fit data.
Returns:
hypers: A list of strings.
"""
hypers = []
for col_name in list(df_fit.columns):
if re.match(r'hyp_*.', col_name):
hypers.app... | 82e0334d6c20ecb6a1cddadae112b2ef1fcaf7cc | 115,618 |
import binascii
def _pack_mac(mac_address):
"""Pack a mac_address into binary."""
return binascii.unhexlify(mac_address.replace(':', '')) | 40e9edfdb9a134c95a333bd3ece8af5671c6454b | 115,619 |
from datetime import datetime
def monthlyVector(startyr,endyr,startmth,endmth):
"""
Returns two datetime vectors with start and end dates at the start and end of months
"""
month=[]
year=[]
m0 = startmth
y0 = startyr
while m0 <= endmth or y0 <= endyr:
month.append(m0)
... | 935a4d4532aa3714eef6d1be1093d96656c05e19 | 115,620 |
from typing import List
def make_low_rcp_list(predicted_temps_dict: dict) -> List[float]:
"""Return a list of RCP 2.6 temperature values
"""
low_rcp_list = []
for year in list(predicted_temps_dict.keys()):
low_rcp_list.append(predicted_temps_dict[year]['RCP 2.6'])
return low_rcp_list | 9726fb085547bad71dfe9a111bc019757179756c | 115,621 |
def is_dunder(val: str) -> bool:
"""Returns True if a __dunder__ name, False otherwise."""
return (len(val) > 4 and
val[:2] == val[-2:] == '__' and
val[2] != '_' and
val[-3] != '_') | f285412ed90c4d338b7984b089f2d74ad44820f4 | 115,624 |
import tempfile
def build_ansible_inventory(config=None, fw_ip=None):
"""
Build a basic ini-style Ansible inventory file.
Parameters:
config (dict): Optional dictionary representing the current configuration file (used in production mode).
fw_ip (string): Optional firewall IP address (use... | 6d4c66cb21a39368d6610473d27eca241a22f9db | 115,626 |
import re
def replace(s, pattern, replacement):
"""Replaces occurrences of a match string in a given
string and returns the new string. The match string
can be a regex expression.
Args:
s (str): the string to modify
pattern (str): the search expression
replacemen... | 1bde773ebdc49c3c5541c7706959c3024ae20a98 | 115,627 |
def populate_table(conn, sql, rows):
""" insert multiple rows of data into a table
:param conn: Connection object
:param sql: INSERT INTO statement
:param rows: the data as a list of rows
:return: lastrowid
"""
cur = conn.cursor()
cur.executemany(sql, rows)
conn.commit()
return c... | 7e2caa7965d46c3ec95ce4354b5766d4a0f36c10 | 115,628 |
def is_solved(neighbours, colors):
"""Checks for all countries, if all their neighbours have another color.
:param neighbours: A dict with country as keys, list of neighbours as values
:param colors: A list indicating which country has which color. First element in this list corresponds
to color of fir... | a1f610e9a03efc10de858e96e4f67f04ad0de0ea | 115,630 |
async def is_record(value):
"""
Checks whether a value is a Record ID or a list of Record IDs
Args:
value (``obj``): any value retrieved from an airtable record field.
Returns:
(``bool``): True if value is Record ID or a list of Record IDs
"""
if isinstance(value, list) and valu... | 7834dd6613e54d845bbf085763b238e15e40dc15 | 115,633 |
def TransToRp(T):
"""Converts a homogeneous transformation matrix into a rotation matrix
and position vector
:param T: A homogeneous transformation matrix
:return R: The corresponding rotation matrix,
:return p: The corresponding position vector.
Example Input:
T = np.array([[1, 0, 0, 0... | 9a0c1682c4f65f1367a59b955a6b3c0d813a1303 | 115,636 |
def host_available(compute_host):
""":returns: `True` if compute host is enabled in nova, `False`
otherwise"""
return compute_host.state == 'up' and compute_host.status == 'enabled' | 0ec053887a0e3b67c53c634c5e93babf12677c47 | 115,637 |
def recurPower(base, exp):
"""
base: int or float.
exp: int >= 0
returns: int or float, base^exp
"""
if exp == 0:
return 1
else:
return base * recurPower(base, exp-1) | d40bb0230889414e7567eccf5d89086bc81894fb | 115,640 |
import base64
def b64_decode(data):
"""Decodes standard unpadded base64 encoded string."""
mod = len(data) % 4
if mod:
data += '=' * (4 - mod)
return base64.b64decode(data) | c5ae3a782f005cd72c62358903e8bdbfc45215cc | 115,642 |
import json
def load_features(features_path):
"""
Reading the features from disk.
:param features_path: Location of feature JSON.
:return features: Feature hash table.
"""
features = json.load(open(features_path))
features = {str(k): [str(val) for val in v] for k,v in features.items()}
... | 122aaa5e16e3165b4c3a7937bba9d73e55ac918a | 115,645 |
import math
def factor(n):
"""Simple factorization function. Makes sure to only try each number once."""
factors = []
for i in range(2, int(math.sqrt(n)) + 1):
if i not in factors and not n % i:
factors.append(i)
factors.append(n / i)
return factors | 42f4942d2dd2c340e2b1f6f315267aec7e693ea6 | 115,646 |
import torch
import math
def bucket_values(
distances: torch.Tensor, num_identity_buckets: int = 4, num_total_buckets: int = 10
) -> torch.Tensor:
"""
Places the given values (designed for distances) into `num_total_buckets`semi-logscale
buckets, with `num_identity_buckets` of these capturing single v... | fc445c7ffbb8f058adbf3dd5ad22e5586975f8e4 | 115,667 |
def _indexing(x, indices):
"""
:param x: array from which indices has to be fetched
:param indices: indices to be fetched
:return: sub-array from given array and indices
"""
# np array indexing
if hasattr(x, 'shape'):
return x[indices]
# list indexing
return [x[idx] for... | 8061aee1464ffef0bc13eab0c59b472fd5dc140c | 115,670 |
def strtime(time):
"""Takes a number of seconds; returns a formatted duration string"""
years, days, hours, mins = 0, 0, 0, 0
timestr = ""
if time > 31536000:
years = int(time / 31536000)
time = time - (31536000 * years)
if time > 86400:
days = int(time / 86400)
time ... | b1444f1dc1ade84917a0536ed5a6f4691d2e3cfa | 115,674 |
def gen(x):
"""
Return the generator of ``x``.
EXAMPLES::
sage: R.<x> = QQ[]; R
Univariate Polynomial Ring in x over Rational Field
sage: gen(R)
x
sage: gen(GF(7))
1
sage: A = AbelianGroup(1, [23])
sage: gen(A)
f
"""
return x.... | b829b698625c3dc4b266f59ca80cf7941466ef3f | 115,685 |
def expToTrain(exp,start=None):
"""Converts a bunch of individual domain values to lists, because each domain value must be iterable for training data."""
x_train = []
for data in exp[start:,0]:
x_train.append([data, ])
return x_train | 35033df4d5b1a0178e73ce1678b31317b0d8125b | 115,686 |
def calculate_segment_name(host_name, recorder):
"""
Returns the segment name based on recorder configuration and
input host name. This is a helper generally used in web framework
middleware where a host name is available from incoming request's headers.
"""
if recorder.dynamic_naming:
r... | 230e8ec8cefe953a54bad0e81a0768521f741d83 | 115,690 |
def stations_by_river(stations):
"""takes list of station objects
returns dictionary of format {river: list of stations on this river}"""
stations_by_river_dictionary = {}
# if station is in dictionary, add to to appropriate list, else create new key and item
for object in stations:
... | 6cf2fe1baa38e69fd50bf85d1ef1df8e26731c9b | 115,692 |
def get_status(i2c_hat):
"""Gets the I2C-HAT status word. The exported robotframework keyword is 'Get Status'.
Args:
i2c_hat (I2CHat): board
Returns:
int: The status word
"""
return i2c_hat.status.value | 364669d61cbab620b575fe49ded8bead465bf381 | 115,695 |
def popcount(x):
"""
count the number of high bits in the integer `x`.
Taken from https://en.wikipedia.org/wiki/Hamming_weight
"""
# put count of each 2 bits into those 2 bits
x -= (x >> 1) & 0x5555555555555555
# put count of each 4 bits into those 4 bits
x = (x & 0x3333333333333333) +... | 924e071eaaf46d312ed31ffe4cc53af9dc84a6e0 | 115,697 |
import time
import torch
def record_ddp_fit_model_stats(trainer, model, use_cuda):
"""Helper to calculate wall clock time for fit + max allocated memory.
Args:
trainer: The trainer object.
model: The model to fit.
use_cuda: Whether to sync CUDA kernels.
Returns:
Max Memor... | fdb6d7bd2ce6cb3a38cf9ab491be541863d05fd6 | 115,703 |
def get_transfer_indicator(filename, transferred, total, spaces=50):
"""Returns progress indicator for byte stream transfer."""
if not total:
return "{}, ?".format(filename)
transferred = min(transferred, total)
spaces_filled = int(spaces * transferred / total)
return "{}, [{}] {}kB".format(... | 50d5b8bd65d165e07f7c0e9b6a694bfdca38580b | 115,704 |
def fix_lon(lon):
"""
:returns: a valid longitude in the range -180 <= lon < 180
>>> fix_lon(11)
11
>>> fix_lon(181)
-179
>>> fix_lon(-182)
178
"""
return (lon + 180) % 360 - 180 | 06d8aa05cb949b795b6aa79c4cbd86e3bb62efeb | 115,705 |
import logging
def load_files_serial(feature_files, load_function, **kwargs):
"""
Function for loading the feature files serially.
:param feature_files: The collection of feature files to load.
:param load_function: The function to use for loading the feature files.
:param kwargs: keyword argument... | 63eaaa4db4cacd54f8d9ce8984bcbb8b6f6e1250 | 115,707 |
def _extract_one_stim_dur(stim_durs):
"""
In case of multiple photostim durations - pick the shortest duration
In case of no photostim durations - return the default of 0.5s
"""
default_stim_dur = 0.5
if len(stim_durs) == 0:
return default_stim_dur
elif len(stim_durs) > 1:
pr... | d09ee8e83420d5c0fce17d3ab09459ba65cffd93 | 115,708 |
def read_images(cursor):
"""Returns the ID, recorded datetime and image content of all Testbed images."""
cursor.execute('SELECT id, recorded, testbed_image FROM observations WHERE '
'testbed_image IS NOT NULL ORDER BY id ASC')
return cursor.fetchall() | 58b4d6a5460d8b0a4e4d9a2c561c56796a265cd3 | 115,717 |
def is_url(output_location: str) -> bool:
"""Returns True if the output location is a URL."""
return output_location.startswith(('http://',
'https://')) | fd635193edffec8d633d7348a0585550aad99977 | 115,720 |
def get_rgb_channel(image, channel):
""" Converts an image to RGB and extracts a single channel """
return image[:, :, channel.value] | 35e7be9b99fdf4b4677819e4cc78a2123b915821 | 115,721 |
def is_valid_key(key: str) -> bool:
"""Check if an exiftool key is valid and interesting."""
# https://exiftool.org/TagNames/Extra.html
file_keys = (
'FileName', 'Directory', 'FileSize', 'FileModifyDate', 'FileAccessDate',
'FileInodeChangeDate', 'FilePermissions', 'FileType', 'FileType',
... | 9c1cecb043ff899d0b6959af4f1848bfd790a59b | 115,728 |
def deduplicate_list_of_periods(periods):
"""
Deduplicates a list of ``Period`` objects, ensuring no two ``Period``s have
the same id``
"""
known_ids = []
result = []
for period in periods:
if period.id not in known_ids:
known_ids.append(period.id)
result.app... | 37fe8bb75ec5aeac98744ee2e3aac592c4856f35 | 115,730 |
def get_input_shapes_map(input_tensors):
"""Gets a map of input names to shapes.
Args:
input_tensors: List of input tensor tuples `(name, shape, type)`.
Returns:
{string : list of integers}.
"""
input_arrays = [tensor[0] for tensor in input_tensors]
input_shapes_list = []
for _, shape, _ in inp... | 3420913a7eb682318d3f7f0d71b8dde9b6123fb5 | 115,731 |
def load_moves(filename):
"""Load a list of moves from a file,
ignoring whitespace."""
with open(filename) as f:
return [line.strip() for line in f if line.strip()] | 138f8d9be8429a460661db719ba42cd7490434f2 | 115,736 |
def _zbc_to_hgvs(i):
"""Convert zero-based coordinate to hgvs (1 based, missing zero)"""
if i >= 0:
i += 1
return i | 6741ec36e95ff9c76cdc0c91ffc4eae91e85686a | 115,737 |
def decode(state):
"""
decodes the taxi env state (int in [0,500) ) to:
(taxirow, taxicol, passloc, destidx) tuple
:param state: int in [0,500)
:return: (taxirow, taxicol, passloc, destidx) tuple
"""
destidx = state % 4
state = state // 4
passloc = state % 5
state = state // 5
... | 882df046b30904e0b4494644c36d73ad29256ff1 | 115,740 |
def _has_text(string: str) -> bool:
"""Returns True if a string has non whitespace text."""
string_without_whitespace = string.strip()
return len(string_without_whitespace) > 0 | e3bc86b79c4eec0c5e69836723ca091148dc221f | 115,751 |
import base64
def deserialise_job_command(command):
"""Deserialise job commands received through REST API."""
return base64.b64decode(command).decode("utf-8") | 2ea987c373203cd53e50f0bbc35da5ce77a6d0ed | 115,762 |
def extract(seq, f):
"""
Extract items from a possibly nested sequence.
All items of the possibly nested sequence ``seq`` for which the
callback ``f`` returns ``True`` are returned in a list.
"""
try:
it = iter(seq)
except TypeError:
return []
items = []
for item in ... | bfadd26b91921f7ab78451d3fa99b861dfed543a | 115,768 |
import random
def getRescind() -> str:
"""
Returns:
A random message ending for rescinding a user
"""
options=[
"YOU ARE JUST BEGGING FOR RESCINDITAS, AREN'T YOU?",
"swiggity swind, catch this rescind!",
"rescinded, enjoy ... | 5cd909a71290c70f3207d8cae7a835ee4463a36d | 115,769 |
def get_word_from_derewo_line(line):
"""Processor for individual line from DeReWo textfile.
Args:
line: Single line from DeReWo text file
Returns:
Lowercase word, None if invalid
"""
line = line.split()
# skip words with whitespace
if len(line) > 2:
return None
... | 9ce68515d1950e75d018c075c465abc2d129a681 | 115,770 |
def dotND(v1, v2):
"""Returns dot product of two nD vectors
(same as itemwise multiplication followed by summation)."""
return sum(vv1 * vv2 for vv1, vv2 in zip(v1, v2)) | 12a6adf90e4d3661af3ff088a3b50d595300e2ac | 115,772 |
def experiment_type_from_filename(filename):
"""
Get the experiment type based on filename.
It is assumed that the filename is compliant with
'<some_path>/measurements_<experiment_type>_summary.csv'
:param filename: A string representing the file name. It can be either full
or relative pat... | 758c1a5688a44ccde29678cb6d5fc86d58ec9fa9 | 115,773 |
import re
def _collapse_impacted_interfaces(text):
"""Removes impacted interfaces details, leaving just the summary count."""
return re.sub(
r"^( *)([^ ]* impacted interfaces?):\n(?:^\1 .*\n)*",
r"\1\2\n",
text,
flags=re.MULTILINE) | 504bf7170ea4624d1703ff7ed25106a5bb671834 | 115,774 |
def get_groups_per_chain(chains, ligands, waters):
"""Takes lists of chains, ligands and waters, and returns the chain counts
that should go in the .mmtf file.
:param list chains: the chains to pack.
:param list ligands: the ligands to pack.
:param list waters: the waters to pack.
:rtype: ``lis... | b35cc9e2c71e4a50e44aa68b366733d4701c6d76 | 115,777 |
from typing import Dict
def is_grpc_enabled(server_config: Dict) -> bool:
"""
Checks if the API has the grpc protocol enabled (cortex.yaml).
Args:
server_config: API configuration.
"""
return server_config["protobuf_path"] is not None | 2fcdf9fede008e3672458690a53e45c6817f2c3d | 115,778 |
def get_matched_rule(command, rules, settings):
"""Returns first matched rule for command."""
for rule in rules:
if rule.match(command, settings):
return rule | 3f82622f78d7338e69eb68f8073812637f321842 | 115,781 |
def s2m(seconds: float) -> float:
"""Convert seconds to minutes."""
return round(seconds / 60, 1) | 2d8c2ae992b0e65679752e891f96ba03b95ac3dd | 115,782 |
import re
def process_field_cancelled_value(value):
"""This method processes the value in field. It checks
for the value 'CANCELED' or 'CANCELLED' in the
<value> tag under the parent <field> tag.
"""
value = value.strip().lower()
cancel_match = re.findall(r'cancel[led$]*', value, re.I)... | 197a6a436c9ac8d9661ef8a64a4313fb5929714c | 115,783 |
def get_expiry_date(obj):
"""
A custom field to show the expiry date in the
Moderation Request Admin Changelist in djangocms-moderation.
:param obj: A Moderation Request object supplied from the admin view table row
:return: The expiry date from the matching moderation request object
"""
ve... | 4b6441f4d03527b771cd3071a3b583e8870e5d89 | 115,786 |
def get_lists_diff(py_list1, py_list2):
"""
Get elements of py_list1 which are not in py_list2.
"""
return list(set(py_list1) - set(py_list2)) | fcae7bf2fd503ed0a59d97e26d96bd2ac579766a | 115,803 |
def pad_left(orig, pad, new_length):
"""
Pad a string on the left side.
Returns a padded version of the original string.
Caveat: The max length of the pad string is 1 character. If the passed
in pad is more than 1 character, the original string is returned.
"""
if len(p... | a90f6662847a0c6e3ea8c668c15d4b96cc7d4e43 | 115,805 |
def center(u):
"""Compute the center between edges."""
return 0.5 * (u[1:] + u[:-1]) | e6def381c0e9394a7d5f9ee1e2d91d5aa52da75c | 115,809 |
def is_valid_uuid (uuid):
"""
is_valid_uuid (uuid) -> bool
returns True if uuid is a valid 128-bit UUID.
valid UUIDs are always strings taking one of the following forms:
XXXX
XXXXXXXX
XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
where each X is a hexadecimal digit (case insensitive)
"""
... | f7db551dc98a9f1a55dcebb1cd13cfa37ac61771 | 115,810 |
def position_to_index(v, nelx, nely):
"""
Convert a position vector to the index of the element containing it
"""
return int(v[0]) + int(v[1])*nelx | a73e335fc7a1baf29a34765ca2a3d633342ea03c | 115,816 |
def fdr(ps,alpha=0.05):
"""Given a list of p-values and a desired significance alpha, find the
adjusted q-value such that a p-value less than q is expected to be
significant at alpha, via the Benjamini-Hochberg method
(appropriate for independent tests).
"""
ps = sorted(ps)
m = len(ps)
k... | 0b68b37c285726190416ee3f969dc6c4fcad40ca | 115,823 |
import sympy
def expr_to_json(expr):
"""
Converts a Sympy expression to a json-compatible tree-structure.
"""
if isinstance(expr, sympy.Mul):
return {"type": "Mul", "args": [expr_to_json(arg) for arg in expr.args]}
elif isinstance(expr, sympy.Add):
return {"type": "Add", "args": [e... | 75818fb20b60d3548fab106dfc7a7e6f993b70f2 | 115,824 |
import torch
from typing import Tuple
def _extract_sizes(
h: torch.Tensor,
r: torch.Tensor,
t: torch.Tensor,
) -> Tuple[int, int, int, int, int]:
"""Extract size dimensions from head/relation/tail representations."""
num_heads, num_relations, num_tails = [xx.shape[i] for i, xx in enumerate((h, r, ... | bb94c5d8ddb1d61aa64bc83e143084239a83b92c | 115,827 |
def get_false_times(obs_pair_hash, variable):
"""
Get the timepoints where the variable is false.
Parameters:
obs_pair_hash: the dictionary containing all observations by time unit as a tuple (case, variable).
variable: the observation to look for.
Returns:
A list with all ... | 383fd38bed64dad14e9af3b36ed9b3e8db49a5cb | 115,830 |
import decimal
def big_int_cube_root(x):
"""Return the cube root of the given number.
This works with integers that would cause OverflowErrors when trying to
calculate the cube root the more straightforward way (x ** (1/3)). It
seems to reliably return the result with enough precision that cubing it
... | c4308724acf5c0886250ce0eaa5f264e9527fa83 | 115,838 |
def problem_2_5(node):
""" Given a circular linked list, implement an algorithm which returns the
node at the beginning of the loop.
DEFINITION
Circular linked list: A (corrupt) linked list in which a node’s next pointer
points to an earlier node, so as to make a loop in the linked list.
EXAMPL... | 90028102aaeb71607cfccf5583218a8c735dc09a | 115,841 |
import hashlib
def _sha512(data):
"""
Creates the string of sha512 hashed to the passed in data.
Args:
data (bytes): The data to be hashed
Returns:
type: str
The sha512 hashed data in string of hex values.
"""
return hashlib.sha512(data).hexdigest() | fdff68af99a479bb3bd463636878f90c44b8dd0a | 115,842 |
def show_most_common_entities(entity_dict, n=5):
"""Format information on entity count in a string
Args:
entity_dict (dictionary): entities and their attributes
n (int, optional): only the n most common occurrences are used. Defaults to 5.
Return:
string: formatted output string
... | 89945a6939ea9005bcf7a8ca2c9b44eb51ecc29d | 115,846 |
def html_movie_embed_qt(moviefile, width=400, height=400):
"""Return HTML for embedding a moviefile (QuickTime code)."""
text = """
<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B"
codebase="https://www.apple.com/qtactivex/qtplugin.cab"
width="%(width)s" height="%(height)s" >
<param name="src" value... | 254ccd498c342657ceefc5687d79aa8c6ec53f28 | 115,851 |
def get_number_digits(number: int) -> int:
"""Gets the number of digits in a number.
Parameters
----------
number : int
The number.
Returns
-------
int
The number of digits.
"""
return len(str(number)) | 8bf5734d51b2f97451099f25354f375ef3e14875 | 115,852 |
import re
def process(text):
"""
Remove the leading " * " prefixes from a Purpose, Returns, or Throws
multiiline block of text that we've just pulled out of the function header.
Convert <text> to `text` (Markdown code).
"""
text = re.sub(r'^ \*[ \t]+(\S)', r'\1', text, flags=re.MULT... | 358fbfdaed7b0dd4d741f35776521f8c16d0a117 | 115,853 |
def close(scope):
"""
Closes the existing connection with the remote host. This function is
rarely used, as normally Exscript closes the connection automatically
when the script has completed.
"""
conn = scope.get('__connection__')
conn.close(1)
scope.define(__response__=conn.response)
... | 719636165f1305a59e77ccc5f749641b06bef020 | 115,858 |
def query_long_descr(database, dict_name):
"""Return long description for a given dictionary."""
curs = database.cursor()
sql = '''
SELECT DI_LONG_DESCR
FROM DICTIONARIES
WHERE DI_DICT=?
'''
curs.execute(sql, (dict_name,))
results = list(curs)
if len(results) == 0... | f6c3819f40df85307dffd24000c9edaa96ef6017 | 115,860 |
def db2lin(data):
"""
Convert from logarithm to linear units
Parameters
----------
data: single value or an array
Returns
-------
returns the data converted to linear
"""
return 10**(data/10.) | fe1320cdfcd53e4a96985c81d5edb76a16f26550 | 115,862 |
def is_not_none(value):
"""Helper function returning whether ``value is not None``"""
return value is not None | a7c926339881318e5e774334c803d23b1717ddf0 | 115,867 |
import torch
def mapk(output, target, k=3):
"""
Computes the mean average precision at k.
Parameters
----------
output (torch.Tensor): A Tensor of predicted elements.
Shape: (N,C) where C = number of classes, N = batch size
target (torch.int): A Tensor of elements t... | d4d5ea89833192a8dd8b110d66b70b5804ed1763 | 115,869 |
def Check_VCF_Paths(tp_vcf_path, fp_vcf_path):
"""Checks to make sure there are equal numbers of tp and fp vcfs
Parameters
----------
tp_vcf_path : str
comma seperated list of TP vcf paths
fp_vcf_path : str
comma seperated list of FP vcf paths
Returns
-------
list
... | 9e44b2a49f5bbe2a21aca6b0faa87297970df616 | 115,870 |
def get_nearest_neighbours(p, N, i):
"""Return the nearest N neighbours to a given point, i
Args:
p (DataFrame): vertices dataframe
N (int): integer for number of nearest neighbours to return
i (int): loc within dataframe p
Returns:
a tuple of locs of the nearest neighbours... | 5f9b5b5ce7e09dc91a53d41bf9b8c0bb9619f75c | 115,873 |
def mean(values):
"""
Computes the mean of a list of values.
This is primarily included to reduce dependency on external math libraries
like numpy in the core algorithm.
:param values: a list of numbers
:type values: list
:return: the mean of the list of values
:rtype: float
>>> m... | 4406934e21a02cf9b2bfaef9206bef316381698b | 115,875 |
def sqlquote( value ):
"""Naive SQL quoting
All values except NULL are returned as SQL strings in single quotes,
with any embedded quotes doubled.
"""
if value is None or value=="":
return 'NULL'
return "'{}'".format(str(value).replace( "'", "''" )) | 918230f9d3a914065ed7c4e3644ddd0d8fbb2b89 | 115,877 |
from typing import Tuple
from typing import List
def parse_path(path_string: str) -> Tuple[str, List[str]]:
"""
Inputs:
path_string: a string containing drive_name a colon and one or more folders like:
'my_drive:folder1/folder2'
returns a tuple of the drive_name, folder_list
... | ec94348c9118ce25e754db59bc320e6e83470e2a | 115,882 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.