content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def visualize_scenes(x, generator): """Split images into rgb and depth.""" keys = ['img', 'img_single'] if generator.bg_cube: keys.append('img_bg') out = {} for k in keys: v = x[k] if v is None: rgb = d = None else: rgb = x[k][:, :3] d = x[k][:, -1:] out[f'vis_{...
c3186f31479d7d36efa7a63a0a9d0c3f729dc461
638,679
def split_ko_by_char(sentence, sep=' '): """ split_ko_by_char('안녕 하hello') """ r_lst = '' for w in sentence: if '가' <= w <= '힣': r_lst += (w + sep) else: r_lst += w return r_lst
479648ae0998bcaec89bf1ca0d87a33583c6faad
638,680
import os def add_folder(args, handle, parent_folder, child_folder): """Makes folder_name inside parent_folder and stores in args """ args.folders[handle] = "{}/{}".format( parent_folder, child_folder) os.system("mkdir -p {}".format( args.folders[handle])) return None
9e28e2b4223640aa076215be0d52da0d41361b02
638,681
def genRowList(df, sensitive_zeros): """Converts a dataframe to a list of rows. Args: df: the dataframe. sensitive_zeros: columns for which negative values should be controlled. Returns: row_list: the list of rows. """ row_list = [] for _, row in df.iterrows(): ...
57962b7bf52d56e13be27d3509cc167a9d13c41e
638,682
def get_transit_57(): """Return schedule for 57""" # type: () -> List # in_timings = [] # out_timings = [] # # # with urllib.request.urlopen( # 'http://webservices.nextbus.com/service/publicXMLFeed?command=predictions&a=sf-muni&stopId=14704') as response: # html = respon...
3c581038192379ac0026080d44f5f24bc1603fe4
638,683
def sphinx_role(record, lang): """ Return the Sphinx role used for a record. This is used for the description directive like ".. c:function::", and links like ":c:func:`foo`. """ kind = record["kind"] if kind in ["class", "function", "namespace", "struct", "union"]: return lang + ...
68db234074179cb51af45ea9a2d5098a9d5311ac
638,684
import io def compile(data): """Compiles raw data into an image array""" arr = io.BytesIO() data.save(arr, format = "PNG") arr.seek(0) return arr
ac2d5124f3ab5b5c70bda088dfe91ac994256204
638,686
def _phi_post_processing(phi, N, sorted_by): """Post processing of the dictionary `phi`.""" _phi = dict() if sorted_by == 'term': for (n, k) in phi.keys(): _phi[(n, k)] = phi[(n, k)] / (2**n) elif sorted_by == 'order': for n in range(1, N+1): _phi[n] = phi.pop((n...
af0b4752df8790aa6d962f7f083b6d6f0392304c
638,687
def pfsockopen(): """ Open persistent Internet or Unix domain socket connection""" return NotImplementedError()
d51646d624b6003b7c59df1b893a68b5679e61ea
638,688
from typing import Optional import warnings import random def make_permutation_space(*, elements: list, n_permutations: int, random_seed: Optional[int] = None) -> list: """ Generates a list of tuples containing n_permutations of ...
3c833649eef3e2c991f56553d5d15a2d8eadf53b
638,689
def mock_cs_raises_ImportError(): """We create a mock control system to replace CothreadControlSystem, so that we can check that when it raises an ImportError load_csv.load catches it and raises a ControlSystemException instead. N.B. Our new CothreadControlSystem is nested inside a fixture so it...
d4854f98b4bf6368673cc9c49e2607b38b674f15
638,690
def card_name(value, suit): """ Constructs a name for the card, using the given value, and suit. :arg str value: The value to use. :arg str suit: The suit to use. :returns: A newly constructed name, using the given value & suit. """ if value == "Joker": ...
6f2db64964e99840aab73f2124c9f9a862cb7a72
638,691
def extract_string(str, start, end): """ Returns the string between start and end. """ s = str.find(start) if s < 0: return None slen = len(start) e = str.find(end, s + slen) if e < 0: return None return str[s + slen:e]
cc1495579383924eca4d96d644c3aacbdaccb459
638,692
def rpc_handler(*function_tags): """ Decorator for an RPC handler, may contain multiple functions """ def decorator(handler): handler.__rpc_tags = function_tags return handler return decorator
00dd06ec704cc313f83f44a0571d3de70900924c
638,693
def exprofile(self, ldtype="", load="", value="", pname="", fname="", fext="", fdir="", **kwargs): """Exports interface loads or loads on selected nodes to an ANSYS CFX APDL Command: EXPROFILE Profile file. Parameters ---------- ldtype Load type: SURF - Surface ...
19d5b6a8ec414fb333c0b91db16833840d1129e2
638,694
import os def getImagesFrom(folder_addr, extension='.png'): """ Returns a list of images from a path, with the desired extension. Parameters ---------- folder_addr : str Path to a target directory extension : str Extension of target image files, such as '.png', '.jpg', etc...
6b442c96540eb2b3c04f193b6a7b00800ebb2936
638,695
import sys def inflow(streams): """Determine index of stream for next inflowing particle. Parameters ---------- streams : list of `Stream` List of Stream objects for inlet streams. Returns ------- i_inflow : int Index of stream for next inflowing particle. """ #...
b1e60e4fd367b3d2304379fbd97ee6b7a0349dfb
638,696
import shlex import tempfile import subprocess def run(command_str: str) -> tuple[int, str, str]: """Execute a shell command.""" command = shlex.split(command_str) # use tempfile to overcome the buffer limit stdout = tempfile.TemporaryFile(buffering=0) stderr = tempfile.TemporaryFile(buffering=0)...
1c8e0cd971e8c34fe027547b768812c43e2f7bd6
638,697
def gf_lshift(f, n, K): """ Efficiently multiply ``f`` by ``x**n``. **Examples** >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_lshift >>> gf_lshift([3, 2, 4], 4, ZZ) [3, 2, 4, 0, 0, 0, 0] """ if not f: return f else: return ...
cbc00d595534c0f7816d6604756deb712fdb5045
638,698
def normalize_msisdn(msisdn, country_code='27'): """ Normalizes msisdn using provided country code. Country code defaults to '27' (South Africa) e.g. '082 111 2222' -> '+27821112222' """ # Don't touch shortcodes if len(msisdn) <= 5: return msisdn # Strip everything not a digit or...
fcc53fb7e68136ee531815579d1c083e3aba44e9
638,699
import os import subprocess def silent_check_call(*args, **kwargs): """Wrapper for `subprocess.check_call` which silences all output""" with open(os.devnull, 'w') as devnull: return subprocess.check_call(*args, stdout=devnull, stderr=devnull, **kwargs)
98d5cbc07dea0b39d766c19d2ef848c0890cf5d0
638,700
import torch def _signed_area(path: torch.Tensor) -> torch.Tensor: """ Calculates the signed area / Lévy area of a 2D path. If the path is closed, i.e. ends where it starts, this is the integral of the winding number over the whole plane. If not, consider a closed path made by adding a straight li...
47716d51f981613add08d04ed8d01d5794c89fd6
638,701
def intersection(array1, array2): """ Intersection. Intersects two Lists, resulting in values that reside in both lists. Parameters ---------- array1 : List First List. array2 : List Second List. Returns ------- List Containing values that reside in bot...
15d4dcef2a3fe0926b75edb762b9c51fdfe30349
638,702
def _get_large_test_payload(content_type): """Produces a large test payload, to avoid having pytest output print the contents of a fixture. """ if content_type == 'text/csv': return 'timestamp,value\n'+"1"*17*1024*1024 else: return '{"values": ['+"1"*17*1024*1024+']}'
b8ad39429d22b873d4d406d613414e4d1131f6b3
638,703
import collections import logging import json def get_manuscript_stats(text): """ Compute manuscript statistics. """ stats = collections.OrderedDict() stats["word_count"] = len(text.split()) logging.info(f"Generated manscript stats:\n{json.dumps(stats, indent=2)}") return stats
85de21a82f339884a459884436079aa691271209
638,704
def get_rc_value(cv_values, settings): """ Evaluate and return reaction coordinate value based on a given list of cv_values. Parameters ---------- cv_values : list A list of values for the CVs to plug into the RC equation as needed (same order as candidateops) settings : Namespace ...
b9c846fad419327e4b04371d5b08e92413ca2b90
638,705
def readKeyValueCSV(filename): """ Reads a key-value csv file and returns the contents as a python dictionary. @filename is the path to the file. returns: file contents as <dictionary> """ # Resultant dictionary. result = {} # Read file and collect key-value pairs into result. with open(filename, "r") as...
57ad73af0b85e803cff7722c411ffc617b9c04e3
638,706
def total_rain(rain_hours: list) -> int: """ Sum up the rain mm from list of rain hours """ if len(rain_hours) > 0: return round(sum([list(x.values())[0]['1h'] for x in rain_hours]), 2) else: return 0
72e26bdb2600eaaa321a532712dd1a815ba01789
638,707
def _xr_to_keyset(line): """ Parse xfsrestore output keyset elements. """ tkns = [elm for elm in line.strip().split(":", 1) if elm] if len(tkns) == 1: return "'{}': ".format(tkns[0]) else: key, val = tkns return "'{}': '{}',".format(key.strip(), val.strip())
5ffd6d972e3b074dc47795c8da880fda5bc53bcb
638,708
def parse_table_name(default_schema, table_name, sql_mode=""): """Parse table name. Args: default_schema (str): The default schema. table_name (str): The table name. sql_mode(Optional[str]): The SQL mode. Returns: str: The parsed table name. """ quote = '"' if "ANSI...
affc26703efab06643261af0d5cd7bf3efd0fcf8
638,709
def match(p1, p2, common): """Return whether clauses in common match. Arguments: p1 {np.array} -- first possibility p2 {np.array} -- second possibility common {(str,int,int)} -- common clauses Returns: True/False -- Do clauses in common match? """ for c in common: ...
224d54c21e1613f9813b725e721b8033ee28694b
638,710
def _convert_checkpoint(state): """Enable loading checkpoints in the old format""" if "_version" not in state: # Old checkpoint format meta = state['meta'] state['net_params'] = { "architecture": meta['architecture'], "pretrained": True, "skip_layer": ...
2432158cb6bb6f1c84feea3bcf572c51112bbad3
638,711
def write_int_ranges(int_values, in_hex=True, sep=" "): """From a set or list of ints, generate a string representation that can be parsed by parse_int_ranges to return the original values (not order_preserving).""" if not int_values: return "" num_list = [] int_values = iter(sorted(i...
7cd69925887127d3058f3184640f0755b541fe58
638,712
def build_flow(steps): """Builds a flow from a list of steps, by chaining the steps according to their order in the list. Nested lists are used to represent branches in the flow. Examples: build_flow([step1, step2, step3]) is equivalent to step1.to(step2).to(step3) build_fl...
5ed2a0c02f93aca608a8cd161400711bfc00430f
638,714
import time def toc(tic): """Returns the time since 'tic' was called.""" return time.perf_counter() - tic
976cdeb30a723a8667ae2e0d86a4270ad356d634
638,715
import inspect def _schema_get_docstring(starting_class): """ Given a class, return its docstring. If no docstring is present for the class, search base classes in MRO for a docstring. """ for cls in inspect.getmro(starting_class): if inspect.getdoc(cls): return inspect.getdoc...
8c2bf48da22ebea9f440d51e903522561b23920e
638,716
def get_globals(): """Return a dictionary of dlobal variables.""" return {k:v for k,v in globals().items() if not k.startswith("_")}
1551442f5a6a200296c0d8f5fe249dfe58b72049
638,717
def values_to_dict(values): """ Each row from the spreadsheet is converted to a dict using the first row as the keys. :param values: a list of lists containing the values of a spreadsheet loaded with the sheets api. The first row is considered to contain the header information. :returns: a list of d...
28cc31d0af662937765d152295f8deea173542ec
638,718
import os def get_immediate_subdirectories(file_path, reverse_order=False, show_hidden=False): """Return the direct sub-directories of a given file path.""" if not file_path: raise TypeError('file_path not provided.') directories = [] for name in os.listdir(fi...
cc37aa741493d5874980c2e9af382bb69b59341f
638,719
import os def _list_subdirs(base_dir): """Lists all subdirectories in base_dir, raising ValueError if none exist.""" subdirs = [] for dir_entry in os.listdir(base_dir): if os.path.isdir(os.path.join(base_dir, dir_entry)): subdirs.append(dir_entry) if not subdirs: raise ValueError("No subdirecto...
ffe3a91b08ef827c39598d64cfc1cc134e41f4d3
638,721
def encode_table(joins, froms, table_name, selects, comparisons, output): """Encodes the joins, froms, and """ output[table_name] = {'joins':[], 'selects':selects} # Set the join meta-data for index, _ in enumerate(joins): comparison_left = comparisons[index][0] comparison_right = compar...
357e1db8699948387b2b760b1fc2d37e66710f91
638,722
def make_recurrence(minute, hour, day_of_week): """Return abbreviated form of recurrence. Rather than use a full crontab entry, Tempo currently uses an abbreviated form of specifying the cron schedule, skipping the day of month and month fields. """ return ' '.join(map(str, [minute, hour, day_o...
9c4b3c615124f9d014f290a3894bc0c497284147
638,723
def echapper_accolades(message): """Echappe les accolades.""" return message.replace("{", "{{").replace("}", "}}")
60684030b297d769c11d1a28907f68a7093a7937
638,724
def apply_contraction_mapping(text): """ Applies the contraction mapping to the specified text :param text: the text on which the contraction will be mapped :return: the text after the application of contraction mapping """ contraction_mapping = {"ain't": "is not", "aren't": "are not", "can't": ...
a616529be303023bad7f1d827c5832b7240385fb
638,725
def notas(*args, situacao=False): """ => Recebe várias notas de um aluno e retorna: - A quantidade de notas recebidas - A maior nota - A menor nota - A média da turma - A situação académica (opcional) :param notas: recebe várias notas :param situacao: (opcional) mostra ou não a situação académica :return: dic...
862e3d645918144efd73a76772090dd81696df72
638,726
def min_skew(DNA: str) -> list: """Finds all indexes of minimum skew in a DNA string 'Minimum skew' is when #G - #C is at a minimum. Other bases are ignored :param DNA: the DNA string to calculate skew for :type DNA: str :returns: all indexes where #G - #C is minimized :rtype: list: """ ...
90e22db21f90f75337cb43e81e30b5e5715c6ea2
638,727
def render_bus(context, player, refresh=False): """Render order footer.""" return { "player": player, "request": context.get("request"), "refresh": refresh, "bus": player.room.game.game.bus.bus, "current_card": player.room.game.game.bus.current_card(), "room": pla...
49ba33b0ebf193481a59c801337b84a277eb85ae
638,728
def human_time(s): """Convert floating-point seconds into human-readable time""" if s < 60.0: return "%.3f" % s m = int(s) / 60 if m < 60: return "%d:%06.3f" % (m, s % 60) return "%d:%02d:%06.3f" % (m // 60, m % 60, s % 60)
5ab95271223ab65d44fce3c09e4f77e51e9be342
638,729
import _asyncio async def _wait_with_concurrency(tasks, pool_size): """ Make sure we only run `pool_size` tasks at once """ semaphore = _asyncio.Semaphore(pool_size) async def sem_task(task): async with semaphore: return await task return await _asyncio.wait([sem_task(task) for ta...
7eda04e4c7e6e920a5cc1aa57a364347070f5f73
638,730
import re def remove_comments(text): """ remove c-style comments. text: blob of text with comments (can include newlines) returns: text with comments removed """ pattern = r""" ## --------- COMMENT --------- /\* ## Start of /* ... */ co...
2c97fae55ba7a228e7a6ad9c2d47b1af0e0e02fc
638,731
def parse_cfg(cfgfile): """ 输入: 配置文件路径 返回值: 列表对象,其中每一个元素为一个字典类型对应于一个要建立的神经网络模块(层) """ # 加载文件并过滤掉文本中多余内容 file = open(cfgfile, "r") lines = file.read().split("\n") # store the lines in a list等价于readlines lines = [x for x in lines if len(x) > 0] # 去掉空行 lines = [x for x in lines if x[0...
a42e55d74b7f35e9600894961c360f4cda908b7d
638,732
def composition(f, g): """Return a composition of two functions """ def fg(arg): return g(f(arg)) return fg
2e1f99de6250b82bcc63a4f4697cfe3887dc7243
638,733
import math def calculate_fuel_requirement(mass): """Calculates the fuel requirement based on the given mass. (Part 1) Parameters: mass (int): mass of the module Returns: int:Fuel required """ return math.floor(mass / 3) - 2
4456602dd91a0cb897f3ecdcdc01252795bb2dd7
638,734
def addTwoNumbersByDavidKe(x, y): """returns the sum of a range of floats""" return x + y
671641069735da15d0356436c4ea009702bce6e0
638,735
def wait_for_task(runningTasks, timeout=0.1): # {{{ """ Build a list of analysis modules based on the 'generate' config option. New tasks should be added here, following the approach used for existing analysis tasks. Parameters ---------- runningTasks : dict of ``AnalysisTasks`` Th...
7c421a9a433ba8ba2d02d250a01ccb0de0aee355
638,737
from typing import List import struct def unpack_uint64s(data: bytes) -> List[int]: """ Unpack a series of integers that were packed with pack_uint64.""" if len(data) == 0: return [] return list(x[0] for x in struct.iter_unpack(">Q", data))
1685ed2db9dd903e06578d9a8e98e6071cc013a9
638,738
def utils_args_str(*args): """format a list of args for use with utils.py""" return ' '.join(['--arg={}'.format(arg) for arg in args])
1a5cbf619a4bc69ad4dc4deed5cce85e618f826c
638,739
def unique_responses(group_responses: list) -> list: """ From the list of group responses, pick out the unique responses. Args: group_responses [list] : A list of of lists. Each sub-list contains each groups' person's responses. Returns: list [str] : A list of lists, with d...
e3e30198cb5743fd70a68f1cda8d561547d6d7c0
638,740
from typing import OrderedDict def read_basis(fname): """ return basis names from file (often named as basis.txt). Return a dict. key: basis name. value: basis index, from 0 """ bdict = OrderedDict() if fname.endswith('.win'): with open(fname) as myfile: inside = False ...
f03f01a610c093e50ad7a0b737491bdc3cb870d8
638,741
def benchmark_header( scriptName='script' ): """ Write the header of the benchmarking script. * scriptName = Name of the benchmarking script """ out_file = scriptName.replace('.py','.benchmark.txt') lines = [] lines.append("### Begin Benchmarking Material") lines.append("import casa_call...
7f9937d6bba7267a6c43970c7d36815916049ec7
638,742
def calc_tot_orbits(n_orbit_dict): """Calculate the total number of direct and indirect orbits in n_orbit_dict. Parameters ---------- n_orbit_dict : dictionary A dictionary where each key is an object in the system and each value is a tuple of 2 values. The first represents the numb...
07a9dbc11866b9710503ef8fe75297c14aa0b6c9
638,743
from datetime import datetime def getyrdoy(date): """Return a tuple of year, day of year for a supplied datetime object. Parameters ---------- date : datetime.datetime Datetime object Returns ------- year : int Integer year doy : int Integer day of year "...
506e68bd9dfd47e19771f197dbbf0f93791c30d9
638,745
import math def detectTriangle(supYs,resYs,high,low): """ Detect Triangle and Wedge Patterns Inputs: (supXs,supYs): List of support lines as pairs of x,y lists supSlope: List of slopes of support lines (resXs,resYs): List of resistance lines as pairs...
27ccf4f3c6032390da019aaace5af146192a5861
638,746
def grad_refactor_6(a, b): """ if_test """ if a > b: return 3 * a + b return 2 * b * a
fa10e44401714af6aa9ba620b1d356815ee3b31d
638,747
def _is_leaky_relu_quantizable(layer_node, alpha_target=0.1, threshold=1e-7): """Due to DPU constraints, only leaky_relu with alpha=0.1 is quantizable.""" alpha = layer_node['config']['alpha'] if abs(alpha - alpha_target) < threshold: return True else: return False
d5d079a3bb3e8a8f6bdb81d832bf4a9260c183b6
638,748
def help_letters_and_numbers(arg): """a function to calculate a letter from a string""" for i in arg: if i not in '123456789': return i return arg
d986e316908d338bda768a8568a4e62bc5739e5b
638,749
def indefinite_integral_helper(x,c1,c2,c3,c4): """Indefinite Integral of for use in the following functions. The integral is after the swapping of t=(1-r^2)^(1/4). Assuming Fe=1. """ return c1*x*(1-x**4/5)+c2*x**2*(1-x**4/3)+c3*x**3*(1-3/7*x**4)+c4*x**4*(1-0.5*x**4)
52849e52ead2198d07fc78bfcc9ecfe62696d8b8
638,750
def preprocess_df(df): """ Select the english captions and extract only the desired columns from the dataframe like 'Name' and 'Description' df: dataframe which contains the captions """ df = df[df['Language'] == 'English'].copy() df['Name'] = df[['VideoID', 'Start', 'End']].apply(lambda x: x['...
cf73810ba2f152278cffe0acced1b9d454bc75e5
638,752
def b2s(fileobj, encoding='utf-8'): """ Reads until \x00 """ chars = list() while True: c = fileobj.read(1) if c == b'\x00': return "".join(chars) chars.append(c.decode(encoding))
92d484698c33288c086cd66cb83048ff51639780
638,753
from typing import Dict import re def update_weight_name(repl_patterns: Dict[str, str], weight_name: str) -> str: """Updates weight names according a dictionary of replacement patterns.""" # Create a regular expression from all of the dictionary keys regex = re.compile('|'.join(map(re.escape, repl_patterns.keys...
bbf382e69501b052a5eb0aa53adf1a53fc735e6f
638,754
import numpy def logsum(a_n): """ Compute the log of a sum of exponentiated terms exp(a_n) in a numerically-stable manner: logsum a_n = max_arg + \log \sum_{n=1}^N \exp[a_n - max_arg] where max_arg = max_n a_n. This is mathematically (but not numerically) equivalent to logsum a_n = \log \sum_{n=1}^N...
0d2a1261a568f7f3ce0a6a7522bf90bca98d59d5
638,756
from typing import List from typing import Dict from typing import Any def merge_flat_dicts( languages: List[str], flat_dicts: List[dict] ) -> Dict[str, Dict[str, Any]]: """ creates a dict of keys:index -> (key:languages -> value: text) when merging with merge and base :param languages: :p...
22cd74a0078ea5c8e647e77abd4c8d6fe790702a
638,757
import random def random_box(video, type_id, frame): """ Returns random localization spec for given video object and frame. :param video: :class:`tator.models.Media` object. :param type_id: Localization type ID. :returns: Random localization spec. """ x = random.uniform(0.0, 0.95) y = ran...
f6fb14ccf3f22aeb3ecf6465a2830bcd999c7909
638,758
def _RemoveRedundantHandlers(handler_list): """Removes duplicated or unnecessary handlers from the list. If a handler's pattern and functionality are fully matched by another handler with a more general pattern, we do not need the first handler. At the same time, we remove duplicates. Args: handler_lis...
9fece01e66de352e16590c2dd4aa0942c8452e7c
638,759
import aiohttp async def request(url, *, headers=None, **kwargs): """Base GET request in case you need more control over GET requests. Params ======= headers: dict (Optional) kwarg: kwargs (Optional) Returns ======= Response: aiohttp Response object """ async with aiohttp.Cli...
5e1dc33b0667b0a742c7062e5347c43dc4c3d4c0
638,760
def params_log_ces(factors): """Index tuples for the log_ces production function.""" return factors + ["phi"]
fd32d30785e479da77ef42a228d3445d35216178
638,761
def _date_within( some_date, start_date, end_date ): """ check if start_date <= some_date <= end_date , considering inequality to be true if either start_date or end_date is None """ result = True # start with a truth assumption if start_date is not None: result = resu...
ba9aa20fce1d981cab8401a84b5f1ab45229f424
638,762
def FillNan(df, method='linear'): """Fill Nan values of X_train of X_test with an interpolation.""" # Interpolate the missing value thanks to interpolation for each station_id columns_to_interpolate = ["value_" + str(i) for i in range(10)] # Group samples by station_id g_stations_df = df.groupby([...
c856d6bfff4aa31bbaadab7bc2ec482abe9079d5
638,763
import requests def aud_to_usd(aud_amount, date): """Convert the AUD amount to USD.""" r = requests.get("https://api.fixer.io/{}?base=USD".format(date)) j = r.json() rate = j["rates"]["AUD"] return aud_amount / rate
36f3849382a0c0cc8d1616303c6695b7b32a0782
638,764
from typing import Tuple from typing import Any from typing import List def unpack_response(response: dict) -> Tuple[Any, List[str]]: """Unpack response from dictionary and fetch ranking and keywords.""" assert isinstance(response, dict), "Empty response. Try again." rankings = [*response[[*response][0]]...
f4d985be4d0d2e7322c85eee1aab8d861c91cb15
638,765
def _duplicate_entry(i, keys, population, len): """ Args: :i: :keys: :population: :len: Returns: """ hp_combinations = [] duplicate_indices = [] for val in range(len): entry='' for key in keys: entry += str(population[key][val])...
cc2fdc1673eba71cfeb3f1baac04c1b10e6100ac
638,766
import os def contains_dir_path(file_name: str) -> bool: """Returns True if file_name contains OS path components separator. Returns False otherwise. """ return os.path.sep in file_name
0fb49f4884538ae6ca004106ca52e1e7d3dccae4
638,767
import torch def conv_constitutive_constraint_nonlinear_exp(input, output, sobel_filter): """Nonlinear extension of Darcy's law sigma = - exp(K * u) grad(u) Args: input: K output: u, sigma1, sigma2 """ grad_h = sobel_filter.grad_h(output[:, [0]]) grad_v = sobel_filter.grad...
5390111f87bc726ee3a206c5f0519701e58623f8
638,768
def _preprocess(sentences, preprocess_pipeline, word_tokenize=None): """ Helper function to preprocess a list of paragraphs. Args: param (Tuple): params are tuple of (a list of strings, a list of preprocessing functions, and function to tokenize setences into words). A parag...
9f44962a5ba4a66523beb40feb0a25b63d1dc528
638,770
from numpy import flip def binarr_to_number(vector): """ converts a vector of bits into an integer. """ num = 0 vector = flip(vector) length = vector.shape[0] for i in range(length): num += (2**(i))*vector[i] return num
bde8c7a975da4ca0c675c10f7a0346cb54b7ca89
638,771
import os def _is_pdb_file(pdb_file, extension=None): """Check if provided file is a pdb file.""" if not os.path.isfile(pdb_file): return False _, ext = os.path.splitext(pdb_file) if extension is None: return ext == ".gz" or ".pdb" in ext else: return ext == extension
72e0b64cb6dac0a31d3e6a2a442d57318c8063af
638,772
def zero_equation_0(x, param_0): """ Zero equation :param x: :param param_0: :return: """ return 0
6482a9f6db29f8a74751c6725a29260c61fb7574
638,773
def register(*decorators): """ This allows us to register multiple decorators and later being able to determine which decorators were registered on the given method This is necessary, because our decorators from Middlewares are just marking the method, so when the Middleware's process_request() method ...
000aca5e02a849e561858136496e118025fc12e2
638,774
import os import re import subprocess import sys def _determine_version(options): """ Adds the 'short_version' and 'version' options. Read from the VERSION file to discover the version. This should be a single line file containing valid Python package public identifier (see PEP 440), for example...
b31c21ccbf5330e93d4bd550d910c55433c2c9b0
638,775
def transform_metadata(point): """Bring metadata from the point and put it to the dict.""" metadata = dict() for key, value in point.items(): if (value or value == 0) and key.startswith("metadata."): metadata[key[len("metadata."):]] = value return metadata
13356655eb28dc6e60822fd999f1be1ec9ea61e5
638,776
def extract_task_ids(project_data): """ Extract from project data the list of task id :param project_data: Dictionary of project data of a HOT tasking manager project :return: """ tasks_ids = list() for feature in project_data['tasks']['features']: tasks_ids.append(feature['propertie...
bb276370685d977a98a66195b97be051a20a2d87
638,778
def index(sequence, i): """gets the i-th element from sequence""" try: return sequence[int(i)] except IndexError: pass
f028ca128e3741f0ebb6523943602a834242b33a
638,779
def describe_stack(cfn_client, stack_name): """ Describes a cloudformation stack """ return cfn_client.describe_stacks(StackName=stack_name)["Stacks"][0]
6a5597f66f0103cb9dd9e2c8f0a421bcb95e1d8b
638,780
import subprocess import logging import sys def run_cmd(command): """ XXXX Parameters ---------- XX : XX XXX Returns ------- XXX : XXX XXX """ try: result = subprocess.run(command, capture_output=True,\ check=True, text=True) logging.i...
11f5d355512f553b9c3e178ffa78da6ae017faef
638,782
def _FirewallTargetTagsToCell(firewall): """Comma-joins the target tags of the given firewall rule.""" return ','.join(firewall.get('targetTags', []))
c75ccc9caa8893c5371a4be8e9474b089a7eefca
638,783
import torch import functools def mask_sigma(sigma, pts, mask_radius, mask_rad_norm, invert_mask=False): """Compute and apply mask based on scene bounds.""" masks = [] if mask_rad_norm is not None: if mask_rad_norm == "inf": bounds = (torch....
ba1720314623582f7e485d144b8478afb69efa36
638,784
def get_site_pin_wire(equivalent_site_pin, site_pins): """Returns the site pin wire name of the original site location, given the site pin from the equivalent site. This function requires: - equivalent_site_pin: pin belonging to the equivalent site used to find the co...
cb7352ed0797589821c4d8a31f855ef62875d941
638,785
import os def get_files_in_dir(directory_path): """Get all files in a path Args: directory_path(str) : path where target files are located ted Returns: list_of_files (list): a list that contains all the file names in the directory """ return os.listdir(directory_path)
3ddcaeb679af0f90b16119d166186e9ac64eea50
638,786
import os import sys def import_constraints(path): """ Import constraints from a python file The file at the end of path needs to contain a variable named constraints that contains the constraints. Parameters ---------- path : string path to file.py containing the constraints definition Returns --...
4b91a39367af7b44e8e243921b6f5d861717a48f
638,789
def WMSBBOX(region): """ Return the WMS BBOX query string for this region Returns: string: BBOX=w,s,e,n """ (n,s,e,w) = region.NSEW() return 'BBOX=%f,%f,%f,%f' % (w,s,e,n)
83430c38393c68d5865355ecf3e8eeeecfe56014
638,790