content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def _exist(self) -> bool: """property value of path.exists()""" return self.exists()
7cb4d7c70ecd699ad7024aef04bffad7a790c1dd
654,183
def milky_way_extinction_correction(lamdas, data): """ Corrects for the extinction caused by light travelling through the dust and gas of the Milky Way, as described in Cardelli et al. 1989. Parameters ---------- lamdas : :obj:'~numpy.ndarray' wavelength vector data : :obj:'~numpy....
b99b7ee2dc890aaf481322ec377951997973b49a
654,184
import math def cart2pol(werte): #Wandelt 2d karteschische Koordinaten in Porlarkoordinaten um """returns r, theta(degrees) """ r = (werte[0] ** 2 + werte[1] ** 2) ** .5 theta = math.degrees(math.atan2(werte[1],werte[0])) return [r, theta]
aeffd399ddfe900057bc02e8ff0cebae1dad51f8
654,185
import unicodedata def ascii_alias(s): """ If this name contains combining characters, return the version without combining characters for use as an alias. """ if not s: return None try: ascii = s.encode("ascii") return None except Exception: pass alias = ...
668085bfe12675a0da22e14ee165918877cb444b
654,186
def build_anytext(name, value): """ deconstructs free-text search into CQL predicate(s) :param name: property name :param name: property value :returns: string of CQL predicate(s) """ predicates = [] tokens = value.split() if len(tokens) == 1: # single term return f"{nam...
e7b879a34bcaa0b776a8ffdfd91da7565b3195ab
654,187
import math def compensatoryAnd(m, g=0.5): """ anding function m = list of membership values for x derived from n membership functions g = gamma value 0=product 1=algebraic sum returns compensatory AND value of x """ g = float(g) product1 = 1 product2 = 1 for mem ...
6b8513de08efc24c87925aab9afe89d01674fb39
654,188
def get_ingredients_with_allergens( ingredient_to_food, ingredients_without_allergens): """Return ingredients not present in ingredients_without_allergens.""" return { ingredient: food for ingredient, food in ingredient_to_food.items() if ingredient not in ingredients_without_all...
9eb66996f3453eb36ac297fc7cf80df16e54d915
654,190
import random def _get_a_word(words, length=None, bound='exact', seed=None): """Return a random word. :param list words: A list of words :param int length: Maximal length of requested word :param bound: Whether to interpret length as upper or exact bound :type bound: A string 'exact' or 'atmost' ...
0170df161a63743e1c7a2b1a8b2ac88a8baa4e88
654,191
def dict2str(opt, indent_level=1): """dict to string for printing options. Args: opt (dict): Option dict. indent_level (int): Indent level. Default: 1. Return: (str): Option string for printing. """ msg = '' for k, v in opt.items(): if isinstance(v, dict): ...
026cfe7e819b474a2a4cccf2ee2969a9ae1abd19
654,192
import pytz def convert_ts_to_utc(ts): """ DESCRIPTION ----------- Return a timestamp or datetime object converted to UTC timezone PARAMETERS ---------- ts : dt.datetime A datetime or timestamp instance RETURNS ------- A datetime or timestamp instance with added UTC t...
007162e7ebb00e7c507e9b5f916631c9b85dc6d3
654,193
def is_pos_tag(token): """Check if token is a part-of-speech tag.""" return(token in ["CC", "CD", "DT", "EX", "FW", "IN", "JJ", "JJR", "JJS", "LS", "MD", "NN", "NNS", "NNP", "NNPS", "PDT", "POS", "PRP", "PRP$", "RB", "RBR", "RBS", "RP", "SYM", "TO", "UH", "VB...
1472f3b28bb60097c8725ba07b8d2e0a659ac1e0
654,194
from typing import Dict from typing import Any from typing import List def set_user_defined_functions( fha: Dict[str, Any], functions: List[str] ) -> Dict[str, Any]: """Set the user-defined functions for the user-defined calculations. .. note:: by default we set the function equal to 0.0. This prevents ...
5078168319e4360f3ac3b3c02087439e5175da07
654,195
import math def bbox_to_zoom_level(bbox): """Computes the zoom level of a lat/lng bounding box Parameters ---------- bbox : list of list of float Northwest and southeast corners of a bounding box, given as two points in a list Returns ------- int Zoom level of map in a WG...
f8f97a6e9304d2122cf04a1c1300f911b964bf09
654,196
def serialize(dataset, json_filepath=""): """ Serialize dataset pipeline into a JSON file. Note: Currently some Python objects are not supported to be serialized. For Python function serialization of map operator, de.serialize will only return its function name. Args: dataset (...
6b75b416743787769af754168ae62282e9f9427d
654,197
def scale_size(widget, size): """Scale the size based on the scaling factor of tkinter. This is used most frequently to adjust the assets for image-based widget layouts and font sizes. Parameters: widget (Widget): The widget object. size (Union[int, List, Tuple]): ...
3cd7b8e9a88a544c6086b0d453773f3d26f4eba3
654,199
def pdf_field_type_str(field): """Gets a human readable string from a PDF field code, like '/Btn'""" if not isinstance(field, tuple) or len(field) < 4 or not isinstance(field[4], str): return '' else: if field[4] == '/Sig': return 'Signature' elif field[4] == '/Btn': return 'Checkbox' ...
c677e0decb4efabde7b5aa42fe95f208c4e7a184
654,200
def get_task_prerun_attachment(task_id, task, args, kwargs, **cbkwargs): """Create the slack message attachment for a task prerun.""" message = "Executing -- " + task.name.rsplit(".", 1)[-1] lines = ["Name: *" + task.name + "*"] if cbkwargs["show_task_id"]: lines.append("Task ID: " + task_id) ...
f67798248966730acd90da135d70f734d428a27e
654,201
from typing import Optional from typing import Tuple def make_response(status: int, data: Optional[str] = None) -> Tuple[str, int]: """Construct a non-error endpoint response.""" if data is None: data = "" return (data, status)
dca07b1f103f1bbf5e31d813aa620be1bfc40f8f
654,202
def _is_i3_compliant(stream): """Reads lines from the input stream and scans "flags" lines and returns true if the flags are compatible with the GEM i3 bundle. This is usually filled with the content of /proc/cpuinfo to determine the current systems capabilities The input is a stream that must prov...
3983e70508be79c432daf4830982d7c23b480ec3
654,203
import argparse import sys def parse_args() -> argparse.Namespace: """ Parse command-line arguments. """ parser = argparse.ArgumentParser(description=__doc__) subparsers = parser.add_subparsers(dest="cmd") subparsers.add_parser("status", help="show resource status") subparsers.add_parser("download...
3ee64e4bd3afa31ab8b345d08c5e45c51e73f127
654,204
def mse_grad(y, tx, w): """Compute gradient for MSE loss.""" e = y - tx @ w return (-1/tx.shape[0]) * tx.T @ e
3635335895777112a5cc0c889a9379c043822eb1
654,208
from typing import Tuple def _get_func_expr(s: str) -> Tuple[str, str]: """ Get the function name and then the expression inside """ start = s.index("(") end = s.rindex(")") return s[0:start], s[start + 1:end]
8ac212727859fc2df01cc12164118d9cfcf66d9f
654,209
def add_cmd(cmd, **kwargs): """Function: add_cmd Description: Append name of argument and possibly value for the argument to the command line list array. Arguments: (input) cmd -> List array containing the program setup. (input) **kwargs: arg -> Name of argument bein...
957c77c33c1c750aa374c6e4d90ed16f2c7a4ba0
654,210
def expand_multival_arg(args, name, count): """Expand a "multival" argument.""" value = args.get(name) if value is None: raise ValueError('missing value for {0}'.format(name)) parts = value.split(',') if len(parts) < count: parts += [parts[-1]] * (count - len(parts)) elif len(par...
6deaca0cebf3e146bae9a472c69f50ce6e06af4d
654,212
def get_df_rng(ws, df, start_row=1, start_col=1, include_headers=True): """Gets a range that matches size of dataframe""" nrow = len(df) + 1 if include_headers else len(df) ncol = len(df.columns) return ws.get_range(row=start_row, column=start_col, numb...
b19bb43f2e1b603a887fa220e17cb56cfbba7d14
654,213
def add_odd_numbers(n): """adds all odd number between zero and n, including n""" return sum([number for number in range(n + 1) if number % 2 != 0]) # another approach # return sum([number for number in range(1,n + 1,2) ])
252067283d65cb4da7c67079e38361a2cbe32506
654,214
from numpy import where, cumsum, diff def convert_to_rate(x,y, tau = 1): """ takes one dimensional vector of particle count where index in the vector index defines frame number. """ idx = where(y >0)[0] distance= diff(x[idx]) count = y[idx][:-1] rate = count/(distance*tau) cm = cumsum(...
3b9ef55de8e5a42b78aeadec246712709c33ed4f
654,215
import torch def optimizer_fn(policy, config): """Creates all necessary optimizers for SAC learning. The 3 or 4 (twin_q=True) optimizers returned here correspond to the number of loss terms returned by the loss function. """ # actor optimizer policy.actor_optim = torch.optim.Adam( par...
0182a6894f98148ec0ab60ee51efad64599c8ab3
654,217
from typing import Optional from typing import Sequence def reasonable_len( tokens: Optional[Sequence[Sequence[Sequence[str]]]], n_chars: int, tok_len: int = 8, char_len: int = 20, ) -> bool: """ Checks that tokens / sentences are reasonable length. Unreasonable is when there's no sentence...
bdefef81d4c43b85a24a3f846440f04cebcc0888
654,218
def fill_site_object(site_id, title, updated, url, category, is_read_daily, article_count, is_un_classified): """ site object: { site_id: site_id, title: title, udpated: YYYY-MM-DD, category: category, is_fav: boolean, artic...
96fcf83004686b4807949a945ec796ca1f164441
654,219
def infoset(board, hidden_stones, player) -> str: """ Returns the infoset of the current board. """ s = 'P' + str(player) + ' ' for i in range(len(board)): s += str(board[i]) s += str(hidden_stones) return s
02695c6296e53ad444b17115da76e510e68c1806
654,220
def resolve_coref(text, nlp): """ :param text String of text where to resolve coreference. :return: A text String where the coreference has been resolved. """ doc = nlp(text) return doc._.coref_resolved
0eef1194c57cb336e9b8e1351ac98048106c7881
654,221
def get_numeric_columns(df): """ # Returns a list of numeric columns of the dataframe df # Parameters: # df (Pandas dataframe): The dataframe from which extract the columns # Returns: # A list of columns names (strings) corresponding to numeric columns """ numeric_columns = lis...
6ec1cb8d1a8dd9c4cb49f17257b137e9ec0d4210
654,222
import decimal import logging def format_decimal(n): """ Convert the given float to a string without scientific notation """ try: with decimal.localcontext() as ctx: ctx.prec = 7 if isinstance(n, float): d = ctx.create_decimal(repr(n)) re...
b341b31c48eb36921e5bedc9a98c18d1282b6dee
654,223
from pathlib import Path from typing import Optional def get_file_by_type(folder: Path, suffix: str) -> Optional[Path]: """ Extracts a file by the suffix. If no files with the suffix are found or more than one file is found returns `None`""" if not suffix.startswith('.'): suffix = '.' + suffix candidates = [i fo...
a062be4f3a449473b725f735a622b24432212934
654,224
def clip_column(column, lines, line_number): """ Normalise the position as per the LSP that accepts character positions > line length https://microsoft.github.io/language-server-protocol/specification#position """ max_column = len(lines[line_number].rstrip('\r\n')) if len(lines) > line_number else ...
c5bcab988c9b32951e232d158d0890d15138f7cb
654,225
def get_text_list(list_, last_word='or'): """ >> get_text_list(['a', 'b', 'c', 'd']) 'a, b, c or d' >> get_text_list(['a', 'b', 'c'], 'and') 'a, b and c' >> get_text_list(['a', 'b'], 'and') 'a and b' >> get_text_list(['a']) 'a' >> get_text_list([]) '' """ if len(list_...
ceb6b97b2b7dce802cc7d194a202211a3354fe80
654,226
def normalize_robust(feature, feature_scale=(None, 0.5)): """normalize feature with robust method. Args: feature: pd.Series, sample feature value. feature_scale: list or tuple, [feature.median(), feature.quantile(0.75)-feature.quantile(0.25)]; if feature_scale[0] is n...
87a4787972e01122635ef294483d779e5bfe5589
654,227
def add_state_names_column(my_df): """ This add a column of corresponding state names to a DataFrame. Params (my_df) a DataFrame with a column called "abbrev" that has state abbrevations. Return a copy of the original DataFrame, but with an extra column. """ new_df = my_df.copy() ...
6525356ab96450267ca182ce91bce7afe676f6f0
654,228
async def align_nickname(user_datum, guild_member): """Modifies user nickname to rsi handle :param user_datum: user data from the site :param guild_member: discord.Member :return: String[] of logs """ logger = [] handle = user_datum['handle'] current_nick = guild_member.nick current...
e85d375908c61f7d7c005577a6637709aaf03acc
654,231
def get_org(x, lang='en'): """Get the organization of people status + Org name 2018, Ph.D. IBP row-3: 2018, Ph.D. ror-4: IBP """ org = x.loc[4][lang] return org
e26d6239404519cc2e446c7af7e37f70b1207be7
654,232
from typing import Dict from typing import List from typing import Set def get_parents_of(image_and_parents: Dict[str, List[str]], commit_id: str) -> Set[str]: """Returns a set of all parents of a given commit id.""" parents = None parents_list = [commit_id] i = 0 while i < len(parents_list): ...
6f59db910adf6eaa1ec211159cb065f3d599b4f6
654,233
import six def partition(list_, columns=2): """ Break a list into ``columns`` number of columns. """ iter_ = iter(list_) columns = int(columns) rows = [] while True: row = [] for column_number in range(1, columns + 1): try: value = six.next(ite...
4fc70a56ee10fc49dacae88b6dc5972941a3d947
654,234
def filt(items, keymap, sep='.'): """ Filters a list of dicts by given keymap. By default, periods represent nesting (configurable by passing `sep`). For example: items = [ {'name': 'foo', 'server': {'id': 1234, 'hostname': 'host1'}, 'loc': 4}, {'name': 'bar', 'server': ...
bdf7ffd570bcef90537fdaeb5ca7dddd02a41294
654,235
def ga_status_to_guest_info(ga_status): """ Convert VMStatus object to status blob format """ v1_ga_guest_info = { "computerName": ga_status.hostname, "osName": ga_status.osname, "osVersion": ga_status.osversion, "version": ga_status.version, } return v1_ga_guest_...
6f75e2812e9fcdf1f08eee1595fc32b7f381a4df
654,236
def determine_site_type(name, website): """ The name (or website) of a Federal Site in this list provides an indication of what type of site it might be. This extracts that out. """ name_fragments = [ (' BLM', 'BLM'), (' NF', 'NF'), ('National Forest', 'NF'), (' NWR', 'NWR'), (' NHS', 'NHS...
db5c2533f114a875023d7a887509f5858afe48cf
654,237
import torch def broadcast_inputs(ndims): """ Broadcast inputs to specified number of dims and then back. """ def decorator(forward): def wrapped(self, inputs): expand_dims = ndims - len(inputs.shape) inputs = inputs[(None,) * expand_dims] outputs = forward(self, inputs) if expand_dims...
38a171519c490a1ae10d86af01783e26172ecd9e
654,238
def count_lines(in_path): """Counts the number of lines of a file""" with open(in_path, 'r', encoding='utf-8') as in_file: i = 0 for line in in_file: i += 1 return i
848d6cf870f449a7ba9b9c249461f0438c62a7b0
654,239
def check_if_homomer(chains): """Generates an empty set, then adds sequences to set. Then checks if set has one unique sequence, if so, metal site is homomeric.""" chain_set = set() for chain in chains: sequence = chain.sequence chain_set.add(sequence) if len(chain_set) == 1: ...
628cb5d92f0c83e91bee6ad3da1ae940a8da62d2
654,240
def partition(l, condition): """Returns a pair of lists, the left one containing all elements of `l` for which `condition` is ``True`` and the right one containing all elements of `l` for which `condition` is ``False``. `condition` is a function that takes a single argument (each individual element...
3a5425143706176b6183c5d32fecd74022d2afd6
654,241
from functools import reduce import operator def times(iterable): """ float: multiply each element of the given `iterable`. """ return reduce(operator.mul, iterable)
c956b1eae09755801d174f2f2ba93aef47fb5ea7
654,242
import pkg_resources def get_template(): """ Read and return internal metadata definition as a DataFrame with internal metadata names as indices :return: pandas.DataFrame """ pro_template_file = pkg_resources.resource_filename( 'view', "idl_folder_translation/pro_fsm_template.txt") re...
7aa479f26a8237f8e8c7645ffd6a1d764d530435
654,243
def GetKeywordArgs(prop, include_default=True): """Captures attributes from an NDB property to be passed to a ProtoRPC field. Args: prop: The NDB property which will have its attributes captured. include_default: An optional boolean indicating whether or not the default value of the property should...
9babf84558197b29e41b1693881b5b4a3f965a88
654,244
def loop_merge_sort(l1, l2): """ 定义新的空列表存放结果; 比较2个列表第一个元素,插入小的元素到新列表中,并删除该元素 最终会出现2个列表中某个列表为空的情况,将旧列表追加到新列表的最后 """ tmp = [] while len(l1) > 0 and len(l2) > 0: if l1[0] < l2[0]: tmp.append(l1[0]) del l1[0] else: tmp.append(l2[0]) ...
81370410d833412025ce628ebc1fd669eec4d40a
654,245
from pathlib import Path def find_top_level_mounts(directory_path: Path) -> set[Path]: """Return a sequence of all mount points under the given directory (excluding the directory itself) that are top-level, i.e., that themselves are not under any mount point other than the given directory itself or any ...
7232065a26b8aba8635dbe536732475e8276570e
654,246
from typing import Dict from typing import Any import re def get_good_response(client, caplog): """Get OPTIMADE response with some sanity checks""" def inner(request: str) -> Dict[str, Any]: try: response = client.get(request) # Ensure the DB was NOT touched asser...
628c708ac66bfac33b8bae436a0051cc8113e42b
654,247
def space_check(board, position): """ Returns a boolean indicating whether a space on the board is freely available. :param board: :param position: :return: """ return board[position] == ' '
c09e93f3a51639e9a2fc94f8dfbd489745c0f40e
654,248
import torch def instrument_w_nvtx(func): """decorator that causes an NVTX range to be recorded for the duration of the function call.""" if hasattr(torch.cuda.nvtx, "range"): def wrapped_fn(*args, **kwargs): with torch.cuda.nvtx.range(func.__qualname__): return func(*...
2e711c2a511c1f84bbb65bb5263abae312cf1962
654,249
def _flatten_vectors(vectors): """Returns the flattened array of the vectors.""" return sum(map(lambda v: [v.x, v.y, v.z], vectors), [])
c5892018f2b3d8eaae2bd5a1bf63c1ef221fec9c
654,250
def dmp_div(f, g, u, K): """ Polynomial division with remainder in ``K[X]``. Examples ======== >>> R, x, y = ring("x y", ZZ) >>> R.dmp_div(x**2 + x*y, 2*x + 2) (0, x**2 + x*y) >>> R, x, y = ring("x y", QQ) >>> R.dmp_div(x**2 + x*y, 2*x + 2) (1/2*x + 1/2*y - 1/2, -y + 1) "...
7f49b98c46be10604b6b38076c6f12855e149d18
654,251
def co(self) -> tuple: """ Solve last layer face. Returns ------- tuple of (list of str, dict of {'LAST LAYER FACE': int}) Moves to solve last layer face, statistics (move count in ETM). Notes ----- If the last layer face is not solved, rotate the cube so that the yellow si...
f6324813a3db6bfcb69ba1cf03acd03de2152e95
654,252
def INPUT_SOLVER(): """Return list of Sudoku boards for Solver class tests ./src/solver.py/Solver:class""" return { "nextpos": { "board": [ [1, 5, 0, 0, 0, 0, 0, 0, 3], [0, 0, 0, 0, 0, 6, 4, 2, 0], [0, 8, 4, 5, 0, 0, 7, 9, 0], [...
68c7926818d045b508f3b9c02f7426c89b9ced61
654,253
def is_connected(graph, node_a, node_b) -> bool: """ are node a and node b connected? DFS uses preprocessing time and space proportional to V􏰁E to support constant-time connectivity queries in a graph. _id will provide information about disconnected components. """ _visited = set() _id = {...
087bb183294aebdb3f902e44c97dd7cd637ff1c2
654,254
import os import json def get_tracklist_json(reference_genome, concurrent_id=None): """ Get trackList for jbrowse """ jbrowse_path = reference_genome.get_jbrowse_directory_path() # If this is a concurrent read, read from individual tracks # subdir, named by a concurrent_id. Update is OK if d...
78c5ed74522d1baf254469791e414fe5bde993c1
654,255
from typing import Counter def get_colors(image): """Return a Counter containing each color and how often it appears. """ colors = Counter(pixel for row in image for pixel in row) if len(colors) > 256: msg = ( "The maximum number of distinct colors in a GIF is 256 but " ...
bcf4bc2dadae359e092c04eb9cb125b23e41c4b9
654,256
def list2str(args): """ Convert list[str] into string. For example: [x, y] -> "['x', 'y']" """ if args is None: return '[]' assert isinstance(args, (list, tuple)) args = ["'{}'".format(arg) for arg in args] return '[' + ','.join(args) + ']'
6494c3b4a6912b2a13eba6a84a3e7d9454eb4d4c
654,257
import os def env_var(var, default=None): """ Read the value from an environment variable. Provided default is used if no environment variable is present provided """ if default is None: assert var in os.environ, 'Must set {} evironment variable'.format(var) return os.environ[var]
d2732fd3a10f0088458842c4f1d748c1d52d63a6
654,258
import csv def load_GO_annot(filename): """ Load GO annotations """ onts = ['molecular_function', 'biological_process', 'cellular_component'] prot2annot = {} goterms = {ont: [] for ont in onts} gonames = {ont: [] for ont in onts} with open(filename, mode='r') as tsvfile: reader = csv.r...
9530f502a7a866e5af9015dd87373c9bd9c27fcd
654,259
def lower_bits(sequence,n): """Return only the n lowest bits of each term in the sequence""" return map(lambda x: x%(2**n), sequence)
b7368e04a2a535772d81f491b5d40de0d12cef32
654,261
def make_callback_dictionary(param_dict, status_flag, status_msg): """Utility function that adds extra return values to parameter dictionary.""" callback_dict = param_dict.copy() callback_dict['status_flag'] = status_flag callback_dict['status_msg'] = status_msg return callback_dict
c2fcb7d3637955359ae362ddfd5e4334aa5c2af7
654,262
import re def filter_lines(output, filter_string): """Output filter from build_utils.check_output. Args: output: Executable output as from build_utils.check_output. filter_string: An RE string that will filter (remove) matching lines from |output|. Returns: The filtered outpu...
037281b7f1b1c9b87abbcc8572e198a1f36b6165
654,263
def get_savwriter_integer_format(series): """ Derive the required SAV format value for the given integer series. savReaderWriter requires specific instructions for each variable in order to correctly create target variables. This function determines the width of the maximum integer in the given ser...
af03953c9bd9bf01982073bba643d88e67e42b1e
654,264
def concatenate(str1, str2): """ concatenate str1 and str2""" return str(str1) + str(str2)
f83f42380fc803a3d5e9a04529e53348f273305b
654,265
from typing import Dict from typing import Any def light_auth_validate_func(data: Dict[str, Any]) -> bool: """demo for setting.LIGHT_AUTH_VALIDATE_FUNC""" if data.get('username', None) == data.get('password', None): return True return False
9709beae8fd393333cd0a67eb26afe48c122192d
654,266
def get_monitor_name(domain_name: str) -> str: """ Encapsulate the RUM monitors naming convention. :param domain_name: the domain name for which a RUM monitor is to be created. :return: a Rams' compliant RUM monitor name """ return domain_name + "_RUM"
e31e24aa884c7b251c56d6c5d781ac1915c4167d
654,267
def get_release_version(version): """ If version ends with "-SNAPSHOT", removes that, otherwise returns the version without modifications. """ if version is None: return None if version.endswith("-SNAPSHOT"): return version[0:-len("-SNAPSHOT")] return version
dc8d339231ee6f6cbde1e76ee614e706b501e10f
654,269
def typeOut(typename, out): """ Return type with const-ref if out is set """ return typename if out else "const " + typename + " &"
b4c1dfad171ad1d2168a8873f5757dce4d3dbd9c
654,270
def handle_single_ddc(data): """ produces a about node based on DDC """ return {"identifier": {"@type": "PropertyValue", "propertyID": "DDC", "value": data}, "@id": "http://purl.org/NET/decimalised#c"+data[:3]}
183933ed104902141b4acb22333b72350380952d
654,271
def Double_list (list_genomes): """ Create the new headers of the contig/s of the individual genomes and save the headers and sequences in different lists. In the same position in a list it will be the header and in the other its respective nucleotide sequence. """ # Create the lists: heade...
d981f27ad4d95c43010ea408fef83f982cd19959
654,272
def WrapFunction(lib, funcname, restype, argtypes): """ Simplify wrapping ctypes functions :param lib: library (object returned from ctypes.CDLL() :param funcname: string of function name :param restype: type of return value :param argtypes: a list of types of the function arguments :return:...
c2bf3ff6b7a549e965e0fbe7f20d198bdb69ed13
654,273
import os import fnmatch def getDirContentsRec(dir, pattern=None): """ returns dir content, including subdirectories :param dir: :type dir: str :param pattern: glob style pattern to filter files :type pattern: str :return: returns list of files :rtype: list[str] """ result=[] ...
fad4338657488748992cd59806d14896e8050fd0
654,274
def convert_list_values(values_list, convert_to='str', split_values=False, split_delimiter=','): """This function converts the values in a list to a different type. :param values_list: The list of values to be converted :type values_list: list, tuple, set :param convert_to: One of the following types: ...
dcae084bc0b2da469ff4a958bf6811024da6ec80
654,275
def teleport_counts(shots, hex_counts=True): """Reference counts for teleport circuits""" targets = [] if hex_counts: # Classical 3-qubit teleport targets.append({'0x0': shots / 4, '0x1': shots / 4, '0x2': shots / 4, '0x3': shots / 4}) else: # Classical 3-...
4b009e2d0e6885fe27bd3c103b138319c4a61637
654,276
import re from functools import reduce def guessTextQualifier(input): """ PROTOTYPE: guessTextQualifier(input) DESCRIPTION: tries to guess if the text qualifier (a character delimiting ambiguous data) is a single or double-quote (or None) ARGUMENTS: - input is raw data as a str...
ce3985ca5b122d1ea0e2533b64b66a5632193e0a
654,277
from typing import OrderedDict def remove_duplicates(array: list) -> list: """Return list of array with no duplicates. Preserves order. Used by radix sort.""" return list(OrderedDict.fromkeys(array))
8ceab77d540c6d656cd7b6aa5093fe34d5e3f708
654,278
import inspect def is_generator(func): """Check whether object is generator.""" return inspect.isgeneratorfunction(func)
489321c7e197706d541596830aa3f18b6fb01901
654,279
import platform import os def _on_msys_tainted_paths(): """This duplicates datalad.utils.on_msys_tainted_paths But it does it while minimizing runtime penalties on all irrelevant systems. """ if os.environ.get('MSYSTEM', '')[:4] not in ('MSYS', 'MING'): return False if 'MSYS_NO_PATHCO...
19609be6cbabb5eb94cbb50d97f99c50115eecb2
654,280
def str2int(s): """ str('1-3,6,89-90,67') => [1,2,3,6,67,89,90] """ intervals = list(map(lambda x: x.strip().split('-'), s.strip().split(','))) out = [] for x in intervals: try: p, q = map(int, x) except ValueError: out += [int(x[0...
9f04b53e82b1ada8e0cbba115b4fb68117951297
654,281
def org(mocker): """Fake Organisation instance.""" org = mocker.Mock() org.id = "003" org.name = "org-003" return org
d01c91c88cd40c9e71c0e589492a855a65211bac
654,282
def normalize_space(data): """Implements attribute value normalization Returns data normalized according to the further processing rules for attribute-value normalization: "...by discarding any leading and trailing space (#x20) characters, and by replacing sequences of space (#x20) ...
e95b0178e54312c7ab329bc982f8add632709c3b
654,283
from typing import List import os def get_subdirs_recursive(start_path: str) -> List[str]: """ Recursively search the given directory for subdirectories :param start_path: The root directory of the search :return: A list of subdirectories """ contents = os.listdir(start_path) dirs = [] ...
b560c5831aad62129fe940701c30dd8643c88da3
654,284
def problem_9_1(arr1, arr2): """ You are given two sorted arrays, A and B, and A has a large enough buffer at the end to hold B. Write a method to merge B into A in sorted order. """ m = len(arr2) - 1 p = len(arr1) - 1 n = len(arr1) - len(arr2) - 1 while n >= 0 and m >= 0: if ar...
36196b12b595bd1c9e790f765d010eb59c9467b8
654,285
def lstrip_docstring(docstring: str) -> str: """ Strips leading whitespace from a docstring. """ lines = docstring.replace('\t', ' ').split('\n') indent = 255 # highest integer value for line in lines[1:]: stripped = line.lstrip() if stripped: # ignore empty lines ...
587905876f031b5eae6e7c42e7e5b1b08d11e5d4
654,288
def player_stat_grouping(df, foi): """ Return a dataframe with the means and stds for a player's fields of interest (foi) during a year df: Dataframe of data. Assumed to have column with title 'year', 'unique', and foi column names foi: Fields of interests to group on. Could be either string or lis...
2ff29b8ead4390d11ec52bdc8acf6095f8405bb9
654,289
def PROPER(text): """ Capitalizes each word in a specified string. It converts the first letter of each word to uppercase, and all other letters to lowercase. Same as `text.title()`. >>> PROPER('this is a TITLE') 'This Is A Title' >>> PROPER('2-way street') '2-Way Street' >>> PROPER('76BudGet') '76Bu...
ec47ee1805daad73cbf44915fcc2d889d8725747
654,290
import os import logging def write_jinto_settings_file(module_path, data): """:returns: the path to the settings file.""" settings_dirpath = os.path.join(module_path, ".settings") settings_filepath = os.path.join(settings_dirpath, "de.guhsoft.jinto.core.prefs") try: os.makedirs(settings_dirpat...
45022d2286ab9b5b53a48c6514850a2f74a7776c
654,291
def split(l: list, n_of_partitions: int) -> list: """ Splits the given list l into n_of_paritions partitions of approximately equal size. :param l: The list to be split. :param n_of_partitions: Number of partitions. :return: A list of the partitions, where each partition is a list itself. """ ...
54252151dd5577673e5ead7884c087d28ea9190a
654,292
def validate_source(source): """ Matches abbreviations to full volume names :param source: volume name or abbreviation :return: """ if source == 'i': source = 'NeitzInferiorMonkey' elif source == 't': source = 'NeitzTemporalMonkey' elif source == 'r': source = 'RC...
09dabd0080193c357aae4f64231cea67aa29e61c
654,293
import random def generate(sz, rg, sl): """ :type int sz: size of square matrix(sz * sz) :type int rg, int sl: range and scale of data. For example if the value field will be [-0.2, 0.2], than rg = 2, sl = 10 :rtype: (matrix List[List[float]], vector List[float]), float in Python equal to double i...
70c814d4cd49d501e550cdb4ac6246329751cc3c
654,294
def new_value_part_2(seat: str, visible_count: int) -> str: """ Returns the next state for one seat. """ if seat == "L" and visible_count == 0: return "#" elif seat == "#" and 5 <= visible_count: return "L" else: return seat
6b8dcaecfd5a62fbb8a5c9333dc8ec180cc814ca
654,295