content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def surround(string): """Surrounds a string with curly brackets, square brackets, and a space. :param string: String to be surrounded :type string: str :return: Surrounded string :rtype: str""" return "{[ " + string + " ]}"
1c1b2dad0231a4b663ce303b164ff645956d47b5
634,580
def delete_previous_entries(icursor, scenario, huc12, dates): """Remove whatever previous data we have for this huc12 and dates""" if len(dates) > 366: # Means we are running for 'all' icursor.execute( """ DELETE from results_by_huc12 WHERE scenario = %s and h...
f5386446366241b4f16d21007457aaba9a2fbc69
634,581
def argsort(seq): """ Stable version of argsort """ # http://stackoverflow.com/questions/3382352/equivalent-of-numpy-argsort-in-basic-python/3382369#3382369 return sorted(range(len(seq)), key=seq.__getitem__)
9ccd0f2c3267dcec10db7c9e7668d5f3574050ea
634,582
def iterable(obj) -> bool: """ Determines if this object satisfies the iterable interface, which requires it to support either ``__iter__`` or ``__getitem__``. """ return hasattr(obj, '__iter__') or hasattr(obj, '__getitem__')
adcc62d32d488fe39449a7ba6d4d40ac28693af9
634,583
def apply_permutation(cm, perm): """ Apply permutation to a matrix. Examples -------- >>> cm = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) >>> perm = np.array([2, 0, 1]) >>> apply_permutation(cm, perm) array([[8, 6, 7], [2, 0, 1], [5, 3, 4]]) """ return cm[...
6dc35a54da4970e86506e2215411957ebfcd1d6f
634,584
def datetime64_to_inttime(var): """ Return an "inttime" representing a datetime64. For example, 2016-09-29 as an "inttime" would be 20160929 An 'inttime' is used in statistics which return an actual observation to represent the date that observation happened. It is a relatively compact represen...
ba8d9ec2b76f52b581039226955321215a936251
634,585
def is_leap_year(year): """ Returns whether a year is a leap year - Leap years are any year that can be exactly divided by 4 - Except if it can be divided exactly by 100 then it isn't - But if it can be divided exactly by 400 then it is a leap year """ if (year % 4 == 0 and year ...
23d850d2fa3a6c0ce430227569765e473a9d637a
634,586
def self_attribute(): """obj.meth.__self__: Instance bounded to a method.""" class _ItemClass: def _function(self): return self and "device restart tone" item = _ItemClass()._function.__self__ return item._function()
edca555d26b2d649ea7c91d79389e903478de9b0
634,587
import re def coerce_to_number(ticket_value): """Coerce the input into a number. If the input is a number, return itself. Otherwise parses input strings of two forms. 'SERVER-12345' and '12345' will both return 12345'. """ if isinstance(ticket_value, int): return ticket_value ticket_...
4804a574f1830ee5410de6fda0e904ff13bc974e
634,588
def join_parquets(spark, *parquet_files): """ Join multiple parquets files together on the '_Id' column. Args: parquet_files: list of strings referring to .parquet files. Returns: dataframe: all .parquet files joined into a single dataframe. """ result = None for parquet_fil...
0eecba0e6688e065f5205a387f7e67fa51aef26a
634,589
def linmag(vali, magstart, magend, dur): """ funciton for generating a ramp of values that is linear in magnification vali: initial value (globally) magstart: magnification at the start of the ramp magend: magnification at the end of the ramp dur: number of steps (duration) """ out = [] ...
43cb211aafa36fd8cbc15649f4c2a092bec909e5
634,590
def mask_characters(expression, search_text, target_text, mask_char): """Mask characters found by a regular expression with mask character. Mask characters will equal length of masked string. A different target text to search text may be used, but the developer must ensure that they are compatible. This...
6f2ee6b799b4ff774f9850be6561e0e3a61e2deb
634,591
def Mach(a, V): """ Calculates flow Mach number """ Ma = V / a return Ma
904b33caa9ae3a05ec28fba9a3d68a594d382943
634,593
def get_version(path): """Get __version__ from Python file.""" with open(path, "rt") as f: for line in f: if line.startswith("__version__ = "): return line.strip().split(" = ")[1].strip("\"'")
7895c07653132fba7a62bc24c77e5050d584de7c
634,595
import mmap from typing import Optional import io def _read_until_delimiter(delim: str, mem_map: mmap.mmap, encoding: str, max_bytes: Optional[int] = None) -> str: """ Reads the text that precedes a delimiter character and returns i...
d0c1c12da25850a79c89c8cd532a8b35846a033f
634,596
def get_assist_turnover_ratio(assists, turnovers): """ Calculates the ratio of assists to turnovers. :param assists: Number of assists. :param turnovers: Number of turnovers. :return: The ratio :rtype: float """ try: ratio = float(assists) / turnovers except ZeroDivisionErro...
6304ad6eadcbad71aff9efb89f3376f419390b77
634,597
import os def eval_env_as_float(varname, standard_value) -> float: """ Parse varname as float and return it """ return float(os.getenv(varname, standard_value))
2412a576e4c5e41a7e047abeba3c76f866c52459
634,598
import importlib def get_class_from_path(full_class_name: str) -> type: """Get class from fully-qualified name.""" # Split class name into module and class: full_class_path = full_class_name.split(".") module_name = ".".join(full_class_path[:-1]) class_name = full_class_path[-1] # Import modul...
e637059103b71cebc0b09f90cf82a5cfb3f6fad5
634,599
def _GetMachineInfoPlistValue(key): """Returns value of given key in the machineinfo plist, or '' if not found.""" return ''
ce8a857607ca7cc22b54f788e46495b9f507da3d
634,600
def handle_fixed_bid(input_li, dv_li): """Handles DV360 fixed bid field by applying changes from the input_li to the dv_li Args: input_li: object representing the input line item from the input data dv_li: object representing the DV360 line item Returns: List of strings representing the fields to patch ...
ff5612f6fd823d59ee21f2b26d22cd40f56aeede
634,601
import subprocess def get_os_release_variable(key): """ Return value for key from /etc/os-release /etc/os-release is a bash file, so should use bash to parse it. Returns empty string if key is not found. """ return subprocess.check_output([ '/bin/bash', '-c', "source /etc/os-...
f3a8e6181408335cdb8b0fd20f892e6d51d31fb2
634,602
import sys import pathlib import os def getfile(str_params): """ Returns full path of the param file per system convention: linux/mac: ~/.str_params, Windows: APPDATA folder :param str_params: string that identifies parm file :return: string of full path """ if sys.platform == 'win32' or...
c9f63fde04fc2cb83ca2d6fe6bfc373d28340236
634,603
def is_active(obj, now): """Determine if an object is active.""" if not obj.start or obj.start <= now: if not obj.end or obj.end >= now: return True return False
845300fb218de73385843141c0f30a8a15354f56
634,604
def solution(A): # O(N) """ Write a function to group together all ascending sublists within a list a. >>> solution([1, 2, 10, 10, 8, 12, 5, 23, 1]) [[1, 2, 10, 10], [8, 12], [5, 23], [1]] >>> solution([3, 4, 5, 12, 2, 3, 5, 2, 5, -1]) [[3, 4, ...
d52027823bf89863ba9bd6b044eb5c0de2ddf105
634,606
from datetime import datetime def fmt_datetime(datestr): """ Reformats a date/time string so that it avoids any special characters. :param datestr: a string representing a date/time in 'YYYY-mm-dd HH:MM:SS' or 'YYYY-mm-ddTHH:MM:SS' format :returns: a string representing a date/time...
f83fac1b253a910f86938036bf79ea4c3ecee489
634,608
from pathlib import Path def get_not_existing_file(path_in): """If file exists it appends a number to ensure it dont :param path_in: String path to file :return: Updated path without conflicts """ path_in = Path(path_in) file_folder = path_in.parent file_name = path_in.name[:-len(path_in....
21c27e062f39322ab8958d57201e3cd0e43e2b06
634,609
import re def get_preset_queries(preset_file): """This function returns a list of CodeSonar preset queries contained in the provided preset file. Inputs: - preset_file: Absolute path to the preset file of interest. Outputs: - preset_queries: List of queries that are contained in the pres...
e0c6478c870727fcb11254b0e06b76012786d8c0
634,610
import os def scripts(): """ Get the scripts in the "scripts" directory Returns list List of filenames """ script_list = [] if os.path.isdir("scripts"): for item in os.listdir("scripts"): filename = os.path.join("scripts", item) if os.path.isfile(fi...
0be892fd9dd4bb6e9242af717efb60f36db82b2a
634,611
def validate_format(inp: str): """_summary_ Returns true if the format of the argument inp is one of the folowing: yymmdd-xxxx yy mm dd xxxx ...
1988b573863e3244935c5a9cd361481494dc5da9
634,612
def filter_username(username) -> str: """ Removes '/u/' and 'u/' from a username. :return: The filtered username. """ return username.replace("/u/", "").replace("u/", "")
95c548c30bfa8892063928c441ccc05cd94c40c7
634,613
def hello(_context): """ A solid definition. This example solid outputs a single string. For more hints about writing Dagster solids, see our documentation overview on Solids: https://docs.dagster.io/overview/solids-pipelines/solids """ return "Hello, Dagster!"
7e8427fe474e8559a6d6674b4ccfe6ed527639e8
634,614
def _find_longest_strs_form_results(long_strs, r): """Find various longest strings from a general list of extracted strings and text values assigned to object names. @param long_strs (list) A list of pretty long strings encountered during processing. @param r (list) A list of 2 element tuples wher...
7ab4bed5e811afbba20eb311a7b2614ab59d0bb6
634,615
def format(self, ndigit="", ftype="", nwidth="", dsignf="", line="", char="", **kwargs): """Specifies format controls for tables. APDL Command: /FORMAT Parameters ---------- ndigit Number of digits (3 to 32) in first table column (usually the node or element number). In...
4c01afdccc4066005a4db7d523ef1d13ccf74b36
634,616
import posixpath def normalize(path): """We use posixpath.normpath to support cross-platform path format. However, it doesn't handle None input. So we wrap it up.""" if path is None: return None return posixpath.normpath(path)
15da149a56a98d1493e8730b1a3a772ef273a10b
634,617
import time from functools import wraps import logging def retry(ExceptionToCheck, tries=4, delay_s=1, backoff=2): """Retry calling the decorated function using an exponential backoff. http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/ original from: http://wiki.python.org/moin/Pyt...
a6aed596d7e2c2017bf33ff42a8ef44d7a85c265
634,618
def generate_artifact_link(owner: str, name: str) -> str: """Generate link for downloading artifacts :param owner: Github repo owner name :type owner: str :param name: Github repo name :type name: str :returns: Link to api to download artifacts :rtype: str """ return f"https://api....
5451141bd8905be6447f82224621580b8f3d3606
634,619
def get_slack_channel_link(will, new_channel): """Retrieves a slack formatted link from a channel name. This should probably be moved somewhere else.""" channels = will.load("slack_channel_cache") channel = None for key in channels: # print(channels[key]) if channels[key]['name'] == new_...
f427a77bbbe06d7212439e20327085f008f09c45
634,620
from typing import List def intersection_time_optimized(a: List[int], b: List[int]) -> List[int]: """ O(n) space, O(n) time """ return list(set(a) & set(b))
755cd15ac5d7a7120baa7669e446d4a404baaad2
634,621
def get_route_edge_attributes( G, route, attribute=None, minimize_key="length", retrieve_default=None ): """ Get a list of attribute values for each edge in a path. Parameters ---------- G : networkx.MultiDiGraph input graph route : list list of nodes IDs constituting the pa...
2d3b8aeab2aebcbffc3fcbe177e139b30ae6e63f
634,622
def compute_acc(pred, truth): """ Compute accuracy """ return pred.max(dim=1)[1].eq(truth).sum() / len(pred)
a51015bf209bc9628314ab553b9e591fe7074106
634,623
import os import sys def config_file_paths(config_file): """Get a list of config file paths.""" config_filename = config_file.replace("../configs/", "beta_rec/") paths = [] paths.append(os.path.join(sys.exec_prefix, config_filename)) paths.append(os.path.join(sys.exec_prefix + "/local", config_fil...
f1d14d09090c14b9da8ba2ee2d10c02416b592ab
634,624
def single_freq_version(beam): """Make a single freq version with expected history.""" history_use = beam.history[: beam.history.find(" Combined data")] beam.select(freq_chans=1) beam.filename = [beam.filename[1]] beam._filename.form = (1,) beam.history = history_use return beam
5022f92194bc4e11ace9d3959396092ed5252fd8
634,625
import torch def mask_logits(vec, mask): """Mask `vec` in logspace by setting out of bounds elements to very negative values""" if mask is None: return vec if vec.dtype == torch.float32: mask = mask.float() return vec * mask - (1 - mask) * 1E20 else: raise NotImplementedError()
ccfdb6c1a6a5d5bbc24f761c3a13ee6e00438e09
634,626
def is_sorted(lst, le_cmp=None): """ Check if a list is sorted Args: lst (:obj:`list`): list to check le_cmp (:obj:`function`, optional): less than equals comparison function Returns :obj:`bool`: true if the list is sorted """ if le_cmp: return all(le_cmp(a, b) for ...
cf7b0aae21238876641031be15fae40012b4bf08
634,627
def _get_column_width(max_value, decimals=5): """Get width of column to pass to :func:`numpy.savetxt`, accounting for the decimal point and a sign +/-. """ return len(str(int(max_value // 1))) + decimals + 2
c6330b5e7e579dbea360a7e77705b60a453c1a76
634,629
import base64 import requests def gettxt(url, cookie=None, auth=None): """ Same as above, but returns as text blob """ headers = {"Content-type": "application/json", "Accept": "*/*"} if auth: xcreds = auth.encode(encoding="ascii", errors="replace") bauth = ( base64.encodebytes(...
8827a716d1e679cbee48eb269abf2ed535c49a5a
634,630
import torch def cosine_similarity(v1, v2): """Cosine similarity [-1, 1]. Parameters ---------- v1, v2 : Tensor Tensor with the same shape [batch_size, n_feature]. References ---------- - `Wiki <https://en.wikipedia.org/wiki/Cosine_similarity>`__. """ return torch.sum(t...
09e179274e00ef29d83e5ba93077de5d02db86bb
634,631
import random def crop_img_np(rgb, patch_size, center_crop=True): """ :param rgb: input numpy image. [H, W, C] :param patch_size: desired patch_size :param center_crop: :return: crop img in PIL """ # crop w, h, _ = rgb.shape if not (w, h) == (patch_size, patch_size): if not...
4fa4ed9709efedf425611ba80c06cd69ec81a517
634,632
def _prepare(): """ :return: Preparations section of wwatch3 run set-up and execution script :rtype: str """ preparations = ( "mkdir -p ${RESULTS_DIR}\n" "\n" "cd ${WORK_DIR}\n" 'echo "working dir: $(pwd)" >>${RESULTS_DIR}/stdout\n' "\n" 'echo "Startin...
46b43a67c1c32605838ecaec268be040f0fced50
634,633
def list2string(ls): """Print a list as a string""" s = " ".join(ls) return s
2c9e5b3a04cb2bf6f06c15bdf11ad9e3b827ce75
634,635
import random def shred(d, prefix=None, existing=False, contigs=10000, minsize=500, maxsize=10000): """ Generate random shreds of input fasta file :param d: Dictionary of sequences :param prefix: Prefix string to append to random contigs :param existing: Use existing prefix string ('|' ...
1bad7ebb04613c4edce26704fca533fe4bcf6121
634,636
import os def expandvars(path): """ Expand environment variables in ``path``. """ return os.path.expandvars(path)
bff2e55c5448fb65fcb42c5175d488e2b6b719be
634,637
def str2int(val): """ Converts a decimal or hex string into an int. Also accepts an int and returns it unchanged. """ if type(val) is int: return int(val) if len(val) < 3: return int(val, 10) if val[:2] == '0x': return int(val, 16) return int(val, 10)
dadddb6a82b3243735c1b0136a6ccc266820bd5b
634,638
def check_file_extension(filename, extension_list): """ Check if the extension file match with the authorized extension list :param string filename: Filename to check :param list extension_list: The list of extension the file have to match to :return: True if the extension is correct, False...
91f184fc940b8d71c77ebd56a5d229a864906421
634,639
def patch_resize(c, graph, node_select): """Dummy function for ``grow`` and ``swap`` to make output unchanged.""" return c
e00d3f37af64e7649dbbf4083c7a7e2c558c20f8
634,640
def drop(fields): """Generate example preprocessor removing given fields""" def preproc(refs): for k in list(refs): if k.startswith(fields): refs.pop(k) return refs return preproc
f6216befb5527196954be3fb04e52f816df85cf2
634,641
def human_bytes(n): """ Return the number of bytes n in more human readable form. """ if n < 1024: return '%d B' % n k = n/1024 if k < 1024: return '%d KB' % round(k) m = k/1024 if m < 1024: return '%.1f MB' % m g = m/1024 return '%.2f GB' % g
ddd920d7ccf62eabac882e05409e0625e3517b07
634,642
def format_integer(number, group_size=3): """Formats integers into groups of digits.""" assert group_size > 0 number = str(number) parts = [] while number: number, part = number[:-group_size], number[-group_size:] parts.append(part) number = ' '.join(reversed(parts)) return number
2e690a3bd1beb1cd5cb2c8f3504fc938ae63b377
634,643
def echo(obj): """ <Purpose> Serves as the test function for the XML-RPC client. <Arguments> obj: An object to return to the client. <Exceptions> None. <Side Effects> None. <Returns> The object passed in. """ return obj
006fa4a5b2e91cb404c00b54b0a546f37834211b
634,644
def list_diff(orig_list, new_list): """ 原有列表 和 新列表的差异 :param orig_list: {List} 原有列表 :param new_list: {List} 新列表 :return: add_list: {List} 待新增的列表 delete_list: {List} 待删除的列表 same_list: {List} 不变的列表/变更的列表 """ new_obj_map = {hash(obj): obj for obj in new_list} # 在new_list但不在orig_...
8032f526f8c021e392c389731400895e6e35afb6
634,645
def search_value(d, key, default=None): """Return a value corresponding to the specified key in the (possibly nested) dictionary d. If there is no item with that key, return default.""" stack = [iter(d.items())] while stack: for k, v in stack[-1]: if isinstance(v, dict): ...
bacf9eb5acff05a019fce7bb321306ac0d0ad460
634,646
def surrogate_pairs(code_point): """Return the UTF-16 high and low surrogates for a unicode code point. Arguments: code_point -- A string representation of the form 'U+xxxxx' or '\Uxxxxxxxx' Returns: A tuple containing the surrogate pairs as hexadecimal strings: (high, low), or (code_point,) i...
79f6e3dcbcc29001080fb3e656e1feb9747d635e
634,647
def _build_datasource_dict( str_heading, dict_config_entry): """ returns Metadata dict describing warehoused FRAM dataset's ETL config entry >>> entry1 = {'name':'My Great Dataset','query':'select 1 from dual' ... ,'db_file':'x.ini'} >>> d = _build_datasource_dict( 'great.Data1', entry1) >>> d[...
aa6dd2c10daff940bf2879a8947c14a7575a9b3f
634,648
from typing import Callable import functools def reset_index(func: Callable): """Filters dataset by one line changes in the hunk.""" @functools.wraps(func) def wrapper_reset_index(*args, **kwargs): dataset = func(*args, **kwargs) return dataset.reset_index(drop=True) return wrapper_res...
ba7d292772392d2410446c4251a40901362d1d67
634,649
def get_relative_coordinates(exon_exp_region, search_locus, directed, max_len=5000): """Get relative coordinates of expected regions. Formatting for LASTZ-CESAR optimizer. """ include_regions = list(exon_exp_region.values()) _, start_end_str = search_locus.split(":") start_str, end_str = start_...
48e40e3ecc61f323099166b987217786b026b64f
634,650
def _default_json_indent(): """ default spaces to indent when using json-pretty formatter """ return 4
fc6effc25d1e60bf1cb92546d554085f4fcbaffe
634,651
def prune_icd_hierarchy(list_of_sets): """ example: '26929004': [{'G30.1'}, {'G30.0'}, {'G30'}, {'G30.9'}, {'G30.8'}] reduces to [{'G30'}] """ icd_sections = set() for setA in list_of_sets: if len(setA) == 1: # only worry about single-item sets for now setA_item = list(setA)[0] sectio...
a0d59b8ea809872300bb2269f1654fe5b6b8d526
634,652
def collect(): """ Gathers data your chosen data source and returns it as a dictionary """ data = {} return data
a4fb48af24e5633000476f40771c20c33edfc889
634,653
def xy_axis(type=None, xy_text_size=14, namegap=25, xaxis_name="", xaxis_name_pos="middle", xaxis_rotate=0, xaxis_min=None, xaxis_max=None, interval="auto", yaxis_name="", yaxis_name_pos="middle", ...
546a77db33934bf11e80c9221cdd1271eaeb67e8
634,655
def get_ip(format=None, param_callback=None): # noqa: E501 """Get your public IP address # noqa: E501 :param format: Response format :type format: str :param param_callback: JSONP callback function name :type param_callback: str :rtype: object """ return 'do some magic!'
2b4dfc0b67679d7baba29c3fabf49f9181842373
634,656
def outage_probability( instantaneous_rate_primary, instantaneous_rate_secondary, target_rate_primary_user, target_rate_secondary_user, ): """Returns the outage probability for the system, primary user, and secondary user for SNR value in linear. Arguments: instantaneous_rate_p...
3ff0c767ffbb6aa606160372b766a5ffe424b1ef
634,657
def parseMessage(store, raw_item, status_data): """ Method parses and forms status statments :param store: list of store name :param raw_item: list of item selection (0 or 1 for toilet paper or handsanitizer) :param status_data: contains the raw values of the rating, date, and username for a particular...
6475fa18846202ed0d25d73ffe410df485fd7d3c
634,658
import colorsys def get_spaced_colors(n): """Create n evenly spaced RGB colors :param n: number of colors needed source: https://stackoverflow.com/questions/876853/generating-color-ranges-in-python """ hsv_tuples = [(x * 1.0 / n, 0.5, 0.5) for x in range(n)] rgb_tuples = map(lambda x: colorsy...
95245962fe719ec6eb13d79d2b5dcbf23900a2ae
634,659
def avg_delay_specified_vehicles(env, veh_ids): """Calculate the average delay for a set of vehicles in the system. Parameters ---------- env: flow.envs.Env the environment variable, which contains information on the current state of the system. veh_ids: a list of the ids of the veh...
8686f3a97215f5ff5e582f4bbc716bcd1b560f7d
634,660
import pandas import os def load_ref_panel_description(ref_panel): """ Load the reference panel table as a Pandas DataFrame. Parameters ---------- ref_panel: str Path to the table file describing the reference panel. It relates a chromosome name to 4 references files in Impute2 fo...
3e659a6e6cf6f3edbeb8b58736e5c0a3e9b6b6e0
634,662
def display_value(value): """ Dropdown value change """ return 'You have selected "{}"'.format(value)
fda67fba763778f83c18e01060f6fa97d28d63ed
634,664
def mgen(x): """Defers the master parameter until bound to a master""" def _a(self, *args): def _b(master): return x(self, master, *args) return _b return _a
34f73849e02a8188a8fc682dbcb39be098f63e39
634,666
def process_tweet(text, target): """Check it's ok and remove some stuff""" if (text.startswith("RT ") or "@" in text or "#" in text or "http" in text): return None text_lower = text.lower() if target.lower() not in text_lower: return None exclude...
7f28350cd6d9328986d2291db250fb6658599cbb
634,667
def k_min(r_m: float, p: float) -> float: """Calculates minimum required capital for return to outweigh brokerage. Args: k: capital. p: brokerage as fixed value. Returns: Minimum capital. """ return p + p / r_m
63d6bd9cba207b27105fee0ae05eaa80617093b4
634,668
def get_all_moves(coord): """ Return a list of all coordinates reachable from this one """ return [{'x': coord['x'], 'y': coord['y'] + 1}, {'x': coord['x'], 'y': coord['y'] - 1}, {'x': coord['x'] + 1, 'y': coord['y']}, {'x': coord['x'] - 1, 'y': coord['y']}]
307459c52f5d6baa68ec1a1b9088e74d6629d6b7
634,670
def dfs_tree_to_list(nodes): """ 将树结构转成list :param nodes: :return: """ ids = [] for node in nodes: ids.append(node["id"]) children = node.get("children", []) if children != []: ids = ids + dfs_tree_to_list(children) return ids
9fd29b85fa6a9c2355e6712f533a6e47e3fccb26
634,671
def _needs_german_slugifying_rules(lang, locale): """Checks whether the given language name with corresponding locale needs German slugifying rules.""" if locale.split('_')[0] in {'de', 'gsw'}: # German and Allemanic German return True if lang in {'de', 'de_at', 'de_ch', 'de_de', ...
038c1b0da7d15e77aaeb86998f6253fb459fb1e1
634,672
def below(prec, other_prec): """Whether `prec` is entirely below `other_prec`.""" return prec[1] < other_prec[0]
20337d8d507fc3b4a85c5c2abe5c8c014437d3af
634,673
def _find_lines_from_point(d={}, ptag=-1): """Find lines that have the given point tag Parameters ---------- d : Dictionary GMSH dictionary ptag : int point tag Returns ------- ltag : int List of line tags """ lines = list() for s_data in d.values():...
de2d5234161208906c05c5a013b70312e9c056c1
634,674
import numpy def bincount(X, bins=None): """ Counts the elements in X according to bins. Inputs: - X: A 1-D list or numpt array or integers. - bins: (optional): a list of elements. If bins is None, bins will be range range(min(X), max(X)+1). If bins is provided, bin...
6564c401bf707ea87071dc3ba2e28eef0bfa2473
634,675
import os import re def largest_filename_in_dir(path, pattern): """Returns the largest numbered file matching pattern in dir""" regex_pat = pattern.replace('%', '([0-9]{3})') max_page = 0 for f in os.listdir(path): match = re.search(regex_pat, f) if match is not None and int(match.grou...
d104f3bda01ab4246917cc476689962414affc05
634,676
import re def removeEmoticons(text): """ Removes emoticons from text """ text = re.sub(':\)|;\)|:-\)|\(-:|:-D|=D|:P|xD|X-p|\^\^|:-*|\^\.\^|\^\-\^|\^\_\^|\,-\)|\)-:|:\'\(|:\(|:-\(|:\S|T\.T|\.\_\.|:<|:-\S|:-<|\*\-\*|:O|=O|=\-O|O\.o|XO|O\_O|:-\@|=/|:/|X\-\(|>\.<|>=\(|D:', '', text) return text
1080defcc0b01761420581fddf38fc5ad0106264
634,677
def _crc_update(crc, data, mask, const): """ CRC8/16 update function taken from _crc_ibutton_update() function found in "Atmel Toolchain/AVR8 GCC/Native/3.4.1061/ avr8-gnu-toolchain/avr/include/util/crc16.h" documentation. @param[in] crc current CRC value @param[in] data next byte of data @p...
6538b1720faca541b3ab741451e0dc9dcd20c77c
634,678
from typing import Counter def one_pair_finder(hand): """ Takes a 5-card hand, concats, only takes ranks If we get 1 pair, returns list: [4, pair rank, kicker1, kicker2, kicker3] """ cards = ''.join(hand)[::2] if Counter(cards).most_common(4)[0][1] == 2: if Counter(cards).most_common(4)[1][1] == 1: pair =...
c8a4b0b289d67d199437bf7c3467242c7393c46f
634,679
import torch def generate(net, image): """Reproduce the input with trained VAE.""" with torch.no_grad(): return net.forward(image)
4be6d982369f9d4f5e26c1119870f16a8d64ccfc
634,680
def xor(bytes_1, bytes_2): """XOR two bytearrays of the same length.""" l1 = len(bytes_1) l2 = len(bytes_2) assert l1 == l2 result = bytearray(l1) for i in range(l1): result[i] = bytes_1[i] ^ bytes_2[i] return result
69e2b5bb175280da88eac2cecba7f512bf18ab8a
634,682
def cgi2dict(form, linelist): """Convert the form from cgi.FieldStorage to a python dictionary""" params = {'linelist': linelist.value} for key in form.keys(): if key != 'linelist': params[key] = form[key].value return params
c935c8f3393439a6632cd4a70c7a684c3ce42a85
634,683
import json def load_word2vec(word2vec_json_file): """ generate the vocabulary lookup """ word2vec = json.load(open(word2vec_json_file, "r")) print ("padding " + str(word2vec["padding"][0])) return word2vec
faac220b579b42adb470195caf1f86ac43b7364f
634,684
def _2d_distance_squared(position1, position2): """calculate the square of the distance bwtween two 2D coordinate tuples""" return (position1[0] - position2[0]) ** 2 + (position1[1] - position2[1]) ** 2
3ad48b310fa6cbd238dc8c52738432d49a1263de
634,685
def read_target_positions(file_path, filter_chromosomes): """ reads a bed file and returns a list of tuples containing genomic coordinates """ if filter_chromosomes==None: filter_chromosomes = [] else: print('filtering out: ' + ' '.join(filter_chromosomes)) with open(file_path) a...
37f03029ebfb5e6be70c5f9d0abd59d1887ff8ac
634,687
from typing import List from typing import Tuple from typing import Dict from typing import Union def tags_to_filter( tags: List[Tuple[str, str]] ) -> List[Dict[str, Union[str, List[str]]]]: """Turn list of tuples with tag name and value in to AWS format.""" return [{"Name": f"tag:{tag[0]}", "Values": [ta...
5d44342d1611b1e1b1d70bb400bd3d600bcfe05b
634,688
def get_unbound_arg_names(arg_names, arg_binding_keys): """Determines which args have no arg binding keys. Args: arg_names: a sequence of the names of possibly bound args arg_binding_keys: a sequence of ArgBindingKey each of whose arg names is in arg_names Returns: a sequence of...
92d5ff319c1f96bb246a5d65c93b05b3440df508
634,689
def calculate_time_features(df): """Clagged and rolling mean features of the sales data. Args: df (pd.DataFrame): Dataframe with the sales data. Returns: Dataframe with the sales data including lag and rolling features. """ dayLags = [28] lagSalesCols = [f"lag_{dayLag}" for dayL...
5b46d2b2d938bff4852139ca2db051281eb4336b
634,690
import logging def filter_loadings(df, index): """ Filters loadings in the given table to PC 2. :param pd.DataFrame df :param int index :rtype pd.DataFrame """ logging.info('Filtering loadings') result = df.iloc[:, [index]] result = result.loc[result.iloc[:, 0] != 0.] lo...
0f9f1543dbb6e2297ac1407573ba93238c082ebd
634,691
def apply_type_recognizers(recognizers, type_obj): """Apply the given list of type recognizers to the type TYPE_OBJ. If any recognizer in the list recognizes TYPE_OBJ, returns the name given by the recognizer. Otherwise, this returns None.""" for r in recognizers: result = r.recognize(type_obj)...
199c99016a33979638c2fb14b8ed38a125267f7b
634,692