content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def status_to_dict(status_str): """ Helper that converts the semicolon delimited status values to a dict """ status = {} params = [param.strip() for param in status_str.split(";") if param.strip()] for param in params: (key, val) = param.split(":") status[key] = val retur...
b74b68c74a5eb1ffac3164355537be23b9197309
180,337
def convert_mat_value(val): """Convert values specified in materials elements_vars.""" return { 'values': [float(x) for x in val['values']], 'min_value': float(val['min_value']) if val['min_value'] is not None else None, 'max_value': float(val['max_value']) if val['max_value'] is not Non...
e664d3803f7ae418e48831990ab9caab0b574217
486,661
def _compute_preferred_numer_of_labels( available_space: int, vertical_direction: bool ) -> int: """ Compute an estimate for the preferred number of labels. """ # For horizontal direction (x axis) preferred_number_of_labels = int(available_space / 15) if vertical_direction: # for y ...
4209498eda4fe8b35535ec05ad6d368ea6dba736
50,302
def convert_words_to_index(words, dictionary): """ Replace each word in the dataset with its index in the dictionary """ return [dictionary[word] if word in dictionary else 0 for word in words]
4d1e46b90ecbe855e36617565551d8332f38d29d
514,264
from typing import Counter def add_dict(dicts): """Add dictionaries. This will add the two dictionaries `A = {'a':1, 'b':2, 'c':3}` `B = {'b':3, 'c':4, 'd':5}` into `A + B {'a':1, 'b':5, 'c':7, 'd':5}` but works for an arbitrary number of dictionaries.""" # start with the first di...
a2e0a20735e597c5e6856a3755e14dd7153f418a
356,179
import uuid import base64 def _try_b32_decode(v): """ Attempt to decode a b32-encoded username which is sometimes generated by internal Globus components. The expectation is that the string is a valid ID, username, or b32-encoded name. Therefore, we can do some simple checking on it. If it d...
299a6ae8e2fa11788da0aa7a4ff36e24db614ec1
453,339
def string_to_list(s): """Splits the input string by whitespace, returning a list of non-whitespace components Parameters ---------- s : string String to split Returns ------- list Non-whitespace string chunks """ return list(filter(lambda x: x, s.strip().split(' '...
a88cb4359bd955e13dc6f3f86941e67c5c88c3f6
543,738
def pf(basic): """ pf Is 12% Of Basic Salary""" pf = basic*12/100 return pf
a16bda8b7102c7725b01f7bdbbe613b7f34d9409
363,778
def int_to_little_endian_bytes(integer): """Converts a two-bytes integer into a pair of one-byte integers using the little-endian notation (i.e. the less significant byte first). The `integer` input must be a 2 bytes integer, i.e. `integer` must be greater or equal to 0 and less or equal to 65535 (0xff...
86325aa8dd9a0e6d36ff6b95bc7daac6f0360294
447,839
def gen_function_reset(function_name): """Writes a reset function for stateful models Reset function is used to clear internal state of the model Args: function_name (str): name of main function Returns: signature (str): delcaration of the reset function function (str): definiti...
b35c767a341ff559e0340bf73888badac900b4ba
389,688
def get_character_dictionary_from_text(filename, name_position, dialogue_position, scenario_position): """ This function converts a text file inot a character dictionary. Parameters: filename: string: The path of the file to read name_position: int: Number of spaces before the name dialogue_p...
2c4b9aa6288da8ae2539ea48647e3f903b3a2e90
459,639
def GetCheckoutPath(api): """Path to checkout the flutter/engine repo.""" return api.path['cleanup'].join('builder', 'src')
cedbf61e47ff04e8769275c3197f18a02795b768
453,350
def open_file(path, mode): """ Attempts to open file at path. Tried up to max_attempts times because of intermittent permission errors on windows """ max_attempts = 100 f = None for _ in range(max_attempts): # pragma: no branch try: f = open(path, mode) except Per...
ae58eb8f6eb41cfb15cdbfc9c9d574148b060b73
221,659
def clean_column_name(df, index, name): """Check that the column has the expected name (case insensitive) as a sanity check that the user provided the right data, and return a new dataframe with the column renamed to the preferred casing. """ df_name = str(df.columns[index]) if df_name.lower()...
e522a3f15f9fe416a4afb6dc635720e05c8ed740
505,392
def _check_slice(sli, dim): """ Check if the current slice needs to be treated with pbc or if we can simply pass it to ndarray __getitem__. Slice is special in the following cases: if sli.start < 0 or > dim # roll (and possibly pad) if sli.stop > dim or < 0 # roll (and poss...
70c49ab8932702f310f053588b7a07f8a6ea522d
445,899
def reverse_words(string: str) -> str: """Sort words in reverse order. Examples: >>> assert reverse_words('hello world!') == 'world! hello' """ return ' '.join(string.split()[::-1])
ec5ad7fa50c70543693d69856db7fe21fa85d632
69,984
def indentblock(text, spaces=0): """Indent multiple lines of text to the same level""" text = text.splitlines() if hasattr(text, 'splitlines') else [] return '\n'.join([' ' * spaces + line for line in text])
aba0b00b1943d6662a1ccfcb1afbfce225ad698d
377,865
def get_class_name(obj: object) -> str: """ Get the full class name of an object. :param obj: A Python object. :return: A qualified class name. """ module = obj.__class__.__module__ if module is None or module == str.__class__.__module__: return obj.__class__.__name__ return m...
cbb80bfe03c62604ab5a1ecf9df35094f3f7e145
77,848
def _pickup_dt(sys1, sys2): """ Determine the sampling time of the new system. :param sys1: the first system :type sys1: TransferFunction :param sys2: the second system :type sys2: TransferFunction :return: sampling time :rtype: int | float """ if sys1.dt is None and sys2.dt is ...
4106e5d375da70fe5b2fbaf9a8b3b293751c6820
292,665
def total_sleep_minutes(guard): """Calculate total minutes slept by guard.""" _, shifts = guard return sum( wakes - sleeps for sleeps, wakes in shifts )
4b510c8be5a47aba87b0b513f98026d0b62c636c
555,075
import re def is_a_number(x): """This function determines if its argument, x, is in the format of a number. It can be number can be in integer, floating point, scientific, or engineering format. The function returns True if the argument is formattted like a number, and False otherwise.""" num...
f74e8de1e865793ce1e57e85ed09c8846b9203cd
590,883
from typing import Optional def get_hash_type(hash_value: str) -> Optional[str]: """Get the hash type.""" if len(hash_value) == 32: return "md5" elif len(hash_value) == 40: return "sha1" elif len(hash_value) == 64: return "sha256" else: return None
a2dbdbeb64f8b5e340bad174c763a3302ff8318c
399,080
def round_up(x:int, up_to:int): """ Round up to the nearest specified value""" return x if x % up_to == 0 else x + up_to - x % up_to
e1b7c23d3bbe6e9e22dbb20748ce4b46b4300654
564,685
def strategy_expensive(cookies, cps, history, time_left, build_info): """ Always buy the most expensive item you can afford in the time left. """ info_object = build_info.clone() items_list = info_object.build_items() item_to_buy = None max_cost = float("-inf") for item in items_list: ...
7427332b523d08ea947cd74f00b5e4cfd9fcb3d5
291,051
def extract_patches(features, size, stride): """ Arguments: features: a float tensor with shape [c, h, w]. size: an integer, size of the patch. stride: an integer. Returns: a float tensor with shape [N, c * size * size], where N = n * m, n = 1 + floor((h - size)/strid...
903a7c550d1e044b087e81b2024786f416f4527d
498,545
def perform_data_split(X, y, training_idxs, test_idxs, val_idxs): """ Split X and y into train/test/val sets Parameters: ----------- X : eg, use img_bow_hist y : corresponding labels for X training_idxs : list/array of integers used as indicies for training rows test_idxs : same val...
388737dea103086cb5a37489011e47a81735d53c
307,800
def critical_speed(_x): """Critical speed of rolling disc. _x is an array/list in the following order: g: Gravitational constant r: Radius of disc """ # Unpack function arguments g, r = _x # Calculate return values cs = -3**(1/2)*(g/r)**(1/2)/3 # Return calculated v...
909259c8c9039b87c2c8f5fe4ae22b0236568030
257,797
def create_error(request, status, code='', title='', detail=''): """creates a JSON API error - http://jsonapi.org/format/#errors "status" - The HTTP status code applicable to this problem, expressed as a string value. "code" - An application-specific error code, expressed as a s...
4a98b4b6a746c31926940cb07854e8363b1a97c1
113,238
def pubsub_messages(request): """Create a list of pubsub messages.""" with open('tests/data/pubsub_messages.txt') as f: messages = [line for line in f] return messages
8fea5217e6486454cc966f7e886e749c7cf5d9ab
539,785
def return_geojson(lat,lng,increment): """returns geojson box around lat and lng""" geojson_geometry = { # (lng,lat) "type": "Polygon", "coordinates": [ [ [ lng+increment, lat+increment ], [ lng+increment, lat-increment ], [ lng-increment, lat-increment ...
aa0d09fef600d0d76f8ae6597e8d8f6171abaf96
604,672
def find_number_to_keep(count_of_0, count_of_1, criteria) -> str: """ Compare numbers according to a criteria ('most' or 'least'). Criteria 'most' returns the number of which count is bigger. Criteria 'least' returns the number of which count is lesser. When counts are equal, criteria 'm...
743ddb403a52795cd0348ac880ad6b9011afbe25
249,362
def _make_nested_padding(pad_shape, pad_token): """Create nested lists of pad_token of shape pad_shape.""" result = [pad_token] for dimension in reversed(pad_shape): result = [result * dimension] return result[0]
5be7f0dc387369a4d00c35b538854316848d049b
543,875
def iter_to_string(it, format_spec, separator=", "): """Represents an iterable (list, tuple, etc.) as a formatted string. Parameters ---------- it : Iterable An iterable with numeric elements. format_spec : str Format specifier according to https://docs.python.org/3/library/...
730a8ea44785c9bb995ffae0a1b302fa25b37029
283,210
def get_jaccard_sim(str1, str2): """ Jaccard similarity: Also called intersection over union is defined as size of intersection divided by size of union of two sets. """ a = set(str1.split()) b = set(str2.split()) c = a.intersection(b) return float(len(c)) / (len(a) + len(b) - len(c)...
be39079c7a5b04add59f7e303eb1bcecbae52053
446,662
def get_meta(txt): """Parse meta information from text if available and return as dict. meta information is a block imbedded in "---\n" lines having the format: key: value both are treated as strings the value starts after the ": " end ends with the newline. """ SEP = '---\n' meta...
c9d6f88b4771693790c371e96eada2198c73b989
561,881
def char_collect_all(s, c): """ Find all appearances of char in string :param s: haystack :param c: needle :return: list of indices """ start = 0 res = [] clen = len(c) while True: start = s.find(c, start) if start == -1: break res.append(start) st...
93147386203cb3c275f7227e91e3ce20dd63820c
412,192
def func_node(node): """Get the function AST node from the source.""" return node.body[0]
9e295c7cd1dccd323e9a3544afd5e377cfa4e86c
237,394
def format_label_outputs(label: dict = {}) -> dict: """Take GitHub API label data and format to expected context outputs Args: label (dict): label data returned from GitHub API Returns: (dict): label object formatted to expected context outputs """ ec_object = { 'ID': label...
bd7b7dccdceb989a5cd55e85b9dc875c4269ef40
602,790
def find_pos(mydict, n, keys): """ Find the bag and local position of the overall nth element in one set of a dictionary. Parameters ---------- mydict : dictionary Dictionary with array_like values. Each such array_like must have the same shape except for the first dimension. ...
b51d16b934198511e60c17b6ee74ff2d9d2701e7
325,781
def original_choice(door): """ Return True if this door was picked originally by the contestant """ return door.guessed_originally is True
5d2c11e32ef4181b653642fb18a995427a3bae9b
682,158
def is_commit_verified(commit: dict) -> bool: """`True` if a Github commit is verified, `False` otherwise.""" return commit["commit"]["verification"]["verified"]
0d3e7ab1157a01f83588e47d7fe8f1e260453dff
285,404
def validate_window_size(candidate_window_size: int) -> int: """Return validated window size candidate, raising a meaningful error otherwise. Parameters ----------------- candidate_window size: int, The candidate window size value to validate. Raises ----------------- ValueError, ...
6459fea1322ea791485356d4e25899aa2493fe28
106,758
import re def get_image_name_from_recipe(recipe_file_name: str) -> str: """ Returns the image name contained in a recipe file name. """ return re.sub(r'(^.*?)\..*$', r'\1', recipe_file_name)
51463799d9739082f007bca1b032d45f4590b401
161,000
def tmpdir_repoparent(tmpdir_factory, scope='function'): """Return temporary directory for repository checkout guaranteed unique.""" fn = tmpdir_factory.mktemp("repo") return fn
90ab3cc6d5484da6cfb9c47de0caf128fa0d6a6a
651,358
import configparser def load_config(feed_file): """Load configs into dict.""" config_dict = {} config = configparser.RawConfigParser() # load the feed config config.read(feed_file) config_dict = {} for key in config: config_dict[key] = config[key] return config_dict
d1cecdf1a979d85970accdff9ad717ff733840b0
210,175
import re import string def clean(text): """ Remove tickers, special characters, links and numerical strings Parameters text : str User given input Returns ------- str cleaned text Examples -------- >>>text="RT $USD @Amila #Test\nTom\'s newly listed Co. &...
051cfb0c3acbe092f390b5a7040025a6b172e0de
332,661
def equilibrium_capital(alpha, delta, g, n, rho, theta, **params): """Steady state value for capital stock (per unit effective labor).""" return (alpha / (delta + rho + theta * g))**(1 / (1 - alpha))
f8dc11767621a8b2869bf2c5346d07a3f945e125
353,747
def average_precision_at_k(targets, ranked_predictions, k=None): """Computes AP@k given targets and ranked predictions.""" if k: ranked_predictions = ranked_predictions[:k] score = 0.0 hits = 0.0 for i, pred in enumerate(ranked_predictions): if pred in targets and pred not in ranked_...
57e21a1ca8b8f7fccc0b5c59dbfc799d8618fc93
7,095
import itertools def _n_enr_states(dimensions, n_excitations): """ Calculate the total number of distinct ENR states for a given set of subspaces. This method is not intended to be fast or efficient, it's intended to be obviously correct for testing purposes. """ count = 0 for excitations...
ab974f8e0028928f1671c51537c9b4166c337958
85,874
def AppendPatternsToFilter(test_filter, positive_patterns=None, negative_patterns=None): """Returns a test-filter string with additional patterns. Args: test_filter: test filter string positive_patterns: list of positive patterns to add to string negative_patterns: list of ne...
1719010bd037ea96d6d11300579e6d503ae13df4
451,078
def dms_to_decimal(degrees, minutes, seconds, sign=' '): """Convert degrees, minutes, seconds into decimal degrees. >>> dms_to_decimal(10, 10, 10) 10.169444444444444 >>> dms_to_decimal(8, 9, 10, 'S') -8.152777777777779 """ return (-1 if sign[0] in 'SWsw' else 1) * ( float(degrees) ...
c18bd8c094c650acbb4c374b9793fe2cc01879b5
427,133
def get_value_csr(data, indices, index): """get one value from a sparse vector""" for i in range(len(indices)): if indices[i] == index: return data[i] return 0.0
918b84e8d2cadd4d802b688729ea7dcc4135f55b
221,581
def LoadSiteList(path): """Loads a list of URLs from |path|. Expects the URLs to be separated by newlines, with no leading or trailing whitespace. Args: path: The path to a file containing a list of new-line separated URLs. Returns: A list of strings, each one a URL. """ f = open(path) urls =...
c81533b5b28cc1ed66fe3c699cc66fced807a972
288,424
def get_end_activities_from_log(trace_log, activity_key="concept:name"): """ Get the end attributes of the log along with their count Parameters ---------- trace_log Trace log activity_key Activity key (must be specified if different from concept:name) Returns -...
70179252dac0d5c102f7522f909b6539dd1376ee
458,883
def largest_prime_factor_even_optimized(number): """ We know that, excluding 2, there are no even prime numbers. So we can increase factor by 2 per iteration after having found the """ factors = [] factor = 2 if number % factor == 0: number = number // factor factors.append(...
36269bc3fc68af504d85adae6069fb98469be9d3
76,348
import gzip def get_open_func(filename): """ Gets the open function to use to open the given filename. :param filename: The file to open. :return: The open function, and the read-mode flag to use. """ # Select the open function based on the filename if filename.endswith('.g...
d59e29bf53b80535fa81080dceb78a8712de546e
499,897
from typing import Any def find_by_key(data: dict, target: str) -> Any: """ Find a value by key in a dictionary. .. code-block:: python >>> dct = { >>> "A": "T", >>> "R": 3, >>> "B": { >>> "C": { >>> "D":...
41f3fef0c49f596e7998b32f99419cff624f5568
507,851
def find_English_definition(content: str): """ Find the English Definition from the content :param content: The contents of the website :return Eng_def: The found English definition :return content: The contents that cut the English definition part """ if '释义' not in content: Eng_def...
9c4e748aca047fd8c381a894993f3dc2a08586ff
503,584
def format_null(string: str) -> str: """Remove the quotes from the null values.""" return string.replace("\"null\"", "null")
cfcda3e1775dbe122b7bec89a56e93aeb16c8a50
223,817
import random def sample(p): """Given an array of probabilities, which sum to 1.0, randomly choose a 'bin', e.g. if p = [0.25, 0.75], sample returns 1 75% of the time, and 0 25%; NOTE: p in this program represents a row in the pssm, so its length is 4""" r = random.random() i = 0 while r > p[i...
886da94e2c9e35bd07ceba606de92d2126197b99
25,173
import torch def symmetric_mse_loss(input1, input2): """Like F.mse_loss but sends gradients to both directions Note: - Returns the sum over all examples. Divide by the batch size afterwards if you want the mean. - Sends gradients to both input1 and input2. """ assert input1.size() == in...
64e01abd6b90f2874aa58cd6306709d22535f38c
586,631
def guess_mean_kind(unit, control_var): """ Guess which kind of mean should be used to summarize results in the given unit. :returns: ``'arithmetic'`` if an arithmetic mean should be used, or ``'harmonic'``. Geometric mean uses cannot be inferred by this function. :param unit: Unit...
9007d9d05d93240b1b9abdee7f06a4c6883771b8
346,606
def score_illegals(illegals): """ Take a list of illegal closing characters and return a score per the question's criteria """ sum = illegals.count(')') * 3 sum += illegals.count(']') * 57 sum += illegals.count('}') * 1197 sum += illegals.count('>') * 25137 return sum
9e3e6e2556cf252d51ce7199a660514c3442fc1c
239,994
import re def latexify(txt): """ Take some text and replace the logical vocabulary that ttg understands with LaTeX equivalents """ # Use LaTeX symbols as in Forallx (roughly) substitutions = { "not": "\\lnot", "-": "\\lnot", "~": "\\lnot", "or": "\\lor", "no...
6dc8f65e1c57db7dc729b7e4792b080b2836475b
347,065
def isiter(x): """ Returns `True` if the given value implements an valid iterable interface. Arguments: x (mixed): value to check if it is an iterable. Returns: bool """ return hasattr(x, '__iter__') and not isinstance(x, (str, bytes))
6b2e5a6e4d676cf6c749fbac6f1e3ba64057f8e9
633,321
import re def clean_url(url: str) -> str: """Remove zero width spaces, leading/trailing whitespaces, trailing slashes, and URL prefixes from a URL Args: url (str): URL Returns: str: URL without zero width spaces, leading/trailing whitespaces, trailing slashes, and URL prefixes ...
fb25b77524b03b5f34d8e65dde3e59c16b389cc4
159,920
def lerp(a, b, t): """ blend the value from start to end based on the weight :param a: start value :type a: float :param b: end value :type b: float :param t: the weight :type t: float :return: the value in between :rtype: float """ return a * (1 - t) + b * t
127ff551f81423c299e4434841dd141d449d57d1
632,806
def get_header_string(search_category, search_string): """Returns personalized heading text depending on the passed search category.""" header_string = "" csv_title_index = 0; csv_year_index = 1; csv_author_index = 2 if search_category == csv_title_index: header_string = "\n\nResults books with titles containing:...
191291345dd893731e8a683b6907fbe058f6e67f
119,448
def constant(_): """ Returns a constant value for the Scheduler :param _: ignored :return: (float) 1 """ return 1.
a44434c6ef19f93d6217984a9ac34fff323f26b3
288,907
from datetime import datetime def to_datetime(image_time: str, image_date: str) -> datetime: """builds datetime object Args: image_time (:obj:`string`): time when the image was captured image_date (:obj:`string`): date when the image was captured Returns: :obj:`datetime`: contruc...
d77817e2c0a57f316b5034480c8dae844cb285ee
342,749
def find_num_player_in_group(group): """ find the number of players in a group :param group: A Group object :return: number of players in the group """ players = group.players.all() return (len(players))
3a1f470bf64fe9409237da7afe1c0692a7b68d53
639,808
def compare_list_of_committees(committees1, committees2): """ Check whether two lists of committees are equal. The order of candidates and their multiplicities in these lists are ignored. To be precise, two lists are equal if every committee in list1 is contained in list2 and vice versa. Commit...
3d754496aa5fb6bf7c77fc05258ecbff2d7b3f43
536,332
import re def add_css(str): """ Add css span tags to text by replacing strings of form: ":red:`some text`" with "<span class=\"red\">some text</span>" """ css_str = re.sub(r':(\w+):`([^`]+)`', r'<span class="\1">\2</span>', str) return css_str
78745398e0fed89579c7c6dd2a3199917acb4849
184,587
import itertools def one_to_one(graph, nodes): """ Return True if graph contains only one to one mappings. The directed graph should be represented as a dictionary mapping of edges for each node. Nodes should be passed a simple list. """ edges = itertools.chain.from_iterable(graph.values()) ...
d320e1b018b296dc8b6e50e191a75843ea59201e
73,413
def get_first_annotated_frame_index(filename): """ determines the frame index of the first annotated frame. It is based on the timestamps file provided with the annotations of particular recording. This timestamps file provides both the frame index and corresponding timestamp for all images that have been ...
6a3091ea9b39a97777a3f157f35b4673f45984a8
394,014
import base64 def base64_encode(bot, trigger): """Encodes a message into base64.""" if not trigger.group(2): return bot.reply('I need something to encode.') encodedBytes = base64.b64encode(trigger.group(2).encode('utf-8')) encodedStr = str(encodedBytes, 'utf-8') bot.say(encodedStr)
d9d515ee07b5cb48a28cf0196f483f5e69201fc6
616,061
import torch def batch_quadratic_form(x: torch.Tensor, A: torch.Tensor) -> torch.Tensor: """ Compute the quadratic form x^T * A * x for a batched input x. Inspired by https://stackoverflow.com/questions/18541851/calculate-vt-a-v-for-a-matrix-of-vectors-v This is a vectorized implementation of out[i] =...
4e639fc210e944cdc6726c2daab85e486de58134
24,880
def map_compat_fueltech(fueltech: str) -> str: """ Map old opennem fueltechs to new fueltechs """ if fueltech == "brown_coal": return "coal_brown" if fueltech == "black_coal": return "coal_black" if fueltech == "solar": return "solar_utility" if fueltech == "b...
4f7be4496d7c29eb9e9ab8f48ff408f6f4cc7c11
246,473
def average(nums): """Find mean of a list of numbers.""" return sum(nums) / len(nums)
30b1689663d80657c1530cfcd10f6b5dcfdf2de9
601,588
def point_is_in(bbox, point): """ Check whether EPSG:4326 point is in bbox """ # bbox = normalize(bbox)[0] return ( point[0] >= bbox[0] and point[0] <= bbox[2] and point[1] >= bbox[1] and point[1] <= bbox[3] )
ebec8166789aba006089bbd03092de4d9e35ae86
53,530
def confusionMatrix(predicted, actual, threshold): """ 计算数据的混淆矩阵表数值 :param predicted: 实验数据集 :param actual: 真实数据集 :param threshold: 阀值 :return: 数值形式[tp, fn, tp, tn, rate] """ # 检查数据长度,避免无效输入 if len(predicted) != len(actual): return -1 # 定义混淆矩阵的四项指标 tp = 0.0 # 真实例 ...
866360e041f0870b88e53ea2cc6cd2ebdd568d6d
54,648
def acoustic_reflectivity(vp, rho): """ The acoustic reflectivity, given Vp and RHOB logs. Args: vp (ndarray): The P-wave velocity. rho (ndarray): The bulk density. Returns: ndarray: The reflectivity coefficient series. """ upper = vp[:-1] * rho[:-1] lower = vp[1:] * ...
a2c14f2d0573e386b205b23a0c3956b4bf9e0edc
393,771
def ParseList(List): """Parse lists (e.g. 0,1,3-8,9)""" Res = list() if ( str(List).isdigit() ): Res.append(int(List)) else: for Element in List.split(','): if '-' in Element: x1,x2 = Element.split('-') Res.extend(list(range(int(x1), int(x2)+1))) else: Res.append(int(Element)) return Res
2c5c76479538dced1a452e6d1b49a0c76151ef7e
400,001
def _url_joiner(*args): """Helper: construct an url by joining sections with /""" return '/'.join(s.strip('/') for s in args)
b94b25d0f3b5820993f4adc591e5ef257b4371da
664,273
def boldheader(title): """Convert the given string into bold string, prefixed and followed by newlines.""" return "\n\n**%s**\n\n" % str(title).strip()
987a60ed29bc87e04a92ec003f8b67bb50277d52
351,235
def compress_str(s): """ Compress a string by replacing consecutive duplicate characters with a count of the number of characters followed by the character. """ if not s: return s compressed_str = [] count = 1 for i in range(1, len(s)): if s[i] == s[i-1]: coun...
6e7d6da2244eef331b7e4f68cc31c91138dd4801
454,067
import random def yatzy_game(number_of_dice: int = 5): """ Roll the indicated number of 6 sided dice using random number generator :param number_of_dice: integer :return: sorted list Using random.seed to hold randomness result >>> random.seed(1234) >>> yatzy_game(4) [1, 1, 1, 4] ...
32f990cd4a1d39877e2a951e2ec7f0cdeb4d3ff6
152,292
from datetime import datetime def datetime_to_int_seconds(dt_obj): """Converts a datetime object to integer seconds""" epoch_start = datetime(1970, 1, 1) return int((dt_obj - epoch_start).total_seconds())
12d279466cdea5f2fb3a136c9443ebd08d325f67
317,059
import json def get_json_value(value): """ Get value as JSON. If value is not in JSON format return the given value """ try: return json.loads(value) except ValueError: return value
672f8d79aef23ee8f639ce87860029d54bf78ca3
646,487
def step_is_chg_state(step_df, chg): """ Helper function to determine whether a given dataframe corresponding to a single cycle_index/step is charging or discharging, only intended to be used with a dataframe for single step/cycle Args: step_df (pandas.DataFrame): dataframe to determine wh...
0c36cb62528dbea4c1d58085d3f88fba0632bec0
272,028
import hashlib def first_half_of_sha512(*data: bytes) -> bytes: """Returns first 32 bytes of SHA512 hash""" return hashlib.sha512(b''.join(data)).digest()[:32]
c4f9b7768b35c29d668f60319dab17455b001f7d
489,598
import torch def calculate_blend_weights(t_values: torch.Tensor, opacity: torch.Tensor) -> torch.Tensor: """Calculates blend weights for a ray. Args: t_values (torch.Tensor): A (num_rays,num_samples) tensor of t values opacity (torch.Tensor): A (num_rays,num_sample...
23356725fcc805c9d3805eba9fd2dd22a43a1dc1
524,720
def post_list_mentions(db, usernick, limit=50): """Return a list of posts that mention usernick, ordered by date db is a database connection (as returned by COMP249Db()) return at most limit posts (default 50) Returns a list of tuples (id, timestamp, usernick, avatar, content) """ list = [] ...
1b50f9199b946ff9013d86ff504aa42f01680e7b
48,669
import itertools def all_pairs(args): """ Generate all pairs from the list of lists args. (stolen from cmppy/globalconstraints.py) """ return list(itertools.combinations(args, 2))
ba19d08e7c0342b0a75126e2cfff19c50cea4c53
369,433
from typing import List from typing import Dict def idx(words: List[str]) -> Dict: """Create a mapping from words to indexes Args: words: List of words Returns: w2i: Dict mapping words from their index Raises: """ w2i = {} for i, w in enumerate(words): if w not in ...
173ff21b8c56dd67d38af216ac4481bc455bf397
90,801
import struct import binascii def make_chunk(chunk_type, chunk_data): """Create a raw chunk by composing chunk type and data. It calculates chunk length and CRC for you. :arg str chunk_type: PNG chunk type. :arg bytes chunk_data: PNG chunk data, **excluding chunk length, type, and CRC**. :rtype: bytes """ out...
19843007bdde2b74182c80a6b03404db131735f8
624,834
def map_values(function, dictionary): """ Transform each value using the given function. Return a new dict with transformed values. :param function: keys map function :param dictionary: dictionary to mapping :return: dict with changed values """ return {key: function(value) for key, value ...
7073f63e98f3b5e2a44bf76d74a40d08293f1a1d
646,760
import requests def _get_linecount(fpath, keyword, delimiter=',', encoding='ISO-8859-1'): """ Return the line number in a file where the first item is `keyword`. If there is no such line, it will return the total number of lines in the file. :param fpath: A path or url for the file (if a ur...
6935d5fd121e51ae2a3195e3f06c8afe0920477e
492,348
def resource_id(source_id: str, checksum: str, output_format: str) -> str: """Get the resource ID for an endpoint.""" return f"{source_id}/{checksum}/{output_format}"
0e14b52b7dd2d4da6a4027b639ed273ef1c35e20
62,180
def build_empty_bbox_mask(bboxes): """ Generate a mask, 0 means empty bbox, 1 means non-empty bbox. :param bboxes: list[list] bboxes list :return: flag matrix. """ flag = [1 for _ in range(len(bboxes))] for i, bbox in enumerate(bboxes): # empty bbox coord in label files if bb...
d42abdc68391cb27a2306ae8ed8ff3ab09977b04
320,109