content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def no_sleep(mocker, braze_client): """Disables actual sleeps, but keeps retry wait logic. Zippy tests!""" return mocker.patch.object( braze_client._post_request_with_retries.retry, "sleep", return_value=None )
3a2ac2ced5b3c05cd9403111121b5e61f6948998
655,777
def isWinner(data,c1,c2): """ This function takes the preference ranking data as an input parameter. It computes the head to head winner for the two candidates that are passed into it as parameters. If the first candidate passed as a paramter wins against the second candidate, then the function will ...
6fb1d6d245f6d1a43a9e7fa34e5779b065611458
655,778
def x1(self): """x1 position in % of page""" return self._x1
e9cd790dd03b864a1ceb13efe9f1d1fd078fe6db
655,779
def outgoing_synapses(q, N = None, rel='>',include_inferred=True): """ Get all the outgoing synapses from neurons in a QueryWrapper object. Parameters ---------- q: query.QueryWrapper The query to search for outgoing synapses N: int or None Filter for number of synapses (default...
5e7a358b2f049e447e890f1dd66131cbf8869b3a
655,780
def get_question_asked(handler_input): """ Gets an identifier for the previous question asked to allow for the handling of yes/no questions outside of a DialogState. This identifier is persisted in the Alexa session_attributes and should be removed upon handling the response to avoid unexpected conseque...
ab37c04218ee990fc2412e237d463606a8bedd87
655,782
def revertDateTimeToLongString(dt): """ Turns a date/time into a long string as needed by midas code. """ return str(dt).replace("-", "").replace(" ", "").replace("T", "").replace(":", "")
d87d440598d204d53d5b132cda1f329753bd3a5e
655,783
def deny(user, record): """Deny access.""" return False
c0dba74b4a9bda8f05dbb17c2ef456b5d63026d3
655,784
import os import subprocess def mkVenvLinux(vpath): """ Creates a python virtual environment on linux """ #print(vpath) if os.path.isdir(vpath): print('virtual env exists, activate it instead') return False try: try: with open('logfile', mode='w', encoding=...
22babe10c40076034bb99b96969406c2e0510c81
655,785
import pathlib def is_empty_dir(path: str) -> bool: """Checks if path is emptry directory e.g j.sals.fs.is_empty_dir("/home/rafy/empty_dir") -> True j.sals.fs.is_empty_dir("/home/rafy") -> False Args: path (str): path to check if empty directory Returns: bool: True ...
3c70a841f52e57f20e1db50f41529163e1500f1b
655,786
import ast def datAst(dat): """ Get the ast node of a DAT holding Python code Args: dat: the dat to analyze Returns: ast node of the DAT's text. Will be ast.Module at top """ return ast.parse(dat.text)
6bb4994a4f05c1d813a29e916ebb22236ab808d6
655,787
def get_signature_algorithm(alg_type, alg_hash): """ Returns signature algorithm for ACM PCA Args: isEC: true if Elliptic Curve certificate alg_type: Hash Algorithm from cryptography package to find Raises: ValueError: Algorithm type not supported "...
2c843a6eaf5f67088db774b190a9422f059b79c9
655,788
def frozen (db, user, date, order = '+') : """ Get frozen freeze-records >= date. If some are found, the date is frozen. By default the first record returned is the first after date. But sometimes we want the *last* freeze record. Then we can specify order = '-'. """ f = db.daily_rec...
33d4e23996fff32308b22d30b5031fcefaaed569
655,789
def get_host(url): """ Given a url, return its scheme, host and port (None if it's not there). For example: >>> get_host('http://google.com/mail/') http, google.com, None >>> get_host('google.com:80') http, google.com, 80 """ # This code is actually similar to urlparse.urlsplit, but...
510d7d3a23b8486d084079aa77780f86d10428df
655,790
def compress(s): """ This solution compresses without checking. Known as the RunLength Compression algorithm. """ # Begin Run as empty string r = "" l = len(s) # Check for length 0 if l == 0: return "" # Check for length 1 if l == 1: return s + "1" # Intia...
b1d0b5657003e644f64727ae539cde905bf6bf7d
655,791
import os def rel_path(relative_path): """Get absolute path from relative path.""" return os.path.join(os.getcwd(), relative_path)
8fc4ead47094386f0c5707763c841af4e2421df7
655,792
import time def toJulian2(date): """ Converts date and time to Modified Julian Date. Uses time functions. Note that date has to be in Python time format. :return: Modified Julian Date :rtype: float """ sec = time.mktime(date) days = (sec - time.timezone) / 86400.0 jday = days + 40...
dbfa542e1fa0c09b7fb3b3b392f2acfe64b22ccd
655,793
def _message_no_is_in_list(message_no, main_messages): """Returns True if the main message in Norwegian is in the list of main messages. :param message_no: :param main_messages: :return: """ is_in_list = False for m in main_messages: if message_no == m.main_message_no: ...
c55eafca6b72e6e7a2855f6a164b6898f90e4c84
655,795
def regrid_to_lower_res(mv1, mv2, regrid_tool, regrid_method): """Regrid transient variable toward lower resolution of two variables.""" axes1 = mv1.getAxisList() axes2 = mv2.getAxisList() # use nlat to decide data resolution, higher number means higher data # resolution. For the difference plot, ...
ac9f7800f96b39f28b6ec6d8cf4440273c5dc4c3
655,796
def clean_str(string): """ funcion que toma unstring y lo limpia de tildes y caracteres especiales, devuelve un string en minuscula """ string_new = string.replace("¿","").replace("?","").lstrip().rstrip().replace(",",""). replace("á","a").replace("é","e").replace("í","i").replace("ó","o...
a4393a0e1c2789a9a8d35e6eb9e5fc852a8c2ef0
655,797
import argparse from pathlib import Path import sys import getpass def process_arguments(args: argparse.Namespace) -> argparse.Namespace: """Process command line arguments.""" print("Processing arguments.") # Check that target exists if Path(args.target).is_file() or Path(args.target).is_dir(): ...
231845396a33ab91f6f36e2b11c8b203e4afe936
655,799
import os def create_new_output_path(input_path, output_path): """ Returns a new output_path from input_path :param input_path: path to the files dir :type input_path: str :param output_path: path where to save the file :type output_path: str :return: new output path :rtype: str "...
9d88f2acf02a243754b9186ea24f98cb5a598cc7
655,800
def spin(x, dancers): """ Remove x characters from the end of the string and place them, order unchanged, on the front. Parameters ---------- x : int Number of characters to be moved from end of dancers to the front of dancers. dancers : str A mutable sequence of cha...
a5fb0fa51c034b19a42c768434a7244523321abc
655,801
def run(_word_list): """ Running action stub - causes no change to game state Args: _word_list (list): variable-length list of string arguments Returns: str: output for REPL confirming player ran in place """ response = 'You ran in place. Are you just bored?' return resp...
941eb8180f4c5eb5601573fb71b90f096f4635c6
655,803
from typing import Optional from typing import Union import math def calculate_gain(nonlinearity: str, param: Optional[Union[int, float]] = None): """ Return the recommended gain value for the given nonlinearity function. The values are as follows: ================= =================================...
8c80343f1435b7e3e84b83557cff8aa35443b326
655,804
def replace_for_html(text): """ Replaces characters with the code of their html versions :param text: The original string :return: """ spanish_code = {'á': 'á', 'é': 'é', 'í': 'í', 'ó': 'ó', 'ú': 'ú', 'ñ': 'ñ', '¿': '¿'} re...
0393aca4f3bf4353f92bf5ea964c5cfc60702c7c
655,805
def left_path_clear(Rover, safe_pixs=1500): """ Check if sufficient room on left. Keyword arguments: safe_pixs -- minimum number of pixels on left to deem left path clear """ nav_pixs_left = len(Rover.nav_angles_left) return nav_pixs_left >= safe_pixs
9072290c29b033df5409539171cd1110f48b23c0
655,806
def normalise_tensor(tensor, upper, lower): """ Normalises the tensor by applying computing the following for every element val in the tensor: new_val = (val-minimum_value)/(maximum_value-minimum_value) where minimum_value and maximum_value are the minimum and maximum values in the tensor. :p...
ad5cd3ace7c278bb4a24641039b14e48e263bd40
655,807
def ligand_residue_vs_water_hbonds(hbonds, solvent_resn, ligand): """ Split hbonds into those involving residue and ligand directly and those mediated by water molecules. """ ligand_residue_hbonds, water_hbonds = [], [] for hbond in hbonds: frame_idx, atom1_label, atom2_label, itype = hb...
9fcd571993e90f716f99e45611ddc1bdab694133
655,808
from functools import reduce def apply_reduce(fn): """Return a function that reduces *args with the given fn. """ return lambda *args: reduce(fn, args)
3c4f4e7a6c643816f87fcf8ecf1e157beacdfd1f
655,809
def gen_nested_type_error_msg(instance): """TypeError message for nested ConfigDicts User-map-destined args must be maps containing only maps """ short_name = instance.__class__.__qualname__.replace("Dict", "") msg = ("{} must be JSON objects or Python dicts, not %r.\nSee '/{}/*' " "for ...
d288545938fdd490bb738de7523f5abd28baa9d3
655,811
def lrange(*args): """Convenience helper for list(range(...)). Useful for generating test inputs for functions that expect concrete lists that can be sorted and indxed, not merely iterables. """ return list(range(*args))
8b1ba96a7af8c2d0f9ecda0aea002131e72a017f
655,812
import pickle def _unpickle_run(pickled_func, arg): """Run pickled_func on arg and return. Helper function for multiprocessing. """ return pickle.loads(pickled_func)(arg)
ebdc601d12a551efd85e23389ff35a0d6e6f0886
655,813
def parse_output_file(output_file = "cnbc_urls.txt"): """parse an output files and read the files""" articles = [] try: with open(output_file) as file_in: for line in file_in: clean_line = line.replace("\n", "") articles.append(clean_line) except Exce...
b0f63a5fef2138db515f5024f3dbf0d04e4300b4
655,814
def stations_by_river(stations): """ Given list of stations, return a dict of all the stations on a river """ rivers = {} for station in stations: if station.river in rivers: rivers[station.river].append(station) else: rivers[station.river] = [station] ret...
f25b927559b5e2dd159d0ecb202be06ca6322de8
655,815
def xmlToList(element): """ Convert XML to nested List """ node = [element.tag] text = getattr(element, 'text', None) if text is not None: node.append(text) child_nodes = [] for child in element: child_nodes.append(xmlToList(child)) if child_nodes != []: ...
ff7fe3370c1c06a74f889c49c9171620c952ed6b
655,817
def padding0(data): """ padding '0' into a number. so given a number=1, then it return '01' """ if data is None: return '00' if type(data) == str: int_data = int(data) else: int_data = data if int_data < 10: return '0' + str(int_data) else: ret...
693fb6a3d98c79b443275588cf036f720675cb06
655,818
from typing import Dict import pkg_resources def get_current_environment_requirements() -> Dict[str, str]: """Returns a dict of package requirements for the environment that the current python process is running in.""" return { distribution.key: distribution.version for distribution in pkg...
0856e6ed89a236fe6d08a34f7e69e3490e236606
655,820
def iterations(d): """Bound on number of iterations for divstep. See Theorem 11.2 in BY19. Source: Bernstein & Yang 2019, 'Fast constant-time gcd computation and modular inversion' Link to paper: https://eprint.iacr.org/2019/266 Link to original SAGE code: https://gcd.cr.yp.to/safegcd/11.sage "...
e100c78d10a77953230de61cefb1ea08aa8fdb70
655,821
def net_score(results): """ takes in a results tuple and returns net score after a substraction """ if type(results) != tuple: raise TypeError return int(results[0]) - int(results[1])
10bc8f4c12042c3baeb0865bc3d78bd1b76fcf86
655,822
def take(dataset, num_examples=-1, **unused_kwargs): """Takes the first `num_examples` examples from the dataset. This is done to simulate that the dataset is smaller than it actually is. The result will be cached via `tf.data.Dataset.cache`. This ensures that the same examples get repeated if `dataset` is st...
3eab752c5550f2b5c37dc535f6c8599cb798ba6e
655,823
def new_sharedStrings_text(db): """ Returns xl/sharedStrings.xml text :param pylightxl.Database db: database contains sheetnames, and their data :return str: xl/sharedStrings.xml text """ # location: xl/sharedStrings.xml # inserts: sharedString_len, many_tag_si xml_base = '<?xml versi...
ec0448cd02cf3b8c0f6949e6cf5b26b6d18b567d
655,824
def derived_P_species(df_R, f_TDP): """ Calculate: Total P as the sum of TDP and PP SRP as a function of TDP for both the daily mass flux and the concentrations Inputs: reach results dataframe; value to multiply TDP by to get SRP Returns: dataframe of reach results, with ex...
3c5193c38847421fcffbfbf367aa643ca817aeb6
655,826
def bp_star_rating(tot_group_rate, oa_reviews): """ Function to compute business review per star rating star_rate = tot_group_rate / oa_reviews * 100% """ star_rate = (int(tot_group_rate) / int(oa_reviews)) * 100 m = round(star_rate, 2) return m
d65af2443149e674ffe0c32200d0c4af4e60b2ab
655,827
def get_colours(orig_sentence, words, gender, intensity): """get colours assigned to bias-intensity-levels: shades of red for male, shades of blue for female.""" sen = [] colours = [] if not isinstance(orig_sentence, list): orig_sentence = orig_sentence.split() for i in orig_sentenc...
23dc2ed054b5eeb539f212655b11f5f4b02d1581
655,828
def clean_board(shipDict): """Takes the given dictionary and replaces the 0 values with a single white space. This is to show a clean looking board Args: shipDict (DICT): A dictionary representing the battleship board Returns: DICT: A dictionary where all the 0 values have been replac...
26bbadf27699a1e11617cb1b44f287a13530403d
655,829
def get_dense_hash(sparse_hash): """Get dense hash from sparse hash.""" dense_hash = [] cur_number = None counter = 0 for number in sparse_hash: if counter == 15: cur_number = cur_number ^ number hexed = hex(cur_number)[2:] dense_hash.append(f'{hexed:0>2}'...
ff54928e69c8f078b181041e9e39dadf7f53670d
655,830
import re from typing import OrderedDict def parse_region(regstr): """ Parse the given region string into one of the following 4 cases: 1. annulus 2. pie (cxc) 3. pie + annulus (ftools/xmm) 4. other For the first 3 cases, the return is a dictionary like: { 'shape': 'pie', 'xc': 55...
072a6256f9130013bd94d076af1eed730e4feec5
655,831
def get_state_result(state): """Get result from Prefect state object.""" return state.result()
ed8545c5004eb789a59c65e799576046eef68c52
655,832
def multiFind(string,substring): """Return a list if integers indicating where the substring begins in the string. Substrings are not allowed to overlap themselves: multifind('pppp','pp') = [0,2] If there are no matches, return [] """ start = 0 indices = [] while True: start ...
ba64aa1f915883010b5d3a879686bbaa633adf91
655,834
def can_exit_to_port(descriptor, port): """Derived from compare_unknown_tor_addr_to_addr_policy() in policies.c. That function returns ACCEPT, PROBABLY_ACCEPT, REJECT, and PROBABLY_REJECT. We ignore the PRABABLY status, as is done by Tor in the uses of compare_unknown_tor_addr_to_addr_policy() that we c...
61d2f0a91ff0963f9e93ce3a7cb11216dd36b165
655,835
def permute_all_atoms(labels, coords, permutation): """ labels - atom labels coords - a set of coordinates permuation - a permutation of atoms Returns the permuted labels and coordinates """ new_coords = coords[:] new_labels = labels[:] for i in range(len(permutation)): new_...
ba8aa571afd9039725347a0b5a04885dfafb02b3
655,836
import re def removeConferenceAcronyms(booktitle): """ Removes acronyms from end of proceedings title Example: "Proceedings of the Conference of Examples (COE)" -> "Proceedings of the Conference of Examples" :param booktitle: :return: """ RE_CONFERENCE_BOOKTITLE = re.compile(r"(Proceedings...
656de355c8dd62c6b131064dde42dab85e48c0df
655,837
def GetUpdateResolutionValue(prop): """ Get the proper resolution values based on whether or not it is linked """ islinked = getattr(prop, 'res_link') widthValue = int(getattr(prop, 'res_width')) if islinked: value = (widthValue, widthValue) else: heightValue = int(getattr(prop, 'res...
4a33bbec7dfeeba48580d3d5ad64015938d3cb87
655,838
def github(path): """ :param path: relative (to the root) path of a file in the glottolog data repository :return: URL to a file in Glottolog's data repository on GitHub """ return 'https://github.com/glottolog/glottolog/blob/master/{0}'.format(path)
a87c3003f22796c9e803456d1b93fe5de876d813
655,839
import re def get_vocabs_from_string(string): """ Search in the string to find BODC vocabularies (P01, P06 etc. Returns a dict where: key = vocabulary value = code """ result = re.findall('SDN:[A-Z0-9]*::[A-Z0-9]*', string) vocabs = {} for item in result: spl...
5bc5a2fa472f703291907b4c7322415128ebce9a
655,841
def _get_category_filter_key_set(category_filter_group): """ Returns the set of keys used in the category filter group. In practice there should only be one, but for completeness we allow for the possibility of there being several. In G6/7/8, this was {'serviceTypes'}, in G9 it's {'serviceCategories...
97f9f166a21aaa6dc7f8795a3a600555e1716c73
655,843
def bezier_point(cps, t): """ Cubic Bezier curve interpolation B(t) = (1-t)^3 * P0 + 3t(1-t)^2 * P1 + 3t^2(1-t) * P2 + t^3 * P3 """ p = ((1 - t) ** 3) * cps[0, :] p += 3 * t * ((1 - t) ** 2) * cps[1, :] p += 3 * (t ** 2) * (1 - t) * cps[2, :] p += (t ** 3) * cps[3, :] return p
ca5644539ac0c239ce028f992a07965d92132b8c
655,844
def process_tariff(utilityrate, tariff_dict, net_billing_sell_rate): """ Instantiate the utilityrate5 PySAM model and process the agent's rate json object to conform with PySAM input formatting. Parameters ---------- agent : 'pd.Series' Individual agent object. Returns ------- ...
c75c6ef93aef23b666ce8eb8f2b2f88e28aac66d
655,846
import numpy def snap_to_nearest_config(x, tune_params): """helper func that for each param selects the closest actual value""" params = [] for i, k in enumerate(tune_params.keys()): values = numpy.array(tune_params[k]) idx = numpy.abs(values - x[i]).argmin() params.append(int(valu...
24273d417b6d51e9797ce2dc99de1d8f1da26ba7
655,848
def self(): """self.""" return type(str('Namespace'), (object,), {})()
744b482aad6cb5ce3af60972ca1b04e5305b99ad
655,849
def get_exception_blocks(blocks_dets): """ There can be multiple try-except statements in a snippet so we have to handle each of them. """ exception_blocks = [] for block_dets in blocks_dets: block_exception_types = [] except_handler_els = block_dets.element.xpath( 'd...
d3ae4aafe0ce4976582aaba42e981face1a33ed3
655,850
import subprocess def blame_patch(patch): """ From a patch filename, return a list of "commit summary (author name <author email>)" strings representing the history. """ return subprocess.check_output(("git", "log", "--follow", "--find-renames", "--diff-filter=A...
cfe4e39bcaebdc74d2e4d08e688b002368ab6117
655,851
import re def sanitize(instr, pattern=r'\W', replace=''): """Sanitize characters in string. Default removes all non-alphanumeric characters. """ return re.sub(pattern, replace, instr)
018522e508ec75d31bbedb1f85c496ec94dc0188
655,852
def get_counts(chunked_stamps, compare_realization_id, priority_x = True, x = []): """helper function to get counts from both prediction and real events""" y = [] for e, user_stamps in enumerate(chunked_stamps): c = len(list(user_stamps[compare_realization_id-1])) if priority_x: ...
7e85ca1d76776a4f44df2d711fafe78b429cb9eb
655,853
def check_current_process_pmd_usage(module, pmd_cpus, process_id, range_list): """Check pmd usage in current process cpus range list.""" messages = [] num_list = [] exclude_num_list = [] threads_used = [] try: for val in range_list.split(','): val = val.strip(' ') ...
896a1f9b9c81bd23bf4d145d37e2268649689587
655,855
def geojson_polygon(basic_geometry): """ Returns ------- dict: GeoJSON-style Polygon geometry object. Coordinates are in grid coordinates (Affine.identity()). """ return basic_geometry
dd5b7a2baa3a373c6acc559de6b575b284209b8d
655,856
from typing import Any def tuple_(obj: Any) -> tuple: """Converts any object to tuple. ``string`` to ``(string,)``.""" if isinstance(obj, str): return obj, try: return tuple(obj) except TypeError: return obj,
d644bbc80763565c62641723a4cd0be578fb31b2
655,857
def getCustomOutMsg(errMsg=None, errCode=None, msg=None, exitCode=None): """ Create custom return dictionary """ newOut = {} if errMsg: newOut['error_description'] = errMsg if errCode: newOut['error'] = errCode if msg: newOut['msg'] = msg if exitCode: newOut['exit...
a4b63de28897f1e9ec598dabb72dfca2d9c55e32
655,858
def get_gen_loss(crit_fake_pred): """ Return the loss of a generator given the critic's scores of generator's fake images. :param crit_fake_pred: the critic's scores of the fake images :return: gen_loss: a scalar loss value for current batch of generator """ gen_loss = -1 * crit_fake_pred.mean()...
0a8964ce94f71fc3ff7e9f713c01aa84b53c651f
655,859
def attenuation_length(pressure, rigidity): """ :param pressure: :param rigidity: :return: """ # constants from Desilets & Zreda 2003, Earth & Planetary Science Letters 206 c_0 = 5.4196 * (10 ** (-3)) c_1 = 2.2082 * (10 ** (-4)) c_2 = -5.1952 * (10 ** (-7)) c_3 = 7.2062 * (10 **...
2e3948dac64c86913b20aebfe889090dc95f0096
655,860
def permute(n, seq, permutation): """ This is the code to permute the solution without having to perform the 10000 instruction sequence. """ for i in range(n): seq = seq[permutation] return seq
20606a8493bc4004305d87a0cd6b26ef266dc08e
655,861
def get_fully_qualified_name(func): """ gets the fully qualified name of given function. it returns `module_name.function_name`. for example: `pyrin.api.services.create_route`. :param function func: function to get its fully qualified name. it must be a stand-alone functi...
6f1ea049d67ca665d1db60ba4c6f35894caa74b2
655,862
def get_sns_attributes(item): """ Get Attributes from STAC item for publishing to SNS """ return { 'properties.datetime': { 'DataType': 'String', 'StringValue': item['properties']['datetime'] }, 'bbox.ll_lon': { 'DataType': 'Number', 'Strin...
16800fa970b5b5d8a38ce4f5c9af6070cf20a559
655,864
def get_tokens(sequences, lower=False, upper=False): """Returns a sorted list of all unique characters of a list of sequences. Args: sequences: An iterable of string sequences. lower: Whether to lower-case sequences before computing tokens. upper: Whether to upper-case sequences before computing tokens...
251d53d8aa3662447f88dea8309d0612966679dd
655,865
def get_consumer_groups(acls): """ Given a list of plugins, filter out the `acl` plugin and return a formatted string of all the acl consumer group names which are `allowed` to access the service. """ if acls is None: return return "`" + "`, `".join(i.get("group") for i in acls) ...
cdc49e3caee315a4596ead461de71bc3dd3d01eb
655,866
import re from datetime import datetime import os import six def process_dir(path, operation): """ Create or remove directory """ try: if operation == 'create': dir_path = path + re.sub(r'[^0-9]', '', str(datetime.now())) os.mkdir(dir_path) elif operation == 're...
dd0d2710d45839ea2297a4e1e4796cb8f0e76e5c
655,867
def current_and_new_handle(request, browser, test_server): """fixture return current and newly open window handle""" handle = browser.new_window(url=test_server.url) @request.addfinalizer def _close_window(): if handle in browser.window_handles: browser.close_window(handle) retu...
8b6565b5d4237920e60d0b6e1a67b82d41af9581
655,868
import hashlib def sha256(fp_in, block_size=65536): """Generates SHA256 hash for a file :param fp_in: (str) filepath :param block_size: (int) byte size of block :returns: (str) hash """ sha = hashlib.sha256() with open(fp_in, 'rb') as fp: for block in iter(lambda: fp.read(block_size), b''): sh...
6fcd85de1bc746aba7623e67f6b11dd9cb047582
655,869
import glob def xpand(args): """ Expand command line arguments. Arguments: args: List of arguments. Returns: Expanded argument list. """ xa = [] for a in args: g = glob.glob(a) if g: xa += g else: xa += [a] return xa
45f966aa200e58454b10b75c8834c0e5ec748943
655,870
def delete_srv6_behavior(database, key, grpc_address=None, grpc_port=None, segment=None, action=None, device=None, table=None, nexthop=None, lookup_table=None, interface=None, segments=None, metric=None, fwd_engine=None, ...
0eb7e7250a294877124217e42fc6d0362f2ba7c3
655,871
def format_days(days): """ Converts a list of tuples with a date into a list of tuples with a string representation of the date :param days: List of tuples from database with datetime in second position :return: List of tuples as described above """ formatted = [] for day in days: ...
cd26e67346e97727091db7644080c5f107a4c59b
655,872
import os def list_folders(base_dir): """Lists all folders in current directory Args: base_dir: directory with folders Returns: list of folders in base_dir, empty if None """ files = os.listdir(base_dir) folders = [file for file in files if os.path.isdir(os.path.join(base_di...
148722b8372b7c8b5e0abbee7c06b200295742d3
655,873
def head_tail_middle(src): """Returns a tuple consisting of the head of a enumerable, the middle as a list and the tail of the enumerable. If the enumerable is 1 item, the middle will be empty and the tail will be None. >>> head_tail_middle([1, 2, 3, 4]) 1, [2, 3], 4 """ if len(src) == 0:...
ce141ba969d50e94c1a6fb130bce7de9e7a5ff4f
655,874
def health_check(request): """Retorna se a API está operacional.""" return {"status": "ok"}
8b396b234d4f434c0d31a4727d0f601c8a384cfe
655,875
import json def load_json(file): """Loads a JSON file and returns it as a dict""" with open(file) as f: return json.load(f)
d2e593c2d698223ad28103e4c1d7d91426137f53
655,876
def reduce(df, best, symbols=True): """ Reduce a pandas DataFrame of effect sizes to compare only against to the best among the comparison (algorithm/item) :param df: pandas DataFrame object A pandas DataFrame of effect sizes :param best: str The name of the best sample, for instance, a...
b81b5d4f6e7f37215b8b09656d0f915e22788080
655,877
def B2IQUV_TMS(B, sign_uv=1, sign_q=1): """Convert sky brightness matrix to I, Q, U, V""" B11 = B[0, 0, :, :] B12 = B[0, 1, :, :] B21 = B[1, 0, :, :] B22 = B[1, 1, :, :] stokes = {} stokes['I'] = (B11 + B22) / 2. stokes['Q'] = sign_q * sign_uv * (B11 - B22) / 2. stokes['U'] = sign_u...
47088e1bcb4491fc3e51023412a7f8acae4e9ef1
655,878
import numpy def ex6_clever_fill(height=1000, width=1000): """Fill using 2 outer products""" width_sin = numpy.sin(numpy.arange(width)) height_cos = numpy.cos(numpy.arange(height)) cos_loop = numpy.outer(height_cos, numpy.ones(width)) sin_loop = numpy.outer(numpy.ones(height), width_sin) retur...
1afc52720271e26f7137e310ba38d473a9b8e852
655,879
def filter_tags(rules, tags=[]): """ Filter the rules object for rules that have a certain tag :param rules: YARA rules JSON object :param tags: the selected tags :return: list of filtered rules """ filtered_rules = [] # Process the rules for rule in rules: for tag in tags: ...
f9ec475ebd4db54d9431760397597de8e5c5ee86
655,880
def get_train_valid_test_split_(splits_string, size): """ Get dataset splits from comma or '/' separated string list.""" print(splits_string) splits = [] if splits_string.find(',') != -1: splits = [float(s) for s in splits_string.split(',')] elif splits_string.find('/') != -1: splits...
5ce8cf666e0e9d96983195037f0ab78ce998c055
655,881
import os def cfgDirInit(path: str) -> bool: """ :param path: :return: """ isExists = os.path.exists(path) if not isExists: os.makedirs(path) print('\n' + path, '创建成功') return True else: print('\n' + path, '目录已存在') return False
516bbf4b82761d5f274ef1182dfa54f0a239d756
655,882
import codecs import yaml def parse_yaml_or_json(path): """ Return parsed YAML or JSON for a path to a file. """ with codecs.open(path, mode='r', encoding='utf-8') as infile: doc = yaml.safe_load(infile) return doc
6902c3fcc67e636c35fc9576106943e8bd8d2541
655,883
import os def high_mesh_options(filename, **kwargs): """ Generates an options dictionary for a high mesh """ kwargs["path"] = os.path.abspath(filename) """ List of possible high mesh options in the form: (keyword_argument, xml_name, default_value) """ high_opts = [ (...
e4e0ff3dac0c274a3aeb7629d961bb48f90b2db0
655,884
import os def get_csv_list(): """renvoie la liste des fichiers csv dans ./data/data""" file_list = [file[2] for file in os.walk('./data/data')] #liste contenant une liste des fichiers dans ./data/data csv_list = [file for file in file_list[0] if file[-4:]=='.csv'] #on ne garde que les csv return csv_...
8bfb3d85f36b6363f222c81a3f7ab02c15105dfd
655,885
def less_than(values, target_loc, puzzle_input): """if the first parameter is less than the second parameter, it stores 1 in the target location. Otherwise it stores 0. """ if values[0] < values[1]: puzzle_input[0, target_loc] = 1 else: puzzle_input[0, target_loc] = 0 return puzz...
32d118da27ecfbb18f127027d7c816b9697b6d60
655,886
import json def binance_connected_pairs(): """ Loads the pairs from Binance that have 3 or more connections :return: 'connected' pairs, e.g {USDT:[BTC,ETH], ETH:[ADA, OMG]} :rtype: {str : str list} dict """ with open("pairs_list.json", "r") as f: pairs = json.load(f) binance_pairs...
b3696263fd59873c4c01fe324dce6cefebc8f366
655,887
import subprocess def calculate_sacrebleu(predict_path, target_path): """ Calculate the BLEU scores. Args: predict_path (string): Path to the predict file. target_path (string): Path to the target file. Returns: Float32, bleu scores. """ sacrebleu_params = '--score-o...
243f9b6b08173bec4e6a31bd3cdb17bb6eecdd18
655,888
import os def file_filtered_in(filename, filters): """Checks the filename against a list of filters Keyword arguments: filename(str): the filename to check filters(list): list of string parts to check the filename against Return: True is returned if a filter matches part of the fil...
96181cd72cf2c888bceb083c886cfc98e5b1ac98
655,889
def abs_value_stats(simulated_DE_stats_all): """ This function takes the absolute value of columns=[`logFC`, `t`, `NES`, `ES`]. For ranking genes or pathways, we only care about the magnitude of the change for the logFC, t, NES statistic, but not the direction. The ranking for each gene will be bas...
345c42dcbceed68b5432f9471b6291985c93a0a4
655,890
def get_filename(): """从用户输入中获取文件名""" filename = input("请输入文件名或文件路径(例如:111.txt or ~/111.txt):\n") return filename
70e9fc35b48286c51f90310497b253686ed90063
655,891