content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def sum_powers_in_range(m, n, p): """ What comes in: Non-negative integers m and n, with n >= m, and a number p. What goes out: the sum m**p + (m+1)**p + (m+2)**p + ... + n**p for the given numbers m, n and p. The latter may be any number (possibly a floating ...
872989e94ff242ea8a2b73d7512a168aa0ad28e3
612,663
def tf(term, doc_terms): """ Calculate tf measure for a document """ return doc_terms.count(term)*1.0/len(doc_terms)
c74e47b7a3d13590f405806ed423be7351bd6c7b
612,665
def _translate_attachment_summary_view(_context, vol): """Maps keys for attachment summary view.""" d = {} storage_pool_id = vol['id'] # NOTE(justinsb): We use the storage_pool id as the id of the attachment object d['id'] = storage_pool_id d['storage_pool_id'] = storage_pool_id d['server_id'...
b5ed8754d544dd16cc325c7cc15b74c97c59e64a
612,666
def format_message( text: str, *args, no_arg_phrase: str = "None", enclosing_char: str = "`") -> str: """Construct message from given text with inserting given args to it and return resulting message. Args: text: Main message text with formatting brackets `{...
b03bba4b7dea24fbb3cae4e993c0acc95665c4d6
612,667
import math def degrees_to_cos(x): """Takes the cosine of an angle given in degrees.""" return math.cos(math.radians(x))
cab632f20fdda772d834bff9c68314a8491d3b13
612,668
from typing import List def read_reference_files(*args) -> List[List[str]]: """Read every file given in `args` and produce a list of lists that supports multiple references.""" all_lines = [] for fname in args: lines = [] with open(fname) as f: for line in f: ...
b3e40e02e1349acb35e9f5c036d74d3ce65d018f
612,671
def dropwithsuffix(df, suffix): """ Drop all columns whose name ends with given suffix """ idx = df.columns.str.endswith(suffix) df = df.copy() return df.loc[:, ~idx]
b701e200df2ed37063e7c802bfb639fcdde56141
612,675
def update_label(old_label, exponent_text): """ Update an axis label with scientific notation using LaTeX formatting for the order of magnitude. """ if exponent_text == "": return old_label try: units = old_label[old_label.index("(") + 1:old_label.rindex(")")] except ValueErr...
2e23fda6e365b058dc2c3883fd2db06700742075
612,677
def calc_mean_score(movies): """Helper method to calculate mean of list of Movie namedtuples, round the mean to 1 decimal place""" scores = [movie.score for movie in movies] return round(sum(scores) / len(scores), 1)
f2923c8dd583b1e4aa54dfd4191c5a7aa5484b88
612,681
import math def round_sig_figs(num, sig_figs): """Round to specified number of sigfigs. # from http://code.activestate.com/recipes/578114-round-number-to-specified-number-of-significant-di/ """ if num != 0: return round(num, -int(math.floor(math.log10(abs(num))) - (sig_figs - 1))) else: ...
b6d5e92c1ed787f1c763f8669805cf6fc0e28930
612,684
def run_games_and_record_payoffs(game_queries, evaluate_game, ckpt_to_policy): """Simulate games according to game queries and return results. Args: game_queries: set of tuples containing indices specifying each players strat key_query = (agent_tuple, profile_tuple) format evaluate_game: callable fun...
e026b86e606aa222e42c0ba50a33ce1ee3b563bf
612,686
import re def _filter_cluster_name(cluster_name): """Filter cluster_name argument, only allow alphanumerics and .-_""" return re.sub('(?!-)\W', '', cluster_name)
226455686b662e77bc307c87840bc8943894b771
612,687
import math def totalTreeStepsFinder(nt, sl): """totalTreeStepsFinder() takes a newickTree and a stepLength and finds the total number of steps in the entire tree. """ numSteps = 0 if nt is None: return int(numSteps) numSteps = math.ceil(nt.distance / sl) return int(numSteps + tota...
4e533bd1b260e0d90d6d0bf3b07404924e59620a
612,688
def _partition_examples(examples, splits_dict): """Splits examples according to a split dictionary.""" # Create a dict to hold examples. partitions = dict() # Store the total number of examples. num_examples = len(examples) # Iterate over the items specifying the partitions. for (split_name,...
b44c20f000e9ba359294354e42e66d08bd44fa60
612,690
def div_ceil(n, d): """ The smallest integer k such that k*d >= n. """ return (n//d) + (n%d != 0)
4cdbb7005797c8c9f8c81817b7566bcbe9e58f88
612,695
def user(request): """The user to use for fetching.""" return request.config.getoption('--user')
b19ca8c5b90e1fd8fff8fbbce1b15dcc32ef0cd7
612,696
def declension(singular, plural, count): """ Returns the appropriate word variation for the given quantity. Args: singular (str): The singular variation. plural (str): The plural variation. count (int): The count. Returns: str: The appropriate variation for the quantity...
56b03d758d75cbd06e8f1644d67f9d4b77f37e5f
612,697
import codecs def read_wordpairs(wordpair_path, format="google"): """ Read wordpair file with wordpairs and their similarity scores assigned by humans. Args: wordpair_path (str): Path to word pair file. format (str): Format of wor pair file {google|semrel} Returns: tuple: Tuple of a list of word pairs and...
b6457aec448dd74906dbf55f4ebab131f5f183c4
612,698
import csv def read_csv(filepath: str): """ Returns a list of rows from a CSV file. Parameters: - filepath: str - the filepath from the CSV file """ data_rows_list = [] with open(filepath, 'r', encoding='utf8', newline='') as csvfile: csvreader = csv.reader(csvfile) n...
9f7784d5e13f75b258636b83a8a789030cf1cc0e
612,702
def unpack_table(rec, param_columns, amp_column): """ Unpack initial fitting parameters from a table. Parameters ---------- rec : recarray Records array (table) holding parameters. param_columns : list List of column names which hold lineshape parameters. See :py:func:`...
860114588804394c2a0c9d8a254d55c9e42bbd53
612,703
def compute(params): """ Wrapper method to call Timeline.sample used by multiprocessing.Pool. :param params: (timeline, number of scenarios, timeline name) :return: (name, sampling) """ tl, nb, name = params return name, tl.sample(nb)
ba9c42e7429d7ae743f79b03e8703c32da1bc631
612,714
def get_input_group(building_name, mapping): """ Gets input tags for a specified building Arguments building_name -- the name of the building Returns input_group -- list of opc_tags, in the order specified by mapping.json, corresponding to the inputs of the specified building """ return mapping[building_nam...
cef0787e1c9c40bd8d7117242de6be1433d591b6
612,717
def binary_search_iterative(arr: list, key) -> int: """Returns index of key in sorted arr if key is in arr, else -1. Implements: https://en.wikipedia.org/wiki/Binary_search_algorithm#Algorithm """ lo, hi = 0, len(arr) - 1 while lo <= hi: mid = (lo + hi) // 2 if arr[mid] == key: ...
e401077ecf0a30ac372b0f87384401c7584ff4bd
612,718
from pathlib import Path from typing import List def repo_folder_with_random_existing_files(tmp_path_factory): """ Returns a temporary directory containing a few random files to test methods which check for a files existence within a certain directory. """ folder: Path = tmp_path_factory.mkte...
e6265cd5684834595a8542a0b38355660d79e8cf
612,720
def convert_to_24_hours(time, ap): """ Given a hour and an a/p specifier, then convert the hour into 24 hour clock if need be """ if ap.lower() == 'p' and time <= 12: time += 12 return time
1e7c1ac7eac0e6336b89c61eb03aff6b3fd21835
612,725
def makeStringEndWith(inputString, symbol): """ If the inputString does not end with symbol, append it to inputString and return the result. Else, return the inputString. Args: inputString: the string to be examined to make the output symbol: the symbol that the out...
20c3b649e08c8fe9ac077506f6b993311220e515
612,726
def read_joint_names(filename): """Read motion capture's body joint names from file Args: filename: file name to read Returns: joint_names: list of joint names """ with open(filename, 'r') as f: org = f.read() joint_names = org.split(',') return j...
8f7347d1447f53025898acadea86ff0a912928da
612,729
def cpu_bound(callable_): """ Marks callable as mainly cpu-bound and safe for running off the MainThread. """ callable_.__blocking_type__ = 'cpu' return callable_
77213b52b4226a90e25e63bc1576ec51fb79350c
612,730
import warnings def deprecated(replacement=None): """ Decorator to mark classes or functions as deprecated, with a possible replacement. """ def wrap(old): def wrapped(*args, **kwargs): msg = "{} is deprecated".format(old.__name__) if replacement is not None: ...
37b7d0d760fae73a1114741a793c86a6f3b7d570
612,734
import six def _deserialize_primitive(data, klass): """Deserializes to primitive type. :param data: data to deserialize. :param klass: class literal. :return: int, long, float, str, bool. :rtype: int | long | float | str | bool """ try: value = klass(data) except UnicodeEncod...
eb905a62509a336d59133862bbd516c48e810a97
612,735
def float_wav_to_short(wav): """ Given a float waveform, return a short waveform. The input waveform will be clamped between -1 and 1. """ return (wav.clamp(-1, 1) * (2**15 - 1)).short()
7892aa1641fc19b19f5e25fe35354dfacb0be462
612,737
def chop_markdown_header(md): """ Remove empty lines and travis-ci header from markdown string. :param md: input markdown string :type md: str :return: simplified markdown string data :rtype: str """ md = md.splitlines() while not md[0].strip() or md[0].startswith('[!['.encode('utf-8...
89bd632b1cb79daa3aa9e9400d9437cc7f970bf5
612,738
def get_file_names_on_anaconda_channel(username, anaconda_cli, channel='main'): """Get the names of **all** the files on anaconda.org/username Parameters ---------- username : str anaconda_cli : return value from binstar_client.utils.get_binstar() channel ...
4f547249fabf7a199976a6207820df46833588dd
612,742
def flatten(dictio, output=None, parent=()): """ Function to flatten a nested dictionnary. :param dictio: nested dictionnary to flatten :type dictio: dict :param output: list containing the flatten dictionnary. In the first call, the output should not be set as the flatten dictionnary is given ...
b9c75c8b41f7f941f624a6ff7be87ade2d7e0df6
612,743
def _rec_subclasses(cls): """Returns all recursive subclasses of a given class (i.e., subclasses, sub-subclasses, etc.)""" subclasses = [] if cls.__subclasses__(): for subcls in cls.__subclasses__(): subclasses.append(subcls) subclasses += _rec_subclasses(subcls) retu...
913108802ca3f5b36a3ec18fdedf93eab09e467c
612,744
def pv_fullname(name): """ make sure an Epics PV name ends with .VAL or .SOMETHING! Parameters ---------- pvname: name of PV Returns ------- string with full PV name """ name = str(name) if '.' not in name: name = "%s.VAL" % name return name
5ad60054057a5668ac9cdaab2384d1f65f14f1c7
612,747
from urllib import request from io import BytesIO def download_image(url: str): """Pass an url to download image for prediction Params ------ url: str Url from which to retrieve image Returns ------ filename: str By default every downloaded image will be stored in...
84b6f0f0a08755f72847add0ab1222269ffd435d
612,748
def check_scorecard(id, mongo_conn): """ Function Description: Check to see if the scorecard exists in the DB. Function Parameters: id (Int: The id of the scorecard from Garmin we are inserting.), mongo_conn (Collection: The connection to the Mongo Collection.) Function Throws: Nothing Func...
9fadd9498e75691e18c0b750226a37d27df0e96d
612,750
def sum_hours(entries): """Return the sum total of get_total_seconds() for each entry.""" return sum([e.get_total_seconds() for e in entries])
1522bb65b3fc5bbe73360f9efc3362681fbe9c93
612,756
def role_to_key(role: str) -> str: """Return the dict key string (no whitespace) for the given object role.""" return role.replace(' ', '_')
0368df8e0f53f37d4b31558ad3d8f693fda336f7
612,757
def stable_serialize_call_arguments(execution, args): """Work just like execution.serialize_call_arguments, but serialize arguments in lexicographical order, so test outputs are stable. This doesn't change semantics of the serialization process (as objects identity will be preserved), yet it makes test...
3e20c9b9288eacd608e9a4513dd3a248e0a22ca5
612,761
def file_url(filename): """Convert a local filename to the file's URL on GitHub.""" gh_path = filename.replace("\\", "/")[15:] # org/repo/path_to_file url = ( "https://github.com/" + "/".join(gh_path.split("/")[:2]) + "/blob/master/" + "/".join(gh_path.split("/")[2:]) ) ...
b7fc1d86b39a93a6d1539baab1334aa5a7402755
612,762
def dr_central(f, dr): """ First order central difference differentiation. Parameters ---------- f: ndarray The variable to be differentiated. dr: scalar Step size in r. Returns ------- ndarray """ return (f[2:, 1:-1] - f[:-2,1:-1])/(2*dr)
3ce7a8e1a1b22bec9e1b9a38703a3e449a4bbff5
612,764
def format_kfp_run_id_uri(run_id: str): """Return a KFP run ID as a URI.""" return "kfp:run:%s" % run_id
6bed55ac72c316d91ef45f0a064dc5c3aa9091d4
612,765
def calc_hc(wind_speed): """ This function calculates the convective heat transfer coefficient for external surfaces according to ISO 6946 Eq. (C.6) in section C.1 :param wind_speed: wind speed at this time step from weather file. :return: hc: convective heat transfer coefficient of externa...
52bbb3442afa91bbbbb378df614dc47768f88095
612,766
def list_of_first_n(v, n): """Given an iterator v, return first n elements it produces as a list.""" if not hasattr(v, 'next'): v = v.__iter__() w = [] while n > 0: try: w.append(v.next()) except StopIteration: return w n -= 1 return w
ac98423187b1a45f5c1e5e47b215245ecb30ef6c
612,768
def pad_bounds(bounds, percent=0): """Pad the bounds by a percentage Parameters ---------- bounds : list-like of (west, south, east, north) percent : int, optional percent to pad the bounds Returns ------- (west, south, east, north) """ xmin, ymin, xmax, ymax = bounds ...
b2c94bb5da16efef629bde0d61d361a005b06565
612,773
def two_lens_EFL(f1,f2,d): """Calculate the focal length of two thin lenses sepatated by air. The units must match, and will return the same units. Parameters ---------- f1 : float Focal length of lens 1 f2 : float Focal length of lens 2 d : float Separation di...
f5f87a1414f254ccdbc69aa577e118487cbe9984
612,776
def query_complex_dict(dictionary, preferred_key, key, secondary_key_list=[]): """dictionary is a dictionary of dictionaries with multiple level hierarchies (often related to json file) preferred_key and key are the first-level key When preferred_key is available, use it instead of key Assume at least o...
f71b123dd18b1a701fba4096bbf72ade3f727fdf
612,778
def graphemes(language): """ Make sure a language has segmented forms, i.e. lists of graphemes for each form. """ try: return bool(len(language.forms_with_graphemes)) except (AttributeError, TypeError): return False
df648215589f7f020e50d1eea26c93903aa9f1a9
612,780
import re def size_in_bytes(size_str, default): """ Read a (memory) size as string and convert it to bytes. :param size_str: memory size as string. Allowed formats like "1024", "1G", "1g", "1.0 G", "1.0 GB" :param default: a fallback value as int :return: """ if size_str is None and isinst...
793635c93f995dd2b09e4466b2d8f62141414342
612,784
def add_connection(network, user_A, user_B): """ Adds a connection from user_A to user_B. Makes sure to check that both users exist in network. Arguments: network: the gamer network data structure. user_A: a string with the name of the user the connection is from. user_B: a string with the...
a7af954ba71be5610df01301e2489dc3fb40915e
612,785
def create_dict(entities): """Create the html5 dict from the decoded json object.""" new_html5 = {} for name, value in entities.items(): new_html5[name.lstrip('&')] = value['characters'] return new_html5
2ad9700acbd5ff8b0e2d4b92073b2c1483ba968c
612,789
import torch def remove_segments(original_segments: torch.Tensor, to_be_removed_segments: torch.Tensor) -> torch.Tensor: """ Remove speech segments list in to_be_removed_segments from original_segments. For example, remove torch.Tensor([[start2, end2],[start4, end4]]) from torch.Tensor([[start1, end1...
5bc0272bde30efefb3cb293666a3d5adc5d8b01f
612,792
def uses_all(word, letters): """Write a function named uses_all that takes a word and a string of required letters, and that returns True if the word uses all the required letters at least once.""" for letter in letters: if not(letter in word): return False return True
201077a03e89c5b99af44d899edbd69b77e65f64
612,796
def sanitized(*args): """ Returns a sanitized string uniquely determined by the supplied args, any of which can be a string or C{None}. C{None} args are ignored. Any spaces within an arg are removed. The text of multiple args is joined with an underscore. For example, supplying "Santa Fe" and "...
bf25f9e68889f4157663e0e09ec14d9668e41d6b
612,797
def _Backward3a_v_Ph(P, h): """Backward equation for region 3a, v=f(P,h) Parameters ---------- P : float Pressure [MPa] h : float Specific enthalpy [kJ/kg] References ---------- IAPWS, Revised Supplementary Release on Backward Equations for the Functions T(p,h), v(p...
773d18aa96746ea4b3fd620b1a563654ca3ad22e
612,798
from typing import Tuple from typing import List def n31(a: int) -> Tuple[List[int], int]: """ Returns the Collatz sequence and its length of any postiver integer. >>> n31(4) ([4, 2, 1], 3) """ if not isinstance(a, int): raise TypeError("Must be int, not {0}".format(type(a).__name__))...
bb8d7add0e512b95e1908ecf632b07ed2abb1134
612,801
from typing import List from typing import Tuple from typing import Any def sort_dict_by_value(dictionary: dict, reverse: bool = False ) -> List[Tuple[Any, Any]]: """Sort a dictionary by the values which have to be sortable. Args: dictionary: The dictionary to sort. rev...
61548b5bc0841a56a2f4130e3dffb07be4cf95f8
612,802
def format_datetime(value, format='short'): """Filter that transforms a datetime into a formatted str. The filter is to be used in JINJA2 templates. The possible formats are the following: * short: dd / mm / yyyy * full: mm dd yyyy :param datetime value: Date to be transformed. :param ...
66301cabf5e715fb5cc2916bd57e9fdcbb67429e
612,803
def find_repo_item(repos, name): """Find a repo in a dict mapping Repository objects to data. Arguments: repos: (dict mapping Repository objects to data) name: (str) the full_name of the repo to find. Returns: The data found in the dict, or None if not found. """ for repo,...
9bb062a07bd38ee6311690474d49a0d038c44a5c
612,807
def get_class(str_or_class): """Accept a name or actual class object for a class in the current module. Return a class object.""" if isinstance(str_or_class, str): return globals()[str_or_class] else: return str_or_class
2686d5bd86c54d495beaddfac9db1527694b0cb4
612,808
def parse_id_list(id_list) -> str: """ Converts a list of IDs to a comma-delimited string """ if type(id_list) is list: returned = "" for s in id_list: if len(returned) > 1: returned += "," returned += str(s) return returned else: retur...
711ee35a5b1bf4c110850e4978a5902fa8ce40f5
612,809
def format_persec_column_label(label): """ Return a re-formatted PerSecData column label This function converts column labels to snake case (all lower-case and spaces converted to underscores). Parameters ---------- label: str The original column label to be formatted Returns --...
b882ea9e0255d8cebec40f6d99c8c01df81959dc
612,811
def comb(N, k): """Compute N choose k""" if k > N or N < 0 or k < 0: return 0 M = N + 1 nterms = min(k, N - k) numerator = 1 denominator = 1 for j in range(1, nterms + 1): numerator *= M - j denominator *= j return numerator // denominator
98aa73d29413aaa600ce094004cc0242444968fc
612,820
def checksumStr(data): """Take a NMEA 0183 string and compute the checksum. @param data: NMEA message. Leading ?/! and training checksum are optional @type data: str @return: hexadecimal value @rtype: str Checksum is calculated by xor'ing everything between ? or ! and the * >>> checksumSt...
c135a1942e0e31fecbad9aef560722c732ebc162
612,824
def is_correct(pred_sentence, pred_sentences, gold_sets): """ A predicted sentence is correctly identified if it is part of a gold rationale, and all other sentences in the gold rationale are also predicted rationale sentences. """ for gold_set in gold_sets: gold_sents = gold_set["senten...
8eab3649d25c10171656cb8c68ccafb205da1d44
612,826
def table_log_format(name, timestamp, data): """ Return a formatted string for use in the log""" return str(str(name) + '&' + str(timestamp) + '->[' + str(data) + ']')
db801b3a223b1418d21804fba54133814469817d
612,828
def get_region_code(region_code): """Returns region code corresponding to an AWS region abbreviation.""" try: region_mapping = {'us-east-1': 'USE1', 'us-east-2': 'USE2', 'us-west-1': 'USW1', 'us-west-2': 'USW2', 'af-south-1': 'CPT', ...
5c8debdd2aba723047d8b57438563742e0e97581
612,830
def significant_hail_parameter(mucape, mixing_ratio, lapse, temp_500, shear, flh): """ Calculate the significant hail parameter, as given at https://www.spc.noaa.gov/exper/mesoanalysis/help/help_sigh.html Arguments: - mucape: Most unstable parcel CAPE [J kg-1]. - mixing_ratio: ...
ca3fc78c2e20e2357797a63624fbb1e6d518d54d
612,832
def make_cache_key(baseurl, params_d, private_keys=[]): """Makes a long string representing the query. Alphabetize the keys from the params dictionary so we get the same order each time. Omit keys with private info.""" alphabetized_keys = sorted(params_d.keys()) res = [] for k in alphabetized_ke...
dcbb1447d19154f71cf54641ea47b0773aeacbbf
612,834
import ctypes def _get_word(array, index): """ Shorthand for getting two byte values in an array. Args: array: The array the get stuff from. index: The start index of the word to get. Returns: A c_ushort containing the value of the word. """ value = ctypes.c_ushort(array[index] << 8) value.value...
6d01111fadd29e5a04548630f9c47456bb9cf936
612,835
from typing import List def sequence_to_int(line: str) -> List[int]: """ Transform a sequence of digits to a list of integers. """ return list(map(int, line))
650e3744b1f667e166df3122630ca123c61d728e
612,836
def num_disambiguated_iupac_strings(seq, ambiguous_letters, disambiguation): """ seq is Bio.Seq.Seq or str ambiguous_letters is string containing ambiguous IUPAC codes disambiguation is dict with key from ambiguous_letters and values the strings containing the unambiguous versions (e.g., Bio.D...
9a3a989506d67e9a5bf07803bc69c79979b8fd16
612,837
def shipping_charge_excl_discount(method, basket, postcode): """ Template tag for calculating the shipping charge (excluding discounts) for a given shipping method and basket, and injecting it into the template context. """ return method.calculate_excl_discount(basket, postcode)
48f5932101f98bcefd683722ec95c2c47a39f669
612,842
def is_extended_cigar_prefix(old_cigar_pairs, new_cigar_pairs): """ Checks if new_cigar_pairs is just an extension of old_cigar_pairs e.g. ("=",5) -> ("=",5),("X",1),("=",2) or ("=",5) -> ("=",6). :param old_cigar_pairs: :param new_cigar_pairs: :return: bool """ if len(old_cigar_pairs) >...
2dc174db0ca58713b6ef71f398eeb2f8a345d1c8
612,843
def keepCells(notebook): """ Finds the tag 'keep' in any cell and if it exists, remove the ones that don't have it Returns dict without 'hide' tagged cells """ has_keep = False for cell in notebook['cells']: try: if 'keep' in cell['metadata']['tags']: has...
2f485e250145605ff319673760785fc9e2622181
612,845
def remove_quotes(text_): """ Remove surrounding quotes if there is Parameters ---------- text_ : str text whose surrounding quotes are removev Returns ------- str text without surrounding quotes """ if len(text_) < 2: return text_ if text_[0] == text...
2a1cb63fc3624d647a56bcb3c5493d9646edc0ea
612,850
from typing import List def compute_ap(pos: List[str], amb: List[str], ranked_list: List[str]): """Compute average precision against a retrieved list of images. There are some bits that could be improved in this, but is a line-to-line port of the original C++ benchmark code. Args: pos (List[str]):...
ea653c614990b7b588e2e3413fc5b3dd278c4092
612,851
def sel_speaker(speakers, gender='both', accents_excluded=[]): """select a subset of speakers based on gender and accents gender: 'M', 'F', or 'both' accents_excluded: list of excluded accents, e.g. ['Indian', 'Unknown'] """ if gender != 'both': speakers_selected = [spk for spk in speakers if spk['g...
34335cbac7ecb71b0af1a79d83819ffdcbae79fc
612,856
import requests def get_instance_metadata(compute_url, instance_id, token): """ Retrieve details about the running instance """ url = "%s/servers/%s" % (compute_url, instance_id) headers = {"X-Auth-Token": "%s" % token, "Content-type": "application/json"} curl = requests.get(url=url, headers=headers...
6da0951a2a5be9f522a4645e313d793d9e57ce6a
612,857
def get_row_shape(arr, nrows=1): """Return the shape of a row of an array.""" return (nrows,) + arr.shape[1:]
cdb933a585065c7afe99bf92be34694e4dd47f6b
612,860
from typing import Iterable def or_instances(obj, *instance_types): """ Tests if obj is an instance of any supplied instance types. :param obj: the object to test :param *instance_types: an iterable of instance types to test for. :return: True if the object is an instance of any ...
fcbf916e7691d432f2e80ebae8e56182312f4a90
612,861
def remove_keys(d, *keys): """Returns a new dictionary with the given keys removed. Parameters ---------- d : dict The original dictionary. keys : list of keys The keys to remove. If the key is not found in the dictionary, it is ignored. """ result = dict(d) ...
6b6930714213952110c3abcdf7fceaab8ccc7429
612,862
def word_stats(word_counts): """Return number of unique words and word frequencies.""" num_unique = len(word_counts) counts = word_counts.values() return (num_unique, counts)
4b39ab7d91bc3c584743488000a3ffcbfe37fd9e
612,865
def get_health_check(app, portIndex): """Get the healthcheck for the app.""" checks = [] for check in app.get('healthChecks', []): if check.get('port') or check.get('portIndex') == portIndex: checks.append(check) if len(checks) > 0: return checks return None
2e0998a9ac4018faf4484a6200d4e9719815eb42
612,866
def u(z, theta) -> float: """ Defining utility function. Args: z(float): parameter theta(float): parameter Returns: Utility of assets """ return (z**(1 + theta)) / (1 + theta)
ef8fd5c5983bcfcf95df974cb7c3322c75f1c22a
612,876
def from_0_1_to_m1_1(images): """ Center images from [0, 1) to [-1, 1). Arguments: images: tf.float32, in [0, 1), of any dimensions Return: images linearly scaled to [-1, 1) """ # shifting from [0, 1) to [-1, 1) is equivalent to assuming 0.5 mean mean = 0.5 proimages = (images - mean) / mean ...
5be3259d2a873ef61218665b516b71af486f5158
612,881
import re def _tokenize_155_compat(text): """Tokenizes text in a manner that is consistent with ROUGE-1.5.5.pl.""" text = re.sub(r"-", " - ", text) text = re.sub(r"[^A-Za-z0-9\-]", " ", text) tokens = text.split() tokens = [t for t in tokens if re.match(r"^[a-z0-9$]", t)] return tokens
f6abc1df131bff844d2d6e4baeb4307df548dd2c
612,883
def parse_dbotu_parameters(summary_obj, amplicon_type): """ Parses summary file for dbOTU options. Parameters ---------- summary_obj SummaryParser object amplicon_type '16S' or 'ITS' Returns ------- dist max sequence dissimilarity (default = 0.1) ab...
711db64a54c335c05ff31f5149490359a233e33f
612,884
import sqlite3 def _create_db_connection(db_file_path: str) -> sqlite3.Connection: """Create and return the DB connection.""" return sqlite3.connect(db_file_path)
3f3763a639af81f1473889068533823ff450870e
612,886
import configparser def read_config_file(filename, folder="config/"): """ Reads-in a configuration file using the configparser object. Parameters ---------- filename : string name of the configuration file to read information from folder : string, optional path of configuratio...
b2ef4ca1e60616f47902db997d55aa45adafd7dd
612,887
def options(arg): """Extract options from given arg string""" opts = [] for par in arg.split(): if len(par) > 0 and par[0] == '-': opts.append(par) return opts
abe33aaeb7642b0ccac5ecdb2b88441acc92405c
612,892
def flatten(tensor): """Flattens a given tensor such that the channel axis is first. The shapes are transformed as follows: (N, C, D, H, W) -> (C, N * D * H * W) """ C = tensor.size(1) # new axis order axis_order = (1, 0) + tuple(range(2, tensor.dim())) # Transpose: (N, C, D, H, W) ->...
6cc238b8c60e3004834add6254eee44feabc5682
612,895
def gst_value_from_inclusive(amount, gst_rate): """Calculate GST component from a GST inclusive total. GST amount calculated as amount - (1 + gst_rate)). Args: amount (float): GST inclusive amount gst_rate (float): GST rate to apply. Returns: gst_component (flo...
5d7ba72bfe97598da3b360cf2e263aef59214af2
612,899
def is_puzzle_valid(puzzle): """Check if the entered sudoku puzzle is valid and can be solved""" #check rows for row in puzzle: current_row = set([]) for no in row: if no == 0 : continue if ( no not in current_row ):current_row.add(no) else: return False ...
85b2544d95112678fc8d910430e0aff9e9f1e2bc
612,900
def generate_parameters_string(parameters): """Generates the parameters string from the parameters dictionary Parameters ---------- parameters : dict The parameter values, keyed by parameter name Returns ------- str A string with the parameters to the CLI call """ f...
ef776123576899a25d2be51a8c9209c5f87488e1
612,902
def ataxia(request): """Return hpo term for ataxia""" return "HP:0002497"
7b068d5aa8cb7ed3b0e66d123d567abe9ad0fbee
612,904
def session(db, request): """ Roll back db in between tests using nested session. This fixture should be used for any test that updates the database. :param db: Pytest fixture :return: None """ db.session.begin_nested() def teardown(): db.session.rollback() request.addfinal...
9ed356ded15d595cd690bc94f7a1865d1b454462
612,905
def calculate_hounsfield_unit(mu, mu_water, mu_air): """ Given linear attenuation coefficients the function calculates the corresponding Hounsfield units. :param mu: Attenuation coefficient to determine corresponding Hounsfield unit. :param mu_water: Constant linear attenuation coefficient for water ...
8882a4a1465f0e0a679e2c51f651abcb192eb393
612,906