content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def delete_redshift_cluster(config, redshift):
""" Deletes the Redshift cluster specified in config
Args:
config: a ConfigParser object
redshift: a boto3 client object for the AWS Redshift service
"""
try:
print("Deleting Redshift Cluster: ", config['CLUSTER']['IDENTIFIER'])
... | 2267eb4f017354563c9a7cf047a3a84983cd0044 | 7,659 |
def add_trailing_load(axle_spacing, axle_wt, space_to_trailing_load,
distributed_load, span1_begin, span2_end, pt_load_spacing=0.5):
"""Approximates the distributed trailing load as closely spaced point loads.
The distributed trailing load is approximated as discretly spaced point
loads. The point ... | 3eac900cff7d5e66c399e7f846d66aeff3e7389c | 7,662 |
def str_append(string, add):
"""Append add in end string. Example: str_append('hou', 'se'); Return='house'"""
return string + str(add) + "\n" | efbc9a085d1e63f290af3e6c447cde13bce5f5d0 | 7,663 |
def create_function(treatment_system, parameter, values):
"""
Creates a function based on user input
"""
func = str(treatment_system.loc[0, parameter])
func = func.replace(' ', '')
for key, value in values.items():
func = func.replace(key, str(value))
return func | d0afaf42e50aef943b7551c60f19d180bbbeba0b | 7,664 |
def unformat(combination: str) -> str:
"""Unformats a formatted string to it's original state"""
return str(combination).replace("<", "").replace(">", "") | d017903ddaac78adf5085198d25eb508b62a78b4 | 7,665 |
import re
def _size_to_bytes(size):
"""
Parse a string with a size into a number of bytes. I.e. parses "10m", "10MB", "10 M" and other variations into the
number of bytes in ten megabytes. Floating-point numbers are rounded to the nearest byte.
:type size: ``str``
:param size: The size to parse, given as a stri... | 833657e51bb2c54b0e86684759e263d2f8b03ffe | 7,666 |
def is_valid_group(group_name, nova_creds):
"""
Checks to see if the configuration file contains a SUPERNOVA_GROUP
configuration option.
"""
valid_groups = [value['SUPERNOVA_GROUP'] for key, value in
nova_creds.items() if 'SUPERNOVA_GROUP'
in nova_creds[key].k... | 6f94e88cfcea8775bab3c05a0720ba7df11f68cc | 7,669 |
def insertDoubleQuote(string, index):
""" Insert a double quote in the specified string at the specified index and return the string."""
return string[:index] + '\"' + string[index:] | 00d16f3bc619765895408f9fcdd3a7a6e428b153 | 7,672 |
def powerlaw(x, a, b, c):
"""Powerlaw function used by fitting software to characterise uncertainty."""
return a * x**b + c | e67a0be2f5faaff7867b713b43caec48910bad87 | 7,673 |
def readPeakList(peak_file):
"""
Read in list of peaks to delete from peaks_file. Comment lines (#) and
blank lines are ignored.
"""
f = open(peak_file,'r')
peak_list = f.readlines()
f.close()
peak_list = [l for l in peak_list if l[0] != "#" and l.strip() != ""]
peak_list = [... | 7c99f9fb18b36b658fe142a43adf18db7c42c7bd | 7,675 |
import numpy
def get_pandas_field_metadata(pandas_col_metadata, field_name):
"""
Fetch information for a given column. The column statistics returned
will be a bit different depending on if the types in the column are a
number or a string. 'NAN' values are stripped from statistics and don't
even s... | cbf1a740a202c36fa7b008451d44582e195d71f8 | 7,678 |
def deep_replace(arr, x, y):
"""
Help function for extended_euclid
"""
for i in range(len(arr)):
element = arr[i]
if type(element) == list:
arr[i] = deep_replace(element, x, y)
else:
if element == x:
arr[i] = y
return arr | 55ef1c7efe04d436f9ce96bda0f565a092131400 | 7,679 |
def find_pmp(df):
"""simple function to find Pmp on an IV curve"""
return df.product(axis=1).max() | 5ed7c14bc58a62f6168308ccd1dfa17e56e2db89 | 7,680 |
def readable_timedelta(days):
"""Print the number of weeks and days in a number of days."""
#to get the number of weeks we use integer division
weeks = days // 7
#to get the number of days that remain we use %, the modulus operator
remainder = days % 7
return "{} week(s) and {} day(s).".format(w... | 120f517939842b4e0686a57a3117221e3db63004 | 7,681 |
def isMessageBody(line: str) -> bool:
"""
Returns True if line has more than just whitepsace and unempty or is a comment (contains #)
"""
return not (line.isspace() or line.lstrip().startswith('#')) | 990ae3ff01f794a6c8d4d45ecb766a763c51dff8 | 7,683 |
def get_combinations(limit, numbers_count, combination):
"""Get all combinations of numbers_count numbers summing to limit."""
if sum(combination) >= limit:
return None
if numbers_count == 1:
return [combination + [limit - sum(combination)]]
combinations = []
for number in range(1, l... | caecaeb8a5ef5f68bc47936c3b4db3d7514b6c52 | 7,685 |
def bit_list_to_int(bit_list):
"""
Converts binary number represented as a list of 0's and 1's into its corresponding base 10
integer value.
Args:
bit_list: a binary number represented as a list of 0's and 1's
Returns:
The base 10 integer value of the input binary number
"""
... | ade66899fe1d23a22c76cccf4ba57e9ad9bf0ba1 | 7,686 |
def max_labor_budget_rule(M):
"""
Put upper bound on total labor cost.
Using individual shift variables multiplied by their length and a tour
type specific cost multiplier. Could easily generalize this to make costs
be complex function of time of day, day of week, shift length, tour type,
o... | f2637e4b2dba8cc4eb6e5afcae57c45d1b9560d7 | 7,687 |
import re
def email(value: str):
"""
Extract email from document
Example Result: ['crazyvn@gmail.com', 'feedback@tp.com']
"""
_email_pat = r'[a-z0-9\.\-+_]+@[a-z0-9\.\-+_]+\.[a-z]+'
return re.findall(_email_pat, value) | c8f3dcb4163e99f0aefe7eb42e61b127ffbaa393 | 7,688 |
def TransposeTable(table):
"""Transpose a list of lists, using None to extend all input lists to the
same length.
For example:
>>> TransposeTable(
[ [11, 12, 13],
[21, 22],
[31, 32, 33, 34]])
[ [11, 21, 31],
[12, 22, 32],
[13, None, 33],
[None, None, 34]]
"""
... | d53dc20a9eff391560269e818e99d41f8dc2ce94 | 7,689 |
import os
import logging
def checksum_from_label(path):
"""Extract checksum from a label rather than calculating it.
:param path: Product path
:type path: str
:return: MD5 Sum for the file indicated by path
:rtype: str
"""
checksum = ""
product_label = path.split(".")[0] + ".xml"
... | 69da6b07d091b0c296d09ec0d9a3d0586c34b978 | 7,690 |
def vvisegment2dict( link):
"""
Intern rutine for å gjøre om visveginfo-data til håndterbar liste
"""
start = round( float( link['FromMeasure'] ), 8 )
slutt = round( float( link['ToMeasure'] ), 8 )
mydict = { 'vegref' : str( link['County']).zfill(2) + str( link['Municipality'] ).zfill(2... | ad8c5de2065ee2e935b63674c7f4d11ba11bcff8 | 7,691 |
def percentage(value):
"""Return a float with 1 point of precision and a percent sign."""
return format(value, ".1%") | 43567c120e4994b54a92570405c02934eb989a6f | 7,692 |
def decode(packed_list):
"""
implement the function packed the string
"""
# Empty list of tuple
decode_str = ""
list_len = len(packed_list)
for i in range(list_len):
# element of packed list
str_tuple_count = packed_list[i]
# find number of counting from tuple
... | d6fe8de66ead935a14e99b069d3b416089d5a93d | 7,695 |
def travel_space_separated(curr):
"""Print space separated linked list elements."""
if curr is None:
return ""
print(curr.data, end=' ')
travel_space_separated(curr._next) | 19213588f06a569560b236563975bcd6cb5254a0 | 7,696 |
def identity_matrix(dim):
"""Construct an identity matrix.
Parameters
----------
dim : int
The number of rows and/or columns of the matrix.
Returns
-------
list of list
A list of `dim` lists, with each list containing `dim` elements.
The items on the "diagonal" are ... | dd37f0c7df41478e23dd26df727341a37a201ec1 | 7,697 |
def kg2m3H2O_hot(kg):
"""kg -> m^3 (50 C hot water)"""
return kg/988.1 | 060b039db404014ab6cbea6aa5e416efc70aa8a2 | 7,698 |
import yaml
def load_yaml(file_path):
"""Load a yaml file into a dictionary"""
try:
with open(file_path, 'r') as file:
return yaml.safe_load(file)
except EnvironmentError: # parent of IOError, OSError *and* WindowsError where available
return None | 3d4fa37794bc99c352959e49057d2e9cfb0d4c92 | 7,700 |
import time
def timed_call(f, args):
"""Call function f with arguments args and time its run time.
Args:
f: The function to call
args: The arguments to pass to f
Returns:
Return the result of the function call and how much time it takes as tuple e.g. (result, time).
"""
s... | e592ecdf5ebb4aa3391b2500b2a3a20d2faa9b40 | 7,703 |
def count_words(texts):
"""
Counts the words in the given texts, ignoring puncuation and the like.
@param texts - Texts (as a single string or list of strings)
@return Word count of texts
"""
if type(texts) is list:
return sum(len(t.split()) for t in texts)
return len(texts.split()) | f08cbb1dcac3cbd6b62829cf4467167ae9b7694e | 7,704 |
def get_subnetwork(project_id, context):
""" Gets a subnetwork name. """
subnet_name = context.properties.get('subnetwork')
is_self_link = '/' in subnet_name or '.' in subnet_name
if is_self_link:
subnet_url = subnet_name
else:
subnet_url = 'projects/{}/regions/{}/subnetworks/{}'
... | de0217b7a78d3278d6dbf70db10b4c270aff2b15 | 7,705 |
def quadraticEval(a, b, c, x):
"""given all params return the result of quadratic equation a*x^2 + b*x + c"""
return a*(x**2) + b*x + c | cfb808435b50ec262ec14cd54cf9caf30f2bc4b8 | 7,706 |
def stringdb_escape_text(text):
"""Escape text for database_documents.tsv format."""
return text.replace('\\', '\\\\').replace('\t', '\\t') | 5d41b0b224cb314141b669ff721896d04a2fe2e8 | 7,707 |
import argparse
def parse_args():
"""
Parse command arguments.
"""
parser = argparse.ArgumentParser(description='validate data from starbust algo I for test (ex. chessboard test)')
parser.add_argument('path', help='path to starburst filtered file')
return parser.parse_args() | 544372e75b2dd56923883f13b6c7f3070ecc9e14 | 7,708 |
def friends(graph, user):
"""Returns a set of the friends of the given user, in the given graph"""
return set(graph.neighbors(user)) | 125c3cc21be4cc29f9ff6f0ff0bb60b35a1074ba | 7,710 |
def diagonal(a, offset=0, axis1=None, axis2=None, extract=True, axes=None):
"""
diagonal(a, offset=0, axis1=None, axis2=None)
Return specified diagonals.
If `a` is 2-D, returns the diagonal of `a` with the given offset,
i.e., the collection of elements of the form ``a[i, i+offset]``. If
`a` h... | e18a9ca2dcab7beb5891f701cdc0f26c3943f749 | 7,711 |
def ctd_sbe16digi_preswat(p0, t0, C1, C2, C3, D1, D2, T1, T2, T3, T4, T5):
"""
Description:
OOI Level 1 Pressure (Depth) data product, which is calculated using
data from the Sea-Bird Electronics conductivity, temperature and depth
(CTD) family of instruments.
This data product... | 3756752c661773bd74436311a278efdaa3d3913f | 7,714 |
import hashlib
def sha256(file: str):
"""
Reads a file content and returns its sha256 hash.
"""
sha = hashlib.sha256()
with open(file, "rb") as content:
for line in content:
sha.update(line)
return sha.hexdigest() | c6babc2939e25228df25827a5a0b383d6c68dd07 | 7,715 |
def lookup_capacity(lookup, environment, ant_type, frequency,
bandwidth, generation):
"""
Use lookup table to find the combination of spectrum bands
which meets capacity by clutter environment geotype, frequency,
bandwidth, technology generation and site density.
"""
if (environment, ant_ty... | 3bd132f97022acfe33c4bc6d706265e808679eae | 7,718 |
import json
def to_json(response):
""" Return a response as JSON. """
assert response.status_code == 200
return json.loads(response.get_data(as_text=True)) | 4fb4d62eb8b793363394b6d0759a923f90315072 | 7,719 |
def dots2utf8(dots):
""" braille dots to utf-8 hex codes"""
code=0
for number in dots:
code += 2**(int(number)-1)
return hex(0x2800 + code) | 0406c3cf18d5dbd66ea35b0862785371cdd68796 | 7,723 |
import ast
def doCompare(op, left, right):
"""Perform the given AST comparison on the values"""
top = type(op)
if top == ast.Eq:
return left == right
elif top == ast.NotEq:
return left != right
elif top == ast.Lt:
return left < right
elif top == ast.LtE:
return left <= right
elif top == ast.Gt:
retur... | b82a1c4d101428cf9ded532d65539cfe3195d8a1 | 7,725 |
def get_interface_by_name(interfaces, name):
"""
Return an interface by it's devname
:param name: interface devname
:param interfaces: interfaces dictionary provided by interface_inspector
:return: interface dictionary
"""
for interface in interfaces:
if interface['devname'] == name:... | 9d63bf667a0677ba7d0c3fdde2b4b35affc3b72b | 7,726 |
import unicodedata
def trata_texto(texto):
"""
Trata textos convertendo para maiusulo,\n
sem acentos e espaços indesejaveis.
"""
texto = texto.strip().upper()
texto = unicodedata.normalize("NFKD", texto)
texto = texto.encode("ascii", "ignore")
texto = texto.decode("utf-8").upper()
# ... | 0cced9e55fd3fc15a9cdbaa3899519658668025c | 7,727 |
def normalize_trans_probs(p):
"""
Normalize a set of transition probabilities.
Parameters
----------
p : pandas.DataFrame, dtype float
Unnormalized transition probabilities. Indexed by
source_level_idx, destination_level_idx.
Returns
-------
pandas.DataFrame, dtype floa... | d484c4ac08ee785e5451b1aa92ff2b85fc945384 | 7,728 |
def get_number_of_ones(n):
"""
Deterine the number of 1s ins the binary representation of
and integer n.
"""
return bin(n).count("1") | 83fb14c29064008dd9f8e7ecea4c1d9dfae1dafa | 7,729 |
from typing import Iterable
from typing import Dict
from typing import Sequence
import hashlib
import mmap
def verify_checksums(sources: Iterable[str], hashes: Dict[str, Sequence[str]]) -> bool:
"""Verify checksums for local files.
Prints a message whenever there is a mismatch.
Args:
sources: An... | 95abd66c3e6a007b8df8b2caaecde8a85a1f0886 | 7,730 |
def add_column(colname, desc=None):
"""Adds column in the form of dict."""
return {'name': colname, 'desc': desc} | e0b985f71e17bfef6096d1433c84b5c163d343ff | 7,732 |
def _extreact_qml_file_info(file):
"""Returns file object in QML-ready format"""
return {
"name": file["name"],
"path": file["path"],
"isFile": file["is_file"],
"isDir": file["is_dir"],
"level": file["level"]
} | 4d28a0c1e440023ca887a693a2aea5dbd71d336b | 7,734 |
def check_cn_match(sv_list, cn_increase, cn_decrease, final_cn):
"""
Check that the CNV combination produces the right final copy number.
"""
if sv_list == []:
return False
initial_cn = 2
for sv in sv_list:
if sv in cn_increase:
initial_cn += 1
if sv in cn_dec... | a9d45b1421b5b6f5ce085df7e2f0c8040bffd163 | 7,735 |
def rotateMatrix(m):
"""
rotate matrix
:param m: matrix
:type m: list of list of integers
:return: rotated matrix
:rtype: list of list
"""
for i in range(int(len(m) / 2)):
last_layer = len(m) - i - 1
for j in range(i, last_layer):
offset = j - i
to... | 198c8c28c29c49fee1d26d603e52ec2da43d82a5 | 7,736 |
import re
def GetUniqueName(context, name):
""" Fixup any sbsar naming collision """
foundName = False
nameCount = 1
lastChar = ''
for sb in context.scene.loadedSbsars:
if sb.name.startswith(name):
foundName = True
# find the highest value suffix on the name
... | fe8b868ec791af091eb0e78abea2549b7e724adf | 7,737 |
def get_least_sig_bit(band):
"""Return the least significant bit in color value"""
mask = 0x1
last_bit = band & mask
return str(last_bit) | 9d56bc5fdbf613f31bf7b21ee08f4f753b3a92db | 7,738 |
import os
import json
import subprocess
import re
def get_status(jobdir, jobid=None):
"""
Given list of jobs, returns status of each.
"""
cmd_template = "aws batch describe-jobs --jobs {}"
if jobid is None:
print(("Describing jobs in {}/ids/...".format(jobdir)))
jobs = os.listdir(... | 665ca433ca90ed7d0851bfd4d0d1a1e800fcc4ad | 7,742 |
def denormalize_image(image):
""" Undo normalization of image. """
image = (image / 2) + 0.5
return image | c49a1465d89e317a1c8013969fbee913bf705f4a | 7,744 |
def find_overlapping_selections(selections, selection_strings):
"""
Given a list of atom selections (:py:class:`scitbx.array_family.flex.bool`
arrays) and corresponding selection strings, inspect the selections to
determine whether any two arrays overlap. Returns a tuple of the first pair
of selection string... | fffd25a98cbb2184d372c5904718f30cd7c97d1a | 7,745 |
import imghdr
def check_bmp(input_file_name):
""" Check if filename is a BMP file
:param input_file_name: input file name
:type input_file_name: string
:return whether the file is .bmp
:rtype boolean
"""
return 'bmp' == imghdr.what(input_file_name) | 3a8749832418d3976825a79a0bd89c7a77649fe8 | 7,746 |
import socket
def allowed_gai_family():
"""
https://github.com/shazow/urllib3/blob/master/urllib3/util/connection.py
"""
return socket.AF_INET #* this to force use ipv4 (issue with ipv6, get 2s delay) | 97d983d7c573ba73a2833ca07513a37ce17b521d | 7,748 |
def _get_list_pairs(pairs, idx_class_dict, num_feature):
"""Creates flattened list of (repeated) pairs.
The indexing corresponds with the flattened list of T values and the
flattened list of p-values obtained from _get_list_signif_scores().
Arguments:
pairs: [(int, int)]
list of pa... | fbdff91f18587894a15a9eeb77fc1427779bc6ae | 7,749 |
def evaluate_predictions_per_char(predictions, original_sentences, answers):
"""Evaluates predictions per char, returning the accuracy and lists of correct and incorrect sentences."""
predicted_chars = []
sentences_with_preds = []
errors = set()
correct_sentences = []
total = 0
correct = 0
... | fb27ce85ad0843e474930802b06ab89849d87aba | 7,750 |
def n2es(x):
"""None/Null to Empty String
"""
if not x:
return ""
return x | cf73dd72230040cfc1c71b248b4cdd490004a213 | 7,751 |
def get_default_benchmark_simulated_datasets():
"""Default parameter sets to generate simulated data for benchmarking.
The training periods and forecast horizon are chosen to complement default real datasets.
Every tuple has the following structure:
(data_name, frequency, training_periods, forecast_hori... | aa0d7017fc693e71c016d80f7e50cc1c9a6cdc24 | 7,752 |
import os
import json
def load_config(cfg_path):
"""Load the config from a json file"""
if not os.path.exists(cfg_path):
raise RuntimeError('file {} does not exists!'.format(cfg_path))
with open(cfg_path, 'r') as f:
cfg = json.load(f)
return cfg | dcb1f309f7868191854203994b91cb28f759b5dd | 7,753 |
import re
def __remove_punctuation(string):
"""
Remove all the punctuation symbols and characters in a string.
:param string: the string where the punctation characters must be removed.
:return: a string without punctuation.
"""
return re.sub("[!@#£$.()/-]", "", string) | bb2015dc040fedb3656099b57b103f7fb9c416b9 | 7,755 |
def pad_chunk_columns(chunk):
"""Given a set of items to be inserted, make sure they all have the
same columns by padding columns with None if they are missing."""
columns = set()
for record in chunk:
columns.update(record.keys())
for record in chunk:
for column in columns:
... | 2e5d91ad03ad613b55bcaea97fd8c0785eec977f | 7,756 |
def get_next_match( map ):
""" This changes the inverse table by removing hits"""
todelete = []
retval = None
for px,s in map.iteritems():
if len(s) > 1:
retval = s.pop(),s.pop()
if retval[0][0] == retval[1][0]:
s.add( retval[1] )
#print retval, s
retval = None
co... | a1154773fb466f976c8145787200c6489f800f5f | 7,757 |
import os
import pickle
def read_pickle(text_folder_path, file_name):
"""
Read a pickled file from a directory.
Parameters:
text_folder_path (string): path to the directory where the file is located
file_name (string): name of file to read.
Returns:
read_text (string): text read from the... | 046dba6305a7b786715d3af89fbda597851ce684 | 7,758 |
def is_negligible(in_text):
"""" Checks if text or tail of XML element is either empty string or None"""
if in_text is None:
return True
elif type(in_text) is str:
if in_text.strip(chr(160) + ' \t\n\r') == '':
return True
else:
return False
else:
r... | 3e9e5276e0b58518d942fc3e2a16f64223eb4e0d | 7,759 |
def make_a_tweet(Hash, Message, Reduced):
"""
Generate a valid tweet using the info passed in.
"""
tweet = Hash + ': ' + Message
if Reduced:
tweet += '…'
return tweet | 1d0c3246874f8a6c9b3cb1b1f7cf27040ff1bd1b | 7,761 |
import os
def search_with_id(student_id):
"""
Obtain the username for a user with a given Student ID number (if server is tied into WPI network).
:param student_id: Student ID number to use in the search
:return: The user's network username
"""
try:
username = os.popen('id +' + str(st... | f7792ba2a2c891c22b07988846dd6bd8016676c7 | 7,763 |
def remainder(numbers):
"""Function for finding the remainder of 2 numbers divided.
Parameters
----------
numbers : list
List of numbers that the user inputs.
Returns
-------
result : int
Integer that is the remainder of the numbers divided.
"""
ret... | 4c17d717ef52a7958af235e06feff802ed9c3802 | 7,764 |
def ret_int(potential):
"""Utility function to check the input is an int, including negative."""
try:
return int(potential)
except:
return None | 682ab4987e94d7d758be5957b610dc1ee72156a1 | 7,769 |
def read_file(file_name):
"""Read contents of file."""
with open(file_name, encoding='utf8') as file:
return file.read().rstrip().lstrip() | cb8e85c076baa97d8f1a5361abe6ab4ee5b9f00c | 7,770 |
def RGB2HEX(color):
"""In: RGB color array
Out: HEX string"""
return "#{:02x}{:02x}{:02x}".format(int(color[0]), int(color[1]), int(color[2])) | 7283f0a8a72d83496c93084ab5c514a0184682c7 | 7,771 |
def signed_area(contour):
"""Return the signed area of a contour.
Parameters
----------
contour: sequence of x,y coordinates, required
Returns
-------
area: :class:`float`
Signed area of the given closed contour. Positive
if the contour coordinates are in counter-clockwise... | 79a60d064fad70afb8902d6d66b980d778215de3 | 7,772 |
def set_initxval(constr_func, constr_values):
""" Calculates the initial value of xval.
Args:
constr_func (:obj:`list`): constraint functions applied.
constr_values (:obj:`list`): Values of constraint functions applied.
Returns:
initial_xval (:obj:`float`): First value of xval
... | 434608817ed261538e605b8a8d4e4b53c0749906 | 7,774 |
def deep_dictionary_check(dict1: dict, dict2: dict) -> bool:
"""Used to check if all keys and values between two dicts are equal, and recurses if it encounters a nested dict."""
if dict1.keys() != dict2.keys():
return False
for key in dict1:
if isinstance(dict1[key], dict) and not deep_dicti... | b5011c2c79c79ecc74953e5f44db5c4a62464c07 | 7,776 |
def unshared_copy(inList):
"""perform a proper deepcopy of a multi-dimensional list (function from http://stackoverflow.com/a/1601774)"""
if isinstance(inList, list):
return list( map(unshared_copy, inList) )
return inList | 44cfd186e02a70a51cd29a3cdf01c698c1380d02 | 7,777 |
def SEARCH(find_text, within_text, start_num=1):
"""
Returns the position at which a string is first found within text, ignoring case.
Find is case-sensitive. The returned position is 1 if within_text starts with find_text.
Start_num specifies the character at which to start the search, defaulting to 1 (the fi... | 1afc843583695a801aca28b5013a6afa21221094 | 7,778 |
def GetDefaultAndCustomPreset(presets):
""" Get the default and custom preset values from the saved property group"""
defaultPreset = ''
customPreset = ''
if presets:
for p in presets:
if p.name == 'Default':
defaultPreset = p.value
if p.name == 'Custom':
... | ad5ee60ec995a1662f7c674a11ebf11bf16ab3be | 7,779 |
def getvaluelist(doclist, fieldname):
"""
Returns a list of values of a particualr fieldname from all Document object in a doclist
"""
l = []
for d in doclist:
l.append(d.fields[fieldname])
return l | b85d171b537636477b00021ce717788b5e4735da | 7,780 |
import numpy
def to_cpu_async(array, stream=None):
"""Copies the given GPU array asynchronously to host CPU.
Args:
array: Array to be sent to GPU.
stream (~pycuda.driver.Stream): CUDA stream.
Returns:
~numpy.ndarray: Array on CPU.
If given ``array`` is already on CPU, th... | 2149ddf3de42a7ea41e59810dea3151f5eb97d9b | 7,781 |
import numpy
def preprocess_depth(depth_data):
""" preprocess depth data
This function "reverses" the original recorded data, and
convert data into grayscale pixel value.
The higher the value of a pixel, the closer to the camera.
Parameters
----------
depth_data : numpy.ndarray
The data coming f... | 25aa5f13594752f262a27b9ea99ee72c38ab3db7 | 7,782 |
def changed_keys(a: dict, b: dict) -> list:
"""Compares two dictionaries and returns list of keys where values are different"""
# Note! This function disregards keys that don't appear in both dictionaries
return [k for k in (a.keys() & b.keys()) if a[k] != b[k]] | 77ae93614a2c736091886024338c1b4ecb1f6ec1 | 7,783 |
def _negation(value):
"""Parse an optional negation after a verb (in a Gherkin feature spec)."""
if value == "":
return False
elif value in [" not", "not"]:
return True
else:
raise ValueError("Cannot parse '{}' as an optional negation".format(value)) | c13f06b8a11ecbe948a4c2d710e165e1731f08fd | 7,784 |
import re
import requests
import json
def get_all_stealth_cards():
"""Returns a list of all the Stealth Cards"""
class StealthCard:
def __init__(self, card_info):
self.name = card_info["Name"]
self.img_url = card_info["ImageUrl"]
self.cost = card_info["Cost"]
... | 93abd19276a600f9b344ca5d72a87d7a7f0a9e1a | 7,785 |
from typing import Any
from pathlib import Path
def config_to_ext(conf: Any) -> str:
"""Find the extension(flag) of the configuration"""
if isinstance(conf, dict):
return "dict"
conf = Path(conf)
out = conf.suffix.lstrip(".").lower()
if not out and conf.name.lower().endswith("rc"):
... | 53a4c452c050266736d1fddc1bd18634702e2f5a | 7,786 |
def get_status_messages(connection, uid, timeline='home:', page=1, count=30):
"""默认从主页从时间线获取给定页数的最新状态消息,另外还可以获取个人时间线"""
# 获取时间线上最新的状态消息ID
statuses = connection.zrevrange('%s%s' % (timeline, uid),
(page - 1) * count, page * count - 1)
pipe = connection.pipeline(True)
... | 21af458155d7de793b420047178507d1f77296d2 | 7,787 |
import warnings
def ensure_all_columns_are_used(num_vars_accounted_for,
dataframe,
data_title='long_data'):
"""
Ensure that all of the columns from dataframe are in the list of used_cols.
Will raise a helpful UserWarning if otherwise.
Pa... | 0470503c8adac107f85dd628409fc3ca8de641d3 | 7,788 |
def arrayizeDict(g):
"""Transforms a dict with unique sequential integer indices into an array"""
mk = max(g.keys())
ga = [None] * mk
for k, v in g.items():
ga[k - 1] = v
return ga | d2da3848436be8d47b3f338797eefd87cfa4344c | 7,790 |
def get_values(units, *args):
"""
Return the values of Quantity objects after optionally converting to units.
Parameters
----------
units : str or `~astropy.units.Unit` or None
Units to convert to. The input values are converted to ``units``
before the values are returned.
args ... | 462e336fa2f4bcdfd77ba43658c37cf4c6782c75 | 7,792 |
def cli(ctx, library_id, filesystem_paths, folder_id="", file_type="auto", dbkey="?", link_data_only="", roles=""):
"""Upload a set of files already present on the filesystem of the Galaxy server to a library.
Output:
"""
return ctx.gi.libraries.upload_from_galaxy_filesystem(library_id, filesystem_pa... | c0b269344da39a2ae9f43280ec1d7bf69a6a345c | 7,793 |
import numpy
def h2e(az, za, lat):
"""
Horizon to equatorial.
Convert az/za (radian) to HA/DEC (degrees, degrees)
given an observatory latitude (degrees)
"""
sa = numpy.sin(az)
ca = numpy.cos(az)
se = numpy.sin(numpy.pi / 2.0 - za)
ce = numpy.cos(numpy.pi / 2.0 - za)
sp = numpy... | 89f82c0035eaf9b73d3c2adf07b2ed1145c822f9 | 7,794 |
def _add_metadata_as_attrs_da(data, units, description, dtype_out_vert):
"""Add metadata attributes to DataArray"""
if dtype_out_vert == 'vert_int':
if units != '':
units = '(vertical integral of {0}): {0} kg m^-2)'.format(units)
else:
units = '(vertical integral of quant... | 3bdead2b0b341a065ef1e147660605c9c591c0df | 7,795 |
def load_uvarint_b(buffer):
"""
Variable int deserialization, synchronous from buffer.
:param buffer:
:return:
"""
result = 0
idx = 0
byte = 0x80
while byte & 0x80:
byte = buffer[idx]
result += (byte & 0x7F) << (7 * idx)
idx += 1
return result | f45534114fa310c027e9ff7627a41bfd51950b48 | 7,796 |
def parse_print_dur(print_dur):
"""
Parse formatted string containing print duration to total seconds.
>>> parse_print_dur(" 56m 47s")
3407
"""
h_index = print_dur.find("h")
hours = int(print_dur[h_index - 2 : h_index]) if h_index != -1 else 0
m_index = print_dur.find("m")
min... | 7b1a29f31ba38e7d25b4dca9600d4be96a1da3ac | 7,797 |
def welcoming():
"""
Welcoming for user
"""
return("""
*************************************************
** **
** Welcome to speech emotion recognition! **
** **
********... | b3bcd19adda9cc8aa9678e823d1e524ba36f80af | 7,798 |
def _find_vlan(mac, domain_interfaces):
"""
Given a mac address and a collection of domains and their network
interfaces, find the domain that is assigned the interface with the
desired mac address.
Parameters
----------
mac : str
The MAC address.
domain_interfaces : dict
... | c4f667dd80146de83157e8966cb34e5867457397 | 7,799 |
import os
import re
def canonicalize_path(path, prefix=None):
"""Canonicalize a given path.
Remove the prefix from the path. Otherwise, if the path starts with
/build/XXX/package-version then remove this prefix.
Args:
path
Returns:
Canonicalized path.
"""
dummy_prefix = ... | 47bd737502466f15679047ec77b9d4f5a3cbea33 | 7,801 |
def tests():
""" Make these Unittests for each function. """
tests_list = [
'assertNotEqual',
'assertEqual'
]
return tests_list | cdba4e6293df2231640d6896a5104791cdf073be | 7,802 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.