content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def _split_key_val(option): """Split extra command line data into key-value pairs.""" key_val = option.split(':', 1) assert len(key_val) == 2, "Bad option %s" % option return key_val
85991e20b7384b7e3a7c966d2e6b52e573befb64
458,359
def get_utm_zone(pos_longlat): """ Return the UTM zone number corresponding to the supplied position Arguments: pos_longlat: position as tuple (This in (long, lat) Returns: The UTM zone number (+ve for North, -ve for South) """ lon, lat = pos_longlat z = int(lon/6) + 31 ...
4f3ff0dac79928b9d0be3980527388c9f5051ed3
450,332
def create_dataset(dataset=None, labels=None): """ 构造贷款数据集 :return: 返回数据集和是否放贷(二类) """ if not dataset: dataset = [[0, 0, 0, 0, 'no'], [0, 0, 0, 1, 'no'], [0, 1, 0, 1, 'yes'], [0, 1, 1, 0, 'yes'], [0, 0, 0, 0, 'no'], ...
5a363c71f6ff85ed6a765c39defa3fdac97b2aa3
419,310
import hashlib def compute_hash(filename): """Returns the MD5 hash of the specified file""" with open(filename, 'r') as f: contents = f.read().encode('utf-8') return hashlib.md5(contents).digest()
f73983580eace66d9fe82156ac6cddb1576da58d
657,397
from pathlib import Path from typing import Optional def find_in_parents(name: str, path: Path) -> Optional[Path]: """Searches parent directories of the path for a file or directory.""" path = path.resolve() while not path.joinpath(name).exists(): path = path.parent if path.samefile(path...
252a1d8c985f1a572495401f79759dea35bc56e6
164,647
import turtle def create_turtle(c, s): """ Creates a turtle :param c: turtle's color :param s: turtle's size :return: returns the turtle object fully created """ t = turtle.Turtle() t.pencolor(c) t.pensize(s) return t
3d9d35133a0c8a9c29f9a6a0fa6ff8b101930a08
32,937
def quote_str(value): """ Return a string in double quotes. Parameters ---------- value : str Some string Returns ------- quoted_value : str The original value in quote marks Example ------- >>> quote_str('some value') '"some value"' """ return ...
beaa09c517b6c2a92363652f2d53ae7fd6becabe
622,499
def parse_info_papers(_bibtexs:str, **kwargs) -> list: """ Parse the bibtex string and return a list of lists with the information It is anticipated that _bitexs has the format %l;%Y;%j;%J;%V;%p;%q;%K;%pp;%pc;%R;%S;%T;%u\n according to the documentation (https://ui.adsabs.harvard.edu/help/actions/expor...
7b0df544f6935a423d3dc8a875d7004d1eddd175
377,027
def c_not(condition): """The intrinsic conditional function Fn::Not Returns true for a condition that evaluates to false or returns false for a condition that evaluates to true. Fn::Not acts as a NOT operator. """ return {'Fn::Not': [condition]}
1d98bfbd83c3ba9994018179647caf622041522b
392,480
import re def get_vocabs_from_string(string): """ Search in the string to find BODC vocabularies (P01, P06 etc. Returns a dict where: key = vocabulary value = code """ result = re.findall('SDN:[A-Z0-9]*::[A-Z0-9]*', string) vocabs = {} for item in result: spl...
5bc5a2fa472f703291907b4c7322415128ebce9a
655,841
def format_route_name(name: str) -> str: """Used to format route name. Parameters ---------- name : str Returns ------- str """ return name.replace("Route", "").lower()
073f1407af0045289fe3dd5fa0554345d0b1c582
487,825
def modify_color(hsbk, **kwargs): """ Helper function to make new colors from an existing color by modifying it. :param hsbk: The base color :param hue: The new Hue value (optional) :param saturation: The new Saturation value (optional) :param brightness: The new Brightness value (optional) ...
ecc5118873aaf0e4f63bad512ea61d2eae0f7ead
708,258
import torch def batch_first2time_first(inputs): """ Convert input from batch_first to time_first: [B * T * D] -> [T * B * D] :param inputs: :return: """ return torch.transpose(inputs, 0, 1)
1e806761c6ab09dc9f601100cd2e5d4187fc1630
445,810
import math def roundup(n: float, m: int = 10) -> int: """ Round up a number n to the nearest multiple of M. Args: n: Number m: Multiple of which number to roundup to Returns: Rounded integer number """ return int(math.ceil(n / m)) * m
818a683d666b1f868453a11a8755eabb7f46881a
250,668
def get_byte(byte_str): """ Get a byte from byte string :param byte_str: byte string :return: byte string, byte """ byte = byte_str[0] byte_str = byte_str[1:] return byte_str, byte
2a00e82e10b4ed367ebcb41240d5393477f3b234
62,748
def form_save_instance(self, commit=True, **kwargs): """ Save this form's self.instance object if commit=True. Otherwise, add a save_m2m() method to the form which can be called after the instance is saved manually at a later time. Return the model instance. """ if self.errors: raise Val...
5bfb3c30ae0f1447706c90fa9b39b3bf2575ca22
464,686
def convert_tuple_to_8_int(tuple_date): """ Converts a date tuple (Y,M,D) to 8-digit integer date (e.g. 20161231). """ return int('{0}{1:02}{2:02}'.format(*tuple_date))
8584bb9ade995e95d12c9d09c4a6d52f7df44f5d
8,208
def validate_HR_data(in_data): # test """Validates input to add_heart_rate for correct fields Args: in_data: dictionary received from POST request Returns: boolean: if in_data contains the correct fields """ expected_keys = {"patient_id", "heart_rate"} for key in in_data.keys(...
ee5393145f92c5c5e844e3c2577a04be35d27f5f
362,664
def _format_group(g): """Format a restclient deployment group for display""" return { 'id': g['id'], 'description': g['description'], 'default_blueprint_id': g['default_blueprint_id'], 'deployments': str(len(g['deployment_ids'])) }
905ddf119009c89967f642ca92e6d3323ff523f6
301,517
def is_hermitian(matrix): """Check, if a matrix is Hermitian. `matrix` can be a numpy array, a scipy sparse matrix, or a `qutip.Qobj` instance. Args: matrix (list, numpy.ndarray, qutip.Qobj): Input array. Returns: bool: Returns `True` if matrix is Hermitian, `False` otherwise. ...
eae341b5fcf1c0a22f8b3f33ee432f67d077bb8d
398,345
def cli(ctx, workflow_id, invocation_id, step_id): """See the details of a particular workflow invocation step. Output: The workflow invocation step. For example:: {'action': None, 'id': '63cd3858d057a6d1', 'job_id': None, 'model_class': 'WorkflowI...
8892a9afa419ca270beb920e7b0390513a297054
190,063
def format(format_string, cast=lambda x: x): """ A pre-called helper to supply a modern string format (the kind with {} instead of %s), so that it can apply to each value in the column as it is rendered. This can be useful for string padding like leading zeroes, or rounding floating point numbers to a ...
fb485665d4dae0d8f4aaf256f48a49972c9f3120
170,412
def parse_header( line ): """Parses a header line into a (key, value) tuple, trimming whitespace off ends. Introductory 'From ' header not treated.""" colon = line.find( ':' ) space = line.find( ' ' ) # If starts with something with no whitespace then a colon, # that's the ID. if colon > -1 and ( space == -1 o...
854fb76adf49fdc6743ae5ee167ea93bf1ad711e
61,681
def _rangelen(begin, end): """Returns length of the range specified by begin and end. As this is typically used to calculate the length of a buffer, it always returns a result >= 0. See functions like `_safeDoubleArray` and `safeLongArray`. """ # We allow arguments like begin=0, end=-1 on purp...
8e010b08ef91b5ce011b348832ca1cdb829e519a
572,882
def form_message(sublines, message_divider): """Form the message portion of speech bubble. Param: sublines(list): a list of the chars to go on each line in message Return: bubble(str): formaatted to fit inside of a bubble """ bubble = "" bubble += message_divider bubble += "".join(subl...
c3ca1c2a684d25b439a594cfc5ade187f272a2c1
30,123
def get_extra_libraries(experiment_md): """get the extra_libraries field, or empty if not specified""" return experiment_md.get("extra_libraries", ())
5605625929fd60d71294a92f6c0c1000374c8870
515,711
def dms_to_string(d, m, s, decimals=2): """Converts degrees, minutes and decimal seconds to well formated coordinate string. Example: (41, 24, 12.2)-> 41°24'12.2" :param int d: degrees :param int m: minutes :param float s: decimal seconds :param int decimals: second's decimals :rtype: str ...
e97d904123b2534b40ed38645af61835c7dfaf12
178,351
def indent(input_string): """Put 4 extra spaces in front of every line.""" return '\n '.join(input_string.split('\n'))
645f8f7e793e99aec9453327c5e07a429aeab439
579,335
def frequency_temporal_evolution(Q_12,Q_23): """ convolve displacement estimates in the frequency domain Parameters ---------- Q_12 : np.array, size=(m,n), ndim={2,3} cross-power spectrum of first interval. Q_23 : np.array, size=(m,n), ndim={2,3} cross-power spectrum of second i...
73750df2b5af844a37ce5ee879ad3767a3ff5c5f
504,978
def noise(nx, ny, gen): """ Generate noise value at (nx, ny) using generator gen, tweaked to return a value from (0, 1) """ return gen.noise2d(nx, ny) / 2.0 + 0.5
de57ed5bd7e864b7464f3771fc01a2ad2338bd62
261,106
def recon_rule_preview_payload(passed_keywords: dict) -> dict: """Create a properly formatted payload for retrieving a rule preview from recon. { "filter": "string", "topic": "string" } """ returned_payload = {} if passed_keywords.get("filter", None): returned_payload["f...
dc18c7db03ca133666ac9c8d7f46ae6d4c55c19d
91,214
def alpha_rate(iteration): """ alpha learning rate :param iteration: the count of iteration :return: alpha """ return 150/(300 + iteration)
a62499dcc211827d7edaecf8cba047e4439c6c57
231,195
def cost(graph,e): """ Return the cost of an edge on a graph. Parameters ---------- G = A networkx graph. e = An edge on graph. Returns ------- The weight of an edge 'e' on a graph 'graph'. """ return graph.edges[e]['weight']
af41eb667d2ea586b523fd31c72d4e377ffbfa04
69,384
def cli(ctx, invocation_id): """Get a detailed summary of an invocation, listing all jobs with their job IDs and current states. Output: The invocation step jobs summary. For example:: [{'id': 'e85a3be143d5905b', 'model': 'Job', 'populated_state': 'ok', ...
d5e83ecdc061e8161a5f7ca7ac9bcda864293b7d
52,567
def render_User_detailed(self, h, comp, *args): """Render user detailed view""" h << h.h3(self.data.fullname) h << h.div(comp.render(h, model='avatar')) return h.root
eb1d692f828e219d5dc398fcfbac686bf2df7636
537,064
def stripped(text): """Remove invisible characters Remove all characters not between the ascii 32 and 127 and not an ascii 10 (line feed) """ def whitelist(c: int) -> bool: if 31 < c < 127 or c == 10: return True return False return "".join(filter(lambda c: whiteli...
caf4d1afa1d90dbab8d42f5535eedc3d314d48cd
220,543
def content(title, headers, items, style, **context): """ A table. :param title: Table's title. :param headers: List of headers [..., {"id": "<header_id>", "title": "<header_title>"}, ...] :param items: List of content (dicts). Each header will take <header_id> part. :param style: Style of the f...
0f6fe5aeeb594f66620475ca488221044a888a7d
157,624
def get_game_url(season, game): """ Gets the url for a page containing information for specified game from NHL API. :param season: int, the season :param game: int, the game :return: str, https://statsapi.web.nhl.com/api/v1/game/[season]0[game]/feed/live """ return 'https://statsapi.web.nh...
a404609e565b7b423226bba056f93574d2d21366
448,366
def test_lessthan(value, other): """Check if value is less than other.""" return value < other
199d674e58b55a6c5ceb49136e35ace0067c5289
159,961
from typing import List def convert_sample_names_to_indices( names: List[str], samples: List[str] ) -> List[int]: """Maps samples to their integer indices in a given set of names. Used to map sample string names to the their integer positions in the index of the original character matrix for efficien...
3e4bf00fbcebb446757dcf1a09d6dbb1382c8ea1
178,591
import re def remove_spaces(text): """ Remove all the tabs, spaces, and line breaks from the raw text Args: text(str) -- raw text Returns: text(str) -- text clean from tabs, and spaces """ # remove \t, \n, \r text = text.replace("\t", "").replace("\r", "").replace("\n", "")...
64e0da2b0a6c274476ed1a560fd814479608908b
626,628
def format_theta(theta_topic_row, limit=10): """ Convert full theta row (topic) into compact form The result will be sorted by probability (high to low). """ topics = theta_topic_row; topics = [(i, val) for i, val in enumerate(topics)]; topics = sorted(topics, ke...
05c30a16c40d1c474aabb4e054ff8d9cba6e1cd5
88,050
def remove_numbers(s): """Remove any number in a string Args: s (str): A string that need to remove number Returns: A formatted string with no number """ return ''.join([i for i in s if not i.isdigit()])
0777995b98e1c312d6f5276a85cf8eecd7978a51
404,285
from typing import List from typing import Union def list_sum_normalize(num_list: List[Union[int, float]]) -> List[float]: """Normalize with sum. Args: num_list(list): List of number to normalize. Returns: list: List of normalized number. """ t = sum(num_list) # avoid dive z...
4439a382ba8ba02ed26f645c847e93c4e56b51bc
251,055
import re def get_tensor_names(string_obj): """ Get tensor names from the given string. :param obj: a string representing an object from gc.get_objects() :return: the name of the tensor variable >>> names = get_tensor_names(log2) >>> assert len(names) == 3 >>> assert names[0] == "tensor1...
d7b036aa2545cf16d088c29a724f4d1cebab56b1
89,297
def normal_group(group): """ Returns true if group name can be normalized, false otherwise :param group: str :return: bool """ return False if group.startswith('_product_admin_') else True
503441c5657fa5aa277ad2867aad28a5047f11b8
356,160
def calc_average(total, count): """ Function that will return the average of a set of numbers """ return float(total / count)
65c72c81e054f13e0467a1e7aef559c977b115c2
227,069
def JNumber(state_list): """Calculate the angular momentum from the number of sub-states in the list. Parameters: state_list (list): List of sub-states of a single angular momentum state. Returns int: The total angular momentum of the state. """ return int((len(state_list)-...
b82b5dc60e5d567ea9033bc0f91ae0b26b1509cd
365,532
def maximum(a, b): """ Finds the maximum of two numbers. >>> maximum(3, 2) 3 >>> maximum(2, 3) 3 >>> maximum(3, 3) 3 :param a: first number :param b: second number :return: maximum """ return a if a >= b else b
bcdf0a116af1f7b921a390525e8ff5b0fa7c81fb
340,006
def transform_input_kernel(kernel): """Transforms weights of a single CuDNN input kernel into the regular Keras format.""" return kernel.T.reshape(kernel.shape, order='F')
fc2b69664c364e6989566c8f9538109c7a7833b5
103,686
def diff_lists(lists): """Diff the last list with the other lists and return a list of elements that are in the last list but not in the any of the previous lists. Arguments: lists -- The last list (-1) in this list of lists will be diffed with the other lists. Returns: A list of elements that...
918655ba48e9d278e29d369b5880077d9f5494a9
164,740
from typing import List def quantile(xs: List[float], p: float) -> float: """Returns the pth-percentile value in x""" p_index = int(p * len(xs)) return sorted(xs)[p_index]
35dbf0ca4fc6929786cf08908806a8092be6fe1c
617,893
import random def rand_cord(width : int, height : int): """Pass width and heeight of the window Returns one random coordinate within given window space Steps by 20s """ cord = [] x = random.randrange(0,width - 19,20) y = random.randrange(0,height - 19,20) cord.append(x) cord.append...
c81b6a85aa44a46953db82b73f4382557f49d4fd
427,867
def expand(v): """Split a 24 bit integer into 3 bytes >>> expand(0xff2001) (255, 32, 1) """ return ( ((v)>>16 & 0xFF), ((v)>>8 & 0xFF), ((v)>>0 & 0xFF) )
d63a441e8bb9d33c0ff92ceceb412932b0fea84c
330,835
def bind_method(value, instance): # good with this """ Return a bound method if value is callable, or value otherwise """ if callable(value): def method(*args): return value(instance, *args) return method else: return value
33ced528e79e30da1709dae12adb5254f41470d2
513,677
def find_list_string(name, str_list, case_sensitive=True, as_prefix=False, first_matched=False): """ Find `name` in the string list. Comparison parameters are defined in :func:`string_equal`. If ``first_matched==True``, stop at the first match; otherwise if multiple occurrences happen, raise :exc:`...
f485ae3cdebcee9e4cfe85378c38f7f27d737b96
37,236
def read(metafile): """ Return the contents of the given meta data file assuming UTF-8 encoding. """ with open(str(metafile), encoding="utf-8") as f: return f.read()
82135a6b680803c01cb9263e9c17b4c3d91d4516
688,557
from typing import Dict from typing import Any def format(content: str, substitutions: Dict[str, Any]) -> str: """Formats the given content by performing the requested substitutions""" for currentKey in substitutions: content = content.replace( "%" + currentKey + "%", str(substitutions[cur...
9762afe81a6783900e730f7c3037fefe82e0383f
526,917
def get_num_classes(dataset: str): """Return the number of classes in the dataset. """ if dataset == "imagenet": return 1000 elif dataset == "cifar10": return 10 elif dataset == "mnist": return 10
e3d6a0fe4d40629cec58d93cf8bb9d4f95ea6e29
566,242
import random def choose_from(*args): """Choose a random item from a variable number of lists.""" num_words = sum([len(x) for x in args]) # Take the ith item from the lists i = random.randint(0, num_words - 1) for (j, x) in enumerate(args): if i < len(x): return x[i] i -= len(x)
5dc283d6356205cca95dd886431390910f4f9a25
525,343
import math def area(r: float) -> float: """ Calculate the area of a circle based on the radius. :param r: The radius of the circle: Float :return: The area of the circle: Float """ return math.pi * (r ** 2)
4b0fea9198ce289b7712f732249458a86038a237
191,872
def generalized_entropy_index(distribution, alpha): """Genralized Entropy Index Args: distribution (list): wealth distribution of the population alpha (float): inequality weight, for large alpha the index is especially sensitive to the existence of large incomes, whereas...
56746b50450d8b17bbb9aa840b561cded8d3a830
468,385
def _get_local_explanation_row(explainer, evaluation_examples, i, batch_size): """Return the local explanation for the sliced evaluation_examples. :param explainer: The explainer used to create local explanations. :type explainer: BaseExplainer :param evaluation_examples: The evaluation examples. :...
b17f88b7f03d0ff40772102a88afc4449fee8035
663,142
def addSeqTokensArgs(parser): """ Add arguments defining DNN processing sequences of tokens Parameters: - parser -- argument parser as an object of ArgumentParser to add arguments Returns: constructed argument parser """ parser.add_argument('--seq_len', default=None, type=i...
15bb822b8f96f58c7e8f30af1789a36bc2471f15
595,786
def _weights(vgg_layers, layer, expected_layer_name): """ Return the weights and biases already trained by VGG """ W = vgg_layers[0][layer][0][0][2][0][0] b = vgg_layers[0][layer][0][0][2][0][1] layer_name = vgg_layers[0][layer][0][0][0][0] assert layer_name == expected_layer_name return W, ...
eca1cba51cc4736aef3460666d390cab306ce063
367,318
import gzip import json def import_compressed_json(file_name): """Import gzip compressed JSON. :param file_name: Name of file to be read e.g. dict.json.gz :returns: JSON as a dictionary. """ with gzip.open(file_name, mode="rt") as f: return json.load(f)
c9c4bca3c04a9a36cb33d5b172b6836ec044d5d5
589,856
def check_ALL_DS(DS_ES_X_Map): """ ES used with ALL as DS can not be used with any other DS. This function checks if this is true. """ ES_with_ALL = [row[1] for row in DS_ES_X_Map if row[0] == "ALL"] ES_without_ALL = [ES for ES in ES_with_ALL for row in DS_ES_X_Map if row[0...
58b2f2fd4a4a1f20bba74aa6150d91169a4a9695
40,252
def _IsBoundary(i, n, cont, assigned): """Is path i a boundary, given current assignment? Args: i: int - index of a path to test for boundary possiblity n: int - total number of paths cont: dict - maps path pairs (i,j) to _Contains(i,j,...) result assigned: set of int - which paths are...
2ea312e2d497980a3bdfd45ac5005e6857869543
231,964
def _get_class(value, max): """Get the CSS class for the value and max such that higher values are better""" if value < (max * 0.33): return "bad" if value > (max * 0.67): return "good" return "okay"
88b0cf6359155f504a6bdbd26e6e3b88941e83c6
524,090
def make_pairs(args, pair_len=2): """Divide input list args into groups of length pair_len (default 2).""" assert len(args) % pair_len == 0 return [tuple(args[pair_len * i: pair_len * (i + 1)]) for i in range(len(args) // pair_len)]
b93526b84784f422676f32d12ff82dc8ae839003
565,878
def infer_angular_variance_spherical(var_r, phi_c, var_q_min): """Calculate angular variance given properties of a beam with quadratic phase corrected by a lens. The lens which removes the spherical component has focal length f = -k*var_r/(2*phi_c). This means that -phi_c is the phase of the quadratic comp...
b8c3fcfff84530bb6fd2a9cee2e52dcb6fa4baa7
289,571
def _PlatformEventHandler(data): """Decorator for platform event handlers. Apply giving the platform-specific data needed by the window to associate the method with an event. See platform-specific subclasses of this decorator for examples. The following attributes are set on the function, which i...
db2a5194772eb1df26e9cd66402cba60bcf42e32
474,868
def increment(number: int) -> int: """Increment a number. Args: number (int): The number to increment. Returns: int: The incremented number. """ return number + 1
27f4becd9afb747b22de991ab4cf030b14d3dac5
702,917
def makeaxisstep(start=0, step=1.00, length=1000, adjust=False, rounded=-1): """ Creates an axis, or vector, from 'start' with bins of length 'step' for a distance of 'length'. :type start: float :param start: first value of the axis. Default is 0. :type step: float :param st...
2c6066f1ae76816bf34135507e180e08f98d12f5
321,931
def dict_from_file(filename, key_type=str): """Load a text file and parse the content as a dict. Each line of the text file will be two or more columns splited by whitespaces or tabs. The first column will be parsed as dict keys, and the following columns will be parsed as dict values. Args: ...
8d12620ca12c65c9cc8769262eba253d26581a72
617,877
def mangle(cls, name): """Applies Python name mangling using the provided class and name.""" return "_" + cls.__name__ + "__" + name
348f9d1b1819c6283f81c8e7bf3a07a1e7c25b7f
99,954
def get_url(query, page): """ Generate URL from query and page number. The input query will be split into token or list of word, e.g 'luka parah' will be ['luka', 'parah'] and 'kdrt' will be ['kdrt'] For input query with more than 1 word, the url will be `..q={token1}+{token2}&..`, e.g `..q=luka+parah&....
365e5408f1d429bc63bb5a512164069a149c1c26
122,169
def increment_count(val): """ Increments the value by 1. """ return val + 1
107dc447d5e749daae5b1d0f578a213088d5ba84
678,294
def error_response(message): """ Construct error response for API containing given error message. Return a dictionary. """ return {"error": message}
677912817c91725c7079b538bfdf915eb21f3fa0
689,262
def construct_SN_default_rows(timestamps, ants, nif, gain=1.0): """ Construct list of ants dicts for each timestamp with REAL, IMAG, WEIGHT = gains """ default_nif = [gain] * nif rows = [] for ts in timestamps: rows += [{'TIME': [ts], 'TIME INTERVAL': [0.1], ...
b81e45d2d5299042b3332a2386a0fd4d2d6d59d7
1,517
import pickle def load_objects(loadpath): """Load (unpickle) saved (pickled) objects from specified loadpath. Parameters ---------- loadpath : absolute path and file name to the file to be loaded Returns ------- objects : list of saved objects """ try: with open(l...
3cd6a212d43a1b8c8c91f58cd332d725398d4dc6
425,226
def box(points): """Obtain a tight fitting axis-aligned box around point set""" xmin = min(points, key=lambda x: x[0])[0] ymin = min(points, key=lambda x: x[1])[1] xmax = max(points, key=lambda x: x[0])[0] ymax = max(points, key=lambda x: x[1])[1] return (xmin, ymin), (xmax, ymax)
8efb486150aa6d9f74f011c37302b57cf78d46f2
255,219
def get_clade_point(arg, node_name, time, pos): """Return a point along a branch in the ARG in terms of a clade and time""" if node_name in arg: tree = arg.get_marginal_tree(pos - .5) if (time > tree.root.age or (time == tree.root.age and node_name not in tree)): ret...
b62822600c0cd192769d2813b90358d8b1b66d50
375,132
from typing import Any from typing import Iterable from typing import Optional from typing import Dict def obj_to_dict_helper( obj: Any, attribute_names: Iterable[str], namespace: Optional[str] = None ) -> Dict[str, Any]: """Construct a dictionary containing attributes from obj This is useful as a helper...
c1c4d95f65f8b5d575629fcb23258f52b871b30b
284,352
from typing import Dict def success_of_action_dict(**messages) -> Dict: """Parses the overall success of a dictionary of actions, where the key is an action name and the value is a dictionarised Misty2pyResponse. `overall_success` is only true if all actions were successful. Returns: Dict: The dictio...
542725d492df7758e9b90edf8d18a935c824e18a
676,795
def _clean(sensor, fetch_resp): """ Clean data by deleting streams with zero values. Parameters ---------- sensor : sensor name type to evaluate e.g. Zone_Air_Temperature fetch_resp : Mortar FetchResponse object Returns ------- sensor_df : dataframe of nonzero sensor measurements ...
3c8404dd6b4a9d9bc7237f16201d91e829d1e113
156,441
def get_text(index_name, es, text_id): """ Return a text in ElasticSearch with the param id :param index_name: ElasticSearch index file :param es: ElasticSearch object :param text_id: Text id :return: str """ res = es.get(index=index_name, id=text_id) return res['_source']['text']
b57ef476c8a1e74614846f7a231cf81b05833fda
296,324
from typing import List def getValuesInInterval(dataTupleList: List, start: float, end: float) -> List: """ Gets the values that exist within an interval The function assumes that the data is formated as [(t1, v1a, v1b, ...), (t2, v2a, v2b, ...)] """ intervalDataList = [] for dataTuple i...
42dd008ff3dfadc5e7ac4d7b34f30626a6dadf73
148,796
import datetime as dt def createDatetime(yr, mo, dy, hr): """ Same thing as above function but converts to datetime format instead of decimal year """ datetime = [] for i in range(len(yr)): time = dt.datetime(yr[i], mo[i], dy[i], hr[i]) datetime.append(time) return datetime
087b6672dbd7d3a0a81e3fd6c8fc808667563074
167,256
def area_of_rectangle(height, width = None): """ Returns the area of a rectangle. Parameters ---------- height : int or float The height of the rectangle. width : int or float The width of the rectangle. If `None` width is assumed to be equal to the height. Return...
6867148be08d474f41e928d59d248041236911e8
188,717
def other(si, ti): """ Retrieves the "other" index that is not equal to the stack index or target stack index. Parameters ---------- si : int The stack index that would be removed from. ti : int The target stack index that would be added to. Returns ------- int ...
357e51f22f4dd9b40af4bbf66da2363df9fd2a7b
553,957
def set_is_singles(slots): """Check whether a set is in the singles or doubles format based on its slots""" if slots is None: return False for slot in slots: entrant = slot['entrant'] try: participants = entrant['participants'] if len(participants) > 1: ...
89e919d9205076e84103f563b0ce364eb947fef4
340,890
def none_has_no_cards(player_cards,players_number): """checks if every player has cards on their hands >>> p1_cards=[('A', '♥', 11),('K', '♣', 10), ('5', '♥', 5), ('7', '♣', 7), ('8', '♣', 8), ('5', '♦', 5),('J', '♠', 10)] >>> p2_cards=[('A', '♥', 11),('4', '♦', 4), ('2', '♠', 2), ('3', '♣', 3), ('9', '♣',...
1eb1ac44df3fbf5e2a824057813b7ea710a2610a
317,796
def q_learn(old_state_action_q_value, new_state_max_q_value, reward, learn_rate=0.01, discount_factor=0.9): """ Returns updated state-action Q_value. :param old_state_action_q_value: Q_value of the chosen action in the previous state. :param new_state_max_q_value: maximum Q_value of new state. :para...
cfe2f70823dff79b43a426b2f9e0996ac5e507c1
643,016
def portfolio_return(weights, returns): """ Computes the return on a portfolio from constituent returns and weights weights are a numpy array or Nx1 matrix and returns are a numpy array or Nx1 matrix """ return weights.T @ returns
9e6ac36b97c1fbcd74c209ab04493ff12a8ca713
421,941
def pxe_mac(mac): """ Create a MAC address file for pxe builds. Add O1 to the beginning, replace colons with hyphens and downcase """ return "01-" + mac.replace(":", "-").lower()
483ccf559b5cb014070be3cc9e0237ac5d1a0b34
670,281
def get_kqshift(ngkpt, kshift, qshift): """Add an absolute qshift to a relative kshift.""" kqshiftk = [ kshift[i] + qshift[i] * ngkpt[i] for i in range(3) ] return kqshiftk
0fe469cbeea3265705e1eb89bad8c00cb59374a7
624,208
def _repeated_proto3_field_to_list(field): """Convert a proto3 repeated field to list. Repeated fields are represented as an object that acts like a Python sequence. It cannot be assigned to a list type variable. Therefore, doing the conversion manually. """ result = [] for item in field: ...
424ef2a64d2878a2dce547bcb22c6f265d417aea
83,573
def getDistance(sensor): """Return the distance of an obstacle for a sensor.""" # Special case, when the sensor doesn't detect anything, we use an # infinite distance. if sensor.getValue() == 0: return float("inf") return 5.0 * (1.0 - sensor.getValue() / 1024.0)
68ff9e0c8c4dd7687e328d3b9c4634677cfe25cd
702,978
def load_reports_file(path): """ Loads radiology reports from a file. Radiology reports must be separated by the following string: '----------------------------------------------' Inputs: path str path to the file containing the reports Output: reportlist list a list...
4a941c75c725f73134007112a74920954465494d
106,855