content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def error_function(par, func, xdata, ydata=None, yerr=None): """Calculate the error as the sum of square of residuals Parameters ---------- par : list Parameter values. func : function Function being minimized. xdata : array The independent data ydata : array ...
bf34c6bc13837ca3dc6875b50c9e0cbda63eb659
613,724
import math def compute_hypotenuse(a, b): """Compute the hypotenuse length of a right triangle with legs a and b.""" return math.hypot(a, b)
2a3313bdf254193265ec29bdf4ebf4c5354a81e6
613,725
def response_from_message(message): """ Helper to wrap a message string into the minimum acceptable Alexa response JSON. """ return { 'version': '1.0', 'response': { 'outputSpeech': { 'type': 'PlainText', 'text': message, } ...
aca6fa43587c1c1045736225a5b6a2141dae15d5
613,729
from typing import List def mean_floor(target_list: List[int]) -> int: """ Gets the rounded down mean of the list """ return sum(target_list) // len(target_list)
8820f06d875b63b60a79b6c0d1bc487aeeb02ae5
613,730
def is_prime(n): """ Return a boolean value based upon whether the argument n is a prime number. """ if n < 2: return False if n == 2: return True for m in range(2, int(n ** 0.5) + 1): if (n % m) == 0: return False else: return True
63c31f2836395b85c128223ae3212339d97c72ce
613,731
import base64 def base64_encode(string): """ Encodes data with MIME base64 This encoding is designed to make binary data survive transport through transport layers that are not 8-bit clean, such as mail bodies. """ return base64.b64encode(string)
d1632c2952fc470a322926aae6a32a6cbe3cc930
613,735
def basename(p): """Returns the basename (i.e., the file portion) of a path. Note that if `p` ends with a slash, this function returns an empty string. This matches the behavior of Python's `os.path.basename`, but differs from the Unix `basename` command (which would return the path segment preceding ...
bb77636e25a4f1cf39506f7b9ce93f544c28658b
613,736
import random def _generate_fwf_row(characterSet, offsets): """Generates a random fwf line Args: characterSet (str): valid to pick characters from offsets (list[int]): lengths of each field Returns: line(str): line formatted in fwf """ return [ "".join(random.choi...
ac4c778335c173c0802ec8a225f7edc6465bd776
613,740
def calculateIncomeHelper(income, pay_period): """Returns annual income based on income each pay_period""" pay_multipliers = {'weekly':52, 'biweekly':25, 'semimonthly':24,'monthly':12} return income*pay_multipliers[pay_period] if pay_period in pay_multipliers else income*pay_period*52
4b5add97321391669ed614cbf0d383a1491ffc48
613,741
def first_row_check(header): """This function checks whether there is a column in header row spanning multiple subcolumns under the same category. If there is such a column this function will reapeat the header element for each one of the corresponding subcolumns. ARGS: header (bs4.Tag...
38da2e16d3194cbc488d8d71867e2229c21613bd
613,742
import torch def append_bias_ones(tensor): """Appends vector of ones to last dimension of tensor. For examples, if the input is of shape [4, 6], then the outputs has shape [4, 7] where the slice [:, -1] is a tensor of all ones. """ shape = list(tensor.shape[:-1]) + [1] return torch.cat([tenso...
0aae2687c35ed0da02f755b5008aa7db03d1a543
613,745
import logging def clear_session(model): """ Clear session from a model to prevent any out-of-memory or segmentation fault issues. Parameters ---------- model : malaya-speech object. Returns ------- result : boolean """ success = False try: if hasattr(model, 'ses...
c2cbe7479c7dcaa6143d2e654f8c20eeed5071b8
613,746
def sequentialSearch(collection, t): """Demonstrate search for target t in collection.""" for e in collection: if e == t: return True return False
c94b4d2d4a58c6cf3af24b54ce54a6a348dd0da8
613,747
def RGBToHTMLColor(rgb_tuple): """ convert an (R, G, B) tuple to #RRGGBB """ hexcolor = '#%02x%02x%02x' % rgb_tuple # that's it! '%02x' means zero-padded, 2-digit hex values return hexcolor
4abd45d9f0e362a4c5a7e89b088d262d5947aebf
613,748
import torch def prob_next(LMModel, vocab, text, hn=None, subvocab=None, clustermask=None, onscore=False, renorm=False): """ Output the probability distribution for the next word based on a pretrained LM, given the previous text. If 'subvocab' is not None, the distribution is restricted on the specified s...
e3c11ef2354c1dda9649be51d283b59dafed334f
613,750
import random def get_rand_ss_idx(ss): """ Takes list of indices where secondary structure changes, and outputs a single coordinate from within each ss element """ output = [] for i in range(len(ss)-1): if ss[i+1] - ss[i] > 4: #don't sample if ss region is smaller than 5 residues ...
b49b1536e19724c49114526d8d4198a1f9315527
613,751
def utf_encode_list(text): """utf encode every element of a list.""" return [x.encode('utf-8') for x in text]
87198a0609c693d59c6d4842b01c63147012fcae
613,753
def move_up(t): """ A method that takes coordinates of bomb's position and returns coordinates of neighbour located above the bomb. It returns None if there isn't such a neighbour """ x, y = t if x == 0: return None else: return (x - 1, y)
4fcdcc31cd063e727d55116e37528498ae839337
613,755
def should_check_integrity(f): """Returns True if f should be checked for integrity.""" return f not in ('README.md', 'TRAINING_LOG', 'checksum.md5', 'data') and not f.startswith('.')
1807916ed8744d01288a5047c996efcaa0b6d76f
613,760
def unpack_data(data_str): """Extract the code and message from a received string. Parameters ---------- data_str : str Returns ------- code : str msg : str """ if data_str: data_list = data_str.split(' ', 1) code = data_list[0] msg = None if len(data_li...
1585ea4ea25638cec5483daad1f86626823fdc3c
613,762
def recvall(sock, n): """ returns the data from a recieved bytestream, helper function to receive n bytes or return None if EOF is hit :param sock: socket :param n: length in bytes (number of bytes) :return: message """ # data = b'' while len(data) < n: print("Start func...
5641e7f13c4e61f9cdf672dc524c397f415e8a62
613,763
import textwrap def shortentext(text, minlength, placeholder='...'): """ Shorten some text by replacing the last part with a placeholder (such as '...') text: The text to shorten minlength: The minimum length before a shortening will occur placeholder: The text to append after remo...
f6bc93f5c36432a57ac78f531184f6f04ef68fab
613,765
from typing import OrderedDict def bs3_cols(sizes): """ Convert a BS3 column sizes dict into a css class string. The `sizes` may be a list of tuples instead of a dict. >>> bs3_cols({'md': '6', 'xs': '8'}) 'col-md-6 col-xs-8' """ if not isinstance(sizes, dict): sizes = Ord...
89c20d30e97ae1a12dc22d1fa6812535b7d6f31c
613,772
def refactor_str_column(df, str1, str2, col='file_name', inplace=False): """ Takes a column in a dataframe and replaces all instances of str1 with str2 :param pandas.DataFrame df: :param str col: :param str str1: :param str str2: :param bool inplace: [False] - If True, perform the ...
1d32230f97435b7d6ca4efcf37c7ccc0691974b0
613,775
def NoNegative(a): """ Clip all negative value to 0. """ a[a < 0] = 0 return a
2ffa2d06e45adf0b04219b4e203a50b8749307d2
613,777
def reader(path): """Reads a file into a string Reads whole file into single string. Typically, namelists are small enough to be stored in memory while updates and edits are being performed. :param path: Path to input file :returns: entire file as a single string """ with open(path, ...
291e39d3a7a7a0ac88ee0aea3abc530662caed68
613,783
def get_max_value_from_bytes(bytes_size: int, signed=True) -> int: """Gets the max value that a number can be given the bytes. Args: bytes_size: Bytes size. signed: Whether number is signed or not. Returns: Max number for given bytes. """ bits_size = bytes_size * 8 if signed: bits_size = b...
044ef09ddaf5a8af4dfd175d44f56dad4c6dd39c
613,791
import operator def dotproduct(lhs, rhs): """Compute the dot product of two vectors.""" return sum(map(operator.mul, lhs, rhs))
a56ab7239e670e08af192f8695ad3592f2feb110
613,792
def lucas(n): """Function that returns value of the given index from Lucas sequence""" previous = 2 current = 1 try: for i in range(n): previous, current = current, previous + current return previous except TypeError: return ("Input should be a one integer")
f2102acf9b81f6fa5cd64213cf0748a57d47b7f4
613,793
from typing import Sequence import itertools def right_average(values: Sequence[float], num_items: int) -> float: """Calculate average of `num_items` rightmost values in a sequence.""" if not 0 < num_items <= len(values): raise ValueError(f"Invalid value for average: {num_items}") return ( ...
38359b44f4b3475233f263316d14b7a4a620e521
613,797
import hashlib def generate_shear_masking_factor(passphrase): """Generate a masking factor by hashing a passphrase. Code from Joe Zuntz w/ modifications for python 3 by Matt B. Parameters ---------- passphrase : str A string. Returns ------- factor : float The maskin...
3ad0d3f821f1adbf145856045a8351084fa8bcd8
613,798
def is_false(item): """Self-explanatory.""" return True if item is False else False
a9db435a89c51d1f3014083ce42e591cd172011f
613,799
def _ParseArgument(argument): """Parses a CGI argument name. Args: argument: CGI argument name of the form [model.]attribute[.operator] (str or unicode) Returns: model (str), attribute (str), operator name (str) """ tokens = str(argument).split('.', 2) if len(tokens) == 1: # If only on...
412a3f2702f64976fb4946df20ed6d30b8689d5e
613,802
from typing import Optional def get_uri_parent(uri: str) -> Optional[str]: """Return URI of parent collection with trailing '/', or None, if URI is top-level. This function simply strips the last segment. It does not test, if the target is a 'collection', or even exists. """ if not uri or uri.str...
b764eb6cdfd5b51265a234419b47aba9475caf7d
613,807
import itertools def grouper(iterable, n, fillvalue=None): """ Cut iterable into n sized groups from itertools documentation, may not be most efficient, fillvalue causes issue :param iterable: object to iterate over :param n: int value to group :param fillvalue: value to fill with ...
290bb51845b818562ffba1b54392ab1973f8f2d6
613,808
import socket def is_port_open(port): """Check if port is open Arguments: port {int} -- port Returns: bool """ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: port = int(port) return not s.connect_ex(('localhost', port)) == 0
9ed94bf59e0e0935f907f19c75761eaea42af93e
613,810
def Mean(values): """Returns the arithmetic mean of |values|.""" if not values or None in values: return None return sum(values) / float(len(values))
340784478ab33afa04e8aefc21aa3709a7beae11
613,811
def safeInt(v): """helper function for parsing strings to int""" try: ret = int(v) return ret except: return None
bfd75432d459e083188b6f60b759edca0a395121
613,813
def kg_to_lbs(kg): """ Convert kilograms to pounds """ return kg * 2.204623
ffa488ca872f9b9aa3aa2bae1c35acd90f96a6ff
613,816
def is_sq(number: int) -> bool: """ Check if number is a perfect square. >>> is_sq(1) True >>> is_sq(1000001) False >>> is_sq(1000000) True """ sq: int = int(number ** 0.5) return number == sq * sq
187720f868ef840f3f073aec91a5c42c435db1a8
613,817
def get_single_sleep_profile(df, resp_colnum, activity_colnum): """ Returns a list of tuples with metabolic rate sums, the percentage sleep, and total beam breaks per hour for 24 hours, for one individual fly. """ fly_activity = df.iloc[:,activity_colnum] fly_resp = df.iloc[:,resp_colnum] ho...
2b210433f4892d06e773e2f22c51f683331f80b8
613,819
def two_element_geometries(two_element_grid): """Return geometries of two element grid.""" geometries = [elem.geometry for elem in two_element_grid.entity_iterator(0)] return geometries
aecec65862eb70a8e772bd322ffda130077b98d3
613,823
import math def n_choose_k(n, k): """Returns the combination choose k among n items.""" f = math.factorial return int(f(n) / f(k) / f(n - k))
6e56f8392f30262dcda04ca55f13eae7dc22f328
613,824
def morph_key_indices(settings, m): """ Return indices of key frames for the given morph sequence. Usage ----- >>> a, b = morph_key_indices(settings, m) """ n = len(settings['keyframes']) if settings['render']['loop'] and m == n - 1: a, b = m, 0 else: a, b = m, m...
7c394d8ffcf84ce30bcc62138647f51edc5c557d
613,826
def isBlinking(history, maxFrames): """ @history: A string containing the history of eyes status where a '1' means that the eyes were closed and '0' open. @maxFrames: The maximal number of successive frames where an eye is closed """ for i in range(maxFrames): pattern = '1' + '0'*(i+1)...
98267a85520cae53be09ddc476377e37bf782561
613,828
import math def euclidean (x, y): """ The euclidean distance between two coordinates expressed as two tuples. """ return int(math.sqrt( (x[0] - y[0])**2 + (x[1] - y[1])**2 ))
540b7863144520b9003a7d88197575367785fec5
613,834
import pathlib import base64 def read_image(filepath: pathlib.Path) -> str: """ Read an image from a file. Args: filepath: Input image file path Returns: Image encoded in Base64 """ with open(filepath, "rb") as f: image_base64: str = base64.b64encode(f.read()).decode(...
4219c092188acd6953e9043bdb083f165af742fe
613,839
def float2str(f, var=None): """ Convert float to nicely formatted string :param f: float to convert to string :type f: float :param var: (optional) tkinter.StringVar to write value to :type var: None or tkinter.StringVar :return: string with nicely formatted float, or None :rtype: s...
15927fb1b5858f814a367282fd4fee1f69ea4ebd
613,843
def inNativeCheck(a, a_n): """ Checks if each argument in `a` is in the native function's list of arguments `a_n`. :param a: List of arguments. :param a_n: List of native arguments. """ print("Native check.") arg_native_names = map(lambda d: d.get('name'), a_n) arg_native_alt_names ...
6eb5f6552ccece5bc96f4d468397adce38c05751
613,844
def get_category_data(user_category, level_data_info): """ Loops through the level_data list and adds the rows that match with the user selected category to a new list called category_data. Params: 1) user_category - This is the input received from the user. 2) level_data_info - This i...
a76f3c61945c2c501968c28068b6729c55b6ae94
613,848
def any_color_in_combination(colors, given): """ Returns true if at least one color in colors is part of the given combination. False otherwise.""" number_of_colors = len(colors) starting_position = 0 while starting_position < number_of_colors: if colors[starting_position] in given: ...
759343137103ba49ee3f7fb04ff3012571ce39c6
613,856
def build_signature(function_name, function_parameters): """ Given the function name and function parameters, returns the signature line :param function_name: the name of the function :param function_parameters: the parameters of the function (whatever would be within the brackets) """ re...
921fa5260a7b8ffc887c711219052e0a4bb4a7de
613,860
def col_to_list(col_in, model_ds, cellids): """Convert array data in model_ds to a list of values for specific cells. This function is typically used to create a rec_array with stress period data for the modflow packages. Can be used for structured and vertex grids. Parameters ---------- c...
94462ef5dce7c604c94e80c6ce18c2e8128edf67
613,861
def removeNullTerminator(bytestring): """Remove null terminator from bytestring""" bytesOut = bytestring.rstrip(b'\x00') return bytesOut
e52731a572ab6dbb34a6af30ef210dde29e8ead7
613,864
from typing import Tuple from typing import Optional from typing import Any def validate_coin(coin: str, coins_dct: dict) -> Tuple[str, Optional[Any]]: """Helper method that validates if proper coin id or symbol was provided [Source: CoinPaprika] Parameters ---------- coin: str id or symbol o...
531cb79fc9251a885a4fffe98d097a18cf86e503
613,872
def _is_term_initial_offset(begin, terms): """Returns True if begin is a key in terms.""" return terms is not None and begin in terms
d7b91d4f2098c06e4245cb56d146d178dbe4645e
613,874
def vim_parser(start_chars, generic_repeat=True, is_motion=False): """Decorator for function that handle vim commands Command Handling functions must follow the signature: function( editor, repeat, cmd ) These functions should never be called directly, but instead be called through the GetHan...
63cfbc51b4cbabd477c4a6dcdc4520159c33a738
613,875
def rescale(x, y, factor): """Rescale a scaled coordinate""" return (int(x / factor), int(y / factor))
9c0fae4f1ce49e807e73d5cf3b8d704b2d87b25e
613,880
def job_result_path(instance, filename): """Produce the path to locally store the job results. :param Result instance: the :class:`Result` instance to produce the path for :param str filename: the original filename """ return 'results/{}/{}'.format(instance.job.uuid, filename)
9cea8472f07cb4dbe63ca1f6cede5703ca7d75cf
613,885
from typing import Optional import torch def select_device(device: Optional[str]) -> str: """ Chooses the torch device to run in. Parameters ------------ device: Union[torch.device, str] A device or a string representing a device, such as 'cpu' Returns --------- str ...
624ca61a2fce33bfd2b6105951c4faaecd5e2ec3
613,889
import re def text_preprocess(document): """ Basic text preprocessing :param document: string containing input text :return: updated text """ # Remove all the special characters document = re.sub(r'\W', ' ', str(document)) # Substitute multiple spaces with single space document = r...
a23dd541f66aae3de39c7624b916b6a7b5c0e1e7
613,892
import re def is_batchnorm_param(parameter_name): """ Is this parameter part of a batchnorm parameter? """ return re.match(r""".*\.bn\d+\.(weight|bias)""", parameter_name)
3fd8310a2ec1a88a32c95cf7b3a5e3e30b3723f5
613,894
def _convertResultsToArray(result, varNameList): """Extracts for each SPARQL result binding in 'result' the 'value' of variables specified in 'varNameList' and creates an Array of these result values.""" resultArray = list() for r in result['results']['bindings']: resultList = list() for...
3ab72e7d4e8eaff9d1bfab1bbf2b5d856af69b06
613,895
async def check_read(stream, num_bytes): """Read bytes from an async stream and check for EOF. This detects EOF by getting back 0 bytes from the read, which Python defines as EOF. Parameters ---------- stream : file-like object, async compatible Stream to read from num_bytes : int ...
ea3ca468e854306b31de09e7c97d7ceff4c8a4b7
613,898
def radix_sort(k, arr, base=2): """ Radix sort for an arbitrary base Sorts a list of integers in [0, k) """ i = 0 while (base ** i) < k: buckets = [[] for j in range(base)] for key in arr: digit = (key // (base ** i)) % base buckets[digit].append(key) arr = [] for j in range(bas...
c5ef6292161eefbf9463d858189fb5b09985dc3f
613,900
def is_apriori(Ck_item, Lksub1): """ 进行剪枝,如果满足APriori,即满足支持度,返回True 否则返回False,删除 Judge whether a frequent candidate k-itemset satisfy Apriori property. Args: Ck_item: a frequent candidate k-itemset in Ck which contains all frequent candidate k-itemsets. Lksub1: Lk-1...
35747914410e3c9b7c26207f0c66a210834444ac
613,901
def check_answer(guess, a_followers, b_followers): """Take the user guess and follower counts and returns if they got it right.""" answer = "a" if a_followers > b_followers else "b" return guess == answer
d8b1ee81fff1a7303a07bd9021c7b494a997239f
613,903
import json def json_load(json_filename): """ Load a json file. Args: json_filename (str): Path of the .json file with results. Returns: results_dict (dict): dictionary with results stored in the json file. """ try: with open(json_filename) as j...
be7dd924f227b2bb0c5e3ec588571646b23eaac1
613,904
import shutil def is_cmd(cmd: str): """Check if a command exists on path""" return shutil.which(cmd) is not None
687f6764b1531c365438c432d0b349f8192c2000
613,905
def get_filter_arg_integer(f, arg): """Convert integer value to decimal string representation.""" return '%d' % arg
3d1e2282895b17b371b5ef69c598b348dbb7bfe3
613,906
def flatten(list_to_flatten): """Flatten out a list.""" def genflatten(lst): for elem in lst: if isinstance(elem, (list, tuple)): for x in flatten(elem): yield x else: yield elem return list(genflatten(list_to_flatten))
6359c35c1f30823fe0df2d63a5f4ac40fa600027
613,908
def output_dim(X, S, padding, strides): """ compute along 1 dimension, with these sizes, what will be the output dimension Arguments: X (int): input data dimension S (int): filter dimension padding (int): padding on each side strides (int): striding """ return (X - S...
b4836c512893d09d8e810a3f3bf5d81d6123e8bd
613,909
def l2_loss(x: float, y: float) -> float: """ Compute the L2 loss function. Return the square difference between the inputs. https://www.bitlog.com/knowledge-base/machine-learning/loss-function/#l2-error Parameters ---------- x : float The estimate y : float The actual...
ed096cffbc3a27fd5469b105f9861efe679df65e
613,915
def char_waveform(length): """ Helper function for creating a char waveform PV. Args: length: The length of the array. Return: The dictionary to add to the PVDB. """ return {'type': 'char', 'count': length, 'value': [0]}
026332a96659edf672519aaab9db6fa49f99837a
613,916
def to_variant(dataset): """Returns a variant representing the given dataset. Args: dataset: A `tf.data.Dataset`. Returns: A scalar `tf.variant` tensor representing the given dataset. """ return dataset._variant_tensor # pylint: disable=protected-access
0d1057946841aba133246b1db97487b376f6bfbd
613,918
import torch def mulaw_decode(x_mu, quantization_channels, input_int=True): """Adapted from torchaudio https://pytorch.org/audio/functional.html mu_law_encoding Args: x_mu (Tensor): Input tensor quantization_channels (int): Number of channels input_int: Bool True: conver...
cdc4f5e35a132853c549ea56fdfc581c0f476a46
613,922
def get_name_and_extension(file_name): """ Returns a tuple with the name and extension (name, extension) """ assert isinstance(file_name, str) bits = file_name.split('.') assert len(bits) >= 2 return '.'.join(bits[:-1]), bits[-1]
899bc42b17d9e0ab89f083c0280e7d8333cf5eb8
613,925
import json def write_json(filename, data): """Write a JSON file. Used in the tests. """ with open(filename, "w") as fstream: json.dump(data, fstream) return filename
16a14d658b30da97a68162573c4f1b9d17b586a6
613,926
def _formparams_to_dict(s1): """ Converts the incoming formparams from Slack into a dictionary. Ex: 'text=votebot+ping' """ retval = {} for val in s1.split('&'): k, v = val.split('=') retval[k] = v return retval
476c34601f2c4c0dda31baf85b6c44770b3cedbf
613,928
import torch def _mk_param(val): """Make a torch parameter from a scalar value""" if isinstance(val, torch.Tensor): val = val.item() return torch.nn.Parameter(torch.tensor(val, dtype=torch.float))
bbbefef8ec4880d6d840f76cf02657d2751d84f0
613,930
import math def angle3pt(a: tuple, b: tuple, c: tuple) -> float: """ Calculate the angle by turning from coordinate a to c around b. :param a: coordinate a (x, y) :param b: coordinate b (x, y) :param c: coordinate c (x, y) :returns: * **ang** - ...
e7ccbf67cedfcfebe8015115deb6cc884ee45a14
613,932
def next(iterator, default=None): """A version of the built-in next function, for use with implementations of Python older then version 2.6. """ try: return iterator.next() except StopIteration: if default: return default else: raise StopIteration
25b38e76ddf894102ff96b1842d58050eaac0b09
613,934
def group(*groups): """ Decorator to specify which groups are allowed to use the commands specified for this function. :param groups: List of server groups that are allowed to use the commands associated with this function. :type groups: str """ def save_allowed_groups(func): func.al...
53045a826eef3cfc9c0c225fadc2adf4b22954db
613,935
import requests def get(url: str, **kwargs): """ Wrapper for requests.get """ r = requests.get(url, **kwargs) if r.status_code == 200: return r else: raise Exception( f"Network Exception, failed to fetch requested page {url}")
68cdf43f6b6efae8d7eb77cd47e0bc92972d018d
613,936
def get_input_filtering_cycles(size_in): """Cycles required to perform filtering of received values.""" # Based on thesis profiling return 39*size_in + 135
a6869565dc082589663cb65b816c86bf517e965c
613,938
import csv def import_csv(in_csv, delimit=','): """ Imports contents of a csv text file to a list of lists. Parameters --------- in_csv: str path and name of input csv file delimit: str delimiter of the csv file Returns ------- data_list: list list of list...
875e22073978e0fe90663df9c93596ba8fc738cb
613,939
import re def is_email(email): """Check if a string matches a general email pattern (user@domain.tld)""" return re.match(r"^[-.\w]+@[-\w]+\.[-\w]+$", email)
6330d95642de99b6dfaeea719b09f19a3c6b893d
613,941
def alignUp(value: int, size: int): """Aligns and address to the given size. :param value: The address to align up. :type value: int :param size: The size to which we align the address. :type size: int :return The aligned address. :rtype int """ return value + (size - value % size)...
b7f69b6ea28b99724efee28b72f7e03bd5357f86
613,944
def parse_field(field, field_name): """Parse field according to field type. Parameters ---------- field: str, dict field to be parsed. When a dictionary is given, it will return it as is. When a string is provided it will return the eval version of it, in order to return a dict ...
8178af8b9eb19cabe829122022e17da8a27a3f9b
613,946
def upper_lower_none(arg): """Validate arg value as "upper", "lower", or None.""" if not arg: return arg arg = arg.strip().lower() if arg in ["upper", "lower"]: return arg raise ValueError('argument must be "upper", "lower" or None')
7c4b9d43e653cc445de803394aa7bd90fdfbdb94
613,947
def get_sts_endpoint(region): """Get regionalized STS endpoint.""" return "https://sts.{0}.{1}".format(region, "amazonaws.com.cn" if region.startswith("cn-") else "amazonaws.com")
aa9359b746507997c1152f20eb7b25f2bd3903cf
613,948
def get_wedge_color(theta, depth, scalar_cmap): """Gets a color for a wedge to be, of the form (r, g, b, a). Each component is scaled from 0 to 1.""" # get the index of the color in the colormap # (convert from degrees to float 0-to-1) color_index = theta / 360.0 # get the color at that inde...
c2c1da37105d7873491221b31b9938abba6ac3cd
613,956
from datetime import datetime from dateutil import tz def force_utc(dt: datetime) -> datetime: """ Change a datetime to UTC, and convert naive datetimes to tz-aware UTC. :param dt: datetime to change to UTC :return: tz-aware UTC datetime """ if dt.tzinfo is None: dt = dt.replace(tzinf...
5abf83dbeb2dbbfa29cbc3079a23ae6c88023396
613,959
def extract_numbers(string): """Returns all digits of a string""" return [int(s) for s in string.split() if s.isdigit()]
a9885644aa188f6fcacee897a2bec605cbe69ef9
613,960
def is_equal_tag(element, tag_name, params, content): """ Check is `element` object match rest of the parameters. All checks are performed only if proper attribute is set in the HTMLElement. Args: element (obj): HTMLElement instance. tag_name (str): Tag name. params (dict): Par...
980e8e44e26bedc5c29cfc86ec21eb891be60339
613,965
import requests def get_html(url): """Get raw HTML from a URL.""" headers = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET', 'Access-Control-Allow-Headers': 'Content-Type', 'Access-Control-Max-Age': '3600', 'User-Agent': 'Mozilla/5.0 (X11; Ub...
1b7f636e89e31bf2c2dced24a63f53a851bbaffd
613,969
import hashlib def md5hash(filename, size=50000): """ Helper function to calculate MD5 hash of the file contents (up to a given number of bytes). @param filename file path of file to process @param size the maximum number of bytes to read """ f = open(filename, 'rb') data = f.read(siz...
59891ca50f72e8d3c62504887b0c1480a0753345
613,975
def get_code_list(codes_df): """ Process dataframes to return of lists of codes by level Parameters: codes_df, a dataframe of codes generated by json_to_df() Returns: code_list, a list of concatenated strings for each level of coded text """ code_list = [] for row in code...
3315723e578f3eaf27548a331319106df9e90fed
613,978
import textwrap def AddressArgHelp(include_l7_internal_load_balancing, include_gfe3, include_l7_rxlb): """Build the help text for the address argument.""" lb_schemes = '(EXTERNAL, INTERNAL, INTERNAL_SELF_MANAGED' if include_l7_internal_load_balancing: lb_schemes += ', INTERNAL_MANAGED' ...
9e47a9786ea44c38da064af9cf3b98d539e3234f
613,980
def area_tr(base_t,height_t): """Calculates the area of a triangle with given base and height :Input: The base and height of the triangle (float, >=0) :Returns: The area of the triangle (float).""" if base_t < 0: raise ValueError("The base must be >= 0.") if height_...
e210b34a9679a799677007ead89ed3de1cb1c4d6
613,981