content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def rm(x, l): """List l without element x.""" return [y for y in l if x != y]
8a5967f446b3b514eeef5c1cd693c35d6cf927a6
576,213
import threading def threaded(call, *args, **kwargs): """Execute ``call(*args, **kwargs)`` in a thread""" thread = threading.Thread(target=call, args=args, kwargs=kwargs) thread.start() return thread
6c16d5bfcf9eb037169d1b4e6958d46e2fc6abe9
576,214
from typing import Iterator import json def dictsets_match(dictset_1: Iterator[dict], dictset_2: Iterator[dict]): """ Tests if two dictsets match regardless of the order of the order of the records in the dictset. Return is True if the sets match. Note that this will exhaust a generator. Paramet...
c966c553096851c876f4f4f14675073f861d3372
576,215
def isoverlap(tup1, tup2): """ Determine if two intervals overlap. """ return (tup2[0] <= tup1[0] <= tup2[1]) or (tup1[0] <= tup2[0] <= tup1[1])
c0f9f7dcd0ece040bfa202e9ab572c9010088af8
576,223
def get_contig_lengths(in_fai): """ Get contig lengths from a fasta index. """ lens = dict() with open(in_fai, 'r') as f: for line in f: L1 = line.rstrip().split('\t') lens[L1[0]] = int(L1[1]) return lens
a4bc755435f38f62fd907e0c1aada8b1114be104
576,228
import torch def weighted_l2(y_item, y_pred, weights): """ calculate weighted l2 loss for pytorch input Arguments: ---------- y_item : torch array (N*,) array of true leave values (either probability or regression values) y_pred : torch array (N*,) array of predicted values fo...
275446b399a41dad11509caa6ca905b333f07661
576,231
def get_tag_keys_and_values(list_of_tags): """Creates a dictonary of all the tag keys and values from the list of tags provided. If list_of_tags is: [ {'n': 0, 'foo': 'bar'}, {'n': 1}, {'n': 2, 'foo': 'bar'}, ] The returned dictonary will be: { 'n': [0, 1, 2], ...
9f1d63b1de460f805deec415719694926f799f43
576,234
def iteritems(adict): """Return iterator over items in adict. Compatibility wrapper for Python 2 and 3. """ if hasattr(adict, 'iteritems'): return adict.iteritems() else: return adict.items()
19177098daac17e1a0d151e3fb787e58bea51aeb
576,237
def calculate_score(score: int, threshold: int) -> int: """ Calculates and converts X-Force Exchange score into Demisto score. Args: score (int): the score from X-Force Exchange for certain indicator (1-10). threshold (int): the score threshold configured by the user. Returns: ...
b76888929fc028f4afbd542e4e4c57f31db4daac
576,238
def to_line_equation(coefs, p): """ Substitutes point p into line equation determined by coefs :param coefs: list or tuple of 3 elements (or anything that can be unzipped to 3 elements) :param p: point :return: A * p.real + B * p.imag + C """ A, B, C = coefs return A * p.real + B * p.ima...
fc1561f9e7bdffb76570afd15641958b8b26eb52
576,243
def get_temp_instances(task_instance): """Returns the temp file location from the prior task""" return task_instance.xcom_pull(task_ids="process_symphony.download_symphony_marc")
0ed94bdf6db0aabec76c68e311bf3f6327048e45
576,244
def get_tcp_parameters(tcp_layer): """ Extract the tcp parameters that are relevant to OS detection from a TCP layer :param tcp_layer: a TCP packet (scapy.layers.inet.TCP) :return: tuple - tcp parameters. (win_size, mss) """ if tcp_layer is None: return None win_size = tcp_layer.window mss = dict(tcp_layer.op...
9899913ee32f4e1154a0b4ebfda8a6b66b3e4007
576,245
def extract_arxiv_links(urls): """ Try to find an arXiv link from a given list of URLs. :param urls: A list of URLs. :returns: First matching arXiv URL, or ``None``. """ arxiv_urls = [url for url in urls if "://arxiv.org" in url] if len(arxiv_urls) > 0: return arxiv_urls[0] else...
7ed45403c9ef0ef25d09437c4890f6d464e42005
576,246
def denormalize(reference, series, normalized_variable='close_point_relative_normalization', denormalized_variable='close'): """ Denormalizes the values for a given series. Parameters ---------- reference: pd.DataFrame DataFrame to use as reference. This...
c51cb47191672e6b399c17c379e35474e31fea9f
576,247
def enlarge_bbox(bbox, dx=0.0, dy=0.0): """Symmetrically enlarge bounding box. :type bbox: list :param bbox: bounding box :type dx: float :param dx: horizontal delta :type dy: float :param dy: vertical delta :rtype: list :return: new bounding box """ x0, y0, x1, y1 = bbox return [x0 - dx / 2...
30562fc80c7de61e2bb03cc0ccffca22f9001492
576,250
def into_keywords_format(keywords: dict) -> list: """Convert a dictionary of keyword, counter pairs into a list of dicts. Args: keywords: A dictionary that contains a counter for every keyword. Returns: The keywords in the format specified in wrapper/output_format.py. """ keywords_...
1f50d61cebf3c685f60e15b292eeb4130da0ed9e
576,251
def convert_range_to_list(x): """ Returns list of numbers from given range as string e.g.: convert_range_to_list('3-5') will give [3, 4, 5] """ # pylint: disable=C0103 result = [] for part in x.split(','): if '-' in part: a, b = part.split('-') a, b = int(a),...
ff7ae6b193e9bfc20a7934cb024f8048d56a2ee2
576,252
import torch def aggregate_sum(X, adj, self_loop=False, device='cpu', avg_d=None): """ Aggregate each node by the sum of it's neighbours, weighted by the edge between the nodes. Parameters -------------- X: tensor(..., N, N, Din) Input feature tensor to aggregate. adj: tens...
c900ad2444f8d25fd7ad997fc0a23029b35b1d9e
576,258
def integration_files_dir(salt_factories): """ Fixture which returns the salt integration files directory path. Creates the directory if it does not yet exist. """ dirname = salt_factories.root_dir.join("integration-files") dirname.ensure(dir=True) return dirname
cdc3cf1964778f95d76b61dd9a5740c6029c4df3
576,259
from typing import Optional def run_episode(game, learner, train: bool = True, s0: Optional[list] = None) -> float: """Run an episode of `learner` on `game` Args: train: True if learner is training, False for evaluation s0: The start state of the game, None means random start Returns: ...
7b1746385e99839b9043d312efb3a09192f4dba5
576,262
import re def verbose_namer(name, make_friendly=False): """ Removes all values of screendoor IDs from the column name. Optionally this will make the column name friendly by removing dashes/underscore with spaces. """ if name.endswith("contactmetadata"): return "Contact MetaData" el...
9ada00ca977588288dd3be327c434dd16b632656
576,265
def safe_divide(x: float, y: float) -> float: """This returns zero if the denominator is zero """ if y == 0.0: return 0.0 return x / y
dd438cbba16f739157b21a7bdd0e8b34cf7d0c71
576,274
def common_filters(marker=None, limit=None, sort_key=None, sort_dir=None): """Generate common filters for any list request. :param marker: entity ID from which to start returning entities. :param limit: maximum number of entities to return. :param sort_key: field to use for sorting. :param sort_dir...
7c7852f2dc8458801fa02408fd21c956af547420
576,276
def subsample(df, freq=2): """ Subsample the original data for reduced size :param df: df, dat :param freq: int, every freq item will be taken :return: df, subsampled df """ df = df.iloc[::freq, :] return df
5ffde37406d73ed02a99bcedf098fe3781dcdb37
576,277
def render_nullbooleanfield(field, attrs): """ Render NullBooleanField as dropdown. ("Unknown", "Yes", "No") """ field.field.widget.attrs["class"] = "ui dropdown" return field
afbc5d5e46fb837569c411795aaf5db004b84982
576,279
def has_smach_interface(obj): """Returns True if the object has SMACH interface accessors.""" return (hasattr(obj, 'get_registered_input_keys') and hasattr(obj, 'get_registered_output_keys') and hasattr(obj, 'get_registered_outcomes'))
585f5fe64e63e4658f22c0da9238c2179ca7db84
576,284
def unique3(s, start, stop): """Return True if there are no duplicates elements in slice s[start:stop].""" if stop - start <= 0: # at most one item return True elif not unique3(s, start, stop - 1): # first part has duplicate return False elif not unique3(s, start + 1, stop): # second...
881c65d2cce5036a7c9cfd854293cb52cd77bec5
576,285
def _read_rest_frequency(header): """Read the rest frequency in [Hz].""" try: nu = header['restfreq'] except KeyError: try: nu = header['restfrq'] except KeyError: nu = header['crval3'] return nu
023c85823d0055b772d8be86078903948754c60f
576,287
from typing import Sequence def tosequence(x): """Cast x to sequence. Returns x if at all possible.""" return x if isinstance(x, Sequence) else list(x)
1e6a966f9df91ea2be470337d21ab53aca2131bf
576,288
import colorsys def create_unique_color_float(tag, hue_step=0.41): """Create a unique RGB color code for a given track id (tag). The color code is generated in HSV color space by moving along the hue angle and gradually changing the saturation. Parameters ---------- tag : int The uni...
5103fa8fd6706d71350f0366f654d509c1855ca1
576,291
def eat_char(text_string, char_set): """ Eats the specified subset of characters from the beginning of the string and returns index when done eating :param text_string: :param char_set: :return: index into its string where no char_set are found """ idx = 0 for this_char in text_string: ...
697386188d54611c546f8645d2940a4bbb963343
576,295
def grompp_nvt(job): """Run GROMACS grompp for the nvt step.""" nvt_mdp_path = "nvt.mdp" msg = f"gmx grompp -f {nvt_mdp_path} -o nvt.tpr -c em.gro -p init.top --maxwarn 1" return msg
57de170978cf561df5665e7466d8649b2ca932af
576,296
def _get_time_series_params(ts_value_names, ts_values): """_get_time_series_params Converts data in ts_value_names and ts_values into the value_names and time_series_value_counts properties of the Facet API. ts_value_names is a dictionary mapping value names (such as True or '10-19') to numbers by ...
4178207b3b29d32231213c6da473c9ac6dbba41b
576,299
def line_wrap(text, indent=0, max_len=78, string=False): """Return a wrapped line if length is larger max_len. The new parameter 'string' allows to wrap quoted text which is delimited by single quotes. It adds " '" to the end of the line and "'" to the start of the next line. """ split_len = ma...
48cc691d561421f9b7e34b5795cefec87de02ba6
576,303
def dotp(a, b): """Dot product of two equal-dimensioned vectors""" return sum(aterm * bterm for aterm,bterm in zip(a, b))
502fba46bf2284a1b7d48572c38cef1d1a188c11
576,307
def parse_time_cmd(s): """ Convert timing info from `time` into float seconds. E.g. parse_time('0m0.000s') -> 0.0 """ s = s.strip() mins, _, secs = s.partition('m') mins = float(mins) secs = float(secs.rstrip('s')) return mins * 60.0 + secs
273ba26145502860be21072538f3416cda143564
576,308
import math def get_coords(theta, range): """ This maps polar to rectangular coordinates given the LiDAR's frame of reference. We rotate 90deg to right to reorient to polar origin :param theta: LiDAR theta :param range: LiDAR range :return: """ y = math.cos(theta)*range x = -1 * ma...
9abb046a2a4e8bf7098d0fa0f64cbc5b832306fc
576,309
def gettuples(records,languages): """ return a tuple of the ID and all renderings in all selected languages """ languages = [0,3]+languages #print(languages) return [records[l] for l in languages]
6b2144f2eb0ee448ed75e077aac295c93fbbf752
576,310
def unique_sorted_values_plus_ALL(array): """Obtain a sorted array of all unique values in an array, including an additional value of 'ALL' to denote all values. Args: array (list|pd.Series|np.array): An array of values. Returns: list: A sorted array of unique values including an additiona...
5c5a7ddfd5532f396dbae56b0f29d06dc8689759
576,318
def fmap_to_graphmap(G, H, f): """ Takes source and target Graphs and a numeric map (list) from homsearch_interface, returns G-H-vertex map. Vertices assigned -1 are given None """ # Work for Sage and NetworkX try: Gvs = G.vertices() except AttributeError: Gvs = G.nodes() ...
baf271eadb4503d463a64fdb327590fb5d2f37da
576,322
import hashlib def valid_proof(last_hash, proof): """Validates the Proof. Multi-ouroborus: Do the last five characters of the hash of the last proof match the first five characters of the hash of the new proof? IE: last_hash: ...AE912345, new hash 12345E88... """ guess = str(proof).encode()...
3fcd96379ff38e08bb3e760c14dd45a928cb2ba7
576,323
def compute_trajectory(cpu_status, mem_status): """ Function to alert whether mutliple resources are crossing thresholds or not. Args: cpu_status: Keyword 'High', 'Normal' or 'Low' mentioning the status of cpu mem_status: Keyword 'High', 'Normal' or 'Low' mentioning the status of memory Re...
6986eb577e5322e67d0917250048a00841d47297
576,330
def _search_document_to_dict(doc): """Converts and returns the search document into a dict format. Args: doc: Document. The document to be converted into dict format. Returns: dict(str, str). The document in dict format. """ d = {'id': doc.doc_id, 'language_code': doc.language, 'ra...
763a0a875a86e739dd349bd08e6c6dfbc7cd9fdc
576,333
import textwrap def format_warning( test_id: str, warning: str, ) -> str: """ Formats warning messages for a single endpoint. Example Output: basic.get_private_listing /path/to/file.py:345 Warning: This is a warning message! """ if not warning: return '' retu...
5661400927c8e388f688fdd6c1de99729d7b5fda
576,338
def get_tasks_args(parser): """Provide extra arguments required for tasks.""" group = parser.add_argument_group(title="tasks") group.add_argument( "--epochs", type=int, default=None, help="Number of finetunning epochs. Zero results in " "evaluation only.", ) ...
3aa3752f30e3f4194de3d6dcc2cb03590ef9e26b
576,339
def polygon_to_lonlat(polygon): """Convert a WKT polygon string to a tuple of lat and lon lists. Parameters ---------- polygon : str A WKT polygon string. Returns ------- tuple of lists A 2-tuple containing a list of longitudes and a list of latitudes. """ poly_coor...
1ac896513fc1a93b343ef59cc29b212c1b05519e
576,341
def isVowelStart(str): """ A utility function to return true if the first letter in the str is a vowel """ retval = False if str and len(str) > 0: vowels = ['A', 'E', 'I', 'O', 'U'] firstLetter = str.upper()[0:1] if firstLetter in vowels: retval = True return ...
0f7a44e8c66fb8dea1ecadc37f8419441d17f50f
576,343
def get_neighbor_distances(net, v): """Create a lookup of neighbors with distances for dijkstra. Parameters ---------- net : tigernet.Network v : int Source node for iteration of neighbors. Returns ------- neighbors : dict Lookup dictionary in the form ``{neighor_ID: n...
bdc41c0deba2b566570dde6240077f96a757a088
576,346
import re def extract_initials(names): """Extract a list of initials from names. Parameters ---------- names : str or list of str Names (in one long string, or divided into elements of a list) from which to extract initials. Each name in names can be a full name or initial. In...
7844ef6563b5c9a0c5b473a17784c859e5085426
576,347
def levenshtein_2d_blocks(string, transpositions=False, flag1='\x00', flag2='\x01', flag3='\x02'): """ Function returning the minimal set of longest Levenshtein distance <= 2 blocking keys of target string. Note that this method is basically a generalization of the `levensthein...
c6e0d5fb80bc49d85a73c223390f1bae1e372660
576,352
def trace(X_ref, Y_ref): """ Calculates the slope and intercept for the trace, given the position of the direct image in physical pixels. These coefficients are for the WFC3 G141 grism. See also: https://ui.adsabs.harvard.edu/abs/2009wfc..rept...17K/abstract """ BEAMA_i = 15 BEAMA_f = 196 DYDX_0_0 = 1.96882E...
3c6b0aa978f9758f7777a9729fb3c1999b64ffe9
576,353
def sample_func(word: str): """ this is a sample func for demonstration of numpy docstring and import methods Parameters ---------- word : str this is any string word to pass in function Returns ------- str this is output with some added text to word """ output...
cf19d5d95fba7a34311dc35332b29603ab61b9a1
576,364
def identity(x): """ The identity link function given by $$ y = x $$ """ return x
9de6736d7fb2fb4240a61a5f8596f1393b6c5cb4
576,369
import pickle def get_all_names_set(participants_file_path): """ Given the path of a file that contains all documents with their participants, extract a set of all participant names """ with open(participants_file_path, 'rb') as f: gva_input_annotations = pickle.load(f) all_names=set...
6726b942935418ba34557d2556038f9ef3e7e35c
576,376
def PyInt_FromSsize_t(space, ival): """Create a new integer object with a value of ival. If the value is larger than LONG_MAX or smaller than LONG_MIN, a long integer object is returned. """ return space.wrap(ival)
aaa65a95e122db8485400a1aad8a5cf3e08fedd0
576,378
def calculate_performance_score(stat_arr, beta): """Calculate F beta, or precision or TPR Args: stat_arr (np.array): arr([tp, fp, fn]) beta (int): non-negative int for F beta score Returns: Precision (float): for beta = 0 F_beta (float): for 1 <= beta <= 100 TPR (flo...
c1dc3b6dd1c7d625f8c3ecf7b1129a0afbeac9de
576,379
def parse_priv_from_db(db_privileges): """ Common utility function to parse privileges retrieved from database. """ acl = { 'grantor': db_privileges['grantor'], 'grantee': db_privileges['grantee'], 'privileges': [] } privileges = [] for idx, priv in enumerate(db_priv...
e84a2f234c4c428d13fc3645438ae07250281052
576,383
def half_adder(a, b): """Representation of half adder ALU logic Args: a (binary integer): Either 0 or 1 b (binary integer): Either 0 or 1 Returns: tuple: (sum, carry) """ return (a^b, a and b)
c041b5a40580daad1fc8890c3041d193745d4fbd
576,385
def sum_floats(nums): """Return sum of floating point numbers in nums. >>> sum_floats([1.5, 2.4, 'awesome', [], 1]) 3.9 >>> sum_floats([1, 2, 3]) 0 """ # hint: to find out if something is a float, you should use the # "isinstance" function --- research how ...
e6d50f8b2baad03bff3ef91a5f13bedc8e563838
576,386
def parse_illumina_trimstats(path_to_trimstats): """Parse illumina trimstats into a dict. Args: path_to_trimstats: path to file that contains illumina trimstats Returns: dict with trimstats qc metrics Raises: AssertionError if a row that splits into number of tokens other than 2 ...
b7390f3b44854e6fb6390be02e8903f2170bb37e
576,389
def to_video(tensor): """ Takes generator output and converts it to the format which can later be written by SummaryWriter's instance input: tensor of shape (N, C, D, H, W) obtained passed through nn.Tanh """ generated = (tensor + 1) / 2 * 255 generated = generated.cpu() \ ...
890375a21d3ee6994c116991d89b09456e0d0242
576,391
import dill def load_config_from_file(name): """Loads an experiment config from file""" with open(name, "rb") as config_file: return dill.load(config_file)
2368a717400e6d653044ac25cfd0f48a96f4e74d
576,398
def pskToString(psk: bytes): """Given an array of PSK bytes, decode them into a human readable (but privacy protecting) string""" if len(psk) == 0: return "unencrypted" elif len(psk) == 1: b = psk[0] if b == 0: return "unencrypted" elif b == 1: return ...
a47797e8658aa5f175bff3b7d452528aeeeb8bee
576,402
def cubicInterpolate(v0, v1, v2, v3, alpha): """ Cubic interpolator. Gives better continuity along the spline than the cosine interpolator, however needs 4 points to interpolate. """ alpha2 = alpha * alpha a0 = (v3 - v2) - v0 + v1 a1 = (v0 - v1) - a0 a2 = v2 - v0 a3 = v1 return ...
09a71f23d91addf9a93ffa1c42b90f2bb6141e34
576,403
def horizontal_rule(length=79, style="_"): """Return a horizontal rule. Keyword arguments: length -- Specifies the length of the rule (default 79, minimum 3). style -- Character used for the rule (may be either "_" or "*"). If the length is too low, or the style is invalid, a ValueError is...
7865401259f794803e869e90983baab7cba66218
576,412
import re def get_dihedrals(qm_scan_file): """ Returns dihedrals from the torsiondrive scan file. Parameters ---------- qm_scan_file : str Output scan file containing torsiondrive scans. Returns ------- dihedrals : list List of all the dihedral values from the qm sca...
12f78bfc762d28ff9992f8300e62d658090a1834
576,416
import math def reset_state(state): """ The function to reset state array to initial values. Arguments: state: the array with state variables. Returns: The state array with values set to initial ones. """ state[0], state[1], state[3], state[4], state[5] = 0, 0, 0, 0, 0 stat...
29275d390d0afa6bd75c6c65f38721f5d6a9190c
576,421
def ask(description: str, strict: bool = False) -> str: """Ask for user input with description. If strict==True, then user must confirm given input. """ while True: value = input(description + ' >').strip() if strict: confirmation = input('Enter 1 for confirmation').strip()...
079109d21af5c26b6b73abe9ed1369fdc80a9760
576,422
def guess_rgb(shape): """ Guess if the passed shape comes from rgb data. If last dim is 3 or 4 assume the data is rgb, including rgba. Parameters ---------- shape : list of int Shape of the data that should be checked. Returns ------- bool If data is rgb or not. ...
bb3d8ccdac9cf8cd487af87ebf37384599f2e8d7
576,424
from datetime import datetime def dt_for_str(dt_string): """ Return datetime object from ISO 8601 string """ return datetime.strptime(dt_string, r"%Y-%m-%dT%H:%M:%SZ")
6559105f28a72cf0e49c9c7277bf2826d6fd3184
576,426
def sortresult(func): """ Decorator to wrap a function that returns a list to return a sorted list. """ def wrapper(*args, **kwargs): result = func(*args, **kwargs) return sorted(result) return wrapper
e4419912431b6d8abd1d24a67312f2a90c5f7602
576,428
def positive_negative(inputlist): """ return true if all items in the input list having same sign (+ or -)""" if ((all(item>0 for item in list(inputlist))) or (all(item<0 for item in list(inputlist)))): return True # elements with same sign (+ or -) else: return False
69ebde6129139f5212d50891b4b81c0a5a76d51f
576,430
def aggregate_labels(label_list): """ Join a list of label list. Args: labels (list): The input label list. Returns: labels (list): The joint list of all lists in input. """ all_labels = [] for labels in label_list: for label in labels: all_labels.append(l...
5b3397995a3a20e0f836ac944c755b06863d1a24
576,432
def stroke_width(width: float): """ Returns an SVG stroke width attribute using the given width. :param width: `float` stroke width :return: stroke-width="<width>" """ return f'stroke-width="{str(width)}"'
d6d3f4756d083cb4dbf3545df124bcd16db0bcbd
576,434
import difflib def diff_output(expected: str, actual: str) -> str: """ Compares the expected and actual outputs of a command Args: expected: desired output actual: STDOUT captured from command Returns: str: diff output """ # files read in are converted to "universal"...
cce18472d064196739fcfa0ea7a6a98256c5c20d
576,436
def convert_pid(value): """Convert pid from hex string to integer.""" return int(value, 16)
87eac744be5966046b5dbea6465832ce1f98a5a6
576,439
def list_intersection(list1, list2): """ Check if each value in list1 is also in list2 :param list1: :param list2: :return: a list containing the elements common to both the lists """ return [value for value in list1 if value in list2]
da3301e4cd1e1e091e8ce173c0a106938973bbd6
576,440
def calculate_age(seconds): """ Convert seconds to time period string e.g. 6000 -> 1 h 40 m """ m, s = divmod(seconds, 60) h, m = divmod(m, 60) return '%d h %02d m' % (h, m)
649ab2e7ac366327eb510406108659de228b8042
576,445
import re def munge_filename(name, mode='strict'): """Remove characters that might not be safe in a filename.""" if mode == 'strict': non_alphabetic = re.compile('[^A-Za-z0-9_.]') else: non_alphabetic = re.compile('[^A-Za-z0-9_\\-.=,:]') return non_alphabetic.sub('_', name)
d98d4de1bf7e5c06b2475e459230dca0bd2d8cb7
576,453
def read_cluster_file(cluster_file_dir): """Read the clustered pockets as a list of lists.""" f = open(cluster_file_dir, 'r') data_text = f.read() f.close() data_text = data_text.split('\n') while('' in data_text): data_text.remove('') clusters = [] for x in data_text: ...
d3af8426ad5c11b896036a07f420ccc79175ef90
576,455
def parse_snmp_return(ret, is_bulk=False): """Check the return value of snmp operations :param ret: a tuple of (errorIndication, errorStatus, errorIndex, data) returned by pysnmp :param is_bulk: True if the ret value is from GetBulkRequest :return: a tuple of (err, data) er...
075a50642222efef5677da47d37b7890a6e4745c
576,456
def UnixifyPath(file_path): """converts \ to /""" return file_path.replace("\\", "/")
3459dc3b17126ab06f6a476124e9a92a7efc5ed6
576,459
def _extension(platform): """Get the init extension for a platform.""" if platform == 'windows': return '.ps1' return '.bash'
4b540d932cff344087258c909f14f7893818a2a7
576,461
def resolve(name, user_config, flags, default=None): """Resolve the provided option from either user_config or flags. If neither is set, use the default. If both are set, the flags take precedence. """ answer = user_config.get(name, default) if getattr(flags, name, None): answer = getat...
5abadd22c82fccd0002e26754a97eb6c645035ab
576,465
def _process_predictions(y, y_pred1, y_pred2): """Pre-process the predictions of a pair of base classifiers for the computation of the diversity measures Parameters ---------- y : array of shape = [n_samples]: class labels of each sample. y_pred1 : array of shape = [n_samples]: ...
081fe86842d7ce69c9b25e6f760a61a48b046224
576,467
from datetime import datetime import calendar def dt_to_ts(value): """ If value is a datetime, convert to timestamp """ if not isinstance(value, datetime): return value return calendar.timegm(value.utctimetuple()) + value.microsecond / 1000000.0
6eb254d301630444ef9a0cb313cf25512ac21556
576,468
def radius_from_volume(volume: float, dim: int) -> float: """Return the radius of a sphere with a given volume Args: volume (float): Volume of the sphere dim (int): Dimension of the space Returns: float: Radius of the sphere """ if dim == 1: return volume / 2 el...
22d8c4e6b2567465f0aaf5fd5fac1d4429ec3754
576,473
import random def get_quadrant_from_class(node_class): """Return the ID of the segment of the plane corresponding to a class.""" up, edge_type, _ = node_class if up == 0: return 0 if random.random() < 0.5 else 7 mappings = {(-1, 'modification'): 1, (-1, 'amount'): 2, ...
291d1b7bf3cd641fd5793034823e753fd547c5b6
576,477
import torch def smooth_l1_loss(bbox_pred, bbox_targets, bbox_inside_weights, bbox_outside_weights, beta=1.0): """ SmoothL1(x) = 0.5 * x^2 / beta if |x| < beta |x| - 0.5 * beta otherwise. 1 / N * sum_i alpha_out[i] * SmoothL1(alpha_in[i] * (y_hat[i] - y[i])). N is the numbe...
04b809b51b1cd5fe3aab4a3c8b5288752932cd06
576,479
def Decimal2Binary(dec_num): """ Return the binary representation of dec_num """ if dec_num == 0: return '0' return (Decimal2Binary(dec_num >> 1) + str(dec_num % 2))
b6767154a32e7d23647d800bda808d4c965f16b2
576,480
def every_pred(*preds): """ Makes a super-predicate from the passed ones. A super-predicate is true only if all the child predicates are true. The evaluation is lazy (like bool expressions). """ def composed(val): for pred in preds: if not pred(val): return Fa...
7a0f2939b06e5118f3606aea26f0a0f0ba12c958
576,484
from typing import Set from typing import Any def set_constructor(loader, node) -> Set[Any]: """ A constructor for !set yaml tags, returning a python set object """ value = loader.construct_sequence(node) return set(value)
ccc7aabf6649e9f80f6f6b6ed581da44920dcc13
576,485
def calculate_bearing_difference(current_bearing, previous_bearing): """Calculate the difference between two bearings, based on bearings between 0 and 360.""" difference = current_bearing - previous_bearing while difference < -180: difference += 360 while difference > 180: difference -...
e344ce60c95a12385329c1886c8baae0f2d9c4df
576,487
def index_modifier(index, modifier, index_mod=0): """ Modify and index based on the sub division, whilst also allow to modify the current index by an int """ return (index + index_mod) + ((index + index_mod) * modifier)
f787e7778f4e9c1f17bae771732e46fcc92552c3
576,489
import copy def extract(d, path=None): """ extract section of dictionary Parameters ---------- d : dict path : list[str] keys to section Returns ------- new_dict : dict original, without extracted section extract_dict : dict extracted section Examples...
0f5280185dcb4a6af6eeae37fd2219e71deb9c1a
576,490
import socket def IsIP4Addr(addr): """Returns True for valid dotted-quad IPv4 addresses like 1.2.3.4.""" try: socket.inet_pton(socket.AF_INET, str(addr)) except socket.error: return False return True
3e8a4b0b0a7188c269521e35e9c80d8bb6beff2a
576,495
def validate_iyr(value: str) -> bool: """issue year must be an int between 2010 and 2020, inclusive""" try: return int(value) in range(2010, 2021) except (TypeError, ValueError): return False
11efec82c8d4c235eda6405ed5e04d699abb97bc
576,500
import torch def if_def_when(lossyear, year, cutoffs=[2, 5, 8]): """ Creates categorical variables for deforestration event given cutoffs. Values in cutoffs define the time bins Returns len(cutoffs) + 1 categorical layers: Example: cutoffs = [2,5,8], num of layers = 4 , considered year = year ...
6ab4bf61341f7d86fe305f6eca82d457b9ff0769
576,502
def datenum_to_season(path, datenum): """ Transform %Y%m%d into %Y%SEASON, e.g. 20180506 --> 2018S2 """ month_season_table = {"01":"S1", "02":"S1", "03":"S1", "04":"S2", "05":"S2", "06":"S2", "07":"S3", "08":"S3", "09":"S3", "10":"S4"...
87ea8fe77e974856d3fb0ca2faacbccadd6b5ea5
576,503
import torch def div(input, other, *args, **kwargs): """ Divides each element of the input ``input`` by the corresponding element of ``other``. Examples:: >>> import torch >>> import treetensor.torch as ttorch >>> ttorch.div(ttorch.tensor([ 0.3810, 1.2774, -0.2972, -0.3719, 0.4...
4d09b1e870a0966f33e65d36b21461ec266e6858
576,506