content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from importlib import metadata
def version() -> str:
"""
Get the version of the package installed via pip
"""
return metadata.version("pascal-triangle") | d0aa912bfab670f2d52714e597f8c97ccd247721 | 593,301 |
import re
def simpleTokenize(string):
""" A simple implementation of input string tokenization
Args:
string (str): input string
Returns:
list: a list of tokens
"""
return re.sub('[^a-zA-Z0-9\s_]+', ' ', string).lower().split() | 45ede9b33cd92edfbcbd899a8ce8c033b4f4b279 | 593,306 |
def sum_integers_in_file(filename):
""" Return the sum of the integers in FILENAME, assuming one per line. """
sum = 0
with open(filename,"r") as f:
for line in f:
sum += int(line)
return sum | 8020ab312346af741d06c3e62d6c09381cdad47f | 593,308 |
import json
def load_configuration(configuration):
"""Returns a dictionary, accepts a dictionary or a path to a JSON file."""
if isinstance(configuration, dict):
return configuration
else:
with open(configuration) as configfile:
return json.load(configfile) | e141542d9b356530f921ffa2b80d6728e1d90644 | 593,309 |
def BoothRecToString(s, indent=0):
"""Convert a Booth recoding number to human-readable string.
Arguments:
s -- String of Booth recoding
indent -- Number of spaces in the head of lines (optional)
Returns: string
"""
sp = " " * indent
h = []
n = []
for i in list(s):
if ... | d2ff759cb0f7063f22ebd7249d999622b30f2fa5 | 593,310 |
def add_annotation_to_output_dict(file_id, annotation, output_dict):
"""Updates output_dict with given annotation"""
if file_id in output_dict.keys():
current_annotations = output_dict[file_id]
current_annotations.append(annotation)
output_dict[file_id] = current_annotations
... | 6e8dd7d5b147ec6696fde25a77afbe4fc2d59277 | 593,311 |
from typing import Optional
from typing import Dict
from typing import Any
def filter_nonempty_values(d: Optional[Dict[Any, Any]]) -> Dict[Any, Any]:
"""Return the input map with empty values removed. On an input of None
will return an empty Dict."""
if d:
return {e[0]: e[1] for e in d.items() if ... | 0884a5c1fcb8034aabf52b3bc1be06458ec83236 | 593,317 |
def sample_detection_method(image_data, image_details, method_parameters):
"""Sample of image detection method"""
parameter = method_parameters["test_parameter"]
print(f"Sample detection start with parameter: {parameter}")
return image_data, "image detected objects description" | 1d4437c0fdf8c4cbd94039812fe77656ba7fc907 | 593,319 |
import itertools
def xor_repeat(a: bytes, b: bytes) -> bytes:
"""XOR a bytestring with a repeating bytestring."""
return bytes(x ^ y for x, y in zip(a, itertools.cycle(b))) | 6edea579c308159210686c58f674707045f57d38 | 593,322 |
def get_element_children(element):
"""
Get all children of element
:param element: parent element
:return: list of element children
"""
return list(element) | 07a273b5aa85a01a538e152d807844abb0fdc360 | 593,323 |
def _append_query_filter(filterList, operator, left, right):
"""Append a query condition to a filter list.
Args:
filterList (list): List with query filters
operator (string): operator to use
left (object): Left-Hand value
right (object): Right-Hand value
Returns:
li... | 98e5d8d087163d860ae52eebc7facafaf24052c2 | 593,331 |
def inrange(x, m, M):
"""x in [m, M]?"""
return m <= x <= M | c6e0db80d194c0a8b8855798fd440c5afddd935f | 593,339 |
def get_indentation(line: str) -> int:
"""Returns the indendation of a line of code."""
if len(line.lstrip()) == 0:
# if it is a newline or a line with just spaces
return 0
return len(line) - len(line.lstrip()) | 05b3b1e55b6805583707d580c8216ef65356866d | 593,341 |
def bytes_2_str(bytes_str):
"""
用于将bytes 类型转换为 str 类型
:param bytes_str:
:return:
"""
return str(bytes_str, encoding='GBK') | c7e37a63cb6af5dfc695ef986bba5d2a8c8720cd | 593,342 |
import asyncio
import threading
def run_in_thread(coro, loop=None):
"""
Spawn a coroutine in the specified loop on a background thread. The loop will stop when the coroutine exits, and
then the background thread will complete.
:param coro: the coroutine to spawn.
:param loop: the event loop to r... | d90c89dd9901b3b90ca2917171f173a12eb736a7 | 593,347 |
def load_label_indices(label_indices_filename):
"""
Load label indices used in training
label_indices_filename: one label (diacritic) per line, in order used in Current
returns class2label, label2class (dicts): maps from index to label and from label to index
"""
labels = open(label_in... | 84f3f52d9440b03eb77fac7ecf6b2c7c7294dcf1 | 593,348 |
def _booleanise(value):
"""Try to booleanise something, return it unchanged if not possible"""
try:
if value.lower() in ['true', 'false']:
value = value.lower() == 'true'
except (AttributeError, TypeError):
pass
return value | c4a51e9a741a8decc3cb45ec7cb7759d25c3a573 | 593,351 |
import base64
import hmac
import hashlib
def build_signature(customer_id, shared_key, date, content_length, method, content_type, resource):
"""Returns authorization header which will be used when sending data into Azure Log Analytics"""
x_headers = 'x-ms-date:' + date
string_to_hash = method + "\n" + st... | ae06787afbf1b9c526d66e73f75c634eec7fcd40 | 593,352 |
from typing import Any
def is_num(num: Any) -> bool:
"""Function that tests if object can be converted to number
A function that takes any input and detects if it is a number by
attempting to convert the input to a float. This function catches
convertable digit string cases.
Source:
https://... | d74a40b1cf5c2dee6b8001b7fc937a546ea55bc0 | 593,359 |
import itertools
def sliding(iterable, size, fillvalue=None):
"""
Returns an iterator the slides over the given iterator in chunks of the
given size
"""
a = [itertools.islice(iterable, i, None) for i in range(size)]
return itertools.zip_longest(*a, fillvalue=fillvalue) | 8cfc779426d53e25e747ea8638d3aee89a2deb39 | 593,360 |
def is_valid_minute(minute):
"""
Check if minute value is valid
:param minute: int|string
:return: boolean
"""
return (minute == '*') or (59 >= minute >= 0) | ddd7cf5995805e16b56b6dd844735116685d6a59 | 593,365 |
from datetime import datetime
def georgian_day(date):
""" Returns the number of days passed since the start of the year.
:param date:
The string date with this format %m/%d/%Y
:type date:
String
:returns:
int
:example:
>>> georgian_day('05/1/2015')
121
... | ccf21e3e09a383339a28c6828d27d07cf87f6739 | 593,367 |
def get_boolean(value):
""" Return a bool from value.
Args:
value: A string or bool representing a boolean.
Returns:
If value is a bool, value is returned without modification.
If value is a string this will convert 'true' and 'false'
(ignoring case) to their associated values.
Raises:
V... | 6909461ddef9e9e69d3978a17db209a9acb797db | 593,368 |
def get_value(x):
"""
Extract value from <v,u> data.
"""
return x.value | d89f25e23b5b28cb3d36a1299b1f1fab01be9896 | 593,378 |
def get_ami_info(ec2, ami_id):
"""
Returns information about the specified AMI.
Parameters
----------
ec2 : botocore.client.EC2
AWS EC2 client.
ami_id : str
AMI ID.
Returns
-------
dict
"""
resp = ec2.describe_images(ImageIds=[ami_id])
return resp['Image... | cdb1d05afae5bf0c76df0aa7eca5208771fd2923 | 593,379 |
from typing import Union
from typing import Dict
import collections
def write_roman(num: Union[int, str]):
"""Convert integer to roman number.
Parameters
----------
num: int
integer to convert to roman number
References
----------
https://stackoverflow.com/questions/52554702/roma... | 85b639166b523be2b7752c8e37fe63ccbce949f5 | 593,385 |
def infer(runner, input_tensors):
""" Run loaded subgraphs.
Args:
runner: an instance of Runner.
input_tensors: Input tensors. Format: {name: value}.
Returns:
Output tensors. Format: {name: value}.
"""
return runner.infer(input_tensors) | a8f497052be34ffc9191ae072f2d9355214c4fbe | 593,387 |
import math
def calc_gaussian(val, mean, std):
"""
This function determines the gaussian probability of a given value based on mean and standard deviation.
:param val:
:param mean:
:param std:
:return: numeric probability
"""
variance = float(std) ** 2
pi = 3.1415926
denom = (2... | 0a64123eeb9881d4197e3d126055ed7a2692f56c | 593,393 |
def get_average_brightness(block, size, gradation_step):
"""
Get average brightness of image
param block: mosaic block size
param size: size
param gradation_step: gradation of gray
return int
>>> get_average_brightness(np.ones((3, 3, 3)) * 200, 2, 15)
195
>>> get_average_brightnes... | 0fe0070b3438b64b2bbfa0a85bee39764d3c0523 | 593,397 |
import re
def remove_empty_rules(css: str) -> str:
"""Remove empty rules."""
return re.sub(r"[^\}\{]+\{\}", "", css) | 612e2a5be9bded086e79c4b305ef061616154a15 | 593,399 |
import re
def read_text(file):
"""Reads the text from a plain text file."""
# print(os.path.basename(file))
with open(file, "r") as infile:
text = infile.read()
# print(text[0:100])
text = re.sub("\n", " ", text)
text = re.sub(" ", " ", text)
return text | 965911dc4ba34a7ec1694522deb3945e8d284c1f | 593,402 |
def make_einstring(tn):
"""
Convert a TN into an einsum-style string describing its contraction
"""
# Build einsum terms and free symbols from the nodes of the TN
ein_terms = []
free_syms = []
for node in tn.nodes(as_iter=True, copy_nodes=False, danglers=True):
if node.dangler:
... | a92255b03cc14caf77045879818cd058fba87498 | 593,403 |
def parse_version_tag(version_tag):
"""
:param str version_tag: the version tag.
:return: Given a version tag, return it as a list of ints
:rtype: list[int]
"""
return [int(x) for x in version_tag.lower().replace('v', '').split('.')] | a4f0c3473e5bae57c689c7a62e206314e2dacfea | 593,409 |
def checksum(sin):
"""
Determine validity of a Canadian Social Insurance Number.
Validation is performed using a modified Luhn Algorithm. To check
the Every second digit of the SIN is doubled and the result is
summed. If the result is a multiple of ten, the Social Insurance
Number is considere... | d8b4b5aa7a695ac9ea966aaa916de9a188f6efe6 | 593,413 |
def obj_to_lists(obj_file: str)-> tuple:
"""Convert a obj file into lists"""
# Initialization
vertices = []
normals = []
faces = []
file = open(obj_file, 'r')
lines = file.readlines()
file.close()
# Find data
for line in lines:
if line.startswith('v '):
data... | f86781967d02095f0fc0a778d764e00c4e9f2f64 | 593,414 |
from typing import List
def list_from_dict_key(d: dict, k: str, delim: str=',') -> List[str]:
"""Extract a list from a delimited string in a dictionary.
Parameters
----------
d : dict
The dictionary containing the delimited string.
k : str
The key under which the delimited value ... | 1e8b700a3ef43d8d8a2ec6631958bd78946e75d5 | 593,416 |
def group_uniqnames(group):
"""Return group member uniqnames."""
members = group["members"]
return [x["username"].replace("@umich.edu", "") for x in members] | 6c6dad162caf0376c5ba4ca48110b5b1c48809c6 | 593,417 |
import socket
import fcntl
import struct
def address_by_interface(ifname):
"""Returns the IP address of the given interface name, e.g. 'eth0'
Parameters
----------
ifname : str
Name of the interface whose address is to be returned. Required.
Taken from this Stack Overflow answer: https:/... | 4cc44765556f33b66344e0a96d81f8ff22af582a | 593,421 |
def get_endpoint(url):
"""Get the parent url of this url."""
return url.rsplit("/", 1)[0] | 42022b2e897a76ca56bb70d72e45c6eaea478d95 | 593,424 |
def boardToArray(board):
"""
Function that converts a board (in FEN notation) in a list of lists of lines of the chess board
Parameters :
-board : the current board
Returns :
-arrayBoard : a list composed of lists(=lines) of the strings(=pieces) of the boards
"""
#replacement o... | de097e22206d9c8b99f83263ec8e37ed87e7a324 | 593,425 |
def ha_to_ev(value_in_ha):
"""Converting unit in Ha to eV, returns eV value"""
umrechnungs_faktor = 27.2113825435
value_in_eV = value_in_ha * umrechnungs_faktor
return value_in_eV | 86f8e4a107ea832d6a82c3ccb1cbf47318bafa2f | 593,428 |
def get_color_cycle(ax):
"""Get color cycle iterator from multiple versions of matplotlib axes
Parameters
----------
ax : :class:`matplotlib.axes.Axes`
Returns
-------
iterator
Iterator over colors, passable to matplotlib `color` keyword
"""
if hasattr(ax, "_get_lines"):
... | 7b0ece9c2626579850af1732148b3bf32a34b803 | 593,432 |
def metrics(table):
"""Calculate the metrics for a set of crater matches.
Arguments:
table : Pandas table with the columns
N_match
N_detect
N_csv
Returns:
table : modified table with the additional columns
frac_new_csv : fract... | a4ff1c019442d8334e26e30bf5126c807083e766 | 593,437 |
import re
def email_phone_extractor(text):
"""
Finds emails and phone numbers from text using regex
:param text:
:return:
"""
email = re.findall(r"[\w\.-]+@[\w\.-]+\.\w+", text)
phone_number = re.findall(r"[\+\(]?[1-9][0-9 .\-\(\)]{8,}[0-9]", text)
return email, phone_number | 7330543856b3a74246f2d6a109e0fb4047931652 | 593,438 |
def _dict_to_list(artifact_dict):
"""Returns a list artifacts from a dict of name to version."""
return [
":".join([name, version])
for (name, version) in artifact_dict.items()
] | df903cf36deaf1eacdb314cd84413da10e1a86ee | 593,441 |
import re
def StrPrefixOf(prefix, input_string):
"""
Return True if the concrete value of the input_string starts with prefix
otherwise false.
:param prefix: prefix we want to check
:param input_string: the string we want to check
:return: True if the input_string starts with prefix else fal... | c0b64695d75ed03773045c21ad8f691ad4c020e9 | 593,444 |
def should_print_row(i: int, max_entries: int, num_entries: int):
"""Make decision to print row or not based on max_rows.
:param i: index of row
:type i: int
:param max_entries: max number of entries for the table
:type max_entries: int
:param num_entries: number of possible entries (the full l... | 366c2428a9c5f0193df5d47b96d9ff0b880acf39 | 593,446 |
def get_NA_features(df):
"""identify features containing NA values
Parameters
----------
df : DataFrame
input dataset
Returns
-------
list : features containing missing values
"""
return df.isna().sum()[df.isna().sum() > 0].index.tolist() | fa8a0023255029e7a9bdfbd0f6a21d0efde6bcd1 | 593,448 |
def chunkInto64CharsPerLine(data, separator=b'\n'):
"""Chunk **data** into lines with 64 characters each.
:param basestring data: The data to be chunked up.
:keyword basestring separator: The character to use to join the chunked
lines. (default: ``b'\n'``)
:rtype: basestring
:returns: The *... | e8e1be8d733af70633f93a2f666ad3b664bcd853 | 593,453 |
def get_legacy_qos_policy(extra_specs):
"""Return legacy qos policy information if present in extra specs."""
external_policy_name = extra_specs.get('netapp:qos_policy_group')
if external_policy_name is None:
return None
return dict(policy_name=external_policy_name) | 826133833a0b9e90046bb5d984b958825328de94 | 593,455 |
def noy(Ky, M, rho, w):
"""
Calculates the number of units at the plate.
Parameters
----------
Ky : float
The masstransfer coefficent Ky, [kmol / (m**2 * s)]
M : float
The molar mass, [kg / kmol]
rho : float
The destiny , [kg / m**3]
w : float
The speed [m... | 42c51fa168ecfdec0436933a1da2feb3d178174f | 593,460 |
def push(package, release, media_type, blob, force, package_class, **kwargs):
"""
Push a new package release in the the datastore
Args:
package (:obj:`str`): package name in the format "namespace/name" or "domain.com/name"
release (:obj:`str`): the 'exact' package release (this is not a release... | 97fdfb724da3789bcc5f92f566174843393f0f8c | 593,463 |
def is_blank_line(line, allow_spaces=0):
"""is_blank_line(line, allow_spaces=0) -> boolean
Return whether a line is blank. allow_spaces specifies whether to
allow whitespaces in a blank line. A true value signifies that a
line containing whitespaces as well as end-of-line characters
should be con... | 7134381c54d9db56e8b297b337cb49fbdcc3c5a8 | 593,465 |
def remove_carts(lines):
"""Remove carts from lines, replacing them with normal tracks."""
for row_no, row in enumerate(lines):
for col_no, square in enumerate(row):
if square in '<>':
lines[row_no][col_no] = '-'
elif square in 'v^':
lines[row_no][... | cfc2c57b0a551f30f6f3b3618764b90e76b4b540 | 593,468 |
def check_repeated(df,sel_col,id):
"""
Checking for # of unique combinations of a selection of attributes.
Different IDs sometimes do not guarantee uniqueness
Parameters:
-----------
df: pd.DataFrame
sel_col: list of column names
Selection of columns where number of unique co... | 593e64e51239e4e556233d225124858785b5c81f | 593,469 |
def user_check(message):
"""
Check if user wants to proceed visualization when the API request number exceeds 200
Parameters
----------
message : string
Message to indicate users the options
"""
check = input(message)
if str(check) == "yes" or str(check) == "no":
return ... | 5cdf2894b13a8b0d1ee582cb4052fc0c628fd4ed | 593,472 |
def get_routes(solution, routing, manager):
"""Get vehicle routes from a solution and store them in an array."""
# Get vehicle routes and store them in a two dimensional array whose
# i,j entry is the jth location visited by vehicle i along its route.
routes = []
for route_nbr in range(routing.v... | bbbf4164686cfa2997607921f10516d5a3564a67 | 593,473 |
import math
def tile_ref(position, tile_size):
"""Returns the column and row of the tile at the given x and y coordinates.
position is a pair of x, y coordinates as a 2-item sequence
tile_size is the size of each tile as an int"""
# The coordinates are divided by the tile size and rounded down t... | 76c5e3ff537094c225bc03059e5acf2b8607d152 | 593,477 |
def get_sentiment(score):
"""
Calculates the sentiment based on the compound score.
"""
result = 0 # Neutral by default
if score >= 0.05: # Positive
result = 1
elif score <= -0.05: # Negative
result = -1
return result | e0f261a14d7b83f82ee5d9472802bd12500efe78 | 593,478 |
import re
def parse_auditory_number(text):
"""
Get directions to auditorium including building, floor.
Parametrs:
text - string, number as represented in schedule ("42з")
Returns:
string, formatted directions info
"""
numbers = re.findall(r'\b\d+[а-я]?\b', text)
if not numbers:
return ... | 55ec7ffddfed7ad2e363ca12681ace42da0f17b2 | 593,484 |
def _check_empty(circuits):
"""Returns true if circuits is the empty tensor."""
return len(circuits) == 0 | 63e5ddcb232e5e36c2d1e8d63ef1924683ab0718 | 593,487 |
def argvquote(arg, force=True):
""" Returns an argument quoted in such a way that that CommandLineToArgvW
on Windows will return the argument string unchanged.
This is the same thing Popen does when supplied with an list of arguments.
Arguments in a command line should be separated by spaces; this
f... | 5559ff1a3e4c0fd5abbeb2c06a1c00089113690f | 593,488 |
import hmac
import hashlib
def hmac_sha256_digest(key, msg):
"""
Return the HMAC-SHA256 message authentication code of the message
'msg' with key 'key'.
"""
return hmac.new(key, msg, hashlib.sha256).digest() | 182161612c0e94e5d80d53813bf174234d952b3f | 593,489 |
def rivers_with_station(stations):
"""
function that returns a set of the rivers with at least one station on them
if passed a list of MonitoringStation objects
"""
riversWithStation = set()
for station in stations:
if station.river is not None:
riversWithStation.add(station.river)
... | fe12df8092a2245424a114e406abdf4acd367f27 | 593,490 |
def relist_streamlines(points, offsets):
""" Given a representation of a set of streamlines as a large array and
an offsets array return the streamlines as a list of shorter arrays.
Parameters
-----------
points : array
offsets : array
Returns
-------
streamlines: sequence
"""
... | bff394b1a488ec29f0d26bc46a04d6bac7c24908 | 593,495 |
def get_train_validation_set(data, train_ind, val_inds):
"""
Get the train and test set given their indices.
"""
training_data = data[train_ind]
validation_data = data[val_inds]
return training_data, validation_data | d87b63b206aff3e3055c3edbec83e2422b1a35a4 | 593,497 |
def _get_sel_code(sel, **kwargs):
"""
Get selection code.
Args:
sel (str):
| selection string (case independant)
| "system" or "all": all atoms
| "protein": protein atoms
| "ca" or "calpha": CA atoms
| "bb" or "backbone": backbone atoms
Returns:... | 1572a0e23345349da04488293b4ecb890972e7cd | 593,498 |
def saves_to_partial_epochs(epochs, saves):
"""epochs is a list of epochs, and saves[k] is a list of all the saves for epoch k. This utility converts these two
lists into a single list that shows all of the (fractional) epochs at which saves occur. For instance,
epochs = [0,1,2,3] and saves=[[0,1],[0,1],[0,... | faa8633d2c4b43411c6c98184d11cce489d2438b | 593,499 |
def get_monthly_report_subject(month_day, person):
"""
Returns subject string for monthly report email
`month_day:datetime.date` - any date for the month we are reporting for
`person:str` - reporting person's name, e.g. 'Jon Doe'
"""
calendar_time = "{year}/{month:02}".format(
year=mont... | 5a224c8656afa694fbec73a4c4eefc7361bff1cc | 593,501 |
def read_vault_secret(vault_client, path_to_secret, vault_value_key="value"):
"""Read a vault secret given a {vault_client} and {path_to_secret}
If the secret is "complex", in that it's more than just key/value,
then passing `vault_value_key=None` will return the blob from vault
and you can do w/ it as... | 62797d4847aed4bb722c00b232ee7d5f2b848976 | 593,502 |
def grow_zone_stripper(grow_zone):
""" Strips brackets off grow zones """
if ',' in grow_zone:
grow_zone = grow_zone[1:-1]
return grow_zone
else:
return grow_zone | 4464d26162d52f789585c1a8af4f1d127de413bc | 593,503 |
from typing import Tuple
from typing import Any
def list_all_pages(func, data_field: str, *args, **kwargs) -> Tuple[Any, ...]:
"""Collects all data items from a paginator-based 'List' API.
Args:
func: The GCP API method that supports paged responses.
data_field: The field in a response object... | 282cfdbfbb12dcb46155faeef77303fcf6ddf744 | 593,504 |
def blit_text(surface, font, position, text, font_color,
background_color=None, size=None, anchor="NW", fill=True):
"""
Blits text into a pygame Surface following the parameters described below
:param surface: Destination surface
:type surface: pygame.Surface
:param font: Text font
... | d5ec238f887a3413c927869a426e3bacf075ab99 | 593,505 |
def trim_to_constant_numtimesteps(ds):
"""
Trims a :class:`DataSet` so that each circuit's data comprises the same number of timesteps.
Returns a new dataset that has data for the same number of time steps for
every circuit. This is achieved by discarding all time-series data for every
circuit with... | d88c535d6d0ae34d3d136b4606ff19c8c413ef80 | 593,508 |
def _get_file_stats(commit_files):
"""
Get total additions and deletions from commit_files
:param commit_files: List of database file objects
:return: Total additions and deletions for files
"""
additions = 0
deletions = 0
for commit_file in commit_files:
additions += commit_file... | 63db9b5a8313e3d623299f7831a43987f2bdb2a0 | 593,510 |
def get_pxe_iso(env):
"""Return the disk image for the PXE boot iso."""
name = env.config.require('ravello', 'pxe_iso')
images = env.client.call('GET', '/diskImages')
for image in images:
if image['name'] == name:
return image
raise RuntimeError('PXE ISO `{}` not found.'.format(n... | ba80cf51557af3533afb497601bb4f569ab8d490 | 593,512 |
def is_iterable_but_not_string(obj):
"""Return True if ``obj`` is an iterable object that isn't a string."""
return (hasattr(obj, '__iter__') and not hasattr(obj, 'strip')) | 6a30988a885e43606234b6850cbb564ba9cdf4b7 | 593,515 |
def cli(ctx, feature_id):
"""Get analyses associated with a feature
Output:
Feature analyses
"""
return ctx.gi.feature.get_feature_analyses(feature_id) | 81f3a05056efd2e231bf602af1257434b12e908e | 593,517 |
def _split_rpdr_key_line(text_line):
"""Remove newline chars and split the line by bars."""
return tuple(text_line.replace('\r', '').replace('\n', '').split('|')) | 0fd7f027f68b2dd04dc36dc8b0c8568aaaa47483 | 593,518 |
def get_scope_preview(value, n):
"""
Get the top N lines of a ``scope`` list for an individual :model:`rolodex.ProjectScope`.
**Parameters**
``value``
The ``scope`` value of an individual :model:`rolodex.ProjectScope` entry
``value``
Number of lines to return
"""
return "\n... | e2c733c29ab5ca7f05c5189d488d5c7693e33975 | 593,519 |
def merge_status(main, other):
"""
Merge two status tuples.
"""
new_code = main[0] | other[0]
new_out = "%s%s" % (main[1], other[1])
new_err = "%s%s" % (main[2], other[2])
return new_code, new_out, new_err | 8a9f7cb70458687ff0ddfabe78df6b222fb6de72 | 593,521 |
def get_version_from_request(req):
"""Attempt to extract the API version string."""
for part in req.path.split('/'):
if '.' in part and part.startswith('v'):
return part
return 'N/A' | 5cfcdf9c12d195c577bc1009df2788e87b15ef75 | 593,525 |
import json
def load_json(filepath):
"""Load a json file."""
with open(filepath, "r") as fp:
json_obj = json.load(fp)
return json_obj | 9e73f3ad24c38d08883ff23af91af1295fea1176 | 593,526 |
def get_node_subdir(node):
"""
Get package subdir that a node should be copied to
Returns:
dir str
"""
if node.Class() in ["DeepWrite", "Write"]:
return "images/outputs"
return "images/inputs" | 057f44a34bf1510a09d4ab8d4785e3c50a0fbb60 | 593,527 |
def getAllFactors(n):
"""Get a list of factors of n
Does not include 1 and n
"""
factorList=[]
for factors in range(2, n):
if n%factors == 0:
factorList.append(factors)
return factorList | d3fdcbd4c6227511689200ba7e210c78f03fe66d | 593,536 |
def del_from_list(target, index_positions):
"""
Deletes the elements in a list given by a index_positions list
:param target: a target list to have items removed
:param index_positions: a list of index positions to be removed from
the target list
:type target: list
... | c5837d16f608cf7e8a404223cd0c7d3b3e02042f | 593,537 |
def spritecollideany(sprite, group, collided = None):
"""pygame.sprite.spritecollideany(sprite, group) -> sprite
finds any sprites that collide
given a sprite and a group of sprites, this will
return return any single sprite that collides with
with the given sprite. If there are no coll... | fa83cab01c0857fe4ccb64a381fa79353805365d | 593,538 |
def patch_random_choice(x, element):
"""Dummy function for ``np.random.choice`` to make output deterministic. This dummy function
just returns the element of ``x`` specified by ``element``."""
if isinstance(x, int): # np.random.choice can accept an int or 1D array-like input
return element
ret... | 18b64065334f716973d88bde0c0fe6c15aba4f83 | 593,539 |
def card(id, title, s):
"""Build a card by ID."""
return """<card id="%(id)s" title="%(title)s"><p>%(s)s</p></card>""" % \
{'id': id, 'title': title, 's': s} | a112372f8fa7cc159df57cf465c2838114353992 | 593,542 |
def _join_prefix(prefix, name):
"""Prepend `prefix` and a dot if `prefix` is non-empty."""
return prefix + '.' + name if prefix else name | 2213210222372842bd81a14d5ff6cae67e099175 | 593,543 |
def PyDateTime_TIME_GET_FOLD(space, w_obj):
"""Return the fold, either 0 or 1
"""
return space.int_w(space.getattr(w_obj, space.newtext("fold"))) | aa46ad9e6163d7ade3da3269913b34fc0e419962 | 593,545 |
def list_number(doc, par, prev=None, level=None, num=True):
"""
Makes a paragraph into a list item with a specific level and
optional restart.
An attempt will be made to retreive an abstract numbering style that
corresponds to the style of the paragraph. If that is not possible,
the default num... | 882d9c209c98cf6dbf260e966d1d0f729cad9feb | 593,546 |
def is_leap_year(year: int) -> bool:
"""Checks if year is a leap year.
ASSUMPTION: To be a leap year, the year number must be divisible by four,
except for end-of-century years, which must be divisible by 400.
Args:
year (int): Year
Returns:
bool: Is leap year or not
... | 11d5b7ce1f4f69a96ea6182590aebbf28cba3454 | 593,552 |
def set_bdev_nvme_options(client, action_on_timeout=None, timeout_us=None, retry_count=None, nvme_adminq_poll_period_us=None):
"""Set options for the bdev nvme. This is startup command.
Args:
action_on_timeout: action to take on command time out. Valid values are: none, reset, abort (optional)
... | d32401b6e396dba89e4a3b879a6d0a59317b3433 | 593,554 |
import math
def twisting_imperfection(x, y, z, length, theta_twist, n1, n2, **kwargs):
""" Returns the twisting imperfection of the node.
:param float x: x coordinate of node
:param float y: y coordinate of node
:param float z: z coordinate of node
:param float length: total length of the compone... | 568ddfbedb5c7865492c643eaae0234cefa7b6d8 | 593,555 |
import math
def haversine(x):
"""
Computes the haversine formula
Parameters
----------
x : angle in radians
Returns
-------
: square of sine of half the radian (the haversine formula)
Example
-------
>>> haversine(math.pi) # is 180 in radians, hence sin of 90... | 362816a4558959f4514b204cbc711a8dddb85006 | 593,556 |
def __to_js(var, value):
"""
Encapsulates python variable into a javascript var.
:param var: The name of the javascript var.
:param value: The value to set.
"""
return '<script type="text/javascript">var %s = "%s";</script>' % (var, value)
return join(dirname(file), 'templates/') | b29b2c6234f21d4a69b135803918cd33076ae3cd | 593,557 |
import re
def is_regex_search(regex_pattern, search_context):
"""
Wrapper method to check if the regex pattern is within the search context.
If it is, returns True. False if not.
"""
regex_search = re.compile(regex_pattern)
if regex_search.search(search_context) is not None:
return T... | 8718fb0fd34033d8f56436562e29ce12469e17ab | 593,564 |
def get_storage_object_ids_ebs(self, match_all=True, **kwargs):
"""Retrieves ObjectIds for EBS Snappables from Polaris
Args:
match_all (bool): Set to False to match ANY defined criteria
tags (dict): Optional allows simple qualification of tags
kwargs (dict): Optional any top level objec... | 7436e86830da71c1bc203fe5529d71a9eb6ebc6d | 593,565 |
def extract_commit_components(commits):
"""
Extract components from individual commits to create lists for each component
:param commits: List of database commit objects
:return: Dictionary with all the components from the commits
"""
commit_components = {
'messages': [],
'reposi... | 3b9b428e55a6ff75b721b22cfdb4e1bc725da430 | 593,566 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.