content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def clean_component(doc): """ Clean up text. Make lowercase and remove punctuation and stopwords """ # Remove punctuation, symbols (#) and stopwords doc = [tok.text.lower() for tok in doc if (not tok.is_stop and tok.pos_ != 'PUNCT' and ...
a22af7eb061360ae65ef1a90eedda3df74c16837
662,140
from typing import List def _get_key_hashes(rec: dict) -> List[str]: """Get key hashes in ledger state snapshot record.""" return [r[0]["key hash"] for r in rec]
0a4d2684f1c38c5dce2c711d6852f9e43c42faa7
662,143
import re def parse_output_areas(msg): """Parse create area message and return area number""" res = re.search(r"(OUTPUT AREAS =\s*)([0-9]+)", msg) if res is not None: return int(res.group(2))
9265a6e8501b513549872264788c23655dd3f106
662,145
def filter(df,column_name,field_value): """Filter a data frame to only include matches with field value in column_name""" tmp_df = df[df[column_name].isnull() == False] return tmp_df[tmp_df[column_name]==field_value]
f42eee7f02c0ff1e4e8b5766558f27dc3f5737d5
662,146
import fnmatch def ignore_rule_matches_result(ignore_rule, pa11y_result): """ Returns a boolean result of whether the given ignore rule matches the given pa11y result. The rule only matches the result if *all* attributes of the rule match. """ return all( fnmatch.fnmatch(pa11y_result.g...
e3596b41fe8fbcc910154d0514c62dc29096fa6c
662,150
def DecodeMAC(macbin): """Turn the given binary MAC address into a printable string.""" assert len(macbin) == 6 return ':'.join(['%02x' % ord(i) for i in macbin])
4c44f6e5d4a5d7430a2ccef6c94ff238ac71a894
662,152
import pkg_resources def get_data(filename): """Gets a data file from the package. Args: filename: The name of the data file as located in the package data directory. Returns: A readable file-like object for the data file. """ path = "data/" + filename return pkg_r...
91a55af8e6446fa896bd1f6fc3253dfbae0b4e57
662,153
def get_time_groupby_name(time_groups): """Return a name reflecting the temporal groupby operation.""" # Define time groupby name time_groups_list = [] for k, v in time_groups.items(): if v == 1: time_groups_list.append(k) else: time_groups_list.append(str(v) +...
22bd58bb533c2c85f2cb4d6342d122d6e3b8ad41
662,154
def to_numpy(tensor): """ If the tensor requires gradients, then detach it from the computation graph, move it to the CPU, and convert it to a NumPy array. Otherwise, just move it to the CPU and convert it to a NumPy array :param tensor: A PyTorch tensor :return: the tensor as a numpy array. ...
e343e1e07e0b5e22ddaeb546fef84a88a2ba83cd
662,155
def BinsTriangleInequality(d1, d2, d3): """ checks the triangle inequality for combinations of distance bins. the general triangle inequality is: d1 + d2 >= d3 the conservative binned form of this is: d1(upper) + d2(upper) >= d3(lower) """ if d1[1] + d2[1] < d3[0]: return False i...
fa0a20f5471badd9a8436d4f03102becf306d26d
662,158
from pathlib import Path from typing import Set def get_local_projects(path: Path) -> Set[str]: """ Returns all the projects (directories) under `path`. """ return {f.name for f in path.iterdir() if f.is_dir() and not f.name.startswith(".")}
0fe6c86e09c93a7026ba7d497ba2ee869cb64bd4
662,162
from typing import Any import lzma import pickle def load(input_path: str) -> Any: """ Unpickle the object. :param input_path: Input path of pickled object. :return: The object. """ with lzma.open(input_path, 'rb') as reader: reto = pickle.load(reader) return reto
f306614cb286ebc393dc211bcd5d839d39bef5b2
662,163
def _parse_values(value_string): """Parse comma-delimited values from a string""" values = list() for raw in value_string.split(','): raw = raw.strip() if len(raw) > 1 and raw[0] == '"' and raw[-1] == '"': raw = raw[1:-1].strip() values.append(raw) return values
178119c2ae59d97e297c6d58abeb85c4e94deb99
662,164
import time def datecode(t=None, local=False): """The date code incorporates both the unix time and the date in either the local timezone (respecting DST) or UTC (aka GMT). It is convenient for naming ops subdirectories or tagging events for easy sorting.""" if t == None: t = time.time() zt = tim...
dbf5b38dc47eff225fbe394374cd61ed589d68ee
662,166
def valid_request_body_with_existing_priority(valid_request_model): """ A fixture for creating a request body with existing priority number for a client. Args: valid_request_model (Model): a valid request model created by a fixture. """ return { 'title': 'Add PayPal ...
2745a966e13742353f870ee6f049b9271a9e8eb2
662,167
def read_elastodyn_dat(path): """Get dictionary from an elastodyn dat file""" d = {} with open(path, 'r') as ed: end = False for line in ed: contents = line.split() if contents[0] == 'OutList': end = True if end: break ...
4867050aab1b5497f6f9b9a91014113978e69103
662,168
import json def get_file_json(path): """Read a file and return parsed JSON object.""" with open(path, 'r') as f: return json.load(f)
1fd08b5b196ed03f5c871abd117e15ba67b02fcf
662,172
def swagger_escape(s): # pragma: no cover """ / and ~ are special characters in JSON Pointers, and need to be escaped when used literally (for example, in path names). https://swagger.io/docs/specification/using-ref/#escape """ return s.replace('~', '~0').replace('/', '~1')
8f6e7112a565a6840fd046446cff77e11ee8425a
662,178
def make_ffmpeg_section_args( filename, start, length, *, before_options=(), options=(), ): """Returns a list of arguments to FFmpeg It will take the required amount of audio starting from the specified start time and convert them into PCM 16-bit stereo audio to be piped to stdout. ...
4599368c2b44a51da1ea1c2935305a4423ae581d
662,184
def mse_node(w_samples, y_sum, y_sq_sum): """Computes the variance of the labels in the node Parameters ---------- w_samples : float Weighted number of samples in the node y_sum : float Weighted sum of the label in the node y_sq_sum : float Weighted sum of the squared ...
cd637bb01bc334a20d83179f5e9925e505fb9912
662,186
def GetKeyIdFromResourceName(name): """Gets the key id from a resource name. No validation is done.""" return name.split('/')[5]
3f6d2a06adfebe684e8b1f637ebfc12417169b2a
662,187
def encode(value, encoding='utf-8'): """Encode given Unicode value to bytes with given encoding :param str value: the value to encode :param str encoding: selected encoding :return: bytes; value encoded to bytes if input is a string, original value otherwise >>> from pyams_utils.unicode import enc...
bd417a0ef50ef0f9a48594fd2b9c049e98932bc8
662,188
import math def rotate(x, y, alpha, xCenter = 0, yCenter = 0): """ rotate a point by a given angle @param x x-coordinate of the point that needs to be rotated @param y y-coordinate of the point that needs to be rotated @param alpha rotation angle [0..2pi radians] @param xCenter x-coordinate of the origin (0 is ...
e043e58d28089a972238eafaa669ea29f8efd669
662,190
import re def remove_tag(entry, alltag=False): """remove SRT and ASS tags if alltag, NoTagApp specials ([b]/[i]/[u]) tag are removed too """ tag_pattern = r"{\\.*?}|</?font.*?>|</?.*?>" if alltag: tag_pattern += r"|\[/?.?\]" return re.sub(tag_pattern, "", entry)
5d9197888cb727d97f713fed3cb1d09defd89adf
662,192
def sqrt(n: int) -> int: """Gets the integer square root of an integer rounded toward zero.""" return int(n ** 0.5)
380a2516ae77a038469d190e5898ee9fd59f7820
662,193
def convert_diameter_sigma_to_fwhm(diameter): """ Converts a beam diameter expressed as the full with at half maximum (FWHM) to a beam diameter expressed as 2-sigma of a Gaussian distribution (radius = sigma). :arg diameter: 2-sigma diameter diameter. """ # d_{FWHM} = 1.177411 (2\sigma) ...
9ff9b8581fdda3f0063a99df340bc5239e296a1f
662,200
def construct_exec_result(result, exec_result): """ Transform an ImpalaBeeswaxResult object to a QueryResult object. Args: result (ImpalaBeeswasResult): Tranfers data from here. exec_result (QueryResult): Transfers data to here. Returns: QueryResult """ # Return immedietely if the query failed....
d6a6ac4f6882e2236d6f8ea585d7c683dbd178af
662,202
def table_from_fk(fks): """Get the table name of the fk constraint, ignoring the cordis_projects table Args: fks (:obj:`list` of SqlAlchemy.ForeignKey): All foreign keys for a given table. Returns: tablename (str): The table name corresponding to the non-Project foreign key. """...
ffbc61087189a4dc57326a5c91439353a8f0c2dc
662,204
import gzip def write_fastq(filename): """ return a handle for FASTQ writing, handling gzipped files """ if filename: if filename.endswith('gz'): filename_fh = gzip.open(filename, mode='wt') else: filename_fh = open(filename, mode='w') else: filename...
b68d85cf7d551cb2e04df5fae9f1a34837aeffc5
662,206
def intersection(set1, set2): """ Calculates the intersection size between two sets, used to compute overlap between a word context and a definition's signature. @param set1 - First set @param set2 - Second set @return Intersection size """ return len(set(set1) & set(set2))
95f3e651d71f217567e9c2e89048f7d1ce5114cd
662,207
def groupby(keys, values): """Group values according to their key.""" d = {} for k, v in zip(keys, values): d.setdefault(k, []).append(v) return d
35f54ecc179971575aaeb8a8a1e86a3dc03556ed
662,208
def square_loss(a, b): """ Returns the value of L(a,b)=(1/2)*|a-b|^2 """ return 0.5 * (a - b)**2
6b852ec061273f4d69da64eeee51caee031a5306
662,209
def is_filetype(filename: str) -> bool: """ Return true if fname is ends with .csv, .xlsx, or .xls. Otherwise return False. :filename: filename string Returns bool """ cfname = filename.lower() if cfname.endswith(".csv") and not cfname.startswith("pdappend"): return True ...
9dbf867723b474a1e57151ed31e7f358770af25f
662,210
def image_meta(system_metadata): """Format image metadata for use in notifications from the instance system metadata. """ image_meta = {} for md_key, md_value in system_metadata.items(): if md_key.startswith('image_'): image_meta[md_key[6:]] = md_value return image_meta
c76bd0dc4deb26447827bfd1aed9828361a9281e
662,218
def get_tech_installed(enduse, fuel_switches): """Read out all technologies which are specifically switched to of a specific enduse Parameter --------- enduse : str enduse fuel_switches : dict All fuel switches where a share of a fuel of an enduse is switched to a specif...
4e84c574c9afd08010df653cf00c03daa38bab45
662,219
def x_label(epoch_axis): """ Get the x axis label depending on the boolean epoch_axis. Arguments: epoch_axis (bool): If true, use Epoch, if false use Minibatch Returns: str: "Epoch" or "Minibatch" """ return "Epoch" if epoch_axis else "Minibatch"
ed6d120e04344ef2a9abf8b0b190f032d6faf763
662,222
import ast def count_number_of_functions(filepath): """Count number of functions inside a .py file.""" # Taken from: https://stackoverflow.com/a/37514895/1274908 with open(filepath, "r+") as f: tree = ast.parse(f.read()) return sum(isinstance(exp, ast.FunctionDef) for exp in tree.body)
4f6ff4d62be9add2b798c73aff3af384646c405f
662,225
import inspect def parse_comments(func): """ parse function comments First line of comments will be saved as summary, and the rest will be saved as description. """ doc = inspect.getdoc(func) if doc is None: return None, None doc = doc.split('\n', 1) if len(doc) == 1: ...
ac8c1acccc0fa6a7b2e2f64a8e2df7ce604b9b84
662,226
def __tokenify(number): """ 生成随机验证字符串 :param number: :return: 随机验证字符串 """ token_buf = [] # char map 共64个字符 char_map = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ*$' remainder = number while remainder>0: token_buf.append(char_map[remainder&0x3F]) remainder = remainder // 64 return ''....
522c9170a55b9c97bc44e7080ed073e06eae3fca
662,228
def remove_at_index(lst, index): """ Creates a new list which is a copy of the input one with a single element removed from it """ removed = lst[:] del removed[index] return removed
1f5c7dbb32075335a489ee4d2a4857057a4c19dd
662,232
def early_stop(metrics, steps, min_improvement=0, higher_is_better=False): """Early stopping condition. Args: metrics: A list of metric values. steps: Consider the improvement over this many steps. min_improvement: Continue if the metric improved less than this value: higher_is_better: Whether a hi...
a5b8f6681989c33f5e8c22698a5ccb82ac49b01b
662,237
def r19o(factor: float = 1) -> float: """ The outer size of the mounting rails of a 19-inch full rack giving it its name. """ return 482.6 * factor
2eeb9be4643dd68d389f06415a3a4c09e8178e99
662,238
def decode_message(encoded_text, dictionary): """Decodes encoded text according to the given dictionary. Huffman encoded messages can be decoded only if we have the original dictionary that is used to encode the message. If the encoded message includes an unknown code function raises an error. Arg...
51e05c4685fc4a0a8c2a86c1c019d07bdab25d66
662,240
def detail_line(e): """Given an expectation, return a readable one-line explanation of it.""" fields = [fname for fname in ('mutable', 'optional', 'volatile') if getattr(e, fname, None)] if e.depends_on: fields.append("depends_on=%s" % e.depends_on) line = ', '.join(fields) i...
53406fc415347b6db8e03b2f68c9de1e0d38cb7a
662,243
def group_by_phrase(docs_df): """ Takes a Pandas data frame with index=phrase, cols: num_occurrences as input, calculates the no. of unique and total occurrences of each phrase over the whole time period (a quarter) by grouping by phrase and aggregating on the column num_occurrences (sum and count). Th...
3e88545511494e344ff9877cabd27a25438898c0
662,244
def clamp(n, maxabs): """Clamp a number to be between -maxabs and maxabs""" return max(-maxabs, min(n, maxabs))
619c73b63d12caef58f9e219b2484f20ef569a3f
662,245
import random def mutation_single_customer_rerouting(vehicle, p1, quality, duration, setup_time, setup_cost, demand): """Re-routing involves randomly selecting one customer, and removing that customer from the existing route. The customer is then inserted in the best...
c923b18ed57848a681c2ea6ec14025b6c4213b2b
662,248
def parse_context_name(context_obj): """Parses context name from Dialogflow's contextsession prefixed context path""" return context_obj["name"].split("/contexts/")[1]
95b897395c58d7dac7501778ad968512fbdd4d8e
662,250
def options2args(options): """Convert a list of command line options to a args and kwargs """ args = list() kwargs = dict() for a in options: if "=" in a: a = a.split("=", maxsplit=1) kwargs[a[0].lstrip("-")] = a[1] else: args.append(a) return args...
3819ba1455d280c22e9f3f124125410781bc2f7a
662,252
def rename_variable(formula, old_name, new_name): """ Function that traverses the formula and changes the appearance of one variable. The renaming is done to the values of the id and field attributes. :param formula: Root node of the formula object :param old_name: Old variable name :param ...
b76498143e08a07d227ed799d5f74d5ec0e1b731
662,253
def convert_list_to_string(org_list, seperator=' '): """ Convert list to string, by joining all item in list with given separator. Returns the concatenated string """ return seperator.join(org_list)
dcc7da366e62b1b638a7f4190aa760a3c4016600
662,258
def _pad_with_nulls(data, len_): """ Pad string with null bytes. Parameters ---------- data : str/bytes the string/bytes to pad len_ : int the final desired length """ return data + (b'\x00' * (len_ - len(data)))
238cc6c7b883d087cfa09131eec2b463054f791e
662,260
def generated_tag_data(tags): """Convert :obj:`dict` to S3 Tag list. Args: tags (dict): Dictonary of tag key and tag value passed. Returns: list: List of dictionaries. """ generated_tags = [] for key, value in tags.items(): generated_tags.append({ 'Key': ke...
8817d2ab05bd26bb056f3facaadc025b547ef3fc
662,265
def fitness(individual, problem): """ Score the fitness of an indivdual based on a MAXSAT problem. :param individual: An "individual" represented as an array :param problem: MAXSAT problem to compute fitness in ref to, usually stored as global MAXSAT_PROBLEM :return: An int representation of ind...
410bfd493bf9551f735c0fd6e2f2c5946750490d
662,266
def is_excluded(path, dirs): """ if path is excluded in list of dirs/files :param path: path to check for exclude :param dirs: list of excludes :return: Boolean """ for directory in dirs: if path.startswith(directory): return True return False
4bb6e5c5bf38f90252abda7171e949a951baf7a6
662,269
def rearrange_name(s: str) -> str: """Converts last, first to first last Args: s (str): the original string Returns: str: the standardized string """ return ' '.join(reversed([i.strip() for i in s.split(', ')]))
66d734d820ec1836a973e2b8bc658817284503c7
662,279
def int_pow(x: float, exponent: float) -> int: """Finds the nearest integer to ``pow(x, exponent)``. Args: x: The number whose power will be found. exponent: The number to which ``x`` will be raised. Returns: The result of rounding ``pow(x, exponent)`` to the nearest integer. "...
f710adbb0299ec57bc63784fc101b102dadc821d
662,280
def mock_moira(mocker): """Return a fake mit_moira.Moira object""" return mocker.patch("moira_lists.moira_api.Moira")
91e9c4ba881cbd22780ea7c75e2f9c39c4294af4
662,281
def _trapz_simps_overlap2(dy, dx): """Correction term in the squared error when combining trapezoidal and Simpson's rule. Only exact for equal spacing *dx* left and right of *dy*. err^2 = (h/6)^2 ((3 Df0)^2 + ((3+2)Df1)^2 + (8Df2)^2 + (4Df3)^2 + ...) |-- trapz ---| |--------- Simpson...
81bd671f27b74d5f4ae3c1ec85bde9e37a0950c5
662,282
import ast def _safe_eval(node, default): """ Safely evaluate the Boolean expression under the given AST node. Substitute `default` for all sub-expressions that cannot be evaluated (because variables or functions are undefined). We could use eval() to evaluate more sub-expressions. However, this...
e71e320efc330073d355169283b3398eabe56d13
662,283
def percentage(context, num, total_num): """ Works out the percentage of num over total_num and then appends the percentage sign """ p = float(num)/float(total_num) * 100 percent = str(p) + "%" return percent
66bb8db090a9f9cc01b34fda291055aeae731f1c
662,284
def bdev_nvme_set_options(client, action_on_timeout=None, timeout_us=None, timeout_admin_us=None, keep_alive_timeout_ms=None, retry_count=None, arbitration_burst=None, low_priority_weight=None, medium_priority_weight=None, high_priority_weight=None, ...
9191a0e1317de57beefb271859736f42857a2e04
662,288
import json def update_json(row, fields): """Add data to the taxon_json field.""" taxon_json = json.loads(row.taxon_json) for field in fields: if row[field]: taxon_json[field] = row[field] return json.dumps(taxon_json, ensure_ascii=False)
cc08e6011a5514212b2a5293350069d789b4df1d
662,289
def fix_ambiguous_cl(column=4): """awk command to replace non-N ambiguous REF bases with N. Some callers include these if present in the reference genome but GATK does not like them. """ return r"""awk -F$'\t' -v OFS='\t' '{if ($0 !~ /^#/) gsub(/[KMRYSWBVHDXkmryswbvhdx]/, "N", $%s) } {print}'""" % ...
4b7f8de10fce8f9d98d103cd0e3f146d3cca3816
662,291
def make_list(nb_letters): """Makes the list of words. Args: nb_letters (int): number of letters in the words of the list Returns: list: the list of words """ words_list = [] # Open the file that contains the words with the required number of letters with open(f'data/mots_{nb...
93982818e55fe46f58b06416fd70dd11b847d8d2
662,292
def get_travel_requests_of_timetables(timetables): """ Retrieve a list containing all the travel_request_documents, which are included in a list of timetable_documents. :param timetables: [timetable_documents] :return: travel_requests: [travel_request_documents] """ travel_requests = [] ...
7d825f26799aaaf29521055dab7b07371ffe1cb0
662,293
def number_vowels(w): """ Returns: number of vowels in string w. Vowels are defined to be 'a','e','i','o', and 'u'. 'y' is a vowel if it is not at the start of the word. Repeated vowels are counted separately. Both upper case and lower case vowels are counted. Examples: number...
c5d3003681767b726172547c83c8f44c7a583733
662,294
def div_by_nums(i, nums): """ Test if number (i) is divisible by array of numbers (nums) :param i: :param nums: :return: """ for n in nums: if i % n == 0: return True return False
987bb99f50e4cff8a423ad42cca6692c46a0b4f9
662,298
from typing import Any from pydantic import BaseModel # noqa: E0611 from enum import Enum async def clean_python_types(data: "Any") -> "Any": """Turn any types into MongoDB-friendly Python types. Use `dict()` method for Pydantic models. Use `value` property for Enums. Turn tuples and sets into lists...
f67c2be6ada2b528122093c2879f40055dd0f135
662,299
def temporal_affine_forward(x, w, b): """ Inputs: - x: Input data of shape (N, T, D) - w: Weights of shape (D, M) - b: Biases of shape (M,) Returns a tuple of: - out: Output data of shape (N, T, M) - cache: Values needed for the backward pass """ N, T, D = x.shape M = b.shap...
eae8f0dbbea596a4bcc1a7739cfd249e8898df90
662,301
def get_history_resource_data(session, team, date, hour, storage): """Return the history energy usage of the team for the date and hour.""" return storage.get_history_resource_data(session, team, date, hour)
e0e0f9233c95e69313f97c432bebb0f36252bd4c
662,307
def list2cmdline(lst): """ convert list to a cmd.exe-compatible command string """ nlst = [] for arg in lst: if not arg: nlst.append('""') else: nlst.append('"%s"' % arg) return " ".join(nlst)
33a469357406377d8ca772d4a91b0a64ee82896b
662,310
def get_directory_contents(directory): """ return a sorted list of the contents of a directory """ contents = [] for child in directory.iterdir(): contents.append(child) return sorted(contents)
6df92b20bff12df5aeb7ecb98431710a8a19a660
662,311
def is_date_time(file_type, path): """ Return True if path is an object that needs to be converted to date/time string. """ date_time_objects = {} date_time_objects["Gzip"] = ("mod_time",) date_time_objects["PE"] = ("pe.coff_hdr.time_date_stamp",) date_time_objects["Windows shortcut"] = ("he...
e9f722fcbc6de94a2794a2639db68f21be538e41
662,316
def sent_ngrams_list(words, n): """ Create a list with all the n-grams in a sentence Arguments: words: A list of strings representing a sentence n: The ngram length to consider Returns: A list of n-grams in the sentence """ return [tuple(words[i:i + n]) for i in range(len(words) - n ...
bc090aad5108d828251263ad1f5dce7ce8020d7d
662,317
def index_fact(fact, index, negated=False): """ Returns a representation of 'fact' containing the step number and a leading 'not-' if the fact is negated """ name = str(fact) if negated: name = 'not-' + name return "%s-%d" % (name, index)
be15921b2ad14a3b76841f588bfd2a7a8643cb9c
662,318
def sum67_loop(nums): """ A basic loop method. the key is to keep a flag set to know whether a 6 has been encountered """ total = 0 is6 = False for num in nums: print("adding:", num, is6) if num == 6 or is6: is6 = True else: total += num ...
97ec25821b5dd240404751296cdbb0fc47302b5e
662,319
def __predict(X_test, model, X_scaler): """ Do prediction for provided fetures Arguments: X_test: the test data [n_samples, n_features] model: the classification predictive model X_scaler: the standard scaler used to scale train features Return: predicted labels as array ...
7e4c3819d261e7bee0512362a1022a9ef25b4c74
662,322
def get_num_channels(image5d): """Get the number of channels in a 5D image. Args: image5d (:obj:`np.ndarray`): Numpy arry in the order, `t,z,y,x[,c]`. Returns: int: Number of channels inferred based on the presence and length of the 5th dimension. """ return 1 if image5d i...
6c389d51cfe3eeec49a491bebf732d0573200535
662,323
def is_e164_format(phone): """Return true if string is in E.164 format with leading +, for example "+46701740605" """ return len(phone) > 2 and phone[0] == "+" and phone[1:].isdigit() and len(phone) <= 16
2773030b9c8e7b2004e0c233abc23258b3200f7d
662,324
def dcf_to_swap(dcf): """ Helper function transforms sorted discount factors to swap rates. :param dcf: discount factors :return: par swap rates """ num_dcf = len(dcf) swap_rates = num_dcf * [0] for index, dcf_ in enumerate(dcf): if index == 0: swap_rates[index] = (1...
9b03b2b6e0e08515b1e1b78cb1a72810a343926f
662,325
def search_ancestor(node, *node_types): """ Recursively looks at the parents of a node and returns the first found node that matches node_types. Returns ``None`` if no matching node is found. :param node: The ancestors of this node will be checked. :param node_types: type names that are searched fo...
709cbda37e591088c600736c36cf5c09b06f2d89
662,327
import torch def to_torch(tensor): """Converts an array-like object (either numpy or pytorch) into a pytorch tensor.""" if tensor is None: return None elif isinstance(tensor, torch.Tensor): return tensor torch_tensor = torch.from_numpy(tensor) if torch_tensor.dtype == torch.fl...
6d537ee1a6778547da66164ad9c5c8d6f706a0f1
662,328
import linecache def clang_range_str(source_range): """Get the text present on a source range.""" start = source_range.start stop = source_range.end filename = start.file.name if filename != stop.file.name: msg = 'range spans multiple files: {0!r} & {1!r}' msg = msg.format(filename...
c855c0c04db0cf00c47166ad1566228b730bd561
662,329
def measure_lexical_diversity(tokenized_string): """ Given a tokenized string (list of tokens), return the fraction of unique tokens to total tokens. """ return len(set(tokenized_string)) / len(tokenized_string)
018b07d6ebeb02439f41b496e512d2bb0713f6b7
662,334
def get_primary_language(programming_language_tallies): """ Return the most common detected programming language as the primary language. """ programming_languages_by_count = { entry['count']: entry['value'] for entry in programming_language_tallies } primary_language = '' if program...
0500d23a13eeab17580c3c94703251b133eb7a73
662,335
def wind_consistency(windspeed, winddirection, variablelimit): """ Test to compare windspeed to winddirection. :param windspeed: wind speed :param winddirection: wind direction in range 1-362 :param variablelimit: maximum wind speed consistent with variable wind direction :type windspeed: float...
ae713cdd5ee3a0d27d47bf0eb7a2fd5045628d29
662,337
def compute_net_sales_booking(target_object): """ Return net sales booking data by finding the difference of object's, which is an argument, revenue and cost data """ net_sales_booking = int(target_object._booking) - int(target_object._booking_cost) return net_sales_booking
7923813316df88fdf0ba3fae71b4f2f5a2503645
662,338
def filter_deleted_items(items, flag): """Filter deleted items :param items: target :param flag: deleted flag name, always True means deleted :return: list does not contain deleted items """ # just return if parameter is not a list if not isinstance(items, list): return items ...
0f494d3515f7bd78661b3e5bed00055eeea6f7d3
662,339
def number(selection_string: str, minimum: int, maximum: int, default = None) -> int: """ Asks the user for a number within the provided minimum and maximum with optional default and returns their response """ while True: if default: input_string = f"{selection_string} default={defau...
4f2f17b94c362e5e5c919a1e6df989c7881892c6
662,341
def get_list_nodes_from_tree(tree, parameters=None): """ Gets the list of nodes from a process tree Parameters --------------- tree Process tree parameters Parameters Returns --------------- list_nodes List of nodes of the process tree """ if paramet...
0d0178407d7675d3b245965606462c23ead232b7
662,342
def getrecursionlimit(space): """Return the last value set by setrecursionlimit(). """ return space.newint(space.sys.recursionlimit)
9acf9d018eb0a54d5507dfc5f6e6775ac6c36c9a
662,345
def get_sort_dirs(sorts, page_reverse=False): """Extract sort directions from sorts, possibly reversed. :param sorts: A list of (key, direction) tuples. :param page_reverse: True if sort direction is reversed. :returns: The list of extracted sort directions optionally reversed. """ if page_reve...
a525e2f1e19c0c5e5f1774b38f7de6f949dec640
662,349
def make_header(pandoc_format, title, categories): """ Generate pandoc header based on given metadata. """ lines = [ "---", "format: " + pandoc_format, "title: " + title, "...", ] if categories is not None and len(categories) > 0: lines.insert(2, "cate...
6b383ee02ff7075afa38ddc5d2dfe91b2c3d7b1f
662,350
def null_safe(rule): """Return original expr if rule returns None.""" def null_safe_rl(expr): result = rule(expr) if result is None: return expr else: return result return null_safe_rl
964997cf5ac6369f89f7e93390aeba5b610c68e7
662,352
def get_version(name: str, version: str) -> str: """ Get the version of a script. Parameters ---------- name : str Name of the script. version : str Version of the script, in format major.minor.patch. Returns ------- str Script's version. """ return...
3fb554bdeef00e4900730212dd4b96680fefc80b
662,356
def tag_dictkeys(tag, dictionary): """Return the dictionary with tagged keys of the form 'tag.key'""" tagged = {} for key, val in dictionary.items(): tagged[tag+'.'+key] = val return tagged
62e3a0082ff28ff5f5520450e3b6f0ddf630d04c
662,361
def sort_tuple(tup, n=2): """Sort a tuple by the first n values tup: tuple input tuple n : int values to sort tuple by (default is 2) Returns ------- tup : tuple tuple sorted by the first n values """ return tuple(sorted(tup, key=lambda t: t[:n]))
094c855935ed568e384f09d466e9fdb522de2a90
662,364
def check_description(description, title): """ Verifies that the description is within the specified bounds (20 < x < 20000) and that the description is longer than the inputted title. :param description: product description :param title: product title :return: True if the description meets...
38c4b7c66e7e35586dba12cb82347011836e7c56
662,365
def get_strings(public, private): """ Get the string values for a public and private key. :param public: Public key to convert :param private: Private key to convert :type public: rsa.PublicKey :type private: rsa.PrivateKey :returns: a tuple (str, str) :rtype: tuple """ retur...
0093373ce3149c909fa7ef95bba3d5f82c038b68
662,368