content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import re
def remove_unnecessary_spaces(text):
"""Removes spaces at the beginning, end and multiple spaces in between in the given text"""
return re.sub(' +', ' ', text).strip() | f1e2007e1bb4bc0de58dbb94650adfd1a38f45c3 | 617,928 |
def count_leaf_items(item_list):
"""Recursively counts and returns the
number of leaf items in a (potentially
nested) list.
"""
print(f"List: {item_list}")
count = 0
for item in item_list:
if isinstance(item, list):
print("Encountered sublist")
count +... | be0bb45a4609483db8b268c3f7f89530d970faad | 617,934 |
from datetime import datetime
def str2datetime(dcm_date: str) -> datetime:
"""Parse a date in DICOM string format and return
a datetime object.
Strings can come in the following formats:
YYYYMMDD (date), or YYYYMMDDHHMMSS.FFFFFF&ZZXX
(datetime) -as specified by the DICOM standard.
Parameters... | 78a38044b1a3d83734b0980384be11e475f97e6f | 617,937 |
def make_query(part_id: str) -> str:
"""Creates a SPARQL query
:param part_id: biobrick identifier
:returns: SPARQL format query
"""
query = """PREFIX wd: <http://www.wikidata.org/entity/>
PREFIX wdt: <http://bioparts.wiki.opencura.com/prop/direct/>
PREFIX wikibase: <http://wikiba.... | d7f4d85d47b93268347499ca3c4091b786264191 | 617,943 |
def _scipy_distribution_positional_args_from_dict(distribution, params):
"""Helper function that returns positional arguments for a scipy distribution using a dict of parameters.
See the `cdf()` function here https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.beta.html#Methods\
to see a... | b00f38f8b9dc8530b36945c57f0b39df0f2394ca | 617,946 |
def str_point(point: tuple, precision: int = 1):
"""Return a printed tuple with precision"""
prec_str = "{:." + str(precision) + "f}"
format_str = "(" + prec_str + ", " + prec_str + ")"
x, y = point
return format_str.format(x, y) | 8a972cda236709257b4b56149f85da38ff5c80dc | 617,951 |
def feedback_calculate(answer, guess):
"""
In this function I'm handling the guess from the player or computer.
I'm returning this value as described in the article, Yet another mastermind strategy.
Its going to be a list with 2 items.
- The first number refers to the amount of 'pawns' that ar... | 541e7b5e7f9a583b6f069e66ef09a8f2e99e4e75 | 617,958 |
def combine_bboxes(bboxes, threshold=0.6):
"""
If the bboxes are close together, combine them into one.
We check this by comparing the sum of areas over the area of the combined
bbox. If it's over a threshold, we go ahead and combine.
Inputs:
bboxes - list of (x0, y0, x1, y1)
threso... | 6ab1855b5a5aae1a33ba842310d511692542c10a | 617,963 |
def calc_unsaturated_evaporation(pet, unsatStore, fieldCap, wetFrac):
""" Calculate evaporation from the unsaturated zone
Parameters
----------
pet : int or float
Potential evapotranspiration [mm day^-1]
unsatStore : int or float
Storage in the unsaturated zone [mm]
fieldCap : i... | 26164678a6b375a1cff1b07786f452f1bbb9dd50 | 617,964 |
def sanitize_filename(s):
"""Sanitizes a string so it could be used as part of a filename."""
def replace_insane(char):
if char in u' .\\/|?*<>:"' or ord(char) < 32:
return '_'
return char
return u''.join(map(replace_insane, s)).strip('_') | 0e51a478349f850ede68d0945cb44a431eb92348 | 617,965 |
def get_current_triplett(sequence, position, forward=True):
"""returns the triplett of the current position and the position within the triplett"""
if not forward:
sequence = sequence[::-1]
position = len(sequence)-position-1
triplett_position = position % 3
start_of_triplett = int(posit... | 2f5d26e9db79bbfc0163f53c358a9e3af08a39e0 | 617,967 |
def get_chains(struct):
"""Returns all chains of a Bio.PDB.Structure.Structure."""
return struct.child_list[0].child_list | f6816247dfe2ebc5fe02ae73ae25db4f4ca648dc | 617,969 |
def get_weekday(day_datetime):
"""
UTILITY FUNCTION
takes the datetime object and returns its week day.
"""
week_days = {0:'monday',
1:'tuesday',
2:'wednesday',
3:'thursday',
4:'friday',
5:'saturday',
... | 7985b1317803106221327931b4a68fc3425c40fe | 617,970 |
import requests
def get_player(id):
"""Return a snooker player's full name based on his ID."""
player = requests.get('http://api.snooker.org/', params={'p': id})
player = player.json()[0] # the data consists of a single dictionary in a list
return f"{player['FirstName']} {player['LastName']}" | ef6dbe3cb77598efdc0c4d573250b2c8ab13a9bc | 617,972 |
import struct
import socket
def ip2int(ip):
"""Convert IP as string to integer."""
return struct.unpack('!L',socket.inet_aton(ip))[0] | 322ec64c9cdb1c0ff7ee8b710d13c0f38f010bb6 | 617,974 |
def fill_mean(df):
"""Fill NaN with mean."""
df = df.fillna(df.mean().fillna(0).to_dict())
return df | fce4559ac056b8c6a8b43a8a337895ec9a81fe3c | 617,979 |
def normalise_suffix(suffix):
"""Bring suffix to lowercase without dot."""
if suffix.startswith('.'):
suffix = suffix[1:]
return suffix.lower() | c4e92087571f1789a804cc665144c71de4161316 | 617,986 |
from datetime import datetime
def pretty_date(time):
"""
Get a datetime object or a int() Epoch timestamp and return a
pretty string like 'an hour ago', 'Yesterday', '3 months ago',
'just now', etc
Based on https://stackoverflow.com/a/1551394/713980
Adapted by sven1103
"""
now = datet... | 5b56f1bb911cac34f245258d84adbc8d927b9a49 | 617,989 |
def _get_queue_arguments(rabbit_ha_queues, rabbit_queue_ttl):
"""Construct the arguments for declaring a queue.
If the rabbit_ha_queues option is set, we try to declare a mirrored queue
as described here:
http://www.rabbitmq.com/ha.html
Setting x-ha-policy to all means that the queue will be mi... | 95f25035b201636e8a04d513f8212a51a364fbc4 | 617,990 |
def get_dict_from_result(db_result):
"""
Returns a list of dictionaries where each dictionary is {field:value} pairs for one row.
"""
d, a = {}, []
for rowproxy in db_result:
# rowproxy.items() returns an array like [(field0, value0), (field1, value1)]
for column, value in rowpr... | 7045f560d85381cfc3c0a7a64dd6a28874a1bdfc | 617,998 |
def Q_014_1(n):
""" 14. 先頭からN行を出力
自然数Nをコマンドライン引数などの手段で受け取り,入力のうち先頭のN行だけを表示せよ.
"""
data = []
with open('data/hightemp.txt', 'r') as f:
data = [line.strip() for line, _ in zip(f, range(10))]
return data | 8ab5f3a4b740f8e6d525fe48358fb1926c7e8a65 | 617,999 |
import re
def skip_member(app, what, name, obj, skip, options):
"""Ignore ugly auto-generated doc strings from namedtuple."""
doc = getattr(obj, "__doc__", "") or "" # Handle when __doc__ is missing on None
is_namedtuple_docstring = bool(re.fullmatch("Alias for field number [0-9]+", doc))
return is_n... | 0d408ed2fd2263f12241d348bafc86708dc509b8 | 618,001 |
def osr_proj(input_osr):
"""Return the projection WKT of a spatial reference object
Args:
input_osr (:class:`osr.SpatialReference`): the input OSR
spatial reference
Returns:
WKT: :class:`osr.SpatialReference` in WKT format
"""
return input_osr.ExportToWkt() | fb4b9bdb33f724d9c414ce7969ac516db1e91a85 | 618,004 |
def day_lags(lags):
"""Translate day lags into 15-minute lags"""
return [l * 96 for l in lags] | e2109e87a184aff725cb7f14daa067e57f83b1c8 | 618,005 |
def deg2dmm(degrees: float, latlon: str) -> str:
"""
Convert decimal degrees to degrees decimal minutes string.
:param float degrees: degrees
:param str latlon: "lat" or "lon"
:return: degrees as dm.m formatted string
:rtype: str
"""
if not isinstance(degrees, (float, int)):
r... | 789b2d496416365386c63d8b17839a31dc160549 | 618,011 |
import torch
def log_interpolate(log_a, log_b, alpha_logit):
"""Numerically stable implementation of log(alpha * a + (1-alpha) * b)."""
log_alpha = -torch.nn.functional.softplus(torch.tensor(-alpha_logit))
log_1_minus_alpha = -torch.nn.functional.softplus(torch.tensor(alpha_logit))
y = torch.logsumexp... | b07d8e9fdfc6a002d46dd84551408aef863c3867 | 618,012 |
def _get_deterministic_value_for_table_name(table_name, max_value):
"""
For a given table_name, returns hash of the table_name limited by max_value.
"""
return hash(table_name) % max_value | 0a72625bc0086e7e9c112969254367654cf1bc27 | 618,013 |
def one_of_k_encoding_unk(x, allowable_set):
"""
taken from https://github.com/thinng/GraphDTA
function which one hot encodes x w.r.t. allowable_set with one bit reserved for elements not in allowable_set
x:
element from allowable_set
allowable_set: list
list of all known elements
... | 1ccd42a1d4f27e09baedac0e5cdf43ca8871a58a | 618,016 |
def _subtract_intervals(x, y):
"""Set difference for lists of intervals. That is, returns a list of
intervals that bounds all values bounded by x that are not also bounded by
y. x and y are expected to be in sorted order.
For example _subtract_intervals([(1, 10)], [(2, 3), (9, 15)]) would
return [(... | a22aa30dc5c12eb88f390b1b4933981366509495 | 618,017 |
def _normalize_version_number(version):
"""Turn a version representation into a tuple."""
# trim the v from a 'v2.0' or similar
try:
version = version.lstrip('v')
except AttributeError:
pass
# if it's an integer or a numeric as a string then normalize it
# to a string, this ens... | 817bb95e2465fe4fdef293a6e5bc6f87a8145e80 | 618,019 |
def sum(a, b):
"""Compute the sum of two numbers, a and b"""
return a + b | 37933d3fcb1fe9dee3b0d1d28ddf9c0c9056680c | 618,020 |
def is_iterable(value, include_maps=False, include_sets=True):
"""Returns whether value is iterable.
``include_maps``
Maps are technically iterable, defaulting to their keys, but you
commonly want to find if it is a list-like type and leave maps alone,
so this is False by default.
... | 001b504e2823992ff44fa9334600f189431f6912 | 618,027 |
from typing import Tuple
def grid_cell_to_xy(pos: int, grid_size: int = 5) -> Tuple[int, int]:
"""Converts an integer from 0-24 into an (x, y) position."""
num_cells = grid_size * grid_size - 1
if not 0 <= pos <= num_cells:
raise ValueError(f'Grid cell does not exist in grid of size {grid_size}')
x = pos ... | cc0f2d57a5c119cc5a3184642f539e69f594ecc3 | 618,028 |
def predict_tf_lite(model, image):
"""
TFLite model prediction (forward propagate)
:param model: TFLite interpreter
:param image: Input image
:return: Numpy array with logits
"""
input_details = model.get_input_details()
output_details = model.get_output_details()
model.set_tensor(in... | 6f651f602498066024aa370531f9afe2f94f8a60 | 618,029 |
def out_features(model):
"""Try to extract number of output features from the last layer of a
model. This is often useful when building encoder-decoder models or
stacking encoders and classification heads. Not sure how airtight the
logic is here so use with caution.
Parameters
----------
mo... | 990a0cf300ae3dff3e0ef0360a15ecbe39867880 | 618,030 |
import yaml
def _get_metadata(tokens):
"""Find and parse metadata (if present)."""
for token in tokens:
if token.type == "front_matter":
return yaml.safe_load(token.content)
return {} | e9298b93afff1109fa76c61e4d6030805e729f0f | 618,031 |
def elem_apply(fns, elems):
"""apply list of functions to list of elements,
element-wise"""
return map(lambda a, b: a(b), fns, elems) | 72ca363c149096d7253b3316c83e99d7e79277fe | 618,033 |
import re
def KCamelToShouty(s):
"""Convert |s| from kCamelCase or CamelCase to SHOUTY_CASE.
kFooBar -> FOO_BAR
FooBar -> FOO_BAR
FooBAR9 -> FOO_BAR9
FooBARBaz -> FOO_BAR_BAZ
"""
if not re.match(r'^k?([A-Z][^A-Z]+|[A-Z0-9]+)+$', s):
return s
# Strip the leading k.
s = re.sub(r'^k', '', s)
# A... | 7209ebeb4c94292b74da41b02c6e32c18d8fefe4 | 618,035 |
def merge_slow_csv_and_eddypro(stationName,slow_df,eddy_df, mergedCsvOutDir):
"""Merge slow data and EddyPro data DataFrames
Parameters
----------
stationName: name of the station
slow_df: pandas DataFrame that contains all slow variables for the entire
measurement period
eddy_df: panda... | 7d6634251226aa9613b9e76280a5d12684e74009 | 618,036 |
def merge_fast_two(one, two):
""" Merge two dictionaries performantly into an instance of “dict”.
Based on this extremely beloved SO answer:
https://stackoverflow.com/a/26853961/298171
"""
# N.B. the dict-expanded operands appear here in the opposite order
# from their posit... | 9fefcbf21ba1d5ea5966d93b9f8df66a9a59f88f | 618,039 |
def transform_y(f_x_y, xf_and_dxf_dyprime):
"""Transform f_x_y(x,y) into f_x_yprime(x,yprime)
xf is the inverse transformation: from yprime to y
y = xf(yprime, *xf_params)
dxf_dyprime is its derivative with respect to yprime"""
def f_x_yprime(x,yprime,p):
xf, dxf_dyprime = xf_and_dxf_dyprime(yprime, p)
return ... | 474b5083ecfe4d4b38e2a91c4ddf26e9d7a0bbdc | 618,042 |
def get_all_env_names(envs):
"""Returns set of all env names from envs."""
result = set()
for e in envs.values():
result.update(e.keys())
return result | 2aab986e98d70afe3124690922f8be17c0179865 | 618,043 |
def compute_optimal_action_with_environment_dynamics(
observation, environment_dynamics):
"""Computes the optimal action using the environment dynamics.
Args:
observation: a (possibly batched) observation.
environment_dynamics: environment dynamics object (an instance of
`non_stationary_stochasti... | c2d5177549a156e393f0fe132c3b6fee5819f796 | 618,045 |
import struct
def pack_long(l) :
"""pack_long(l)
returns big-endian representation of unsigned long integer"""
arr = []
while l > 0 :
arr.insert(0, struct.pack("B", l & 0xff))
l >>= 8
return ''.join(arr) | fec7da722bc4934f2e3a21149d7b76820f4f260b | 618,047 |
def create_hash(key, size): # O(1)
"""
Creates a hash by taking the first character in a string, getting its
ASCII value and apply a modular function to the provided size
>>> create_hash(42, 5)
4
>>> create_hash(42, 4)
0
>>> create_hash(122.12, 4)... | 0a14356a1df16f5386997cb1b1d7f3456dfcab95 | 618,051 |
def hamming(s, t):
"""
Calculate the Hamming distance between two strings. From Wikipedia article: Iterative with two matrix rows.
:param s: string 1
:type s: str
:param t: string 2
:type s: str
:return: Hamming distance
:rtype: float
"""
if len(s) != len(t):
raise Value... | 979b45f76b806411cdc0d226ae186cdbf11bdb63 | 618,053 |
def getStr(bytes_arr):
"""Create string from ASCIIZ string buffer"""
strng = ""
for value in bytes_arr:
if value != 0:
strng = strng + chr(value)
else:
break
return strng | a323212e6f7c9f32558cc5837421d8c19bd564e6 | 618,059 |
def modulo11(base):
"""Calcula o dígito verificador (DV) para o argumento usando "Módulo 11".
:param str base: String contendo os dígitos sobre os quais o DV será
calculado, assumindo que o DV não está incluído no argumento.
:return: O dígito verificador calculado.
:rtype: int
"""
pes... | 1e766acd55edb5f52320ab43af1e9befff95f08c | 618,061 |
def get_parse_dates(file):
"""Return a list of columns for which dates have to be parsed."""
parse_dates = [
'click_time',
'attributed_time'
]
if 'test' in file:
parse_dates.remove('attributed_time')
return parse_dates | d3475f6204924935583f15bff42d3dcc281f782c | 618,063 |
def huffman_decoding(data, root):
"""Decodes data using Huffman Coding compression algorithm.
Args:
data: A str in binary to be encoded using the provided Huffman Tree
root: A HuffmanNode object representing the root node of a Huffman Tree
to be used to decode the provided data
... | 345f7693342037b86dbb9f803c7bbbd07fa6945f | 618,064 |
def force_column(arr):
"""Turns 1d numpy array into an (N, 1) shaped column"""
return arr.reshape((len(arr), 1)) | 932761ffd044d85d94138784fc52dd0e55f1b692 | 618,065 |
import re
def dict_from_regex_match(pattern, input_, type_dispatcher=None):
"""Return a dict from matching `pattern` to `input_`.
If match failed, returns None.
Parameters
----------
pattern : str, `re.Pattern`
The regex that matches to the `input_`.
input_ : str
The string ... | ffccfaf811bdbb586eace4e0bdb1bf082647b4f1 | 618,067 |
def getUserUpdateTuple(user):
"""
Converts a user object to a tuple that can be given to an SQL update query
@param user: The user object
@return: The tuple of values
"""
tuple = (
user.name,
user.telegram_firstName,
user.expectedMessageType,
str(user.tempParams),
user.wantsMenu,
user.course,
user.w... | ce80066c04c856b1b82b47671b482644ebcebbe8 | 618,068 |
def param_dict_from_output(output_line):
"""
Generate a parameter dictionary with enough variables to correctly estimate the rates of
reactions.
:param output_line: (pandas series) any row from the relevant UCLCHEM output
"""
param_dict={
"initialDens":output_line["Density"],
"initialTemp":output_line["gasT... | e48c32b19ad720126a4eb2aed7ba6cefcf8e75e4 | 618,069 |
import codecs
def output(counter, top_n=None, output_counts=True):
"""Prints a counter with optional formatting
:param counter: A Counter object to print
:param top_n: The top N most common terms to print (default print all)
:param output_counts: If true, prints term followed by count, separated by ta... | a71e1e5ab99bd56314f5a44c9c776602b12132fd | 618,070 |
import math
def binary_search(t, x, start, end):
"""Find the index i of t with t[i] <= x <= t[i+1].
Under the assumption that t is nondecreasing t[j] <= t[j+1]."""
mid = math.floor((start + end) / 2)
if ((start - end) == 0) or ((t[mid] <= x) and (x < t[mid+1])):
return mid
elif t[mid] <= x... | 78d69a1971e129fc989fc8c99f7b139cb36843cc | 618,072 |
def validator(value):
""" Trivial validator. """
return value | 9b983402862c50511636f7b220b2a5c6598cf88d | 618,073 |
def _xcom_pull(task, key="return_value"):
"""Generates a Jinja template that pulls an XCom variable for a task.
XCom allows data to be shared between different tasks.
Args:
task: The task instance.
key: The XCom key to retrieve the value for. (default: return_value)
Returns:
The Jinja template re... | 4b3e5b5b4c06537418b411de20aa018ef93665ce | 618,075 |
def get_objects(resource, bucket_name, prefix=""):
"""List objects inside a bucket"""
client = resource.meta.client
next_token = ""
content = []
directory = []
add_list = lambda keys, values: keys.extend(values) if values is not None else None
while True:
response = client.list_obje... | 6cdf8fa079417320379f21e94224821ee4b9f225 | 618,076 |
def echo(value):
"""
Returns the given argument.
:param value: argument to be returned
:return: the given argument
>>> echo(0)
0
>>> [echo(x) for x in range(3)]
[0, 1, 2]
"""
return value | 500a4de456d88cd3b14bdaa61f95e9d747ccbe86 | 618,077 |
def update_chr_prefix(regions, mode='remove'):
"""
Add or remove the (annoying) 'chr' string from specified regions.
The method will automatically detect regions that don't need to be
updated and will return them unchanged.
Parameters
----------
regions : str or list
One or more re... | 65d4f23989dc91b4604caa3543feb3e29ef05034 | 618,080 |
import json
import random
def get_random_user(in_file):
""" Open up user input json and grab a random user from the specified users """
with open(in_file) as data_file:
data = json.load(data_file)
users = data["dm_users"]
return random.choice(users) | 2c02ddfd5b494672e7c958dca97e316a9b6e5e03 | 618,084 |
from math import floor, ceil
def truncate(value, args='10'):
"""
Truncates a string after a certain number of characters.
final_len: Number of characters the final returned value should be,
after the truncate and string is concatenated.
str: the string that will be concatenated to the truncated ... | e09d11ba6845a0e2ec80517720fbf76e612a7943 | 618,085 |
def getVersionString(plist, key=None):
"""Gets a version string from the plist.
If a key is explictly specified, the value of that key is
returned without modification, or an empty string if the
key does not exist.
If key is not specified:
if there's a valid CFBundleShortVersionString, returns... | cb92f652eda0bbcf9c908f1c96328ff13b9a0f8a | 618,086 |
def hexdump(data, saddr=0, compress=True, length=16, sep='.'):
""" Return string array in hex dump.format
:param data: {List} The data array of {Bytes}
:param saddr: {Int} Absolute Start Address
:param compress: {Bool} Compressed output (remove duplicated content, rows)
:param length: {Int... | a0e72a7201ea6a02dd81544354f9cbaad4b714d0 | 618,088 |
def ans_entity_full(ner_tag, new_ans):
"""Returns a function that yields new_ans iff every token has |ner_tag|."""
def func(a, tokens, q, **kwargs):
for t in tokens:
if t['ner'] != ner_tag: return None
return new_ans
return func | 058b97d8fb653fe5d32dda9529874dcf97ca2939 | 618,092 |
def split_df(df, split_col, split_vals):
"""
takes a data frame and splits is according to the values in the specified column, the number of returned data frames
will be equal to the number of passed split values
:param df: the data frame that shall be splitted
:param split_col: defines the column b... | 0128ba962d478ec9178ccefbf547b1ac866f0f23 | 618,093 |
import configparser
from pathlib import Path
def get_version() -> str:
"""
Gets the current version from the setup.cfg file
"""
config = configparser.ConfigParser()
path = Path(__file__).parent.parent / "setup.cfg"
config.read(path)
return str(config["metadata"]["version"]) | f0a351cdefb417fba875dd04c8a1055e9f13e2c8 | 618,094 |
def present(span):
"""Accepts a spaCy Span and returns True if the text contains non-whitespace characters."""
return span and span.text.strip() | b822e6053ba01135be6f5c703d5dd1a3a33b4588 | 618,095 |
def template_function(message: str, show: bool = True) -> str:
"""Return a message if `show` is True.
Args:
message (str): The message to be returned.
show (bool): Flag to return the message.
Return:
The message. Is show is True, empty string otherwise.
"""
return message ... | bf84d876d133ff1a7ff2ab31d863ae5a527f8e0d | 618,103 |
def isiterable(obj):
"""
Test if the argument is an iterable.
:param obj: Object
:type obj: any
:rtype: boolean
"""
try:
iter(obj)
except TypeError:
return False
return True | 394fb9fdb4a18bf558b7b748896ffe9f3d0203eb | 618,107 |
def flatten(nested_list: list) -> list:
"""
Flatten an input list which could have a hierarchical multi nested list
:param nested_list: The source list
:return: The flatten list
"""
if len(nested_list) == 0:
return []
if type(nested_list[0]) is list:
return flatten(nested_lis... | 18d36006f6a2a18fb8840960f0fef4de431714ba | 618,109 |
def build_object_spec(client_factory, root_folder, traversal_specs):
"""Builds the object Spec.
:param client_factory: Factory to get API input specs
:param root_folder: Root folder reference as the starting point for
traversal
:param traversal_specs: filter specs required for t... | 69f36c46281364f3d8ab4cbd4310d87c9517c780 | 618,110 |
def get_filenames_and_urls(url_df, method_list=None, organ_list=None):
"""Takes in dataframe and returns corresponding filename(s) and url(s).
Takes in dataframe (with sample information stored), a list of methods,
and a list of organs.
Returns filenames and figshare URLs associated with inputs.
If... | 76364d5e0f8858ff00989fd6534a232f21672be8 | 618,111 |
def remSpecialChar(text):
"""removes special LaTeX/BibTeX characters from a string"""
text = text.replace("{","").replace("}","")
text = text.replace("\\","")
text = text.replace("&","")
return text | 66d00cbfd2be8df5f19086c3ac06c68859c76dca | 618,114 |
def read_file(filename: str) -> bytes:
"""
Opens a file, reads its contents as bytes, and returns it.
:param filename: A filename
:return: The bytes in the file
:raises IOError: upon failure
"""
with open(filename, 'rb') as file:
return file.read() | 75dd666bd973de5671b6f456bced9ff072d886ff | 618,116 |
import json
def get_owner_ids(json_filename):
"""Return a set with all the owner IDs in posts from ‘json_filename’."""
with open(json_filename, 'r', newline='') as json_file:
owner_ids = set()
for line in json_file:
json_dict = json.loads(line)['_node']
owner_ids.add(in... | b711a0ade24332789a3b6cd64f420ecf414253c5 | 618,117 |
def check_word_lengths(start_word, stop_word):
"""Check if the both words are of equal length.
:param start_word: Starting word
:param stop_word: Stopping word
:returns: True if lengths are equal, False otherwise
:rtype: bool
"""
if len(start_word) != len(stop_word):
print("Words {... | 714578f8ac32c0ed478ce46412492d2eea776af9 | 618,118 |
import timeit
def benchmark_it(func, repeat=3, number=1000):
"""
Benchmark <func> by taking the shortest time of <repeat==3> test runs.
"""
#print(s.ljust(20), end=" ")
res = func()
print(str(func) + ' took {:>5.0f} ms'.format(min(timeit.repeat(func,
r... | 9b59a517d1df0738c1102b8755017812fb67dbb3 | 618,119 |
def dir_Gen(row_num, dataframe):
"""
Gets the directory of the data from the remarks column
"""
row = dataframe.loc[row_num]
directions = row['remarks']
directionsList = [x.strip() for x in directions.split(',')[:-1]]
return directionsList | 55435cfbe5a394037e9998487c7548dd196a1ea1 | 618,121 |
def get_user_id(conn, user_name):
"""Get ID of a user based on user name.
Must be an exact match. Case sensitive.
Parameters
----------
conn : ``omero.gateway.BlitzGateway`` object
OMERO connection.
user_name : str
Name of the user for which an ID is to be returned.
Return... | 4c29585502477d123ec5a8df315de374ebf9badc | 618,122 |
from typing import Any
def shape_str(element_type, shape):
"""Return human-friendly description of array shape."""
dim_0 = "?" if shape[0] in (Any, None) else shape[0]
sub_shape = element_type if len(shape) == 1 else shape_str(element_type, shape[1:])
return "[{0} x {1}]".format(dim_0, sub_shape) | d2732143b5c13a92f675666604559c405f3271a3 | 618,124 |
def _get_image_and_label_from_entry(entry):
""" Get the image's path and its label from a dataset entry.
Args:
entry: string containing the path to a image and its label.
Return:
file_path: string with the path where a image is stored.
label: int representing the... | 67b5fa11c8538ea038181f67a50d51312af93de3 | 618,125 |
def format_coords(df, col_to_convert, col_new_name):
"""
Takes col_to_convert and creates a list of a set of strings that
contain coordinates in an integer form.
Parameters
----------
df : df
pd.DataFrame that contains Neotoma information.
col_to_convert : string
Name of co... | 2c1c8591bdc968066603021bb4504fe17341edfd | 618,126 |
def find_neighbors(ID, neighboring_matrix):
"""Filters all polygons which are actually neighbors to given polygon.
Args:
ID (int): ID of specific polygon under consideration.
neighboring_matrix (dataframe): output from neighboring_polys().
Returns:
dataframe: dataframe containig ID... | d70d8858025c4081eb5cac53b4814951c6c694c8 | 618,127 |
import time
def try_with_times(times, interval, sleep_first, logger, tag, func, *args, **kwargs):
"""
Try a function with certain chances and retry intervals
:param times: Amount of chances
:param interval: Interval between retries
:param logger: Logger to log information
:param tag: Tag of th... | 11c12c0ac0a9068c7c200ad9efbdcc0ed3d711be | 618,129 |
def camera_to_world_frame(P, R, T):
""" Inverse of world_to_camera_frame
Args
P: Nx3 points in camera coordinates
R: 3x3 Camera rotation matrix
T: 3x1 Camera translation parameters
Returns
X_cam: Nx3 points in world coordinates
"""
assert len(P.shape) == 2
assert P.shap... | 693962a076cfb8b6644d738d5b270b3caaa89eba | 618,131 |
def enforce_ordered_labels(labels):
"""Transform the label sequence to an ordered form.
This is the same type of label sequence used in the paper "Discriminative
neural clustering for speaker diarisation". This makes the label sequence
permutation invariant.
Args:
labels: an array of integers
Returns... | 870d7326469ae2496623358713928cd64e580a94 | 618,133 |
from typing import List
from typing import Tuple
def check_letter_in_word(secret_word: str, user_guess: str, current_word: str,
wrong_guesses: List[str]) -> Tuple[str, List[str]]:
"""Check if the user's guess is in the word.
Args:
secret_word (str): The secret word chosen by ... | 68821440a66af3d06d3d89af06b88efd4cc0db9f | 618,135 |
def result_to_str(result):
"""Return a string based on the attributes of the supplied Result.
Usage example:
>>> result_to_str(Result('error', 'nullPointer', 'my.cpp', [1], 'bad'))
'my.cpp (1): (error) nullPointer - bad'
:error: an Result, probably from parse_output()
:returns: a strin... | 61c4c6884db64f4a33452b57ac386f714d3ec0a1 | 618,137 |
def make_false(unused_value):
"""Makes a False boolean value lambda."""
return False | 0d5451c8f58575e086a259da0fd17bff34f76292 | 618,145 |
def knot2mph(k):
"""
Converts knots to miles per hour.
"""
if k == None:
return None
return k * 1.15078 | f5cc35eae7ee2b7e893b753e2a16daa2ae4e4212 | 618,146 |
import math
def _distance_at_cutoff(variance, similarity_cutoff):
"""Return distance that gives similarity_cutoff for a gaussian kernel with given variance."""
return math.sqrt(
variance * math.log(1.0 / similarity_cutoff)) | 9e585d537a15e22064f1317cb6b66769da1604db | 618,148 |
def round_decimals(dataframe, decimals=3):
"""
Rounds the decimals in teh dataframe to the
given number of decimal places.
:param dataframe: a pandas dataframe with float
values in a column.
:param decimals: an integer
:return: return a dataframe with float values
rounded to 3 decimals.
... | bf1b76ef199e7c919f698c44a2302bec8597e4e6 | 618,153 |
from typing import Counter
def get_class_weights2(y, smooth_factor=0):
"""
Returns the normalized weights for each class based on the frequencies of the samples
:param smooth_factor: factor that smooths extremely uneven weights
:param y: list of true labels (the labels must be hashable)
:return: d... | 27526ac76f362664a37026b123267849ffa010b9 | 618,156 |
def thermalcond(x, So, Gb):
"""
Calculate thermal conductivity of wood at moisture content, volumetric
shrinkage, and basic specific gravity.
Example:
k = thermalcond(12, 12.3, 0.54)
Inputs:
x = moisture content, %
So = volumetric shrinkage, Table 4-3, %
Gb = basic s... | c7ec643f9ea26edf14bb167a798691a051de4d6e | 618,159 |
def single_index_function(index):
"""Creates a function that returns an index for every single wavelength
Arg:
index(complex): the index of refraction to be returned
Returns:
callable: returns the complex index for an argument of any float
"""
get_index = lambda wavelengths: index
... | 883b2b22ad3b6f043341f93a84fefdc7a105efb3 | 618,160 |
def extract_authors(elem):
"""extract the authors from an xml element
Args:
elem (xml): xml element
Returns:
tuple: containing a dictionary with authors
"""
authors = list(elem)
authors = {"Authors":
", ".join(["{} {}"
.format((((author... | 77cb6fba62b835ac9ad0f13ef21910de6cdced94 | 618,161 |
def classify_line(features, model, l_encoder=None):
"""
Classifies the features based on the given model.
If a label encoder is specified, it reverses the encoding of the label
:param features: a vector of features
:param model: a Classification Model
:param l_encoder: a LabelEncoder
:return... | 6c77424eb3e7f4e972527cf9f23d1d133e66bf98 | 618,162 |
def rho2_rho1(M1, gamma):
"""Density ratio across a normal shock (eq. 3.53)
:param <float> M1: Mach # before the shock
:param <float> gamma: Specific heat ratio
:return <float> Density ratio r2/r1
"""
n1 = (gamma + 1.0) * M1 ** 2
d1 = 2.0 + (gamma - 1.0) * M1 ** 2
return n1 / d1 | d61eaee3d66e5478a5db93bde784c510ce9137a4 | 618,164 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.