content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def dscp_class(bits_0_2, bit_3, bit_4): """ Takes values of DSCP bits and computes dscp class Bits 0-2 decide major class Bit 3-4 decide drop precedence :param bits_0_2: int: decimal value of bits 0-2 :param bit_3: int: value of bit 3 :param bit_4: int: value of bit 4 :return: DSCP cla...
79e9881e413a5fcbbbaab110e7b3346a2dbcaa53
705,684
def scale_to_one(iterable): """ Scale an iterable of numbers proportionally such as the highest number equals to 1 Example: >> > scale_to_one([5, 4, 3, 2, 1]) [1, 0.8, 0.6, 0.4, 0.2] """ m = max(iterable) return [v / m for v in iterable]
92cfc7ef586ecfea4300aeedabe2410a247610f7
705,686
def get_total_count(data): """ Retrieves the total count from a Salesforce SOQL query. :param dict data: data from the Salesforce API :rtype: int """ return data['totalSize']
7cb8696c36449425fbcfa944f1f057d063972888
705,688
def dummy_location(db, create_location): """Give you a dummy default location.""" loc = create_location(u'Test') db.session.flush() return loc
ec6ffa3b42e07c88b8224ee2aaaf000853a4169f
705,689
import os def list_profiles_in(path): """list profiles in a given root directory""" files = os.listdir(path) profiles = [] for f in files: full_path = os.path.join(path, f) if os.path.isdir(full_path) and f.startswith('profile_'): profiles.append(f.split('_',1)[-1]) ret...
1e377b2a686d3c63e569c57af7415a9604b3709e
705,691
def extractLine(shape, z = 0): """ Extracts a line from a shape line. """ x = shape.exteriorpoints()[0][0] - shape.exteriorpoints()[1][0] y = shape.exteriorpoints()[0][1] - shape.exteriorpoints()[1][1] return (x, y, z)
c61021b1e3dc6372d9d7554a7033bbd3ab128343
705,692
def substring_in_list(substr_to_find, list_to_search): """ Returns a boolean value to indicate whether or not a given substring is located within the strings of a list. """ result = [s for s in list_to_search if substr_to_find in s] return len(result) > 0
77521a1c5d487fa110d5adecb884dd298d2515e5
705,693
def getQueryString( bindings, variableName ): """ Columns a bunch of data about the bindings. Will return properly formatted strings for updating, inserting, and querying the SQLite table specified in the bindings dictionary. Will also return the table name and a string that lists the columns (properly formatted...
9cc81601cde229cc5f5bf53ef73997efc515ed2b
705,694
def average(l): """ Computes average of 2-D list """ llen = len(l) def divide(x): return x / float(llen) return list(map(divide, map(sum, zip(*l))))
67395ce4417022a673565a8227c684b7649a5e6a
705,695
import json def getPath(): """ Gets path of the from ./metadata.json/ """ with open('metadata.json', 'r') as openfile: global path json_object = json.load(openfile) pairs = json_object.items() path = json_object["renamer"]["path"] return path
03047172e653b4b4aee7f096a67291ad460969c9
705,696
def axes_to_list(axes_data: dict) -> list: """helper method to convert a dict of sensor axis graphs to a 2d array for graphing """ axes_tuples = axes_data.items() axes_list = [axes[1].tolist() for axes in axes_tuples] return axes_list
fb2e5ef1f2283e2f31e5c8828a3ec7ef94869c5c
705,697
from typing import Iterable import functools import operator def prod(values: Iterable[int]) -> int: """Compute the product of the integers.""" return functools.reduce(operator.mul, values)
3f03200078daf1b0b27f777e7744144ab72ec7af
705,698
def get_stars_dict(stars): """ Transform list of stars into dictionary where keys are their names Parameters ---------- stars : list, iterable Star objects Return ------ dict Stars dictionary """ x = {} for st in stars: try: x[st.name] = ...
6d627be48a96d8ba93bd13511a05c251f3a3f169
705,699
def clean_packages_list(packages): """ Remove comments from the package list """ lines = [] for line in packages: if not line.startswith("#"): lines.append(line) return lines
a6c942f9b90c8f6c610ba0b57728f3da48f35ded
705,700
import random def IndividualBuilder(size, possList, probList): """ Args: size (int) - the list size to be created PossArr - a list of the possible mutations types (mutation, deletion,...) ProbArr - a list of the probibilities of the possible mutations occuring. ...
055d582fffbc2e13a25a17012831c098fc89330d
705,701
import os def get_file_open_command(script_path, turls, nthreads): """ :param script_path: path to script (string). :param turls: comma-separated turls (string). :param nthreads: number of concurrent file open threads (int). :return: comma-separated list of turls (string). """ return "%s...
9d85df723cf6512e876c2c953ab2229f947ef40e
705,702
import os import sys def setup_parameters(): """ This function sets up the hyperparameters needed to train the model. Returns: hyperparameters : Dictionary containing the hyperparameters for the model. options : Dictionary containing the options for the dataset location, augmentation, etc. ...
0e3c0e30618062b6c3b7b252a714a5dab2b09cba
705,703
def get_genres_from_games(games, their_games): """ From the games we will get the same genres """ genres = set() for d in games: n = d['id'] if n in their_games: genres.add(d['Genre']) return genres
27bbf3c5ba40c6443e12b4119943c40879ceb622
705,704
import pathlib import platform import os def get_candidate_dir(): """ Returns a valid directory name to store the pictures. If it can not be determined, "" is returned. requires: import os import pathlib import platform https://docs.python.org/3/library/pathlib.html#pathl...
48353d226da4a6fdc4ca3208118b01c406e00dfb
705,706
def add_kwds(dictionary, key, value): """ A simple helper function to initialize our dictionary if it is None and then add in a single keyword if the value is not None. It doesn't add any keywords at all if passed value==None. Parameters ---------- dictionary: dict (or None) A dictio...
96aa104f86e521e419d51096b6c1f86e4b506c57
705,707
def _get_cindex(circ, name, index): """ Find the classical bit index. Args: circ: The Qiskit QuantumCircuit in question name: The name of the classical register index: The qubit's relative index inside the register Returns: The classical bit's absolute index if all regi...
340105a2ddfe5fb2527171a7592390c9dd2937e5
705,708
def get_bin(pdf: str) -> str: """ Get the bins of the pdf, e.g. './00/02/Br_J_Cancer_1977_Jan_35(1)_78-86.tar.gz' returns '00/02'. """ parts = pdf.split('/') return parts[-3] + '/' + parts[-2] + '/'
a1e25162b8a353f508667ccb4fc750e51fcf611d
705,709
def burkert_density(r, r_s, rho_o): """ Burkert dark matter density profile """ x = r / r_s density = rho_o / ( (x) * (1.0 + x)**2) return density.to('g/cm**3')
8293a62b6c52c65e7c5fe7c676fd3807f301e40b
705,711
def area_description(area,theory_expt): """ Generate plain-language name of research area from database codes. """ area_name_by_area = { "As" : "Astrophysics", "BP" : "Biophysics", "CM" : "Condensed matter", "HE" : "High energy", "NS" : "Network science", ...
d7743c2d80d9a74dd6a24f735b7c0a389eb36468
705,712
def parse_username_password_hostname(remote_url): """ Parse a command line string and return username, password, remote hostname and remote path. :param remote_url: A command line string. :return: A tuple, containing username, password, remote hostname and remote path. """ assert remote_url ...
50410ad87865559af84b83ab6bdfae19e536791d
705,713
import ast def skip_node(node): """Whether to skip a step in the traceback based on ast node type.""" return isinstance(node, (ast.If, ast.While, ast.For))
2406d02190a4dccb3d1f5d743a742f82c97f6541
705,714
def convertASTtoThreeAddrForm(ast): """Convert an AST to a three address form. Three address form is (op, reg1, reg2, reg3), where reg1 is the destination of the result of the instruction. I suppose this should be called three register form, but three address form is found in compiler theory. ...
17bcd628b2b6feb916cdfaea2f6a210f47afa7bf
705,715
def lc_reverse_integer(n): """ Given a 32-bit signed integer, reverse digits of an integer. Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer over...
eff1054873ef0e77a82e34b7cf7af51d42f27d6c
705,716
from typing import Optional import logging import tempfile import sys import subprocess def install_to_temp_directory(pip_dependency: str, temp_dir: Optional[str] = None) -> str: """Install the given pip dependency specifier to a temporary directory. Args: pip_dependency: Path...
6f18fd2e3a2ade2c0e770076cc29df8ef4cca5b3
705,717
def alias_phased_obs_with_phase(x, y, start, end): """ :param x: a list containing phases :param y: a list containing observations :param start: start phase :param end: end phase :return: aliased phases and observations """ x = [float(n) for n in x] y = [float(n) for n in y] if...
4b9bd3507180d2e7cd2c9957e1c2ea4ce3e17cb6
705,718
import platform def get_os(): """ Checks the OS of the system running and alters the directory structure accordingly :return: The directory location of the Wordlists folder """ if platform.system() == "Windows": wordlist_dir = "Wordlists\\" else: wordlist_dir = "Wordlists/" ...
6f4a6f70505b1512987e75a069a960b136f66d97
705,719
def check_derivation(derivation, premises, conclusion): """Checks if a derivation is ok. If it is, returns an empty list, otherwise returns [step, error] Does not check if the conclusion and premises are ok, for that there is another function""" for step in sorted(derivation): try: # ...
67c15ae26ee399e95808495845c260ca55808532
705,720
def uniques_only(iterable): """ This works only for sequence, but not for all iterable """ items = [] for i, n in enumerate(iterable): if n not in iterable[:i]: items.append(n) return items
159e220be340fc027053b7dbae0d146ae88ceea9
705,721
def tsallis(ion_temp, avg_temp, n): """ Non-normalized probability of an ion at ion-temp using a Tsallis distribution :param ion_temp: temperature of ion (K) :param avg_temp: average temperature of ions (K) :param n: average harmonic oscillator level :return: value """ kb = 1.38e-23 ...
4598c5241fc06219938beced4c9d5a4473cf8363
705,722
def _extractRGBFromHex(hexCode): """ Extract RGB information from an hexadecimal color code Parameters: hexCode (string): an hexadecimal color code Returns: A tuple containing Red, Green and Blue information """ hexCode = hexCode.lstrip('#') # Remove the '#' from the string ...
e1d67b4f2004e5e2d4a646a3cc5dc49a1e8cd890
705,723
def summarise(indices, fields, **kwargs): """Summarise taxonomy.""" summary = {} meta = kwargs['meta'] try: if 'taxid' in meta.taxon: summary.update({'taxid': meta.taxon['taxid']}) names = [] for rank in ('superkingdom', 'kingdom', 'phylum', 'class', 'order', 'family'...
87f04cb86978e2350f3e535b65a1efa14af77ee8
705,724
def get_user_partition_groups(course_key, user_partitions, user, partition_dict_key='name'): """ Collect group ID for each partition in this course for this user. Arguments: course_key (CourseKey) user_partitions (list[UserPartition]) user (User) partition_dict_key - i.e. 'i...
3bb2f76f4a48ce0af745637810903b8086b2fc02
705,725
import os import socket def has_reuse_port(*, use_env=True): """Return true if the platform indicates support for SO_REUSEPORT. Can be overridden by explicitly setting ``AIOCOAP_REUSE_PORT`` to 1 or 0.""" if use_env and os.environ.get('AIOCOAP_REUSE_PORT'): return bool(int(os.environ['AIOCOA...
142b766f1f38fb671107aa754de5689837b3008e
705,726
import collections def factory_dict(value_factory, *args, **kwargs): """A dict whose values are computed by `value_factory` when a `__getitem__` key is missing. Note that values retrieved by any other method will not be lazily computed; eg: via `get`. :param value_factory: :type value_factory: A function fr...
f7d4898e62377958cf9d9c353ed12c8d381f042f
705,727
def build_or_passthrough(model, obj, signal): """Builds the obj on signal, or returns the signal if obj is None.""" return signal if obj is None else model.build(obj, signal)
bee9c8557a89a458cf281b42f968fe588801ed46
705,728
import requests import json def warc_url(url): """ Search the WARC archived version of the URL :returns: The WARC URL if found, else None """ query = "http://archive.org/wayback/available?url={}".format(url) response = requests.get(query) if not response: raise RuntimeError() ...
afc24876f72915ba07233d5fde667dd0ba964f5a
705,729
def array_to_top_genes(data_array, cluster1, cluster2, is_pvals=False, num_genes=10): """ Given a data_array of shape (k, k, genes), this returns two arrays: genes and values. """ data_cluster = data_array[cluster1, cluster2, :] if is_pvals: order = data_cluster.argsort() else: ...
4f9a0ea673f4ddfa59e7d4fc2249597daef4a260
705,730
import os def parse_fastani_write_prophage(CRISPR_mates): """[summary] Args: CRISPR_mates ([type]): [description] Returns: [type]: [description] """ if not os.path.exists('prophageannotations'): os.system('mkdir -p prophageannotations') viral_cluster_prophages = di...
82cf3bfff65bb57ab33c7a2108734a90da1a4d11
705,731
def set_attrib(node, key, default): """ Parse XML key for a given node If key does not exist, use default value """ return node.attrib[key] if key in node.attrib else default
0e21b6b0e5a64e90ee856d4b413084a8c395b070
705,732
def is_order_exist(context, symbol, side) -> bool: """判断同方向订单是否已经存在 :param context: :param symbol: 交易标的 :param side: 交易方向 :return: bool """ uo = context.unfinished_orders if not uo: return False else: for o in uo: if o.symbol == symbol and o.side == side:...
42363c8b3261e500a682b65608c27537b93bcfb1
705,733
def average_pool(inputs, masks, axis=-2, eps=1e-10): """ inputs.shape: [A, B, ..., Z, dim] masks.shape: [A, B, ..., Z] inputs.shape[:-1] (A, B, ..., Z) must be match masks.shape """ assert inputs.shape[:-1] == masks.shape, f"inputs.shape[:-1]({inputs.shape[:-1]}) must be equal to masks.shape({ma...
e6f99634245a4c46e2b5d776afcd73e855da68de
705,735
def save_ipynb_from_py(folder: str, py_filename: str) -> str: """Save ipynb file based on python file""" full_filename = f"{folder}/{py_filename}" with open(full_filename) as pyfile: code_lines = [line.replace("\n", "\\n").replace('"', '\\"') for line in pyfile.readlines()] ...
f2711f0282c2bf40e9da2fec6e372c76038ac04a
705,736
def make_coro(func): """Wrap a normal function with a coroutine.""" async def wrapper(*args, **kwargs): """Run the normal function.""" return func(*args, **kwargs) return wrapper
080e543bc91daee13c012225ba47cd6d054c9ea5
705,737
import math def gvisc(P, T, Z, grav): """Function to Calculate Gas Viscosity in cp""" #P pressure, psia #T temperature, °R #Z gas compressibility factor #grav gas specific gravity M = 28.964 * grav x = 3.448 + 986.4 / T + 0.01009 * M Y = 2.447 - 0.2224...
5ff1ad63ef581cea0147348104416913c7b77e37
705,738
def url_mapper(url, package): """ In a package.json, the "url" field is a redirection to a package download URL published somewhere else than on the public npm registry. We map it to a download url. """ if url: package.download_urls.append(url) return package
95d6b67a42cac14110b457b96216a40a5d5430f9
705,739
def mettre_a_jour_uids(nom_fichier, organisateurs, uids): """ Met à jour le fichier CSV UID,EMAIL à partir du dictionnaire """ nouveaux_uids = False for id_reunion in organisateurs: if organisateurs[id_reunion]["id_organisateur"] not in uids: uids[organisateurs[id_reunion]["id_organisate...
ac0f61b135c8a7bb9de9bb6b5b8e3f9fd7b176f0
705,740
def is_base(base_pattern, str): """ base_pattern is a compiled python3 regex. str is a string object. return True if the string match the base_pattern or False if it is not. """ return base_pattern.match(str, 0, len(str))
d0b0e3291fdbfad49698deffb9f57aefcabdce92
705,741
def stations_by_river(stations): """For a list of MonitoringStation objects (stations), returns a dictionary that maps river names (key) to a list of MonitoringStation objects on a given river.""" # Dictionary containing river names and their corresponding stations rivers = {} for station in stati...
c7fc460aa3e387285abdddfcb216a8ec41d27e06
705,742
def check_double_quote(inpstring): """ Check if some strings needs of a double quote (if some space are inside the string, it will need to be inside two double quote). E.g.: --sfmt="TIFF (unstitched, 3D)" Input: inpstring: input string or array of strings Output: newstring = new string (or...
3da3941d9cd8c4c72643f87c533bcfbfbd9b9a79
705,744
import fcntl import os import socket import struct def get_linux_ip(eth): """在Linux下获取IP""" assert os.name == 'posix', NotLinuxSystemError('不是Linux系统') s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) ip = socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', eth[:15]))) return ...
381d3681bee21de2f0fca489536e12f997eaaec8
705,745
def split_line(line) -> list: """Split a line from a dmp file""" return [x.strip() for x in line.split(" |")]
e9c5fb93bab1007b3deb11b8d71fe0cffd3f5bab
705,746
def translate(text): """.""" return text
a0732d6a802f9846de5b294863f2c096f72c6c70
705,747
def helper(n, big): """ :param n: int, an integer number :param big: the current largest digit :return: int, the final largest digit """ n = abs(n) if n == 0: return big else: # check the last digit of a number if big < int(n % 10): big = int(n % 10) # check the rest of the digits return helper(n/1...
aa7fa862d326d9e3400b58c9c520a10672e7340c
705,748
def getPageNumber(ffile): """ Extract the page number from the file name :param ffile: :return: image URI as a string """ return str(ffile).split('_')[-1].split('.')[0]
f78166ae3da8ea234c98436144e6c815f341ff5e
705,750
import os def get_files_from_folder(directory, extension=None): """Get all files within a folder that fit the extension """ # NOTE Can be replaced by glob for newer python versions label_files = [] for root, _, files in os.walk(directory): for some_file in files: label_files.append...
e572333be8786a32aabf2e217411c9db11e65175
705,751
def predicate(line): """ Remove lines starting with ` # ` """ if "#" in line: return False return True
ff7d67c1fd7273b149c5a2148963bf898d6a3591
705,752
import random def fight(player, enemy): """ This starts a round of combat between the user and their selected enemy. It returns a list of information relating to combat, to be used in the view function to display it, if required. """ # Random player damage based on 80-100% of player damage s...
bca739be92ccacb92c90d784cdbf5b4abb2e61c0
705,754
def sort_list_by_list(L1,L2): """Sort a list by another list""" return [x for (y,x) in sorted(zip(L2,L1), key=lambda pair: pair[0])]
04b7c02121620be6d9344af6f56f1b8bfe75e9f3
705,755
def unpack_singleton(x): """Gets the first element if the iterable has only one value. Otherwise return the iterable. # Argument: x: A list or tuple. # Returns: The same iterable or the first element. """ if len(x) == 1: return x[0] return x
cf551f242c8ea585c1f91eadbd19b8e5f73f0096
705,756
from typing import List from typing import Dict def make_car_dict(key: str, data: List[str]) -> Dict: """Organize car data for 106 A/B of the debtor :param key: The section id :param data: Content extract from car data section :return: Organized data for automobile of debtor """ return { ...
671cb2f82f15d14345e34e9823ea390d72cf040a
705,757
def draw_support_spring( fig, support, orientation="up", color='orange', show_values=True, row=None, col=None, units="N/m"): """Draw an anchored spring shape on a plotly figure. Parameters ---------- fig : plotly figure plotly figu...
73c546289ac02d9021375f553504991bdaa4ca89
705,758
def quantity_remover(my_thing): """ removes pint quantities to make json output happy Parameters ---------- my_thing Returns ------- """ if hasattr(my_thing, 'magnitude'): return 'QUANTITY', my_thing.magnitude, my_thing.units.format_babel() elif isinstance(my_thing, ...
54b2db5b638f297ca503513f79eb4eec4ac2afa2
705,759
def cleanse_param_name(name): """Converts Chainer parameter names to ONNX names. Note ONNX identifiers must be a valid C identifier. Args: name (str): A Chainer parameter name (e.g., /l/W). Returns A valid ONNX name (e.g., param_l_W). """ return 'param' + name.replace('/', '_')
9b7774aabeeab322f53321b91195333359c8ee7b
705,760
def _s_to_b(value): """[string to binary single value]""" try: return bytes(value, 'utf-8') except: return value
bbabffa2fbd2ec62778a19c8ab3e1fe410b4640f
705,761
import struct def get_array_of_float(num, data): """Read array of floats Parameters ---------- num : int Number of values to be read (length of array) data : str 4C binary data file Returns ------- str Truncated 4C binary data file list List of flo...
92a0a4cc653046826b14c2cd376a42045c4fa641
705,762
def count_routes_graph(graph, source_node, dest_node): """ classic tree-like graph traversal """ if dest_node == source_node or dest_node - source_node == 1: return 1 else: routes = 0 for child in graph[source_node]: routes += count_routes_graph(graph, child, dest...
f952b35f101d9f1c42eb1d7444859493701c6838
705,763
import six def inject_timeout(func): """Decorator which injects ``timeout`` parameter into request. On client initiation, default timeout is set. This timeout will be injected into any request if no explicit parameter is set. :return: Value of decorated function. """ @six.wraps(func) de...
479ed7b6aa7005d528ace0ff662840d14c23035c
705,764
def cver(verstr): """Converts a version string into a number""" if verstr.startswith("b"): return float(verstr[1:])-100000 return float(verstr)
1ad119049b9149efe7df74f5ac269d3dfafad4e2
705,765
def _replace_oov(original_vocab, line): """Replace out-of-vocab words with "UNK". This maintains compatibility with published results. Args: original_vocab: a set of strings (The standard vocabulary for the dataset) line: a unicode string - a space-delimited sequence of words. Returns: a unicode ...
2e2cb1464484806b79263a14fd32ed4d40d0c9ba
705,768
import os async def stat_data(full_path: str, isFolder=False) -> dict: """ only call this on a validated full path """ file_stats = os.stat(full_path) filename = os.path.basename(full_path) return { 'name': filename, 'path': full_path, 'mtime': int(file_stats.st_mtime*1...
f78a27ac9cbe116c6a04e5a5dbc45e454b26f02b
705,770
import os def fix_path(file_path): """fixes a path so project files can be located via a relative path""" script_path = os.path.dirname(__file__) return os.path.normpath(os.path.join(script_path, file_path))
f733b0c0eb12ced5193393013198d89cd774297a
705,771
import json import subprocess import sys def cmd(cmd_name, source, args: list = [], version={}, params={}): """Wrap command interaction for easier use with python objects.""" in_json = json.dumps({ "source": source, "version": version, "params": params, }) command = ['/opt/res...
be1ebe77c70ce2b377cb64d6d54f043c39dde85a
705,772
def geq_indicate(var, indicator, var_max, thr): """Generates constraints that make indicator 1 iff var >= thr, else 0. Parameters ---------- var : str Variable on which thresholding is performed. indicator : str Identifier of the indicator variable. var_max : int An uppe...
319f18f5343b806b7108dd9c02ca5d647e132dab
705,773
import re def parse_manpage_number(path): """ Parse number of man page group. """ # Create regular expression number_regex = re.compile(r".*/man(\d).*") # Get number of manpage group number = number_regex.search(path) only_number = "" if number is not None: number = nu...
b45edb65705592cd18fd1fd8ee30bb389dbd8dff
705,774
import argparse def ParseArgs(argv): """Parses command line arguments.""" parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument( '-b', '--bundle-identifier', required=True, help='bundle identifier for the appli...
507935ea2ea42dea66bfff545caecb7fc2cded55
705,775
def get_sale(this_line): """Convert the input into a dictionary, with keys matching the CSV column headers in the scrape_util module. """ sale = {} sale['consignor_name'] = this_line.pop(0) sale['consignor_city'] = this_line.pop(0).title() try: maybe_head = this_line[0].split() ...
39fee66b4c92a2cb459722f238e4a3b6e5848f4d
705,776
import logging def filtering_news(news: list, filtered_news: list): """ Filters news to remove unwanted removed articles Args: news (list): List of articles to remove from filtered_news (list): List of titles to filter the unwanted news with Returns: news (list): List of arti...
98049b6bd826109fe7bc8e2e42de4c50970988a9
705,777
from typing import Optional from typing import List import itertools def add_ignore_file_arguments(files: Optional[List[str]] = None) -> List[str]: """Adds ignore file variables to the scope of the deployment""" default_ignores = ["config.json", "Dockerfile", ".dockerignore"] # Combine default files and ...
f7e7487c4a17a761f23628cbb79cbade64237ce6
705,778
import torch def compute_accuracy(logits, targets): """Compute the accuracy""" with torch.no_grad(): _, predictions = torch.max(logits, dim=1) accuracy = torch.mean(predictions.eq(targets).float()) return accuracy.item()
af15e4d077209ff6e790d6fdaa7642bb65ff8dbf
705,779
def gm_put(state, b1, b2): """ If goal is ('pos',b1,b2) and we're holding b1, Generate either a putdown or a stack subtask for b1. b2 is b1's destination: either the table or another block. """ if b2 != 'hand' and state.pos[b1] == 'hand': if b2 == 'table': return [('a_putdown...
c9076ac552529c60b5460740c74b1602c42414f2
705,780
import random import time def hammer_op(context, chase_duration): """what better way to do a lot of gnarly work than to pointer chase?""" ptr_length = context.op_config["chase_size"] data = list(range(0, ptr_length)) random.shuffle(data) curr = random.randint(0, ptr_length - 1) # and away we...
f4a51fe1e2f89443b79fd4c9a5b3f5ee459e79ca
705,781
def get_child(parent, child_index): """ Get the child at the given index, or return None if it doesn't exist. """ if child_index < 0 or child_index >= len(parent.childNodes): return None return parent.childNodes[child_index]
37f7752a4a77f3d750413e54659f907b5531848c
705,782
import os def split_missions_and_dates(fname): """ Examples -------- >>> fname = 'nustar-nicer_gt55000_lt58000.csv' >>> outdict = split_missions_and_dates(fname) >>> outdict['mission1'] 'nustar' >>> outdict['mission2'] 'nicer' >>> outdict['mjdstart'] 'MJD 55000' >>> ou...
851fa5a85d0acfd9d309725284ebb1859734432e
705,783
def get_renaming(mappers, year): """Get original to final column namings.""" renamers = {} for code, attr in mappers.items(): renamers[code] = attr['df_name'] return renamers
33197b5c748b3ecc43783d5f1f3a3b5a071d3a4e
705,784
async def clap(text, args): """ Puts clap emojis between words. """ if args != []: clap_str = args[0] else: clap_str = "👏" words = text.split(" ") clappy_text = f" {clap_str} ".join(words) return clappy_text
09865461e658213a2f048b89757b75b2a37c0602
705,785
def remove_extra_two_spaces(text: str) -> str: """Replaces two consecutive spaces with one wherever they occur in a text""" return text.replace(" ", " ")
d8b9600d3b442216b1fbe85918f313fec8a5c9cb
705,786
def load_utt_list(utt_list): """Load a list of utterances. Args: utt_list (str): path to a file containing a list of utterances Returns: List[str]: list of utterances """ with open(utt_list) as f: utt_ids = f.readlines() utt_ids = map(lambda utt_id: utt_id.strip(), utt_...
6a77e876b0cc959ac4151b328b718ae45522448b
705,787
def compute_flow_for_supervised_loss( feature_model, flow_model, batch, training ): """Compute flow for an image batch. Args: feature_model: A model to compute features for flow. flow_model: A model to compute flow. batch: A tf.tensor of shape [b, seq, h, w, c] holding a batch of triple...
a74f392c1d4e234fdb66d18e63d7c733ec6669a7
705,788
import os def _get_filename_from_request(request): """ Gets the filename from an url request. :param request: url request to get filename from :type request: urllib.requests.Request or urllib2.Request :rtype: str """ try: headers = request.headers content = headers["conte...
51d2f79ebc5f2abf57d5b12d0271d6d704a24297
705,789
import os def _find_pkg_info(directory): """find and return the full path to a PKG-INFO file or None if not found""" for root, dirs, files in os.walk(directory): for filename in files: if filename == 'PKG-INFO': return os.path.join(root, filename) # no PKG-INFO file fou...
ada0afe963cb859a5c5b19813ebbdea03cda7db3
705,790
import itertools def labels_to_intervals(labels_list): """ labels_to_intervals() converts list of labels of each frame into set of time intervals where a tag occurs Args: labels_list: list of labels of each frame e.g. [{'person'}, {'person'}, {'person'}, {'surfboard', 'person'}] Retu...
65b63ea3e6f097e9605e1c1ddb8dd434d7db9370
705,791
def get_wolfram_query_url(query): """Get Wolfram query URL.""" base_url = 'www.wolframalpha.com' if not query: return 'http://{0}'.format(base_url) return 'http://{0}/input/?i={1}'.format(base_url, query)
0122515f1a666cb897b53ae6bd975f65da072438
705,792
import copy def merge_dictionary(src: dict, dest: dict) -> dict: """ Merge two dictionaries. :param src: A dictionary with the values to merge. :param dest: A dictionary where to merge the values. """ for name, value in src.items(): if name not in dest: # When field is n...
12305510a9a2d50bcdc691cb7fe8d5a573621e69
705,793
import json def scheming_multiple_choice_output(value): """ return stored json as a proper list """ if isinstance(value, list): return value try: return json.loads(value) except ValueError: return [value]
d45bbb1af249d0fed00892ccc55cf8f28f7f099f
705,794
import re import os def get_name(path): """get the name from a repo path""" return re.sub(r"\.git$", "", os.path.basename(path))
42c410fd21e1d50270cf7703b9f054a8455c7efd
705,795