content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def create_non_8021Q_vea_cmd(lpar_id, slot_num, port_vlan_id):
"""
Generate HMC command to create a non-8021Q virtual ethernet adapter
:param lpar_id: LPAR id
:param slot_num: virtual adapter slot number
:param port_vlan_id: untagged port vlan id
:returns: A HMC command to create a non 8021Q ve... | a3ede365325f9eec46316546c566b6fbf1882604 | 500,684 |
import string
def decode_labels(encoded_labels: list) -> str:
"""
Decodes predictions to their string equivalent
:param encoded_labels: List of encoded predictions
:return: Str of decoded predictions
"""
labels = string.digits + string.ascii_uppercase + "." + "+" + "-" + "?"
text = ""
... | e9e3557eb49910a5f834eb2b815b01e235c9940e | 283,806 |
def dt_calc(etime):
"""Returns an interval of time that increased as the ellapsed time etime increases"""
if etime <= 10:
return 0.25
elif etime <= 60:
return 0.5
elif etime <= 120:
return 1.0
elif etime <= 300:
return 5.0
elif etime <= 3600:
return 10.0
... | 9f8b7d5d07e336287674e2d5cd044f9a0bf752f9 | 476,551 |
def idify(string: str):
"""
Converts a string to a format suitable for HTML IDs
eg 'Add goods' becomes 'add_goods'
"""
return string.lower().replace(" ", "_") | ebe3279e0fc10cf0bfe97e0d5a8ab070291629cb | 311,962 |
def min_with_none(x_seq):
"""Find the minimum in a (possibly empty) sequence, ignoring Nones"""
xmin = None
for x in x_seq:
if xmin is None:
xmin = x
elif x is not None:
xmin = min(x, xmin)
return xmin | f85f115f29a625eea967d2fe483c27e74aadf81c | 416,114 |
def select_daily_mean(daily_mean, gw_data):
"""
Select the lakes in the daily_mean file that are retained in the final growth window.
Input:
daily_mean: dataframe with all compiled daily mean water quality data
gw_data: growth window dataframe (output from the growth_window_means function)
... | 331bead7dcbe17086f52b247f807be87d5fe0e43 | 44,607 |
import random
def generate_random_seed(project_parameter):
"""
Generate random seed for project parameters
Args:
project_parameter (dict):
Returns:
dict: The project parameters dictionary including the key 'seed'
"""
if "seed" not in project_parameter.keys():
project_... | a6047689de5a585f915a01b478dbd048d1ca67d4 | 209,206 |
def buscar_posicion_minimo(lista, i):
"""Devuelve la posición del elemento mínimo en lista[i:]"""
posicion_minimo = i
while i < len(lista):
if lista[i] < lista[posicion_minimo]:
posicion_minimo = i
i += 1
return posicion_minimo | 2a2feb608fb8b0e52ea6f38da690f432eed7d26f | 631,585 |
import torch
def _psnr(input, target, normalization='max'):
"""
This function is a torch implementation of skimage.metrics.compare_psnr
Parameters
----------
input : torch.Tensor
target : torch.Tensor
norm : either max or mean
Returns
-------
torch.Tensor
"""
input_vi... | 58ae2615ab77d3deff68310638e122afdab9a061 | 255,946 |
from typing import Union
import requests
def validate_request_success(resp: Union[requests.Response, str]):
"""
Validate the response from the webhook request
"""
return not isinstance(resp, str) and resp.status_code in [200, 201] | 13fa27f2c71780f7f33a62ff767eccae45722b91 | 673,028 |
def tds_quote_id(ident):
""" Quote an identifier
:param ident: id to quote
:returns: Quoted identifier
"""
return '[{0}]'.format(ident.replace(']', ']]')) | c85cba28fe3b9d7791cc8541e42356f8088e1207 | 466,422 |
def read_file_to_lines(filename):
"""
Reads an input filename and process it into a list of strings representing
the lines of input.
:param filename: File to read
:return: List of string
"""
with open(filename) as reader:
return reader.read().split('\n') | d4e35687f226582fac378e5a16c736fe4a26d34e | 372,972 |
def _remove_duplicate_folders(folder_list):
"""Removes duplicate folders from a list of folders and maintains the
original order of the list
Args:
folder_list(list of str): List of folders
Returns:
list of str: List of folders with duplicates removed
"""
new_folders_set = set()
new_folders_list ... | 17243262bcbe9ff46e0b4d55b786fb22946fc892 | 386,870 |
def _http_400(start_response):
"""Responds with HTTP 400."""
start_response('400 Bad Request', [('Content-Length', '0')])
return [] | 73017c350321b5c190f27c12bbe63ec64bc1337b | 299,182 |
import re
def configMultiEntry (lineData, configSection):
""" Search for section and return list of strings of the multiply entry lines after section heading """
sectionContentsStringList = []
error='NONE'
sectionfound = 0
for line in lineData:
#print(line)
if sectionfound is 0:
... | 96530d70b27a760b87bfa27a51c16dbd0a238679 | 235,343 |
def _get_user_display_name(user):
"""Return a human-friendly display name for a user."""
# An anonymous user has no display name
if user.is_anonymous:
return ''
# Form display name by concatenating first and last names and stripping whitespace
display_name = user.get_full_name().strip()
... | dfd8572893bb5c491d2b6c16e07975f6a141b235 | 669,067 |
def ktau_weighted_distance(r_1, r_2):
"""
Computes a weighted kendall tau distance. Runs in O(n^2)
Args:
r_1, r_2 (list): list of weighted rankings.
Index corresponds to an item and the value is the weight
Entries should be positive and sum to 1
... | ec04adb26c084a0c49f3004742893faa86c55fab | 441,273 |
def IoA(poly1, poly2):
""" Intersection-over-area (ioa) between two boxes poly1 and poly2 is defined as their intersection area over
box2's area. Note that ioa is not symmetric, that is, IOA(poly1, poly2) != IOA(poly1, poly2).
:param (shapely.geometry.Polygon) poly1: Polygon1
:param (shapely.geometry.P... | 4960e10b486f6cf80ee2ea8bc1caa99ebf30fb5b | 242,567 |
import re
def multi_replace(text, d):
""" Takes a dictionary pattern -> substitution and applies all substitutions to text
"""
s = text
for key in d:
s = re.sub(key, d[key], s)
return s | 73367f611dccce39c82ff49c8724c7e1705bb888 | 458,399 |
def is_code_line(line):
"""A code line is a non empty line that don't start with #"""
return line.strip()[:1] not in {'#', '%', ''} | 558a37d8a30f20d75f5dcc9b72e82f5981e6f84b | 291,996 |
def to_identifier(name):
"""Convert name to an identifier (upper snake case)
Args:
string: a string to be converted to an identifier
Returns:
a string in upper snake case
"""
return name.replace(' ', '_').upper() | 39d7d3804e8a6b59dc46efb271197ee7882e805b | 549,840 |
def get_tag(instance):
"""
Get the tag associated with the instance, if there is one.
"""
return getattr(instance, '_tag', None) | 8df7540a12beb3eff634aad983374cce60fba56a | 212,301 |
def clean_headers(headers):
"""
Sanitize a dictionary containing HTTP headers of sensitive values.
:param headers: The headers to sanitize.
:type headers: dict
:returns: A list of headers without sensitive information stripped out.
:rtype: dict
"""
cleaned_headers = headers.copy()
... | 4e375db09ad38cff145344a38225a38c75a98e85 | 354,993 |
def dot(xx:list,yy:list):
"""
Dot product of two lists.
>>> dot([1,2,3],[4,5,6])
32
"""
return sum([x*y for (x,y) in zip(xx,yy)]) | 21bdeafc0a53af3f30b1ca354a33def5c5c16c59 | 220,991 |
def complete_cases(_data):
"""Return a logical vector indicating values of rows are complete.
Args:
_data: The dataframe
Returns:
A logical vector specifying which observations/rows have no
missing values across the entire sequence.
"""
return _data.apply(lambda row: row.no... | 3e6e294f11988d04fd1c3d7d46b409badf1f90f9 | 678,727 |
def massage_key(key):
"""Massage the keybase return for only what we care about"""
return {
'fingerprint': key['key_fingerprint'].lower(),
'bundle': key['bundle']
} | 229cf81b90e9d4602ad2e25f7cc6fcea6afd12e8 | 56,590 |
def separate_particles(samples, index=None):
"""Get particle coordinates from array (just reshape the array)
Args:
samples (array_like): [N_samples, 2xN_particles]
index (int, optional): Where to split, (usually at the half of the array). Defaults to None.
Returns:
px (array_like):... | 1c2074c168a668157fc34349cc02c6be7f1a82f2 | 553,778 |
import math
def cs_h(c, R):
"""Height of the circular segment, given its radius R and chord
length c See: [http://en.wikipedia.org/wiki/Circular_segment]
"""
if c >= 2*R:
print('WARNING: the chord is greater than the diameter!')
print('WARNING: returning maximum height, the radius')
... | 8ac19c5703a35953135ff0730130aa76926df2e2 | 417,184 |
import redis
def log_to_redis(host="localhost", port=6379, dbn=11):
"""Record the tuning record to a redis DB.
Parameters
----------
host: str, optional
Host address of redis db
port: int, optional
Port of redis db
dbn: int, optional
which redis db to use, default 11
... | 893849c368705f3bad05701012bfa246bc0eacdf | 289,502 |
from typing import List
from typing import Dict
def get_images(ecr_client, repository_name: str) -> List[Dict]:
"""Get all images from a repository."""
return ecr_client.list_images(repositoryName=repository_name)["imageIds"] | 26cfab58ed3d16767df43c1f7972f28d81ffc557 | 181,394 |
def parse_hal_spikes(hal_spikes):
"""Parses the tag information from the output of HAL
Parameters
----------
hal_spikes: output of HAL.get_spikes() (list of tuples)
Returns a nested dictionary:
[pool][neuron] = list of (times, 1) tuples
The 1 is for consistency with the return of p... | fb1faba1c10845331bc2e526bbd5553289be2be7 | 36,641 |
import re
def parse_kernel_monitor(output):
"""Parse the thread monitor output and return the parsed data as a
dictionary with thread names as keys.
"""
re_thread = re.compile(r'(.*)\s+([\d\.]+)')
threads = {}
for line in output.splitlines():
mo = re_thread.match(line)
if ... | 9c5437b2d4b506fe57d48aa647940dc249ac110f | 349,878 |
def toBytes(b):
"""
Converts a string to a bytes object by encoding it as utf-8.
"""
if type(b) == str:
return b.encode("utf-8")
else:
return b | 29912d7cbc75c7d7a6b4e73bf3b7a4935699ef68 | 629,226 |
def produce_inter_times(timestamps, max_filter=None):
"""
Produces a list of the ordered timespans in seconds between epoch
timestamps.
Args:
timestamps: list of positive numbers representing epoch time
stamps in seconds.
Returns:
inter_times: list of time i... | e7b91435dd4bfe24cd02f81c759872e9bd4ed359 | 111,507 |
import pickle
def pickle_load(path):
"""Un-pickles a file provided at the input path
Parameters
----------
path : str
path of the pickle file to read
Returns
-------
dict
data that was stored in the input pickle file
"""
with open(path, 'rb') as f:
return... | 8d68e349118eb2fa2d5c1ce5b31b65cbc29a382f | 686,268 |
def confirm_yorn(prompt_msg: str) -> bool:
"""Prompts the user for a yes or no answer."""
confirm_input: str = input(prompt_msg)
return confirm_input.lower()[0] == "y" | f537126becd483a427d179b4afbe54386629b6af | 208,331 |
def flatten(lst_of_lst):
""" Flatten list of list objects.
"""
lst = []
for l in lst_of_lst:
if isinstance(l, list):
lst += flatten(l)
else:
lst.append(l)
return lst | 589d31f3999ffbfaa0b065357976462500fa9838 | 604,851 |
def index_in_str(text, substring, starting=0):
"""
Gets index of text in string
:arg text: text to search through
:arg substring: text to search for
:arg starting: offset
:return position
"""
search_in = text[starting:]
if substring in search_in:
return search_in.index(subst... | 397ffb9e5e6e0235e77b2deaa1ab03dbc84810ad | 469,371 |
def combine_meta_classes(*args, **kwargs):
"""
Combine multiple metaclasses into one.
When a class hierarchy employs metaclasses the subclasses
metaclass must always be a subclass of the parents metaclass.
This function combines multiple metaclasses into one. Suppose
you have two metaclasses M... | e945aa12f52861fe939c19e3bbb29bc757c8f9a3 | 516,479 |
import torch
def pcorrect(out, tilt):
"""Compute proportion of stimuli classified correctly from network output
Args:
out (torch.Tensor): output of network for each stimulus, i.e. the
predicted probability of each stimulus being tilted right
tilt (torch.Tensor): true tilt of each stimulus (1. for t... | 7d051c2ebb2e4850553e6846e828d57f3c5890c9 | 212,147 |
def should_concat(prev_type, cur_type):
"""This function contains the logic deciding if the current node should be grouped with the previous node in the same notebook cell.
Args:
prev_type: (str) type of the previous node.
cur_type: (str) type of the current node.
Returns
A Boolean
"""
... | f91e4026f376906b42e5a0182e1ca42e7e285b9e | 496,267 |
def arg_range(arg, lo, hi):
"""
Given a string of the format `[int][-][int]`, return a list of
integers in the inclusive range specified. Open intervals are
allowed, which will be capped at the `lo` and `hi` values given.
If `arg` is empty or only contains `-`, then all integers in the
range `[... | 77dda7ac1fb3ad3f05aa50ac01045565e0bb426b | 56,952 |
def partition(iterable, pivot, key):
"""Returns 3 lists: the lists of smaller, equal and larger elements, compared to pivot.
Elements are compared by applying the key function and comparing the results"""
pkey = key(pivot)
less = []
equal = []
greater = []
for x in iterable:
k = ke... | 122b88af683f80dee8d31a026b931fcebc318bf9 | 527,441 |
def insertion_sort(alist):
"""
Returns the history of running the insertion sorting
algorithm on a list of numbers, i.e. saves the state of
the list after each step of the algorithm.
"""
history = [alist[:]]
for index in range(1,len(alist)):
currentvalue = alist[index]
posit... | 0f6e4aac97676380712823a0739bab3c0c91eacc | 252,686 |
def getAllListings(command):
""" Check if command is to get all listings (l | list). """
return (command.strip().lower() == "l" or command.strip().lower() == "list") | a821b78e13b6788cd27eac03204529e1e792106f | 335,308 |
import re
def create_regex_function(body):
"""
Create function from regex pattern.
It is used for creating a function for classification.
Args:
body (string): A regex pattern
Returns:
function: A function which will return string for classification
"""
pattern = re.c... | a9f3b79b2f13feddf494e51b04cf7a716de37b4e | 395,412 |
def _get_record_depends(fn, record, instructions):
""" Return the depends information for a record, including any patching. """
record_depends = record.get('depends', [])
if fn in instructions['packages']:
if 'depends' in instructions['packages'][fn]:
# the package depends have already b... | 3a394278244d221de2fb85678a7a1f129a6756e9 | 161,734 |
def getAxis(node):
"""Parse rotation axis of a joint."""
axis = [0.0, 0.0, 0.0]
axisElement = node.getElementsByTagName('axis')[0].getAttribute('xyz').split()
axis[0] = float(axisElement[0])
axis[1] = float(axisElement[1])
axis[2] = float(axisElement[2])
return axis | ce9b268fcbd564845a1b05a342c96ed94998bd09 | 616,018 |
def raiser(exception):
"""Returns a function that raises an exception"""
def do_raise(*args, **kwargs):
raise exception
return do_raise | c4d5d5aab728b2c3903cb1a9d0b6bca129adab58 | 520,790 |
def get_progress(context, scope):
""" Returns the number of calls to callbacks registered in the specified `scope`. """
return context.get("progress", {}).get(scope) | cd0f827c3bf1f548a51dce992949b804d6b97aba | 663,579 |
import re
def ParseElastix(input,par):
"""Parse an elastix parameter file or elastix.log file and
extract a number associated with the given string parameter.
Parameters
----------
input: string
Path to input file.
par: string
String indicating the parameter in the files to e... | 69f2e09bcb70e05490f48fff31f3c318bfff13b7 | 199,807 |
import math
def polares_cartesianas_complejos(nump:list) -> list:
"""
Funcion que realiza la transformacion de coordenadas
polares a cartesianas de un numero complejo.
:param nump: lista que representa el numero complejo en cordenadas polares
:return: lista que representa la forma cartesiana del n... | ddb7020946d623543e6c9c1d1e142d2847462315 | 413,105 |
def generate_grid(obj, size):
"""Returns an array of x,y pairs representing all the coordinates in a
square (size * size) grid centered around a RoomPosition object"""
pos = obj.pos or obj
# set boundaries to respect room position limits
left, right = max(0, pos.x - size), min(49, pos.x + size) + ... | 50024640d5b59320d594ec4bfccb241657294e01 | 114,336 |
import requests
def lldp_local(url, cookie):
"""
Retrieve LLDP Local Information
:param url: base url
:param cookie: Cookie Value
:return: LLDP per local port information
:Example:
result = lldp_local(base_url, sessionid)
"""
header = {'cookie': cookie}
get_lldp_local = reques... | df2afe0deb7e449808889738309ee9184ce6e985 | 488,985 |
import multiprocessing
def forkitindexer(filelist):
"""
Return a list of tuples of indecies that divide the passed
list into almost equal slices
"""
p = int(8*multiprocessing.cpu_count()/10)
lenset = len(filelist)
modulus = int(lenset%p)
floordiv = int(lenset/p)
slicer = [[... | 5175761c1014a94755a575404b006be6a0b248ff | 323,556 |
def get_roll_selection(prompt:str = '\nRoll again? (y/n): '):
"""Return the users character when prompted to continue (y/n)."""
return input(prompt) | f18203efa800da09c789e330625c4ba4c3d23ee6 | 93,837 |
from pathlib import Path
def is_dir_gzipped(directory: str) -> bool:
"""
Check if the all the files in directory have a '.gz' extension
"""
files = Path(directory).glob("**")
if not files:
return False
files = filter(lambda x: x.is_file(), files)
for f in files:
if f.suffix... | 5ae4672df96388a815c7dc6247428f6898cab587 | 436,406 |
import re
def getJUnitVersion(commandsList):
""" Find the junit version
Parameters
----------
commandsList : list of str
A list of the parts of a command for running junit
Returns
-------
None, int, or str
Returns None if it cannot find the string junit in the classpath s... | 9295cbb789d761ff041585f2d40c680f61f3bf42 | 179,890 |
def peek(state, pos=0):
"""Peeks the character at pos from the head of data."""
if state.head + pos >= len(state.data):
return None
return state.data[state.head + pos] | d62925a2ee91f21b1371bf0cd42570735fb44498 | 538,033 |
import string
import random
def generate_uuid(length=4, characters=string.ascii_letters + string.digits):
"""Generate a string of random characters.
Args:
length (int, optional): The length of the UUID to generate.
characters (string, optional): The character set used to build the UUID.
... | 396cf1d979b2bf4edbba0bd690ebc628a56abe77 | 595,782 |
import torch
def add_channels(imgs: torch.Tensor, num_channels: int=3) -> torch.Tensor:
"""
Converts an Input image with one channel to a multi-channel input image.
Parameters
----------
imgs: Input images, for which the channels should be repeated.
num_channels: Target number of channels.
... | 756aea35f65d5862dbd6609ad3c2716280dc1a1c | 131,823 |
def verbose_name(obj):
"""Return the object's verbose name."""
try:
return obj._meta.verbose_name
except Exception:
return '' | ae5542404b326be960331632239c11b0ad0411dc | 653,815 |
import torch
def cross_squared_distance_matrix(x, y, device):
"""Pairwise squared distance between two matrices' rows.
Computes the pairwise distances between rows of x and rows of y
Args:
x: [n, d] float `Tensor`
y: [m, d] float `Tensor`
Returns:
squared_dists: [n, m] float `Tenso... | 37c8176b454320e4dd5a998251a8419f82ae1380 | 299,890 |
def img_resolution(width, height):
"""
Returns the image's resolution in megapixels.
"""
res = (width * height) / (1000000)
return round(res, 2) | 1275a92842fd95f1cd745ac2c8366ec03a183e3e | 284,417 |
def get_chess_square(size, x, y):
"""
Returns the coordinates of the square block given mouse position `x` and `y`
"""
return (x // (size // 8), y // (size // 8)) | d51ef89ceb5f88a1b189b01e9f0b0034ebfcd8c4 | 121,878 |
def shame(df):
"""
Filter the dataframe of game data on shame
(games where one team was shamed).
Returns: tuple (string reason, pd dataframe)
"""
reason = 'shame'
filt = df.loc[df['shame']==True]
filt = filt.sort_values(['runDiff', 'winningScore', 'season', 'day'], ascending=[False, Fal... | de8e49446c618c9ce562b568a656b3671b4c6b9b | 295,273 |
def crosscorr_time(u, v, model, **kwargs):
"""
Cross correlation of forward and adjoint wavefield
Parameters
----------
u: TimeFunction or Tuple
Forward wavefield (tuple of fields for TTI or dft)
v: TimeFunction or Tuple
Adjoint wavefield (tuple of fields for TTI)
model: Mod... | ac3f84bf13e56e910fa2780ecb7aa803cdd6f325 | 177,272 |
from typing import Dict
from typing import Any
from typing import Tuple
def global_average_precision_score(
y_true: Dict[Any, Any], y_pred: Dict[Any, Tuple[Any, float]]
) -> float:
"""
Compute Global Average Precision score (GAP)
Parameters
----------
y_true : Dict[Any, Any]
Dictionary... | 3cb7b97fa19ec63053b7b10668dd3d7a992b9fb9 | 629,620 |
from math import floor, sqrt
def is_triangular(num):
"""
Determine if a number is of the form (1/2)n(n+1).
"""
assert isinstance(num, int) and num > 0
near_sqrt = floor(sqrt(2 * num))
return bool(int((1 / 2) * near_sqrt * (near_sqrt + 1)) == num) | 4279545769d3e0f200381abd4bf493fe5bc2ec4e | 296,933 |
def flatten_rf(flow):
"""
Flattens the Risky Flow objects into a flat dict to write to CSV.
"""
return {
"id": flow.get("id"),
"businessUnit": flow.get("businessUnit", {}).get("name"),
"riskRule": flow.get("riskRule", {}).get("name"),
"internalAddress": flow.get("internal... | 461f051ba4e92aacefc085367052a2511410e354 | 491,215 |
def dobra(x):
"""
Dobra o valor da entrada
Parâmetros
----------
x : número
O valor a ser dobrado
Retorno
-------
número
O dobro da entrada
"""
return 2*x | 00431c5fb8a1ab056252b5d8389868f71c872c62 | 665,853 |
def build_reaction(reac):
"""
This function gets the reactants and products in smiles format
from reaction list and writes the reaction in a way that
can be fed to rdkit.
Parameters
------
reac : str
A reaction string with reactants/products and their
stoichiometri... | 3761ecd54a4d9f6976a0581ac1260096135691ed | 539,460 |
def req_thickness(t_min, t_corr, f_tol):
"""Return the required wall thickness [m] based on the mechanical allowances -
extrapolated from PD8010-2 Equation (4).
:param float t_min: Minimum wall thickness [m]
:param float t_corr: Corrosion allowance [m]
:param float f_tol: Fabrication tolerance [-]... | 81266f3abe36dd7d1252461660ae9aa0757de877 | 393,832 |
import six
def convert_perm(perm):
"""Convert a string to an integer, interpreting the text as octal.
Or, if `perm` is an integer, reinterpret it as an octal number that
has been "misinterpreted" as decimal.
"""
if isinstance(perm, six.integer_types):
perm = six.text_type(perm)
return ... | a20ed3337cf4ffffa73a978c0b736e5d10bbc7bd | 455,026 |
import re
def mkccj_is_compiler_command(parsedArgs, commandString):
"""Return True if the commandString is or appears to name a compiler"""
if parsedArgs.compiler:
if parsedArgs.compiler == commandString:
return True
else:
return False
if re.search(r"cc$", commandS... | 5b45a87fddf4b93059dad65d8b031058a0962f18 | 472,912 |
def compare_dictionaries(d1, d2):
"""
Compare two dictionaries
:param d1:
:param d2:
:return: (bool) True if equal, False if different
"""
res = True
try:
for key in d1:
res &= (d1[key] == d2[key])
for key in d2:
res &= (d1[key] == d2[key])
exc... | 480ffc59e52d2831ab079d755d9125fcb6033264 | 466,351 |
def byte2hex(buf):
"""Convert a bytestring to a hex-represenation:
b'1234' -> '\x31\x32\x33\x34'"""
return "\\x" + "\\x".join(["%02X" % x for x in buf]) | 0bf55720cd5cb98936ae435f8f25782605eedb5c | 471,046 |
def smaller_starting_year(year, starting_year):
"""
If the year is older than the defined "starting_year", i.e
the year from when we start counting, set it to the "starting_year"
This is just internal handling of the code and won't change the data
"""
if year < starting_year:
year = star... | 544096038a15a42630af7c1cb7e7842487bd18c0 | 206,294 |
def cbrt(x):
"""cubic root, this cubic root routine handles negative arguments"""
if x == 0.0:
return 0
elif x > 0.0:
return pow(x, 1./3.)
else:
return -pow(-x, 1./3.) | 06dbfcdcfbfe3d11d8b2d6ebc7f7043b66735511 | 81,327 |
def parse_direction(direction):
"""
Use this to standardize parsing the traffic direction strings.
:param direction: str; The direction value to parse.
:return: Optional[str]; One of 'ingress', 'egress', or 'both'. Returns None if it could not parse the value.
"""
direction = direction.lower()
... | 513274ba3be44f266099c1561c3719b37053c74d | 126,430 |
import torch
def mat2euler(rot_mat, seq='xyz'):
"""
convert rotation matrix to euler angle
:param rot_mat: rotation matrix rx*ry*rz [B, 3, 3]
:param seq: seq is xyz(rotate along z first) or zyx
:return: three angles, x, y, z
"""
r11 = rot_mat[:, 0, 0]
r12 = rot_mat[:, 0, 1]
r13 = r... | d06397aaa3ecd15211a2fb20483aef0ef4223568 | 574,573 |
import json
def load_table(pinyin_word_table_path):
"""
Load pinyin-word table from pinyin_word_table_path.
Args:
pinyin_word_table_path: Path to the source pinyin-word table json file.
Returns:
pinyin-word table, a dict, key->pinyin, value->(word, log(probability)).
"""
with... | a1d90dde5aa28aefa8038a2a30594354c0226ae8 | 149,860 |
def partition(start, stop, step):
"""Partition an integer interval into equally-sized subintervals.
Like builtin :py:func:`range`, but yields pairs of end points.
Examples
--------
>>> for lo, hi in partition(0, 9, 2):
print(lo, hi)
0 2
2 4
4 6
6 8
8 9
"""
re... | 60949af9fdcc5b5a387de99fda3d4f4aa8f99862 | 309,853 |
def containsZero(n):
"""
n: an int or a str
output: True if n contains '0'
"""
numStr = str(n)
for letter in numStr:
if letter is '0':
return True
return False | e8698f6ba935079ecdb37adbdeb88b61edf9d640 | 44,090 |
def drop_duplicate_rows(data_frame, column_name):
"""Drop duplicate rows in given column in pandas data_frame"""
df = data_frame.drop_duplicates(subset=column_name, keep="first")
return df | 9dcdc06cf4f5ef466c6d808e03a92ef09b451994 | 42,429 |
def _make_row(old, parent_key=None):
"""Make nested dictionary into a single-level dictionary, with additional processing for lists
For example:
{
"metadata": {
"durations": {
"call": 38.6015,
"setup": 0.0021
},
"statuses": {
... | 894649a98d12d88f7543e5ede9383ec3703148b3 | 118,820 |
def delta(prev, cur, m):
""" Compute the delta in metric 'm' between two metric snapshots. """
if m not in prev or m not in cur:
return 0
return cur[m] - prev[m] | c525ff4402b244b6a599d6380fb4b2a029c940b4 | 249,670 |
def convert_kb_into_str(size):
"""
Converte um parâmetro de tamanho de arquivos (em kb) para a escala mais adequada
Parâmetros
----------
:param size: variável numérica representando o tamanho de arquivos em kb [type: float]
Retorno
-------
:param size: valor convertido pra esc... | 60fe61288540e0f710b2aa0d1376c8d1b9ef79b5 | 157,913 |
def is_valid_0_1(param):
"""
Checks if param is zero or one
"""
return param == "0" or param == "1" or param == 0 or param == 1 | 25541824db5d587ba142238793028a414e524075 | 175,075 |
def is_binary(file_path):
""" Returns True if the file is binary """
with open(file_path, 'rb') as fp:
data = fp.read(1024)
if not data:
return False
if b'\0' in data:
return True
return False | 2df56f93d4e31220a580bf1e659c3c51b96260d2 | 707,743 |
def process_collection(id, col):
""" Helper function processing the collection.
Args:
id: (short) name of the collection.
col: a collection (python module).
"""
return {
"id": id,
"name": col.__name__,
"description": col.__description__,
"version": co... | 32a53a1fe8711b00b6faf2abe046f187a7ab40bb | 415,806 |
def repeat(character: str) -> str:
"""Repeat returns character repeated 5 times."""
word = ""
for _ in range(5):
word = word + character
return word | 19bdda35ffafa97d22200f74f1e078958e193962 | 57,579 |
import logging
def _decodeCStd( version, strictAnsi ):
"""
Decodes the C standard given the values of the macros
__STDC_VERSION__ and __STRICT_ANSI__
"""
retVal = None
if version == '__STDC_VERSION__' and strictAnsi == '1':
retVal = 'c90'
elif version == '199409L' and str... | 2620f3ae0e1a42c2c616c2b087163071dcdc29eb | 102,946 |
def _is_git_url_mismatch(mismatch_item):
"""Returns whether the given mismatch item is for a GitHub URL."""
_, (required, _) = mismatch_item
return required.startswith('git') | b1c3cec3d8cf3c7d3ffa5c405522b1a08754223b | 2,096 |
def read(filename):
"""Read content of specified test file.
:param str filename: Name of file in 'testdata' folder.
:return: Content of file
:rtype: str
"""
with open('testdata/' + filename) as f:
return f.read() | 3d5485021d3a3578485f3b5f3ea59e0badc4a3c7 | 653,147 |
def tonative(n, encoding='ISO-8859-1'):
"""Return the given string as a native string in the given encoding."""
# In Python 3, the native string type is unicode
if isinstance(n, bytes):
return n.decode(encoding)
return n | bb71e3718bc3f0537159971ce123e861beb98abb | 337,170 |
def certificate_domain_list(list_of_domains, certificate_file):
"""Build a list of domains where certificate_file should be used"""
cert_list = []
for domain in list_of_domains:
cert_list.append({"host": domain, "certificateFile": certificate_file})
return cert_list | 352ab45ce7bfb855eaf0acdb6c1fea632fcdd0ed | 499,007 |
def user_input_validator(validator, question): # pragma: no cover
"""Validate a user input until it passes a validator function.
validator: function, test for user input. Returns a truthy
value for a valid input, falsey for invalid.
question: str, prompt for user to answer
"""
user_... | 95d54e223ce1023e5a5ebc2b8c28df82b648e8ad | 113,418 |
def get_wgs84_utm_epsg_code(*utm_zone):
"""
Convert utm zone information to an EPSG code to make projection definition easier. Can take parameters output
from `get_utm_zone` as arguments for `utm_zone`.
:param utm_zone: iterable with at least two parameters (zone number[int], hemisphere[str:'north'|'so... | 428bb59e50b15cc3a6035a593c82b1d8d24c0510 | 507,721 |
def clean_rating_count(rating_count):
"""Return just the digits for the rating count"""
return rating_count.replace('Bewertungen', '') | 8eb024208f5c8fafd733cbe54141b1466a544018 | 177,419 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.