content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import re def parse_details_page_notes(details_page_notes): """ Clean up a details page notes section. The purpose of this function is to attempt to extract the sentences about the crash with some level of fidelity, but does not always return a perfectly parsed sentence as the HTML syntax varies ...
bbe7041668974d3fa3b27828966d39b78f1775a3
651,663
import subprocess def file_len(fname): """ Function from Stack Overflow Simply returns the amount of lines in the given file fname It is possible that the file has to be a .txt """ p = subprocess.Popen(['wc', '-l', fname], stdout=subprocess.PIPE, stderr=subprocess.PIPE...
3843dd2837ad6e94225e6726f4156bc5ed8c35e8
651,664
def sha512sum(p_object): # real signature unknown; restored from __doc__ """ sha512sum(object) -> str Return the sha512sum of the object. 'object' may either be a string, in which case the sha512sum of the string is returned, or a file() object (or file descriptor), in which case the sha512sum ...
6f1699c9cdfecf92e79e01fe6fb81609a0ce5340
651,665
import uuid def unique_id(): """Generate a unique ID for the migration using 8 first digits from uuid4. Returns: str: Return a string containing a unique ID. """ return str(uuid.uuid4())[:8]
fed3027e1aa0a5de8c20b0d27acd7ad100e85865
651,666
def get_prob_current(psi, psi_diff): """ Calculates the probability current Im{psi d/dx psi^*}. """ print("Calculating probability current") curr = psi*psi_diff return -curr.imag
5573a437cc4bea28612f8f6224979558bf7e173a
651,668
def get_urls(info): """Return list of SLC URLs with preference for S3 URLs.""" urls = list() for id in info: h = info[id] fields = h['_source'] prod_url = fields['urls'][0] if len(fields['urls']) > 1: for u in fields['urls']: if u.startswith('s3:/...
891ca10d95963447c3498091ea114322d8262934
651,669
import random def majority_vote(votes): """ Return the most common element in votes. """ vote_counts = {} for vote in votes: if vote in vote_counts: vote_counts[vote] += 1 else: vote_counts[vote] = 1 winners = [] max_count = max(vote_counts.valu...
5c4d1545ff6f8e24c390cbbb1c94f3d292a2ff4b
651,670
def get_provider(ns, type, backend): """ Returns SSSD provider for given backend. :type type: string :param type: Type of the provider (= value of its LMI_SSSDProvider.Type property). :type backend: LMIInstance of LMI_SSSDBackend :param backed: SSSD backend to inspect. :rtype: strin...
1c8ac89c27aa8b600073adf47be0e64eaf13b950
651,671
import argparse def add_command_parser(subparsers: argparse._SubParsersAction): """ Function to add the relevant parser for the command Args: subparsers: subparser to add arguments to """ return "pr", None
0d1186bb3e45536d185e36a1d2bc4cbbd2414460
651,672
from operator import rshift from operator import lshift def caesar(message, numshifts, encrypt): """performs a caesar shift of the given message using the given number of shifts""" outstring = '' # for each character in the message if the character is a letter shift the character # by the given numb...
56b09b295a1f332e54dc7c87374a0f7d5d083cb2
651,673
from typing import Mapping def is_mapping(obj): """Check if object is mapping.""" return isinstance(obj, Mapping)
6c0934c3331d65ee6ffdab79b9502acb00e8b968
651,674
import locale def get_encoding(): """Return system encoding. """ try: encoding = locale.getpreferredencoding() 'TEST'.encode(encoding) except: encoding = 'UTF-8' return encoding
6a35e34b2b2c0d35fffc2a099d44161357ba7383
651,675
import torch def full_pose_3d(pose): """Expand (B, 12) pose to (B, 4, 4) transformation matrix.""" shape = list(pose.shape[:-1]) shape += [3, 4] pose = torch.reshape(pose, shape) zeros = torch.zeros_like(pose[..., :1, 0]) last = torch.stack([zeros, zeros, zeros, zeros + 1], -1) full_pose = torch.ca...
5584148de473496db28d687efdf51b58fa6bd0ce
651,676
import six def unpack_dd(buf, offset=0): """ unpack up to 32-bits using the IDA-specific data packing format. Args: buf (bytes): the region to parse. offset (int): the offset into the region from which to unpack. default: 0. Returns: (int, int): the parsed dword, and the number of ...
478ea18629c1ce3f5c4b461dd4fd21cdd4938f6d
651,677
import shlex def shell_split(st): """ Split a string correctly according to the quotes around the elements. :param str st: The string to split. :return: A list of the different of the string. :rtype: :py:class:`list` >>> shell_split('"sdf 1" "toto 2"') ['sdf 1', 'toto 2'] """ ...
30f5ce93aa58d1c984eb2562293f9e7009f9e041
651,678
def find_cluster(centroid): """Identify the different clusters with their trends. Parameters ---------- centroid: pd.DataFrame Hourly profile for each cluster Returns ------- dict name: cluster_id """ # There must be just 4 clusters assert centroid.shape[0] == 4...
414609b3be4ea20845fb18598f6d0b799c1d5deb
651,679
import re def natural_sort_key(s, _nsre=re.compile('([0-9]+)')): """Used to ensure samples load in sane order from filesystem.""" return [int(text) if text.isdigit() else text.lower() for text in re.split(_nsre, s)]
e81494f5dd99b89fa1314d28a051f6795231dd50
651,680
import math def __clean_convert_weight(x): """ This function strips any white space and new lines. It also converts the value to a numpy 64 bit integer. Also normalizes big and small values using natural logarithm and rounding them up to 6 decimal points. :param x: Any number variable that can be conv...
98df5ae9364118e2ca46c7ad38b4a580f4a2ccc0
651,681
def to_millis(secs, nanos): """Combine seconds and nanoseconds and convert them to milliseconds.""" return 1000 * secs + nanos / 1000000
0c09b48e038de4c216f02bee1cd0f5e1ea64fc45
651,682
import torch def seq_normalization(x:torch.Tensor, col_idx:int=145): """Normalizes a Tensor across its temporal (1) dimension `N. H, W` up to `col_idx` in the `W` dimension""" epsilon = 1e-10 m_x = x[:,:,:col_idx] x[:,:,:col_idx] = (m_x - m_x.mean(1).unsqueeze(1))/(m_x.std(1).unsqueeze(1)+epsilon)...
6f82a6ef0140ede3edb1d6e744e8a0170c64cef4
651,683
def split_by_label(data, targets, labels): """ Given a data matrix and the targets for the data, the method splits the data by class :return: a dict with the data separeted by label, each label is a key of the dict """ d = dict() for cl in labels: d[cl] = data[targets == cl] return d
ba3521b2833897790b81d7818672a2dae70c258a
651,685
def expected_count(af, effective_mutation_rate): """Calculate the expected number of somatic variants greater than a given allele frequency given an effective mutation rate, according to the model of Williams et al. Nature Genetics 2016""" return effective_mutation_rate * (1.0 / af - 1.0)
92a6802df93260777d9ecdd90376ba03495e6400
651,687
def find_uniq_preserve_order(orig_keys, orig_values=None): """remove duplicate keys while preserving order. optionally return values.""" seen = {} keys = [] values = [] for i, item in enumerate(orig_keys): if item in seen: continue seen[item] = 1 keys.append(item) if orig_values: v...
337e96e3a8acccaa0347f703b3afc932c919beb7
651,688
def _overrideFunc(v, t): """ Private function to be used to pass as an alternate onTimeoutCancel value to timeoutDeferred """ return "OVERRIDDEN"
b7ab14ee82ad2c4e4cd00bc6b5ae2b9590ea275f
651,689
def cycspec(self, label="", node="", item="", comp="", **kwargs): """Defines the set of result items for a subsequent CYCCALC command in APDL Command: CYCSPEC postprocessing a cyclic harmonic mode-superposition analysis. Parameters ---------- label One of the following labels: ...
4a8d0f6d6bbb55e9b7c23689f9db5aa9b0e3554d
651,690
def add_to_existing_groups(no_people, existing_groups, max_size): """ Attempts to add the given number of people to the list of existing groups without exceeding the maximum group size. Modifies the list of existing groups. Returns the number of people remaining after the attempt. ...
7b9b0c4f0318d3d873f9a2d6288bcee63966b944
651,691
def walk_vertices(graph, start, order, path=None): """depth-first search: walk order nodes from start""" if path is None: path = [] path = path + [start] if len(path) == order: return [path] paths = [] for node in graph[start]: if node not in path: newpaths = ...
8645ad1cc8fec935f9d1d60bd248547c4ead9e3b
651,692
import numpy as np import pandas as pd def get_uniprot_nt_lengths(uniprot_file, min_nt_length=0, types=None): """ This function parses a file exported from UniProt giving protein information. It then filters based on the 'Status' types, and finally filters based on the nucleotide lengths of the se...
c4ccfdb59938bcb92f99154001f384682272fcae
651,693
def stci(ds): """Calculate the Subtropical Cell Index (STCI) according to Duteil et al. 2014 Parameters ---------- ds : xr.Dataset Input dataset. Needs to have a variable `psi` which represents the meridional mass overturning streamfunction Returns ------- xr.Dataset The ST...
8a02306c4ddd04e09bfa15ebe47b29a11edf449a
651,695
def linear(start, increment, limit): """Linear delay generator. Creates a function generator that yields a constant delay at each iteration. :param start: The starting delay in milliseconds. :param increment: The amount to increment the delay after each iteration. :param limit: ...
03236d75dc8af62ace4489e35ed90a7aa7787e53
651,696
def has_unique_result(entities, blacklist_articles, serie): """ Check if the set of entities lead to a unique article selection :param entities: entity set to verify :param blacklist_articles: articles which should not appear in the tree :param serie: pandas series with object id as index and entiti...
28613c1f75dab7d98114599226d1370bf5bf2214
651,697
async def confirm_message(after): """ Returns bool true if the channel the message was pinned in is not readable by all roles. """ channel_perms = after.channel.overwrites # Returns dictionary of overwrites in the current channel roles = after.guild.roles # Returns all roles in the guild perm_roles = []...
72db5ffb730427094e4996c2202ffe33053574a7
651,698
from typing import List import os def get_files_in_dir(abs_dir: str) -> List[str]: """Lists files in the supplied directory specified with an absolute path.""" return [ os.path.join(abs_dir, f) for f in os.listdir(abs_dir) if os.path.isfile(os.path.join(abs_dir, f)) ]
98b6fbae2a24d882effb520f6b173d0d5cdc7825
651,699
def makeQTXML(d): """Makes an xml file as plain text""" """make the header""" s = """<?xml version="1.0" encoding="ISO-8859-1"?> <?xml-stylesheet type="text/xsl" href="../../help.xsl"?> <documentation>""" s += '</documentation>' return s
0a5568241f22de046ce925ff4a562f96bb8fea30
651,700
import glob import os def listdir_recursively(): """ Returns a list of all files/directories of within the current working directory recursively. This function is like 'os.listdir()' but also recursing into directories! """ files_and_dirs = [] for pathname in glob.iglob(os.getcwd() + '**/**', recu...
5c0a19aa58bdbfdfd1c3ed50176f1a505f9f3c52
651,701
def applyOrderList(order, aList): """ Apply order to aList. An order of the form [2,0,1] means that the first element should be the 3rd element of aList, and so on. """ if order==[]: return aList else: return map(lambda v:aList[v], order)
4daacf5ee553cd57aa0e6b38e621f28505d26cfa
651,702
def mergeLists(genes1, genes2): """Merge list1 to list2""" list1 = genes1.split(',') list2 = genes2.split(',') for i1 in list1: if i1 not in list2: list2.append(i1) return ",".join(sorted(list2))
a9038d047618fa1b62f96118a51fb7ac950b73e0
651,703
def rec_repr(record): """Return the string representation of the consumer record. :param record: Record fetched from the Kafka topic. :type record: kafka.consumer.fetcher.ConsumerRecord :return: String representation of the consumer record. :rtype: str | unicode """ return 'Record(topic={},...
c0046b7450d7d025cd0c2e41252ae58b5658b744
651,704
def standard_rb(x, baseline, amplitude, decay): """ Fitting function for randomized benchmarking. :param numpy.ndarray x: Independent variable :param float baseline: Offset value :param float amplitude: Amplitude of exponential decay :param float decay: Decay parameter :return: Fit function...
60d67143e16307ebd2fa8581d269570590ae6774
651,705
import math def num_buses(n): """ (int) -> int Precondition: n >= 0 Return the minimum number of buses required to transport n people. Each bus can hold 50 people. >>> num_buses(75) 2 >>> num_buses(100) 2 >>> num_buses(101) 3 >>> num_buses(1) 1 >>> num_buses(0) ...
b22e49655ba7170070f00634cc47117124a5c88d
651,706
import pathlib def list_images(directory): """Generates a list of all .tif and/or .tiff files in a directory. Parameters ---------- directory : str The directory in which the function will recursively search for .tif and .tiff files. Returns ------- list A list of pathlib...
a174b30328dde171e6e15d59abaddd14be50defb
651,707
import argparse def set_argparse(): """Set the args&argv for command line mode""" parser = argparse.ArgumentParser() parser.add_argument( "index", nargs="?", type=int, default=0, help="start index") parser.add_argument( "step", nargs="?", type=int, default=1, help="step offset") re...
088d7ea5d30ea66de90a4c45b2441a2afe6473e5
651,708
def identifyJoystick(): """ Identifiserer hvilken styrestikk som er koblet til; enten logitech eller dacota (eventuelt en annen styrestikk) Denne funksjonen skal ikke endres. """ for i in range(2, 1000): path = ("/dev/bus/usb/001/{:03d}".format(i)) try: with open(pat...
85505fd3645f55c9eb71eee1837b97f3d5bc5030
651,709
def slope(y0, y1, x0, x1 ): """Resturn slope. Parameters ---------- Returns ------- """ deltaX = float(x1) - float(x0) deltaY = float(y1) - float(y0) return deltaY/deltaX
ed7192bed6e2ef24d6cc12d87c215270c50cb735
651,712
def d2dms(d, delimiter=':', precision=6): """ Convert decimal degrees to dd:mm:ss """ inverse = '' if d < 0: inverse = '-' minutes, seconds = divmod(abs(d) * 3600, 60) degrees, minutes = divmod(minutes, 60) return '{0:s}{1:.0f}{4}{2:02.0f}{4}{3:0{5:d}.{6:d}f}'\ .format(i...
0d4289965431fbec87f164a7541a8bd4e5f5a27e
651,713
def default_fit_options(reg_type, D): """returns an object with default linear regression fit options """ opts = {} opts['Display'] = None opts['verbose'] = False opts['TolFun'] = 1e-3 opts['MaxIter'] = 200 opts['Method'] = 'lbfgs' opts['MaxFunEvals'] = 2000 opts['TolX'] = 1e-3 ...
abe4e9d21c613824f9782ef79bef7a57d6d9858c
651,714
import os def _file_name_to_var(source_file_path): """ converts a file path into a python-valid variable name :param source_file_path: the full path, including extension :return: a valid python variable name """ # remove the extension var_name = os.path.basename(source_file_path).split('.'...
e59280e956bcfd73175654aed2b797c6eb9322d2
651,715
def extract_vocabulary(D): """ D is the list of documents, pairs of the form (cat, [token, ...]) Returns vocabulary V as a map from words to word indices. """ vocab = set() for (cat, tokens) in D: # naively including every word in the vocabulary! # This could be trimmed down, or...
9619f0387d115f08a2277d67013efb4d30e4ac04
651,716
def get_product(): """ Запросить данные о товаре """ name = input("Название товара? ") shop = input("Название магазина? ") coast = int(input("Введите его цену ")) return { 'name': name, 'shop': shop, 'coast': coast, }
f8fe939d2483fefe1b7a558ebc06906c97ec7d55
651,717
from typing import Optional from typing import Tuple def _format_show_name( show_name: str, season_num: int, show_num_tuple: Optional[Tuple[int, int]], original_title: str, quality: str ) -> str: """ Format the show number into 'Show Name - SxxEyy' if show_num_tuple is not None and has the same value. ...
2018fcede5c8c3bcb0a00995b303dee65ab30651
651,718
def lookup(collection, key): """ Lookup a key in a dictionary or list. Returns None if dictionary is None or key is not found. Arguments: dictionary (dict|list) key (str|int) Returns: object """ if collection: try: return collection[key] except ...
9f714f80d7846ceb6b25fa486ed501ccd5bac2da
651,719
from typing import Optional def _find_mark(instrumented_config: dict, path: str) -> Optional[dict]: """ Find mark in instrumented config by path :param instrumented_config: { field1: 'a', field2: 'b', '__line__': 0, '__field1__': { 'start': {'line': 1, 'column': 1}, 'end': {...} }} :param ...
54d9b444afc5ad2da6042d71e2a209a5ad0dcd25
651,720
from typing import List from typing import Any from typing import Dict def transformUserIDs(userID: str, args: List[Any]) -> str: """Transform user IDs.""" userIDMap: Dict[str, str] = args[0] return userIDMap[userID]
de417dd886325f41ef37010f88e80e6ada429db8
651,721
def abbrev_timestr(s): """Chop milliseconds off of a time string, if present.""" arr = s.split("s") if len(arr) < 3: return "0s" return arr[0]+"s"
e0e49fa0489a351e21ea8f1076bf234d54dd8da2
651,723
import json def read_template(template): """ Read and return template file as JSON Parameters ------------ template: string template name returns: dictionary JSON parsed as dictionary """ data = None with open(template) as data_file: data = json.load(data...
9708b1947998301ae2426bf30d375feb915bba3e
651,724
def variance(rows): """ Calculates the class variance of the remaining data param rows -- the dataset in the current branch """ if len(rows) == 0: return 0 data = [float(row[len(row) - 1]) for row in rows] mean = sum(data) / len(data) variance = sum([(d - mean) ** 2 for d in data]) / len(data) ...
f4ed75de200d573139047cfc89da837c9ee8ca9f
651,725
def _check_empty_script(filename, message, expect_fail): """Returns a script check that checks for empty diagnostics in a file. Args: filename: name of file containing diagnostic output. message: message to print when there are unexpected findings. message may be multiline. expect_fai...
982ce1cdef9e729c079aa74a9a692af2cdb32fc2
651,726
def get_holding_info(holdings_list,library): """Return some info of the holding in a holdings list for a libarry pass in parameter Arguments: holdings_list {[type]} -- [description] library {[type]} -- [description] Returns: [dict] -- [description] """ holding_info = {} ...
96acd229d716b709b119f6f1a0f8943c5dd9f951
651,727
import numpy def numpy_refract(in_directions, normals, etai_over_etats): """ Calculate the refracted ray. I have almost no idea what's going on in here :(. Stolen from https://raytracing.github.io/books/RayTracingInOneWeekend.html#dielectrics/snell'slaw Args: in_d...
0637c0c962b90c16bbb5ccf08e4657d59c2a9813
651,728
def project(position_current, velocity_current, acceleration_current, use_acceleration, delta_t): """ This module estimates the projected position of a particle. :param position_current: The position of the particle at time "t". It must be a numpy array. :param velocity_current: The velocity of the par...
41f49f90eb2eacbad8ec3b68bbe75a9eef47b8c3
651,729
def calc_salary(s_from, s_to): """Calc salary. First modify salary to get 'from', 'to' :param s_from: int, salary from :param s_to: int, salary to :return: int or None, size of salary by 'from' and 'to' """ if (s_from is not None and s_to is not None): return (s_from + s_to) / 2 ...
f9468e9f0c0db67bee7fa2285e5662f04dacfb62
651,730
def upsert_record(client, zoneid, record_name, value, record_type='A', ttl=300): """Updates or Creates the specified AWS Route 53 domain resource record Parameters ---------- client: boto3.client The boto3 'route53' client to utilize for the update request zoneid: str The Route 53 H...
e71cf391dfa2093f74929c6fecd9c36b5af622c6
651,732
def read_protein_from_file(file_pointer, include_tertiary): """ Modified from github.com/OpenProtein/openprotein:preprocessing.py on June 20, 2019. Original carries an MIT license. Copyright (c) 2018 Jeppe Hallgren. """ dict_ = {} _dssp_dict = {'L': 0, 'H': 1, 'B': 2, 'E': 3, 'G': 4, 'I': 5,...
bb0b0296de8923c394311a4f8359f47ece4a6a0c
651,734
def check_for_age_range(child_age, age_range): """ check if input child age is in the query's age range :param child_age: the age to check (int) :param age_range: the age range (list) :return: True if the age is in the range, else False """ return True if min(age_range) <= child_age <= max(a...
6d86cc56b57a0148d2736c97c30b123ed2a4166b
651,735
def get_padded_filename(num_pad, idx): """ Get the filename padded with 0. """ file_len = len("%d" % (idx)) filename = "0" * (num_pad - file_len) + "%d" % (idx) return filename
91ccb54951ea091603c5fbacb4f28013fa371e51
651,736
def GCD(a , b): """ define a function GCD which takes two integer inputs and return their common divisor""" com_div =[1] i =2 while i<= min(a,b): if a % i == 0 and b % i ==0: com_div.append(i) i = i+1 return com_div[-1]
8941563cb5fad97bf371e2575a44ba146cd60964
651,737
def decSinglVal(v): """Return first item in list v.""" return v[0]
747f66d136428461001ea76a1727865f46331c1e
651,738
def nest_class_ids(class_dict, ser_to_encode): """ convert the flat table of relationship types as text, into lists of ids df_rel_types: pd.DataFrame, the table of unique relationship types. used to create the id dictionary df_relationships: pd.DataFrame, the flat table of relationship types as text...
88c54a1ac117207fd2368f07017230ac9a8bbb07
651,739
def read_file(fname): """Read input file format.""" with open(fname,"r") as f: lines = f.read().strip().split("\n")[1:] return [map(int, l.split(" ")) for l in lines]
d5c452ef2cf1274006834b4a9887057d47741ef1
651,740
import os def is_file_available(filename): """Checks if a file is present on the filesystem. :param filename: A path pointing to the file to be checked. :type filename: str :return: Whether the file is there or not. :rtype: bool """ return os.path.isfile(filename)
091b45b1f95e7fbf630c796f9862642961295002
651,741
def special_elements(): """Elements that we will discard while keeping their contents that need additional processing.""" elements = ['q', 'sub', 'sup'] return elements
6f3a7827c75621c4eff423f82cab567617f37699
651,742
def sort_insertion(data): """插入排序。 将未排序好的元素与排序好的元素依次比较,并插入到合适的位置上,直至将所有元素全部插入到排好的 序列中。 """ first_unsorted_index = 1 # 第二个元素 while first_unsorted_index != len(data): for i in range(first_unsorted_index): # `i` 是已排序好的序列的指标 if data[first_unsorted_index] < data[i]: ...
71eb9b4db918d11c1af16e5d45b17e4dfd658f58
651,743
def leiafloat(decimal): """ --> Função que faz a validação da entrada de dados do tipo float :param decimal: Dados de entrada do usuário :return: Retorna o valor digitado pelo usuário, caso correto :print: Retorna mensagem de erro caso o dado de entrada não seja do tipo float """ while True:...
2aca9b4f177a2b3fd5418bc542b57722ba9d8d7f
651,744
import re def get_variable(config_text, variable): """ Get the value of a variable in config text :param config_text: str :param variable: str :return: value """ pat = re.compile(variable) for line in config_text.splitlines(): altered_line = line if pat.match(line): ...
506239777f3c23d9e6f617ae564f8489542e08c7
651,745
def dummy_dataset_paths_no_valid(tmpdir_factory): """Creates and returns the path to a temporary dataset folder, and train, and test files. """ # create a dummy dataset folder dummy_dir = tmpdir_factory.mktemp('dummy_dataset') # create train, valid and train partitions in this folder train_file ...
b73d73c0ac46498565ca6bba410b2d48089703d5
651,746
from typing import Iterable import warnings def _check_numpy_fn_param_value(name: str, value: Iterable, nargs: int) -> bool: """ Check whether a value is fit for use in a three argument numpy function """ if (isinstance(value, (tuple, list)) and len(value) == nargs and not any([i is None f...
8e935f0ea371fd3e48504a826a4092cc2918a07a
651,747
def _vector_neg(x): """Take the negation of a vector over Z_2, i.e. swap 1 and 0.""" return [1-a for a in x]
73f447f8ea5c8f9749a6a68d576aacbc11b1ad1c
651,748
def get_children(self): """ Creates a ``QuerySet`` containing the immediate children of this model instance, in tree order. The benefit of using this method over the reverse relation provided by the ORM to the instance's children is that a database query can be avoided in the case where the ins...
dba97203d8ef630b1fb6cef0a9977d0100f1d24f
651,749
def _grad_j(q_j, A_j, b_j, b_j_norm, a_1_j, a_2_j, m): """Compute the gradient with respect to one of the coefficients.""" return (A_j.t() @ q_j / (-m)) + (b_j * (a_1_j / b_j_norm + a_2_j))
d051883d848386af9eeb40a10029351158b075c0
651,750
def perimeter_square(length): """ .. math:: perimeter = 4 * length Parameters ---------- length: float length of one side of a square Returns ------- perimeter: float perimeter of the square """ return length * 4
07b8eefed384636a254c1ca84d861bebf80782ec
651,751
def gen_items(n_items): """"Function used in yt_dl to generate the string of indices corresponding to the desired number of items to be downloaded.""" items = '1' for ii in range(2,n_items): items = '{},{}'.format(items, ii) items = '{},{}'.format(items, n_items) return items
deafc759fa8dab3d15ff65a5dc27c6edd298143d
651,752
from typing import Any def client_info_query_response(token: str, response: Any) -> None: """client_info_query_response(token: str, response: Any) -> None (internal) """ return None
03aac9968d1b723c24a1421eb05c837f20da6f4e
651,753
def scope_modifiable(obj): """ docstring """ return bool(obj.conTextItem.rule) and \ 'terminate' not in obj.conTextItem.rule
8cd5061f2767475158fd88574b59a94c9392d329
651,754
def read_python_source(filename): """Read the Python source text from `filename`. Returns bytes. """ with open(filename, "rb") as fin: source = fin.read() return source.replace(b"\r\n", b"\n").replace(b"\r", b"\n")
470444440cdace6d00ebad788e83a30ba821f313
651,755
from typing import Union def game_of_life_rule(cell: bool, neighbors: int) -> Union[bool, None]: """Classic rule of John Conway's Game of Life.\n Common notation: `B3/S23`. """ # A low cell switches to high state if is has 3 neighbors if not cell and neighbors == 3: return True # A hig...
9e5c2ee31842ab397f4b3c62367732d006463eea
651,756
from bs4 import BeautifulSoup def ParseTables(html): """Parses each row of the html table. Args: html: list[] of duppels (filename, html). Returns: aidData: list[] of dict{} of aid projects. 'contract-number': contract number. 'contract-title': title of the project. 'country-region': country and/o...
ecac5d84b0a814011f65f01119d368f82b70180f
651,757
def index2slot(sx, sy, ox, oy): """**Return slot number of an inventory correlating to a 2d index**.""" print((sx, sy, ox, oy)) if not (0 <= sx < ox and 0 <= sy < oy): raise ValueError(f"{sx, sy} is not within (0, 0) and {ox, oy}!") return sx + sy * ox
0a1253d863fbbc560bb8400f9959d2b15b25aeb0
651,758
def get_increase_amount_nominal(P: float, f: float, m: int, n: int) -> float: """ " Parameters ---------- P : float Сума яку отримає власник векселя f: float номінальна річна облікова ставка m: int Кількість нарахувань у році n: int кількість років Returns...
cc258510b37747f6eabe3e9af990ccaeeb7c5e8a
651,759
import csv def write_dataset(dataset, dataset_file: str) -> bool: """ Writes a dataset to a csv file. Args: dataset: the data in list[dict] format dataset_file: str, the path to the csv file Returns: bool: True if succeeds. """ assert len(dataset) > 0, "The anonymized dat...
6082f29ab2a87ad62b4b944ff55483da62989004
651,760
def encrypt(m, p, q): """ 加密函数 """ e = 65537 n = p * q return pow(m, e, n)
f4b21e33602b5e1d40e3bc266aba9ade7cde5240
651,762
import random def modify_rate(rate, change): """ Calculate a random value within change of the given rate Args: rate: the initial rate to change from change: the maximum amount to add or subtract from the rate Returns: random value within change of the given rate Explanati...
09f3f47de58de786b06584bde80be56367c61435
651,763
def _get_test_cases(): """Provides test cases.""" is_training = [True, False] policy = ["learned", "random", "ordered_logits", "sobel_mean", "sobel_var"] i = 0 cases = [] for p in policy: for t in is_training: cases.append(("case_%d" % i, p, t)) i += 1 return tuple(cases)
f63b6cc287c38eadb824bec7db0a60a7ecca5762
651,765
def AAPIEnterVehicle(idveh, idsection): """ called when a new vehicle enters the simulation """ return 0
f5dc22651fe006b4efe330acfa581a00bc9aa8b2
651,766
def can_preview(file): """Return True if filetype can be previewed.""" return file.is_local() and file.has_extensions('.zip')
5a817c501c05dbbd16e7d1acf9639e358fb8aefa
651,767
import unicodedata def _preprocess_text(inputs, lower=False, remove_space=True, keep_accents=False): """Remove space, convert to lower case, keep accents. Parameters ---------- inputs: str input string lower: bool If convert the input string to lower case. remove_space: bool ...
47e256fb5640c14467038e514efdf6f0372d59cf
651,768
def make_ordinal(n): """ Convert an integer into its ordinal representation:: make_ordinal(0) => '0th' make_ordinal(3) => '3rd' make_ordinal(122) => '122nd' make_ordinal(213) => '213th' """ n = int(n) suffix = ['th', 'st', 'nd', 'rd', 'th'][min(n % 10, 4)] if...
fc66f85d6f1d745b89f7e89f3684365e92305b53
651,769
import pandas as pd def getdata(verbose=True, mode='all'): """ data = test_get_data() df = data['housing.csv'] df.head(3) https://github.com/szrlee/Stock-Time-Series-Analysis/tree/master/data """ flist = [ 'https://raw.githubusercontent.com/samigamer1999/datasets/main/titanic.csv...
5ba7c7f9d1a36dc366d95869769a4e9689546389
651,770
def generate_data(function, xdata, func_params): """Create a data set using a given function and independent variable(s). Parameters ---------- function : callable A function to use to generate data points from input values. xdata : array_like An array of values of shape (N, M) wher...
2aaa7bf0f46a3c6ede360b46cf873e2a1aa844da
651,772
def to_camel_case(input_string): """ Based on https://stackoverflow.com/a/19053800 Args: input_string (str): Returns: (str): """ if "-" in input_string: components = input_string.split('-') elif "_" in input_string: components = input_string.split('_') e...
a5e2676baf92ddf1f52a371732fa4697c067e3c3
651,773
def lr_calc(settings, epoch_id): """Update the learning rate with an exponential schedule.""" lr_mult = settings['lr_mult_base'] ** (1. / settings['num_epochs']) lr_new = settings['lr'] * lr_mult ** epoch_id return lr_new
9e32353eeb2f233ecc9e938d03ddf7db0061b5e7
651,774