content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def collatz_function(n): """ This function, collatz function, takes a number n and the entire part on the division with 2 if n is even or 3*n+1 is n is odd. """ if n % 2 == 0: return n//2 else: return 3*n+1
bd9b061e9651e46e4c6efd3f6e45524d824040ff
6,855
def has_enabled_clear_method(store): """Returns True iff obj has a clear method that is enabled (i.e. not disabled)""" return hasattr(store, 'clear') and ( # has a clear method... not hasattr(store.clear, 'disabled') # that doesn't have a disabled attribute or not store.clear.disabled )
28ee30f92d44d14300e30fec0de37a2a241c8e92
6,856
import argparse def _parser(): """Take care of all the argparse stuff. :returns: the args """ parser = argparse.ArgumentParser(description="Arxiv Text-To-Speach") parser.add_argument('arxivID', help='Arxiv Identifier') parser.add_argument('-o', '--output', default=False, ...
43b5e7f52751e889d664ca7ba1cc6c493c24d5d8
6,857
import torch def coin_flip(prob): """ Return the outcome of a biased coin flip. Args: prob: the probability of True. Returns: bool """ return prob > 0 and torch.rand(1).item() < prob
672929fb49a0e65101a4bdfdd13e981ae5eae31c
6,858
def to_pass(line): """ Replace a line of code with a pass statement, with the correct number of leading spaces Arguments ---------- line : str, line of code Returns ---------- passed : str, line of code with same leading spaces but code replaced with pass statemen...
f8444ecc38523aaef13d535258974881956e30b9
6,860
import numpy def reverse_sort_C(C, sorted_index): """ Perform the reverse of sort described in sort_by_sorted_index, on rows in a numpy array. Args: C (numpy.array): array with C.shape[0] = len(sorted_index) sorted_index (list of ints): desired order for rows of C """ m,n = C.shape C_new = numpy.zeros(C.s...
a0865dba6479104bb1442ea185ec7913ed8cb53c
6,861
import itertools def string_permutations(test_list, list_to_permutate): """Takes a list and a set, and returns a list of all the permutations as strings""" str_perms = [list(permutation) for permutation in itertools.permutations(list_to_permutate)] return [str(test_list + str_perm) for str_perm in str_pe...
b4cee2f34e0382a7cd2b49f5b5f22bc85712731a
6,862
def broadcastable_to_str(b): """Return string representation of broadcastable.""" named_broadcastable = { (): "scalar", (False,): "vector", (False, True): "col", (True, False): "row", (False, False): "matrix", } if b in named_broadcastable: bcast = named_b...
35dbe968a8341d076a264333c68fb597212439bc
6,863
def partition(sort_list, low, high): """ All the elements smaller than the pivot will be on the left side of the list and all the elements on the right side will be greater than the pivot. """ i = (low - 1) pivot = sort_list[high] for j in range(low, high): if sort_list[j] ...
3ae3a569fc5c3968ae047bf20df7a7a59bdfb0cf
6,865
def New_Dataframe(old_df,indicator_name): """ create a new dataframe that is composed of only one indicator Args: old_df (dataframe): general dataframe from which we extract the new one indicator_name (string): Name onf the indicator that will composed the new dataframe Re...
5ccd394a01a70b39b64d2a12ed0aac6f39296a0a
6,866
def check_args(args): """ Checks validity of command line arguments and, in some cases modifies them a little bit. :param args: The command-line arguments. :type args: argparse.ArgumentParser Namespace :returns: argparse.ArgumentParser Namespace -- The updated command-line argumen...
04270a50fce1003ee3960576b60bdcdc21f69767
6,868
from pathlib import Path def check_path_in_dir(file_path, directory_path): """ Check if a file path is in a directory :param file_path: Full path to a file :param directory_path: Full path to a directory the file may be in :return: True if the file is in the directory """ directory = Path(...
5e96abd89c72ea39a944e75b4548fc20b67892cd
6,871
def flat_out(f, *a, **kw): """Flatten the output of target function.""" return f(*a, **kw).flatten()
ffe09ffbaae93657fde818de8a03cc17fee962f1
6,873
import argparse def _parser(): """Take care of all the argparse stuff. :returns: the args """ parser = argparse.ArgumentParser( description='Interactively normalize fits spectra.') parser.add_argument("fitsname", type=str, help="Specturm to continuum normalize.") ...
ef5b682909925ef95f7d1388f8c28e1bd8d27027
6,874
import sys def get_error_hint(ctx, opts, exc): """Get a hint to show to the user (if any).""" module = sys.modules[__name__] get_specific_error_hint = ( getattr(module, 'get_%s_error_hint' % exc.status, None)) if get_specific_error_hint: return get_specific_error_hint(ctx, opts, exc) ...
5dad7b9a0c35170ae83efcbc076b2b9f4b3dd1d8
6,875
def get_relation(filename): """read relation file, return rel2idx""" rel2idx = {} f = open(filename, 'r') lines = f.readlines() for (n, rel) in enumerate(lines): rel = rel.strip().lower() rel2idx[rel] = n f.close() return rel2idx
1c239ec3343cf63e502bf9de485171c9a346e240
6,876
def id_for_base(val): """Return an id for a param set.""" if val is None: return "No base params" if "editor-command" in val: return "Long base params" if "ecmd" in val: return "Short base params" return "Unknown base params"
ecf54fa40195ba4de7db13874e44388a04527bed
6,877
def serialize_serializable(obj, spec, ctx): """ Serialize any class that defines a ``serialize`` method. """ return obj.serafin_serialize(spec, ctx)
936c3b51257c60c156cd9686e38b09ec55a929f2
6,878
def parse_labels_mapping(s): """ Parse the mapping between a label type and it's feature map. For instance: '0;1;2;3' -> [0, 1, 2, 3] '0+2;3' -> [0, None, 0, 1] '3;0+2;1' -> [1, 2, 1, 0] """ if len(s) > 0: split = [[int(y) for y in x.split('+')] for x in s.split(';')] e...
d2f77876f1759e6d4093afc720e7631f1b4d9ff4
6,879
from typing import Any import dataclasses def _is_nested(x: Any) -> bool: """Returns whether a value is nested.""" return isinstance(x, dict) or dataclasses.is_dataclass(x)
798000adfd8eb900b61be988ab6a31e1b062540d
6,880
def contains_pept(name): """Checks if the saccharide name contains the peptide fragment, such as EES, GS, SA etc""" contains_pept = False for pept_stub_name in ('_E', '_G', '_S', '_A'): if (pept_stub_name in name) and ('_NRE' not in name): contains_pept = True return contains...
937679a96b21766e96eb455baca51c1695412287
6,881
import torch def check_stacked_complex(data: torch.Tensor) -> torch.Tensor: """ Check if tensor is stacked complex (real & imag parts stacked along last dim) and convert it to a combined complex tensor. Args: data: A complex valued tensor, where the size of the final dimension might be 2. ...
afce7ac1840ff64199c9ebc9f4222e1d3f09dafd
6,882
def circle(x, y, a, b, width): """ widthで指定された直径の中に含まれているかを判定 :param x: :param y: :param a: :param b: :param width: :return: """ _x = round(((x - a) ** 2), 3) _y = round(((y - b) ** 2), 3) _r = round(((width/2) ** 2), 3) if (_x + _y) <= _r: return _r - (_x + _...
fabddad9e3c404dc36e1cf1830ebcc107cf66516
6,883
def demo__google_result_open_in_new_tab(raw_text, content_mime): """Force google search's result to open in new tab. to avoid iframe problem 在新标签页中打开google搜索结果 """ def hexlify_to_json(ascii_str): _buff = '' for char in ascii_str: if char in '\'\"<>&=': _buff ...
9e11f59ab66d037887c60fa0e5b636af2c5fc0c8
6,886
def iterations_for_terms(terms): """ Parameters ---------- terms : int Number of terms in the singular value expansion. Returns ------- Int The number of iterations of the power method needed to produce reasonably good image qualit for the given number of terms in th...
4142d8325f132e16e0525c36d114dd989873870f
6,887
def get_leaf_nodes(struct): """ Get the list of leaf nodes. """ leaf_list = [] for idx, node in enumerate(struct): if node['is_leaf']: leaf_list.append(idx) return leaf_list
90c66e49bac0c49ef5d2c75b4c1cbe6f4fdd4b83
6,888
def get_node_edge(docs, w2d_score, d2d_score): """ :param docs: :param w2d_score: :param d2d_score: :return: """ wid2wnid = {} w_id, d_idx = [], [] w_d_wnid, w_d_dnid = [], [] w_d_feat = {"score": [], 'dtype': []} d_d_dnid1, d_d_dnid2 = [], [] d_d_feat = {"score": [], '...
40e4d0a11fdd671971319ae8d463ad94a7e3ca9a
6,889
def _get_dir_list(names): """This function obtains a list of all "named"-directory [name1-yes_name2-no, name1-no_name2-yes, etc] The list's building occurs dynamically, depending on your list of names (and its order) in config.yaml. The entire algorithm is described in "img" in the root directory and in th...
284c328878c2c8d0e0ae273c140798e2884ef13f
6,890
def mapCardToImagePath(card): """ Given a card, return the relative path to its image """ if card == "01c": return 'src/imgs/2C.png' if card == "02c": return 'src/imgs/3C.png' if card == "03c": return 'src/imgs/4C.png' if card == "04c": return 'src/imgs/5C.png...
f2a8d4918b26617335a274a536a0569c845cb526
6,891
def consolidate_gauge(df): """ takes in gauge columns and normalizes them all to stiches per inch """ try: df['gauge_per_inch'] = df.loc[:,'gauge']/df.loc[:,'gauge_divisor'] except: print("Error occured when consolidating gauge") return df
a3a1eecec97b521c19bc50f2d1496f1aba9fbce6
6,892
import time def parse_data(driver): """Return a float of the current price given the driver open to the TMX page of the specific symbol.""" # The driver needs time to load the page before it can be parsed. time.sleep(5) content_obj = driver.find_element(by="id", value="root") content_text = conten...
289a71909753278336c414a0b3c3854aeb60b05f
6,893
def add_shift_steps_unbalanced( im_label_list_all, shift_step=0): """ Appends a fixed shift step to each large image (ROI) Args: im_label_list_all - list of tuples of [(impath, lblpath),] Returns: im_label_list_all but with an added element to each tuple (shift step) """ ...
63fc45bc14e54ec5af473ec955bd45602f3c7041
6,894
def are_aabb_colliding(a, b): """ Return True if given AABB are colliding. :param AABBCollider a: AABB a :param AABBCollider b: AABB b :return: True if AABB are colliding :rtype bool: """ a_min = [a.center[i] - a.size3[i] / 2 for i in range(3)] a_max = [a.center[i] + a.size3[i] / 2 for i in range(3)] b_min ...
e4d3174cbde1bcffb8e43a710ad2434fb9e4e783
6,895
def aic(X, k, likelihood_func): """Akaike information criterion. Args: X (np.ndarray): Data to fit on. k (int): Free parameters. likelihood_func (function): Log likelihood function that takes X as input. """ return 2 * k - 2 * likelihood_func(X)
18ec376d15bdb8190818730b4676febdc01bd476
6,897
def construct_policy( bucket_name: str, home_directory: str, ): """ Create the user-specific IAM policy. Docs: https://docs.aws.amazon.com/transfer/latest/userguide/ custom-identity-provider-users.html#authentication-api-method """ return { 'Version': '2012-10-17', 'Stat...
650459810d01b28cc82d320a3b42592d3bb51170
6,898
def cleanup(sender=None, dictionary=None): """Perform a platform-specific cleanup after the test.""" return True
655a4f7192d36aa9b73eca40e587eefd3e37f65d
6,901
def find_n_max_vals(list_, num): """Function searches the num-biggest values of a given list of numbers. Returns the num maximas list and the index list wrapped up in a list. """ li_ = list_.copy() max_vals = [] #the values max_ind = []# the index of the value, can be used to get the param w...
48e274a2e2feac04b285b883ce5948c8f39caff3
6,903
import subprocess def runGodot(command_args): """Runs godot with the command args given (a list) Returns a string of the output or None""" try: byte_string = subprocess.check_output(command_args, stderr=subprocess.STDOUT) except subprocess.CalledProcessError: return # convert to a string and return retu...
1056bb8a9c898cad269318e68ca2b0d948901fd7
6,904
import json import requests def get_lol_version(): """ Get current League of Legends version """ versions = json.loads(requests.get( "https://ddragon.leagueoflegends.com/api/versions.json").text) # reformats from 10.14.5 to 10.14 latest = ".".join(versions[0].split(".")[:2]) return latest
2702b3375cee503cea561f2965bbafdb17a3f232
6,906
def is_same_float(a, b, tolerance=1e-09): """Return true if the two floats numbers (a,b) are almost equal.""" abs_diff = abs(a - b) return abs_diff < tolerance
a8c10ae330db1c091253bba162f124b10789ba13
6,908
import subprocess import shlex import json def ffprobe_json(media_file): """Uses ffprobe to extract media information returning json format. Arguments: media_file: media file to be probed. Returns: json output of media information. return code indicating process result. """ ...
7c13366b31de40aacae561442030d5eb0687246e
6,910
def _mp_fabber_options(wsp): """ :return: General Fabber options for multiphase decoding """ # General options. note that the phase is always PSP number 1 options = { "method" : "vb", "noise" : "white", "model" : "asl_multiphase", "data" : wsp.asldata, "mask" ...
af1c724bd9b88a0d76e7c7d18a3fa2b19591984e
6,911
def default_cfg(): """ Set parameter defaults. """ # Simulation specification cfg_spec = dict( nfreq=20, start_freq=1.e8, bandwidth=0.2e8, start_time=2458902.33333, integration_time=40., ntimes=4...
0b76e2166ce17d6ab42e4f72d7003ba6c03b11f6
6,912
def getTail(compiler,version): """ Function which generates the Tail of a Compiler module file. @input compiler :: compiler name ('intel','pgi',..) @input version :: version of the compiler @return :: list of Lua lines """ strA = 'local version = "{0}"'.format(version) ...
46df63461d05b26fbc5e5a45e6162a2794f92ed1
6,913
import curses def new_border_and_win(ws): """ Returns two curses windows, one serving as the border, the other as the inside from these *_FRAME tuples above. """ return ( curses.newwin(ws[1][1], ws[1][0], ws[0][1], ws[0][0]), curses.newwin(ws[1][1] - 2, ws[1][0] - 2, ws[0][1] + 1, ws[0][0] + 1), )
cec302bda38ba5fa9d0c88dbfac1c501984a96a0
6,915
import socket def mk_sock(mcast_host, mcast_ip, mcast_port): """ multicast socket setup """ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.setsockopt( socket.IPPROTO_IP, socket.IP_ADD_M...
702a95e5baec4ecf54206f8f16cfa22d8365f8a0
6,917
def cmd(command_id): """ A helper function for identifying command functions """ def decorator(func): func.__COMMAND_ID__ = command_id return func return decorator
cff8664ad18c78629bb3c1b4946be592142711e0
6,918
def xover_selection(snakes, survivors, opts, num_survivors): """ Picks parents from the current generation of snakes for crossover params: snakes: list, current generation of snakes of class Snake survivors: list, snakes of class Snake that survived opts: dict, contains hyperparamters ...
990e65aac637abe8c4c6c8a661f4a039b0900ca4
6,919
def interleave_value(t0,series,begin=False,end=False): """Add t0 between every element of *series*""" T = [] if begin: T += [t0] if len(series) > 0: T += [series[0]] for t in series[1:]: T += [t0,t] if end: T += [t0] return T
33e3d8562a482e897bb3fd8d49f33a1dfed9bfb9
6,920
def menu(): """Menu grafico testuale per programma di gestione Immobili """ x = 1 while x !=0 : print (" Menu'") print(" Gestione Immobiliare") print(" INSERIMENTO IMMOBILE .........digita 1 --> ") print(" MODIFICA IMMOBILE .........digita 2 --> ") print(" CAN...
bfb16f3a50339b6e9ed672e1002e727b10f7cc39
6,921
def sort(request): """ Valid values for the 'sort' parameter used in the Index setops methods (intersection, union, etc.) Caution: Don't confuse this one with the "sort" fixture used for DataFrame.append or concat. That one has parameters [True, False]. We can't combine...
0f1e7bb570b6f8f617a7564695c1a20d71cfbe80
6,923
import json def credentials_from_file(file): """Load credentials corresponding to an evaluation from file""" with open(file) as file: return json.load(file)
8f73c595b4e61757ae454b1674a7177ab4d05059
6,924
import requests def get_workspace_vars(auth, workspace_id): """ Function to get variables created in a workspace """ headers = {"Content-Type": "application/json"} url = f"https://intersight.com/tfc/api/v2/workspaces/{workspace_id}/vars" response = requests.get(url, headers=headers, auth=auth)...
ed05bc7fee86d0303e25fe6ea0b0fd898a08e347
6,925
def format_date(value, format='%Y-%m-%d'): """Returns a formatted time string :param value: The datetime object that should be formatted :param format: How the result should look like. A full list of available directives is here: http://goo.gl/gNxMHE """ return value.strftime(fo...
3f094918610617e644db69415d987fa770a06014
6,926
def DatetimeToWmiTime(dt): """Take a datetime tuple and return it as yyyymmddHHMMSS.mmmmmm+UUU string. Args: dt: A datetime object. Returns: A string in CMI_DATETIME format. http://www.dmtf.org/sites/default/files/standards/documents/DSP0004_2.5.0.pdf """ td = dt.utcoffset() if td: offset =...
706faec64a116ad4dc255b6ff9b87b4a8488bcff
6,928
def set_field_value(context, field_value): """populates variable into a context""" if field_value: context['field_value'] = field_value else: context['field_value'] = '' return ''
68110380f244b78550a04d08ad9bda5df193211e
6,931
def show_books(object_list): """ 加载指定书籍列表的模板。 :param object_list: Book模型实例的列表 :return: 返回一个字典作为模板的上下文 """ if len(object_list) > 0: try: getattr(object_list[0], 'object') except AttributeError: pass else: object_list = map(lambda ele: e...
034707460c73eed6e69578726c860ee55a070ac6
6,932
import re from typing import OrderedDict def parse_dict(s, sep=None): """ parser for (ordered) dicts :s: the input string to parse, which should be of the format key1 := value1, key2 := value2, key3 := value3, ...
dcfdec6dcc68661f5d27f49a280326bec6cfd90b
6,933
def distr_selectbox_names(): """ Accessing stats.name. """ names = ['alpha', 'anglit', 'arcsine', 'argus', 'beta', 'betaprime', 'bradford', 'burr', 'burr12', 'cauchy', ...
5051cab27bf6497d3dfb4d4828daeaeefa528403
6,935
def read_file(filename): """Read filename; return contents as one string.""" with open(filename) as my_file: return my_file.read()
fa4b47085f5d3ace5c011fcda27e6ffa94c7085a
6,936
def say(number): """ print out a number as words in North American English using short scale terms """ number = int(number) if number < 0 or number >= 1e12: raise ValueError if number == 0: return "zero" def quotient_and_remainder(number, divisor): """ retu...
42b8d321c001c60e37f6bbd94bd2a3404ddf5c66
6,937
import re def rm_noise(diff): """Filter out noise from diff text. Args: diff (str): diff text Returns: str: cleaned diff text """ result = diff patterns = ["\n", "\u0020+", "་+?"] for pattern in patterns: noise = re.search(pattern, diff) if noise: ...
8a139f22e30e3c98b1dfef3b47fa623db8b22a29
6,939
import numpy def word2array(ft_names, word): """Converts `word` [[(value, feature),...],...] to a NumPy array Given a word consisting of lists of lists/sets of (value, feature) tuples, return a NumPy array where each row is a segment and each column is a feature. Args: ft_names (list): l...
4305f7b85287f70ffc7cb9ade2c8c2663dc11659
6,941
def external(field): """ Mark a field as external. """ field._external = True return field
83de43305f9655aa2be9c6b7264552bd3e2783f7
6,942
def getExactFreePlaceIndexForCoordinate(freePlaceMap, x, y): """ Returns the Exact Value for a given Coordinate on the FreePlaceMap :param freePlaceMap: The generated FreePlaceMap :param x: The X Coordinate on the FreePlaceMap :param y: The Y Coordinate on the FreePlaceMap :return: The Indexvalu...
4af9dec9163bd505f944f02db55a2dcfa80cb434
6,943
def split_on_text(row): """Spliting original text into million character blocks for Spacy""" val = round(row['original_text_length'] / 1000000) final_texts = [] count = 1000000 counter = 0 for i in range(0, val): if (count + 1000000) > row['original_text_length']: final_texts...
678377650df3ca49cfb0d4404382589e32e3c6ae
6,944
def get_number(number): """ Repeats back a number to you --- operationId: getPetsById parameters: - name: number in: path type: string description: the number responses: 200: description: Hello number! """ return "Hello {}!".format(numbe...
22d6c8a7a5b3a8ff946e4dccaf5876134a0293cd
6,945
def align_frontiers_on_bars(frontiers, bars): """ Aligns the frontiers of segments to the closest bars (in time). The idea is that frontiers generally occurs on downbeats, and that realigning the estimation could improve perfomance for low tolerances scores. Generally used for comparison with techni...
ef1f3d62a36065f64d31c4e4d7f6ce07045e2e5e
6,946
def _high_bit(value): """returns index of highest bit, or -1 if value is zero or negative""" return value.bit_length() - 1
1bd783593ae7d5b15cc56c8a8db5c86798fd8c9f
6,947
def qual(obj): """ Return fully qualified name of a class. """ return u'{}.{}'.format(obj.__class__.__module__, obj.__class__.__name__)
5b9779935b84a8bb3653cc9fc2c627dda5dd0e7f
6,949
def default_reply(event, message): """Default function called to reply to bot commands.""" return event.unotice(message)
3c83d8abaea0f4c968db25fff51185bb6c32d26e
6,950
def making_change(amt: int, coins: list) -> int: """Iterative implementation of the making change algorithm. :param amt (int) : Amount, in cents, to be made into change. :param coins (list) : List of coin denominations :return (int) : Number of different combinations of change. """ # calc[i...
188496f5db4252fa27f153d0a0379031847c669d
6,951
def table_dispatch(kind, table, body): """Call body with table[kind] if it exists. Raise an error otherwise.""" if kind in table: return body(table[kind]) else: raise BaseException, "don't know how to handle a histogram of kind %s" % kind
18d827baeabbca8d27848ea87a067328fe82d16a
6,952
import os def get_testcases(problem): """ Gets testcases for problem, which are then displayed if user is Apprentice. :param problem: id of problem :return: array of testcases """ testcases_dir = os.path.join(os.popen('echo $CG_FILES_TESTCASES').read().strip(), problem) testcases_...
ed6eedac3be57368a79af79692802ebe93d9a5ff
6,953
import base64 def _get_base64(data: str) -> str: """Base 64 encodes data.""" ebytes = base64.b64encode(data.encode("utf-8")) estring = str(ebytes, "utf-8") return estring
a7bd3080dba077077d96602eb35142db32b003de
6,954
def setSortGroups(sortGroups=None): """ Return the sorting groups, either user defined or from the default list """ if sortGroups is None: # Default groups return [('-inf', '+inf'), ('-inf', 100), (101, '+inf')] else: sortGroups.insert(0, ('-inf', '+inf')) return sortGr...
f2e8cff00fe70627e81dcc0ce576f56e4d289228
6,955
def ubuntu_spec(**kwargs): """Ubuntu specs.""" # Setup vars from kwargs builder = kwargs['data']['builder'] builder_spec = kwargs['data']['builder_spec'] distro = kwargs['data']['distro'] version = kwargs['data']['version'] bootstrap_cfg = 'preseed.cfg' # https://github.com/mrlesmithj...
fca2605c5b10f86519ef5ca952ab340e1f5560f2
6,956
import subprocess def run(cmd): """Run a command on the command line.""" proc = subprocess.Popen(['sh', '-c', cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) stdout, stderr = proc.communicate() return proc.ret...
f7978e59044cf7aebc76355536c3e3fa1d08b729
6,958
def NOT_TENSOR_FILTER(arg_value): """Only keeps a value if it is not a Tensor or SparseTensor.""" return not arg_value.is_tensor and not arg_value.is_sparse_tensor
14eb28c1824f58bd7ef6ad1da96922891114fe5a
6,959
def check_if_neighbors_match(src_neighbor, trg_neighbor): """Check if any source and target neighbors match and return matches Args: src_neighbor (list): Source Neighbor List trg_neighbor (list): Target Neighbor List Returns: list: Matching of neighbors. """ matching = {} ...
c4d91ffca1f175e9964ca67c8b2200b1848b56d9
6,960
def tapisize(fieldKeyName): """Transforms a string into a Tapis query parameter """ return fieldKeyName.lower()
cc8032a6cc9e822193430134bb33da8aef74cf06
6,963
def calculate_average_resolution(sizes): """Returns the average dimensions for a list of resolution tuples.""" count = len(sizes) horizontal = sum([x[0] for x in sizes]) / count vertical = sum([x[1] for x in sizes]) / count return (horizontal, vertical)
06dac1834989df96ce7bff88c435dd4067bfccbd
6,964
from pathlib import Path def create_folder(subfolder: str, folder: str) -> None: """ Function for creating folder structure for saved stationdata """ path_to_create = Path(folder, subfolder) Path(path_to_create).mkdir(parents=True, exist_ok=True) return None
e50052d22cb8385e1c3a83caa643ec0d0289d1b0
6,965
def _partition_fold(v,data): """ partition the data ready for cross validation Inputs: v: (int) cross validation parameter, number of cross folds data: (np.array) training data Outputs: list of partitioned indicies """ partition = [] for i in range(v): if i...
fc833b5120c5d8e479af1758f86e0541c5d7d87c
6,966
def get_distance(m, M, Av=0): """ calculate distance [in pc] from extinction-corrected magnitude using the equation: d=10**((m-M+5-Av)/5) Note: m-M=5*log10(d)-5+Av see http://astronomy.swin.edu.au/cosmos/I/Interstellar+Reddening Parameters --------- m : apparent magnitude M : absol...
b4773065d7cf1bc793400ac344c4ca7a580f8567
6,967
import argparse def get_args_parser(PORT: int = 4500): """ Extendable parser for input arguments Args: PORT: default port to be exposed """ parser = argparse.ArgumentParser(add_help=True, description="Backend service API") parser.add_argum...
8fcddec4df5f64c9425a028432ad7c80eae6542f
6,968
import json def load_base_models_json(filename="base_models.json"): """Load base models json to allow selecting pre-trained model. Args: filename (str) - filename for the json file with pre-trained models Returns: base_models - python dict version of JSON key-value pairs """ with...
c17f123e192b94e6f87938bca10822ea785e2d91
6,969
import json def load_data_from_json(jsonfile): """Load the data contained in a .json file and return the corresponding Python object. :param jsonfile: The path to the .json file :type jsonfile: str :rtype: list or dict """ jsondata = open(jsonfile).read() data = json.loads(jsondata) r...
f0f7a0620be8ffcd15a57fd561dda8525866faa3
6,971
def precut(layers, links, all_terms, user_info): """ This function cuts terms in layers if they do not exist inside the accuracy file of model 1. It also cuts all links if one of the terms inside does not exist inside the accuracy file of model 1. Finaly it cuts all terms taht do not exist insid...
cf04eec77d01ad931f7654a3743baaf51aad53fa
6,974
import os def fullPathListDir(dir: str) -> list: """ Return full path of files in provided directory """ return [os.path.join(dir, file) for file in os.listdir(dir)]
b456008e782e6f5a1d3471f5a9b5536ae4aad132
6,975
def _clean_conargs(**conargs): """Clean connection arguments""" conargs['metadata'] = [x.strip() for x in conargs['metadata'].split(',') if x.strip()] return conargs
f5942f750949ab674bd99778e79ea35c2d0bb775
6,976
def get_living_neighbors(i, j, generation): """ returns living neighbors around the cell """ living_neighbors = 0 # count for living neighbors neighbors = [(i-1, j), (i+1, j), (i, j-1), (i, j+1), (i-1, j+1), (i-1, j-1), (i+1, j+1), (i+1, j-1)] for k, l in neighbors: ...
437229b8152c3b2ce5b90ef6ddef83daa5c24a85
6,979
def StrToList(val): """ Takes a string and makes it into a list of ints (<= 8 bits each)""" return [ord(c) for c in val]
79ee38dc4952b677896a77379c3cccca8f74eb2c
6,980
def set(data,c): """ Set Data to a Constant Parameters: * data Array of spectral data. * c Constant to set data to (may be complex) """ data[...,:]=c return data
cff2592b3973bbd3f9a1a4dbaa6d6ba4b99260bc
6,983
from typing import Any from typing import Dict def get_meta(instance: Any) -> Dict[str, Any]: """ Returns object pjrpc metadata. """ return getattr(instance, '__pjrpc_meta__', {})
1357cab8698297b8ba9c10423e4c0473690cb8f0
6,984
def free_residents(residents_prefs_dict, matched_dict): """ In this function, we return a list of resident who do not have empty prefrences list and unmatched with any hospital. """ fr = [] for res in residents_prefs_dict: if residents_prefs_dict[res]: if not (any(res in mat...
b07991f6286be3c0e4b163ca2f0991630f910b4c
6,986
import os import asyncio async def runCmdWithUser(cmd, addToEnv=None) : """Runs a command allowing the users to interact with the command and then returns the return code. Based upon the Python asyncio subprocesses documentation. """ if addToEnv is not None : for aKey, aValue in addToEnv.items() : ...
e3c075c9e6ccd946724921f763bfe240fb40e4fe
6,987
import pickle def load(directory): """Loads pkl file from directory""" with open(directory, 'rb') as f: data = pickle.load(f) return data
d500c6f717535ee95f452abd435be4d8688a59a4
6,988
import numpy def interleave(left, right): """Convert two mono sources into one stereo source.""" return numpy.ravel(numpy.vstack((left, right)), order='F')
29833d8b4516de2bdab9a33246cb165556d287bc
6,989
def get_seconds(time_string): """ Convert e.g. 1m5.928s to seconds """ minutes = float(time_string.split("m")[0]) seconds = float(time_string.split("m")[1].split("s")[0]) return minutes * 60.0 + seconds
5a729d24ab6c437fca536cae8ac3d34a45bb9054
6,990