content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def get_word(word): """Return normalized contents of a word.""" return "".join([n.string.strip() for n in word.contents if n.name in [None, "s"]])
7625e485b66a95e53cb9d0ccea30190408d7579b
652,513
def to_str(bytes_or_string): """if bytes, return the decoded string (unicode here in python3). else return itself""" if isinstance(bytes_or_string, bytes): return bytes_or_string.decode('utf-8') return bytes_or_string
b1fa95df710523179d08a7155c7f7c4d7e31303c
652,515
from typing import Any def dynamic_import(import_path: str) -> Any: """Dynamically import the specified object. It can be a module, class, method, function, attribute, nested arbitrarily. Parameters: import_path: The path of the object to import. Raises: ImportError: When there ...
78ecdd95d4b0d31ff908da190a4c7842e5d2efd2
652,518
from typing import Tuple def screen_to_world(screen_pos: tuple, pan: tuple, zoom: float) -> Tuple[float, float]: """ Converts screen coordinates to world coordinates using the pan and zoom of the screen """ result = (((screen_pos[0] - pan[0]) / zoom), ...
3096fe18742cf4c5bbfdc629ede3eac83e6d4f74
652,519
def count_empty(index, key): """ Count for any key how many papers leave the value unspecified. Note that this function only checks the first of the rows corresponding to a paper. """ count = 0 for paper, rows in index.items(): value = rows[0][key] if value in {"", "none given", ...
64b48a945fbec7ed7f219f3f541f8f27cf174f46
652,522
from typing import Tuple def _convergent(continued_fractions: Tuple[int, ...],) -> Tuple[int, int]: """Get the convergent for a given continued fractions sequence of integers :param continued_fractions: Tuple representation of continued fraction :return: reduced continued fraction representation of conve...
c5263b5046e07fb9b19f20ede2080112013bbe4f
652,523
def matches_release(allowed_releases, release): """ Check if the given `release` is allowed to upgrade based in `allowed_releases`. :param allowed_releases: All supported releases :type allowed_releases: list or dict :param release: release name to be checked :type release: string :return: ...
9555254459e56114e9544dcded66f24af9a6de32
652,524
def is_valid_xml_char(char): """Check if a character is valid based on the XML specification.""" codepoint = ord(char) return (0x20 <= codepoint <= 0xD7FF or codepoint in (0x9, 0xA, 0xD) or 0xE000 <= codepoint <= 0xFFFD or 0x10000 <= codepoint <= 0x10FFFF)
8bd5edf78246d9ba2ef4f50a48780c6a210ffdb0
652,528
def DecodeFileRecordSegmentReference(ReferenceNumber): """Decode a file record segment reference, return the (file_record_segment_number, sequence_number) tuple.""" file_record_segment_number = ReferenceNumber & 0xFFFFFFFFFFFF sequence_number = ReferenceNumber >> 48 return (file_record_segment_number,...
e6f47a5e221ab5e53398c7aac55d0abcb3ad0308
652,533
def firstjulian(year): """Calculate the Julian date up until the first of the year.""" return ((146097*(year+4799))//400)-31738
782627810324ad43fa010b4f060e28af63bbfe96
652,535
def sum_non_reds(s): """ Sum all numbers except for those contained in a dict where a value is "red". Parameters ---------- s : int, list, or dict An item to extract numbers from. Returns ------- int The total of all valid numbers. """ if isinstance(s, int): ...
8d5ffb05b3575d9d3b34d3836b5ef7e728471ddd
652,536
import typing import struct def read_uint32(stream: typing.BinaryIO) -> int: """Reads a Uint32 from stream""" return struct.unpack("<I", stream.read(4))[0]
8ae59153ff53076ade31374f2fad3e03859ec336
652,537
import requests def buscar_avatar(usuario: str) -> str: """ Busca avatar no GitHub Args: usuario (str): usuário no github Return: str com o link do avatar """ url = f'https://api.github.com/users/{usuario}' resp = requests.get(url) return resp.json()['avatar_url']
1199336cb1f1f0774e3e159308c0a4c313ef8f6c
652,538
def get_ftp_dir(abspath: str) -> str: """ Returns path within ftp site Parameters ---------- abspath The full ftp url Returns ------- str The relative path within the ftp site Examples -------- >>> abspath = 'ftp://ftp.ncbi.nlm.nih.gov/genomes/all/GCF/901/1...
ca815927f16e36ca3b1e8e153ea662acb6ad8676
652,542
def make_graph_abcde(node): """ A -> B | | | v +--> C -> D | +--> E """ d = node('D') e = node('E') c = node('C', cd=d) b = node('B', bc=c) a = node('A', ab=b, ac=c, ae=e) return a, b, c, d, e
0c234a64c9a716c5629f0b6cc757ca588210fe7c
652,550
import pathlib def process_path(path, parent, default): """Convert a path to an absolute path based on its current value. Arguments --------- path : PathLike The path to be processed. parent : PathLike The parent path that `path` will be appended to if `path` is a relative path. ...
8e69ef8881f854e9d6016aaffb96a0210f432d20
652,553
def normalize_preferences(choices): """Removes duplicates and drops falsy values from a single preference order.""" new_choices = [] for choice in choices: if choice and (choice not in new_choices): new_choices.append(choice) return new_choices
bde074bfdc0e690eb16ae83e42ee01e542188cec
652,554
from calendar import isleap import datetime def datetime_from_numeric(numdate): # borrowed from the treetime utilities # https://github.com/neherlab/treetime/blob/de6947685fbddc758e36fc4008ddd5f9d696c6d3/treetime/utils.py """convert a numeric decimal date to a python datetime object Note that this onl...
849825381df7cacf33bb94bd22cbfd027a79f804
652,570
import re def sha_from_desc(desc): """ Extract the git SHA embedded in the description field """ m = re.match(".*\[SHA ([A-Za-z0-9]{7})[\]!].*", desc) if m: return m.groups()[0]
8f8a598c3bba0aba8d0786d4d4d2737e1bc4d8df
652,572
def find_irreducible_prefix(brackets): """Find minimal prefix of string which is balanced (equal Ls and Rs). Args: brackets: A string containing an equal number of (and only) 'L's and 'R's. Returns: A two-element tuple. The first element is the minimal "irreducible prefix" of `brackets`, which ...
fa8bd7998550de63f9fea9523424b198bfc96a45
652,575
def _extract_node_text(node): """Extracts `text` and `content-desc` attribute for a node.""" text = node.get('text') content = node.get('content-desc', []) all_text = [text, content] if isinstance(content, str) else [text] + content # Remove None or string with only space. all_text = [t for t in all_text if...
66800ba5ab924fc0641a6a725069e3899fee39ef
652,576
def substitute(message, substitutions=[[], {}], depth=1): """ Substitute `{%x%}` items values provided by substitutions :param message: message to be substituted :param substitutions: list of list and dictionary. List is used for {%number%} substitutions and dictionary for {%name%} subs...
4a46c46faf1848f1c7e437fed956e21cfdd3a813
652,579
def encodeDict(items): """ Encode dict of items in user data file Items are separated by '\t' characters. Each item is key:value. @param items: dict of unicode:unicode @rtype: unicode @return: dict encoded as unicode """ line = [] for key, value in items.items(): item = u'%...
2cd39fc638753c943bae28cac22ad4cce3259862
652,580
import typing def find_section_in_list( section: typing.List[typing.Any], action: typing.Dict[str, typing.Any], key: str ) -> int: """ Find index of section in list :param section: list, where we want to search :param action: action dictionary :param key: the key marker :return: index of s...
b958b06472020aac57b53bdf29873ca2d3ffba1e
652,583
def get_order_category(order): """Given an order string, return the category type, one of: {"MOVEMENT, "RETREATS", "DISBANDS", "BUILDS"} """ order_type = order.split()[2] if order_type in ("X", "D"): return "DISBANDS" elif order_type == "B": return "DISBANDS" elif order_type ...
08c276c6080a47b6170e211f5c63f3163eedf3a6
652,588
import random def powerlaw_sequence(n,exponent=2.0): """ Return sample sequence of length n from a power law distribution. """ return [random.paretovariate(exponent-1) for i in range(n)]
aa394a74e92c1c3f1f59a56d55a585e7d0c8bdd4
652,591
def distance_between(origin_x, origin_y, destination_x, destination_y): """Takes origin X,Y and destination X,Y and returns the distance between them""" return ((origin_x - destination_x)**2 + (origin_y - destination_y)**2)**.5
98b3fa8499c149f4c162f2b40eb58da8b36596ee
652,596
def basic_data_context_config_dict(basic_data_context_config): """Wrapper fixture to transform `basic_data_context_config` to a json dict""" return basic_data_context_config.to_json_dict()
febc522b59deb4b6920a56941a5f439ae5c90475
652,598
def split_elem_def(path): """Get the element name and attribute selectors from an XPath path.""" path_parts = path.rpartition('/') elem_spec_parts = path_parts[2].rsplit('[') # chop off the other ']' before we return return (elem_spec_parts[0], [part[:-1] for part in elem_spec_parts[1:]])
63394c8a1ecf5d4e2fbeb1f7f3b58f4c386b29e2
652,600
def _normalize_target_module(source_module, target_module, level): """ Normalize relative import, to absolute import if possible. Parameters ---------- source_module : str or None Name of the module where the import is written. If given, this name should be absolute. target_module :...
7f6ce7688a5e5f8116419074c7cafc94ef794996
652,602
import copy def ApplyFunToRadii(fiber_bundle, fun): """ Applies function to fibers radii Parameters ---------- fiber_bundle : [(,4)-array, ...] list of fibers fun : function Returns ------- res : [(,4)-array, ...] translated fiber_bundle """ fiber_bundle ...
fd904747954dc7b894cf6e086c1843f98b9ece27
652,604
def get_file_info_from_url(url: str, spec_dir: str): """ Using a url string we create a file name to store said url contents. """ # Parse a url to create a filename spec_name = url.replace('https://raw.githubusercontent.com/', '')\ .replace('.yml', '')\ .replace...
229de0038d0b0249a68a7e4c058f76f972296fac
652,606
def make_idx(*args, dim, ndim): """ Make an index that slices exactly along a specified dimension. e.g. [:, ... :, slice(*args), :, ..., :] This helper function is similar to numpy's ``_slice_at_axis``. Parameters ---------- *args : int or None constructor arguments for the slice o...
78f432d18e6107b0aed9d68f60b6e088e795dedf
652,608
from typing import Iterable from typing import Any def contains(collection: Iterable, entity: Any) -> bool: """Checks whether collection contains the given entity.""" return entity in collection
7688428427e056ed24830b2fd9c3ba34be02e84b
652,610
from pathlib import Path def extract_sequence(fasta: Path, target_contig: str) -> str: """ Given an input FASTA file and a target contig, will extract the nucleotide/amino acid sequence and return as a string. Will break out after capturing 1 matching contig. """ sequence = "" write_flag = Fal...
547ba39dc3658e6c28c77012eba79393c01690ee
652,612
def obter_pos_c(pos): """ obter_pos_c: posicao -> str Recebe uma posicao e devolve a componente coluna da posicao. """ return pos['c']
f1df4cc2416ed0a6f5cab5bb72b0fe8392a132e0
652,615
def interval_len(aInterval): """Given a 3 column interval, return the length of the interval """ return aInterval[2] - aInterval[1] + 1
ea4aca73d330852f41cc66a77e93b49c595cac68
652,616
def get_emoji(hashtag): """Return a helpful emoji bashed on the hashtag of the earning report.""" if "miss" in hashtag: return "🔴" return "🟢"
d9cdcee7d0d3aa5b6b040fe29abf8d688ebdef9c
652,619
from typing import List def find_occurrences_in_text(text: List[List[List[str]]], researched_tokens: List[str]) -> List[str]: """ Find occurrences of given tokens in a given text. Each occurrence has the following format: <chapter>-<line>-<half-line>-<word>. >>> text = r...
9c19223fc21660fdf01fc1566177899b4f2427e5
652,620
def read_reco2vol(volumes_file): """Read volume scales for recordings. The format of volumes_file is <reco-id> <volume-scale> Returns a dictionary { reco-id : volume-scale } """ volumes = {} with open(volumes_file) as volume_reader: for line in volume_reader.readlines(): if l...
8914f0f8351f3340fa3382c7dad00c61ce0aa154
652,623
import hashlib def sha256(path): """Return the sha256 digest of a file.""" h = hashlib.sha256() with open(path, 'rb') as f: for chunk in iter(lambda: f.read(8192), b''): if not chunk: break h.update(chunk) return h.hexdigest()
97ec85f000ff9db7dbdbffab78ede1dd3b12fc65
652,648
import yaml def jinja_filter_toyaml_dict(value) -> str: """Jinjafilter to return a dict as a Nice Yaml. Args: value (dict): value to convert Returns: Str formatted as Yaml """ return yaml.dump(value, default_flow_style=False)
eb3506fd00a9a36390037436a38de36a9ccbe343
652,649
def minibatch_fn(net, loss_fn, optimizer, batch): """ Trains network for a single batch. Args: net (torch network) ANN network (nn.Module) loss_fn (torch loss) loss function for SGD optimizer (torch optimizer) optimizer for SGD batch (torch.Tensor) ...
2e4cc7ae929efe08a0b8ffb23521f6b29a4e559c
652,658
import hashlib def control_sum(fpath): """Returns the control sum of the file at ``fpath``""" f = open(fpath, "rb") digest = hashlib.sha512() while True: buf = f.read(4096) if not buf: break digest.update(buf) f.close() return digest.digest()
050d30cc92d1379fc89be716f31909531284b3f4
652,660
def tenant_is_enabled(tenant_id, get_config_value): """ Feature-flag test: is the given tenant enabled for convergence? :param str tenant_id: A tenant's ID, which may or may not be present in the "convergence-tenants" portion of the configuration file. :param callable get_config_value: config k...
00c90b9a0c58aeca4a9cddc64fac41d93ce8c1d6
652,668
def get_defined_pipeline_classes_by_key(module, key): """Return all class objects in given module which contains given key in its name.""" return [ cls for name, cls in module.__dict__.items() if isinstance(cls, type) and key in name ]
55a3dd6a0bfeaa2fea49e6193f39438c2abaf0be
652,669
def calc_bits(offset, size): """ Generates the string of where the bits of that property in a register live Parameters ---------- offset : int, size : int, Returns ---------- ret_str : str, the string """ # Generate the register bits if size == 1: ret_str ...
b28c5de3d22957102e264c97f3d31376bc0ade59
652,670
def set_color_mask(A, M, c): """ Given image array A (h, w, 3) and mask M (h, w, 1), Apply color c (3,) to pixels in array A at locations M """ for i in range(3): A_i = A[:,:,i] A_i[M]=c[i] A[:,:,i] = A_i return A
3e113d168d1a6d5321628a7cc099e67c770f601c
652,675
def cents_to_pitchbend(cents, pb_range) -> int: """ Convert cent offset to pitch bend value (capped to range 0-16383) :param cents: cent offset :param pb_range: pitch bend range in either direction (+/-) as per setting on Roli Dashboard / Equator :return: """ pb = 8192 + 16384 * cents / (pb_...
8f9f55efc411d4f53846c8ef3a91fe8bc34cd2b5
652,676
import functools def _numel(arr): """ Returns the number of elements for an array using a numpy-like interface. """ return functools.reduce(lambda a, b: int(a) * int(b), arr.shape, 1)
6c51e35f7d753f7b0acde02543c93671395b1c80
652,679
import platform def get_architecture() -> str: """Return the Windows architecture, one of "x86" or "x64".""" return "x86" if platform.architecture()[0] == "32bit" else "x64"
ef7fcb690061e72900e999464fc1a716d27fdc87
652,685
def _get_numbers(directive): """ Retrieve consecutive floating point numbers from a directive. Arguments: directive: A 2-tuple (int, str). Returns: A tuple of floating point numbers and the remainder of the string. """ num, line = directive numbers = [] items = line.spl...
ebade379e4f879b39a4072a308281ca89f12fd53
652,688
import math def format_amount( amount_pence, trim_empty_pence=False, truncate_after=None, pound_sign=True ): """ Format an amount in pence as pounds :param amount_pence: int pence amount :param trim_empty_pence: if True, strip off .00 :param truncate_after: if a number of pounds, will round in...
d805ad380986097cf7be118558bfa127a0c00386
652,689
def bonferroni(false_positive_rate, original_p_values): """ Bonferrnoi correction. :param false_positive_rate: alpha value before correction :type false_positive_rate: float :param original_p_values: p values from all the tests :type original_p_values: list[float] :return: new critical value...
a920d44fc04670eaf776444b4e39f105e685de80
652,690
def get_max_vals(tree): """ Finds the max x and y values in the given tree and returns them. """ x_vals = [(i[0], i[2]) for i in tree] x_vals = [item for sublist in x_vals for item in sublist] y_vals = [(i[1], i[3]) for i in tree] y_vals = [item for sublist in y_vals for item in sublist] ...
7fc84ba468d8e53660cdd5252f669609adecbe92
652,698
def get_between(haystack, starter, ender): """ Find text between a start flag and end flag. Get the location of the desired substring and the location of the entire field separately. Example: If starter is "line " and ender is " " and haystack contains "line 1 ", then the result is a dict w...
5af3352f285df86e8e1e7d444ca119e6c91d40e1
652,702
def scienti_filter(table_name, data_row): """ Funtion that allows to filter unwanted data from the json. for this case: * fields with "FILTRO" * values with the string "nan" * passwords anything can be set here to remove unwanted data. Parameters: table_name:str n...
03029587e43f4e8aad809b607c45f53149d94fa2
652,704
import math def compute_icns_data_length(ctx): """Compute the required data length for palette based images. We need this computation here so we can use `math.ceil` and byte-align the result. """ return math.ceil((ctx.width * ctx.height * ctx.bit_length) / 8)
af479039a5ac51561b5eeac5f9ef519ffa65b442
652,706
import math def getHeading(q): """ Get the robot heading in radians from a Quaternion representation. :Args: | q (geometry_msgs.msg.Quaternion): a orientation about the z-axis :Return: | (double): Equivalent orientation about the z-axis in radians """ yaw = math.atan2(2 * ...
4476051d48c6766aded3ad9308367960f77cead3
652,707
def wants_other_orders(responses, derived): """ Return whether or not the user wants other orders """ return 'Other orders' in derived['orders_wanted']
3ce624e5784ca8896d8cdc25d479e98761ce69af
652,710
def removeAlignmentNumber(s): """ If the name of the transcript ends with -d as in ENSMUST00000169901.2-1, return ENSMUST00000169901.2 """ s = s[:] i = s.find('-') if i == -1: return s else: return s[0:i]
f6509eacd414b1ff92fd3fb1a75e211f60c29ed8
652,712
def output_dir(tmpdir): """Fixture. Create and return custom temp directory for test.""" return str(tmpdir.mkdir('templates'))
c9d8fb8960055aaae40f38acbe468ceb9bd3adba
652,715
def det(a: list) -> int: """ Calculates the determinant of a 2x2 Matrix, via the shortcut (a*d) - (b*c) :param a: The matrix A. :return: The determinant. """ d= (a[0][0] * a[1][1]) - (a[0][1] * a[1][0]) return d
462c0a9a400c69e0b8ade8f4153bc40143de9134
652,721
def _intify_keys(d): """Make sure all integer strings in a dictionary are converted into integers.""" assert isinstance(d, dict) out = {} for k, v in d.items(): if isinstance(k, str) and k.isdigit(): k = int(k) out[k] = v return out
21eca39f20dcfbb65bee80df3cef711eb632791c
652,733
def get_job_state_str(job): """Get string representation of a job.""" if not hasattr(job, 'next_run_time'): # based on apscheduler sources return 'pending' elif job.next_run_time is None: return 'paused' else: return 'active'
fc44db5560bc94a8d48988b2bf36656037bafc72
652,734
import torch def normalize_pointcloud_transform(x): """ Compute an affine transformation that normalizes the point cloud x to lie in [-0.5, 0.5]^2 :param x: A point cloud represented as a tensor of shape [N, 3] :return: An affine transformation represented as a tuple (t, s) where t is a translation an...
06c2178a92d8e5a1b585249e9aa1e1bd4c4e3d5d
652,736
def is_json(_path) -> bool: """Return True if file ends with .json, otherwise False.""" if _path.endswith(".json"): return True else: return False
ba2a3ec6b93675dc86d07fbd626fac7c75a14585
652,737
def get_next_tile(thisTile, neighboringTile): """ Look 1 tile over in the direction specified by the value passed in neighboringTile (north, south, ..., etc.) """ row, column = thisTile # thisTile[i, j] row_neighboringTile, column_neighboringTile = neighboringTile # neighborTile[k, l], where [k, l] is the dir...
99e828afa60dc1bbeaced0cd223a57e5d5ca1c4a
652,745
def grouped(sequence, key=None, transform=None): """ Parse the sequence into groups, according to key: >>> ret = grouped(range(10), lambda n: n % 3) >>> ret[0] [0, 3, 6, 9] >>> ret[1] [1, 4, 7] >>> ret[2] [2, 5, 8] """ groups = {} if not key: ...
ee73afaff8de674d2132971a78d507320b50d42e
652,749
def _is_typing_object(type_object): """Checks to see if a type belong to the typing module. Parameters ---------- type_object: type or typing._GenericAlias The type to check Returns ------- bool True if `type_object` is a member of `typing`. """ return type_object._...
43c5326e158639f288e266f146a16ce8d35c7e2c
652,751
def merge_dicts(*dictionaries): """Return a new dictionary by merging all the keys from given dictionaries""" merged_dict = dict() for dictionary in dictionaries: if not dictionary: continue merged_dict.update(dictionary) return merged_dict
310285cff7fb854abf3e39ef506d2bdd9f66002e
652,753
import torch def get_optimizer(opts, model): """ Create optimizer and scheduler according to the opts """ opt_name = opts.optimizer.name.lower() if opt_name == "adam": opt_class = torch.optim.Adam else: raise NotImplementedError("Unknown optimizer " + opts.optimizer.name) o...
a670c7e07454eb04b1072bbc4b226251ef52e2f2
652,755
import math def define_joint_angle_list(shoulder_pan_joint, shoulder_lift_joint, elbow_joint, wrist_1_joint, wrist_2_joint, wrist_3_joint): """ This function takes float values for each joint and returns a list. :param shoulder_pan_joint: shoulder pan joint angle :param shoulder_lift_joint: shoulder l...
05010c00fc9440ac732938692e741e0825f86935
652,757
def NestedMultiplication(x, xValues, coeff): """Evaluates Newton Polynomial at x in nested form given the interpolating points and its coefficents""" n = coeff.size y = coeff[n-1] for i in reversed(range(n - 1)): y = coeff[i] + (x - xValues[i]) * y return y
143729cfab7bfd61e76b6195d505e34e81366ad9
652,758
def default_if_empty(value, arg): """ Set default one if the value is empty. String: None, '' Integer: None, 0 """ if not value: return arg return value
cf5575704c4aee50e7baefa5be93e248ddd24c11
652,764
def exitCodeToOutcome(exit_code): """convert pytest ExitCode to outcome""" if exit_code == 0: return "passed" elif exit_code == 1: return "failed" elif exit_code == 2: return "interrupted" elif exit_code == 3: return "internal_error" elif exit_code == 4: r...
caf15830c44353cc46ecdf0a322b39c71ae3dda9
652,765
def update_set(current_value, new_value): """Set Updater Returns: The value provided in ``new_value``. """ return new_value
2bffc6a8ab4eb42cca94ed311de4b0612c9ad154
652,769
from typing import Any def is_false(x: Any) -> bool: """ Positively false? Evaluates: ``not x and x is not None``. """ # beware: "0 is False" evaluates to False -- AVOID "is False"! # ... but "0 == False" evaluates to True # https://stackoverflow.com/questions/3647692/ # ... but comparison...
027ab344b5b646c6324fed3c2d441634082e4bce
652,770
from typing import Iterable import click def _get_options_flags(options: Iterable[click.Option]): """ Given a list of options, produce a list of formatted option flags, like "--verbose/-v". """ return ", ".join(["/".join(opt.opts) for opt in options])
69e68aeeea5a36810b7c6a62374cbb9bd785024d
652,772
import ast from typing import Callable def bin_op(op: ast.operator) -> Callable[[ast.expr, ast.expr], ast.BinOp]: """Generate an ast binary operation""" def _bin_op(left: ast.expr, right: ast.expr) -> ast.BinOp: return ast.BinOp(left=left, op=op, right=right) return _bin_op
efe8f8fb7a23a53e304da67ab3ce9c6c5cfce42a
652,773
import math def norme_vecteur(vect): """Calcul de la norme d'un vecteur en dimension 2""" return math.sqrt(math.pow(vect[0],2)+math.pow(vect[1],2))
eb304827420403e75cece88a324a2e026c122bef
652,775
def gradient_descent(wb, dwdb, optimizer_args): """ The simple gradient descent update. Parameters ---------- wb : dict A dictionary of the weights/biases for each layer. dwdb : dict A dictionary of the gradients with respect to the weights and biases. optimizer_args...
ab6f626d4b6066e7105b074d2bb9581277044307
652,776
from datetime import datetime def now(request): """ Add current datetime to template context. """ return {'now': datetime.now()}
8d3d0ab4edcd1bc2dafbd6f3cdc14c6e27385a02
652,777
import random def roll_dice(sides=6) -> int: """Simulate Rolling a die. Uses random.randrange to calculate the roll. sides defaults to 6 sides. :param sides: number of sides the die has. :return: the int value of the roll. """ sides += 1 # Include the last number for randrange. roll...
21326f5505222c0351fcc41907d4bd50353b90c2
652,778
def get_tw_refs(tw_refs_by_verse, book, chapter, verse): """ Retrurns a list of refs for the given book, chapter, verse, or empty list if no matches. """ if book not in tw_refs_by_verse: return [] if chapter not in tw_refs_by_verse[book]: return [] if verse not in tw_refs_by_vers...
d2a9379c9242d063a511dbd6d30666043dddb977
652,781
def diff_list(first, second): """Computes the difference between two input sets, with the elements in the first set that are not in the second. """ second = set(second) return [item for item in first if item not in second]
c67611f8f8080b4dada415680958855b82fdfb4e
652,785
def pure_list(comma_list): """ Transform a list with items that can be comma-separated strings, into a pure list where the comma-separated strings become multiple items. """ pure_items = [] for comma_item in comma_list: for item in comma_item.split(','): pure_items.append(ite...
4de2e624a042ab8fa48d8a913ed545f65a8eb9ce
652,788
def wmo_correction(R_raw): """Apply WMO calibration factor to raw rain rate parameters ---------- R_raw : array like Rain rate in mm/h return ------ R_calib : pandas.DataFrame Corrected rain rate in mm/h """ R_calib = (R_raw / 1.16) ** (1 / 0.92) return R_ca...
a32efccbe669f2b5a8f4dc57685633e820679c9f
652,789
def decode_pair(left: str, right: str, rep: int, s: str) -> str: """Decodes a left/right pair using temporary characters.""" return ( s.replace("", "") .replace("\ufffe" * rep, left) .replace("\uffff" * rep, right) )
946a106d608adae78cfc0ec26a629192c8aff87f
652,790
def calor_vaporizacion(T, Tc, C1, C2, C3, C4): """Calor de vaporización de liquidos organicos e inorganicos [J/(mol.K)]""" Tr = T / Tc return C1*(1 - Tr)**(C2 + C3*Tr + C4*Tr**2) / 1000
ae938a053cf9a4e9cc37a526d2252b5a412dc7f0
652,792
def get_requires_for_build_wheel(config_settings=None): """Returns a list of requirements for building, as strings""" return []
12e139b2052d7f52ea92a04703f118bd0ae436f8
652,797
def isproperty(obj): """ Is this a property? >>> class Foo: ... def got(self): ... return 2 ... def get(self): ... return 1 ... get = property(get) >>> isproperty(Foo.got) False >>> isproperty(Foo.get) True """ return type(obj) == pro...
14e2a33b89117fdcdcbd99babfd04dd7ff264c73
652,801
def target_schema() -> str: """Get target schema name.""" return "dv"
17950059542d217c10bd8baad9c062fa32d0a628
652,802
def calculate_change_label(last_close, close): """ Calculate the label for a given input. The label is the change of the closing price from the last closing price. :param last_close: closing price of last candle :param close: closing price of current candle :return: float """ return (close - la...
2b887cefcc580d26a60e3b3b6bc6c784aebf99bb
652,807
def check_role_requirement(requirement, roles): """ Check user roles meets requirement A requirement looks like: { "type": "all|any" "roles: ["role_A", "role_B"] } """ allow = False if requirement["type"] == "all": # require user has all the roles specified ...
2df641d1a865a3724ea6199ff15056e08735fd15
652,808
def has_tag_requirements(tags, required_tags, qtype): """ Returns True if `tags` meets the requirements based on the values of `required_tags` and `qtype`. False otherwise. """ has_tag_requirements = False tag_intersection = set(required_tags).intersection(set(tags)) if qtype == "or": ...
62ac825ba17babd2cd8b449693658d0394d2f965
652,810
def getSelectColumns(columns): """ Prepare the columns to be selected by the SELECT statement. """ if columns == '*': return columns else: return ', '.join(columns)
caef33ffd42027be970107b53ecdd6bed125a381
652,811
from typing import List def annotation_name(attributes: List[dict], category_name: str, with_attributes: bool = False) -> str: """ Returns the "name" of an annotation, optionally including the attributes. :param attributes: The attribute dictionary. :param categ...
8044a5618477e26f10be0a52e3e673de20d060d4
652,814
import unicodedata def strip_accents_unicode(s: str) -> str: """Transform accentuated unicode symbols into their ASCII counterpart.""" try: # If `s` is ASCII-compatible, then it does not contain any accented # characters and we can avoid an expensive list comprehension s.encode('ASCII'...
08c0b66e4f70241e4a3585f181c3bbb43361d04d
652,815
def get_param_value_by_name(parameters, name): """ Return the value from the conditions parameters given the param name. :return: Object """ for p in parameters: if p['name'] == name: return p['value']
aead03bc5fd33762a8ab6660b747bfda2bc418bc
652,820