content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def to_float(nmb: str): """ convert numbers from rinex files to python floats rinex floats can either be: 4.391254341941D-09 4.391254341941E-09 that is, the scientific notation can use the ´E´ or ´D´ char """ try: flt = float(nmb) except ValueError: nmb = nmb...
26a92184ed4c78ab0ce90c1b05c513629271f120
638,334
def e() -> float: """ e = 1 :return: eccentricity :rtype: float """ return 1.
1bf99b28dd463731b934fadd7182f9278eb379ab
638,335
def get_vertical_layers_centroids_list(vert_layers): """ Returns a list with points that are the centroids of the heads of all vertical_layers_print_data. The head of a vertical_layer is its last path. """ head_centroids = [] for vert_layer in vert_layers: head_centroids.append(vert_layer.head_c...
ae8757778fd10d68cbc4fade18cb44e51de4d677
638,336
def read(path, as_single_string=False): """Read the file at the path and return its contents as a list or string.""" the_file = open(path, 'r') if as_single_string: contents = the_file.read() else: contents = the_file.readlines() the_file.close() return contents
968eb1bf955f8f08f172ff8cdbce660d28ba24ea
638,337
def get_reducer_params_str(codecs_serial,fft_at_mapper,internal_log_reducer,fft_size,windowing,phase_calibration,single_precision): """ Returns string with all the parameters to call the reducer. Parameters ---------- codecs_serial [only testing] "" by default. Serialized version of c...
c4c4355a2dbba1a511f904dc50644056fc5066c5
638,340
def pdf_diff(): """The diff that should be reported for the PDF files.""" return r"The files '\S*/file.pdf' and '\S*/file.pdf' are different\."
4cfc9ebab58fb64d39419ef38fb6fff906b17c3a
638,341
def add(a, b): """ >>> add(2, 3) 5 >>> add(100,200) 300 """ return a + b
151d21f0f47cb80ca0b1b2f27345f81b4708c3c2
638,342
from typing import Any def set_device_temp(device_id: str, auth_token: str, value: Any) -> bool: """Set the device temp.""" return True
793833f64480dde78e52ae5433665291d69d2c93
638,343
def get_msb(num): """docstring""" while num & (num-1): num &= num - 1 # return num
1ca695450243cf9651b2b0f7295cabf28172e8fe
638,344
def _calculate_color_sim(ri, rj): """Calculate color similarity using histogram intersection""" return sum([min(a, b) for a, b in zip(ri["color_hist"], rj["color_hist"])])
3b817013e0828c06dc90dba451375e5427c4439d
638,345
def _observed_name(field, name): """Adjust field name to reflect `dump_to` and `load_from` attributes. :param Field field: A marshmallow field. :param str name: Field name :rtype: str """ # use getattr in case we're running against older versions of marshmallow. dump_to = getattr(field, 'du...
727ac76fc21d12ea7ad94e91e19d10747cdf769b
638,347
def remove_duplicates(nonunique): """Remove duplicate values in a list. Args: nonunique (list) - a list of values Returns: a list of the unique values in the nonunique list Example: unique_values(['a', 'a', 'b', 'c']) --> ['a', 'b', 'c'] """ un...
7da75f4e2e51969fb624bdd2c765017fc03b4f30
638,348
def is_grayscale(image): """ Check if given image is in grayscale color space. :param image: checked image :return: result of the check (boolean value) """ GRAYSCALE_DIMENSION_COUNT = 2 return len(image.shape) == GRAYSCALE_DIMENSION_COUNT
010c93f593d39858ba334b9d917a6b411e5077de
638,349
def follow_expand( from_what, follow_what ): """ A SpaCy dependency graph follower... :param from_what: :param follow_what: :return: """ found = [x for x in from_what.children if x.dep_ == follow_what] return [ " ".join(str(x) for x in one.subtree) for one in found ]
78d8611bc5a6f3aece675315024ef3e5c53056f0
638,350
def Dutch_Flag(input_list): """ Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal. Args: input_list(list): List to be sorted Adapted from https://en.wikipedia.org/wiki/Dutch_national_flag_problem """ #Null input if input_list == None: ...
d8e8219f1e2e2e9dbe633295d053d20f26e43424
638,351
def get_filepath(video_id): """ Returns the filepath of the video in the clevrer directory Args: video_id(int): The id of the video obtained from the json Returns: filepath(string): the path from the dataset directory to the video Ex: image_00000-01000/video_00428 """ ...
4d18c856af09f737856e2d2e57c84115ae51a108
638,352
from typing import Sequence def _to_list(scalar_or_iter): """Convert scalars and iterables to list. Parameters ---------- scalar_or_iter : str or list Returns ------- list Examples -------- >>> _to_list("a") ['a'] >>> _to_list(["b"]) ['b'] """ return ( ...
cac99f3ecb2c53965d623e7ac95bd47d3cc7a302
638,353
import sys from multiprocessing import cpu_count def get_num_cpus(): """Return the number of CPUs on the current machine.""" if sys.version_info < (2, 6, 0): num_cpus = 8 else: num_cpus = cpu_count() return num_cpus
5cc6fbf6ea772dfcd91c6e5ce51b8216c8d536ad
638,354
def cmd_blacklist(self, args, message): """/blacklist [add | remove] <id>""" funcs = dict( add=self.user_db.add_to_blacklist, remove=self.user_db.remove_from_blacklist ) if not (len(args) == 2 and args[0].lower() in funcs and args[1].isdigit()): return ("Invalid arguments; expect...
5c93e66812c843560cd7ebc23356a0125cfeb0ed
638,355
def construct_runtime_cache_folder(runtime_cache_prefix, ios_version): """Composes runtime cache folder from it's prefix and ios_version. Note: Please keep the pattern consistent between what's being passed into runner script in gn(build/config/ios/ios_test_runner_wrapper.gni), and what's being configured for ...
2da19c5e184ccbbcab5e39cb5794e6ae973a5ade
638,356
def get_dhl_tweet(df, dhl_acc): """ Get Tweets by DHL associated accounts Parameters ---------- df : pandas.core.frame.DataFrame Tweets data. dhl_acc : list List of Twitter account usernames associated with DHL. Returns ------- pandas.core.frame.DataFrame Fi...
ed2758a4f403e4879cf9ef87b866023fec093512
638,357
def t_ordered_vars(PotentialsList): """ Returns a topological ordering of nodes in a Bayesian network :param PotentialsList: The list of CPTs :returns: The topologically ordered list of nodes """ node_ids = {} for i in range(len(PotentialsList)): node_name = PotentialsList[i].node.name ...
4d273a513afa1282dd1815995a6c4343411531e7
638,358
def dummy(argument, optional=None): """ Dummy Docstring Title Dummy docstring explanation. INPUT: - ``argument`` -- anything. Dummy argument. - ``optional`` -- anything (optional). Dummy optional. EXAMPLES:: sage: from sage.repl.ipython_tests import dummy sage: dummy(1)...
c076b60de1695ffa5ba9820dc70b221ce2c5bb46
638,360
def scalar_product(vector_a,vector_b): """dot product of vectors a b (scalar product) dot(a,b)""" return sum(vector_a*vector_b)
b774611d7bf23f5cbb367426682cb5dcd9066d1b
638,361
def gen_link(name, visual=None, collision=None): """ Generates (as a string) the complete urdf element sequence for a `link` element. This is essentially a string concatenation operation. If `collision` is not provided, a duplicate of `visual` will be used instead. :param name: Name of the lin...
ad71dd3c739d942451166e680038af437f3f81a5
638,362
def get_plugin_media_path(instance, filename): """ Django 1.7 requires that unbound function used in fields' definitions are defined outside the parent class (see https://docs.djangoproject.com/en/dev/topics/migrations/#serializing-values) This function is used withing field definition: file =...
7ae934d2924467bdeb9540f18b1aad84029778ff
638,364
from operator import sub def printcool(text,sym="#",bold=False,color=2,ansi=None,bottom='-',minwidth=50): """Cool-looking printout for slick formatting of output. @param[in] text The string that the printout is based upon. This function will print out the string, ANSI-colored and enclosed in the symbol ...
d8fb5ab5243e58f98d29ee4042f25f50f23f22ca
638,365
import numpy def rand_wfn(adim: int, bdim: int) -> numpy.ndarray: """Utility for generating random normalized wavefunctions. Args: adim (int): length of the alpha string bdim (int): length of the beta string Returns: numpy.ndarray(shape=(adim, bdim), dtype=numpy.complex128) ...
92f0a98d9e461979426ae8f49d59a539ae7be1d5
638,366
import torch def compose_projection_matrix(K, M): """ Compose intrinsics (K) and extrinsics (M) parameters to get a projection matrix """ return torch.matmul(K[:, :3], M)
f685ae4ed40b2b0d284e8a5750b2c471ce041fde
638,367
def move(roundsAlive, repertoire, historyRounds, historyMoves, historyActs, historyPayoffs, historyDemes, currentDeme, canChooseModel, canPlayRefine, multipleDemes): """ roundsAlive, currentDeme are integers, history* are tuples of integers repertoire is a dictionary with keys=behavioural acts and ...
2a60fa8fbc9eb952d0369b3a629f9ed168b88164
638,369
def add_ul(text, ul): """Adds an unordered list to the readme""" text += "\n" for li in ul: text += "- " + li + "\n" text += "\n" return text
580648ca2a3cc89d43400d331e6e91376adc0a77
638,370
def gen_var_info(var_names: list, zip_var_name: str = "uZipVars", offset_name: str = "offset", enum_name: str = "VAR", enum_prefix: str = "U", use_const: bool = True, enum_start_idx: int = 0, enum_var_...
b3da9f3e6298e3e37433023cd4fc90fed8931279
638,371
def diffCertLists(leftList : list, rightList : list) -> dict: """ Return diff between to lists of certs """ missingFromLeft = list() missingFromRight = list() for oLeft in leftList: if oLeft not in rightList: missingFromLeft.append(oLeft) continue #if ...
33c46dcd08bae9aa20e459f1cf1fd6a01c36e2f3
638,372
import random def get_random(): """ :return: random """ return random.random()
2cde8fab6659ce6a0544d66a2f2e2507eb33d36c
638,373
from typing import Optional def next_page_checker( page: dict ) -> Optional[str]: """This is the parser for checking "nextParams" from react page data for automatic paging in get*Iter function. Arguments: page (:class:`dict`) : Page data from get(Comments, Posts, etc..) Returns: ...
780eaed3f8277bc8839c03474ce10e8a84832d46
638,374
def merge_tensors(tensor_objects, non_tensor_objects, tensor_flags): """ Merge two lists (or tuples) of tensors and non-tensors using a mapping of positions in merged list (or tuple). Parameters: tensor_objects (list/tuple): Tensors to merge. non_tensor_objects (list/tuple): Non-tensors to m...
c727d6a568f1c40a18cc8fbd8c80856e224efdf8
638,375
import base64 import six def base64_encode(text): """Base 64 encodes the UTF-8 encoded representation of the text. In Python 2 either a byte string or Unicode string can be provided for the text input. In the case of a byte string, it will be interpreted as having Latin-1 encoding. In Python 3 only a ...
ae599eff5a3fd51e163cae086b55ceba0b491b24
638,376
def no_op(*args, **kwargs): """ No-op function to serve as default ``get_runtime_attrs``. """ return None
3089a28bd2f913787056f3a5e07ce495928f6f3a
638,377
def computeFraction( poi_messages, all_messages ): """ compute the fraction of messages to/from a person that are from/to a POI """ fraction = 0 if poi_messages == 'NaN' or all_messages == 'NaN': fraction = 'NaN' else: fraction = float(poi_messages)/all_messages return fraction
12acfb8bfdbd82637c16dbca78976516da510bf6
638,378
import os def get_name_from_path(path: str) -> str: """ Get name from path to the file :param path: path to the file :return: name of the file """ return os.path.splitext(os.path.basename(path))[0]
0bbfec72bcb3ab2027fa6894d9731092908bcb1e
638,379
def CheckForSize(collection, expected_size, equal_flag, unequal_flag, unexpectedly_empty_flag=None): """Check conditions for collection size. Args: collection: A collection can be a list, set or dictionary. expected_size: The expected size. equal_flag: The value to return if the collec...
6efcf98f72a8191cf1e07180de62762ae67a2388
638,380
def testValidDepth(cdf, numberOfPoints, gridIndexes, depth): """To avoid having to extract all depth layers that do not contain valid data, we find the deepest depth layer of the surrouding stations and use that indices in the further extration""" deepestMax = 40 # The deepes soda depth is 40 deepe...
43fef7af9e024a8c061cdc258dde283e885f9810
638,381
def reversed_tom(liste: list) -> list: """ Return the reversed list. :param liste: list to be returned :return: returned list """ liste.reverse() return liste
b5155493eb805903935a7063035c1bc8cc5ab957
638,382
def calc(a,b): """ calc """ return a+b
d85116e8aab32f3b1197996f71233af4184c2927
638,383
def numseqstr(seq, sep=',', fmt='%0.2f'): """Takes a number sequence or single number and prints it using the given separator and format.""" def gets(s): """Returns a number formatting string using fmt if a number, else str() version""" try: # number return fmt % s except Typ...
7061e6c0b8fb0b2c1158e58ac111d90802648a8f
638,384
def face_in_person(f_box, p_box): """ Judge if the `f_box` is contained by the `p_box` --- param: f_box: a ndarray that represents the location of the face p_box: a ndarray that represents the location of the person """ return f_box[0] > p_box[0] and f_box[1] > p_box[1] and \ ...
a7a2507fb920587f0dc8d1d8e9a754c1c8abbe8b
638,385
import subprocess def cmd_output(cmd_to_run): """Get the stdout from a command run from bash.""" return subprocess.check_output(cmd_to_run, shell=True).decode("utf-8")
c43b12be708c53d29c0a87e9927ccefa29530fcb
638,386
import requests from bs4 import BeautifulSoup def get_boxscore_links(year='2020'): """ retrieves all links to every single available box score. It seems that bball reference lags behind a bit. I ran today (1/6/20) and only through 1/4/20 is up. """ months = ['october', 'november', 'december'...
6a2f1df452ea1b076115f04ce0ca5ebeb08e7898
638,387
def _increment_list_counter(ilvl2count, ilvl: str) -> int: # noinspection SpellCheckingInspection """ Increase counter at ilvl, reset counter at deeper levels. :param ilvl2count: context['numId2count'] :param ilvl: string representing an integer :return: updated count at ilvl. updates c...
c49887a37de5b5a0ff7177d4414e35fbc5273fb6
638,388
def merge_dicts(list_of_dicts): """Merge multipe dictionaries together. Given any number of dicts, shallow copy and merge into a new dict, precedence goes to key value pairs in latter dicts. Args: dict_args (list): a list of dictionaries. Returns: dict """ merge_dict = {}...
28c763d1f97a1c0abd84993803620748045b2691
638,389
def parses(t): """Parser for a specific type in the github response.""" def f(orig): orig.parses = t return orig return f
28fec18fb63fd144afbc530b3887469ce9f7b2b2
638,390
import gc # try brute force import inspect def _find_callable(name, frame): """Find the callable which matches the name and frame code""" func = frame.f_globals.get(name) if func and inspect.isfunction(func) and func.__code__ is frame.f_code: return func if frame.f_back: func = frame...
3a64f3763c513c7f6d4634dfeb1e7b148e0046e1
638,391
from typing import Iterable def apply_ners(query, ners): """ Applies each NER model passed in `ners` on `query`, taking the union set of their predictions. Ignores various types of entities not useful for the business case. """ ignore = ['CARDINAL', 'DATE', 'MONEY', 'ORDINAL', 'PERCENT', 'QUANTITY...
9d7c6293637ca14e815681a71d3264f5c3a7ef83
638,392
def get_ids(data): """ Extracts dataset IDs. :param data: The input data :return: IDs """ ids = [] for i in data: ids.append(i.ID) return ids
c88bccbab4b3af8038cec20c1413b5ef1e0dedbc
638,393
def get_cosigners(pubkeys, derivations, xpubs): """Returns xpubs used to derive pubkeys using global xpub field from psbt""" cosigners = [] for _, pubkey in enumerate(pubkeys): if pubkey not in derivations: raise ValueError("missing derivation") der = derivations[pubkey] ...
28c66e9273303a5b321bb312f9dbbb38c039d873
638,394
import os def _resolve_latestversion(dirname_template): """Resolve the 'latestversion' tag.""" if '[latestversion]' not in dirname_template: return dirname_template # Find latest version part1, part2 = dirname_template.split('[latestversion]') part2 = part2.lstrip(os.sep) if os.path.e...
d230d21b507d0bf99c412b9642252c166c1ac3cb
638,395
def index(): """ Return statement """ return "Hello Yummy recipes"
ca28b9fda1634d507b3058838e410fadb74aff01
638,396
import subprocess def subprocess_wrapper(command): """ Wraps subprocess.check_call so exceptions can be handled cleanly. command: command to run Return value: 0 if successful; else error """ try: subprocess.check_call(command, shell=True) except subprocess.CalledProcessError ...
fddf7383bae599f66bedff8a1bd4d8127f2c4c85
638,397
def _convert_space_to_shape_index(space): """Map from `feature` to 0 and `sample` to 1 (for appropriate shape indexing). Parameters ---------- space : str, values=('feature', 'sample') Feature or sample space. Returns ------- return : int, values=(0, 1) Index location of th...
20ec5aad29366929973b2bfa8e503a5bcbbb9a3a
638,398
def next_recipe_digits(cur_recipe): """Calculate next recipe, based on the cur_recipe.""" if cur_recipe == 0: return [0] digits = [] while cur_recipe > 0: digits.append(cur_recipe % 10) cur_recipe = cur_recipe // 10 return digits[::-1]
c97e590a456e1d4e0801035fcc89989a45010738
638,399
import re def IsGCESlave(slavename): """Returns (bool): Whether |slavename| is hosted on GCE. Args: slavename: The hostname of the slave. """ # The "-c2" suffix indicates that a builder is in GCE (as opposed to # in the Chrome Golo, which has a -m2 suffix). return bool(re.search(r'-c\d+$', slavename)...
613569120fd4390608ba6173ef3686bb1ef1b01f
638,400
def pesos_ady(grafo,vertice): """Dado un grafo y un vertice devuelve un diccionario con los vertices adyacentes como clave y el peso de la arista como valor""" diccionario = {} adyacentes = grafo.ver_a_adyacentes(vertice) for a in adyacentes: diccionario[a[0]] = a[1] return diccionario
ad11e0bd022168c6da8a97f1598a3dd985817b19
638,401
from typing import Optional import requests def get_request(url: str, headers: Optional[dict] = None, params: Optional[dict] = None): """Return response if request is successful and in JSON format""" try: response = requests.get(url, headers=headers, params=params).json() except: return ...
20cd883b39c6b47d893e78d1aba3eaac508f35e7
638,403
def abnormalVolDate(fVolFrac, afVolFrac): """ Abnormal trading volume for firm on date defined as difference between the fraction of shares turned over for firm on date, and the value-weighted average of the fraction of shares turned over for all firms in universe on date Returns FLOAT """ r...
6d5d4ea8b42d7e20b4b492ad4c74bbd861687616
638,404
def get_ncattrs(obj): """ Returns ncattrs of a netcdf object as a dictionary :param obj: Object to collect ncattrs from :return: dictionary representation of those ncattrs """ out = {} for key in obj.ncattrs(): value = obj.getncattr(key) if hasattr(value, 'tolist'): ...
2fdd3d2cf847d1e927b50cf9e9b0d8d997e791c3
638,406
def compute_digital_root(n): """ Compute the digital root of the number n """ # If num is 0. if (n == "0"): return 0 # Count sum of digits under mod 9 answer = 0 for i in range(0, len(n)): answer = (answer + int(n[i])) % 9 # If digit sum is multiple of 9, answer ...
1efaf1abfe299c083085afa5d4c6cf1c8e155400
638,408
def countPrimes(self, n): # ! 厄拉多筛选法的变种 """ :type n: int :rtype: int """ if n < 3: return 0 primes = [True] * n primes[0] = primes[1] = False for i in range(2, int(n ** 0.5) + 1): if primes[i]: primes[i * i: n: i] = [False] * len(primes[i * i: n: i]) retu...
1ec1ce79c05fe73a5a632ac5bb044973f0327017
638,409
def __lu(a, normal): """ The leading unit of a, that is, the unit u such as a = u * normal(a). """ if a.is_zero(): return a.parent().one() quo, _ = a.quo_rem(normal(a)) return quo
fc27140ba3eafb309de6a1deaab0d5e2ead656f2
638,410
def trans_ledu(ledu): """ Translates the level of education code to a human-readable string """ retStr = 'unknown or unsupplied' if ledu == 'p_se': retStr = 'Ph.D. in STEM' elif ledu == 'p_oth': retStr = 'Ph.D. in non-STEM field' elif ledu == 'm': retStr = 'Masters or...
c0b8fe645457f32e87928bbe13d6f28716a5e4ac
638,411
def z_score(data2d, axis=0): """Standarize the mean and variance of the data axis Parameters. :param data2d: DataFrame to normalize. :param axis: int, Which axis to normalize across. If 0, normalize across rows, if 1, normalize across columns. :Returns: Normalized DataFrame. No...
0e8fc71fad9b4cdb55d6d1a88bf814e80b9598ad
638,412
def boolean(value): """Parse the string "true" or "false" as a boolean (case insensitive). Also accepts "1" and "0" as True/False (respectively). If the input is from the request JSON body, the type is already a native python boolean, and will be passed through without further parsing.""" if type(va...
09a6b313a7f85e8d7d480661c257aea194743db6
638,413
import shlex def validate_command(value): """Validate "command" parameter.""" if isinstance(value, str): value = shlex.split(value) return list(value)
57b2e4b9b5e5819b26f0472114c63b73ee0cef11
638,414
import re def _linkify_usernames(text): """Slack wants @usernames to be surrounded in <> to be highlighted.""" return re.sub(r'(?<!<)(@[\w_]+)', r'<\1>', text)
1018503583f47187f84615910d327ab8259afb51
638,415
def difference(first, other, epsilon=0.005): """ Calculate the difference between two dictionaries. The difference is defined as all the values for the keys that are in both ``dict`` and ``other`` which differ. For floating point numbers, the value ``epsilon`` is used to define difference, so two fl...
7c3c7d5b06ee8b244e734e37667454600193cc96
638,416
def Predicate(predicate): """ Display only those objects that match the given predicate Example:: self.olv.SetFilter(Filter.Predicate(lambda x: x.IsOverdue())) """ return lambda modelObjects: [x for x in modelObjects if predicate(x)]
4a7e6a1c5376c0a77612e35a29e0ff766f509608
638,417
def hello_world(): """Original function!""" return "Hello, World!"
bf284c1c0b8e0aa1888100409fadd1f9c5df8a71
638,418
def cut_lc(df, min=-30, max=150): """Short summary. Parameters ---------- df : Pandas DataFrame The dataframe containing the photometry of all events. min : float The minimum phase (relative to trigger) at which to truncate photometry. max : float The maximum phase (rel...
a646b4e354a840c64a27485dd42d458b72c3b28e
638,419
from pathlib import Path from typing import List import ast def tests_from_file(path: Path, base: str) -> List[str]: """ Returns all the tests in the given file, in format expected as arguments when running the tests. e.g. file_stem file_stem.TestFunctionality file_stem.TestFun...
e21cb2c093357dda35b60298ab95793975dc2359
638,421
def split_cubic_into_three(p0, p1, p2, p3, _27=1/27): """Split a cubic Bezier into three equal parts. Splits the curve into three equal parts at t = 1/3 and t = 2/3 Args: p0 (complex): Start point of curve. p1 (complex): First handle of curve. p2 (complex): Second handle of curve. ...
a0fec30070654a0ba62bb4ef2f994a0853a26fe5
638,422
def K(x, y): """Kxy = x""" return x
86bc83cbfc3b6256f4e1bab876ffa0acfac34f81
638,423
import argparse import os def create_arg_parser(): """ ### required - test_question_file (os.path.abspath) path of a test set - pred_label_file (os,path.abspath) path of a predicted file ### optional - output_file (os.path.abspath) path of output file - w_ques...
3d2207a684096dfd1c7d9563f69f070293df6a0a
638,424
import yaml def load_repositories(repos_file): """ Load repository yaml """ if repos_file: try: file_descriptor = open(repos_file, 'r', encoding='utf-8') except IOError as error: print("Error: open file {} failed", repos_file, error) return None ...
d3f1ae60407f3c9eeebc9ca5326fa753e166c2ba
638,425
def calc_fuel(mass): """ divide by three, round down, and subtract 2 """ return mass // 3 - 2
98479556b916e997a2e989c9032467b2527eb5cb
638,426
def observations(ax, data, label='Observations', future=False, **kwargs): """ Plot observed values. :param ax: The plot axes. :param data: The NumPy array containing the observation data. :param label: The label for the observation data. :param future: Whether the observations occur after the f...
8b1bc6c9a618db273bd1afb60fc91325b941f931
638,427
import argparse def parse_args(args): """ Parse the arguments. """ parser = argparse.ArgumentParser( description='Script for generating adversarial examples.') parser.add_argument('test_model', help='Model for testing AEs.', type=str) parser.add_argument('dataset_type', choices=['coco', 'voc'], ...
799c02fd44192045fa7256653bc99d14d83bf2be
638,428
def makeConfiguration(line): """ returns configuration based on the line """ if line == None: configuration = [0.0, 0.0, 0.0] else: x = float( line[30:38].strip() ) y = float( line[38:46].strip() ) z = float( line[46:54].strip() ) configuration = [x, y, z] return c...
c3c4c1d454a854fcf5667e85518b466338309f56
638,429
import torch def compute_accuracy(predictions, labels): """ Compute the frequency that the label belongs to the predicted set Args: predictions (tensor): a batch of topk predictions with shape [batch_size] or [batch_size, k] labels (tensor): a batch of labels with shape [batch_size] ...
9f305af250ea272a9c155c32729dd97aea99b7e2
638,430
def format_timedelta(time_delta): """ Convert a datetime.timedelta to str format example output: "0h:0m:18s" Parameters ---------- time_delta: datatime.timedelta Returns ------- str: formatted timedelta """ d = {} d["hours"], rem = divmod(time_delta.seconds, 3600) ...
3d41644991ec558ea423f24d426e62b417fc9b48
638,431
from typing import Tuple from typing import Any def snd(tup: Tuple[Any, Any]) -> Any: """ Return second member of tuple """ return tup[1]
a24632b572474ea3964d4b35422934ca8a40aaa3
638,432
def create_grant(grant_create_request): # noqa: E501 """Create a grant Create a grant with the specified name # noqa: E501 :param grant_create_request: :type grant_create_request: dict | bytes :rtype: GrantCreateResponse """ return 'do some magic!'
b0d4fad2a955716173279b14abed6ede4b9cae7f
638,434
def q_prior(q, m=1, gamma=0.3, qmin=0.1): """Default prior on mass ratio q ~ q^gamma """ if q < qmin or q > 1: return 0 C = 1/(1/(gamma+1)*(1 - qmin**(gamma+1))) return C*q**gamma
64ecd4e72b8f7478a47a7d6c95f31b7f8447b6f0
638,435
def mark_metadata(metadata, subcollection, selposts): """ Mark all posts corresponding to the current subcollection criteria. This is done in the form of a label in the subcollection column. """ for post in selposts: postindex = metadata[metadata.filename == post].index[0] metadata.s...
5c978d846d2969c81c67d024a9f7e7cac4c8cff7
638,436
import numpy def isscalar(element): """Returns True if the type of num is a scalar type. .. seealso:: :func:`numpy.isscalar` """ return numpy.isscalar(element)
388e34c0853ee3b671f09f76074a045c83396a25
638,437
def charOffsetToTuples(charOffset): """ Splits a comma separated list of character offsets into tuples of integers. Keyword arguments: charOffset -- a string in the format "0-2,5-20" Returns: A list of tuples of two integers each """ tuples = [] ranges = charOffset.split(",") f...
2cebe13228b5142b84118da4e561c39db2137b20
638,440
import argparse def parse_args(argv): """Parse arguments.""" parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter) feed_group = parser.add_mutually_exclusive_group(required=True) feed_group.add_argument( '--from-feeds', type=str, nargs='+', des...
f653a5dea7fa74a994f2655d82bd505124090353
638,441
def select_host(hosts, preferred_hosts, ignore_hosts): """Select a suitable host from a list of hosts. Parameters ---------- hosts : :obj:`list` of :obj:`str` List of all available hosts. preferred_hosts : :obj:`list` of :obj:`str` List of preferred hosts. ignore_hosts : :obj:`l...
8763c958fa327c333b0a556009671a3c817d8662
638,442
def func(a: int, b: int) -> int: """Пример простейшей функции""" c = a + b return c
d916a66e2701acd578261876222e69a6741c91a9
638,443
def is_empty_line(line): """ Returns true if a given line is empty. str -> bool """ return len(line) == 0
0286ee5e3968036892e281c2c679f8f56e2e7cdf
638,444
def add_slash(url): """Add a slash at the end of URL if the slash is not already presented.""" if url and not url.endswith('/'): url += '/' return url
a8011372714807abb0a26215b99100fe26025fac
638,445
def front(self): """Return the item at the front of this queue without removing it,""" if self.is_empty() == True: return None return self.list.head.data
ec24bce7fb8315009f9e569d2056e75cb227a0d7
638,446