content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def preprocess(func, *args, **kwargs): """ Applies function ``func`` with given parameters before making a prediction. Examples -------- >>> from dpipe.im.shape_ops import pad >>> from dpipe.predict.functional import preprocess >>> >>> @preprocess(pad, padding=[10, 10, 1...
7b27e2aaa924a103d8c0440421d1e1005183f097
646,874
def hasHandlers(self): """ See if this logger has any handlers configured. Loop through all handlers for this logger and its parents in the logger hierarchy. Return True if a handler was found, else False. Stop searching up the hierarchy whenever a logger with the "propagate" attribute set to ze...
3a2586bd34513be12c6170edab127315c8be0d08
646,875
def detra_hidalgo(U, rho, R_n): ### COMPLETE """ R. W. Detra and H. Hidalgo, “Generalized heat transfer formulas and graphs for nose cone re-entry into the atmosphere,” ARS Journal, vol. 31, pp. 318–321, 1961. """ # q = 5.16E-5 * np.sqrt((rho / R_n) * (U**3.15)) # q *= 1E6 q = 9.81775E6 * ((((0.6096 * rho) / (2 ...
0f4133b9a5a816d0dd3d89fe0b199631fec81433
646,876
def cmp_column_indices(x,y): """Comparision function for column indices x and y are XLS-style column indices e.g. 'A', 'B', 'AA' etc. Returns -1 if x is a column index less than y, 1 if it is greater than y, and 0 if it's equal. """ # Do string comparision on reverse of column indices ret...
7ce7305eadd32a0b756dd6bdf2cabd20bfe0b2ff
646,877
def color_rgb(red, green, blue): """ Given three intensities red, green, blue, all from 0 to 255, returns the corresponding CSS color string e.g. '#ff00cc' """ return f"#{red*256**2 + green*256 + blue:06x}"
be02aea5a0fc04f7bbedce4b3fc18fb5cdfff862
646,878
import builtins def _parse_warning(warn_str): """Reverse-engineer a warning string Parameters ---------- warn_str : string Returns ------- (str, Warning, str, int) message, category, filename, lineno """ tokens = warn_str.rstrip('\n').split(" ") # The first token is ...
803826059f3bd2cfdd84d2ec7bdf0ef9c97b5eaa
646,879
import functools def expected_failure(exptn, msg=None): """ Wrapper for a test function, which expects a certain Exception. Example:: @expected_failure(ValueError, "point must be an instance of lib.Point") def test_result_error(self): Result([1., 1.], 1.1) @param Excepti...
8270662bc767ba37895ff31d06e0da0b9d59dee4
646,880
def name_for_group(group_name, cl, res): """ Allow a customised ModelAdmin to specify a new field `list_group_by` that can be a method on the model admin or the model itself that defines group ordering. """ if hasattr(cl.model_admin, 'list_group_by'): if callable(group_name): ...
2efdccec9b3591fda42efd851151f977edec54a9
646,882
def elements_to_str(l): """ Convert each element in an iterator to a string representation Args: l (:obj:`list`): an iterator Returns: :obj:`list`: a list containing each element of the iterator converted to a string """ return [str(e) for e in l]
fe38143e0c9f839750a3118e4bc397e6a6fba360
646,883
def fence_native_format(source, language, css_class, options, md): """Format source as div.""" return '<div class="%s">%s</div>' % (css_class, source)
b0ebf41d59b63952d6e2cccb3c89aa64cdfc420c
646,884
def replace_empty(x): """ replace the empty value with unknown """ if x.strip() == '': return 'Unknown' else: return x
6f907bb81e2db5cea609902e577052c303b96874
646,885
def mechanismHub_fee_revenue(params, substep, state_history, prev_state, policy_input): """ This mechanismHub returns the updated fee taken from the trade. This is a practical implementation of fee hypothesis 1 """ # Use the asset as key & the fee revenue gained from it as value asset = policy_inpu...
2ebd54161f2d35f0468e7c21dbfe9024ec3c506c
646,887
import os def get_db_conf(): """ Configures database according to the DATABASE_ENGINE environment variable. Defaults to SQlite. This method is used to let tests run against different database backends. """ database_engine = os.environ.get("DATABASE_ENGINE", "sqlite") if database_engine == ...
0e37bc6db49f6c8fcaa3a39dbda00377be657d42
646,888
import os import re def all_state_dicts(model_str, exp_dir): """Returns a dict of (epoch, filename) for all state_dicts in `exp_dir`. Args: model_str: Model whose state_dicts to consider. exp_dir: path to directory where all experimental data will be stored. """ state_dicts = {} ...
d6a69dbeb4624d576636837d394ee1f611478809
646,889
def add_inplace(X, varX, Y, varY): """In-place addition with error propagation""" # Z = X + Y # varZ = varX + varY X += Y varX += varY return X, varX
37648a0a42cc6578320f20ee771d885172170ee9
646,890
import sys def parseArgs(): """Parse the system arguments into a list. Finds all the arguments in the form key=value and assign them to a list. returns list """ args = sys.argv arguments = {} for arg in args: if arg.find('=') != -1: elem = arg.split('=') arguments[elem[0]] = elem[1] return arguments
1b86176a2903f49f1a374cbd191f7a61452c5d30
646,891
from typing import get_origin from typing import Union from typing import get_args def is_type_SpecificOptional(f_type) -> bool: """ Returns true for types such as Optional[T], but not Optional, or T. """ return get_origin(f_type) is not None and f_type.__origin__ == Union and get_args(f_type)[1]() is...
e4259a94ac0c6a7e2913271a2711ec30b659f11d
646,893
from unittest.mock import patch def _patch_media_setup(): """Patch media_player.async_setup_entry.""" async def _async_return(): return True return patch( "homeassistant.components.songpal.media_player.async_setup_entry", side_effect=_async_return, )
0be6647f867ea009cf441ee851736d6a027e1ba3
646,894
def get_amount(amount): """encode amount (float number) to the cryptonote format. Hope its correct. Based on C++ code: https://github.com/byterubpay/bitbyterub/blob/master/src/cryptonote_core/cryptonote_format_utils.cpp#L211 """ CRYPTONOTE_DISPLAY_DECIMAL_POINT = 12 str_amount = str(amount) ...
156746b0ececefa37dbc5f3cb25f2e8ef68fbbf3
646,895
import time import subprocess def time_command(cmd): """Execute the command on this host and display its duration. Args: cmd (str): command to time Returns: int: return code of the command """ print("Running {}".format(cmd)) start_time = int(time.time()) return_code = su...
2b950c96bc8139377a3414dca664cc5bb7b01372
646,896
from functools import reduce def composer(*functions): """ Composer function, Art of Wizard in_de_dob = compose( inc, pot, dec, double ) this build function composer imperative module Order: ^ / \\ the read is double, dec pot and inc | "...
27d153bc8ebe642184954af9f1ac7589d3356453
646,898
def getting_input(): """ Gets input from user and implements it into an 2 dim array """ print('Enter a table:') return [list(map(int, list(input()))) for _ in range(9)]
62a8d9bec2c9066c46d44899eb7ac4997146b1bc
646,899
import requests def get_filterjs(url): """ Get filter.js file :param url: base url for timetabling system :return: filter.js text """ url = url + 'js/filter.js' source = requests.get(url).text return source
1a1d330c4e2ddf16fc30710096d51e7207fe2e25
646,900
def parseBands(band, allBands, error): """Parses a string that specifies bands. Bands are horizontal rectangles defined with respect to lines. They correspond with regions of interest where we try to find specific marks, such as commas and accents. Parameters ---------- band: string or Non...
f502ddc4107d2440e914166866168c700fd5a6e2
646,901
def check_if_person_exist(tx, ID): """ Method that queries the database for understand if a person node exist :param tx: is the transaction :param ID: is the ID of the person :return TRUE OR FALSE """ query = ( "MATCH (p:Person) " "WHERE id(p) = $ID " "RETURN p" ...
dffee73862b0d1fa5b399bcfbbf2a3632fde20b6
646,902
def GeojsonCheck(filename): """ Checks if filename is of type geojson :param str filename: filename to check :returns: bool - True if filename ends with geojson; otherwise False """ if filename.endswith('.geojson'): return True else: return False
28738d580c849fcfab1572dea70d8928817042ba
646,904
def volume_bars(df, volume_column, threshold): """ Computes volume bars (index) :param df: pd.DataFrame() :param volume_column: (str) name for the column with volume data :param m: (int) threshold for volume :return idx: returns list of indices """ t = df[volume_column] ts = 0 ...
dfac4717cb6bec3776b4b5617e4db40393d067bd
646,905
from typing import Callable def get_lr_schedule( epoch_global: int, lr_initial: float, lr_decay: float ) -> Callable[[int], float]: """Return a schedule which decays the learning rate after each epoch.""" def lr_schedule(epoch: int) -> float: """Learning rate schedule.""" epoch += epoch_g...
c6dc73bc0f365b9847d4b7706b84b5490a2ee00a
646,906
def multiply_by_u(x, u=(9, 4), d=5): """ Multiply x with u, interpreting as numbers from the field sqrt(d). Where u is a fundamental solution. Args: x: <tuple> (a,b) to be interpreted as (a+b*sqrt(d)) u: <tuple> (u1,u2) to be interpreted as (u1+u2*sqrt(d)) d: <int> Returns: (x,y...
21ffab64599033ce3942ad67e681e97e98f2255e
646,907
def zeroth_order(t: float, q: list, k: float) -> float: """Simple zeroth-order rate function. :param t: model time :param q: Vector (list) of mass distribution through compartments (not actually used but required argument for ODE solver) :param k: Time constant of the rate function. :returns:...
71a46a200beeae60f6fa73372b08539672b24d3b
646,908
def construct_conn_msg(stream, lines=None, protocol_opts=None): """Return a connnection message :param stream: stream name :param lines: number of messages to consume :param protocol_opts: optional arguments """ connection_msg = stream if lines: connection_msg += ' {0}'.format(lines...
823411a327e8c6fe0e6cd99d0479b2b4ba8d15cb
646,909
def format_result(interval, lower_result, upper_result): """ :param interval: sequence of numbers :param lower_result: <class 'scipy.optimize.optimize.OptimizeResult'> :param upper_result: <class 'scipy.optimize.optimize.OptimizeResult'> :return: unpacked value as follows, interval, success,...
84c32d6db3f16c10da79ac6025fd1c6778508c03
646,910
def MultipleReplace(Text, ReplaceDict): """ Perform multiple replacements in one go using the replace dictionary in format: { 'search' : 'replace' } """ NewText = Text for Search, Replace in ReplaceDict.items(): NewText = NewText.replace(Search, str(Replace)) return NewText
1c1ff4a1395ca6553855025d369140ec088f18ae
646,911
def bf(main, pattern): """ 字符串匹配,bf暴搜 :param main: 主串 :param pattern: 模式串 :return: """ n = len(main) m = len(pattern) if n <= m: return 0 if pattern == main else -1 for i in range(n-m+1): for j in range(m): if main[i+j] == pattern[j]: ...
f7b9d31565b36134f6ab6aba3f927f1a36188707
646,912
import logging def check_proc_type(image_proc_type): """ check_proc_type function checks to make sure image_proc_type is a string :param image_proc_type: user selected processing technique :raises ValueError: if image_proc_type is not a string :returns True: if pass test """ if isins...
77ec8e9ac1aacef3cdeb0473406081d44ca43590
646,913
def gcd(n1, n2): """ Recursive function to return the GCD of n1 and n2 """ if n1 == 0: return n2 return gcd(n2 % n1, n1)
7e63371859191bd5179dd2a275f870ad97e10208
646,914
from typing import List def min_swaps(arr: List[int]): """Return the minimum number of swaps needed to sort a list in ascending order. arr(List[int]): a list of positive integers. No duplicates. Once sorted, all the elements are consecutive. Return: int: the lowest number of swap...
03623fe0b9f2e86b7eca442aa108a2a1081d936a
646,915
def is_vegetarian(recipe): """ Takes a recipe and determines if it is vegetarian """ r = recipe.read() if not (("chicken" in r) or ("beef" in r) or("pork" in r)): return True else: return False
d2cfb977202515e5fff8ceda7d740e716b3a4967
646,916
def fake_get_action_handlers(actions): """Mocked out decorator store """ def get_action_handler(key): return actions.get(key) return get_action_handler
1b91a5047a160f324e5c82d48772cac61e641f09
646,918
import random def create_AFS(Unlink_Matrix, Pops, individuals, pop1, pop2, pop1_thr, pop2_thr, AFS): """Count the minor allele in each population and populate the observed AFS.""" for snp in Unlink_Matrix: Allowed = ['A', 'C', 'G', 'T'] alleles = set([x for x in snp[...
f73f70ad63ac2d4085554df0f6862c12f63ea0e0
646,919
def rotateVFun(input_v): """! V fun provides V given u """ def rotatedFn(self, *args, **kwargs): if args[2] == 0: # 0 deg rotation (no action) return input_v(self, *args, **kwargs) if args[2] == 1: # 90 deg rotation (no action) return input...
e227639d7989e391ce1bfd4f6f7ad4388f4c255b
646,920
def wrap_with_links(obj, links, val, root_path, many=False): """Adds links key to object (first argument) based on links dictionary and value""" if many: for item in obj: item['links'] = {} for key in links: item['links'][key] = root_path + links[key].format(item[...
ea42bff363fe131a423501b8442449f03c3eccb7
646,921
import click def scores_argument(min_arg=1, force_eval=False, **kwargs): """Get the argument for scores, and add `dev-scores` and `eval-scores` in the context when `--eval` flag is on (default) Parameters ---------- min_arg : int the minimum number of file needed to evaluate a system. For...
32c69da7e4f0f71a0b8f699100ac7ee6a21467f9
646,923
def GetNegativeResult(line): """Extract the name of the negative result from line.""" line = line[len("@remove "):] return line.strip()
fc9c1ddbd6c84bd535f1651c74825a2fa4adb380
646,924
import os def path_similarity_notebooks(): """ Returns the path of the similarity notebooks folder. """ return os.path.abspath( os.path.join( os.path.dirname(__file__), os.path.pardir, "scenarios", "similarity", ) )
f61e4d86f7dd63ebd9d9e6ef9e4fde8be1b4f2f9
646,926
def std_trans_map_dtmc(sourceidx, destidx, p): """Standard graphziv attributes used for transitions in dtmc. Computes the attributes for a given source, destination, action and probability. :param stateidx: The index of the source-state. :type stateidx: int :param destidx: The index of the destinati...
9fc9ff5c647ef8efb21c400ebc87545de70bf125
646,927
import logging def bases_to_complete_previous_codon(phase): # pylint: disable=invalid-name """ Return the bases at exon start that completes the previous codon. >>> bases_to_complete_previous_codon(0) # e.g. -----XXX 0 >>> bases_to_complete_previous_codon(2) # e.g. XX-----X 1 >>> bases_t...
a5b77dc0468ae9144f6f4250c7d3cc49bfce68a6
646,928
import random import string def generate_key(num_chars=32): """ Generate a unique key. :param num_chars: Number of characters. :return: Key of num_chars length """ return ''.join(random.choice(string.ascii_letters + string.digits) for i in range(num_chars))
688deb94ddfef5d2a5e5e8f44171bca43c1429ed
646,929
def is_palindrome(s): """check if a string is a palindrome""" return s == s[::-1]
0e5e89f54374c16800da6785e81260c63b9e5317
646,930
def best_case_name(obj): """Take an object and return the highest quality case name possible. In general, this means returning the fields in an order like: - case_name - case_name_full - case_name_short Assumes that the object passed in has all of those attributes. """ if ...
a2c792a2fab02d9783cf56ca97b1c3848698f5de
646,931
def merge_dict(d1, d2): """Merge two dictionaries The second dictionary `d2` overwrites values in `d1` if they have common keys. This is equivilent to return {**d1, **2} in python3. Using this function improves python2--3 compatibility. """ out = d1.copy() out.update(d2) ...
f6833203264315da8a7efac3e1b21133cc6f6738
646,932
import textwrap def get_docstring(target) -> str: """ Retrieves the documentation string from the target object and returns it after removing insignificant whitespace :param target: The object for which the doc string should be retrieved :return: The cleaned documentation string f...
3c52831c612513ae39d4173194a3b98ba2fbb4f8
646,933
import typing def filter_line( line: str, filters: typing.Optional[typing.Iterable[str]] ) -> typing.Optional[str]: """ Filters out line that contain substring Args: line: line to filter filters: filter strings to apply Returns: line if not filter are found in line, e...
859477b209ad8e5cfd444fb0e172068f94df1596
646,934
def parse_item(item): """ Parse a CVE item from the NVD database """ parsed_items = {} cve = item.get('cve', {}) CVE_data_meta = cve.get('CVE_data_meta', {}) ID = CVE_data_meta.get('ID', '') parsed_items['id'] = ID affects = cve.get('affects', {}) vendor = affects.get('vendor'...
26d03e5054ceb33d071273d6894cfba0bed58ec5
646,935
import os def get_snapshot_dir(): """ Returns absolute path to snapshots directory, creates this directory if it does not exist. Used solely for tmp data saving """ path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) snapshots_dir = os.path.join(path, 'snapshots') if not...
c465688f46ae3686b53f1416f0c1c63d3248aec1
646,937
from typing import Dict def convert_to_instruction_dict(installation_str: str) -> Dict[str, str]: """Convert given string to dict. Args: installation_str (str): The string to be converted. Returns: Dict[str, str]: Expected dict """ return {"cmd": installation_str}
d5c384b9203208b1a9294a7c000602314cf08a02
646,938
def rstrip_zeros(wordIDs): """ removes trailing padding symbols """ wordIDs = list(wordIDs) if 0 in wordIDs: wordIDs = wordIDs[:wordIDs.index(0)] return wordIDs
bb0df30f5a61495bcb6819ef50e27c01239c4c7d
646,939
def fix_aspect_providers(lib_providers): """Change a list of providers to be returnable from an aspect. Args: lib_providers: A list of providers, e.g., as returned from forward_deps(). Returns: A list of providers which is valid to return from an aspect. """ # The DefaultInfo provider...
2a0cfc5465cb89be3f8375997b7a5bcef61c9b82
646,940
def positions(): """ Used for the visualization of Orientation objects with `Orientations.show` """ return [[0, 0.5, 0], [0, -0.5, 0], [1, 1, 1]]
fc09b3aae09f35ce94b626746f5578e468624a3f
646,941
import torch def angle_loss(orient, gt_orient): """Only for evaluation""" angles = torch.atan2(orient[:, 0], orient[:, 1]) gt_angles = torch.atan2(gt_orient[:, 0], gt_orient[:, 1]) # assert all(angles < math.pi) & all(angles > - math.pi) # assert all(gt_angles < math.pi) & all(gt_angles > - math.p...
fcb339f3a2a665ab3c9c52d7035b895f3fe46eba
646,943
def pairs_to_dict(items: list) -> dict: """Example: ['MESSAGES', '3', 'UIDNEXT', '4'] -> {'MESSAGES': '3', 'UIDNEXT': '4'}""" if len(items) % 2 != 0: raise ValueError('An even-length array is expected') return dict((items[i * 2], items[i * 2 + 1]) for i in range(len(items) // 2))
591449759e8794693403abdd3f2207abcef4f0c0
646,944
def int2baseTwo(x): """x is a positive integer. Convert it to base two as a list of integers in reverse order as a list.""" # repeating x >>= 1 and x & 1 will do the trick assert x >= 0 bitInverse = [] while x != 0: bitInverse.append(x & 1) x >>= 1 return bitInverse
ce67059751918933003f3c0ebe6b9f3c81de0145
646,945
def get_filter_links_fake(links, metadata=True, **metrics): """Get test links with optional metadata.""" # pylint: disable=unused-argument filtered_links = ["a", "b", "c"] filtered_links_without_metadata = filtered_links[0:2] if not metadata: return filtered_links_without_metadata return...
05eda0441aefef8b6e444693369f0e2f3c3af721
646,946
def fig(fig, include_plotlyjs='cdn', full_html:bool=False)->str: """Returns html for a plotly figure. By default the plotly javascript is not included but imported from the plotly cdn, and the full html wrapper is not included. Args: include_plotlyjs (bool, str): how to import the necessary javascr...
3447c3b460220afa0bc58285d4b1765f2831e080
646,947
def _triangles(dg): """ Return a list of all oriented triangles in the digraph ``dg``. EXAMPLES:: sage: from sage.combinat.cluster_algebra_quiver.mutation_type import _triangles sage: Q = ClusterQuiver(['A',3]) sage: _triangles(Q.digraph()) [] sage: Q.mutate([0,1]) ...
eb9260b4079d60747ab701aae624a03d70612c5c
646,948
import os def get_chunk_files(chunk_id, result_location): """Get a chunk results file according to a given chunk id and a result location Args: chunk_id (str): Chunk id result_location (str): Path to chunk results files """ chunk_files = [] for chunk_file in os.listdir(result_loca...
03831290315b7aeee2cf42d8936084d7b8617e3b
646,949
from datetime import datetime def wrf_times_to_datetime(wrfdata,timename='Times',format='%Y-%m-%d_%H:%M:%S'): """Convert WRF times to datetime format""" timestrs = wrfdata.variables['Times'][:] if hasattr(timestrs[0],'values'): # xarray return [ datetime.strptime(s.values.tostring().decode...
f3ffe736d2847582ef0fc684a50f20ec352ff799
646,950
import sys def get_integer_arg(arglist, arg_string): """tries to get the value of an integer arg from the cmdline args""" val = None try: arg_ind = arglist.index(arg_string) except: arg_ind = -1 if arg_ind != -1: try: val = int(sys.argv[arg_ind+1]) except: pass return val
33d6dfcfacb362938c342eb27df1782a4b9df505
646,951
def footprintBridge(ra, dec): """ Special selection for pointings near the SMC Northern Overdensity (SMCNOD) """ cut = (ra > 30.) & (ra < 60.) & (dec < -65.) return cut
b1fdd6b70b29f9c1131893a0a00269dc3656f317
646,952
import sqlite3 def count_final_records(db_conn: sqlite3.Connection) -> int: """Adds views to the database Arguments: db_conn: the database to query Return: Returns the final number of records in the combined view """ count_cursor = db_conn.cursor() count_sql = '''SELECT count(...
73806a330dcbaa8329580aa8ffc4944dca0050f2
646,953
from typing import Dict import copy def merge_dicts(dict1: Dict, dict2: Dict) -> Dict: """ Merges dictionaries including nested values. Args: dict1 dict2 Returns: merged_dict """ merged_dict = copy.deepcopy(dict1) for key, value in dict2.items(): if key no...
6324bee5648262df370134917bcd52967cbe15ac
646,954
def _string_format(str, format): """ Lazy variant of string formatting, needed for situations where string formatting may be evaluated before it is calculated """ return str % format
014a24acf5b1b03bcb82a77e2fc6987d888946e4
646,955
import os def get_files_with_name(startswith, endswith, DATA_PATH): """ Find all files with the specified start and end in the data path. """ files = [] for file in os.listdir(DATA_PATH): if file.startswith(startswith) and file.endswith(endswith): files.append(file) print('Found %d...
9e9239f5ed71f0db402f3929e3af7bf4f159f21e
646,956
def validate(msg, rule_stack, rules): """ Consider these rules 0: 2 1 3 1: 2 3 | 3 2 2: "a" 3: "b" And data: abab The only valid matches would be aabb and abab. Logic is: 2 -> a, leaving a, 1, 3. The a (of 'abab') validates, leaving 1, 3. Remove the a. 1 -> 2...
e263d95d5697ff597f1fa7c173e024b6c2c261a3
646,957
import os def _get_hub_root(): """ Get the absolute path of hub package. Returns: str, return a string of path. """ return os.path.abspath(os.path.dirname(__file__))
8ffd779e1caa7fba8e90714d787efc27ef8cc1af
646,958
def get_higher_closing_price(df): """returns the exchange with the higher closing price""" # exchange 1 has higher closing price if (df['close_exchange_1'] - df['close_exchange_2']) > 0: return 1 # exchange 2 has higher closing price elif (df['close_exchange_1'] - df['close_exchange_2']) <...
8002c1124ab2257032f259c72e7a37f6e075562e
646,959
import torch def normalize(clip, mean, std): """ Normalise clip by subtracting mean and dividing by standard deviation Parameters ---------- clip : torch.tensor video clip mean : tuple Tuple of mean values for each channel std : tuple Tuple of standard deviation va...
6949d643c870f39899bd4b876a0ee8301507806d
646,960
import re def fix_varptr_calls(vba_code): """ Change calls like VarPtr(foo(0)) to VarPtr(foo) so we can report on the whole byte array. """ # Do we have any VarPtr() calls? if ("VarPtr(" not in vba_code): return vba_code vba_code = re.sub(r"(VarPtr\(\w+)\(0\)\)", r'\1)', vba_code)...
0461395fba611c054dc5b0c44b19879f0b3e6aef
646,961
def fibonacci_search(arr, val): """ >>> fibonacci_search([1,6,7,0,0,0], 6) 1 >>> fibonacci_search([1,-1, 5, 2, 9], 10) -1 >>> fibonacci_search([], 9) 0 """ fib_N_2 = 0 fib_N_1 = 1 fibNext = fib_N_1 + fib_N_2 length = len(arr) if length == 0: return 0 while...
54e48a5af73f94e5c824d4d20c2b29e77e4d8f08
646,962
def addon_count_neg(addon_counts): """Add-on counts with a negative count, as could occur from adding noise.""" replace_row = (addon_counts["locale"] == "de") & (addon_counts["addon"] == "guid-1") addon_counts.loc[replace_row, "count"] = -1 return addon_counts
31044059795f142ac3615e04ab0a49fc8f51872c
646,963
import hashlib def checksum(file, method='sha1', chunk_size=4096): """Calculate the checksum of a file. """ h = hashlib.new(method) with open(file, 'rb') as f: for chunk in iter(lambda: f.read(chunk_size), b""): h.update(chunk) return h.hexdigest()
5acca91e4cf45f4684f5e8bf07a95eb1a4c7e201
646,964
def _exist_key(key, **kwargs): """ check whether key is exsit in the kwargs and kwargs[key] is not None. """ is_exist = key in kwargs is_not_none = kwargs[key] is not None if is_exist else None return is_exist and is_not_none
0fadd75a5bc735a0a0ed7e387ddd4d9842db8c37
646,965
import re def find_all_substrings(string, sub): """ http://code.activestate.com/recipes/499314-find-all-indices-of-a-substring-in-a-given-string/ """ starts = [match.start() for match in re.finditer(re.escape(sub), string)] return starts
9907df27390f698543766f4f2195aa2eaaf5e452
646,966
def duration_to_string(duration): """Format a duration in seconds as a string. Args: duration (float): The duration in seconds. Return: A more human-readable version of the string (for example, "3.5 hours" or "93 milliseconds"). """ if duration > 3600 * 24: duration_str = "{0:0.1f} days".f...
ce643d44b0436083f0b039ce3f0b7f4085c7f043
646,967
def cli(ctx, quota_id, deleted=False): """Display information on a quota Output: A description of quota. For example:: {'bytes': 107374182400, 'default': [], 'description': 'just testing', 'display_amount': '100.0 GB', 'groups': [], ...
1ba978b422817b36b6124235cd49ff665e299069
646,968
def rank_results(results): """Ranks the results of the hyperparam search, prints the ranks and returns them. Args: results (list): list of model configs and their scores. Returns: list: the results list reordered by performance. """ ranking = sorted(results, key=lambda k: k["score"...
a3878446280e1d006c409c9391a8d9962e447651
646,969
def __scrape_h2o_sys_info__(object): """ Scrapes the following information from the jvm_output_file: user_name, build_version, build_branch, build_sha, build_date, cpus_per_host, heap_bytes_per_node """ test_run_dict = {} test_run_dict['product_name'] = "h2o" test_run_dict['compo...
919d59960800daff5c30cda3b0a3e3edf7a46126
646,970
def compare(golden_file, actual_file, result_file): """ Compare the contents of two files. Parameters ---------- golden_file : String Filename of the file containing the golden results actual_file : String Filename of the file containing the results t...
d8e58a66b1ec194add5eabe2df31a72bb0777722
646,973
def shouldItBeMute(count): """ odd number of times toggle means its not muted as initially it was muted """ return True if not count % 2 else False
b423269abc06f01b20c0f83bd10be45530e71691
646,974
def __contains_special_char(password): """ Checks of the password contains a special character, such as "&" or "@". Returns true if the password contains a special character, otherwise returns False. :param password: a string for the user's password :return: True if valid, else False """ # ...
ebcd3a70900811b87e1be917ba3b512e35ed797b
646,976
def indent(unindented, n_spaces=2): """ Indent a multi-line string using spaces. """ indent = " " * n_spaces newline = "\n" + indent return indent + newline.join(unindented.split("\n"))
4f501b77ab55a3af12b19330a2a7e8af548baec3
646,977
def getAverageRGBOld(image): """ Given PIL Image, return average value of color as (r, g, b) """ # no. of pixels in image npixels = image.size[0] * image.size[1] # get colors as [(cnt1, (r1, g1, b1)), ...] cols = image.getcolors(npixels) # get [(c1*r1, c1*g1, c1*g2),...] sumRGB = [(x...
eb28dd84af9531a39ea12c11d1300d097a45a5a4
646,978
def split(a, n): # the function divmod takes two argument (a1, a2) and returns two results(r1, r2) # r1 = a1/a2, r2 = a1 mod a2 """ divmod(8, 3) = (2, 2) divmod(7.5, 2.5) = (3.0, 0.0) """ k, m = divmod(len(a), n) return list((a[i*k+min(i, m):(i+1)*k+min(i+1, m)] for i in range(n)))
e1d1dd14fe1568521b8cbf594973f3e9106d0b7c
646,979
from typing import Dict from typing import Any import json def forbidden_dependencies() -> Dict[str, Any]: """ - 'root_package.package_1' module inside 'layer_1' depends on the 'root_package.package_2' module inside 'layer_2'. i.e. layer_1 depends on layer_2 - 'root_package.package_2' module inside 'l...
c6bb2e5d17cbded9de4e250c6708b24ead92bf10
646,980
def total(): """Returns the total number of grains on the chessboard.""" return 2**64 - 1
8bafa0c3142bf5b3b3959157033de5eeb62b34e8
646,981
def match(cmd, s): """ Check if cmd has the required parts of s and any of the optional part. """ parts = s.split('-') start = parts[0] if len(parts) > 1: end = parts[1] else: end = "" return cmd.startswith(start) and (start+end).startswith(cmd)
9a92f31a0f463a4a0215fdc82e0ce29a804ebffc
646,982
def score_calibrate(input_df, proba_name, min_score=300, max_score=850): """Score calibration. Parameters ---------- input_df : DataFrame There are two columns of DataFrame, one is prediction probability, the other is label value. proba_name : str Prediction probability nam...
2393e794adf1ee8342e35035aea6f27ac713229c
646,983
def has_failed(node): """ Check whether status is "failed". To avoid false positives check whether status is one of "pass" or "none". :param node: XML node holding status as text. :returns: Whether the status is reported as "failed". """ return (node.text.strip() not in ['pass', 'none'])
ff72db0d6ce2e8dd11cd2167ee23fd49fb4679ec
646,984
def _has_active_network_in_vlan(vlan): """ Check if there are any other active network in the vlan this is used because some equipments remove all the L3 config when applying some commands, so they can only be applyed at the first time or to remove interface vlan configuration :param vlan: vlan...
d271796451aeef5953b4b60d11f9513d1b18f659
646,985
import importlib def create_instance(module_name, class_name, parameters): """ Factory method: create instance of dynamically loaded module Stolen from Dmitry """ my_module = importlib.import_module(module_name) clazz = getattr(my_module, class_name) instance = clazz(parameters) retur...
c3e150a789b29786d837e699c1603d102be98f6e
646,987