content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from typing import Collection
from typing import List
def lowercase_all(toks: Collection[str]) -> List[str]:
"""
Lowercase all English words;
English words in Thai texts don't usually have nuances of capitalization.
"""
return [tok.lower() for tok in toks] | 2fe248b94d727ce2ee3c58f53db8339bdfcde163 | 595,221 |
import re
def parse_url_to_topic(method, route):
"""
Transforms a URL to a topic.
`GET /bar/{id}` -> `get.bar.*`
`POST /bar/{id}` -> `post.bar.*`
`GET /foo/bar/{id}/baz` -? `get.foo.bar.*.baz`
Possible gotchas
`GET /foo/{id}` -> `get.foo.*`
`GET /foo/{id}:action` -> `get.foo.*`
... | 15cfacdb8071cfea694cbfd8d38f2cb12fd65ab5 | 595,232 |
def make_album(artist_name, album_title, num_of_songs = None):
"""Builds a dictionary describing a music album"""
album = {'Artist': artist_name.title(), 'Album': album_title.title()}
if num_of_songs:
album['num_of_songs'] = num_of_songs
return album | e9b8841b1fac6315b9e0ab6f12fc5f8b285640f3 | 595,235 |
import io
import gzip
def decompress_block(byte_stream):
"""Interpret a byte string as a BGZF block and return its decompressed
contents.
BGZF format is gunzip compatible, so the gzip module can perform the
decompression.
Args:
byte_stream (bytes): Complete BGZF block to be decompressed.... | 4ce6c65f79055ac12b4c4b98cb084d960c4959e1 | 595,236 |
def arithmetic_series_dp(n):
"""Arithmetic series by bottom-up DP.
Time complexity: O(n).
Space complexity: O(n)
"""
T = [0 for _ in range(n + 1)]
T[0] = 0
T[1] = 1
for k in range(2, n + 1):
T[k] = k + T[k - 1]
return T[n] | af7a9c1aa94f359bcb6745304409aeaa4dac6951 | 595,237 |
def get_tier_level(files: str) -> str:
"""
Retrieves the RHCS QE tier level based on the suite path or filename.
The argument contains "::" as a separate for multiple test suite execution. The
understanding in both the cases is that, the qe stage is provided at the starting
of the filename or direc... | b7030b110b99d93ee6eef79e69d0db7242060240 | 595,240 |
def normalize_stopcode(code):
"""
Make stopcode a four digit, zero padded string
:param code: raw cod
:return: normalized code
"""
return format(int(code), '04') | 589ebcef841df94e93f0505379c146988db71fea | 595,244 |
def extract_mom(state):
"""Helper function to extract momentum from chain state."""
return state.mom | 1883ea3be1b9b923b8abbe87f570971f3bebfb6c | 595,246 |
from unittest.mock import call
def make_expected_calls(example_count, clean_file_count, total_file_count, lines):
"""Make a list of calls expected to be made by the report function."""
return [
call(f"Total number of examples: {example_count}.\n"),
call(f"Total number of cleaned files: {clean_... | 64b6e6e195ec47271a78137ebd875168c45f189c | 595,247 |
import time
def is_token_expired(token_info):
"""Check if token is expired."""
return token_info['expires_at'] - int(time.time()) < 60*60 | 88d76fffbd794c26359c9d12e8495ef25a6bea19 | 595,249 |
def find_longest(arr):
""" Find the number with the most digits.
If two numbers in the argument array have the same number of digits,
return the first one in the array.
"""
return max(arr, key=lambda x: len(str(x))) | 340bfd92ab2e88bbec071ef0e9ea584cc4c18cf0 | 595,250 |
def make_tbl_dict( driver, xp_k, xp_v, k_word='Player' ):
"""
input
driver: Selenium sebdriver object
xp_k: xpath for table to scrape; will use as dictionary keys
xp_v: xpath for table to scrape; will use as dictionary vals
output:
dictionary containing scraped table
-------------------... | 51e0fee99d7acf6c21cae2c8c0d134b0a616938e | 595,252 |
def clean_user_inputs(queries):
"""
Convert user inputs to match the api request input.
Args:
queries (string): country/us state codes
Returns:
string: lowercase codes and replace underscore to dash
"""
queries = queries.lower()
queries = queries.replace('_', '-')
retur... | 07d9d203cc514ca51e96682ef3a6bdb530391e8d | 595,257 |
import struct
def pack_compact_int(i):
""" See
https://bitcoin.org/en/developer-reference#compactsize-unsigned-integers
Args:
i (int): Integer to be serialized.
Returns:
b (bytes): Serialized bytes corresponding to i.
"""
if i < 0xfd:
return struct.pack('<B', i)
e... | ff4d44b4c54df3ae062713dc00c53eca0f9309c6 | 595,258 |
def relationship_diff(current_items, new_items):
"""
To be used in POST and PUT/PATCH relationship requests, as, by JSON API specs,
in update requests, the 'remove' items' relationships would be deleted, and the
'add' would be added, while for create requests, only the 'add' would be added.
:param ... | cb41827ce630752ad505ef1e84b1cc3ee6f17b33 | 595,259 |
def ellipsize(text, limit, ellipsis=".."):
"""Returns text ellipsized if beyond limit."""
if limit <= 0 or len(text) < limit:
return text
return text[:max(0, limit - len(ellipsis))] + ellipsis | 1ebe5936ca93230836ec46eebfe1e9fbf1a04e39 | 595,265 |
import hashlib
def get_md5_sums(file_bytes):
""" Hashes bytes with the MD5 algorithm """
return hashlib.md5(file_bytes).hexdigest() | 0dbdebac3f0042d8174c90b9f4054b7c39a96877 | 595,267 |
def sequence_recovery(native_struct,designed_struct):
"""calculate percent sequence recovery between a native and designed struct"""
native_residues = native_struct.get_residues()
designed_residues = designed_struct.get_residues()
total = 0.0;
recovered = 0.0;
for native,designed in zip(native_residues,designed_r... | 2b6541dd25406a1569e510f1ea59ca6bd6b14e25 | 595,268 |
def arrange_lyrics(arrangement, song_data):
"""
Returns the lyrics of a song arranged by the song data.
:param arrangement: A list of strings describing the arrangement of the
lyrics. We do not do checking in this function, so the
type must be correct.
:t... | 46b4dbfa436fe27aec8282b1c4ce4aab527bb74a | 595,272 |
def flatten_xml_string(xml_string):
"""
Flatten the xml string so that the output is in one line and without spaces/tabs etc.
This is because otherwise the request is not valid and gets rejected.
"""
return ''.join([line.strip() for line in xml_string.split('\n')]) | 8a35c03b972b6d8bd6a3a1686196703ff4b6a9ae | 595,279 |
import torch
def central_grady(image):
"""Compute central vertical gradient.
Assumes input is a 4D tensor with dimensions (batch, channels, rows, cols).
"""
assert(len(image.shape) == 4)
padder = torch.nn.ReplicationPad2d((0, 0, 1, 1))
padded_image = padder(image)
gy = 0.5 * (padded_image... | 5d484c15a0d347cea4fce9c1e7c5cd487224d308 | 595,283 |
def is_jac_elem(val):
"""Test if value is jac element"""
return type(val) == str and val.startswith("jac:uuid:") | 581fb5ba7e8a4a53b5333b0edaab43c74709f949 | 595,284 |
def floatEq(f1,f2,tolerance=.00001):
"""Return true iff f1 is very close to f2."""
if min(f1, f2) != 0:
return abs(f1-f2)/min(f1,f2) < tolerance
else:
return abs(f1-f2) < .00001 | 0ebf1ca89bc4784ca21a0b27b6ca4ecf3b32942d | 595,288 |
def ixp_sessions(value, family=0):
"""
Returns a queryset of IXP peering sessions.
If family is set to 4 or 6, only the sessions matching the IP address
family will be returned. If family is not set all sessions matching all
address families will be returned.
"""
if not hasattr(value, "get_... | f03d82b66877f32200d4c8be8968335b4cf93ad1 | 595,290 |
def _get_padding(alignment, current_size, next_element_size):
"""Calculate number of padding bytes required to get next element in
the correct alignment
"""
if alignment == 1:
return 0 # Always aligned
elem_size = min(alignment, next_element_size)
remainder = current_size % elem_size
... | 771a02a4f3363653e87f0549834784037c7cdc98 | 595,291 |
def valid_iyr(iyr):
"""iyr (Issue Year) - four digits; at least 2010 and at most 2020."""
if len(iyr) == 4 and int(iyr) >= 2010 and int(iyr) <= 2020:
return True
else:
return False | 807047f73cd60383be246e158aa5f37740d484d1 | 595,292 |
def float_f(f):
"""Formats a float for printing to std out."""
return '{:.0f}'.format(f) | 00a7cb9ad2e39a6fa3bc617d565bf2ad1c29784b | 595,293 |
import random
def get_random_sap(h5_file):
"""
Gete a random sap of a specified h5 file
h5_file (h5py.File): The file to be prcoessed
"""
saps = list(h5_file['saps'].keys())
sap = random.choice(saps)
return sap | 6946710b4709212f25e8c3ab0e9948804cf84e92 | 595,295 |
import math
def pad_amounts(array_length, stride, kern_length):
"""Amount of padding to be applied to a 1D array.
Matches TensorFlow's conv2d padding, when padding='SAME'.
"""
num_patches = math.ceil(array_length / stride)
target_length = (num_patches - 1) * stride + kern_length
padding_amount... | 2dc769c625557b6829e7652f94e0af84c3c8cc7f | 595,297 |
import random
def get_random_mac(base_mac):
"""Get a random MAC address string of the specified base format.
Any part that is '00' will be randomized
:param base_mac: Base MAC address represented by an array of 6 strings/int
:returns: The MAC address string.
"""
return ':'.join(
"{:... | 8852d85f19492e176fc5056767670e60f45d5b36 | 595,305 |
def is_better(to_be_compared, val):
"""
Check that two to_be_compared is higher than val (5% tolerance).
"""
if val == 0:
return to_be_compared == 0
else:
return to_be_compared / val < 0.95 | 1578bebfa2f15b7e8289f85188ad04d9327c8c2d | 595,306 |
def join(*args):
"""Create pipe separated string."""
return "|".join(str(a) for a in args) | 77ba83d29086b085e93c9f701ec146b6c13ed4cd | 595,307 |
import itertools
def matrix_prod_tee(n):
"""Generates a square matrix: n x n
using itertools.product()"""
iterables = itertools.tee(range(1, n + 1), 2)
return (
(i, j, i * j)
for i, j in itertools.product(*iterables)
) | 1d07c201e95aa7857550056f40b3d03a37bfbb04 | 595,312 |
def pvc_has_been_rejected(pvc):
"""Return True if a persistent volume claim has a rejected annotation."""
annotations = pvc.metadata.annotations
return (
annotations and
annotations.get('efs-stunnel.gnuthought.com/rejected','') == 'true'
) | 31a5bd7e9658eaf38d26e04a70b22ee93848dd64 | 595,313 |
def get_slope_b(x_start, x_stop, y_start, y_stop):
"""
Computes the slope and intersection point on the y-axis of line specified by
start and stop point. The format of the line is: y = slope * x + b
Parameters
----------
x_start : float
Start point on x-axis.
x_stop : float
... | a4e4c7b0dc1e091f45b6a5050dac5f63cd974632 | 595,317 |
def queryset_app_name(value):
"""
Return the app verbose name of a queryset
"""
return value.model._meta.app_config.verbose_name | b7ef932e962c6a78ed99b2123159a21de643f909 | 595,318 |
def twoDigit(num):
""" Will return a string representation of the num with 2 digits. e.g. 6 => 06 """
if num < 10:
return "0" + str(num)
return str(num) | 3887df3d8e0b79185642082ce82ebd72da23aa0b | 595,319 |
def _get_leaf_vals(root_node):
"""Get leaf values in deep-to-shallow, left-to-right order."""
all_leaves = []
layer = [root_node]
while layer:
next_layer = []
for node in layer:
if not node.children:
all_leaves.append(node)
else:
ne... | 825fd84936711147f1a51343564671474d85e535 | 595,320 |
def parse_block_scalar_empty_line(IndentTokenClass, ContentTokenClass):
"""Process an empty line in a block scalar."""
def callback(lexer, match, context):
text = match.group()
if (context.block_scalar_indent is None or
len(text) <= context.block_scalar_indent):
if te... | 82ad376fe4b19a4633889b64a21d8a06ebbccba2 | 595,323 |
import collections
def array2ntpl(arr):
"""Convert an array representation of a namedtuple back to a namedtuple.
Convert a :class:`numpy.ndarray` object constructed by
:func:`ntpl2array` back to the original
:func:`collections.namedtuple` representation.
Parameters
----------
arr : ndarr... | 2f7db3036e4dfa1b39ca85d044a967cdcff93b02 | 595,326 |
def find_high_frequency_categories(s, min_frequency=0.02, n_max=None):
"""Find categories with high frequency.
:param float min_frequency:
the minimum frequency to keep
:param Optional[int] n_max:
if given keep at most ``n_max`` categories. If more are present after
filtering for m... | ce2cd9868953932ec72b7b17f6657d84f14f8181 | 595,327 |
from typing import Union
from typing import List
from pathlib import Path
def new_dirs(dir_paths: Union[str, List[str]]) -> List[str]:
"""
初始化文件夹,检验文件夹的存在状态,并返回准备好的文件夹路径。
Args:
dir_paths: 字符串类型的全路径,可以为单个路径,也可以放入列表中,批量创建。
Returns:
包含创建的文件夹路径字符串的list
"""
if isinstance(dir_paths... | 2a0a819a6771b22ee7ae4170cb0b42a8e1f59b52 | 595,329 |
def parse_unit(unit):
"""Parse a unit string
Parameters
----------
unit : str
String describing a unit (e.g., 'mm')
Returns
-------
factor : float
Factor that relates the base unit to the parsed unit.
E.g., `parse_unit('mm')[0] -> 1e-3`
baseunit : str
Ph... | 0ada612f10ac515651d6713e4a30cd6be4341b0a | 595,331 |
import functools
import time
def eventually(timeout: float, interval: float, errors: set={AssertionError}):
"""
@eventually runs a test until all assertions are satisfied or a timeout is reached.
:param timeout: time until the test fails
:param interval: time between attempts of the test
:param er... | 3b9e9113ac0b07b6f090f342f7ed398ae9a5e9d6 | 595,332 |
def find_tag_column_pairs(tags):
"""
Creates a dict, where k = the user-created tag names, like 'life',
v = db column names, like 'tag1'}
"""
all_tag_columns = {}
counter = 0
for tag in tags:
counter += 1
all_tag_columns[str(tag)] = "tag" + str(counter)
return all_tag_co... | 80984628b3f2daf2fb761a5e958452d5e5521efd | 595,337 |
def str222tuples( string ):
"""Converts string into two 2-tuples."""
vals = string.split()
for vv in range( len(vals) ):
vals[vv] = int( vals[vv].strip( '(), ' ) )
return (vals[0],vals[1]), (vals[2],vals[3]) | 6da119c1cf31bf1699c6c977c4bfbb17869f020b | 595,338 |
def parse_sample_temperatures(arguments, samples):
"""Parse inverse temperatures for MCMC simulation
with parallel-tempering.
Parameters
----------
arguments
Parsed arguments containing the "mcmc_temperatures"
argument and optionally the "sample_mcmc_temperatures"
argument.
... | 71a004956939661bf440345949b95ffc9186a763 | 595,341 |
def clean_str(text):
"""
Remove unnecessary characters from text (in order to save it as valid file name)
"""
replace_strs = ["\n", " ", ":", ".", ",", "/"]
for r in replace_strs:
text = text.replace(r, "_")
text = text.replace('%', "perc")
return text | 34e4c6f2938a56606c848520ac7f47d1c4997982 | 595,343 |
def data_description(hf, var):
"""data_description(hf, var)
Returns the description of an output variable. If the
description is empty, returns the variable name.
Args:
hf: An open HDF5 filehandle or a string containing the HDF5
filename to use.
var: Output variable name.
"""
... | 86529659d0aafefab56f94e9ccbfe5a1c1c51de6 | 595,345 |
import re
def url_check(url):
"""Checks the validity of the url required in the connection object and
returns a validated url."""
regex = r'^https?://.+$'
match = re.search(regex, url)
api_index = url.find('/api')
if match is None:
msg = ("Please check the validity of the base_url par... | c36dd753daeb88f72e15a6b2d7a39c56dfc8f89c | 595,347 |
import gzip
def gzip_decode(data, out=None):
"""Decompress GZIP."""
return gzip.decompress(data) | fea343e5a0dcc45a02bee828e5cbcefc19345255 | 595,350 |
def _to_line(title_dict, margin=1):
"""Convert to line.
Convert to ruled line from each title info.
Args:
title_dict (dict): Each title info.
margin (int): Margin of each table column.
Returns:
str: Ruled line.
"""
line = '+'
for value in title_dict.values():
... | 28b0dd2db2c1c54d29e9c991ab776f10a19019c8 | 595,351 |
def safe_div(dividend, divisor, divide_by_zero_value=0):
"""Return the result of division, allowing the divisor to be zero."""
return dividend / divisor if divisor != 0 else divide_by_zero_value | 862acb7487f59427c5e8d73f13428ac52cab0815 | 595,353 |
def N(u, dfs_data):
"""The N(u) function used in the paper."""
return dfs_data['N_u_lookup'][u] | 11cd370fed0a114e218d92cb996c47b41199d36e | 595,366 |
def _inflate_dotted(input_dict):
"""Convert flat dict with dotted key notation into nested dict.
Given a flat dict with dotted keys for nested items, e.g.
>>> input_dict = {'spam.eggs': 23, 'answer': 42}
create a nested dict
>>> output_dict = _inflate_dotted(input_dict)
>>> output_... | d87c9923f0fc60f603c952b9b2f4f475f3002281 | 595,368 |
def get_state_values(event, event_tag='new'):
"""
Retrieves the states from a state change event and
returns them as a dictionary of state name/state value pairs.
- event:
The SPARKL event as returned by `sparkl listen`.
- event_tag:
Either `old` or `new` (default). ... | 7c2c7cad85b8a1ef85e6625adbd794137677be75 | 595,376 |
def get_clean_layer_name(name):
"""Remove any unwanted characters from the layer name.
Args:
name (string): the layer name.
Returns:
string: the filtered layer name.
"""
delimit_chars = ":_/"
for char in delimit_chars:
name = name.split(char)[0]
return name | 9366215fa62c1e398dadc4280c0b0ceeb1b707c6 | 595,378 |
def like_escape(s):
"""
Escape characters in ``s`` that have special meaning to SQL's ``LIKE``
"""
return s.replace('\\', r'\\').replace('%', r'\%').replace('_', r'\_') | 5d92f4a0ff4c91744fb52b0c3ccfe0d43b95ae95 | 595,381 |
from typing import Union
from typing import List
from typing import Tuple
import re
def split_delimiters(text: str, delimiters: Union[List[str], Tuple[str]]) -> List[tuple]:
"""
Splits the text with delimiters and returns the list of tuples in which
first entry is the splitted text and the second is the c... | c27a88d8030759b4aaa5fc6b3a760c9fb12e85a4 | 595,385 |
def runge_kutta_ode_solver(ode, time_step, y, params):
"""4th order Runge-Kutta ODE solver.
Carnahan, B., Luther, H. A., and Wilkes, J. O. (1969).
Applied Numerical Methods. Wiley, New York.
Parameters
----------
ode : function
Ordinary differential equation function. In the Lorenz mod... | 2db376cc7a97bd808c0ea7e4b439213b8132ac09 | 595,386 |
def black(conf):
"""Return HEX Color code for Black"""
return "#000000" | 9dc190b5b1bbec4eda7219f504dfef6b03cd136f | 595,387 |
def count_ones(word_ones):
"""
Counts the ones associated with a (word, next) pair
word_ones: tuple (word, [1,1,..,1])
return: tuple (word, count)
"""
(word, ones) = word_ones
return (word, sum(ones)) | fc83556814e72aceb49e212cd84a29911d1ff927 | 595,392 |
def reference_label(metric, reference):
"""
Format a metric label for a reference.
:return:
A string that is used as the display value for a reference metric.
"""
label = str.strip(metric.label or metric.alias)
if reference is None:
return label
return '{} {}'.format(label... | e5fbb20153c678c50737d75639353e5be69c09fd | 595,398 |
def lu_chen(XYZ, t, a=-10, b=-4, c=18.1):
"""
The Lu-Chen Attractor.
x0 = (0.1,0.1,0.1)
"""
x, y, z = XYZ
x_dt = -a * b / (a + b) * x - y * z + c
y_dt = a * y + x * z
z_dt = b * z + x * y
return x_dt, y_dt, z_dt | e97269a208298ab603713588eecf124cb5326a70 | 595,399 |
def deconvert(dim, coord_norm):
""" Converts normalized coordinates in YOLO format to [xmin, ymin, xmax, ymax] format. """
# xmin = w_image * (xmin_norm - xmax_norm/2)
xmin = dim[0] * (coord_norm[0] - coord_norm[2]/2)
# xmax = w_image * (xmax_norm/2 + xmin_norm)
xmax = dim[0] * (coord_norm[2]/2 + ... | 38bebec71ed373614f318d1571ecaee6888c49a1 | 595,401 |
def _getobsfate(successorssets):
""" Compute a changeset obsolescence fate based on its successorssets.
Successors can be the tipmost ones or the immediate ones. This function
return values are not meant to be shown directly to users, it is meant to
be used by internal functions only.
Returns one fa... | 8b9c9ac0baf1880f022981c80a22a29d5f2e84e3 | 595,408 |
def create_price_table_row(header, description, final_url, price_in_micros, currency_code, price_unit, final_mobile_url=None):
"""Helper function to generate a single row of a price table.
Args:
header: A str containing the header text of this row.
description: A str description of this row in the p... | 051d103d79203a11eca31a38e299464e587ba4fd | 595,410 |
def get_gb_person_id(acc_id, vehicle_index, person_index):
"""
Returns global person id for GB, year and index of accident.
The id is constructed as <Acc_id><Person_index>
where Vehicle_index is two digits max.
"""
person_id = acc_id * 1000
person_id += vehicle_index * 100
person_id +=... | dcd05291fed94088213afd0b1ba67b1a85ff4cc3 | 595,411 |
from re import sub
def add_space_betw_digit_and_unit(string):
"""给数字与单位之间增加空格。"""
# 常用单位,不齐全
units = ['bps', 'Kbps', 'Mbps', 'Gbps',
'B', 'KB', 'MB', 'GB', 'TB', 'PB',
'g', 'Kg', 't',
'h', 'm', 's']
for unit in units:
pattern = r'(?<=\d)' + unit # positi... | ade46cd8954e4bb298deafce6cef55357f31eb0c | 595,414 |
def zeropad(anint):
"""Convert an integer to a two character string."""
intstr = str(anint)
if len(intstr) == 1:
intstr = '0' + intstr
return intstr | 30ee8b7c8d4a268930e615ad1d6b07bcf665e2a6 | 595,417 |
from typing import Optional
def calculate_measurement_value(sources) -> Optional[str]:
"""Calculate the measurement value from the source measurements."""
value = 0
for source in sources:
if source["parse_error"] or source["connection_error"]:
return None
value += (int(source["... | 71b5097620fb83d693d08831ebaf4d04a7161a0c | 595,421 |
def mCVTC(molFrac, vTC, vV, fW, eps=1.0):
"""
mCVTC(molFrac, vTC, vV, fW, eps=1.0)
multi-Component Vapor Thermal Conductivity in W/m/K
Parameters:
molFrac, list of mol fractions
vTC, list of pure component vapor thermal conductivities (components
ordered as in molFrac... | f01e234d8cda556c11c54b4272ed4e83d6d5fcdb | 595,422 |
def phasename(phaseID):
"""
Take a phase ID and return the name of the phase.
Parameters
------------
phaseID : :class:`str`
ID for the particular phase (e.g. 'olivine_0')
Returns
--------
:class:`str`
Name of the phase.
"""
if phaseID.find("_") > 0:
n =... | 928ea69de9972fcf7673854b92569b4c9b603799 | 595,423 |
def get_subreddit_metric_labels(subreddit_name):
"""
:param str subreddit_name: The sub-Reddit we're sending metrics for.
:rtype: dict
:returns: A dict of standard metric labels to send with a data point.
"""
return {'subreddit': subreddit_name} | 6579488f8e03bf3cf8cf92dabc4fbae3becd0eb5 | 595,424 |
def filter_providers(providers, names):
"""
Filters the list of :providers: given one or more :names:.
"""
if names is None or len(names) == 0:
return providers
if isinstance(names, str):
names = [names]
names = [n.lower() for n in names]
return [p for p in providers if p.... | 2da45aec52a9ee33983e830a4e6b9ce37364e213 | 595,435 |
import smtplib
import logging
def send_mail(recipient, sender, subject="", content="", smtp_host="127.0.0.1", smtp_port=25):
"""
Lightweight mail functionality. Sends an mail from *sender* to *recipient* with *subject* and
*content*. *smtp_host* and *smtp_port* are forwarded to the ``smtplib.SMTP`` constr... | 87aab87f43d428a7886e4b0029c9cdb518a4db78 | 595,436 |
import math
def calculate(point1, point2):
"""
Calculate the distance between two points (point1 and point2) on the Earth's surface
using the 'equirectangular' formula.
Input: point1 : two floating point numbers between -180 and 180, where positive indicates North/East
... | 80bc8717a02f70b0daa0ea673ccfcb6b2c57cf36 | 595,438 |
from typing import Dict
from typing import Any
import pathlib
import toml
def load(filepath: str) -> Dict[str, Any]:
"""Load a TOML file"""
if not pathlib.Path(filepath).is_file():
raise FileNotFoundError(f"File not found: {filepath}")
with open(filepath, "r", encoding="utf-8") as infile:
... | 9617ced51943e1717df7d1f65338f4591f5e03e7 | 595,443 |
from typing import List
def load_message(length: int) -> List[int]:
"""Loads array of bits.
Repeats requests until user enters a message of length `length` or greater.
All entered characters must be `0` or `1`.
Args:
length (int): minimum length of message
Returns:
List[int]: li... | e26e51eef902cf73c9ea596fd0d78772aba25517 | 595,444 |
def inspect_data(df, n=5):
"""
Get first 'n' rows from dataframe, types of each feature,
and sum of na values for each feature
Parameters
- df: (pandas dataframe) dataframe
- n (default n=5): (int) num of rows to inspect
Return
- df_sample, df_types, df_na: (tuple)
df_sample: ... | 37b4972e3f88ae858199a6a8a5d0aae474203a6c | 595,448 |
def permute_2d(m, p):
"""Performs 2D permutation of matrix m according to p."""
return m[p][:, p] | a78a2331fdf48616d1b48a2bb09f3c357bcb860d | 595,449 |
import uuid
def CreateSmartShoppingAdGroup(client, campaign_id):
"""Adds a new Smart Shopping ad group.
Args:
client: an AdWordsClient instance.
campaign_id: the str ID of a Smart Shopping campaign.
Returns:
An ad group ID.
"""
ad_group_service = client.GetService('AdGroupService', version='v20... | 361aa1ca04de8e9be916caee1d62cdf6f6f20dd3 | 595,451 |
from typing import Union
from typing import List
from typing import Dict
import json
def load_json(filename: str) -> Union[List, Dict]:
"""Load JSON data from a file and return as dict or list.
Defaults to returning empty dict if file is not found.
"""
with open(filename, encoding="utf-8") as fdesc:
... | 4b560ec82d3d363502c020d695d8e712180f6783 | 595,455 |
def is_hsl(in_col):
"""
Check whether an input is a valid HSL color.
Return True if it is, otherwise False.
"""
if len(in_col) == 3 and type(in_col) == tuple:
if 0 <= in_col[0] <= 1 and 0 <= in_col[1] <= 1 and 0 <= in_col[2] <= 1:
return True
else:
return Fals... | f1de56c2a4457eb8a87d706f004d736c13f67cd0 | 595,462 |
import math
def approximate_size(size, unit):
"""
Returns a size to 10 multiples.
Parameters
----------
size : float
A size to approximate.
unit : float
Unit of input size.
Returns
----------
appr_size : int
A dimensionless number in 10 multiples.
"""
... | 408e757ba31f3595f948a152d208dd5475523be8 | 595,463 |
def image_without_seam(im, s):
"""
Given a (color) image and a list of indices to be removed from the image,
return a new image (without modifying the original) that contains all the
pixels from the original image except those corresponding to the locations
in the given list.
"""
image = im
... | 9239477d85069830d354eb294aa48a09cad2c000 | 595,466 |
def _XMLGetNodeText(node):
"""
Return text contents of an XML node.
"""
text = []
for childNode in node.childNodes:
if childNode.nodeType == node.TEXT_NODE:
text.append(childNode.data)
return(''.join(text)) | 911253a92027838e26d11370f46d7389aeafb16b | 595,468 |
def add(a, b):
"""Adds two numbers
:param int a: First number.
:param int b:
:return: Sum of the two numbers.
:rtype: int
"""
return a + b | b73d54138df405ed261fd6c603b354234c8fd65e | 595,471 |
def list_mean(list):
"""Calculate the mean of a list with numbers."""
mean = float(sum(list)) / float(len(list))
return mean | fdd22dd5ec824abfbf3af18608ee6ec35d523b78 | 595,475 |
from typing import List
def remove_bad_samples(instance_annotation: dict,
minimum_bb_area: float,
minimum_visibility: str,
image_area: int = 1600 * 900) -> List:
"""
Removes bad samples from an instance annotation's sample sequence
:par... | b2a7c91c60ee53693724ddffe5c8cd7cde319dc2 | 595,477 |
def traverse(vertex, mergeDict):
"""
Given a vertex and a dictionaty of merges, returns the id of the cluster
the vertex belongs to.
"""
while vertex in mergeDict:
vertex = mergeDict[vertex]
return vertex | 635ebec6afe8723875060a62bd7bc928c45cea65 | 595,479 |
import csv
def page_titles_to_ids(titles_set, page_table_filename):
"""
Parse data from the Wikipedia page database table to get page IDs for
the given set of page titles.
"""
mapping = {}
with open(page_table_filename, encoding='utf8') as page_file:
reader = csv.reader(page_file)
... | 93eec776e6e8ee62dc1847e13be3382c97960e41 | 595,483 |
def is_numpy(obj):
"""Is a python object a numpy array?"""
return "numpy" in str(type(obj)) | 82d06025179514f291f7534eb0f4a7c419d45713 | 595,484 |
def make_train_dict(input_ids, attention_masks, labels):
"""
Put things in a dictionary. Just a small utility function.
"""
return {'input_ids': input_ids, 'attention_mask': attention_masks, 'labels': labels} | 11d3e7d3ecab60ae451d479d1dc288ff75230716 | 595,488 |
def is_parquet_file(file: str) -> bool:
"""Assess extension to be that of a parquet file.
Returns
-------
bool
`True` if file name is identified as a parquet file, i.e. ending with
``.parquet`` or ``.parq`` or being named ``_metadata`` or
``_common_metadata``.
"""
return... | 85dfcdadac8d6be431aa2151865813362b7fc4c9 | 595,490 |
def resize_logo(logo, scaling_factor):
"""
Scales the logo image according to the scaling factor
:param Image.Image logo: image for the logo
:param float scaling_factor: scaling factor for resizing logo image
"""
width, height = logo.size
return logo.resize((int(width * scaling_factor), int... | e555a09d612321066b6dc532b69450c5c4986afd | 595,496 |
import random
import string
def random_name(prefix, length):
"""Generate a random name with a fixed prefix"""
name = prefix + "".join(random.choice(string.ascii_letters)
for i in range(length))
return name | e88e1412cd04e1ce1d348918fb8b613b64668099 | 595,497 |
def copy_list_dicts(lines):
"""
Convert a lazy cursor from psycopg2 to a list of dictionaries to reduce the access times
when a recurrent access is performed
:param lines: The psycopg2 cursor with the query result
:return: A list of dictionaries
"""
res = list()
for line in lines:
... | 1967fea1868d27d442ab809b7ed717e89da81c29 | 595,499 |
def get_values(dict):
""" extract the values from a dictionary """
return dict.values() | 7b0ccf95dc796cd68a911316c0ac330db9080b54 | 595,500 |
def get_kubernetes_version(ce_client):
"""
get_kubernetes_version
Get the supported kubernetes versions from the service. There are multiple
versions supported but for the example we will just use the last one in the
list.
"""
response = ce_client.get_cluster_options(cluster_option_id="all... | 17ff76d3d5b39f42f50b21b224a9a23d7797f959 | 595,501 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.