content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def find_two_sum(arr, target): """ Finds the two (not necessarily distinct) indices of the first two integers in arr that sum to target, in sorted ascending order (or returns None if no such pair exists). """ prev_map = {} # Maps (target - arr[i]) -> i. for curr_idx, num in enumerate(arr): ...
dc444add33e01e1ca59f8e08977dffc54e433097
675,502
import ast def read_data_from_txt(file_loc): """ Read and evaluate a python data structure saved as a txt file. Args: file_loc (str): location of file to read Returns: data structure contained in file """ with open(file_loc, 'r') as f: s = f.read() return ast.l...
e974b50c2a9f691cb365edf1adef7bbf1bf3b638
675,503
import math def bounding_hues_from_renotation(hue, code): """ Returns for a given hue the two bounding hues from *Munsell Renotation System* data. Parameters ---------- hue : numeric *Munsell* *Colorlab* specification hue. code : numeric *Munsell* *Colorlab* specification ...
72d247c9418b1c6e51ec56e6e10f79203631ae78
675,505
def get_div_winners(df_sim): """Calculate division winners with summarised simulation data :param df_sim: data frame with simulated scores summarised by iteration :return: data frame with division winners per iteration """ return ( df_sim .sort_values(by=['tot_wins', 'tot_pts'], ascending=[False, Fal...
ddaa111ae73209fb8e6c369ce0cecda3a3dd625d
675,508
def _construct_version(major, minor, patch, level, pre_identifier, dev_identifier, post_identifier): """Construct a PEP0440 compatible version number to be set to __version__""" assert level in ["alpha", "beta", "candidate", "final"] version = "{0}.{1}".format(major, minor) if patch: version +=...
9cf26af2250a2fed80b6e63390abc883dcba232b
675,515
def channel_parser(channel): """Parse a channel returned from ipmitool's "sol info" command. Channel format is: "%d (%x)" % (channel, channel) """ chan, xchan = channel.split(' (') return int(chan)
d2a5cb20b9e44bbbc6c617706e952b333db5b2b4
675,519
def find_col(table, col): """ Return column index with col header in table or -1 if col is not in table """ return table[0].index(col)
b6fd7f6e9e3431d042b488ca737c4e7883cf7018
675,521
import torch def loss_fn(outputs, labels): """ Compute the cross entropy loss given outputs from the model and labels for all tokens. Exclude loss terms for PADding tokens. Args: outputs: (Variable) dimension batch_size*seq_len x num_tags - log softmax output of the model labels: (Var...
9f53f0879db5853e516358336081f144e51272d1
675,522
def get_taskToken(decision): """ Given a response from polling for decision from SWF via boto, extract the taskToken from the json data, if present """ try: return decision["taskToken"] except KeyError: # No taskToken returned return None
5af140b26eb8af1fa93fd53e83634ecdd232a33a
675,523
from typing import OrderedDict def broadcast_variables(*variables): """Given any number of variables, return variables with matching dimensions and broadcast data. The data on the returned variables will be a view of the data on the corresponding original arrays, but dimensions will be reordered and ...
00eda392c2ae791a34c02a613ab5b3d6a2a40624
675,524
def chunkFair(mylist, nchunks): """ Split list into near-equal size chunks, but do it in an order like a draft pick; they all get high and low indices. E.g. for mylist = [0,1,2,3,4,5,6], chunkFair(mylist,4) => [[0, 4], [1, 5], [2, 6], [3]] """ chunks = [None]*nchunks for i in range(nchunks): ...
901005a4b9de39efd09c685b0111f30f9eca9679
675,529
def unionRect(rect1, rect2): """Determine union of bounding rectangles. Args: rect1: First bounding rectangle, expressed as tuples ``(xMin, yMin, xMax, yMax)``. rect2: Second bounding rectangle. Returns: The smallest rectangle in which both input rectangles are fully ...
1c89439efb082159400acd25396cbf43d7ea1ddf
675,530
import math def inverse_sigmoid(y): """A Python function for the inverse of the Sigmoid function.""" return math.log(y / (1 - y))
f2f851b23dfd6fddb2ecdfa83aead3b3f880472a
675,533
import math def image_entropy(img): """ calculate the entropy of an image """ hist = img.histogram() hist_size = sum(hist) hist = [float(h) / hist_size for h in hist] return -sum([p * math.log(p, 2) for p in hist if p != 0])
d5e4a6134eeb3d1fb65d19d60995ffa1f4c1c72c
675,537
def strip_alias_prefix(alias): """ Splits `alias` on ':' to strip off any alias prefix. Aliases have a lab-specific prefix with ':' delimiting the lab name and the rest of the alias; this delimiter shouldn't appear elsewhere in the alias. Args: alias: `str`. The alias. Returns: ...
2a38083ecbd313a2bdfea88cd2c613b5b3074cdc
675,544
from datetime import datetime import pytz def read_gpvtg(sentence, timestamp, do_print=False): """ Read and parse GPVTG message""" values = sentence.split('*')[0].split(',') result = {} # Linux timestamp try: result['linux_stamp'] = int(timestamp) except: result['linux_stamp']...
7029eda2f45f7d87d0fafe673fa2244135dbdcae
675,557
def COUNT_DISTINCT(src_column): """ Builtin unique counter for groupby. Counts the number of unique values Example: Get the number of unique ratings produced by each user. >>> sf.groupby("user", ... {'rating_distinct_count':tc.aggregate.COUNT_DISTINCT('rating')}) """ return ("__builtin__count__disti...
d488eda52080b6554256dfd08f29f174b7fbe1ea
675,560
def clamp(value, minimumValue, maximumValue): """clamp the value between the minimum and the maximum value :param value: value to clamp :type value: int or float :param minimumValue: minimum value of the clamp :type minimumValue: int or float :param maximumValue: maximum value of the clamp ...
a9fa67fe2beb876d3c6455fbbaf5c918772480d7
675,563
def check_for_url_proof_id(id, existing_ids = None, min_id_length = 1, max_id_length = 21): """Returns (True, id) if id is permissible, and (False, error message) otherwise. Since we strip the id, you should use the returned one, not the original one""" id = id.strip() # maybe this is too restrictive,...
9603c8fa24a445d8eec32a73c5bddb5db066d29c
675,565
def is_equal_1d(ndarray1, ndarray2, showdiff=False, tolerance=0.000001): """ Whether supplied 1d numpy arrays are similar within the tolerance limit? Parameters ---------- ndarray1 : numpy.ndarray[float64, ndim=1] First array supplied for equality with `ndarray2`. ndarray2 : numpy...
7d7db89b379b6ab626ad18d2e1de19312166c90e
675,567
def sort_and_uniq(linput): # @ReservedAssignment """ Función que elimina datos repetidos. :param linput: Lista :type linput: list :return: Lista modificada :rtype: list """ output = [] for x in linput: if x not in output: output.append(x) output.sort() ...
009bb3ddb963789de8129979ebf5f2c784c2a6ba
675,572
import asyncio def swait(co): """Sync-wait for the given coroutine, and return the result.""" return asyncio.get_event_loop().run_until_complete(co)
3fca650eadce043602a07c909a0988846e6405e0
675,574
def get_indexes(table, col, v): """ Returns indexes of values _v_ in column _col_ of _table_. """ li = [] start = 0 for row in table[col]: if row == v: index = table[col].index(row, start) li.append(index) start = index + 1 return li
fd585a908477dd3632f2dbc3f450c1601157e928
675,575
import json def load_json(filename): """Load a json file as a dictionary""" try: with open(filename, 'rb') as fid: data = json.load(fid) return data, None except Exception as err: return None, str(err)
ce780775aa54913c63e2b9a4525c0da6f053e3fb
675,583
def determine_Cd(w_10): """ Determining the wind speed drag coefficient Following Large & Pond (1981) https://doi.org/10.1175/1520-0485(1981)011%3C0324:OOMFMI%3E2.0.CO;2 """ return min(max(1.2E-3, 1.0E-3 * (0.49 + 0.065 * w_10)), 2.12E-3)
8afdb7c802e0d97276b172372079f29d8f9416fa
675,584
def pack(timestamp, temp, accel_data, gyro_data, magnet_data=None): """ 最新位置情報データを辞書化する。 引数: timestamp 時刻 temp 気温(float) accel_data 加速度データ(辞書) gyro_data 角速度データ(辞書) magnet_data 磁束密度データ(辞書):オプション 戻り値: 最新位置情報データ群(辞書) """ return_dict = {'a...
ae0a9ebddc4e942658cfd6e61ede6b6b8058fe16
675,588
import torch def lengths_to_mask(lengths, max_len): """ This mask has a 1 for every location where we should calculate a loss lengths include the null terminator. for example the following is length 1: 0 0 0 0 0 0 The following are each length 2: 1 0 0 0 0 3 0 0 0 0 if max_len is ...
d487f46c129014092f520f7361926389c6a5ee1a
675,594
def check_line(line): """Check that: * a line has nine values * each val has length 1 * each val is either digital or "-" * digital values are between 1 and 9 """ vals = line.split() if not len(vals) == 9: return False for val in vals: if not len(val) == 1: ...
8d1a8d49e30c7fac395cba351010c77461bf0540
675,595
import six def collect_ancestor_classes(cls, terminal_cls=None, module=None): """ Collects all the classes in the inheritance hierarchy of the given class, including the class itself. If module is an object or list, we only return classes that are in one of the given module/modules.This wi...
8ad9eddf72ea9f7104a28b21797237f42f57b341
675,596
def bin2hex(binbytes): """ Converts a binary string to a string of space-separated hexadecimal bytes. """ return ' '.join('%02x' % ord(c) for c in binbytes)
35bc13518b946db00192026dba2705626d4f06f1
675,599
import torch def calc_f1_micro(predictions, labels): """ Calculate f1 micro. Args: predictions: tensor with predictions labels: tensor with original labels Returns: f1 score """ preds = predictions.max(1)[1].type_as(labels) true_positive = torch.eq(labels, preds)....
d99778a3b3ee96ad3605e9a3aa947d9ca8af6b37
675,603
def flatten(t): """ Helper function to make a list from a list of lists """ return [item for sublist in t for item in sublist]
3181a5f9404f8803741276648f77e50203cb581d
675,605
def get_html_header() -> str: """Helper to get a HTML header with some CSS styles for tables."" Returns: A HTML header as string. """ return """<head> <style> table { font-family: arial, sans-serif; border-collapse: colla...
fc2302ff199ef944169a4096a53f6bd48fdb06fd
675,606
import glob def found_with_glob(value): """ Check if at least one file match the given glob expression. :param value: glob expression """ for _ in glob.glob(value): return True return False
38677a00e2c80981baa8d1d27ad0bec2b8df009f
675,610
import shutil def get_path_to_executable(executable): """ Get path to local executable. :param executable: Name of executable in the $PATH variable :type executable: str :return: path to executable :rtype: str """ path = shutil.which(executable) if path is None: raise ValueErro...
5a840d2dd6ade2fe3f4f26861efac0b69e3a33b9
675,619
def _direction_to_index(direction): """Map direction identifier to index. """ directions = {-1: 0, 0: slice(None), 1: 1, '<=': 0, '<=>': slice(None), '>=': 1} if direction not in directions: raise RuntimeError('Unknown direction "{:d}".'.format(direction)) return directions[direction]
1612c7107601a6166e478815b89725701f8dc3ff
675,621
import requests import warnings def check_pypi_module(module_name, module_version=None, raise_on_error=False, warn_on_error=True): """ Checks that module with given name and (optionally) version exists in PyPi repository. :param module_name: name of module to look for in PyPi :param module_version: (...
f491303844d8ec138e75872be8a16cb0e399e9fc
675,624
def postprocess_chain(chain, guard_solutions): """ This function post-processes the chains generated by angrop to insert input to pass the conditions on each gadget. It takes two arguments: chain - the ropchain returned by angrop guard_solutions - the required inputs to satisfy the gadget c...
a7977ce25ba61e977718f3b9d88328aaa70e2827
675,627
def _parse_top_section(line): """ Returns a top-level section name ("PATH", "GEM", "PLATFORMS", "DEPENDENCIES", etc.), or `None` if the line is empty or contains leading space. """ if line == "" or line[0].isspace(): return None return line
ac202bc8ccbcdf3dd392b442b11ed3601cca9149
675,629
def remove_line_break_escapes(value): """ removes line break escapes from given value. it replaces `\\n` with `\n` to enable line breaks. :param str value: value to remove line break escapes from it. :rtype: str """ return value.replace('\\n', '\n')
f9423411a771a7e7561e165e8a13f125e3aee918
675,631
def _get_id(name): """Gets id from a condensed name which is formatted like: name/id.""" return name.split("/")[-1]
6489f23b5a5a25ee73ed14af2f18ae141fd748f8
675,634
def extract_endpoints(data): """ Turn the dictionary of endpoints from the config file into a list of all endpoints. """ endpoints = [] for nodetype in data: for interval in data[nodetype]: for api in data[nodetype][interval]: endpoints += ( da...
350d93864de0a1ca26732b605874cdd9a3af3a48
675,637
import json import requests def getListOfPositions(position_name : str): """ Retrives all Microsoft publicily listed positions with name `position_name` by sending POST to Microsoft career endpoint. Args: position_name (str): Name of the position Returns: ...
66b753167e6bcd252a77df3e25743d0eae6e2796
675,641
def test_savestate(neuron_instance): """Test rxd SaveState Ensures restoring to the right point and getting the right result later. Note: getting the right result later was a problem in a prior version of NEURON, so the continuation test is important. The issue was that somehow restoring from a Sa...
9ed97f29c8d6c97bcb813803b3022bc0783884c2
675,645
def ask(message, options, allow_empty=False, help=None) -> str: """Ask user for input Parameters ---------- message : str Message. options : dict ``{command: description}`` mapping. allow_empty : bool Allow empty string as command. help : str If provided, add...
20c592b5b46dc1ee082053d5d898e1543fb9bb5e
675,646
import random def random_payload_shuffled_bytes(random_payload_bytes): """ Fixture that yields the randomly generated payload bytes but shuffled in a random order. """ return random.sample(random_payload_bytes, len(random_payload_bytes))
9cf54600d4e6c6dd6dd888daad63de36b6b5b23d
675,647
from typing import Optional def greeting(name: Optional[str] = None) -> str: """Says hello given an optional name. NOTE: `Optional` is just a convenience. It's equivalent to `Union[str, None]`. """ if name: return f"Hello {name}!" else: return "Hello you!"
c325659aedaf7b9254dca97ddb51ee96bdaa19ac
675,650
import math def ecliptic_longitude_radians(mnlong, mnanomaly): """Returns ecliptic longitude radians from mean longitude and anomaly correction.""" return math.radians((mnlong + 1.915 * math.sin(mnanomaly) + 0.020 * math.sin(2 * mnanomaly)) % 360)
8c2075fb071676a00fa0eeec871d2eddc805b02c
675,653
def buff_internal_eval(params): """Builds and evaluates BUFF internal energy of a model in parallelization Parameters ---------- params: list Tuple containing the specification to be built, the sequence and the parameters for model building. Returns ------- model.bude_score...
0a61d7175812862392964f1ae338e75b0b3f3cc9
675,654
from typing import Dict from typing import Any def countdown( element: Dict[str, Any], all_data: Dict[str, Dict[int, Dict[str, Any]]] ) -> Dict[str, Any]: """ Countdown slide. Returns the full_data of the countdown element. element = { name: 'core/countdown', id: 5, # Countdown ...
e43869e55bd68273a3324c036deef4f352275589
675,655
def is_csv_accepted(request): """ Returns if csv is accepted or not :return: True if csv is accepted, False otherwise """ return request.args.get('format') == "csv"
e02e9f0de5e84f6e163d5d6d161352740e418daa
675,658
def can_copy(user, plan): """ Can a user copy a plan? In order to copy a plan, the user must be the owner, or a staff member to copy a plan they own. Any registered user can copy a template. Parameters: user -- A User plan -- A Plan Returns: True if the User has p...
25c6d5589c09b74257905ab8494c728c3ffabdd3
675,662
import pickle def load_classifcation_metrics_pkl(classification_pkl): """Load a classificationMetrics pickle file""" with open(classification_pkl, 'rb') as fh: cm_h = pickle.load(fh) return cm_h
29bf0616608daf0f9cdd5800e94f91018664b585
675,669
def fake_agent() -> str: """ The original FAKE_USER_AGENT in config.py: 'Mozilla/5.0 (Windows NT 6.1; rv:84.0) Gecko/20100101 Firefox/84.0' Works with Startpage when nothing else will. :return: static user agent string. """ # NOTE that the Firefox ver can be any from firefox_agent() re...
27e944ab127f150704268ffcfed2c06cb20bb71c
675,674
import math def optimum_qubit_size(precision: int, error: float) -> int: """ Return the number of qubit required for targeted number of decimal and error rate. """ return math.ceil(precision + math.log2(2+1/(2*error)))
031f35f4d461d712b53f41e3697c73fad16b0b21
675,677
def get_current_weather_desc(data): """Get the current weather description. These values are undocumented. :param data: :return: e.g. 'Partly Cloudy', 'Light Rain' """ return data['current_condition'][0]['weatherDesc'][0]['value']
aebb28d30de09f14867aee8ffc0a6f1db31f5fd0
675,689
import csv def save_to_csv(data: list, file_name: str) -> bool: """ Saved given data to .csv file. Parameters ---------- data: list, required Data produced by function prepare_data_to_save(). file_name: str, required Path and file name to where save file. It should not include...
02726bad42bc3817bbae5dbaf6252744361ee020
675,691
def formatargvalues(args, varargs, varkw, locals, formatarg=str, formatvarargs=lambda name: '*' + name, formatvarkw=lambda name: '**' + name, formatvalue=lambda value: '=' + repr(value)): """Format an argument spec from the 4 values ret...
e649df3304da0687090e7e0520724b72edaff1d4
675,692
def get_roi_names(contour_data): """ This function will return the names of different contour data, e.g. different contours from different experts and returns the name of each. Inputs: contour_data (dicom.dataset.FileDataset): contour dataset, read by dicom.read_file Returns: roi_se...
431e52f70a1153af164f9babb6066bb52661a8f7
675,693
def is_empty(any_structure): """Helper method to check if structure is empty.""" if any_structure: return False else: return True
e9287105f3742f7d7255b28fdc76635059a25a87
675,696
def shift_induction_times(exp, min_start=20, min_end=30): """ Shifts the induction start and end times forward or backward by separately specified numbers of minutes. Returns an experiment object with a new induction record. :param min_start: int Number of minutes to shift induction start ...
2a0469c8cd1e15ea6938466ab2d4065b5fa1fc05
675,697
def phalf_from_ps(bk, pk, ps): """Compute pressure of half levels of hybrid sigma-pressure coordinates.""" return ps*bk + pk
e664515195412c46fbef8d509c2b214c57c49cbb
675,699
def get_shape_points(cur, shape_id): """ Given a shape_id, return its shape-sequence. Parameters ---------- cur: sqlite3.Cursor cursor to a GTFS database shape_id: str id of the route Returns ------- shape_points: list elements are dictionaries containing th...
35dba0d08c6f3e1fc53e3301f8fc9b0337fa2caf
675,705
def preprocess_rsa_key(key_str): """Make Android and iOS RSA keys compatible with cryptography library. Android and iOS have slightly wonky, non-standard key formats. This updates the key to be standardized and compatible with pyca/cryptography. """ if key_str.startswith("-----BEGIN CERTIFICATE"): ...
12edbe5b9ba34c4d1b483f25058f75109e1fc4c2
675,707
import random def reproduce(parent1, parent2): """generate offspring using random crossover""" # random crossover point crossover = random.randrange(0, len(parent1)) # construct children child1 = parent1[0:crossover] + parent2[crossover:] child2 = parent2[0:crossover] + parent1[crossover:] ...
c366efecc2c61c3c1092ba73a54394cceb01e7ce
675,708
import torch def transfer_weights(tf_model, torch_model): """ Example function on how to transfer weights from tensorflow model to pytorch model Parameters ---------- tf_model : tensorflow model Weight donor torch_model : pytorch model (torch.nn.Modules) Weight recipient ...
e5eb62c796375cd280700754689cda2aa8c8df3f
675,709
def service_level(orders_received, orders_delivered): """Return the inventory management service level metric, based on the percentage of received orders delivered. Args: orders_received (int): Orders received within the period. orders_delivered (int): Orders successfully delivered within the p...
8132596dbb8e845aa116bb2451ef89761897b5db
675,713
def easy_emptylist(l): """Takes a list and returns True for empty list, False for nonempty""" return not l
6336d0750de4626b94861bbdfc7b53d27b85d518
675,716
def remove_dash(string): """ Removes the dash from the end of the string if there is one there. :string: (str) an input string :returns: (str) input string with no dash at the end of it """ if string[-1]=='-': return string[:-1] else: return string
a7f53417710cf9d8af2e2a96365e618c33a84136
675,717
def skewed_percentile_to_label(percentile): """ Assigns a descriptive term to the MMSE T-score based on its degree of skewness. """ if percentile > 24: return 'WNL' elif 9 <= percentile <= 24: return 'Low Average' elif 2 <= percentile <= 8: return 'Below Average' elif...
a1a6ea02c899b734f39f8f6d87477304f758ec41
675,719
import torch def lossFunctionKLD(mu, logvar): """Compute KL divergence loss. Parameters ---------- mu: Tensor Latent space mean of encoder distribution. logvar: Tensor Latent space log variance of encoder distribution. """ kl_error = -0.5 * torch.sum(1 + logvar - mu.pow(2) ...
2a9cc400d9a357f69f3f9964304c4cbc0ac4331e
675,721
def deleted_genes_to_reactions(model, genes): """ Convert a set of deleted genes to the respective deleted reactions. Arguments: model (CBModel): model genes (list): genes to delete Returns: list: list of deleted reactions """ if isinstance(genes, str): genes = [ge...
22cd57d35efe6b02aaa0cb3d5e05b9f817f63d10
675,723
def paramsDictNormalized2Physical(params, params_range): """Converts a dictionary of normalized parameters into a dictionary of physical parameters.""" # create copy of dictionary params = dict(params) for key, val in params.items(): params[key] = val * (params_range[key][1]-params_ran...
f6608cf5b79ca7a0170efc34c98cc651289b6584
675,724
def REDUCE(_input, initial_value, _in): """ Applies an expression to each element in an array and combines them into a single value. See https://docs.mongodb.com/manual/reference/operator/aggregation/reduce/ for more details :param _input: Can be any valid expression that resolves to an array. :...
730433e32b7d99de794589064bb0a31394ae7b34
675,726
def linear(x: float) -> float: """ Linear activation function (simply returns the input, unchanged). """ return x
79e10846702d1364794c1b26c14192ae55409a10
675,727
def _pop_next_function(function_list): """Pops and returns the next function in the list.""" if not function_list: raise IndexError('in _pop_next_function: list of functions is empty') return function_list.pop(0)
74dfefcc02b1e8fcccaecdaaff6577d9b1473a17
675,732
def get_symbols(bv): """Return all symbols in binary. Args: bv (BinaryView): top-level binary view handler. Lots of interesting methods can be accessed. Returns: list: list of symbols in binary. """ total_symbols = list() for s in bv.symbols.values(): ...
9c49f2f7eda28635b122a7f12cd144192851afbb
675,733
def _flatten_list(nested_list): """ Given a nested list, returns flat list of all its elements :param nested_list: nested list :return: flat list """ if not isinstance(nested_list, list): return [nested_list] res = [] for sub_list in nested_list: res += _flatten_list(su...
036cc48295e8898c99dcf3b2688c746e0636bb23
675,735
def dict_subset(d, keys): """Return a dict with the specified keys""" result = {} for key in keys: if '.' in key: field, subfield = key.split('.', 1) if isinstance(d.get(field), dict): subvalue = dict_subset(d[field], [subfield]) result.setdef...
2e0053d68a911405379602f7b0db62a51a99edfa
675,737
def ALMAGetBandLetter( freq ): """ Return the project observing band letter from frequency * freq = Frequency in Hz """ if freq<117.0e9: return "A3" elif freq<163.0e9: return "A4" elif freq<211.0e9: return "A5" elif freq<275.0e9: return "A6" elif fre...
db544516104a3c993d9977fadb929177bdf15a0e
675,738
import requests def is_active(url:str) -> bool: """Checks if the url we are parsing is active link. Args: url (str): [description] Returns: bool: True if get a 200 response else """ resp = requests.get(url) return True if resp.status_code == 200 else False
350fa7a7daf5d15d88c3c0ef52cb92bc1aa45c63
675,739
def is_peer_tuple(p): """Is p a (str,int) tuple? I.E. an (ip_address,port)""" if type(p) == tuple and len(p) == 2: return type(p[0]) == str and type(p[1]) == int else: return False
80e4d1c9774efa9a7616eb1d90eceba0ae764d29
675,742
def convert_to_int(s): """ Convert string to integer :param s: Input string :return: Interpreted value if successful, 0 otherwise """ try: nr = int(s) except (ValueError, TypeError): nr = 0 return nr
9f1538cab692a0f50fcbc8d5662057dfea7975f7
675,744
def create_language_method(language_code): """ Creates a manager method that filters given language code """ def get_language(self): return self.filter(i18n_language=language_code) return get_language
fd0b5d9d9d07fb59f874b9178cd1bd34a72bbe2e
675,748
def addArray(pdo, field, vtkArray): """ Adds an array to a vtkDataObject given its field association """ # Point Data if field == 0: pdo.GetPointData().AddArray(vtkArray) # Cell Data: elif field == 1: pdo.GetCellData().AddArray(vtkArray) # Field Data: elif field == 2:...
feff6377e444ac9187803f07aff55d887574aa92
675,749
def to_bytes(value, bytes_num, order='big', signed=False) -> bytes: """ Convert value to bytes representation. # Arguments value: int, Value to be converted. bytes_num: int > 0, Number of bytes in representation of `value`. Must be sufficiently big to store `value` order: 'big' or 'small', Ordering of byte...
c959a29ed15a73e1975e91602f75fba4356343cb
675,753
def bunch(**kw): """ Create object with given attributes """ x = type('bunch', (object, ), {})() for k, v in kw.items(): setattr(x, k, v) return x
15aa82f415b2b56564fdb8e0189720b9044c670c
675,755
def str2seq(st, func=int, sep=None): """ "1 2 3" -> [func('1'), func('2'), func('3')]""" # XXX check usage of this, check if we need list() at all if sep is None: return list(map(func, st.split())) else: return list(map(func, st.split(sep)))
ad04cef546f3048e6213504c1b8933cb6c503368
675,756
def detection_collate_fn(batch): """ Collate function used when loading detection datasets using a DataLoader. """ return tuple(zip(*batch))
562f1e5ff4eec8e47ed8f1464e5b6b58e0e55b0c
675,757
def set_combinations(iterable): """ Compute all combinations of sets of sets example: set_combinations({{b}},{{e},{f}}) returns {{b,e},{b,f}} """ def _set_combinations(iter): current_set = next(iter, None) if current_set is not None: sets_to_combine_with = _set_combin...
853d9c686f93a9dc21c1041fdcd440ab23488e28
675,758
def _tuple_2_id(num_single, idx): """Transfrom from tuple representation to id. If idx is a tuple representation of a member of a couple, transform it to id representation. Otherwise do nothing. Raises: TypeError if idx is neither an integer or a tuple """ if isinstance(idx, int): return idx el...
2f507cb929f68247c5945c4ad10ecbb4974d5605
675,761
def remove_title(soup): """ Remove the title element and return the str representation. Args: soup (BeautifulSoup): HTML parsed notebook. Effect: Changes soup object to have title (h1) element removed. Returns: (str): Title text """ title = str(soup.h1.contents[0])...
dfe068dda48c70c270e2021417e5c03c77f7ebe7
675,762
def translate_points(points, translation): """ Returns the points translated according to translation. """ return points + translation
6fc11502b47249c9b97e8e5a9d88f19c8db23fcd
675,765
def _check_byte_size(size: int) -> bool: """ Checks whether size is a valid size. Sizes include None or >= 0 :param size: The size to check :type size: int :return: Whether the size is valid :rtype: bool """ if size is None: return True return size >= 0
83921b744887b71a6303e8c4169fcf0ff9671ce7
675,768
def _check_boolean(input, name): """Exception raising if input is not a boolean Checks whether input is not ``None`` and if not checks that the input is a boolean. Parameters ---------- input: any The input parameter to be checked name: str The name of the variable for prin...
b9fb435efc9a2b22384f570f0fa5d5462c07a6a9
675,769
def time_at_timestamp(timestamp_ms: int) -> float: """Convert millisecond Epoch timestamp to Python float time value. Args: timestamp_ms: Epoch timestamp in milliseconds. Returns: Python time value in float. """ return float(timestamp_ms) / 1000.0
0b86d35a6a957c1c83326e852a647c9fc4b52a87
675,772
def args_to_str( args, positional_arg=None, fields=None, to_flag=True, arg_joiner=' ', val_sep=' ', list_joiner=' ', ): """Convert an argparse.ArgumentParser object back into a string, e.g. for running an external command.""" def val_to_str(v):...
701efd4dfbadde94ee80b78504db720ac52d33a2
675,775
def _acer_input(endfin, pendfin, aceout, dirout, mat, temp=293.6, iprint=False, itype=1, suff=".00", header="sandy runs acer", photons=True, **kwargs): """Write acer input for fast data. Parameters ---------- endfin : `int` tap...
53bd10121eb09de1185b1a2ba6aaa7adfe2bd10e
675,776
def _splitnport(host, defport=-1): """Split host and port, returning numeric port. Return given default port if no ':' found; defaults to -1. Return numerical port if a valid number are found after ':'. Return None if ':' but not a valid number.""" host, delim, port = host.rpartition(':') if not...
a8af9a33b603d7e0b39bf2130c0eaf1e718f9589
675,777
def create_draft_files_bp(app): """Create draft files blueprint.""" ext = app.extensions["invenio-rdm-records"] return ext.draft_files_resource.as_blueprint()
9d55a6dc1b1ff1678d3a72c6757245e68d7240db
675,779