content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import json def process_row(row, type): """ There are four different file types with different data needed for processing :param row: list csvreader row data :param type: string :return: string json object to be written to queue """ if type == "deletes": return json.dumps({'geoname...
90baf2b434288e69626bed173efbf984eabd9501
33,170
import gc def list_with_attribute(classname, attributename, attributevalue): """Gather all instances in specified class with a particular attribute""" my_list = [] for obj in gc.get_objects(): if isinstance(obj, classname): if getattr(obj, attributename) == attributevalue: ...
91ca3c2104843d78d4b993a702d2db238b027c8b
33,171
import sys def vtkGetTempDir(): """vtkGetTempDir() -- return vtk testing temp dir """ tempIndex=-1; for i in range(0, len(sys.argv)): if sys.argv[i] == '-T' and i < len(sys.argv)-1: tempIndex = i+1 if tempIndex != -1: tempDir = sys.argv[tempIndex] else: tem...
e84a7bc85012b6aea151a56f8c24565c88497285
33,172
def recursive_merge_config_dicts(config, default_config): """ Merge the configuration dictionary with the default configuration dictionary to fill in any missing configuration keys. """ assert isinstance(config, dict) assert isinstance(default_config, dict) for k, v in default_config.items(...
482f0b544a6974a43794ddc0c497f7fc6dea75cb
33,173
import unicodedata def is_fullwidth(char): """Check if a character / grapheme sequence is fullwidth.""" return any( unicodedata.east_asian_width(_c) in ('W', 'F') for _c in char )
2c264f09c5873fc24f31de842a0191b6829997cc
33,174
import torch def stacker(parameters, selector=lambda u: u.values): """ Stacks the parameters and returns a n-tuple containing the mask for each parameter. :param parameters: The parameters :type parameters: tuple[Parameter]|list[Parameter] :param selector: The selector :rtype: torch.Tensor, tu...
07b1d770dbb9c0856a8bdcc9787c85d54a074a6e
33,175
import math def rise_pres(mach: float, beta:float, gamma=1.4) -> float: """ Calculate rise in pressure after oblique shock Parameters ---------- mach:float Mach number beta: float oblique shock angle gamma: float isentropic exponent Returns ------- ma...
0845f9e047b0a372ca5b4fffd96b181d5367c82f
33,176
def insert_into_queue(new_boards, boards_dict={}): """ Insert the boards into a dictionary and return the order in which their keys :param new_boards: list of Board objects :return boards_dict: dictionary of boards with key of the cost :return queue: list of ints. It is the call order of the keys in...
ac857f3eb35ca191489249d08846da52af7e9fcf
33,177
def get_name(soup): """Extract the name from the given tree.""" return soup.find('h2').getText()
46773bb657bffb7624bb82fd43a398f2a72ce24f
33,178
def version_code_table() -> dict[int, tuple[str]]: """A dictionary that contains the code for a specific version. Returns: dict[int, tuple[str]]: A dictionary that contains data in the form (version number: 3-line code tuple) """ table = { 7: ('000010', '011110', '100110'), ...
091685145bb8d7a44ae76c3a2208f29c01581b03
33,179
import os import tempfile def get_transcode_temp_directory(): """Creates temporary folder for transcoding. Its local, in case of farm it is 'local' to the farm machine. Should be much faster, needs to be cleaned up later. """ return os.path.normpath( tempfile.mkdtemp(prefix="op_transcodi...
f6afa621b932e3687205b92bb368a21644bd1f20
33,180
from typing import OrderedDict def process_differential_coordinates(reader): """ Each row is a list of 7 values """ data = OrderedDict() total_rows = 0 for row in reader: total_rows += 1 chromosome_name = row[1] start_position = row[2] end_position = row[3] ...
4ce2744cfb544dbed614c8674581bb4b56ec6e3b
33,182
import ast def build_tree(script): """Builds an AST from a script.""" return ast.parse(script)
a37d24ce3808bfa0af3a5e8e4c1fb8a2d281625e
33,184
import requests def get_url_pages(): """ Takes a URL from SWAPI and then return all the pages related to that category. They will be stored on a list. """ url = "https://swapi.co/api/people/" pages_url = [] while True: pages_url.append(url) r = ...
75ee1d49dfbc8117c7e2e761569094a88e13d108
33,185
def get_maxima(spectrum): """ Crude function that returns maxima in the spectrum. :param spectrum: tuple of frequency, intensity arrays :return: a list of (frequency, intensity) tuples for individual maxima. """ res = [] for n, val in enumerate(spectrum[1][1:-2]): index = n+1 # star...
d8fec410b4a959c27ab03d7540790b85a5a1766b
33,186
def indent(text, indent): """Indent Text. Args: text(str): body of text indent(str): characters with which to indent Returns: text indeneted with given characters """ if '\n' not in text: return "%s%s" % (indent, text) else: text = text.splitlines(True) ...
225575457fe308e3462c0e87181eb88a6e4da939
33,187
def distance_from_root_v1(root, key, distance=0): """ Distance from root is same as the level at which key is present. :param root: :param key: :param distance: :return: """ if root == None: return -1 if root.key == key: return distance else: ld = distanc...
ca68e4d56379d57171ca7a7e3abe073f28666d02
33,188
def create_view(klass): """ This is the generator function for your view. Simply pass it the class of your view implementation (ideally a subclass of BaseView or at least duck-type-compatible) and it will give you a function that you can add to your urlconf. """ def _func(request, *args, **...
aebdc98483f19e64fd71952b93f945d277a6c16b
33,189
def ukr_E(X, B): """UKR reconstruction error.""" E = ((X - B.T.dot(X))**2).sum() / B.shape[0] # (Frobenius norm)^2 return E
bd807018e162bdbb99cfe3d297daa0b5272aefa2
33,190
import sys def connectBodyWithJoint(model, parentFrame, childFrame, jointName, jointType): """Connect a childFrame on a Body to a parentFrame (on another Body or Ground) in the model using a Joint of the specified type. Arguments: model: model to be modified. parentFrame: the Body (or affixed offset) to be con...
6c1316e32e1f37d721aa2680b8fee8725f729ea4
33,192
def min_dist(q, dist): """ Returns the node with the smallest distance in q. Implemented to keep the main algorithm clean. """ min_node = None for node in q: if min_node == None: min_node = node elif dist[node] < dist[min_node]: min_node = node return...
99c4e868748598a44f79ee3cb876d7ebc3abae08
33,193
def _should_profile_development_default(): """Default to enabling in development if this function isn't overridden. Can be overridden in appengine_config.py""" return True
01b72de25feff42c0cfd6c474296ca339745727d
33,194
def filter_localization_probability(df, threshold=0.75): """ Remove rows with a localization probability below 0.75 Return a ``DataFrame`` where the rows with a value < `threshold` (default 0.75) in column 'Localization prob' are removed. Filters data to remove poorly localized peptides (non Class-I by...
7036c730db4c0a649aa25bcf59a962f89ce2710c
33,195
def mean_riders_for_max_station(ridership): """ Fill in this function to find the station with the maximum riders on the first day, then return the mean riders per day for that station. Also return the mean ridership overall for comparsion. Hint: NumPy's argmax() function might be useful: http:...
936f6a8f7ac2c1cebc1c53516963253c9c51ee29
33,196
def _read_first_line(file_path): """ Returns the first line of a file. """ with open(file_path, 'r') as file_: first_line = file_.readline().strip() return first_line
035f22e1e35aa2f945d6ee6d8435d44fee17cc01
33,197
def _month_year_to_tuple(month_year: str) -> tuple[int, int]: # Month, Year """ Parses user-preferred combination of Month/Year string and returns tuple :param month_year: string Month/Year combination space separated (i.e. 10 2021) :return: tuple[int, int] Month, Year """ m, y = month_year.spl...
202d7863767374fc043204be4588443f6296d3e9
33,198
from typing import Optional from typing import Dict def _create_param_name_prefix(enclosing_param_name: Optional[str], prefix_dictionary: Optional[Dict]) -> str: """ Create a param name variant to de-conflict conflicting params :param enclosing_param_name: The name of the en...
68b179bbea40dc044d949eee5067f64250005392
33,199
import os def fetch_genomes(target_genus_species, db_base=None): """ Use rsync to manage periodic updates Examples: >>> fetch_genomes("Escherichia coli") >>> >>> fetch_genomes("Klebsiella pneumoniae", "/home/me/dbs/") :param target_genus_species: the genus species as a string ...
1bf00a478856d706126e58fccc70a7e7533d216c
33,200
import os import logging def get_logger(name): """ Special get_logger. Typically name is the name of the application using Balsa. :param name: name of the logger to get, which is usually the application name. Optionally it can be a python file name or path (e.g. __file__). :return: the logger for...
387e8ad50beb329f43b78121a197b8a600580a09
33,203
def _parse_cubehelix_args(argstr): """Turn stringified cubehelix params into args/kwargs.""" if argstr.startswith("ch:"): argstr = argstr[3:] if argstr.endswith("_r"): reverse = True argstr = argstr[:-2] else: reverse = False if not argstr: return [], {"rev...
a7c7405a3a668e6b7925aa02a1fafc9e5e774f41
33,204
import re def rm_custom_emoji(text): """ 絵文字IDは読み上げないようにする :param text: オリジナルのテキスト :return: 絵文字IDを除去したテキスト """ pattern = r'<:[a-zA-Z0-9_]+?:>' return re.sub(pattern, '', text)
ac0a1cfb59868c6bcd96541f5bcc75de966d8a93
33,206
def open_views_for_file(window, file_name): """Return all views for the given file name.""" view = window.find_open_file(file_name) if view is None: return [] return [v for v in window.views() if v.buffer_id() == view.buffer_id()]
d265e42b99b38606646e0f87b456c8b44d6fcb8c
33,207
def get_bond_type_counts(bond_types): """ Returns a count on the number of bonds of each type. """ count = {} for bt in bond_types: if bt in count.keys(): count[bt] += 1 else: count[bt] = 1 return count
80835f800de7e7cb59f8c0dd05779ef7fab6eba6
33,211
def encoded_capacity(wmb, data, num_bits): """ Returns the total capacity in bits of the bitmask + data :param wmb: weight mask bits -- bit vectors to indicate non-zero values in original weight matrix M :param data: Data corresponding to the non-zero elements of matrix M :param num_bits: number of bits pe...
08442eb84c303962ea538995c6920842aa4ff1b3
33,213
def raise_power(num, pow): """Raise the number to the given power""" # Negative powers are 1 over the positive version if pow < 0: result = raise_power(num, -pow) return 1 / result # Base cases if pow == 0: return 1 if pow == 1: return num # Recurse and mult...
038efd037e19fa22149d866beccc0b4bdd27d448
33,214
def partition_train_validation_test(data): """ Partition a dataset into a training set, a validation set and a testing set :param data: input dataset :return: training, validation and testing set """ # 60% : modulus is 0, 1, 2, 3, 4, or 5 data_train = [item for item in data if item['hash'] %...
4defd18e0dc5ddeb7309b274b707676516901acb
33,218
import os import requests def weather(): """Returns weather in Zagazig, Egypt""" location_key = 127335 # Zagazig location key url = f"http://dataservice.accuweather.com/forecasts/v1/hourly/1hour/{location_key}" parameters = {"apikey": os.environ.get("ACCUWEATHER"), "metric": True} data = requests...
042fa1b613b19f4273721c8f6c9ade7f28c7a401
33,219
def remove_key_values(dictionary, keys=['self', '__class__']): """ Removes key values from dictionary """ new_dict = dictionary for key in keys: del new_dict[key] return new_dict
3e0ed376bb4b00623ffabd2c0fc107d5409b6ef1
33,220
def solution(n: int = 600851475143) -> int: """ Returns the largest prime factor of a given number n. >>> solution(13195) 29 >>> solution(10) 5 >>> solution(17) 17 >>> solution(3.4) 3 >>> solution(0) Traceback (most recent call last): ... ValueError: Paramete...
2c081a09422ef35c81a6173df6e5cf032cf425e1
33,221
def interpolate_line(x1, y1, x2, y2): """ This functions accepts two points (passed in as four arguments) and returns the function of the line which passes through the points. Args: x1 (float): x-value of point 1 y1 (float): y-value of point 1 x2 (float): x-value of point 2 ...
71b26e50fb21f22333df7b20ddacf7bc376789cc
33,222
def dir_names(dirrepo, panel_id): """Defines structure of subdirectories in calibration repository. """ dir_panel = '%s/%s' % (dirrepo, panel_id) dir_offset = '%s/offset' % dir_panel dir_peds = '%s/pedestals' % dir_panel dir_plots = '%s/plots' % dir_panel dir_work = '%s/work' ...
fee6d54795593af4e84497310aae5549d2579c68
33,223
import argparse def arg_parsing(): """ Parses keyword arguments from the command line to customise the training process. returns: Namespace with various strings, ints, floats and bools. """ # Create parser parser = argparse.ArgumentParser(description="Neural Network Settings") ...
f2bccafa9bbc5c451d546c6e49ce3eaca2a025e4
33,224
import os def get_fileset(path): """ Construieste lista de fisiere din directorul dat si din subdirectoare, cu data ultimei moficari """ fileset = dict() for root, _, files in list(os.walk(path)): if not os.path.islink(root): for fname in files: cfil = os.path.j...
9f979743476e7d880788b59da3464a365729d9c9
33,225
def nth_even(n): """get's the nth even number.""" even_numbers = [] m = 0 while len(even_numbers) != n: even_numbers.append(m) m += 2 return even_numbers[-1]
0d06509e8ac6696b745bf2fd48bd21c92498a124
33,226
def is_sequence(item): """Whether input item is a tuple or list.""" return isinstance(item, (list, tuple))
f00d191f68994043dbab0c483a8af58d102a2a11
33,227
def gamma_update(tau, delta=1): """ VBEM update of the parameter of the variational Dirichlet distribution""" return delta + tau.sum(axis=0)
4e430bce68f3aa08fc1d7074e2a59c53378410ed
33,228
from typing import Any from typing import Mapping def value_in_context(value: Any, context: Mapping) -> Any: """Evaluate something in the context of an object being constructed.""" try: return value.evaluate_in(context) except AttributeError: return value
e8037a1d23b266ac02125f2b25fc4dbbf059b3b5
33,229
def remove_at(bar, pos): """Remove the NoteContainer after pos in the Bar.""" for i in range(len(bar) - pos): bar.remove_last_entry() return bar
3814c2d825d5aca8815e62e398a940149f287835
33,230
def calc_gof(resdf, simvar, datavar): """Calculate goodness-of-fit measures for given sim & data vars""" resdf.loc['error'] = abs(resdf.loc[simvar] - resdf.loc[datavar]) maeom = resdf.loc['error'].mean()/resdf.loc[datavar].mean() mape = (resdf.loc['error']/resdf.loc[datavar]).mean() r2 = (resdf.loc[...
bf7f290fb6012b09df56c12d137db8914c75a253
33,232
import argparse def get_input_args_predict(): """ INPUTS: None OUTPUT: parse_args(): a data structure that stores the command line arguments object for the predict script """ # Creates the parser parser = argparse.ArgumentParser() # We create 5 command lines argument, to cover a...
95a5ffad24f909ad5ce3ea66ea77436b70cca9b8
33,233
def fc_params(in_features: int, out_features: int, bias: bool = True): """ Return the number of parameters in a linear layer. Args: in_features: Size of input vector. out_features: Size of output vector. bias: If true count bias too. Returns: The number of parameters. ...
0138ae52f101975aba2fd6f38452471a09a2c8e1
33,234
def schedule_extraction(informations): """ 今月の予定情報(bs4.element.Tag)が入ったlistをぶち込むと {2('date'): {'date': 2, 'yobi': '土曜日', 'yotei': [{'text': '🎍《22:00》朝までバンドリ!TV 2021', 'url_link': 'https://bang-dream.com/news/1095'}, {'text': '📻【第14回】Afterglowの夕焼けSTUDIO+', 'url_link': '...
d14d62168295d47f3eaca02ad431e74fcec91d52
33,236
def _to_float(maybe_float): """Safe cast to float.""" try: return float(maybe_float) except ValueError: return maybe_float
fa46e030d83dd879b09949d310092cca3c75abca
33,237
def get_fuel_cost_part2(x1, x2): """Get the fuel that would cost move from x1 to x2, when: Moving from each change of 1 step in horizontal position costs 1 more unit of fuel than the last. This can be easily computed as a triangular number/binomial coefficient. """ steps = abs(x1-x2) return ste...
16a975c6ba9bcc9af9a85c857d86e7436b80863b
33,238
def get_sim_num(): """ Get number of simulations to run and validates input. :return: none """ while True: simulations = input('Type the number of simulations you want ' 'to run.\nThe higher the number, the more ' 'accurate the numbers ...
2ce3addfdd44a765131474275848b63732a2916c
33,239
def azimu_half(degrees: float) -> float: """ Transform azimuth from 180-360 range to range 0-180. :param degrees: Degrees in range 0 - 360 :return: Degrees in range 0 - 180 """ if degrees >= 180: degrees = degrees - 180 return degrees
068f1e059a64f0070d927cee05777a15bc22b01a
33,240
import threading import os def _temp_file_name(): """Construct a temporary file name for each thread.""" f_name = 'local-{}.temp'.format(threading.get_ident()) return os.path.join(os.path.sep, 'tmp', f_name)
6ce8b62ad90702eadd95501d49f36c385827842e
33,241
def join_data(data1, data2, f): """Simple use of numpy functions vstack and hstack even if data not a tuple Args: data1 (arr): array or None to be in front of data2 (arr): tuple of arrays to join to data1 f: vstack or hstack from numpy Returns: Joined data with provided met...
d823e4751ded4f2c5ad3c174034d3260503fa841
33,242
def get_stack_name(environment, service_name): """ This should be what ef-open templates call "ENV", that is, the short name for the environment. """ environment = environment.split('.', 1)[0] return '{}-{}'.format(environment, service_name)
4704aae7b9f4ae7fb69b6dac161c3bf8d7f44723
33,243
def crit(evals, atol=1e-2): """Keep the non-zero eigenvalues. Assumes eigenvalues to be sorted in ascending order. Args: evals (torch.Tensor): Eigenvalues. atol (float): Cutoff value. Smaller evals will not be considered. Returns: [int]: Indices of non-zero eigenvalues. ""...
cb30ad8b3bdbfa83aae9c8445cf11f357e96ef2e
33,244
def askNbPlayer(): """ask for the number of player Returns: number: the number of player 1(IA) or 2 """ nb = 0 try: userResponse = input("Combien de joueur 1 ou 2: ") nbPlayer = int(userResponse) if not (0 < nbPlayer <= 2): raise(ValueError('wrong number'...
7a09e85c58404d86c59a651b66cff98b62a4a00a
33,245
import torch def update_affine_param( cur_af, last_af): # A2(A1*x+b1) + b2 = A2A1*x + A2*b1+b2 """ update the current affine parameter A2 based on last affine parameter A1 A2(A1*x+b1) + b2 = A2A1*x + A2*b1+b2, results in the composed affine parameter A3=(A2A1, A2*b1+b2) :param cur_af: curren...
e9a5127ebec4cb404b419446a17b8e949a4d8c04
33,246
def is_empty(list): """Determine if empty.""" return not list
9659f43b2724c1e0f3186be8229e903f3f4fec3c
33,247
import math def perfect_square(N): """ Helper function to check whether a number is a perfect square :return: True if number is a perfect square, False otherwise :rtype: bool """ if int(math.sqrt(N))*int(math.sqrt(N))==N: return True return False
8ef6d02b2b9f07857a5549695c627e2d2327cb98
33,248
import itertools def generate_combo(samples, sample_spaces): """ First, generate combinations of i samples from the corresponding sample_spaces. Next, generate the cross product between the elements in the previously generated list. Finally, filter out the original combination from the result. ""...
663a933a3dd1331a4264e6a259d4c60738361b59
33,249
from typing import Dict from typing import Any def _make_serving_version(service: str, version: str) -> Dict[str, Any]: """Creates description of one serving version in API response.""" return { 'split': { 'allocations': { version: 1, } }, 'id': ...
a75fa6bdc03ee67d6f4bb6714d94c489072cfa66
33,250
def signum(x): """Sign of `x`: ``-1 if x<0, 0 if x=0, +1 if x>0``.""" if x < 0: return -1 elif 0 < x: return +1 else: return 0
858f49fe9d271b18e3a20d157bc793e613b6d73a
33,251
import fnmatch import os def find_file(path, pattern): """Wrapper for fnmatch.filter, with additional filecheck""" return [ os.path.join(path,filename) for filename in fnmatch.filter(os.listdir(path),pattern) if os.path.isfile(os.path.join(path,filename)) ]
815964103f7285989cf839a59198a7a218945be1
33,252
def detxy2kxy(xdet, ydet, xstart, ystart, x0, y0, fx, fy, xstep, ystep): """ Conversion from detector coordinates (xd, yd) to momentum coordinates (kx, ky). **Parameters**\n xdet, ydet: numeric, numeric Pixel coordinates in the detector coordinate system. xstart, ystart: numeric, numeric ...
44d353a5c5b5cabeb5a4b9aba8b4a07fc6a3ac2c
33,254
def get_item_from_dict_by_key(dict_name, search_term, search_in, return_content_of="item"): """ Return all items in a dict with a certain field match. It will normally return the content of the field 'item' which ...
e142ad6a017834bc2e3200d5c5350e2bea06c919
33,259
def bounding_box2D(pts): """ bounding box for the points pts """ dim = len(pts[0]) # should be 2 bb_min = [min([t[i] for t in pts]) for i in range(dim)] bb_max = [max([t[i] for t in pts]) for i in range(dim)] return bb_min[0], bb_min[1], bb_max[0] - bb_min[0], bb_max[1] - bb_min[1]
904a567ab962273e22b6e869fde393d23744eed0
33,263
from typing import Union from typing import List from pathlib import Path from typing import Dict from typing import Counter def recursive_open_and_count_search_terms( terms: Union[str, List[str]], folder: Union[str, Path] ) -> Dict[str, int]: """Recursively open files in a folder, and count given search term...
ad25ce04b7010b88a1a975ce37658e8c7a04611a
33,264
def has_been_replied_by_bot(comment, me): """Checks if a comment has been replied already by the bot. It checks if any the replies on the comment has been made by the reddit bot """ # Checking if the parent comment has been made by the bot. if comment.author == me: return True # Gettin...
6beb866adefeede829d9f3c9f9564e6e8ce5036c
33,266
def functionexample(INDIR, path, fname, OUTDIR, ARGS, intranet): """ Description ----------- Example of the function to perform in each file. Opens each file. """ f = open(INDIR + "/" + path + fname) f.close() return intranet
5bc17897970ac824c70b6f3963f76a035dab06fa
33,267
from typing import List import itertools def permutations(raw: str) -> List[str]: """Return a list of all unique permutations of a given input string. In case of an empty string (`''`) a list with an empty string will be returned (`['']`). Parameters ---------- raw: str Input string from...
7de84dde64431722fe25b170c6769e9eabc57858
33,268
def get_colour(temperature: float) -> tuple[float, float, float, float]: """Get colour from temperature. Args: temperature (float): Temperature in range [-1, 1] Return tuple: RGBA tuple """ # blending constant colour_blend = 0.85 alpha_blend = 0.9 # if temperature < 0, ...
dff04ed5023885b127b44632a2f5d49441e8b68e
33,269
def pep440_from_semver(semver): """Convert semantic version to PEP440 compliant version.""" segment = '' if semver.prerelease: segment = '.dev{}'.format('.'.join(semver.prerelease)) local_version = '.'.join(semver.build) local_version = local_version.replace('-', '.') version_str = '{}.{...
e3a8acb4dc0b83011fdfb76283ceb5fd928cda1c
33,271
def has_feature(td, feature): """ Checks for feature in DISTRO_FEATURES or IMAGE_FEATURES. """ if (feature in td.get('DISTRO_FEATURES', '') or feature in td.get('IMAGE_FEATURES', '')): return True return False
b438b3b84a134c0fbe0c38decd8caedbd1e1087c
33,272
def is_xml_file(f): """Tries to guess if the file is a BNC xml file""" f.seek(0) line = f.readline().strip() while line == '': line = f.readline().strip() if line.find('<bncDoc ') != -1: return True else: return False
e54318fc5679cc0709db0924f0444be347e7089a
33,273
import os def which(executable_name, env_var='PATH'): """Equivalent to ``which executable_name`` in a *nix environment. Will return ``None`` if ``executable_name`` cannot be found in ``env_var`` or if ``env_var`` is not set. Otherwise will return the first match in ``env_var``. Note: this functi...
ea446540a7f7f3ea64b5060900f0c57b349f81f2
33,274
def possible_negation_suffix(text: str) -> bool: """ Checks if the texts contains a possible negation suffix :param text: string containing a token :return: True if the texts ends with a possible negation suffix, False if not """ suffixes = ("less",) # length is mentioned so it doesn't con...
0cb8c2f81d29e6b836c2b4a2da2198613bb894cd
33,275
import logging from pathlib import Path def get_logging(filename): """ :return: the stdlib logging module configured with niceties """ logging.basicConfig( level=logging.INFO, filename=Path(".") / f"{filename}.log", filemode="a", format="%(asctime)s %(levelname)s: %(mes...
85ea5bd13f1043d2d3a346f85702cadf51bc375d
33,276
def count_object_methods(obj:object): """ get the number of callable object methods Args: obj (object): any object Returns: int: the number of object class methods """ return len([k for k,v in obj.__dict__.items() if callable(v)])
20fa1375441b30e119181b25c4d001604d5a6796
33,277
def t(s): """Force Windows line endings to Unix line endings.""" return s.replace("\r\n", "\n")
399ee6bccb2207afb79a0a8f74330be541baea6e
33,278
def xml_prompt(): """Prompts user for PubMed XML file.""" try: prompt = input("Please enter the name of the PubMed XML file: ") fhand = open(prompt) return fhand except IOError: print("Please ensure that you spelled the file name correctly and that you're in the right direct...
a4e88e9a77a28bb5afb670c3310f65a4156a2308
33,279
from typing import OrderedDict def linear_set_generator(random, args): """ Generates a list continuous values of the size of a representation. This function requires that a bounder is defined on the EvolutionaryAlgorithm. See Also -------- inspyred.ec Parameters ---------- rando...
39fef7e79d83d6c281e290e4387829d6f3343410
33,280
import textwrap def reindent(content, indent): """ Reindent a string to the given number of spaces. """ content = textwrap.dedent(content) lines = [] for line in content.split('\n'): lines.append(indent + line) return '\n'.join(lines)
b93b59a286e65eff286492315ad35f73ea86a1bd
33,282
def factorial(n: int) -> int: """Calculates the factorial of n Args: n (int): n > 0 Returns: int: factorial of n """ print(n) if n == 1: return 1 return n * factorial((n - 1))
d1a621d0081e1e14c272ca5fa058f3d66e28b097
33,283
import random def mergeUnfairRanking(_px, _sensitive_idx, _fprob): # input is the ranking """ Generate a fair ranking. Attributes: _px: input ranking (sorted), list of ids _sensitive_idx: the index of protected group in the input ranking _fprob: probability to choose the protecte...
072f28bea5a17cfc1df859bb5182708197014402
33,284
import six def construct_getatt(node): """ Reconstruct !GetAtt into a list """ if isinstance(node.value, six.text_type): return node.value.split(".", 1) elif isinstance(node.value, list): return [s.value for s in node.value] else: raise ValueError("Unexpected node type...
180d3f6ffba403213daf7b61b0381bcf758591df
33,285
def distanceSquared(a,b): """Squared L2 distance""" if len(a)!=len(b): raise RuntimeError('Vector dimensions not equal') sum=0 for i in range(len(a)): sum = sum + (a[i]-b[i])*(a[i]-b[i]) return sum
c1875902fba462d2c9a822d66acb1dc2be27c7b8
33,287
def flatten_nested_covariates(covariate_definitions): """ Some covariates (e.g `categorised_as`) can define their own internal covariates which are used for calculating the column value but don't appear in the final output. Here we pull all these internal covariates out (which may be recursively nes...
8f9d92ba1c7baa1a0d6c7153d2bf2b577d49ff70
33,288
def numeric_to_record(n_field): """ Check if the field has a value other then zero. :param str_field_to_check: :return: """ if n_field == 0: return None else: return n_field
11f33852c351b432f02380ec62cd1091759f1a17
33,289
def get_field_name(data, original_key, alternative_value): """ check which column name used in the BioSamples record, if both provided column names not found, return '' :param data: one BioSamples record in JSON format retrieved from API :param original_key: field name to be checked :param alternati...
07b9f01e5d1e0fe58a654c4ea55287a744cd291f
33,290
def fib(n): """Use the slow, recursive formula to calculate Fibonacci numbers. Arguments: n {int} -- Calculate the nth Fibonacci number. Returns: int -- The resulting Fibonacci number. """ if n == 0 or n == 1: return n return fib(n - 1) + fib(n - 2)
58ca55ffd7e17153d9f75a223912076f1cb8fb52
33,291
def generate_tikz_foot(tikzpic=True): """ generates end of tex-file :param tikzpic: if True include end{tikzpicture} before end{document} :return: tex-foot """ if tikzpic: tikzCode = ''' \\end{tikzpicture} \\end{document}''' else: tikzCode = ''' \\end{...
efac23b349cce2f9031cfa2eb5edbb48d47047fd
33,292
def remove_quotes(val): """Helper that removes surrounding quotes from strings.""" if val[0] in ('"', "'") and val[0] == val[-1]: val = val[1:-1] return val
11a8c26e5b261e75a08ae9b11d9c4e39f07da4c3
33,293
def characters_count(sorted_string): """Count only the characters (not numbers) occurrences in the string""" result = [] if sorted_string: unique_characters = set(sorted_string) unique_characters = sorted(unique_characters) for c in unique_characters: result.append({c...
536b9b1a0cf422df0e606191a02dd36f64e6828d
33,294
def basic_name_formatter(name): """Basic formmater turning '_' in ' ' and capitalising. """ return name.replace('_', ' ').capitalize()
4b87af7df7bfc23c8c63d958e29a4fe614780fa8
33,295
def no_inference(csp, var, assignment, removals): """ If we do not implement an inference algorithm, just return that everything is ok.""" return True
6bea7afca66a73a5236ef7667e857b746b4c95a4
33,297