content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def onek_unk_encoding(x, set): """Returns a one-hot encoding of the given feature.""" if x not in set: x = 'UNK' return [int(x == s) for s in set]
c788794770757e31f749e42cc61b15f86c632b96
668,518
def hamming_distance(str1, str2): """Computes the hamming distance (i.e. the number of differing bits) between two byte strings. Keyword arguments: str1 -- the first byte string str2 -- the second byte string """ distance = 0 for b1, b2 in zip(str1, str2): # xor in each place is...
5bc24c6ebf7b0d0f589e91b9f50617bb037c83a8
668,520
import fnmatch def is_copy_only_path(path, context): """Check whether the given `path` should only be copied and not rendered. Returns True if `path` matches a pattern in the given `context` dict, otherwise False. :param path: A file-system path referring to a file or dir that should be rend...
9dd45350a0a4df42923e50c06aca110fbcf40f38
668,521
def jaccard_coefficient(x,y): """ Jaccard index used to display the similarity between sample sets. :param A: set x :param y: set y :return: similarity of A and B or A intersect B """ return len(set(x) & set(y)) / len(set(x) | set(y))
d806a6e2a9e86d840eeba2709acd373e32c4801f
668,523
import ssl def get_ssl_context(account): """Returns None if the account doesn't need to skip ssl verification. Otherwise returns ssl context with disabled certificate/hostname verification.""" if account["skip_ssl_verification"]: ssl_context = ssl.create_default_context() ssl_context.c...
a4c095b3b843849d287eaf257e4b775f3391ac9c
668,525
def removeBelowValue(requestContext, seriesList, n): """ Removes data below the given threshold from the series or list of series provided. Values below this threshold are assigned a value of None. """ for s in seriesList: s.name = 'removeBelowValue(%s, %d)' % (s.name, n) s.pathExpression = s.name ...
52afb595f42de0c4a18fff60458bbdc012a57dcc
668,526
import requests def request_issues(url): """Request issues from the given GitHub project URL. Parameters ---------- url : str URL of GitHub project. Returns ------- response : Response Response data. """ response = requests.get(url) return response
9f33675d687941873d9b401ddd381894b8cdb3e2
668,527
def create_snapshot_dict(pair, revision_id, user_id, context_id): """Create dictionary representation of snapshot""" parent, child = pair.to_2tuple() return { "parent_type": parent.type, "parent_id": parent.id, "child_type": child.type, "child_id": child.id, "revision_id": revision_i...
2b773edd8ae64d1fd7fcf74b4fbb31b8902234c8
668,528
def new_evidence_file(network_filename, variable, value): """Creates a new evidence file for a given goal variable-value pair (and returns its filename).""" new_filename = network_filename + '.inst' with open(new_filename, 'w') as evidence_file: evidence_file.write( '<?xml version="1...
0faa00acc621da427540e41d215307bc369be253
668,529
def erd_encode_bytes(value: bytes) -> str: """Encode a raw bytes ERD value.""" return value.hex('big')
35c6f185f4626e3fa29a5476f44d600414bb73cd
668,531
def quaternion_is_valid(quat, tol=10e-3): """Tests if a quaternion is valid :param quat: Quaternion to check validity of :type quat: geometry_msgs.msg.Quaternion :param tol: tolerance with which to check validity :return: `True` if quaternion is valid, `False` otherwise :rtype: bool """...
486396802e1bb8386d8c0a722145d1feca3c14fa
668,533
def normalize_program_type(program_type): """ Function that normalizes a program type string for use in a cache key. """ return str(program_type).lower()
a22858f13708964f159b9b930aa289c9184661e1
668,534
def _strip_path_prefix(path, prefix): """Strip a prefix from a path if it exists and any remaining prefix slashes Args: path: <string> prefix: <string> Returns: <string> """ if path.startswith(prefix): path = path[len(prefix):] if path.startswith("/"): pa...
9cd4460ffd318600287300686de748141442e0d1
668,536
from typing import Optional def is_eof(char: Optional[str]) -> bool: """Check if a character is EOF.""" return char is None
089c2d04b2bf3be34707e1b4206b0537baadd9c8
668,537
def clean_backticks(msg): """Prevents backticks from breaking code block formatting""" return msg.replace("`", "\U0000ff40")
5ec8b60fc50b9f1eb5dd51cc1ce2b699be151413
668,539
def pythonify_metrics_json(metrics): """Converts JSON-style metrics information to native Python objects""" metrics = metrics.copy() for key in metrics.keys(): if key.endswith("_histogram") or key.endswith("_series"): branch = metrics[key] for sub_key in branch.keys(): ...
0c0339c83146aab6581061be1a07ba4c683eb2aa
668,540
def newline_to_br(base): """Replace newline with `<br />`""" return base.replace('\n', '<br />')
fe807e08a875358f8f8da0c422f1b43cd19f7e03
668,541
def is_key(sarg): """Check if `sarg` is a key (eg. -foo, --foo) or a negative number (eg. -33).""" if not sarg.startswith("-"): return False if sarg.startswith("--"): return True return not sarg.lstrip("-").isnumeric()
f61ef81e2f8bcbbb9e7b51f695f6a8c789abbd0a
668,547
def find_empty_cell(board): """ finds the empty cell going left to right, top to bottom on the board """ for i in range(len(board)): for j in range(len(board[0])): if board[i][j] == 0: return (i, j) return None
8c94c7b7d55376142b8d8dc0d8ac97c5c006e1c0
668,551
def splitLast(myString, chunk): """ returns a tuple of two strings, splitting the string at the last occurence of a given chunk. >>> splitLast('hello my dear friend', 'e') ('hello my dear fri', 'nd') """ p = myString.rfind(chunk) if p > -1: return myString[0:p], myString[p + len(chun...
6bdf7c2f3b16ca3b0885bdb41623183342c4d4af
668,553
def server_no_key(server_factory): """ Return a :class:`saltyrtc.Server` instance that has no permanent key pair. """ return server_factory(permanent_keys=[])
18614069c21af369eeb3d36f2993873ac0690572
668,557
def lower_tree(tree): """ Change all element names and attribute names to lower case. """ root = tree.getroot() for node in root.iter(): node.tag = node.tag.lower() attributes = dict() for attribute in node.attrib: attributes[attribute.lower()] = node.attrib[a...
c61737154a86ee62f0c825de5d006913c624d817
668,558
def _gr_text_to_no(l, offset=(0, 0)): """ Transform a single point from a Cornell file line to a pair of ints. :param l: Line from Cornell grasp file (str) :param offset: Offset to apply to point positions :return: Point [y, x] """ x, y = l.split() return [int(round(float(y))) - offset[0], int(round(flo...
b07a7587cc82ecc9b6a8796e0d09119086092ad7
668,559
def _PyDate_FromTimestamp(space, w_type, w_args): """Implementation of date.fromtimestamp that matches the signature for PyDateTimeCAPI.Date_FromTimestamp""" w_method = space.getattr(w_type, space.newtext("fromtimestamp")) return space.call(w_method, w_args)
bec844b8184c17c46c16a284bc56b8f140ab6e84
668,563
import time def beats(text): """- Gets the current time in .beats (Swatch Internet Time).""" if text.lower() == "wut": return "Instead of hours and minutes, the mean solar day is divided " \ "up into 1000 parts called \".beats\". Each .beat lasts 1 minute and" \ " 26.4 s...
83eee649e21fae5770cf6ed4729e7ad960ac14b8
668,564
def get_frame_interface(pkt): """Returns current frame interface id alias. """ iface_raw = pkt.frame_info._all_fields['frame.interface_id'].showname_value ifname = ".".join(iface_raw.split()[1][1:-1].split(".")[:2]) return ifname
e50d056db6743154d65c896ba646169a52f21fe4
668,566
import re def norm_key(key_name): """ Normalize key names to not have spaces or semi-colons """ if key_name: return re.sub('[;\s]', '_', key_name) return None
5ea501c15ca8bafc13f3148efe77eaeabdfb0a4c
668,568
import math def dB(x): """Returns the argument in decibels""" return 20 * math.log10(abs(x))
8f31606d217d0eacfced6dd42e1db50fe3d4f17f
668,574
def normalize_measurement(measure): """ Transform a measurement's value, which could be a string, into a real value - like a boolean or int or float :param measure: a raw measurement's value :return: a value that has been corrected into the right type """ try: return eval(measure, {}, {}...
aa918e06ee4e9ebceeb6597c5fdedd90aa20b5e6
668,576
def generate_entity_results(entity_class, count, **kwargs): """ generates entity results with given entity type using given keyword arguments and count. :param type[BaseEntity] entity_class: entity class type to put in result. :param int count: count of generated results. :rtype: list[BaseEntity] ...
de431eb24ac7d1a75a8c9ad862b780c22b7872a2
668,577
from datetime import datetime def get_iso_time() -> str: """ Return the current time in ISO 8601 format. """ return datetime.now().isoformat()
57feee4572877197e0e2ddd9f1f4f4370bf8da3e
668,579
import ast from typing import TypeGuard def _is_ipython_magic(node: ast.expr) -> TypeGuard[ast.Attribute]: """Check if attribute is IPython magic. Note that the source of the abstract syntax tree will already have been processed by IPython's TransformerManager().transform_cell. """ return ( ...
20e59f3ba1e5a5b5b0497ad78f5ecd3655059602
668,581
def length(vec): """ returns the length/norm of a numpy array as the square root of the inner product with itself """ return vec.dot(vec) ** 0.5
6a22c83a57ab98dc1e179fd589dd7a1a292c3cd8
668,582
def interface_r_cos(polarization, n_i, n_f, cosTh_i, cosTh_f): """ reflection amplitude (from Fresnel equations) polarization is either "s" or "p" for polarization n_i, n_f are (complex) refractive index for incident and final th_i, th_f are (complex) propegation angle for incident and final ...
fd7da775fbba9c411ff2a461aa8d41c673fe8584
668,587
def box_text(text: str) -> str: """ Draws an Unicode box around the original content Args: text: original content (should be 1 line and 80 characters or less) Returns: A three-line string. Unicode box with content centered. """ top = "β”Œ" + "─" * (len(text) + 2) + "┐" bot =...
2ec9d33cfeb0da60318235345cd1b8d25498e614
668,589
def strip_position(pos): """ Stripes position from +- and blankspaces. """ pos = str(pos) return pos.strip(' +-').replace(' ', '')
1097bf545d58cea0ef526683cf020be7678aa029
668,590
def index_map(i, d): """ The index map used mapping the from 2D index to 1D index Parameters ---------- i : int, np.array the index in the 2D case. d : int the dimension to use for the 2D index. Returns ------- int, np.array 1D index. """ return 2 *...
b322d7377eb319333343467017044356a97862a0
668,593
def should_run_stage(stage, flow_start_stage, flow_end_stage): """ Returns True if stage falls between flow_start_stage and flow_end_stage """ if flow_start_stage <= stage <= flow_end_stage: return True return False
2e241aad6752553bc1b1ca4f76e1e300e5692ce8
668,594
from typing import Union from pathlib import Path from typing import Tuple from typing import List import re import hashlib def split_dataset( root_dir: Union[str, Path], max_uttr_per_class=2 ** 27 - 1 ) -> Tuple[List[Tuple[str, str]], List[Tuple[str, str]]]: """Split Speech Commands into 3 set. Args...
3b3ee8b4972c7a38bbc3884786fa1982c86ec992
668,599
def get_launch_args(argv, separator=':='): """ Get the list of launch arguments passed on the command line. Return a dictionary of key value pairs for launch arguments passed on the command line using the format 'key{separator}value'. This will process every string in the argv list. NOTE: all ...
a2cdb11d134cca904be5158846362e12769b5556
668,604
def _add_months(date, delta): """Add months to a date.""" add_years = delta // 12 add_months = delta % 12 return date.replace(year=date.year + add_years, month=date.month + add_months)
65f1a4fab2dfc94681edaf398a788b1f3eea2d8e
668,605
import pickle import zlib def blobloads(blob): """ Inverse of blobdumps(). Decompress the pickled object, and unpickle the uncompressed object. Returns a Python object. """ return pickle.loads(zlib.decompress(blob.encode('latin1'))) # No need to specify pickle protocol, as it will be au...
b4bf4fa9abd232d6aa6d4d78ceb7dc94fe1f7f9a
668,606
def memoized_coin_change(amount, denoms, denoms_length): """ Memoized version Parameters ---------- amount : int Target amount denoms : list<int> denominations denoms_length : int number of unique denominations Returns ------- int count of ways ...
614ab634fee52ea14e58a6d2922175fa186281d8
668,607
def _get_error_list(error_code): """ Get error list. Args: error_code (int): The code of errors. Returns: list, the error list. """ all_error_list = ["nan", "inf", "no_prev_tensor"] error_list = [] for i, error_str in enumerate(all_error_list): error = (error_cod...
521759ba0e02e0b69b1756439c06d4c3082a93e3
668,611
from typing import Optional import requests def get_page_text(url: str) -> Optional[str]: """ Download complete HTML text for a url """ cookies = {"devsite_wall_acks": "nexus-image-tos"} request = requests.get(url, timeout=10, cookies=cookies) if request.ok: return request.text req...
ad6f8576f52efa3c7faae7c98a28d076c968ecd7
668,615
def ssh_cmd_docker_container_exec( detail, command_on_docker, wait_press_key=None ) -> str: """SSH command to execute a command inside a docker containter.""" wait_cmd = "" if wait_press_key: wait_cmd = "; echo 'Press a key'; read q" return ( f"TERM=xterm ssh -t {detail['ec2InstanceI...
21392652f692199934cfe88271e673cc5fdb01ae
668,616
def safestr(value): """ Turns ``None`` into the string "<None>". :param str value: The value to safely stringify. :returns: The stringified version of ``value``. """ return value or '<None>'
71ef04a33a4329c9a17aa96f83a50859f813e2b0
668,617
def rest_api_parameters(in_args, prefix='', out_dict=None): """Transform dictionary/array structure to a flat dictionary, with key names defining the structure. Example usage: >>> rest_api_parameters({'courses':[{'id':1,'name': 'course1'}]}) {'courses[0][id]':1, 'courses[0][name]':'course1'} ...
f62faa8bbd3e65eb2f61144b7e4fff2cd75076a8
668,619
def process_input(input: list[list[str]]) -> dict: """Convert the input data structure (lists of pairs of caves that are connected) into a dict where each key is a cave and the corresponding value is a list of all the caves it is contected to. """ input_processed = {} cave_pairs = [] for ...
88b6a11049e30f8aed99b7cac2e6445c5d342827
668,620
import socket def port_connected(port): """ Return whether something is listening on this port """ s = socket.socket() s.settimeout(5) try: s.connect(("127.0.0.1", port)) s.close() return True except Exception: return False
ad198aa4cda1e358e2fedcd596bef2772eafdb60
668,623
import operator def le(n: float): """ assertsion function to validate target value less or equal than n """ def wrapper(x): return operator.le(x, n) return wrapper
d70acd5fb7946c725bede2c27056645f61db52ec
668,624
from typing import Any import typing from typing import Union def deannotate(annotation: Any) -> tuple[Any]: """Returns type annotations as a tuple. This allows even complicated annotations with Union to be converted to a form that fits with an isinstance call. Args: annotation (Any): ty...
c74de52db80aa91f1d0ae7db3d1095b88ac3ff2e
668,630
import re def template_to_regex(template): """Convert a string template to a parsable regular expression. Given a data_path_format string template, parse the template into a parsable regular expression string for extracting each %VAR% variable. Supported %VAR% variables: * %EXPE...
b24378fab8eb80568b5dcdaaaba80d602c28bcab
668,631
def calculate_points_for_street(street): """ Calculates the points for a given street :param street: List of chips, that can be placed :return: int with points for street """ points = 0 for chip in street: # print(chip[0]) points += chip[0] return points
88a506a76a447682d00875efe37c6f7c7813d3eb
668,632
import re def parse_show_udld_interface(raw_result): """ Parse the 'show udld interface {intf}' command raw output. :param str raw_result: vtysh raw result string. :rtype: dict :return: The parsed result of the show udld command in a \ dictionary of the form: :: { ...
eed8255cadf9be7377b4e94b60850688d60899fe
668,635
def remove_prefix(string: str, prefix: str) -> str: """ Removes a prefix substring from a given string Params: - `string` - The string to remove the prefix from - `prefix` - The substring to remove from the start of `string` Returns: A copy of `string` without the given `prefix` """ ...
786c1fa55a08cb1155960c60c611fe07b766d8b0
668,637
def pgo_stage(stage): """ Returns true if LLVM is being built as a PGO benchmark :return: True if LLVM is being built as a PGO benchmark, false if not """ return stage == "pgo"
ea13020b79301ae6b60850fadc0b4decacc45aa7
668,638
def ReadGoldStandard(gold_file): """Read in gold standard data.""" fp = open("../test_data/gold_data/%s" % gold_file, "rb") gold_content = fp.read() fp.close() return gold_content
89747ed04283bfce1fe96b26a31abc143f924dee
668,639
import random def interchanging_mutation(genome): """Performs Interchanging Mutation on the given genome. Two position are randomly chosen and they values corresponding to these positions are interchanged. Args: genome (required): The genome that is to be mutated. Returns: The mu...
ae816f0a7619b516c31e27949f22c7a920c9c437
668,646
from typing import List def generate_numbers(parallel_steps: int) -> List[int]: """Generate a list of numbers from 0 to 'parallel_steps'.""" numbers = [i for i in range(parallel_steps)] print(f"Numbers: {numbers}") return numbers
227cd8bc8db7fc0e9d150bbb48e19213d14808aa
668,649
def _multi_line(in_string): """true if string has any linefeeds""" return "\n" in str(in_string)
d1381d2a86548178cd4a4b4690018092fe989b5f
668,650
def filter_values(values, **wanted): """ Return a list of desired Value objects. :param networks: list of Value dicts :param wanted: kwargs of field/value to filter on """ ret = [] for v in values: if all(v.get(field) == value for field, value in wanted.items()): ...
6e8535667815f7ca38c512fe0182aa509b033f99
668,653
def BuildDtd(desc_json): """Create a list out of a single detailed timing descriptor dictionary. Args: desc_json: The dictionary of a single detailed timing descriptor info. Returns: A list of 18 bytes representing a single detailed timing descriptor. """ d = [0] * 18 # Set pixel ...
bfe59efe3d022630a2983c08d51118865d9974d2
668,654
def to_list(dataseq): """Converts a ctypes array to a list.""" return list(dataseq)
00f139988633549efa7037c63e6285021068ed82
668,655
def parse_top_output(out): """ Parses the output of the Docker CLI 'docker top <container>'. Note that if 'ps' output columns are modified and 'args' (for the command) is anywhere but in the last column, this will not parse correctly. However, the Docker API produces wrong output in this case as well. ...
36d210bf6e012e36ca616a9e0506b53d828c57c1
668,657
def grep_init_lr(starting_epoch, lr_schedule): """ starting_epoch : starting epoch index (1 based) lr_schedule : list of [(epoch, val), ...]. It is assumed to be sorted by epoch return init_lr : learning rate at the starting epoch """ init_lr = lr_schedule[0][1] for e, v in lr_...
e02445b3d61912385a4e7899dfc4bb7c9a3c168e
668,658
def _random_subset_weighted(seq, m, fitness_values, rng): """ Return m unique elements from seq weighted by fitness_values. This differs from random.sample which can return repeated elements if seq holds repeated elements. Modified version of networkx.generators.random_graphs._random_subset ""...
438b72a0d36e529ec554e33357b7ad6dc37aaea5
668,659
def add_tag(tag: str, s: str) -> str: """ Adds a tag on either side of a string. """ return "<{}>{}</{}>".format(tag, s, tag)
86b7b66cf595651e1da25e7cb342e42e80628193
668,660
import ast def ast_expr_from_module(node): """ Get the `ast.Expr` node out of a `ast.Module` node. Can be useful when calling `ast.parse` in `'exec'` mode. """ assert isinstance(node, ast.Module) assert len(node.body) == 1 assert isinstance(node.body[0], ast.Expr) return node.body[0]....
0536c6cae807ce92ca423de067b016a8ff555e49
668,664
import math def dInd_calc(TNR, TPR): """ Calculate dInd (Distance index). :param TNR: specificity or true negative rate :type TNR : float :param TPR: sensitivity, recall, hit rate, or true positive rate :type TPR : float :return: dInd as float """ try: result = math.sqrt((...
20134d302553f65de081876a501a9bb16a697cd6
668,667
import unicodedata def normalize_unicode(text): """ Normalizes a string by converting Unicode characters to their simple form when possible. This is done by using Normal Form KC of a string. For example, the non-breaking space character (xa0) will be converted to a simple space character. Refe...
3e197fb5489e5623612bb2c062b6bc13aebddc22
668,669
import math def wgs_to_tile( latitude, longitude, zoom): """Get google-style tile cooridinate from geographical coordinate Note: Note that this will return a tile coordinate. and a tile coordinate is located at (0,0) or origin of a tile. all tiles are 256x256. there are as many gps locations in...
a9908049ce74259b1141af00e849779cbdee01f6
668,670
def mils(value): """Returns number in millions of dollars""" try: value = float(value) / 1000000 except (ValueError, TypeError, UnicodeEncodeError): return '' return '${0:,}M'.format(value)
2dcbcb3b4a731c2b76ff348a398e469b0f493174
668,671
def get_integer(prompt): """ Get an integer from standard input (stdin). The function keep looping and prompting until a valid `int` is entered. :param prompt: The string user will see when prompted for input :return: the `int` user has entered """ while True: temp = in...
83f10689655846c6ee364dd1c25c7ffca0ef132f
668,675
from typing import List from typing import Dict def dedup(l: List[str], suffix: str = "__", case_sensitive: bool = True) -> List[str]: """De-duplicates a list of string by suffixing a counter Always returns the same number of entries as provided, and always returns unique values. Case sensitive compariso...
7c7e7ce2ca6446cf0b76df34a9ec66df255ba9eb
668,680
def cm2inch(*tupl): """ Convert a value or tuple of values from cm to inches. Source: https://stackoverflow.com/a/22787457 Input --- tupl : float, int or tuple of arbitrary size Values to convert Returns --- Converted values in inches. """ inch = 2.54 if is...
8563bc70c8a63e3e7791e045134cbb0ac2707835
668,684
import torch def directional_derivatives(lin_op, directions, device): """``lin_op`` represents a curvature matrix (either ``GGNLinearOperator`` or ``HessianLinearOperator`` from ``vivit.hessianfree``). ``directions`` is a ``D x nof_directions`` matrix, where ``nof_directions`` directions are stored co...
b91f1f09159d1f09933f007b3b1b4cec1da3513d
668,688
def apply_ant_t_delay(scan_rad): """Accounts for antenna time delay by extending the scan rad Gets the "true" antenna radius used during a scan. Assumes ant_rad is measured from the black-line radius on the plastic antenna stand. Uses formula described in the M.Sc. thesis of Diego Rodriguez-Herrera...
e6a79999a2eb000d7436e6a56f45b87663bdd71c
668,691
import math def compute_mcc(tp, fp, tn, fn): """ Compute the Matthew correlation coefficient. Regarded as a good measure of quality in case of unbalanced classes. Returns a value between -1 and +1. +1 represents perfect prediction, 0 random, and -1 total disagreement between prediction and observa...
254bb7df12fe1059f07605f67089906ae2ffb8ff
668,693
def clean_text(text, patterns): """ Applies the given patterns to the input text. Ensures lower-casing of all text. """ txt = text for pattern in patterns: txt = pattern[0].sub(pattern[1], txt) txt = ''.join([letter for letter in txt if (letter.isalnum() or letter.isspace())]) retur...
78f221a35549f40b2a2b81596901a63c528cae20
668,694
def rk4_step(f, y, t, dt, params): """ Returns the fourth order runge-kutta approximation of the change in `y` over the timestep `dt` Parameters ---------- f (callable): accepts `y`, `t` and all of the parameters in `params` y (ndarray or float): current system stat...
d761bc43a0a2bf47aba0ab68b2c11be9ec33d9ba
668,698
def get_incremental_iteration_dets(for_el): """ Look for the pattern: pets = ['cat', 'dog'] for i in range(len(pets)): print(f"My {pets[i]}") For/target/Name id = i iter/Call/func/Name id = range args/Call/func/Name id = len args/Name i...
e3076d311cc1b7492a8905bde4fb15278130d917
668,700
from typing import Optional from typing import Tuple import re def _parse_addr(addr: str, allow_wildcard: bool = False) -> Optional[Tuple[str, str]]: """Safely parse an email, returning first component and domain.""" m = re.match( ( r'([a-zA-Z0-9\-_\+\.]+)' + ('?' if allow_wild...
ab62e2a99b9ad460163f08997e5c9bd9d6096bac
668,704
def prepare_standard_scaler(X, overlap=False, indices=None): """Compute mean and standard deviation for each channel. Parameters ---------- X : np.ndarray Full features array of shape `(n_samples, n_channels, lookback, n_assets)`. overlap : bool If False, then only using the most r...
8dbce4fed5a2bd1772f9b042d4dacdb0501b2462
668,705
def _list_intersection(list1, list2): """Compute the list of all elements present in both list1 and list2. Duplicates are allowed. Assumes both lists are sorted.""" intersection = [] pos1 = 0 pos2 = 0 while pos1 < len(list1) and pos2 < len(list2): val1 = list1[pos1] val2 = list...
4e1eb7c7051b54aade8be0c11247cafc65ac27c1
668,715
import io def read_input(input_file): """ Read OpenAssessIt .md file """ if input_file: if type(input_file) is str: with io.open(input_file, encoding='utf-8') as stream: return stream.read()
b9811ab89d5fa45b6b0f56851f9c7d7e9bbbdf74
668,716
def caesar(shift, data, shift_ranges=('az', 'AZ')): """ Apply a caesar cipher to a string. The caesar cipher is a substition cipher where each letter in the given alphabet is replaced by a letter some fixed number down the alphabet. If ``shift`` is ``1``, *A* will become *B*, *B* will become *C*, ...
c4bf5bd7fc878599e737e107c8311549a02f6a95
668,717
from typing import Optional def get_src(src: Optional[str], curie: str): """Get prefix of subject/object in the MappingSetDataFrame. :param src: Source :param curie: CURIE :return: Source """ if src is None: return curie.split(":")[0] else: return src
9b04c3182549abbdadd60546c30c52dc05bce376
668,720
from pathlib import Path def read_key(location: Path) -> str: """ reads a key from a text file containing one line parameters: location: Path the location of the file to read from """ with location.open() as file: return file.read().strip()
c044caa2ccedf795326df996244cee71501e1b1f
668,723
def readGmtFile(gmtPath): """ Read GMT file. In GMT file each line consists of term ID, term name and genes, all tab separated, no header. :param str gmtPath: Path of the GMT file :return: **geneSetsDict** (*dict*) – Dictionary mapping term IDs to set of genes. :return: **gsIDToGsNameDict** (*dict*) – Dictionary...
45c3bce208ec479e8454fbb7a4d6b3cd83c29324
668,728
def second(seq): """Returns the second element in a sequence. >>> second('ABC') 'B' """ seq = iter(seq) next(seq) return next(seq)
491004d1e74eda99c8ba49e5b28ec6c9de809fb0
668,730
def modelform_with_extras(form_cls, **extra_kwargs): """ Wrap a ModelForm in a class that creates the ModelForm-instance with extra paramaters to the constructor. This function is ment to to be returned by ModelAdmin.get_form in order to easily supply extra parameters to admin forms. """ cl...
a0b221a0097d46ca46bf7ee4594e0b632e3faa73
668,731
def _message_from_pods_dict(errors_dict): """Form a message string from a 'pod kind': [pod name...] dict. Args: - errors_dict: a dict with keys pod kinds as string and values names of pods of that kind Returns: a string message """ msg_list = [ "{0}: {1}".format(k...
51c87b1744fea7ca2540c35648c3305ea08e52a2
668,733
import pickle def pickle_load(fname): """ Load data from file using pickle. """ # load the model loaded_object = pickle.load(open(fname, 'rb')) return loaded_object
c2281dac1eb7daca831780ec86fbc9bef9e3fc23
668,734
def ari(b3, b5): """ Anthocyanin Reflectance Index (Gitelson, Chivkunova and Merzlyak, 2009). .. math:: ARI = (1/b3) - (1/b5) :param b3: Green. :type b3: numpy.ndarray or float :param b5: Red-edge 1. :type b5: numpy.ndarray or float :returns ARI: Index value .. Tip:: Kar...
1c763aa7da5faa45342035cc36de0cffd11bf58e
668,738
import math def angle_normalize(z): """ convenience function to map an angle to the range [-pi,pi] """ return math.atan2(math.sin(z), math.cos(z))
b64f1ef7b79c2302909a74ab6e50602fc5a99c40
668,740
import re def filterBadLibraries(infiles, bad_samples): """ Takes a list of infiles, removes those files that match any pattern in list of bad_samples, returns the filtered list of outfiles """ bad_samples = [re.compile(x) for x in bad_samples] to_remove = [] for inf in infiles: fo...
a033ab50500f17a587ac655b521d89bd6c8bdbae
668,746
from functools import reduce from operator import getitem def _get_by_path(tree, keys): """ Access a nested object in tree by sequence keys. """ return reduce(getitem, keys, tree)
79edeae0cd5aa85a508ce20562f34ebbe46eba0d
668,748
def analytical_domain(request): """ Adds the analytical_domain context variable to the context (used by django-analytical). """ return {'analytical_domain': request.get_host()}
2d1f32ada6524cdc14075596a7b61de3d82d2ea1
668,749
def get_start_middle_end_point(line): """ Ger three point on line Transform it to DB.Curve :param line: Line :type line: DB.Line :return: Start, middle and end point of line :rtype: [DB.XYZ, DB.XYZ, DB.XYZ] """ curve = line.GeometryCurve start = curve.GetEndPoint(0) end = cu...
b6b4f578cd8ce44663a3c7ebb0c6b7dff3ab18d8
668,754