content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def experiment_pivot_table(experiment_snapshots_df, per_benchmark_ranking_function): """Creates a pivot table according to a given per benchmark ranking, where the columns are the fuzzers, the rows are the benchmarks, and the values are the scores according to the per benchmark ra...
10d2929b767261bd99c4bfdd8daf6863038d0ed3
620,950
def get_robot_number_and_alliance(team_num, match_data): """Gets the robot number (e.g. the `1` in initLineRobot1) and alliance color.""" team_key = f'frc{team_num}' for alliance in ['red', 'blue']: for i, key in enumerate(match_data['alliances'][alliance]['team_keys'], start=1): if team...
f20b2c34f67b10fffaceac7ef067953df43dbdd6
620,952
def getOutputFormat(seconds): """Returns a format string for the given number of seconds with the least leading zeros.""" if seconds < 60: return "%S" elif seconds < 3600: return "%M:%S" else: return "%H:%M:%S"
1a1a292f70090bdb19cb1eaaabc751f436e616cf
620,953
def A_tot_wkend_days_init(M, i, t, e): """ Initialize number of weekend days worked in the i'th pattern, tour type t, and weekend type e. :param M: Model :param i: weekend worked pattern :param t: tour type :param e: weekend type (1=Sun and Sat, 2=Fri and Sat) :return: number of weekend...
f1ee32a30bd4a89c30148c3d0cdf95da6c5836ed
620,954
def apply_homography_to_point(hmg, x, y, is_matrix=True): """Transforms a point (x, y) with a homography hmg. Args: hmg: a homography transformation of data type float32. If mode is 'matrix', it is of shape [3, 3]; otherwise its shape is [8]. x: the x coordinate of the point y: the y coordinate o...
bc78ec3413b73b32f766cc95421d00086d2c4846
620,960
def get_effective_bp(lam_i, lam_f, Nbp): """Returns the bandpass values given initial & final wavelengths, and number of bands""" return (lam_f/lam_i)**(1./Nbp) - 1.
869da01026543f23dfe9152d73dd03908bb51226
620,967
def pdfa2dict(pdfa): """Convert PDFA into nested dictionary of the form: mapping = { <State>: (<Label>, { <Action>: { <State>: <Probability> } } } Returns: mapping and the start state. """ mapping = {} for s in pdfa.states():...
cf45d2578453f52f395b5986731280f9c47b10b4
620,970
def _coalesce(*args): """ Returns first non-null argument, or None if all are null. """ return next((a for a in args if a is not None), None)
1e23821d86deea76af786cd98886b4fa86b91b8b
620,971
def findall(lst, key, value): """ Find all items in lst where key matches value. For example find all ``LAYER``s in a ``MAP`` where ``GROUP`` equals ``VALUE`` :param list lst: A list of composite dictionaries e.g. ``layers``, ``classes`` :param string key: The key name to search each dictionary in ...
4439b193bec153c8db3d72db7589aadad90c2f9f
620,973
def return_label(predicted_probs): """ Function that takes in a list of 7 class probabilities and returns the labels with probabilities over a certain threshold. """ threshold = 0.4 labels = [] classes = ['not toxic', 'toxic', 'severe toxic', 'obscene', 'threat', 'insult',...
d31178cc50d37ee9bb142cd401501fa49d4e51b0
620,974
from typing import Union from typing import List def list_of_ints(string: str, delimiter: Union[str, None] = None) -> List[int]: """Cast a string to a list of integers. Args: string: String to be converted to a list of int's. delimiter: Delimiter between integers in the string. De...
53a1ad5ace4cc9b1e6687910b34d9bbb12f595c9
620,980
def incrementMatching(text, matchSet, maxLength=None, n=2): """ Adds incrementing n-digit numbers to text until it no longer matches any entries on matchSet. """ if maxLength is not None and len(text) > maxLength: text = text[0:maxLength] while text in matchSet: if text[-n:].isdi...
767d32bc75be4b69b8f1a03b30b22be1b5e1a454
620,984
def _power_law_conversion_factor(g, e, e1, e2): """Conversion factor between differential and integral flux.""" term1 = e / (-g + 1) term2 = (e2 / e) ** (-g + 1) - (e1 / e) ** (-g + 1) return term1 * term2
1b43eea88a5d63faf60e7a043e9ce38f885d9419
620,986
def timedelta_seconds(timedelta): """Returns the total timedelta duration in seconds.""" return (timedelta.total_seconds() if hasattr(timedelta, "total_seconds") else timedelta.days * 24 * 3600 + timedelta.seconds + timedelta.microseconds / 1000000.)
615b71d43d477ab887783c2af93cfe85ce859fdf
620,987
import time def W3CDate(tmsecs=None): """ Return UTC time string according to http://www.w3.org/TR/NOTE-datetime """ if not tmsecs: tmsecs = time.gmtime() return time.strftime("%Y-%m-%dT%H:%M:%S", tmsecs) + "Z"
f602719864239e3be716af1d3361ec6b5c8e16f4
620,989
def _get_spot_surface(image, spot_y, spot_x, radius_yx): """Get a subimage of a detected spot in 2 dimensions. Parameters ---------- image : np.ndarray Image with shape (y, x). spot_y : np.int64 Coordinate of the detected spot along the y axis. spot_x : np.int64 Coordina...
e541d9751a0d841c8afd819a51f8f7bb8fcd165d
620,995
def increase(colour, increments): """Take a colour and increase each channel by the increments given in the list""" colour_values = [int(colour[1:3], 16), int(colour[3:5], 16), int(colour[5:], 16)] output = [min(255, colour_values[0] + increments[0]), min(255, colour_values[1] + increments[1]), min(255, col...
57202d67cfff7da638c94d78eb83d08bf5664001
620,996
from typing import Optional from datetime import datetime def check_expiration(expiration_datetime: Optional[datetime]): """ Checks if an expiration date was exceeded. Returns true if expired. """ return expiration_datetime is not None and datetime.now() >= expiration_datetime
df8a94b1205c9f2aef55d6b44d7734d88019df65
621,000
def _CheckNoFRIEND_TEST(input_api, output_api): """Make sure that gtest's FRIEND_TEST() macro is not used, the FRIEND_TEST_ALL_PREFIXES() macro from testsupport/gtest_prod_util.h should be used instead since that allows for FLAKY_, FAILS_ and DISABLED_ prefixes.""" problems = [] file_filter = lambda f: f.Loc...
cbac95ed3329bd1661cd0f8bbb4c50aac8d3654c
621,002
import random def shuffle_deck(deck): """Returns a shuffled deck made up of cards from the given deck""" # print("\nShuffling the deck!") shuffled_deck = deck[:] random.shuffle(shuffled_deck) return(shuffled_deck)
7623de9735fa778578a74313dd1a759da501c6b7
621,010
def walk_through_dict( dictionary, end_fn, max_depth=None, _trace=None, _result=None, **kwargs ): """Runs a function at a given level in a nested dictionary. If `max_depth` is unspecified, `end_fn()` will be run whenever the recursion encounters an object other than a dictionary. Parameters --...
cde35b3bf63662038968b7b23a31b996ac05a0d7
621,015
def _version_string(version): """Convert version from bytes to a string. Args: version: version in byte format. Returns: Three byte version string in hex format: 0x00 0x00 0x00 """ return ' '.join('0x{:02x}'.format(ord(b)) for b in version)
cb17c4efb4d3ccab5b1d13ca5b90471841b1f9a4
621,020
def quantify(iterable, pred=bool): """Return the how many times the predicate is true. >>> quantify([True, False, True]) 2 """ return sum(map(pred, iterable))
b99228f3af989522749b9ad9c1a07228dfca3a56
621,021
def read_template_source(filename): """Read the source of a RiveScript template, returning the Unicode text.""" try: # v0.2.0: Issue #3 with open(filename, 'r', encoding='utf-8') as f: text = f.read() except Exception: # v0.2.0: Issue #3 text = '' ...
24af50c30cfc490731ca84b5118326c308bcd0c8
621,022
def hamming_distance(m, n): """Hamming Distance between two natural numbers is the number of ones in the binary representation of their xor. """ return sum(map(int, bin(m ^ n)[2:]))
00b48a83912b869d2669ee0b0f75ecd38fdebcf1
621,026
def load_txt(label_file): """Load bounding boxes data from the given label file. Parameters label_file: str Path to label file. Returns data: list List of bounding boxes data. """ data = [] with open(label_file) as f: for line in f: row = line.st...
0ed25c209d0690d5d609a7db749c174a7e9e2534
621,027
def remove_dupes(iterable): """ Removes duplicate items from iterable object preserving original iterable order :param iterable: iterable :return: iterable """ unique = set() new_iter = iterable.__class__() for item in iterable: if item not in unique: new_iter.append...
afd4a4b5d8e694c252ce3b11f4f53148dcf4eb02
621,029
def is_iri(string): """ Return True if the given string looks like an IRI, and False otherwise. Used for finding type IRIs in the schema. Right now only supports http(s) URLs because that's all we have in our schema. """ return string.startswith('http')
c503d36555ce46b6fcecb4d151f3ef7d43818a6d
621,030
def _check_and_convert_legacy_input_config_key(key): """Checks key and converts legacy input config update to specific update. Args: key: string indicates the target of update operation. Returns: is_valid_input_config_key: A boolean indicating whether the input key is to update input config(s). ...
5a40eb7af24903fdc796ef233616f5f9a8685a81
621,031
def load_metis_part_sol (inputfile): """ read metis partition result """ lines = [open(inputfile, 'r').read().strip("\n")][0].split('\n') cut = int( lines[0].split('\t')[1] ) partDict = {} for line in lines[1:]: tokens = line.split('\t') part = int( tokens[0].split(' ')[-1] ) nodes = tokens[1].split(',')...
7e76723593faa616156eaf5b2d3c0501bc71a07b
621,034
def parseMovie(line): """ Parses a movie record in MovieLens format movieId::movieTitle . """ fields = line.split("::") return int(fields[0]), fields[1]
adb5d04b59eced65b2ca5e477624401d199499d4
621,037
import re def remove_non_numeric (value): """ Remove non-numeric characters from value. :param value: The value to be modified. :return Numeric value. """ return re.sub("[^0-9]", "", value)
4c84deeaee5759cb0029e4baf585d272667369ba
621,038
def with_leading_upper(example): """ Changes the leading letter of the text of example `example` to uppercase. """ text = example.text for (i, c) in enumerate(text): if not c.isspace(): text = text[:i] + text[i].upper() + text[(i + 1):] break example.text = text ...
102aff28df83a541d5500400db1e2fb1818e1c53
621,041
import re def get_int_or_none(value): """ >>> get_int_or_none(123) 123 >>> get_int_or_none('123asda') 123 """ if isinstance(value, int): return value try: return int(re.sub(r'^(\d+)(.*)$', r'\1', value)) except (TypeError, ValueError): return None
8104fd969b473056ed7d2f037cdb57dc061cebeb
621,042
def _to_int_or_none(data: str) -> int | None: """Convert to an integer or None.""" return int(data) if data else None
9387efaeaab6591e2eeb6f7d32014da355990f52
621,043
def build_example_algo_config( ticker, timeseries='minute'): """build_example_algo_config helper for building an algorithm config dictionary :returns: algorithm config dictionary """ willr_close_path = ( 'analysis_engine/mocks/example_indicator_williamsr.py') willr_open...
4f30ac8056afb91740aace5eb75b1aa5fed07664
621,046
def set_pooling_options(opts, pooling_options=None): """Set the IPU pooling compilation options for the session. .. code-block:: python # Set "poolUseIntrospectiveMapping" flag to "false" opts = create_ipu_config() opts = set_pooling_options(opts, pooling_options={"poolUseIntrospective...
0f66e6f5e34a80f99e6b28931e8d9011d6468cec
621,047
def is_ipynb_file(file_name: str) -> bool: """ Return whether a file is a jupyter notebook file. """ return file_name.endswith(".ipynb")
8281b511f61ec4bf46afae8327f21b29daa37a72
621,051
from typing import Any from typing import MutableSequence def is_adjacency_matrix(item: Any) -> bool: """Returns whether 'item' is an adjacency matrix.""" if isinstance(item, tuple): item = item[0] return (isinstance(item, MutableSequence) and all(isinstance(i, MutableSequence) for i ...
9c5ff9dde4953ad7601ffa6fad9d91cbc7797256
621,053
def truncate_path(full_path, chars=30, skip_first=True): """Truncate the path of a category to the number of character. Only the path is truncated by removing nodes, but the nodes themselves are never truncated. If the last node is longer than the ``chars`` constraint, then it is returned as is (w...
b3ced4c6114b75fd6702b7f06f791f3d5008c399
621,054
def flatten_dictionary(input_dict, parent_key='', separator='.'): """Flatten a given dictionary with nested dictionaries if any. Example: { 'a' : {'b':'c', 'd': {'e' : 'f'}}, 'g' : 'h'} will be flattened to {'a.b': 'c', 'a.d.e': 'f', 'g': 'h'} This will flatten only the values of dict type. :para...
ccdb90303568dc899728096a05e9cde207f3c382
621,055
def convert_emotion_metric_entity_to_dict(e_metric): """Convert a datastore EmotionMetric entity into a dictionary. Args: e_metric: an EmotionMetric datastore entity. Returns: A dictionary with keys as emotions and values are confidences """ e_dict = {} e_dict['amusement'] = e_metric.amusement e...
affd816597973edf120d23b8ca912270b81c88d4
621,056
def classpath(klass): """Return the full class path Args: klass (class): A class """ return f"{klass.__module__}.{klass.__name__}"
1275e318e97c786e620ec916005ddfb69ba837f7
621,058
import glob def glob_all(args): """Given a list of command line arguments, expand all of them with glob.""" result = [] for arg in args: if arg[0]=="@": with open(arg[1:],"r") as stream: expanded = stream.read().split("\n") expanded = [s for s in expanded if...
3e7a23b3b89e3285c722415b1eee5e6d71b380d3
621,059
import random def random_action(state): """ Plays a game using random actions until a terminal state is reached. Returns score of that game. """ while not state.is_terminal(): valid = state.get_valid_actions() if not valid: raise Exception("Non-terminal state has no v...
9cb3db28ed638118cf4da4344b92d8f4cb16b7ec
621,062
def remove_at(i, s): """Removes character from string at provided position""" return s[:i] + s[i + 1 :]
ee881c431910b8b708768421555628167d54e732
621,063
def MakeSpecificSKUAllocationMessage( messages, vm_count, accelerators, local_ssds, machine_type, min_cpu_platform): """Constructs a single specific sku allocation message object.""" prop_msgs = ( messages.AllocationSpecificSKUAllocationAllocatedInstanceProperties) return messages.AllocationSpecific...
f050d59635a2a93019fd4612009ceca195751740
621,065
import string def deriveArtistFromName(name): """ Ensure that the given name doesnt have usual suspects like "Featuring" or "Ft" or " with" to attempt to return just the artist name :param name: str :return: str """ if not name: return name removeParts = [" ft. ", " ft ", " fe...
5e47083819ceb3a1ec635dc53435ac13cfe61e74
621,068
def rvShift(wavelength, rv): """ Perform the radial velocity correction. Parameters ---------- wavelength : numpy array model wavelength (in Angstroms) rv : float radial velocity shift (in km/s) Returns ------- wavelength : numpy array shifted model wavelength (in Angstroms) """ r...
eaf749be79227797d4b474beaeb4dbf425ff414d
621,073
def jaccard(macs1, macs2): """Returns jaccard similarity between two lists of MAC Addresses""" union = list(set(macs1) | set(macs2)) intersection = list(set(macs1) & set(macs2)) return len(intersection) / len(union)
36feb625afb96aaecfbed56f560236340caada51
621,076
def upper_bound(arr, value, first, last): """Find the upper bound of the value in the array upper bound: the first element in arr that is larger than value Args: arr : input array value : target value first : starting point of the search, inclusive last ...
fb66b3d5deedc67156843f18e5b7b60ed58b617e
621,078
def subdict(dic, keys): """ Returns a new dictionary dic2 such that dic2[i] = dic[i] for all i in keys dic -- a dictionary keys -- a list of keys """ dic2 = {} for key in keys: if key in dic: dic2[key] = dic[key] return dic2
fd9dbb7b38834a6ccfbacb666cc8f7a0badaa1ac
621,080
def _minimize(obj): """Remove lists with only one entry""" if isinstance(obj, list): if len(obj) == 1: return _minimize(obj[0]) else: result = [] for x in obj: y = _minimize(x) if y: result.append(y) ...
c96df4e6407ed7106cabe686fad9e0347e125135
621,082
from pathlib import Path def get_local_paths(root, pattern): """Returns a generator of files matching the glob_pattern under the root directory .""" path = Path(root) return path.glob(pattern) # find the columns that are not common
a6eda9f1e4e32972e4848e9a17877f8ce3fe7302
621,084
def is_strf_param(nm): """Check if a parameter name string is one of STRF parameters.""" return any(n in nm for n in ("rates_", "scales_", "phis_", "thetas_"))
995ab39c2ac86d2213a6180fb2bac427e041b110
621,087
def get_params(**override): """Returns default parameters dictionary for model.""" params = dict( # Model args num_channels=3, multiscale='Steerable', # 'Steerable', Laplacian', None nscales=3, steerable_filter_type=1, cnn='Conv', num_filters=[64, 64, 64, 3], paddi...
5dfb12f705ccda9c35103a125f20d8ac9d53e51f
621,089
def _is_virtio_blk(device_path): """ Check whether the supplied device path is a virtio_blk device. We assume that virtio_blk device name always begin with `vd` whereas Xen devices begin with `xvd`. See https://www.kernel.org/doc/Documentation/devices.txt :param FilePath device_path: The devic...
45bb91a3a634528389a70e8b0c1a1c9d60cc5b4d
621,090
import torch def pad_to_multiple(tensor, pad_base): """ This function pads the sequence with zeros to be divisible by pad_base. Assumed tensor is of shape (batch, seq_len, channels) """ new_len = ((tensor.shape[1] - 1) // pad_base + 1) * pad_base # one is subtracted for the case when tensor.sh...
51c17f1533113067f0946e67a89602ad273ca9da
621,092
def fraction(count, value): """Divides the given character count by the length of the string representation for the given value. Parameters ---------- count: int Character count returned by one of the count functions. value: scalar Scalar value in a data stream. Returns ...
6b315576b278e6a391291c98fda3a4f4c52eadbc
621,096
def cc_is_manager(ctx): """Check if command sender has channel managment permissions.""" return (ctx.guild == None) or (ctx.author.permissions_in(ctx.channel).manage_channels)
907011d349ec89d56d139e7d9e01c581ceb82862
621,099
def ChanModDS(ds, chan, mod=lambda x: x): """ apply any well-behaved lambda function to a specific channel within a dataset :param ds: xarray dataset :param chan: channel to apply modification too :param mod: well-behaved lambda function :return: adds a channel with the modified data """ ...
fcca25d1fc65d1bc6b84d397e9b6c0cc40b90e81
621,100
def IsPalindromePermutation(s): """ check if the string s is a permutation of a palindrome""" chars = {k : 0 for k in set(s)} for i in s: chars[i] += 1 odd_nums = 0 for k, v in chars.items(): if (v % 2) != 0: odd_nums += 1 if odd_nums > 1: return False return True
0d977ed5b112c2647fdcb676243093c07fd30322
621,101
def find_closest_pixel(pos, pixel_tab): """ Compute the closest pixel of a given position Parameters ---------- pos : 1D Numpy array giving a position pixel_tab : N-dim Numpy array of pixels positions [X,Y] Returns ------- Pixel index in the given pixel_tab, corresponding distance t...
47d602362f1c34fbcc29b37b4ca5ab97209e840a
621,102
def is_divisible(m: int, n: int) -> bool: """ predicate to be divisible Args: m: dividend n: divisor Returns: True if divisible """ return m % n == 0
cdee5c4960be55aceed164b4ed028dd58b48bcc4
621,103
import ast def get_edgesID(row, columns): """ The ABM stores the sequence of edgeIDs traversed in each route in different columns, given the 254 characters limit per field. This functions merges such lists in one List. Parameters ---------- row: Pandas Series A row of the GeoData...
66347c78bc9f2b4a4978669f854fc6565da705e8
621,106
def get_ap_os_version(ap): """Parses os_version from AP data Removes model from start of os version if found. Args: ap (dict): ap data returned from FortiOS managed-ap REST endpoint Returns: str: OS version on 'unknown' id not detected """ if 'os_version' not in ap: ...
6212d577c42fa03b29b492812e73f3a4ad237fcd
621,108
import json def min_groups(mag, ins, filt, sub, mod, band, infile): """Estimates the minimum number of groups to reach target acq sat requirements. Parameters ---------- mag : float Magnitude of star. ins : str Instrument. filt : str Filter. sub : str ...
2a010d886cc68c4555e15445ed7d3f1086e1aa37
621,117
def add_edge(locations, edge): """ Add edge to list of locations, returning a list of edge-added locations """ if edge is None: return locations return [tuple([i + j for i, j in zip(edge, l)]) for l in locations]
dd32eab9b1033a41184b234798dcc5f673df1352
621,122
import locale def asunicode_win(s): """Turns bytes into unicode, if needed.""" if isinstance(s, bytes): return s.decode(locale.getpreferredencoding()) else: return s
318901e2337c78bd6d9b3b6e0c6427f50ab19344
621,128
def _call_signature(callable, *args, **kwargs): """ Generate a human-friendly call signature From recipe http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/307970 """ argv = [repr(arg) for arg in args] + ["%s=%r" % x for x in kwargs.items()] return "%s(%s)" % (callable.__name__, ", ".join(...
24ae6a7ac4cb1285c2d9c1de11698da1f10266fb
621,129
def pos_distribution(doc): """Get POS distribution from a processed text. Let us suppose that a given sentence has the following pos tags: ``[NOUN, VERB, ADJ, VERB, ADJ]``. The PoS distribution would be * ``NOUN: 1`` * ``VERB: 2`` * ``ADJ: 2`` This function returns this distrubution as a ...
8d4aae39d779f26990d1acd933e8979453cdd155
621,133
def origin_volume(origin_str): """Extracts original phisical volume name from origin record""" return origin_str.split("@")[0].split("/")[1]
baf25e7b84fd1f1008b172bfebc980ed73f86c51
621,134
def _unit_conll_map(value, empty): """ Map a unit value to its CoNLL-U format equivalent. Args: value: The value to convert to its CoNLL-U format. empty: The empty representation for a unit in CoNLL-U. Returns: empty if value is None and value otherwise. """ return empty if value i...
1555617637c2bd3096eb80dcbe9d121d63edefa3
621,135
def make_optic_canula_cylinder( atlas, root, target_region=None, pos=None, offsets=(0, 0, -500), hemisphere="right", color="powderblue", radius=350, alpha=0.5, **kwargs, ): """ Creates a cylindrical vedo actor to scene to render optic cannulas. By default thi...
fd62541bd97f540e97eef99fc065ea1822c58598
621,137
def strong_emphasis(text: str) -> str: """Strongly emphasizes (bolds) the given text by placing <strong> tags around it. :param text: The text to be strongly emphasized """ return f'<strong>{text}</strong>'
07a6cbe0647e3c2e57b4c41618321bdef2cbc0e4
621,145
def ParsePlaceId(json_obj): """Parse the place id from the 'place' twitter tag if it exists.""" if not json_obj: return None return json_obj.get('id', '')
97e387c307af6ec8d7068418d27ad6da8a9d8337
621,147
import requests def get_response(url, params) : """ Handle GET response and convert to json. """ response = requests.get(url, params) response.raise_for_status() data = response.json() return data
16e4ea499a4a95f122ae43c402cedf1980c147d8
621,148
def _get_block_sizes(resnet_size): """Retrieve the size of each block_layer in the ResNet model.""" choices = { 18: [2, 2, 2, 2], 34: [3, 4, 6, 3], 50: [3, 4, 6, 3], 101: [3, 4, 23, 3], 152: [3, 8, 36, 3], 200: [3, 24, 36, 3] } return choices[resnet_size]
7cfd70e655bfd91560df54ad5faff3e7771b928c
621,151
import socket def findFreePort(interface="127.0.0.1", family=socket.AF_INET, type=socket.SOCK_STREAM): """ Ask the platform to allocate a free port on the specified interface, then release the socket and return the address which was allocated. @param interface: The local address to try to bind the po...
37cb499eb388250ee31195ec5008b0ea7c9e6469
621,154
import re def parse_dump_file(filename): """Parse dump file data.""" with open(filename, 'r') as dump_file: results = dict() for line in dump_file: match = re.search(r'Janky frames: (\d+) \(([\d\.]+)%\)', line) if match is not None: results['jankNum'] = ...
2524244df40f04e7d780da959e036b4b591aab58
621,156
import warnings def process_border_size_arg(border_size_arg): """Handle borderSize arg in vidstab.__main__ Convert strings that aren't 'auto' to 0 :param border_size_arg: borderSize arg in vidstab.__main__ :return: int or 'auto' >>> process_border_size_arg('a') 0 >>> process_border_size...
2afd217b4110c4060f7438f6f11e874b67085950
621,158
def mocked_user_input_macos(mocked_user_input): """Mocking user input and return `macos`""" mocked_user_input.return_value = "macos" return mocked_user_input
a5a5997ba8777c685fd3bda79ac55a012abb2050
621,159
def get_hounsfield_coeffs(ds_open_file): """Returns the slope-intercept pair needed to convert an image to Hounsfield units""" rescale_slope = ds_open_file[0x28, 0x1053].value rescale_intercept = ds_open_file[0x28,0x1052].value return (rescale_slope,rescale_intercept)
28e3bef8a634748a951d2e06d9601ba7495a6ba4
621,160
def check_elements(string): """Check for chemical letters outside of the CHNOPS set. If the string only contains CHNOPS, returns True. Otherwise, returns False. Note: does not cover Scandium :( """ bad_elements = "ABDEFGIKLMRTUVWXYZsaroudlefgibtn" # chem alphabet -CHNOPS return not any(n i...
fed127c6546e7bea9f6201b30de5bd99e5ece615
621,163
def sanitize_code(code): """ Sanitize code removing unnecessary characters Params: code (str): target code Returns: the sanitized code """ if code: code = code.replace('-', '') code = code.ljust(7, '0') return code
714a081ab390d85e9dfb961ba8a89c2abe0cab9a
621,164
def str_list_oconv(x): """ Convert list into a list literal. """ return ','.join(x)
bc575e9df0d5425110f40a4dddc5b080e754e99c
621,167
def is_order_constrained(paths, constraints, j, k): """Is the order of the sequences between j and k constrained. Such that reversing this order will violate the constraints.""" for q in range(j, k): # search between j and k. first_path = paths[q] for constraint in constraints: ...
c385b1245213a67b5c78e59247c067fac68f547b
621,169
def to_applescript(b): """Convert a Python boolean to a string to be passed back to AppleScript""" return str(b)
2576d535addd310b135501fc8cb4c7443f294d35
621,175
def multi_arity(*funcs): """Returns a new multi-arity function which dispatches to `funcs`. The returned function will dispatch to the provided functions based on the number of positional arguments it was called with. If called with zero arguments it will dispatch to the first function in `funcs`, if c...
15a7617efdf6b22f8ad3d65fcc873b0b14237b74
621,179
def how_many_squares_in_shape(input_shape, feature_shape, delta): """ Computes the shape of an output layer that can be plugged into the input layer with respect to their shapes and the delta Parameters; `input_shape`: The shape of the input layer `feature_shape`: The shape of the feat...
3219c604d679658a71408ccc12826c1eeaae66ac
621,180
def eval_datasets_flist_reader(flist): """ :param flist format: impath,impath\nimpath impath\n ... :return: (impath, label) list """ imlist = [] with open(flist, 'r') as rf: for line in rf.readlines(): q,r = line.strip().split(',') if q == 'query_id': ...
1152c84834720aa3dea5dd853c20fddc5ef9895b
621,181
def getHdbCopyBase(ctx): """ Get base directory where SAP HANA database snapshots are copied to """ return f'{ctx.cf.nfs.bases.copy}/{ctx.cf.refsys.hdb.host.name}/{ctx.cf.refsys.hdb.sidU}'
e80407e4514cd5b245939f2b6aed12afe6d9efc8
621,188
import pickle def load(fname): """Load a hierarchical model saved to file via model.save(fname) """ with open(fname, 'rb') as f: model = pickle.load(f) return model
b2559ebe37cd0c21aff027ce36458e9bf8607476
621,192
def h(params, sample): """This evaluates a generic linear function h(x) with current parameters. h stands for hypothesis Args: params (lst) a list containing the corresponding parameter for each element x of the sample sample (lst) a list containing the values of a sample Returns: Evaluation of h(x) """ ac...
4267ba1499eb6863cdc32a9b3572afd196599105
621,196
def get_pipe_dict(d, i): """ given a dictionary d for a given instrument, return the dictionary for the ith pipeline version """ pipe_versions = list(d.keys()) k = pipe_versions[i] mode = list(d[k].keys())[0] return d[k][mode]
ad2a95866ed5a95009274a41ae75af526e3c2fc3
621,200
def get_image_topic(bag): """ Returns the name of the topic for the main camera """ topics = bag.get_type_and_topic_info()[1].keys() for t in topics: if 'camera_node/image/compressed' in t: return t msg = 'Cannot find the topic: %s' % topics raise ValueError(msg)
70a0ee16fb4802782f8ff386ef8ea4c6b08b191d
621,204
import requests def get_drive_time(apiKey, origin, destination): """ Returns the driving time between using the Google Maps Distance Matrix API. API: https://developers.google.com/maps/documentation/distance-matrix/start # INPUT ------------------------------------------------------------------...
ed612022cdade4d98efc15fd0c42711bdc95a2e2
621,205
def get_symbol_map(source_nodes): """Generates a dict of {'id': SourceUnit} used for linking nodes. Arguments: source_nodes: list of SourceUnit objects.""" symbol_map = {} for node in source_nodes: for key, value in ((k, x) for k, v in node.exportedSymbols.items() for x in v): ...
8c4138d9f95598112724b31c2c97e0fcd537ac42
621,210
def dictStructure(dictionary, indent=4, level=0): """ Get the structure of a dictionary. Returns an ``OrderedDict`` with the same keys as the one passed as input but the values replaced with its type. Args: dictionary (`dict`): dictionary to traverse indent (`int`): number of spaces to ...
047beaf7b0f5714b75ba84543d7ce4d0b484e7d4
621,212
def get_num_iterations(iterations_per_utterance, examples): """Returns the number of iterations to run for in this batch of examples Args: iterations_per_utterance (int): iterations per utterance config examples (list[Example]) Returns: int: number of iterations """ return ...
b7b0f6a9c186b83bbb5ddc2d0be11240f2500a96
621,214