content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def score_evaluation(state): """Return the state's score. This is a simple evaluation function used as default. """ return state.get_score()
7a68ddf5cc60b9d56c7e17b3ccdef6afbaf5e351
609,225
import gzip def open_log(log_file_path): """ Mapping files path with reading method Depending wether it is a plain file or gzip find a way to open the file Args: log_file_path: path to a log file Returns: Method for open file """ gz_format = ('gz', 'tgz') open_method = g...
50b734b10901632c76f97959f4fc37da4e2b7391
609,226
import pickle def read_x_y_z_fromfile(filename): """read x y z from file: filename :param filename: The file which we want to read from :returns: three arrays: x, y, z :rtype: numpy.arrays """ try: read_file = open(filename, 'rb') except IOError: print("cannot open this f...
76f75402e0fdbcd34c93f87cbb87e87fbb82d7a8
609,229
def build_member_matrix(mbr_list): """Return a matrix of information on the given members list.""" headers = [ 'Last Name', # Member.last_name 'First Name', # Member.first_name 'Party', # Member.party ] matrix = [headers,] for mbr in mbr_li...
685b511cea108660b0f51350c51434efdbc0ed64
609,230
import ssl import certifi def client_context() -> ssl.SSLContext: """Return an SSL context for making requests.""" context = ssl.create_default_context( purpose=ssl.Purpose.SERVER_AUTH, cafile=certifi.where() ) return context
8c6008ef418eca1b7b5e0b995bdeb0eed5b9b079
609,233
def split_df(df, key): """ Split dataframe containing structure(s) based on specified key. Most commonly used to split by ensemble (`key="ensemble"`) or subunit (`key=["ensemble", "subunit"]`). :param df: Molecular structure(s) in ATOM3D dataframe format. :type df: pandas.DataFrame :param key: key ...
d314cce13694291f2b5c17d0374e0be9c1d60f56
609,234
def check_xr_rio_ds_match(ds1, ds2): """ Checks if spatial attributes, crs, bounds, and transform match. Inputs ---------- ds1 : xarray.Dataset with rioxarray extension ds2 : xarray.Dataset with rioxarray extension Returns ------- bool """ if ( (ds1["spatial_ref"]....
6a4e1d95e90e53c887badd65febc206aee617cc6
609,236
def coco_root(dir, subset, year=2014): """Construct coco root dir.""" if subset == "minival" or subset == "valminusminival": subset = "val" image_dir = "{}/{}{}".format(dir, subset, year) print(image_dir) return image_dir
e4280dba65c49ef6f6d76e575bfee3aebcc51249
609,237
def _nom_2_eff(nominal_rate, piy): """Convert a nominal rate to an effective rate. :nominal_rate: nominal rate to be changed :piy: number of periods in a year for the nominal rate """ return nominal_rate / piy
106d595c7bc1444332a24a48ead85c81ee258df3
609,239
def bizect(l, steps="a"): """ given a list, select the a/b n-th group plus the last element >>> l = list(range(10)) >>> bizect(l) [0, 1, 2, 3, 4, 9] >>> b...
8d8a159d5961b025881ce7aa097fb45f6242fc28
609,241
def _GenerateNamespacePrefixAndSuffix(namespace): """Generates the namespace prefix and suffix for |namespace|. Args: namespace: A string corresponding to the namespace name. May be empty. Returns: A tuple of strings corresponding to the namespace prefix and suffix for putting the code in the corres...
538cce6b5bfe175b21c87a23c1d1158e139d2490
609,246
def get_fastq_manifest_entry_for_ss2(bundle): """Return the bundle manifest file entry for the input fastq files for SmartSeq2 pipeline. Args: bundle (humancellatlas.data.metadata.Bundle): A Bundle object contains all of the necessary information. Returns: tuple: A tuple consisting of the...
dedff071a7774e501e6715d56ecc7a8ba7fbfd0d
609,249
def translate_chromosome_name_from_nc_id(nc): """Helper function to translate chromosome name from NC ID""" if nc == 'NC_000023': return 'X' if nc == 'NC_000024': return 'Y' if nc == 'NC_012920': return 'MT' return str(int(nc[3:]))
0395493721db888c699204e29e41d41086f10dd8
609,250
def passwd(request): """Return db password.""" return request.config.getoption("--passwd")
30f7f14691b2bdb7974946775f790b283a9949e8
609,251
def _HasLabelChanges(args): """True iff any of the label flags are set.""" label_flags = ['update_labels', 'clear_labels', 'remove_labels'] # hasattr check is to allow the same code to work for release tracks that # don't have the args at all yet. return any(hasattr(args, flag) and args.IsSpecified(flag) ...
a94368cd6e0608eb6de608fbfbd856ca9c58cc50
609,254
from typing import OrderedDict import itertools def group_samples(samples, grouping="sample"): """Group samples by sample or sample run. :param samples: list of :class:`ISample <ratatosk.experiment.ISample>` objects :param grouping: what to group by :returns: dictionary of grouped items """ ...
aa839a72352e8b352312d08a88a6bbfc9729f1a5
609,255
import click def attach_help_option(cmd: click.Command) -> click.Command: """ Recursively attach -h/--help to every click Group and Command. Click by default only supports --help. """ help = click.help_option("-h", "--help") if isinstance(cmd, click.Group): cmd.commands = {name: atta...
1d5543cd194b8a6afcdc133e51df4e6766a2a428
609,258
def distribute(N,nmax): """ Distribute N things into cells as equally as possible such that no cell has more than nmax things. """ actual_max = int(2.*(nmax+1)/3.) numcells = int(round(N*1./actual_max)) each_cell = [actual_max]*(numcells-1) rem = N-sum(each_cell) if rem>0: each_cell.append(rem) assert sum(ea...
3a535872a252a15b0c762ac732e30f633e027c4a
609,259
import requests def request_arcgis_token( username, password, token_server="https://www.arcgis.com/sharing/rest/generateToken", exp=10): # 06/17/20, updated exp=10 mins (from 5 mins) by Surendra, G2 IS """Request a token from ArcGIS token server Request a user token from ArcGIS. On...
55b74c3a70ac919e8e455ee6f2fe5d7c14603ff7
609,261
import torch def read_subgraphs(sub_f, split=True): """ Read subgraphs from file Args - sub_f (str): filename where subgraphs are stored Return for each train, val, test split: - sub_G (list): list of nodes belonging to each subgraph - sub_G_label (list): labels for each subgrap...
b0c1455bf0efc813a4cffc23f8735cb3a258989d
609,262
def prepare_data(in_data, correction): """Prepare data to be feed into (image, steering angle) generator. Input data maps 3 images per record - center camera, left camera and right camera. Output data has 1 image per record. The correction is applied for left and right camera images. Args: ...
2b956dd70a1735051a45552cb8dba3faee73db00
609,265
import hashlib def md5hash(text): """Takes in text and returns the md5 hash""" hash = hashlib.md5() hash.update(text.encode("utf-8")) return hash.hexdigest()
a94f41fce11a43c4bbe038b7818b322c77cb3420
609,267
def running_sum(a, b): """ Add Expr a and b, unless either is None, in which case, return the other (None is treated as 0). """ if a is None: return b elif b is None: return a return a + b
cc037040f57af02f1b4909d3e4556f7c0ec02187
609,271
def pow2_exponent(val: int) -> int: """Compute exponent of power of 2.""" count = 0 while val > 1: count += 1 val >>= 1 assert val == 1 return count
cc74651a236ed41b7fb78d380dead6896ff47ff2
609,272
def get_zabbix_agent_status(code): """Get zabbix agent status from code.""" zabbix_agent_status = {1: "Available", 2: "Unavailable"} if code in zabbix_agent_status: return zabbix_agent_status[code] + " (" + str(code) + ")" return "Unknown ({})".format(str(code))
941c6a4185f11b679fd7616e36cbfa53a39e3797
609,276
def datetime_to_truncated_tuple(datetime_): """Converts a datetime to a tuple of (year, month, day, hours, minutes, seconds)""" return datetime_.timetuple()[:6]
e2b9d589daec3d7aa4a4849e9a5bd36914deacfe
609,278
def get_json_response(request): """Retrieve the response object with content_type of json.""" response = request.response response.headers.extend({'Content-Type': 'application/json'}) return response
6202cc22e6e556c11c61bd55ddc5b03004165d3a
609,279
def list_system_images(docker_client): """Return a list of all images on the current system. Args: docker_client (docker.client): An already initialized docker client Returns: list[str]: A list of strings of all image names/tags on the system. """ return [ image.attrs["RepoT...
64532349d98ab999e7308fb1128a303b0c5f5c47
609,281
import random import string def crypto_string(self, size): """ Securely generate a random string of a specified length Can include uppercase or lowercase ASCII characters and/or integers :param int size: desired length of string :returns: str """ # http://stackoverflow.com/a/23728630/199...
60e38f16078978a5999271e9679c5ce2749ace9c
609,283
import csv import itertools def setup_temperature_csv(csv_location): """Return a list of CSV values containing day & temperature data. The index of the list represents the day of the year, and the value at that index represents the temperature at that day. """ with open(csv_location) as csvfile: r...
0a06c77fb7a1ce968384744b0069cda7af22b6ca
609,294
def dump_datetime(value): """Deserialize datetime object into string form for JSON processing""" if value is None: return None return [value.strftime("%Y-%m-%d")]
e0461cb69a5b702b5139e8813e3c3585f9d74b87
609,296
def compute_wiener_filter(speech_psd, noise_psd): """ Compute Wiener filter in the frequency domain. Parameters ---------- speech_psd : numpy array Speech power spectral density. noise_psd : float or numpy array Noise variance if white noise, numpy array otherwise. Returns ...
2aa59a0f2b4d93fc22c20c4e29e0e79f35411191
609,297
def _unhash(hashed, alphabet): """Restores a number tuple from hashed using the given `alphabet` index.""" number = 0 len_alphabet = len(alphabet) for character in hashed: position = alphabet.index(character) number *= len_alphabet number += position return number
05441f45ddeb8962f550b80fbbef6ff6bbbca0b0
609,304
import socket def is_valid_ipv6(ip: str) -> bool: """Check whether the passed IP is a valid V6 IP address.""" try: socket.inet_pton(socket.AF_INET6, ip) except socket.error: return False return True
c997c0780d41e83655d34d99e30b74fd862c06e3
609,306
def calculate_iou(proposals, label): """ Calculate the intersection over union between bounding boxes of selective search and labels This code is adapted from https://gist.github.com/meyerjo/dd3533edc97c81258898f60d8978eddc :param proposals: A region proposal bounding box :param label: Bounding box...
fb2e724e2426c47d742b8c55be8e095b0304d13a
609,313
def remove_nested_parens(s): """ Returns a copy of "s" with parenthesized text removed. Nested paretheses are handled properly. """ result = "" paren_level = 0 for c in s: if c == "(": paren_level += 1 elif (c == ")") and paren_level: ...
b12cc39df102fc549bb5f9f84c53a6e6fb400be6
609,315
def _sparse_variance(X, tmp, axis=0): """Calculate variance across the specified axis of a sparse matrix""" mean_gene = X.mean(axis=axis).A.squeeze() tmp.data **= 2 return tmp.mean(axis=axis).A.squeeze() - mean_gene ** 2
77e60a42d2e467df15100623fe187a312a1e7b06
609,316
def iter_range(items): """ returns a zero based range list for iteration in templates """ return range(0,items)
15a22a26acdd8f0f2d4559d53f87837b634db5c2
609,317
def hexdecode(value): """ Decodes string value from hex to plain format >>> hexdecode('666f6f626172') 'foobar' """ value = value.lower() return (value[2:] if value.startswith("0x") else value).decode("hex")
b91af6ef77fa1bc8270b62dc72ed7c7a07d96aa9
609,319
from datetime import datetime def time_to_str(t_init): """Convert time integer to string. Convert a time duration to a string of format 00h:00m:00s or 1.000s if under 1 min. Parameters ---------- t_init: datetime Time to convert (in seconds). Returns ------- str ...
1915e03da396b2a6f4cc5f866a74b8514ae02ba5
609,320
def _generate_related_name(base_model, fields): """ Generates a related name to the tracking model based on the base model and traked fields """ related_name = base_model._meta.object_name.lower() return '_'.join(fields) + f'_{related_name}' if fields else related_name
8b7a57b1cac53ba076cb2eef748beb7c898406e9
609,322
def error(request, code=404): """ 根据 code 返回不同的错误响应 目前只有 404 """ # 之前上课我说过不要用数字来作为字典的 key # 但是在 HTTP 协议中 code 都是数字似乎更方便所以打破了这个原则 e = { 404: b'HTTP/1.x 404 NOT FOUND\r\n\r\n<h1>NOT FOUND</h1>', } return e.get(code, b'')
0a4f6a22a2bff4de0514607b1430335a1ef729ef
609,323
def undulating(number): """ Returns True if number is undulating """ if number < 100: return False number = str(number) for idx in range(len(number)-2): if number[idx] != number[idx+2]: return False return True
e114bebb260c8c1f895fcd1f9fefb3e14b38f9c6
609,332
def dependency_extracting(list_gate_qubits, count_program_qubit: int): """Extract dependency relations between the gates. If two gates g_1 and g_2 both acts on a qubit *and there is no gate between g_1 and g_2 that act on this qubit*, we then say that g2 depends on g1, which means that (1,2) will be in ...
8e0cc44fec8c1b767868c9af24b7354f5842c981
609,341
from typing import List from typing import Counter def _count_ngram(ngram_input_list: List[str], n_gram: int) -> Counter: """ Counting how many times each word appears in a given text with ngram Args: ngram_input_list: A list of translated text or reference texts n_gram: gram value ranged ...
0bec7e50d59336a1a977921bd31602c766973486
609,342
def compute_sized_powerlevel(grid, x, y, size=3): """ Compute combined powerlevel for sizexsize grid with topleft element (x,y). """ total_power_level = 0 for i in range(size): for j in range(size): total_power_level += grid[(x+i, y+j)] return total_power_level
196ec34746ef236b4f18e3109b1831fcdd2229ea
609,343
def get_sort_params(value, default_key=None): """Parse a string into a list of sort_keys and a list of sort_dirs. :param value: A string that contains the sorting parameters. :param default_key: An optional key set as the default sorting key when no sorting option value is specified...
f47d2c6e3c6d5f527bc2dedfecdba36e18283e44
609,347
def get_sample_labels_value(sample): """Extract the labels and values of a sample. prometheus_client 0.5 changed the sample type to a named tuple with more members than the plain tuple had in 0.4 and earlier. This function can extract the labels and value from the sample for both sample types. Arg...
345175be50c79a7016ea5b44f3e641a3f4e1ec89
609,355
def add_tabix_subparser(subparser): """ Get commandline arguments Args: subparser (?): Subparser object. Returns: args (Namespace): the parsed arguments. """ parser = subparser.add_parser("tabix", help="Tabix subparser") parser.add_argument("-vcf", "--variant-call-file", dest...
001d09086df2f9c0308496eeda6476f85345278e
609,356
def access_nested_dict(thedict: dict): """Demo of how to access a nested dictionary with a two dictionary comprehensions Examples: >>> a_dictionary = { ... "1-2017": { ... "Win7": "0.47", ... "Vista": "0.2", ... "NT*": "0.09", ... ...
bed5f41695eea5200fabec71385647d84ea7be26
609,357
def lenient_float(value, default=None): """Like Python's ``float`` but returns the default value when the value cannot be converted to a float.""" try: return float(value) except ValueError: return default
fa8da689a74fd5058314a0a5dfb3896e9c09542d
609,358
def _valid_value(value): """ this function is used to determine if the result of the consolidate function is valid. Valid types include int, float and lists of numbers. :param value: return value of the `consolidate` function :return: True if type is valid otherwise False """ value_type = ty...
02e2a923b703ef02d3d0f3e0fdbb220d97c3edea
609,359
def readtxt(filepathname): """Skips a line that starts with “>” and then reads in the rest of the file while removing any new lines (“\n”)""" sequence = "" for line in open(filepathname, 'r'): if line[0] != ">": sequence += line.replace("\n","") return sequence
b2485d2341bb772de52402116ee0fe122cc05a62
609,360
def avg(arr: list): """ Returns the average of the array. Uses floating-point division. """ return sum(arr) / float(len(arr))
dbbc95f88832dcafadca2338d333b61d9260a278
609,361
def _get_jax_to_tf_batch_norm_mapping(tf_bn_layer_name): """Returns a dictionary from JAX naming to tf naming for batch norm parameters. Args: tf_bn_layer_name: String denoting the name of the batch norm layer in tf. Returns: A dictionary from JAX naming to tf naming for batch norm parameters. """ re...
82e10fc7002fbd05c36674eb6bfdef60595474a8
609,365
def get_words(filename): """Return a list of all the words.""" result = [] with open(filename) as file: for line in file: result.append(line.rstrip()) return result
d25aa39a361019db371f27049a1aad905b362eb7
609,368
def create_ch_mapping(ch_names, name_addition): """Create a name mapping funtion to generate distinguishable channel names.""" ch_mapping = {} for ch_name in ch_names: ch_mapping[ch_name] = name_addition + "_" + ch_name return ch_mapping
aa75b7c36114f5ebb1a04af345bfde70a078eaf2
609,372
def verify(links): """ Verifies the integrity of all columns of links :param links: :return: True if integrity is maintained, False otherwise """ ret = True for key, val in links.items(): if len(key) < 2 or len(val["Company"]) < 2 or len(val["RoC"]) < 2 or len(val["Status"]) < 2 or l...
1f8895fa194e3acde423ad9b9b14372003403baa
609,374
def get_endpoint(platform: str): """ Return Api url by platform name. :param platform: igor, cgc, gcp, cavatica :return: api url """ if platform in ['igor', 'sbpla', 'default']: return "https://api.sbgenomics.com/v2" elif platform == 'cgc': return "https://cgc-api.sbgenomics....
4488530c7a604ee926e90bfab5a3f77059725fa3
609,376
import math def sum_probs(ln_pa,ln_pb): """ Returns the log prob. of two added probs. Pc = Pa + Pb => ln(Pc) = ln(Pa) + ln(1+exp(ln(Pb)-ln(Pa))), by Graves dissertation eq 7.18 """ #print(ln_pa,ln_pb,ln_pa + math.log(1+math.exp(ln_pb-ln_pa))) return ln_pa + math.log(1+math.exp(ln_pb-ln_pa))
67cbb5ce9e07b810240be14ea806bc38724d1a1d
609,383
def nest(dict_in, delim="__"): """Nests the input dict by splitting keys (opposite of flatten above)""" # We will loop through all keys first, and keep track of any first-level keys # that will require a recursive nest call. 'renest' stores these keys output, renest = {}, [] for key in dict_in: ...
097cdf142f6f763424117ff6fc926464cee0b3bf
609,384
def _get_all_cbns(cs_fielded_obj): """ Get all cbns of the provided fielded cs :param cs_fielded_obj: fielded cs for which we need to get the CBns for. :return: list of cbs of the provided fielded cs. """ return cs_fielded_obj.cbns
1621d47b88a7cc00f895f6ff5cde850917f93b20
609,388
def _get_class_name(obj): """Return a name which includes the module name and class name.""" class_name = getattr(obj, '__name__', obj.__class__.__name__) module_name = obj.__module__ if module_name is not None: return '{}.{}'.format(module_name, class_name) return class_name
3e9ad769fe3a3264a1eba30da4ef0039d2be50b9
609,389
def user_has_github_account(user): """Check if the user has a Github account linked. Args: user (User): User to check. Returns: bool: If the user has a Github account linked. """ return len(user.social_auth.filter(provider="github")) > 0
37c1e20c2c1bc097b817bf5513fd8c0c816d76ed
609,390
def read_file_bin(file_path: str) -> bytes: """ Read contents of file using binary mode. :param file_path: :return: """ with open(file_path, 'rb') as f: return f.read()
eaf7e7befcea998a25bf913c4467b1fa78017c38
609,395
def parse_password_and_prompt_args(args): """Parse -P/--password optional arg (nargs=?, const=True). """ # --P was provided without argument (True) if args.password is True: password = None prompt = True # --P was not provided (None), or provided with argument (<password>) else: password = args.p...
239b3ead6dbeda4778f1915b1a80b154bca7cbaa
609,397
def patchmaker(img, imsize=(100,100), percent_overlap=20): """ Split an image into overlapping patches Parameters ---------- img : ndarray Image from which to extract patches imsize : tuple of ints size of patches percent_overlap : int Percent as int of overlap desir...
fc96370132e18460aeff440112ce910f3601b62f
609,398
def GetUniqueFunctions(traces): """ Returns the unique set of functions for the input list of traces. """ functions = set() for trace in traces: functions = functions | trace.UniqueFunctions() return sorted(list(functions))
7c13eaac509adcdd94f5ba512a7606f074500522
609,399
import json def get_json_data(json_path: str) -> dict: """Get the json data in form of a dictionary Args: json_path: path to the json file. """ # Opening JSON file f = open(json_path) # returns JSON object as a dictionary json_data = json.load(f) # Closing file f.close() ...
13dd843df82febbd97e504ea77accad236ae6387
609,401
import fnmatch def included_in_paths(filepath, paths): """ Returns true if the filepath is included in the list of paths that may contain full paths or wildcard paths that need to be expanded. :param str filepath: Filepath to check :params list paths: List of paths to check against :retu...
cce8350832f5c6e4fb5620a347eea0d79dfccc5a
609,404
import struct def get_bool(s: bytes) -> bool: """ Get bool value from bytes :param s: bytes array contains bool value :return: bool value from bytes array """ if str(s) == "b\'F\'": return False elif str(s) == "b\'T\'": return True else: return struct.unpack('?'...
8da9c3c76a578ca347f8835404ef415005a39ed4
609,406
import re def hash_pickles(pickle_list): """ Assume we have a list of pickle files of the following general form: ------------------------------------------------ log-2019-02-22-12h-45m-00s-pickle-0.bin, log-2019-02-22-12h-45m-00s-pickle-1.bin, ... log-2019-02-22-12h-45m-00s-pickle-100.b...
a631e74f879e78aad58925c1f954b051ecd00b08
609,407
def qdict_to_dict(qdict): """ Convert a Django QueryDict to a Python dict. Single-value fields are put in directly, and for multi-value fields, a list of all values is stored at the field's key. """ return {k: v[0] if len(v) == 1 else v for k, v in qdict.lists()}
4c41bd91acd5e99eaf7323bd692f1af7c0628b90
609,408
import random def random_guesser_v2(passage): """Takes in a string and returns a dictionary with 6 features as keys and tuple values representing the binary value and score, respectively. Note: for the scores, 0 represents no score, while -1 represents '?' Arguments --------- passage: st...
e9072c4bf0908b6dcdeae0cd99f33ba50dd615f6
609,409
def summarize_bitmap(bitmap: list) -> str: """Give a compact text summary for sparse bitmaps""" nonzero_bits = [] for i, b in enumerate(bitmap): if b != 0: nonzero_bits.append(f'{i:x}:{b:02x}') sorted_nonzero_bits = ', '.join(sorted(nonzero_bits)) summary = f'{len(nonzero_bits)}/...
9208fbf2156fef17526f433556f870fa4aa64340
609,411
def denormalize(img, mean, std): """Denormalize an array of images with mean and standard deviation. Parameters ---------- img: array An array of images. mean: float Mean of img array. std: float Standard deviation of img array. """ return (img * std) + mean
1a459a5dd76a69e862c404677eefaaaa3c5b54e2
609,423
import re def classifyRequirements(plaintextRequirements): """ Takes a list of strings, each representing a requirement for annual reports. Returns a dictionary containing 5 k/v pairs: "budget" : T/F "attendance" : T/F "audited financial statements" : T/F "assessed valuation" : T/F "to...
ad6b6258bbd623e36f7532f84907c0a71ea928b5
609,425
def interleave_list(num_list): """ Takes in a list of numbers and interleaves them with the second half reversed """ if type(num_list) != list: raise TypeError("The argument for interleave_two_lists must be a list") if len(num_list) <= 2: return num_list final_list = [] le...
5297bc077f6717dd45b88d77cffebed7e4141dfd
609,428
def execute_command(ssh_client, command,verbose=False): """Runs a command on a remote host. Used to execute scripts on the cluster from local controllers. Only the stderr and stdout from the scripts are recorded, return values/exit statuses are not. Args: ssh_client: A paramiko SSHClient ...
03b2b4968088808f221294197b70243cc69ea346
609,437
def strip_name(name): """ Remove the last component of a Lean name.""" return '.'.join(name.split('.')[:-1])
a831313054b051a2c10cdeb16000de958e1a7ccd
609,442
def num2alphabet(number): """This function converts a number into its corresponding alphabetic letter. Meaning 1 gives a A while 2 gives a B. Since i use it to acces the excel collumns I convert the numbers to uppercase chars. When a number is higher than 26 the remainder gets appended to the A such that 27...
b4ece3202382330c937506a4a2c773746265e1a2
609,443
import pydoc def getspec(routine): """return a string with Python routine specification""" doc = pydoc.plain(pydoc.render_doc(routine)) return doc.splitlines()[2]
3d210634e4bd931e5c4793a129ab1832ea9c1cc8
609,445
def dummy_decorator(func): # noqa: D401 """Dummy property decorator, to test if chained decorators are handled correctly.""" return func
3cc6c14b387a9a81283ca26c802792e008e6cf72
609,447
import json def read_package(path): """Reads the package.json as a dict :param path: path to the package :type path: pathlib.Path :rtype: dict """ path = path / 'package.json' with path.open(encoding='utf-8') as file_object: return json.load(file_object)
706dfacb9e84d8f8e799c7e834d7cbc877817e42
609,448
def clone_model(instance, cls, commit: bool=True, exclude_fields: tuple=('id',), base_class_suffix: str='_ptr', **kw): """ Assigns model fields to new object. Ignores exclude_fields list and attributes ending with pointer suffix (default '_ptr') :param instance: Instance to copy :param cls: Class na...
b3b81d4aece8257f97b4b9285dab75f171d7b26e
609,451
def _calculate_number_batteries(_power_usage_, _deployment_duration, _battery_capacity_, _battery_derate_, _battery_self_discharge_): """ Calculate the number of batteries based off the power usage and deployment duration. This will also take into account the derate of the battery. :param _power_usage_...
1465dd55b3eea30479008f5cb0b18fa1798c3e55
609,453
import importlib def class_from_name(class_path): """ Instantiates a class from the given class path, consisting of a module path and the class name. :type class_path: unicode | str :return: type """ module_name, __, class_name = class_path.rpartition('.') module = importlib.import_module...
61dfa85d11dee2f0d5a8ae4dd8cf7a3eb00a15fd
609,454
import math def torsion_energy(phi, fc, multiplicity, npaths, phi0): """ Calculate the torsion energy using the periodic potential. One torsion term at a time, using this function: E = fc/npaths * [1 + cos(multiplicity*phi - phi0)] Args: phi (float): dihedral angle [degrees] fc (flo...
a434a34220cb50bed910dd3fad7f15ff43e2c22e
609,455
def _euclidean_dist(x, y): """ Scalar distance function. """ return abs(x-y)
9f151a7c553931ac7acfb4141dddf2b57d777194
609,464
def xpath_id(svg, id): """ Convenience function for finding an xml element with a particular id """ query = './/*[@id="' + id + '"]' targets = svg.xpath(query) if not targets: raise Exception("No elements found with id=%s" % id) if len(targets) > 1: raise Exception("Multiple element...
eb71f1a5e6bc2509fcc9eb2d3597ff7cfce34e82
609,466
import string def remove_punctuation(text): """Remove all punctuation from a piece of text. Args: text (str): Any piece of text. Returns: str: That text without any characters that were punctuation. """ translator = str.maketrans('', '', string.punctuation) return(text.translate(translator))
9a9b38d0dfdf9e7dc5851f213a517732aa26d700
609,472
from pathlib import Path import logging def make_a_logger(myinput: Path): """ Creates a logger that will output to the console and to a log.txt file in the same folder as the file specified by 'myinput'. """ # Create a custom logger # get root logger. FYI, this "root logger" is calle...
3f63463aa8c432266f957eea53d3b405b2d68400
609,474
from datetime import datetime from typing import Tuple import math def calc_travel(lat: float, lon: float, utc_start: datetime, speed_mps: float, heading: float, lead_s: float) -> Tuple[float, float]: """Calculate travel from lat, lon starting at a certain time with given speed and heading Arguments: ...
a9975f887a64a2915b55e43fd7269be63d818994
609,475
import torch def J_E(Q_t, action_tensor, is_demo, margin=0.8): """ Large Margin Classification Loss -------------------------------- Parameters Q_t: (b,|A|) tensor of q-values from model action_tensor: (b,|A|) 1-hot vector of actions taken is_demo: (...
7f4396468797bb4f15a57522df8b602bcaffd537
609,477
def forward(ctx, typespecs): """A converter just forwarding. All parameters are kept as they are.""" return ctx
5ed271a028c08481bdeec6f1a4b7a6381b4f6ae9
609,480
def oget(optional, default=None): """Get optional value or default value""" return default if optional is None else optional
4d21b5db358f4281c4942486fc61933a8cbe810e
609,486
def function(a,b): """This function is use to make average of two numbers""" c = (a+b)/2 # to make new function use def return c
dd7c4acb565ef357d986646a870246967741781e
609,487
def _ref_potential_walls_plumed(cv, at, kappa, offset=0.0, exp=2.0, eps=1.0, upper_wall=True): """A reference implementation of PLUMED UPPER/LOWER_WALLS restraint for testing.""" if upper_wall and cv <= at - offset: return 0.0 elif not upper_wall and cv >= at - offset: return 0.0 dist = ...
b9612ad3ccb2efa3c76459dea5d5d29d90540a46
609,488
import ast def _fields_of_2(a, b): """Return dict of fields of both nodes. Key is field name, value is a pair containing the field values for the 2 nodes. If a field is missing on one node, None is used instead of the missing value. """ ret = {} for f, v in ast.iter_fields(a): l ...
094b65fe6a446db27db6c49010e27530d488e180
609,490
def reciprocal_viewname(viewname): """ Return the name of the reciprocal view Parameters ---------- viewname : str Returns ------- reciprocal_viewname : str Examples -------- >>> reciprocal_viewname('L-LT') 'TL-L' """ tx_path, rx_path = viewname.split("-") ...
732d3db612c9587b108181c72d960bfe213c630b
609,491