content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def remove_zeros(r, M): """ image processor to remove zero :param r: Source image measure :param M: Cost matrix :return: Processed r and M with zeros removed """ M = M[r > 0] r = r[r > 0] return r, M
d742326d0a18f08b26badd06095677bec9bd03d2
681,538
def cycle_slice(sliceable, start, end): """Given a list, return right hand cycle direction slice from start to end. Usage:: >>> array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> cycle_slice(array, 4, 7) # from array[4] to array[7] [4, 5, 6, 7] >>> cycle_slice(array, 8, 2) # from arra...
15ef9e3cb5243e31d2d4cbb4717955ff0e611a6e
681,539
import importlib def make_checker(checker_cls, tmp_dir, **kwargs): """Returns a checker object. Parameters ----------- checker_cls : str the Checker class absolute path name. tmp_dir : string directory to save temporary files in. kwargs : dict keyword arguments needed ...
4a617e58b6e4cffc95b1c9aabe4ceca5e0f65f2a
681,540
def index_by_iterable(obj, iterable): """ Index the given object iteratively with values from the given iterable. :param obj: the object to index. :param iterable: The iterable to get keys from. :return: The value resulting after all the indexing. """ item = obj for i in iterable: ...
b167775ba331244361492e64e01cb1db92410f67
681,541
def create_8021Q_vea_cmd(lpar_id, slotnum, port_vlan_id, addl_vlan_ids): """ Generate IVM command to create 8021Q virtual ethernet adapter. :param lpar_id: LPAR id :param slotnum: virtual adapter slot number :param port_vlan_id: untagged port vlan id :param addl_vlan_ids: tagged VLAN id list ...
b0d745c12e9f6c192f1d9c54d94c33a737e1d011
681,543
def rgb_2_luma(color: tuple) -> int: """ Calculate the "brightness" of a color. ...and, yes I know this is a debated subject but this way works for just fine my purposes. :param color: a tuple of RGB color values eg. (255, 255, 255) :returns: luminance "brightness" value """ r, g, b = ...
d00760dee46a2bb7e9cb1ae45d540e431a227590
681,544
from typing import Sequence from typing import List from typing import Set def expand_ranges(ranges: Sequence[Sequence[int]], inclusive: bool = False) -> List[int]: """Expand sequence of range definitions into sorted and deduplicated list of individual values. A range definition is either a: * one eleme...
bd18736f6def6f22195b3802046fc77dea3c8623
681,547
def GetJidFromHostLog(host_log_file): """Parse the me2me host log to obtain the JID that the host registered. Args: host_log_file: path to host-log file that should be parsed for a JID. Returns: host_jid: host-JID if found in host-log, else None """ host_jid = None with open(host_log_file, 'r') as...
4e8f7d7ff3284026025fb97d59b9be4af16c81ee
681,551
def compose2(f, e): """Compose 2 functions""" return lambda x: f(e(x))
9e48818b5c4150d1af138935c712e31c58a1f9c1
681,553
def filtered_tooltip(options, filter): """Returns tooltip for the filter icon if the filter matches one of the filter options """ for option in options: if filter == option[1]: return "Showing only %s"%option[0] return ""
28cb83a353f007a1e6042e91c8f3f66ac2279ea1
681,556
def _valvar(unk, vardict): """Determines if an unknown string is a value or a dict variable. Parameters ---------- unk : float or str The unknown value, either a float or a dictionary key. vardict : dict The dictionary to be searched if unk is not a float. Returns ------- ...
88d70cd5e62578ae90d699627791eb6c5fe33fc7
681,557
def rectangle(a, b): """ Return classic logic rect function: ^ ...... | | | |___|____|___ a b """ return lambda x, a=a, b=b: 1. if a <= x <= b else 0.
f8673d1edf43f4d898b21742c401af8f818166a3
681,559
def fnCalculate_Bistatic_RangeRate(speed_light,tau_u1,tau_d1,tau_u2,tau_d2,tc): """ Calculate the average range rate. eqn 6.37 in Montenbruck 2000. tc = length of integration interval, i.e. length of CPI Created: 04/04/17 """ range_rate = (speed_light/tc)*(tau_u2+tau_d2-tau_u1-tau_d1); # removed 0.5 factor. 19.0...
68093a69b3290d43fd42ce62489167b4e50a51c6
681,565
from typing import OrderedDict def get_wall_duration(op_names, all_ops, pid_list=(11, 7, 13, 15, 9)): """ Calculates wall duration for each op in op_names. Params: op_names: list (str), names of ops of interest. pid_list: list (str), names of pid to include. all_ops: output of get_all_ops(). ...
ba2af449c1c1b96108ca3ddbc97ff0bc31064651
681,569
def read_biosids(bdfiles, verbose=False): """ REad the biosample ID files. :param bdfiles: iterable of Files with biosample IDs :param verbose: more output :return: a dict of the sample_name and biosample ID """ biosids = {} for fl in bdfiles: with open(fl, 'r') as f: ...
02d8f6790645c85a8257a9ed1bf635e5ac89da63
681,571
import importlib def _get_module_attr(module_name, attribute_name): """Import a module and get an attribute from it. Args: module_name (str): The module name. attribute_name (str): The attribute name. Returns: Any: The attribute. Raises: ModuleNotFoundError: The modu...
485f36fbedc2784968bcc5f393bbd3f2c5867883
681,574
def simple_app(environ, start_response): """Simplest possible WSGI application object""" status = '200 OK' response_headers = [('Content-type','text/plain')] start_response(status, response_headers) return ['Hello world!\n' for i in range(100)]
59fa4d9978cf29cfb2989afb5ae6197c1b8ee054
681,575
def ozone_ppm(results, temperature=22): """ Calculate ppm for given results array with Mol/m3 concentrion :param results: array of results in Mol/m3 :param temperature: gas measurement temperature in celsius :return: array of ppm """ P = 1e5 # pascal V = 1 # m3 R = 8.314472 # JK-...
01f01ab2f91d36c2fd2e3dfbddab598fe4e490e5
681,577
def css_class(field): """ Returns widgets class name in lowercase """ return field.field.widget.__class__.__name__.lower()
e6a555199c9b6762758837e0f7794bd69dc7fe09
681,578
from pathlib import Path def get_file(filepath): """Return the content of a file in the test_files directory.""" full_path = Path(__file__).parent / 'test_files' / filepath with open(full_path, 'rb') as file: return file.read()
8f0a03bb85cb3d0fdb26ad683bf103c5df1b30a9
681,579
import ipaddress def calc_prefix(arg, addresses): """Calculates the prefix for the list of addresses. Creates the prefix from arg if one is supplied, otherwise computes the prefix from the addresses. """ # This can throw an exception if they supplied an invalid netmask. if arg: ...
6ed123dfa15c312ff31899a63451daaa540516bb
681,584
def color_hex_to_dec_tuple(color): """Converts a color from hexadecimal to decimal tuple, color can be in the following formats: 3-digit RGB, 4-digit ARGB, 6-digit RGB and 8-digit ARGB. """ assert len(color) in [3, 4, 6, 8] if len(color) in [3, 4]: color = "".join([c*2 for c in color]) ...
70089c50afa569327d10413b1e0693697194988f
681,588
def msg(m, ctx): """Check if the message is in the same channel, and is by the same author.""" return m.channel == ctx.channel and m.author == ctx.author
38c4f72bb69c8e491dc9d8816060347e9bbac1b2
681,593
import torch def all_or_none_accuracy(preds, targets, dim=-1): """ Gets the accuracy of the predicted sequence. :param preds: model predictions :param targets: the true targets :param dim: dimension to operate over :returns: scalar value for all-or-none accuracy :rtype: float32 """ p...
4e46720996a383b601f7de332945182971f53988
681,596
def get_ee_points(offsets, ee_pos, ee_rot): """ Helper method for computing the end effector points given a position, rotation matrix, and offsets for each of the ee points. Args: offsets: N x 3 array where N is the number of points. ee_pos: 1 x 3 array of the end effector position. ...
d7903638720102c6d4e3b3664301f09ba10029df
681,599
import math def get_observation_data(observation, t): """ Get observation data at t. """ vars = ['Foil', 'Fw', 'Fs', 'Fa', 'Fb', 'Fc', 'Fh', 'Fg', 'Wt', 'discharge', 'DO2', 'T', 'O2', 'pressure'] # convert to pH from H+ concentration pH = observation.pH.y[t] pH = -math.log(pH) / math.log(1...
7e85f2ce3db3e37228118d7c852f1740168268ef
681,602
def num_cooperators(population): """Get the number of cooperators in the population""" return population['Coop'].sum()
fb61a4100a0fc72b5cdd45b3500a4c4f35e09c75
681,606
def int_or_zero(s): """ >>> int_or_zero('') 0 >>> int_or_zero('10') 10 """ return 0 if not s else int(s)
5615432033d88be8183ab502719730e93dc7d078
681,608
def split_company_name_notes(name): """Return two strings, the first representing the company name, and the other representing the (optional) notes.""" name = name.strip() notes = u'' if name.endswith(')'): fpidx = name.find('(') if fpidx != -1: notes = name[fpidx:] ...
4848d5f56420fe6da2c8ad62a43a4ab31b23baba
681,611
def test_asyncio_request_response(connection, receiver): """ Test request/response messaging pattern with coroutine callbacks """ async def endpoint_handler(message): return message.payload + "-pong" connection.register_async_endpoint(endpoint_handler, "test.asyncio.request") connectio...
5c055e5a2b41a8170cd21062fff22c8e95f4ac15
681,615
import random def stat_check(stat1, stat2): """ Checks if stat1 wins over stat2 in competitive stat check. """ roll1 = random.randrange(stat1) roll2 = random.randrange(stat2) return roll1 >= roll2
64b96fad051d20c182dfbf719403590951f1b13c
681,616
def artists_to_mpd_format(artists): """ Format track artists for output to MPD client. :param artists: the artists :type track: array of :class:`mopidy.models.Artist` :rtype: string """ artists = list(artists) artists.sort(key=lambda a: a.name) return ', '.join([a.name for a in arti...
b96c191e58af39485fe9e5d8d5b4eb444ba55367
681,617
def flatten_substitution_choices(subs_choices): """ For a given dict {expr: (expr1, expr2)} returns a list of all possible substitution arising from choosing to subs expr by expr1 or expr2. """ subs_choices = subs_choices.copy() if not subs_choices: return [{}] result = [] expr ...
2661b657aac723c67df409aadc78b4eae6c86dd5
681,618
from typing import Any def cmp(a: Any, b: Any) -> int: """ Restores the useful `cmp` function previously in Python 2. - Implemented according to [What's New in Python 3.0](https://docs.python.org/3.0/whatsnew/3.0.html#ordering-comparisons). Args: a: An object. b: An object. Retu...
782eef5699c5f0bc55ba57d494ef69a1737a6c78
681,620
def forbidden_view(message, request): """Get JSON response for a 403 status code.""" request.response.status = 403 return {'message': str(message), 'status': 403}
0b8b70dff047823c6ba11a4d8f01efb2757efb2d
681,622
def normal_diffusion(times, diffusion_coefficient, dimensions=2): """Models the relationship between mean squared displacement and time during a normal (Brownian) diffusion process. During normal diffusion the mean squared displacement increases linearly with time according to the Einstein relation. ""...
b09b183b381a81d168e4f138245be02ee1ae9a39
681,624
import re def check_mac(mac_address, capital_letters=True): """ Check mac address is valid. Either format of 52:54:00:AE:E3:41, or 52-54-00-AE-E3-41 """ if capital_letters: regex = r'^([0-9A-F]{2}[:]){5}([0-9A-F]{2})$' else: regex = r'^([0-9a-f]{2}[:]){5}([0-9a-f]{2})$' ...
38a574f9d888267f5a74d2a70ed353ed0e6fdc5e
681,626
def electrolyte_diffusivity_Valoen2005(c_e, T): """ Diffusivity of LiPF6 in EC:DMC as a function of ion concentration, from [1] (eqn 14) References ---------- .. [1] Valøen, Lars Ole, and Jan N. Reimers. "Transport properties of LiPF6-based Li-ion battery electrolytes." Journal of The Electroch...
0becd5997ae29ee40a1e2fa38f66386476a706e6
681,628
def pascal_voc_palette(num_cls=None): """ Generates the PASCAL Visual Object Classes (PASCAL VOC) data-set color palette. Data-Set URL: http://host.robots.ox.ac.uk/pascal/VOC/ . Original source taken from: https://gluon-cv.mxnet.io/_modules/gluoncv/utils/viz/segmentation.html . `num_cls`: t...
4859082ad0a02a4bbc7715bcabd01774758c214d
681,629
def R(units): """Universal molar gas constant, R Parameters ---------- units : str Units for R. Supported units ============= =============================================== ============ Unit Description Value ...
485ccef1da6e865406420955b024f479356674de
681,633
import torch def compute_pdist_matrix(batch, p=2.0): """ Computes the matrix of pairwise distances w.r.t. p-norm :param batch: torch.Tensor, input vectors :param p: float, norm parameter, such that ||x||p = (sum_i |x_i|^p)^(1/p) :return: torch.Tensor, matrix A such that A_ij = ||batch[i] - bat...
ae997a59c7e208fca4dc80ee1f7865320edeff86
681,634
import socket import struct def get_ip_mreqn_struct(multicast_address, interface_address, interface_name): """ Set up a mreqn struct to define the interface we want to bind to """ # See https://github.com/torvalds/linux/blob/866ba84ea30f94838251f74becf3cfe3c2d5c0f9/include/uapi/linux/in.h#L168 ip_...
69f3e41986d89ec0ee14ff1e1b9a27450761543e
681,636
def _get_id(mf, url=None): """ get the uid of the mf object Args: mf: python dictionary of some microformats object url: optional URL to use in case no uid or url in mf Return: string containing the id or None """ props = mf['properties'] if 'uid' in props: return props['uid'][0] elif 'url' in props:...
51ecd4f77161dec47fbed1faa395c68b2698491d
681,637
def get_worksheet_names(workbook): """ Gets the names of all the worksheets of the current workbook. :param workbook: Current workbook to manipulate. :return: A list of all the worksheets' names of the current workbook. """ return workbook.sheetnames
738423827f9fe4b1a016a31e032fc389d23ccc68
681,643
import time def is_task_successful(task, retry=10 , interval=5): """ Method to check the task state. :param task: VMware task. :param retry(int): Number of Retries. :param interval(int): Interval between each retry. :return: bool( """ while retry > 0: task_status = str(task.inf...
efc31efd20a5a77fab50862971ab132d068f02a7
681,644
import torch def binary_acc(y_pred, y): """Calculates model accuracy Arguments: y_pred {torch.Tensor} -- Output of model between 0 and 1 y {torch.Tensor} -- labels/target values Returns: [torch.Tensor] -- accuracy """ y_pred_tag = torch.round(y_pred) correct_r...
81099841fa75b8302bbc9c4044e62b8ca01a5828
681,646
def cvode_stats_to_dict(path: str) -> dict: """ Converts a Delphin integrator_cvode_stats file into a dict. :param path: path to folder :return: converted tsv dict """ file_obj = open(path + '/integrator_cvode_stats.tsv', 'r') lines = file_obj.readlines() file_obj.close() tsv_dict...
39b5e78d142b8ad01f5cdd55130c1e05673eab17
681,647
def _scale_col_to_target(col, target, metric_func): """ Scale a column's values so that in aggregate they match some metric, for example, mean, median, or sum. Parameters ---------- col : pandas.Series target : number metric_func : callable Must accept a Series and return a numb...
3d7465d29917b133bc8cbaa56924bb2f08782a10
681,651
def binlogs_to_backup(cursor, last_binlog=None): """ Finds list of binlogs to copy. It will return the binlogs from the last to the current one (excluding it). :param cursor: MySQL cursor :param last_binlog: Name of the last copied binlog. :return: list of binlogs to backup. :rtype: list ...
227ab73ece3df209f53cdd061c54f524cc5943b1
681,654
def performanceCalculator(count, avg, std, maxv, countref, avgref, stdref, maxvref): """ =========================================================================== Performance calculator function =========================================================================== Calculate performance bas...
92f98baa720f19a1e6f5dbcdb610b38036c49c6c
681,655
import torch def weighted_mean_rule_func(predictions: torch.Tensor, weights: torch.Tensor, *_) -> torch.Tensor: """ Mean the predictions of different classifier outputs with classifier weights. Args: predictions: outputs of the base models weights: a one-dimens...
b88bf7cc162adc1b968a34dca0380f7686ae875d
681,657
def set_val_if_dict( dct, key, val ): """ Set the { ... `key`:`val` ... } only if `dct` is a dictionary """ try: dct[ key ] = val return True except (TypeError, KeyError): return False
abeef6e3039b206ac661c9abc8e7403c7b0a9e50
681,658
import torch from typing import Optional def weighted_average( x: torch.Tensor, weights: Optional[torch.Tensor] = None, dim=None ) -> torch.Tensor: """ Computes the weighted average of a given tensor across a given dim, masking values associated with weight zero, meaning instead of `nan * 0 = nan`...
e2422c4b4f1de49b4273b2d9704fd38495a337e3
681,660
def check_sudoku(sudoku): """ Funktion zur Überprüfung einer Sudoku-Lösung auf Korrektheit. Als Eingabe an die Funktion wird die Sudoku-Lösung in Form einer Liste von Listen übergeben. Die Funktion gibt als Ergebnis einen Wahrheitswert zurück. """ # Prüfe Zeilen # Gehe jede Zeile durch for ...
5d39cd4ab1bc3116bc745cf10cc68a7b00dde533
681,661
import re def _is_pull_request_base_branch_match(pull_request: dict, base_branch: str) -> bool: """ Determine if the pull request represents a notification for a base branch we should consider. :param pull_request: Pull request section of payload to examine :type: :class:`~dict` :param base_branc...
30c7d0e495419ecd4eee6949d3d851de01192734
681,662
def get_contigous_borders(indices): """ helper function to derive contiguous borders from a list of indices Parameters ---------- indicies : all indices at which a certain thing occurs Returns ------- list of groups when the indices starts and ends (note: last element is t...
66c3dd37573e09763dde20f1428f1101341fefe1
681,663
import math def hsvToRGB(h, s, v): """Convert HSV color space to RGB color space @param h: Hue @param s: Saturation @param v: Value return (r, g, b) """ hi = math.floor(h / 60.0) % 6 f = (h / 60.0) - math.floor(h / 60.0) p = v * (1.0 - s) q = v * (1.0 - (f*s)) t = v * (1.0 - ((1.0 - f) * s)) D = {0...
7bb1d7268ba3c8b91adc4872521f75f8e699376e
681,664
def is_too_similar_for_axes(word1, word2): """ Checks if the words contain each other """ return word1 in word2 or word2 in word1
7156490dcaac3081fd44845ee6350906fd196f19
681,665
def dominance(solution_1, solution_2): """ Function that analyze solutions dominance. Parameters ----------- :param solution_1: Solution :param solution_2: Solution Returns --------- :return int If solution_1 dominates solution_2 -> return 1 :return -1 If soluti...
2b6b39e12afed85a9064cb36d0ecb9c3473bac61
681,666
from typing import List def _parse_csv(s: str) -> List[str]: """Return the values of a csv string. >>> _parse_csv("a,b,c") ['a', 'b', 'c'] >>> _parse_csv(" a, b ,c ") ['a', 'b', 'c'] >>> _parse_csv(" a,b,c ") ['a', 'b', 'c'] >>> _parse_csv(" a,") ['a'] >>> _parse_csv("a, ") ...
62c83f091e49fd75b30fe9cca46c2bf4175e959a
681,667
def get_antigen_name(qseqid): """ Get the antigen name from the BLASTN result query ID. The last item delimited by | characters is the antigen name for all antigens (H1, H2, serogroup) @type qseqid: str @param qseqid: BLASTN result query ID @return: antigen name """ if qseqid: ...
02f63245021a09cf02db27f34a5241070a5c8b3b
681,674
import requests def get_img_content(img_url): """ 函数功能:向服务器请求图片数据 参数: img_url:图片的链接地址 返回:图片的内容,即图片的二进制数据 """ header2 = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36' try: r = requests.get(img_url, headers...
1f00ddbfeddb5b2db8c0e57d9cf8ed96cb763087
681,675
def normalize_matrix(transformer, matrix): """Normalize count matrix to scale down the impact of very frequent tokens :param transformer: A Sklearn TfidfTransformer object :param matrix: An array representing a term document matrix, output of CountVectorizer.fit_transform """ matrix_normalized ...
069f5c3878d0a795dcefd906ba5d03a3c333f5f2
681,680
import tempfile import zipfile def unpack_zip(zip_ffn): """ Unpacks zip file in temp directory Parameters: =========== zip_ffn: str Full filename to zip file Returns: ======== temp_dir: string Path to temp directory """ #build ...
95ee3c9d3f215fe91a949d6de3b296a63005d775
681,683
def _colors(strKey): """ Function gives access to the RxCS console colors dictionary. The Function returns a proper console color formating string (ANSI colors) based on the key given to the function. |br| Available keys: 'PURPLE' 'BLUE' 'GREEN' 'YELLOW' 'RE...
90f09148ac709299d1666930e7c675595d04663f
681,689
def get_target_name(item): """Take a query record, split the name field, and return the target name.""" return item.file_location.split('/')[-2].split('_')[-1]
f1fce4b4886b68a845267e35eaab47111969548a
681,690
import re def split_by_punct(segment): """Splits str segment by punctuation, filters our empties and spaces.""" return [s for s in re.split(r'\W+', segment) if s and not s.isspace()]
25e94ca97b13bf163a2f2e3f1c9d6038747a8fea
681,697
import re def filename_safe(name: str, lower: bool = False) -> str: """ Perform the necessary replacements in <name> to make it filename safe. Any char that is not a-z, A-Z, 0-9, '_', ' ', or '-' is replaced with '_'. Convert to lowercase, if lower=True. :param lower: If True, apply str.lower() to res...
ba1149d0b375184d326fc03c5b4a7748794254bf
681,698
from typing import Tuple from typing import Optional def _parse_key_value_pair(arg: str) -> Tuple[Optional[str], str]: """ Parameters ---------- arg : str Arg in the format of "Value" or "Key=Value" Returns ------- key : Optional[str] If key is not specified, None will be t...
87170907e969727950320e524f45c9be7045ad9a
681,699
def str_to_bool(val: str) -> bool: """Converts a string to a boolean based on its value. :param val: string being converted :return: boolean value expressed in the string :raises: ValueError if the string does not contain a value corresponding to a boolean value """ if isinstance(val, str): ...
dbb78367a1db8461b20b44d521bf8522b8d9a048
681,702
import functools def require(required): """ Decorator for checking the required values in state. It checks the required attributes in the passed state and stop when any of those is missing. """ def decorator(function): @functools.wraps(function) def wrapper(*args, **kwargs): ...
b92675b5602ad96a68db858b6938c0de40820fec
681,706
def GetNestedAttr(content, nested_attr, default=None): """Get the (nested) attribuite from content. Get the (nested) attribute from the content dict. E.X. content is {key1: {key2: {key3: value3}}, key4: value4} nested_attr = [key1] gets {key2: value2, {key3: value3}} nested_attr = [key1, key2] gets {key3: va...
a35074088e58739f0ac9cfcf264e8f7f7e3de566
681,709
import json def format_json(json_string): """Converts a minified JSON str to a prettified JSON str. Args: json_string (str): A str representing minified JSON. Returns: (str): A str representing prettified JSON. """ parsed = json.loads(json_string) return json.dumps(parsed, in...
cb0d60db6e4f1a0044e24405dafc222a6af5ac1b
681,712
def wrapped_list(list, which): """ Selects an element from a list, wrapping in either direction. """ if which < 0: ix = len(list) + (which % len(list)) else: ix = which % len(list) return list[ix]
122fd9f24969568bd0dc305aa35f3a9912a61af2
681,716
def deploy_command(deb_package, hostname, username = "pasha"): """Command for start deployment on `target_hosts` of package. Args: deb_package (File): Debian package to install hostname (str): host for installation username (str): SSH user for installation process Returns: ...
32532499bb801678ff9a542e86edec30d46bcf89
681,722
def parameter_values(params, **kwargs): """Return a copy of the parameter list, substituting values from kwargs. Usage example:: params = parameter_values(params, stock='GOOG', days_back=300 ) Any parameters not supplied will keep their original value. """ ...
aac886173c6604b317b9ad582beb279adc165b67
681,723
def gf_TC(f, K): """ Return trailing coefficient of ``f``. **Examples** >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_TC >>> gf_TC([3, 0, 1], ZZ) 1 """ if not f: return K.zero else: return f[-1]
9e478fcbd3eb7daa7d7f300d1d2f2a8155bef8e4
681,725
import re def utc_offset_string_to_seconds(utc_offset: str) -> int: """match a UTC offset in format ±[hh]:[mm], ±[h]:[mm], or ±[hh][mm] and return number of seconds offset""" patterns = ["^([+-]?)(\d{1,2}):(\d{2})$", "^([+-]?)(\d{2})(\d{2})$"] for pattern in patterns: match = re.match(pattern, utc...
6b1a0fa73c6cdfd71824a4079d2c5d6e8b4f6ab3
681,726
def output_to_IOB2_string(output): """ Convert Stanford NER tags to IOB2 tags. """ iob2_tags = [] names = [] previous_tag = 'O' for _, tup in enumerate(output): name, tag = tup if tag != 'O': tag = 'E' if tag == 'O': iob2_tags.append(tag) ...
1b31df0b72fff2317f3658c6c085d8ae86f03e9a
681,728
import ipaddress def get_networks(cidrs): """Convert a comma-separated list of CIDRs to a list of networks.""" if not cidrs: return [] return [ipaddress.ip_interface(cidr).network for cidr in cidrs.split(",")]
e17e9982dc52dad9df96891592aaf1fc423c7d18
681,729
def release_for_relnote(relnote): """ Turn a release note dict into the data needed by GitHub for a release. """ tag = relnote['version'] return { "tag_name": tag, "name": tag, "body": relnote["text"], "draft": False, "prerelease": relnote["prerelease"], }
4f7d93a75ab8b130eb62df708df5766c4b39137d
681,737
import pytz def localized_datetime(naive_dt, timezone_name='America/Los_Angeles'): """Attaches a timezone to a `naive_dt` """ tz = pytz.timezone(timezone_name) dt = tz.localize(naive_dt) return dt
e1ea9d7db0778d04e9a8d3a0b08eddc97769d9f1
681,741
import re def parse_time_window(window): """ Parse the specified time window and return as (float) minutes, or None if invalid """ regexps = { '^(\d+):?$': lambda match: float(match.group(1)) * 60, '^(\d+):(\d+)$': lambda match: float(match.group(1)) * 60 + float(match.group(2)), '^:(\...
c7d5b5fbd0222bc04e051a913a381c56b183daf2
681,743
def sequence(*decorators): """ Helper method which creates a decorator that applies the given sub-decorators. Decorators are applied in reverse order given. @decorator_sequence(dec_1, dec_2, ...) def function(...): ... is equivalent to: @dec_1 @dec_2 ... def function(....
bca2d7fe7aec8d7878780769084f1238df4bd781
681,745
def then_by_descending(collection, selector, context): """:yaql:thenByDescending To be used with orderBy or orderByDescending. Uses selector to extract secondary sort key (descending) from the elements of the collection and adds it to the iterator. :signature: collection.thenByDescending(selector)...
1b6fc79a2e1e225345970295bc1d9475a3d59e5b
681,751
def int_or_string(val: str): """ Loads a value from MO into either an int or string value. String is returned if we can't turn it into an int. """ new_s = val.replace(",", "") try: return float(new_s) except ValueError: return val
00562dedbcd1721f55326fa01630c273c4211253
681,753
from typing import List def add_jupyter_args(run_args: List[str]) -> List[str]: """ Adds `--ip 0.0.0.0` and `--no-browser` options to run args if those are not there yet. Args: run_args: Existing list of run arguments. Returns: Modified list of run arguments. """ run_args...
9a41749f4bf73f0abcdeae9cb207e28fc4084ac3
681,755
def drop_table_sql(name = "small_peptide"): """Generate an SQL statement for droping a table.""" return f"DROP TABLE IF EXISTS {name};"
0380e7ad99cf589bb851f55eb08d647be9f8a87b
681,756
def regularise_periapse_time(raw, period): """ Change the periapse time so it would be between 0 and the period """ res = raw if res < 0: res += period if res > period: res -= period return res
3a135b7f45b99f7bdf8a7107d87f606b1f290e66
681,758
def get_redundant_feature_pairs(feature_distance_series, threshold): """ Expects results from a `feature_distances` func. Returns redundant feature pairs, as determined by passed `threshold` for inter-feature measurement. """ return feature_distance_series[ feature_distance...
b17609575d2f92fa0f5bdd1e3d2fac72259162ab
681,760
def _get_join_indices(left_table, right_table, join_conditions): """Given the join conditions, return the indices of the columns used in the join.""" left_indices = [] right_indices = [] for cond in join_conditions: for join_col_name in (cond.left_operand, cond.right_operand): left...
6a42bb08ec1c8b370f2ea3e3bbc4bdce375003ff
681,763
def trim(s): """Removes whitespace, carriage returns, and new line characters.""" s = s.strip().replace("\n", "").replace("\r", "") return s
def098990ff997f38b80b94a58f4eab573b225b2
681,767
def filter_values(function, dictionary): """Filter ``dictionary`` by its values using ``function``.""" return {k: v for k, v in dictionary.items() if function(v)}
64d6370f580fad8ad37e51d62e150f1846073b27
681,771
def intersection(l1, l2): """Return intersection of two lists as a new list:: >>> intersection([1, 2, 3], [2, 3, 4]) [2, 3] >>> intersection([1, 2, 3], [1, 2, 3, 4]) [1, 2, 3] >>> intersection([1, 2, 3], [3, 4]) [3] >>> intersec...
a2d89502b4bc42cb012433e1e9e3b326cf433742
681,772
import re def remove_html_a_element_for_dingtalk(s): """ Replace <a ..>xx</a> to xx and wrap content with <div></div>. """ patt = '<a.*?>(.+?)</a>' def repl(matchobj): return matchobj.group(1) return re.sub(patt, repl, s)
40d52f7ae7971803aac859ec18c3da2115446bad
681,774
import re def dist_info_name(distribution, version): """Get the correct name of the .dist-info folder""" escaped_name = re.sub(r"[^\w\d.]+", "_", distribution, flags=re.UNICODE) escaped_version = re.sub(r"[^\w\d.]+", "_", version, flags=re.UNICODE) return '{}-{}.dist-info'.format(escaped_name, escaped...
018a0fa356637fd1867d6476b276b069c43b92d2
681,775
def repr2(x): """Analogous to repr(), but will suppress 'u' prefix when repr-ing a unicode string.""" s = repr(x) if len(s) >= 2 and s[0] == "u" and (s[1] == "'" or s[1] == '"'): s = s[1:] return s
e5eb7ff30ce2e225eab3a8769e7b65a92abede34
681,781
def get_fix_string(input_string: str, length: int): """ Transforms input_string to the string of the size length. Parameters ---------- input_string : str input_string length : int length of output_string, if -1 then output_string is the same as input_string Returns ---...
c450b6a223eab85e1d74ae9ced1aea5251d95fcd
681,786
def get_elements_of_type(xform, field_type): """ This function returns a list of column names of a specified type """ return [f.get('name') for f in xform.get_survey_elements_of_type(field_type)]
8335dc76395a0cb8fd05931b447628634a17408c
681,787
from typing import Sequence from typing import Tuple from typing import Optional import re def find_token( string: bytes, pos: int, tokens: Sequence[bytes] ) -> Tuple[Optional[bytes], int]: """Find the first occurrence of any of multiple tokens.""" pattern = re.compile(b"|".join(re.escape(token) for token...
8f2b194a998ef97e34eb96261130fd37fc7f6600
681,788