content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def interval_union(a, b):
"""Returns a 2-tuple representing the union of two intervals.
Args:
a: 2-tuple containing integer coordinates representing a half-open interval.
b: 2-tuple containing integer coordinates representing the other half-open interval.
Returns:
2-tuple containin... | d7fb8f7cb1e626f99aaa91ee56b3b23a73a92880 | 259,117 |
import re
def is_valid_coordinates(coordinates):
"""Test coordinates for validity."""
if re.match('^-?\d+\.?\d*\,{1}\s-?\d+\.?\d*$', coordinates):
lat, lon = coordinates.split(', ')
return -90 <= float(lat) <= 90 and -180 <= float(lon) <= 180
else:
return False | 63b9b6d0bb7fd7794e3b75735ebdf72b4f4b4029 | 390,550 |
def _use_constant_crc_table(opt):
"""
Return True is the CRC table is constant.
"""
if opt.width is not None and opt.poly is not None and opt.reflect_in is not None:
return True
else:
return False | 72c6861f80b4e3f81fe9ac97bff4985cd7c18245 | 444,625 |
def remove_features(df, drop_list):
"""
Remove features from dataframe with columns containing substrings in
drop_list. Return a new dataframe.
"""
keep = []
for column_name in list(df.columns.values):
keepQ = True
for substring in list(drop_list):
if substring in co... | 084e84d3d7cb6b2c5557c9a91e6ac7077e21f1a0 | 537,932 |
import base64
def embed_png2html(figdata_png):
"""
Convert the data to base64 format before the PNG data can be embedded in HTML
Parameters:
plt_fig: matplotlib figure
Return:
figdata_png: base64 encoding images
"""
figdata_png = base64.b64encode(figdata_png)
figdata_png = ... | 280f429f55d71baeb004aa0b7be41b7bbe2cfbc9 | 295,021 |
def get_synchrony(sequences):
"""
Computes the normalised synchrony between a two or more sequences.
Synchrony here refers to positions with identical elements, e.g. two identical sequences have a synchrony of 1, two completely different sequences have a synchrony of 0.
The value is normalised by dividing by the n... | 92d48ebbf43869e9ff41a6c81d458b0ae7861016 | 335,962 |
def dict_to_kwds(dct, kwdstr):
""" convert a dictionary to a string of keywords
Parameters
----------
dct : dict
kwdstr: str
additional keyword strings
Examples
--------
>>> dict_to_kwds({"a":1,"c":3},'a=1,b=2')
'a=1,c=3,b=2,'
"""
string = ''
for key in sorted(... | c646c68cb9205d00d55dfda210ed41a7743df0b4 | 343,311 |
def add_one(value: int) -> int:
"""Add one to a number."""
return value + 1 | a7230ac288192fc75edebbfb281043b1cf7025b2 | 434,695 |
import re
def getTimeElementsFromString(dtStr):
"""Return tuple of (year,month,day,hour,minute,second) from date time string."""
match = re.match(r'^(\d{4})[/-](\d{2})[/-](\d{2})[\s*T](\d{2}):(\d{2}):(\d{2})(?:\.\d+)?Z?$',dtStr)
if match: (year,month,day,hour,minute,second) = map(int,match.groups())
... | e1a2ef030e6041d256cad85a18baf4f3784377d8 | 125,159 |
def parseText(text1, nlp):
"""Run the Spacy parser on the input text that is converted to unicode."""
doc = nlp(text1)
return doc | 99d6a585358a700f8fc48c5dc4fc761a03ab42a7 | 705,984 |
def parse_coordinates(result):
"""
Function purpose: parse coordinates from console result into a list
Input: string
Output: list
"""
bboxStr = result[result.find("[") + 1:result.find("]")]
bboxList = [float(i) for i in bboxStr.split(',')]
return bboxList | 2fb1ee98219618381994960d14aacb0b21abdba3 | 457,777 |
def patches2image(patches):
"""
Return patches obtained from a 2D image into the original image.
Args:
patches:
Tiles to return into the 2D image. Shape = (N_patch_x, N_patch_y, Patch_size_x, Patch_size_y)
Return:
image:
2... | e9f78cdf4fa356fce42df01890f0f618f01d732d | 317,425 |
import hashlib
def hex_sha1_of_stream(input_stream, content_length):
"""
Returns the 40-character hex SHA1 checksum of the first content_length
bytes in the input stream.
:param input_stream: stream object, which exposes read() method
:param content_length: expected length of the stream
:type... | fb4666f89a20fe0112840c58600d96915a66510a | 283,146 |
import math
def printXYZDegrees(self):
"""Print X, Y, and Z components in degrees."""
return ("[%f, %f, %f]" % (math.degrees(self.x), math.degrees(self.y), math.degrees(self.z))) | 8f48563c13e170a18b1c9a9e6385a842e307d177 | 649,555 |
import itertools
def _Powerset(input_list):
"""Create powerset iterator from the elements in a list.
Note: Based on example in official Python itertools documentation.
Example:
[p for p in Powerset(['a', 'b')] == [(), ('a',), ('b'), ('a', 'b')]
Args:
input_list: A sequence of Python objects
Retu... | 0218cc5f6b4a5905c0563332d8229c49fd0e8dd2 | 548,816 |
import math
def calc_heading(currentLat, currentLong, targetLat, targetLong):
"""
Calculates target heading from coordinates
Args:
currentLat: Current latitude of the player
currentLong: Current longitude of the player
targetLat: Target latitude
targetLong: Target long... | 51392f6a533f7c02c2d392af5ca5fe08188476bb | 341,895 |
def formatDateTime(raw: str) -> str:
"""
Helper function. Converts Image exif datetime into Python datetime
Args:
raw (str): exif datetime string
Returns:
str - python compatible datetime string
"""
datePieces = raw.split(" ")
if len(datePieces) == 2:
return da... | d9c0ec43e42e1d24223eb8f640d8790ec48b82fc | 64,543 |
def _chi2_ls(f):
"""Sum of the squares of the residuals.
Assumes that f returns residuals.
Minimizing this will maximize the likelihood for a
data model with gaussian deviates.
"""
return 0.5 * (f ** 2).sum(0) | af223f48bc0beffa9a99fba872c769a94fbe3235 | 19,200 |
from pathlib import Path
import inspect
def here(frames_back: int = 0) -> Path:
"""
Get the current directory from which this function is called.
Args:
frames_back: the number of extra frames to look back.
Returns: the directory as a Path instance.
"""
stack = inspect.stack()
pre... | a261aeac42b8fe4143783e41a74c1025e937e17d | 87,668 |
def sum_period_review_request_stats(raw_aggregation):
"""Compute statistics from aggregated review request data for one aggregation point."""
state_dict, late_state_dict, result_dict, assignment_to_closure_days_list, assignment_to_closure_days_count = raw_aggregation
res = {}
res["state"] = state_dict
... | 68a46d89bbe773668ea27a1ac8a04c8f62e45292 | 466,446 |
def format_headers(unformatted_dict):
"""
Utility method for formatting a dictionary of headers.
Params:
unformatted_dict (dict): Unformatted dictionary being submitted for formatting.
Returns:
formatted_headers (dict): Dictionary that has been camel cased with spaces replacing
... | 10d09985a811ef3e6cf4d5cf43cf7c998f50548c | 387,317 |
def pass_through_formatter(value):
"""No op update function."""
return value | 202ea761db9e1fa858718c61df3a7fd18f02826c | 706,015 |
def guess_content_type(name):
"""Return the content type by the extension of the filename."""
if name.endswith(".jpg"):
return "image/jpg"
elif name.endswith(".jpeg"):
return "image/jpeg"
elif name.endswith(".png"):
return "image/png"
elif name.endswith(".gif"):
retur... | 3f6681e1df2384e3fcba58eda436cb31c3e8d18c | 665,613 |
import pickle
def distance_histogram_dict(f):
"""Parses distance histogram dict pickle.
Distance histograms are stored as pickles of dicts.
Write one of these with contacts/write_rr_file.write_pickle_file()
Args:
f: File-like handle to distance histogram dict pickle.
Returns:
Dict with fields:
... | dcd3a1eca88327a47e4c16b27463d3f0b6c475e4 | 298,663 |
from typing import Sequence
from typing import List
from typing import Tuple
def search_sub_seq(s1: Sequence, s2: Sequence) -> List[Tuple[int, int]]:
"""
Searches all occurrences of sequence s1 in s2,
:param s1: First sequence.
:type s1: Sequence
:param s2: Second sequence.
:type s2: Sequence... | ef29454bed263dbb7456623f0e5d4254010a6a8e | 571,419 |
import turtle
def make_window(color, title):
"""
Set up the window with the given background color and title.
Returns the new window.
"""
window = turtle.Screen()
window.bgcolor(color)
window.title(title)
return window | e3a23fddbbffd0f4851a28c327b37cebf1bcda5d | 599,196 |
def is_mode_correct(mode_no):
"""The function checks the correctness of the game mode (number range from 1 to 3)."""
try:
num = int(mode_no)
if num < 1 or num > 3:
return False
except ValueError:
return False
return True | 4b9218abdc4f66a692bc423fbb2fb6323175e5f2 | 530,207 |
def violate_safety_requirement(complete_solution):
"""Checks whether a complete_solution violates a safety requirement. In
case of violation, the function returns `True`, otherwise it returns
`False`. Since the definition of fitness function is based on the safety
requirement and it is defined in a way ... | c1ee4e79948a68f75893a89270cf807b9f6ef844 | 365,556 |
def extract_gp_layer_kwargs(kwargs):
"""Extracts Gaussian process layer configs from a given kwarg."""
return dict(
num_inducing=kwargs.pop("num_inducing", 1024),
normalize_input=kwargs.pop("normalize_input", True),
gp_cov_momentum=kwargs.pop("gp_cov_momentum", 0.999),
gp_cov_ridge_penalty=... | 416097ab3ebe7f8980177862d18e2b0b24005918 | 575,789 |
def line_to_int_list(line):
"""
Args:
line: A string of integers. Ex: '1 3 5\n'
Returns:
A list of integers. Ex: [1, 3, 5]
"""
data = line.split(' ')
data = filter(None, data)
data = [int(x.strip('\n')) for x in data]
return data | 0ba3f984704219f134185a80d7858e176679e8bf | 566,560 |
def frame_to_midi(frame, ignore_graces=True):
"""
:param list frame: Frame of data from :obj:`~decitala.utils.get_object_indices`.
:return: A numpy array holding the pitches within the frame.
:rtype: numpy.array
>>> from music21 import note
>>> my_frame = [
... (note.Note("B-", quarterLength=0.125), (4.125,... | b567d7358b4a1a3ccd0a828c7f67ec318ba82a27 | 135,619 |
def getmorphology(word, tagmap):
"""Get morphological features FEATS for a given word."""
if tagmap and word.tag_ in tagmap:
# NB: replace '|' to fix invalid value 'PronType=int|rel' in which
# 'rel' is not in the required 'attribute=value' format for FEATS.
# val may be an int: Person=3... | 572499db5e104041900c13d238862739afd1039e | 229,655 |
def indicator_bollinger(df_t, lookback=20):
"""Creates columns for bollinger channel. Requires columns "high" and "low" in intraday_df
Args:
df (pd.DataFrame): OHLCV intraday dataframe, only needs close
lookback (:obj:int, optional): rolling window. Default is 20
Returns:
pd.Data... | 42e188968eb69dae138906a467ee5eaff5c93a7e | 326,608 |
import toml
import yaml
import json
def mock_settings_file(request, monkeypatch, tmpdir, file_extension):
"""Temporarily write a settings file and return the filepath and the expected settings outcome."""
ext = file_extension
p = tmpdir.mkdir("sub").join("settings" + ext)
expected_result = {"testgrou... | 4899ebbc9efbe31a931387d4a09dcb8c727eaf8d | 698,303 |
def get_mac_address(path):
"""
input: path to the file with the location of the mac address
output: A string containing a mac address
Possible exceptions:
FileNotFoundError - when the file is not found
PermissionError - in the absence of access rights to the file
TypeError - If t... | 814a530b63896103adcb8fbc84d17939644b9bbe | 709,477 |
def get_next_free_ind(d:dict):
""" given a dictionary of indices, get the next free index """
return max(d.values()) + 1 | 96a7c95fd65cd1b4f3db1fc731a3d227340326fb | 464,543 |
def convert(k: str) -> str:
"""Convert key of dictionary to valid BQ key.
:param k: Key
:return: The converted key
"""
if len(k.split(":")) > 1:
k = k.split(":")[1]
if k.startswith("@") or k.startswith("#"):
k = k[1:]
k = k.replace("-", "_")
return k | 06eaa83cbc0ebdde02c498123cb48662936eba01 | 579,226 |
def _prev_rosdistro(index, rosdistro_name):
"""Given current rosdistro name, return the previous."""
valid_rosdistro_names = list(index.distributions.keys())
valid_rosdistro_names.sort()
# skip distributions with a different type if the information is available
distro_type = index.distributions[ros... | 6d6c1e8e5d9ca02115c7e0a4ee6006ba4af98c13 | 495,467 |
import re
def re_search(regex, string):
"""Try matching a regular expression."""
return re.search(regex, string) | 4cd9cfadfda9fdf875c6c4a96a589d038afcfd30 | 522,593 |
def getOrderedTeamGames(teamGames):
"""
input: team games
output: map team -> ordered list of games (by time)
"""
orderedTeamGames = {}
for team in teamGames:
orderedTeamGames[team] = []
currentTeamGames = teamGames[team]
keylist = list(currentTeamGames)
keylist.s... | 87b29b9f9a392a7d813b0ddd9be0be0be4c28c10 | 501,186 |
def get_probability(sample, cond):
"""Find the probability that the sample fullfills conditions.
Example
-------
>>> y = np.array([-1., 0., 1., 2.])
>>> print get_probability(y, y<=0)
0.5
Arguments
---------
sample : ndarray
A sample to check the condition on.
cond : n... | 5e993081fd9ee14d386bce9229c61d2835adb6ad | 163,580 |
import re
def intcomma(value):
"""
Converts an integer to a string containing commas every three digits.
For example, 3000 becomes '3,000' and 45000 becomes '45,000'.
"""
value = str(value)
new = re.sub("^(-?\d+)(\d{3})", '\g<1>,\g<2>', value)
if value == new:
return new
else:
... | fca5cbbff83cf23e052308cec0d88a2a49d85387 | 609,584 |
def read_file(path):
# type: (str) -> list
"""Loads a text file from ``path`` into a list of str and returns it.
"""
with open(path, "rU") as text:
return text.readlines() | 396341e9a46fbcfebd473cc2fb171d56dd2cc41c | 384,146 |
def make_constant(match):
"""Returns a Constant JSON Object"""
return {
'type': 'c', #c for constant, f for function
'name': match.group('name'),
'value': match.group('value') #is this necessary?
} | 75d3781aaefec29570c06e1c672409de9c71974d | 286,126 |
def tidy_participation_url(url: str) -> str:
"""
>>> tidy_participation_url(
... "https://test.connpass.com/event/123456/participation/")
'https://test.connpass.com/event/123456/participation/'
>>> tidy_participation_url(
... "https://test.connpass.com/event/123456/participation")
'ht... | bda0b6c69eff84f959de35f223c6c23602612f2e | 235,748 |
def get_attribute_values(elements,name):
""" returns a list of attributes 'name' from a list of elements """
attribute_values = []
for element in elements:
attributes = element.attributes
for n in range(attributes.length):
attribute = attributes.item(n)
if attribute.n... | 953ae221b0dd88812fc9b59e5dc86add9d9ededb | 649,022 |
def count_items(alist):
"""
Count number of items in alist.
"""
count = 0
for item in alist:
count = count + 1
return count | 69675913ffbcc1e6021c2c1002d4fa039ecc63b4 | 52,148 |
def _gen_param_excluder(added_kwargs):
"""
Pass through all the original keys, but exclude any kwargs that we added
manually through prep_scalar
Parameters
----------
added_kwargs : list of str
Returns
-------
excluder : callable
"""
def excluder(params, except_=None):
... | 99b7db0cd064a3afc9997e8c0e82adea991a836d | 506,151 |
def to_string(val):
"""Convert a value to a string."""
return str(val) | 0f3d4a4d74c10f1e37f95d9e23b6b04e6c10d3be | 202,692 |
def maplist2dict(dlist):
""" Convert a list of tuples into a dictionary
"""
return {k[0]: k[1] for k in dlist} | 2d6c03d09ad8cdb9c9d7878c5038b99a28992dde | 68,510 |
def parse_vertex_and_square_ids(
data: str, start_string: str = "Square ID", end_string: str = "# Edges",
) -> dict:
"""Return a dictionary of vertex ID & square ID pairs.
This function will parse through the read-in input data between ''start_string'' and ''end_string''
to return the filtered text in-... | 168ec7a785a89508c60061a6ac85b2f8a62c001b | 561,130 |
def exoption(self, ldtype="", option="", value="", **kwargs):
"""Specifies the EXPROFILE options for the Mechanical APDL to ANSYS CFX profile file transfer.
APDL Command: EXOPTION
Parameters
----------
ldtype
Load type:
* ``"SURF"`` : Surface load
* ``"VOLU"`` : Volume lo... | 82a3d62b5d9d079e8a5c3f2ca457e133e329030b | 136,693 |
def format_month_interval(val):
"""
Format a MonthInterval value.
"""
return f"{int(val)}M" | 28ac3d457dab6c4c877d15b137a26930180c389e | 62,977 |
def strip_namespace(obj):
"""
Returns the given object name after striping the namespace
:param obj: str, object to strip namespace from
:return: str
"""
return obj.split(':')[-1] | 1c34576458df1a90b6c0d075d7e54bbd7c350125 | 46,564 |
def classify(model, dataframe):
"""Classifies a dataframe using a trained random forest model
Args:
model: trained RandomForestClassifier
dataframe: A features dataframe
Returns:
dataframe of raw predictions
"""
return model.transform(dataframe)\
.select(['... | c0331c2767772c386fd7a8eac7f2d30d974841dc | 593,683 |
import json
def dict_to_json(json_dict: dict, sort_keys=True, indent=None) -> str:
"""
Transforms a tree made up of dictionaries and list into json string.
:param json_dict: the dict to transform
:return: the json string
"""
return json.dumps(json_dict, sort_keys=sort_keys, indent=indent) | b5004f8913eebfdfa6876dd269693dc5d56bd46d | 501,260 |
from datetime import datetime
def year(date):
""" Returns the year
Accepted format: %m/%d/%Y
"""
try:
fmt = '%m/%d/%Y'
return datetime.strptime(date, fmt).timetuple().tm_year
except ValueError:
return 0 | bb4a0e942967cf70ffc45c0ffcdf1df1fecd1910 | 142,541 |
def get_mappings(params):
"""
Create a mapping between attributes and their associated IDs.
"""
if not hasattr(params, 'mappings'):
mappings = []
k = 0
for (_, n_cat) in params.attr:
assert n_cat >= 2
mappings.append((k, k + n_cat))
k += n_cat
... | d75ffb85f1a5ccb1705866b16de65275347c1865 | 285,660 |
import struct
def parse_sch(l2cap_data):
"""
Parse the signaling channel data.
The signaling channel is a L2CAP packet with channel id 0x0001 (L2CAP CID_SCH)
or 0x0005 (L2CAP_CID_LE_SCH)
0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7
----------------------------------------... | 93acbe97cdcbd2a961c13e5adede037941a44abe | 254,949 |
def get_numeric_ratio(s):
"""
gets the ratio of numeric characters to the total alphanumerics
:type s: str
:rtype: float or NoneType
"""
num_numeric = 0
num_alphabetic = 0
if len(s) == 0:
return None
else:
for character in s:
if character.isnumeric():
num_numeric += 1
elif character.isalpha():
... | 2a7fa2cd97bd2044cced18efa68530e366e0f179 | 488,987 |
def get_magnetic_galaxy_dir(galaxy: str, data_directory: str) -> str:
""" Get the full path to a specific galaxy directory
Args:
galaxy (str): Name of the galaxy
data_directory (str): dr2 data directory
Returns:
str: Path to galaxy directory
"""
return data_directory + "/ma... | 29c4266bac4bb3b133baf23c3fb1381ffb4a6349 | 139,643 |
import math
def format_pace(pace):
"""formats a pace in s/km as a nice mm:ss/km"""
rem, inte = math.modf(pace/60)
return f"{int(inte)}:{int(rem*100):02d}/km" | c8d14fe4bd67a3bf5daf7cd623a65eb84cfd452f | 265,923 |
import hashlib
def get_fingerprint(file_path: str) -> str:
"""
Calculate a fingerprint for a given file.
:param file_path: path to the file that should be fingerprinted
:return: the file fingerprint, or an empty string
"""
try:
block_size = 65536
hash_method = hashlib.md5()
... | b0ee4d592b890194241aaafb43ccba927d13662a | 3,511 |
def strip_tuple(tuple_list, tuple_index = 0):
"""Given a list of tuples, creates a list of elements at tuple_index"""
elem_list = []
for i in range(0, len(tuple_list)):
elem_list.append(tuple_list[i][tuple_index])
return elem_list | 0540b1f85987f5bce1a42ee6e72460faecd6a31c | 205,171 |
import time
def timestamp(d=True, t=True, tz=True, utc=False, winsafe=False):
"""Simple utility to print out a time, date, or time+date stamp for the
time at which the function is called.
Parameters
----------:
d : bool
Include date (default: True)
t : bool
Include time (defau... | a2d74db673993a9a22822062b962fbc161dfe59d | 241,495 |
import re
def parse_speaker(path):
"""
Get speaker id from a BAS partitur file
Parameters
----------
path : str
a path to the file
Returns
-------
str or None
the speaker id
"""
speaker = ''
with open(path, 'r', encoding='utf8') as f:
lines = f.read... | 31f65b13903324b1b941b2beb6c28edde430ffa1 | 67,391 |
def dp(n):
"""Returns the n-th number of fib with DP"""
f = [0] * (n + 1)
for i in range(n + 1):
if i <= 1:
f[i] = i
else:
f[i] = f[i - 1] + f[i - 2]
return f[n] | d421689bbb3b51d6745a92eefbf41800761dcd68 | 387,855 |
def es_parentesis(caracter):
"""
(str of len == 1) -> str
>>> es_parentesis('(')
'Es parentesis'
>>> es_parentesis('x')
'No es parentesis'
>>> es_parentesis('xa')
Traceback (most recent call last):
..
TypeError: xa no es un parentesis
:param caracter: str el caracter a eva... | bdace083e11eadbbf3f2d679bf9fffad4a1313c0 | 358,183 |
import time
def date_passed(date):
"""Check if the date has already passed."""
return date <= int(time.time()) | 9f3499bf6fbef190b21131f40b4b5d2c42acda53 | 319,971 |
def get_sentence_at_index(index, resolved_list):
"""Returns the sentence beginning at the index
"""
end_of_sentence_punctuation = ['.', '!', '?']
begin_index = index
end_index = index
while begin_index >= 0:
val = resolved_list[begin_index].strip()
if val in end_of_sentence_punct... | 5f081086e227689c1aa6d774c8f83e79d62e344f | 468,072 |
import binascii
def hex_decode(string):
"""
Hex decode string
Parameters
----------
string : str
String to be decoded from hexadecimal
Returns
-------
str
Text string with ASCII / unicode representation of hexadecimal input string
"""
return binascii.a2b_hex(st... | 5513101514bded4b28f1a6b0038ce9a6f2dfac87 | 652,350 |
import click
def geojson_type_feature_opt(default=False):
"""GeoJSON Feature or Feature sequence output mode"""
return click.option(
'--feature',
'geojson_type',
flag_value='feature',
default=default,
help="Output as GeoJSON feature(s).") | d9705fcb28d70f92d94803850652231ccff1b77e | 494,726 |
def model_eval(model, b_gen, metric_str, workers=4):
"""
Evaluate model on data generator.
Prints and returns scores for specified metrics.
Parameters
----------
model : Keras model
The model to evaluate.
b_gen : DataGenerator object
DataGenerator object to use for loading t... | 0055da84a8c790bf414930f40f65400d1b441820 | 406,266 |
def find_value(dic, key):
"""return the value of dictionary dic given the key"""
return dic[key] | c1bbc2da7c1cb35659be9bfd76904daeac46e870 | 297,734 |
def _list_to_hash(lst):
"""Convert a flat list of key value pairs to a hash"""
return {lst[i]: lst[i+1] for i in range(0, len(lst), 2)}; | 6848b7681d79c6e6609dbc98b12d763cd5e5fdbb | 197,841 |
def k12_enrollment(parcels):
"""
Enrollment for grades kinder through 12th.
"""
return parcels['k6_enrollment'] + parcels['g7_8_enrollment'] + parcels['g9_12_enrollment'] | e1b8eca67d9e6f35883a2a15ed6f73f511ac4aba | 608,050 |
def str_to_bool(s):
""" String to bool used to read config file
Parameters
----------
s : str
String to convert
Returns
-------
s : bool
Boolean value of input string
"""
if s == 'True':
return True
elif s == 'False':
return False
else:
... | 1ccfd2b39ef298fb7b02925fe667cc6d38398614 | 50,698 |
def trim_taxon(taxon: str, int_level: int) -> str:
"""
taxon_hierarchy: '1|2|3|4|5|6|7'
level: 5
output: '1|2|3|4|5'
"""
return '|'.join(taxon.split('|')[:int_level]) | 0b9fe0b01633d81964f7d2a245ccb7621b8c10ed | 205,769 |
def get_right_slices(var, right_ndims, fixed_val=0):
"""Return an indexing tuple where the left dimensions are held to a
fixed value and the right dimensions are set to slice objects.
For example, if *var* is a 5D variable, and the desired indexing sequence
for a numpy array is (0,0,0,:,:), then ... | 1665eb5077bf14c6fa5b5617c6b3285317e8f29a | 152,414 |
def sanity_check_iob(naive_tokens, tag_texts):
"""
Check if the IOB tags are valid.
* Args:
naive_tokens: tokens split by .split()
tag_texts: list of tags in IOB format
"""
def prefix(tag):
if tag == "O":
return tag
return tag.split("-")[0]
def body(... | 4fb16ed2bd7a623a7dad331d8b7c8a5033a382ea | 35,148 |
import six
def is_string(value):
"""Returns whether value has a string type."""
return isinstance(value, six.string_types) | bbdc9602b2317fc2d8ed183af69ec60f9fce12ee | 511,639 |
def construct_filter_based_on_destination(reimbursable_destination_type: str):
"""
Construct Filter Based on Destination
:param reimbursable_destination_type: Reimbusable Destination Type
:return: Filter
"""
filters = {}
if reimbursable_destination_type == 'EXPENSE_CATEGORY':
filters... | 73116ce3e6398e98c1540380094e70cc1620867b | 27,221 |
def adjacency_to_edges(nodes, adjacency, node_source):
"""
Construct edges for nodes based on adjacency.
Edges are created for every node in `nodes` based on the neighbors of
the node in adjacency if the neighbor node is also in `node_source`.
The source of adjacency information would normally ... | d593b4acd2b6f7553d6b9677209422ee665bc2d0 | 651,274 |
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 format_geo(geography_id):
"""
Format geography id for use within an SDF
:param geography_id: string; corresponds to DV360 geography id
:return: string; formatted for SDF usage
"""
return '{};'.format(geography_id) | 63d56fd91419ce150452acb2b35dc0f6b53388b7 | 106,038 |
def convert_dcc_translation(translation):
"""
Converts given tpDcc translation into a translation that DCC can manage
NOTE: tpDcc uses Y up coordinate axes as the base reference axis
:param translation: list(float, float, float)
:return: list(float, float, float)
"""
return translation[0], ... | a0376cb496af36693a6119640ef985e7853a8eff | 465,608 |
import re
def parse_port_name(name):
"""
Parses a port name. Returns the base name, cell index and bit index.
>>> parse_port_name("A_PORT")
('A_PORT', None, None)
>>> parse_port_name("A_PORT_0")
('A_PORT', 0, None)
>>> parse_port_name("A_PORT_b31")
('A_PORT', None, 31)
>>> parse_p... | 643dbcad09f890419d36b47123a6478387944548 | 87,809 |
def _insert_single_package_eups_version(c, eups_version):
"""Insert version information into the configuration namespace.
Parameters
----------
eups_version
The EUPS version string (as opposed to tag). This comes from the
``__version__`` attribute of individual modules and is only set f... | 5fb78d55952466d454f911cead259948407c6e92 | 585,300 |
import torch
def decoder_padding_mask(
ys_pad: torch.Tensor, ignore_id: int = -1
) -> torch.Tensor:
"""Generate a length mask for input.
The masked position are filled with True,
Unmasked positions are filled with False.
Args:
ys_pad:
padded tensor of dimension (batch_size, input_l... | 5c494ed2c4f18118a708b3fa4c50b05599e93b3f | 556,830 |
def place_piece(piece, x, y, board):
"""
Utility function that places the piece at a given (x,y) coordinate on the given board if possible
Will overwrite the current value at (x,y), no matter what that piece is
Returns True if the piece is placed successfully and False otherwise
Arg piece: string - ... | 271e5b553cc21f826dda644f0c486ee329191af1 | 467,899 |
def deserialize_yesno(value):
"""
Deserialize a boolean (yes or no) value.
"""
return value.lower() == 'yes' | c3c92966302d1865763a7106ea7905c00cae9f2c | 442,562 |
from typing import List
def subtotals_for_deltas(deltas) -> List[int]:
"""
Given a list of deltas corresponding to input coins, create the "subtotals" list
needed in solutions spending those coins.
"""
subtotals = []
subtotal = 0
for delta in deltas:
subtotals.append(subtotal)
... | 88111337b07328d56d63eb8c5e3ad76b0e6d84ea | 169,770 |
def is_palindrome(string: str) -> bool:
"""Return whether string is a palindrome or not."""
if "".join(reversed(string)).lower() == string.lower():
return True
return False | b40bdaa54b9807ff0d1f88cef08dd232d8b26cb9 | 350,608 |
def is_tuple(value):
"""is value a tuple"""
return isinstance(value, tuple) | 08f51cba93b07620a93b531dd9ea380ae7dd1118 | 336,695 |
import warnings
def deduplicate(S):
"""deduplicate pd.Series by removing rows with same index and values"""
dedup = S.groupby(S.index).first()
diff = len(S) - len(dedup)
if diff:
warnings.warn(f"found {diff} duplicates in S, removing them")
return dedup
return S | 743d2429ffc5e3fad435fa30e63f2c19a1fa2e09 | 552,776 |
def triple(n):
""" (number) -> number
Returns triple a given number.
>>> triple(9)
27
>>> triple(-5)
-15
>>> triple(1.1)
3.3
"""
one = n * 3
return (one) | 0f10a8026aba22ce9a1905c5d445984c7310763d | 636,956 |
def parse_clusters(cluster_file):
"""
expects one line per cluster, tab separated:
cluster_1_rep member_1_1 member 1_2 ...
cluster_2_rep member_2_1 member_2_2 ...
"""
cluster_dict = {}
with open(cluster_file) as LINES:
for line in LINES:
genes = line.strip()... | 88243b7a142224e755eb2046c11a90b352d5835d | 685,017 |
def sniff_params(read):
"""
Given a read dict parsed from JSON, compute a mapping parameter dict for the read.
The read will have param_XXX annotations. Turn those into a dict from XXX to value.
These should be the same for every read.
"""
# This is the annotation dict from the re... | 312e792d58ff4a5c6b5c7a05086f4356f5fcda43 | 422,386 |
def get_summary(html_text):
"""Returns the summary part of the raw html text string of the wikipedia article.
:param html_text: The html content of an article.
:type html_text: str
:return: The summary of the input wikipedia article.
:rtype: str
"""
# The summary ends before the first h tag... | 762085d15826ee1ca3bb6a9d63ee5e6700500029 | 432,392 |
from typing import List
from typing import Union
def average(values: List[Union[int, float]]) -> float:
"""Return the average."""
return sum(values) / len(values) | 4e63aa9055c1251f240465440b79aec2241f07d7 | 413,423 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.