content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import hashlib import base64 def get_file_hash(filename, algorithm='md5'): """Linux equivalent: openssl <algorithm> -binary <filename> | base64""" hash_obj = getattr(hashlib, algorithm)() with open(filename, 'rb') as file_: for chunk in iter(lambda: file_.read(1024), b""): hash_obj.upd...
ff90f5ce1c7ac0f8b51597e9a93d1fe4d349b4e3
654,132
import torch def kl_divergence(d1, d2, K=100): """Computes closed-form KL if available, else computes a MC estimate.""" if (type(d1), type(d2)) in torch.distributions.kl._KL_REGISTRY: return torch.distributions.kl_divergence(d1, d2) else: samples = d1.rsample(torch.Size([K])) retur...
b575ad3d7bab340cf0242dd1b4cb0eb52cbc1ba3
654,135
def forcerange(colval): """Caps a value at 0 and 255""" if colval > 255: return 255 elif colval < 0: return 0 else: return colval
d0895fcf53788eb3a09a400576f2f6fc472ec654
654,138
import calendar def weekday_of_birth_date(date): """Takes a date object and returns the corresponding weekday string""" get_weekday = date.weekday() weekday = calendar.day_name[get_weekday] return weekday
38ac564e7f6607aca5778e036346389b8c0531ef
654,139
def r_to_q_Ri(params, substep, state_history, prev_state, policy_input): """ For a 'r to q' trade this function returns the amount of token UNI_R for the respective asset depending on the policy_input """ asset_id = policy_input['asset_id'] # defines asset subscript r = (policy_input['ri_sold']) #am...
1ce600ae3bb448a60a612bcb4eca8372c8ab3f3d
654,140
import six def _hex2rgb(h): """Transform rgb hex representation into rgb tuple of ints representation""" assert isinstance(h, six.string_types) if h.lower().startswith('0x'): h = h[2:] if len(h) == 3: return (int(h[0] * 2, base=16), int(h[1] * 2, base=16), int(h[2] * 2, base=16)) i...
6f5cf531c22d8f51107924d6c7f9cc6cca75b5bc
654,144
from typing import Optional from typing import List from typing import Set def select_functions(vw, asked_functions: Optional[List[int]]) -> Set[int]: """ Given a workspace and an optional list of function addresses, collect the set of valid functions, or all valid function addresses. arguments: ...
0e98af6a0e6da85d6e9612cc03cc7389fd5b7555
654,145
import torch def load_model(model, load_path, device): """Load torch model.""" model.load_state_dict(torch.load(load_path, map_location = device)) return model
90e29764afd6ad46522c475c97bca6dc2af93299
654,147
def is_encrypted_value(value): """ Checks value on surrounding braces. :param value: Value to check :return: Returns true when value is encrypted, tagged by surrounding braces "{" and "}". """ return value is not None and value.startswith("{") and value.endswith("}")
ba7a9b8d74f11d85afcfc1f156dd01a4c443d1a9
654,153
def duplicates(L): """ Return a list of the duplicates occurring in a given list L. If there are no duplicates, return empty list. """ dupes = list() seen = set() for x in L: if x in seen: dupes.append(x) seen.add(x) return dupes
631c77c7ecab6cc22776b4994c4b8fe173cd3ce1
654,160
def make_regexps_for_path(path): """ given a path like a/b/c/d/e.ipynb, return many regexps mathing this path. specifically, [^/]+/b/c/d/e.ipy a/[^/]+/c/d/e.ipy a/b/[^/]+/d/e.ipy a/b/c/[^/]+/e.ipy a/b/c/d/[^/]+ """ components = path.split("/") patterns = [] for i in range...
6caccb8c25a50db4c5c86465fbde98cdca944585
654,161
def format_math(expr): """Replace math symbols with HTML conterparts :param expr: expression to format :type expr: str :returns: replaced string """ expr2 = expr.replace(".gt.", "&gt;") expr2 = expr2.replace(".geq.", "&gt;=") expr2 = expr2.replace(".lt.", "&lt;") expr2 = expr2.repl...
b31590c807bfadb698ca1ffef15dbc101bbe05ea
654,163
import requests def get_github_list(base_url): """ Helper to traverse paginated results from the GitHub API. Used to retrieve lists of tags and releases. """ results = [] per_page = 100 page_number = 1 while True: response = requests.get("%s?per_page=%s&page=%s" % (...
bc10abf6317802091b7f504f7760ff7628cbf2ac
654,165
def add_labels_to_predictions_strict(preds, golds, strict=True): """ Returns predictions and missed gold annotations with a "label" key, which can take one of "TP", "FP", or "FN". """ pred_spans = {(s["start"], s["end"]) for s in preds} gold_spans = {(s["start"], s["end"]) for s in golds} ou...
5092b1179225038eac0b33e9997176adc16b4ff8
654,168
def connection_mock_factory(mocker): """Factory of DB connection mocks.""" def factory(vendor, fetch_one_result=None): connection_mock = mocker.MagicMock(vendor=vendor) cursor_mock = connection_mock.cursor.return_value cursor_mock = cursor_mock.__enter__.return_value # noqa: WPS609 ...
ce559c55024e3a2db181ca50509a264888036b16
654,172
def _get_longest_match(digraph, html_files): """Find the longest match between ``digraph`` and the contents of ``html_files``. Parameters ---------- digraph : str The ``digraph`` attribute of a :py:class:`Dotfile` object html_files : list A list of the Sphinx html files Returns...
3a4bbf2adee7e50c2512b724daa7c75c9a8ef6df
654,174
def get_attributes(parent, selector, attribute): """Get a list of attribute values for child elements of parent matching the given CSS selector""" return [child.get(attribute) for child in parent.cssselect(selector)]
f4fecaf7aa16465a63e3e1dd062465b4cc810ad8
654,176
from typing import List def mock_random_choice(candidates: List, weights: List[float], *, k: int) -> List: """ This is a mock function for random.choice(). It generates a deterministic sequence of the candidates, each one with frequency weights[i] (count: int(len(candidates) * k). If the sum of total ...
c60aebb59aeb299e6e36b9b7ed24a0fe6e0882b3
654,177
def reformat_icd_code(icd_code: str, is_diag: bool = True) -> str: """Put a period in the right place because the MIMIC-3 data files exclude them. Generally, procedure ICD codes have dots after the first two digits, while diagnosis ICD codes have dots after the first three digits. Adopted from: https://...
988893c9994785fc18d08b5afc2ea644e6fc4201
654,178
def milky_way_extinction_correction(lamdas, data): """ Corrects for the extinction caused by light travelling through the dust and gas of the Milky Way, as described in Cardelli et al. 1989. Parameters ---------- lamdas : :obj:'~numpy.ndarray' wavelength vector data : :obj:'~numpy....
b99b7ee2dc890aaf481322ec377951997973b49a
654,184
def build_anytext(name, value): """ deconstructs free-text search into CQL predicate(s) :param name: property name :param name: property value :returns: string of CQL predicate(s) """ predicates = [] tokens = value.split() if len(tokens) == 1: # single term return f"{nam...
e7b879a34bcaa0b776a8ffdfd91da7565b3195ab
654,187
import math def compensatoryAnd(m, g=0.5): """ anding function m = list of membership values for x derived from n membership functions g = gamma value 0=product 1=algebraic sum returns compensatory AND value of x """ g = float(g) product1 = 1 product2 = 1 for mem ...
6b8513de08efc24c87925aab9afe89d01674fb39
654,188
import random def _get_a_word(words, length=None, bound='exact', seed=None): """Return a random word. :param list words: A list of words :param int length: Maximal length of requested word :param bound: Whether to interpret length as upper or exact bound :type bound: A string 'exact' or 'atmost' ...
0170df161a63743e1c7a2b1a8b2ac88a8baa4e88
654,191
def dict2str(opt, indent_level=1): """dict to string for printing options. Args: opt (dict): Option dict. indent_level (int): Indent level. Default: 1. Return: (str): Option string for printing. """ msg = '' for k, v in opt.items(): if isinstance(v, dict): ...
026cfe7e819b474a2a4cccf2ee2969a9ae1abd19
654,192
def is_pos_tag(token): """Check if token is a part-of-speech tag.""" return(token in ["CC", "CD", "DT", "EX", "FW", "IN", "JJ", "JJR", "JJS", "LS", "MD", "NN", "NNS", "NNP", "NNPS", "PDT", "POS", "PRP", "PRP$", "RB", "RBR", "RBS", "RP", "SYM", "TO", "UH", "VB...
1472f3b28bb60097c8725ba07b8d2e0a659ac1e0
654,194
from typing import Dict from typing import Any from typing import List def set_user_defined_functions( fha: Dict[str, Any], functions: List[str] ) -> Dict[str, Any]: """Set the user-defined functions for the user-defined calculations. .. note:: by default we set the function equal to 0.0. This prevents ...
5078168319e4360f3ac3b3c02087439e5175da07
654,195
import math def bbox_to_zoom_level(bbox): """Computes the zoom level of a lat/lng bounding box Parameters ---------- bbox : list of list of float Northwest and southeast corners of a bounding box, given as two points in a list Returns ------- int Zoom level of map in a WG...
f8f97a6e9304d2122cf04a1c1300f911b964bf09
654,196
def scale_size(widget, size): """Scale the size based on the scaling factor of tkinter. This is used most frequently to adjust the assets for image-based widget layouts and font sizes. Parameters: widget (Widget): The widget object. size (Union[int, List, Tuple]): ...
3cd7b8e9a88a544c6086b0d453773f3d26f4eba3
654,199
def pdf_field_type_str(field): """Gets a human readable string from a PDF field code, like '/Btn'""" if not isinstance(field, tuple) or len(field) < 4 or not isinstance(field[4], str): return '' else: if field[4] == '/Sig': return 'Signature' elif field[4] == '/Btn': return 'Checkbox' ...
c677e0decb4efabde7b5aa42fe95f208c4e7a184
654,200
def get_task_prerun_attachment(task_id, task, args, kwargs, **cbkwargs): """Create the slack message attachment for a task prerun.""" message = "Executing -- " + task.name.rsplit(".", 1)[-1] lines = ["Name: *" + task.name + "*"] if cbkwargs["show_task_id"]: lines.append("Task ID: " + task_id) ...
f67798248966730acd90da135d70f734d428a27e
654,201
from typing import Optional from typing import Tuple def make_response(status: int, data: Optional[str] = None) -> Tuple[str, int]: """Construct a non-error endpoint response.""" if data is None: data = "" return (data, status)
dca07b1f103f1bbf5e31d813aa620be1bfc40f8f
654,202
def mse_grad(y, tx, w): """Compute gradient for MSE loss.""" e = y - tx @ w return (-1/tx.shape[0]) * tx.T @ e
3635335895777112a5cc0c889a9379c043822eb1
654,208
from typing import Tuple def _get_func_expr(s: str) -> Tuple[str, str]: """ Get the function name and then the expression inside """ start = s.index("(") end = s.rindex(")") return s[0:start], s[start + 1:end]
8ac212727859fc2df01cc12164118d9cfcf66d9f
654,209
def get_df_rng(ws, df, start_row=1, start_col=1, include_headers=True): """Gets a range that matches size of dataframe""" nrow = len(df) + 1 if include_headers else len(df) ncol = len(df.columns) return ws.get_range(row=start_row, column=start_col, numb...
b19bb43f2e1b603a887fa220e17cb56cfbba7d14
654,213
def get_numeric_columns(df): """ # Returns a list of numeric columns of the dataframe df # Parameters: # df (Pandas dataframe): The dataframe from which extract the columns # Returns: # A list of columns names (strings) corresponding to numeric columns """ numeric_columns = lis...
6ec1cb8d1a8dd9c4cb49f17257b137e9ec0d4210
654,222
from pathlib import Path from typing import Optional def get_file_by_type(folder: Path, suffix: str) -> Optional[Path]: """ Extracts a file by the suffix. If no files with the suffix are found or more than one file is found returns `None`""" if not suffix.startswith('.'): suffix = '.' + suffix candidates = [i fo...
a062be4f3a449473b725f735a622b24432212934
654,224
def get_text_list(list_, last_word='or'): """ >> get_text_list(['a', 'b', 'c', 'd']) 'a, b, c or d' >> get_text_list(['a', 'b', 'c'], 'and') 'a, b and c' >> get_text_list(['a', 'b'], 'and') 'a and b' >> get_text_list(['a']) 'a' >> get_text_list([]) '' """ if len(list_...
ceb6b97b2b7dce802cc7d194a202211a3354fe80
654,226
def normalize_robust(feature, feature_scale=(None, 0.5)): """normalize feature with robust method. Args: feature: pd.Series, sample feature value. feature_scale: list or tuple, [feature.median(), feature.quantile(0.75)-feature.quantile(0.25)]; if feature_scale[0] is n...
87a4787972e01122635ef294483d779e5bfe5589
654,227
from typing import Dict from typing import List from typing import Set def get_parents_of(image_and_parents: Dict[str, List[str]], commit_id: str) -> Set[str]: """Returns a set of all parents of a given commit id.""" parents = None parents_list = [commit_id] i = 0 while i < len(parents_list): ...
6f59db910adf6eaa1ec211159cb065f3d599b4f6
654,233
import six def partition(list_, columns=2): """ Break a list into ``columns`` number of columns. """ iter_ = iter(list_) columns = int(columns) rows = [] while True: row = [] for column_number in range(1, columns + 1): try: value = six.next(ite...
4fc70a56ee10fc49dacae88b6dc5972941a3d947
654,234
def filt(items, keymap, sep='.'): """ Filters a list of dicts by given keymap. By default, periods represent nesting (configurable by passing `sep`). For example: items = [ {'name': 'foo', 'server': {'id': 1234, 'hostname': 'host1'}, 'loc': 4}, {'name': 'bar', 'server': ...
bdf7ffd570bcef90537fdaeb5ca7dddd02a41294
654,235
def count_lines(in_path): """Counts the number of lines of a file""" with open(in_path, 'r', encoding='utf-8') as in_file: i = 0 for line in in_file: i += 1 return i
848d6cf870f449a7ba9b9c249461f0438c62a7b0
654,239
def partition(l, condition): """Returns a pair of lists, the left one containing all elements of `l` for which `condition` is ``True`` and the right one containing all elements of `l` for which `condition` is ``False``. `condition` is a function that takes a single argument (each individual element...
3a5425143706176b6183c5d32fecd74022d2afd6
654,241
def GetKeywordArgs(prop, include_default=True): """Captures attributes from an NDB property to be passed to a ProtoRPC field. Args: prop: The NDB property which will have its attributes captured. include_default: An optional boolean indicating whether or not the default value of the property should...
9babf84558197b29e41b1693881b5b4a3f965a88
654,244
def space_check(board, position): """ Returns a boolean indicating whether a space on the board is freely available. :param board: :param position: :return: """ return board[position] == ' '
c09e93f3a51639e9a2fc94f8dfbd489745c0f40e
654,248
def _flatten_vectors(vectors): """Returns the flattened array of the vectors.""" return sum(map(lambda v: [v.x, v.y, v.z], vectors), [])
c5892018f2b3d8eaae2bd5a1bf63c1ef221fec9c
654,250
def co(self) -> tuple: """ Solve last layer face. Returns ------- tuple of (list of str, dict of {'LAST LAYER FACE': int}) Moves to solve last layer face, statistics (move count in ETM). Notes ----- If the last layer face is not solved, rotate the cube so that the yellow si...
f6324813a3db6bfcb69ba1cf03acd03de2152e95
654,252
def list2str(args): """ Convert list[str] into string. For example: [x, y] -> "['x', 'y']" """ if args is None: return '[]' assert isinstance(args, (list, tuple)) args = ["'{}'".format(arg) for arg in args] return '[' + ','.join(args) + ']'
6494c3b4a6912b2a13eba6a84a3e7d9454eb4d4c
654,257
def lower_bits(sequence,n): """Return only the n lowest bits of each term in the sequence""" return map(lambda x: x%(2**n), sequence)
b7368e04a2a535772d81f491b5d40de0d12cef32
654,261
def make_callback_dictionary(param_dict, status_flag, status_msg): """Utility function that adds extra return values to parameter dictionary.""" callback_dict = param_dict.copy() callback_dict['status_flag'] = status_flag callback_dict['status_msg'] = status_msg return callback_dict
c2fcb7d3637955359ae362ddfd5e4334aa5c2af7
654,262
import re def filter_lines(output, filter_string): """Output filter from build_utils.check_output. Args: output: Executable output as from build_utils.check_output. filter_string: An RE string that will filter (remove) matching lines from |output|. Returns: The filtered outpu...
037281b7f1b1c9b87abbcc8572e198a1f36b6165
654,263
def get_savwriter_integer_format(series): """ Derive the required SAV format value for the given integer series. savReaderWriter requires specific instructions for each variable in order to correctly create target variables. This function determines the width of the maximum integer in the given ser...
af03953c9bd9bf01982073bba643d88e67e42b1e
654,264
def get_monitor_name(domain_name: str) -> str: """ Encapsulate the RUM monitors naming convention. :param domain_name: the domain name for which a RUM monitor is to be created. :return: a Rams' compliant RUM monitor name """ return domain_name + "_RUM"
e31e24aa884c7b251c56d6c5d781ac1915c4167d
654,267
def get_release_version(version): """ If version ends with "-SNAPSHOT", removes that, otherwise returns the version without modifications. """ if version is None: return None if version.endswith("-SNAPSHOT"): return version[0:-len("-SNAPSHOT")] return version
dc8d339231ee6f6cbde1e76ee614e706b501e10f
654,269
def typeOut(typename, out): """ Return type with const-ref if out is set """ return typename if out else "const " + typename + " &"
b4c1dfad171ad1d2168a8873f5757dce4d3dbd9c
654,270
def Double_list (list_genomes): """ Create the new headers of the contig/s of the individual genomes and save the headers and sequences in different lists. In the same position in a list it will be the header and in the other its respective nucleotide sequence. """ # Create the lists: heade...
d981f27ad4d95c43010ea408fef83f982cd19959
654,272
def WrapFunction(lib, funcname, restype, argtypes): """ Simplify wrapping ctypes functions :param lib: library (object returned from ctypes.CDLL() :param funcname: string of function name :param restype: type of return value :param argtypes: a list of types of the function arguments :return:...
c2bf3ff6b7a549e965e0fbe7f20d198bdb69ed13
654,273
def teleport_counts(shots, hex_counts=True): """Reference counts for teleport circuits""" targets = [] if hex_counts: # Classical 3-qubit teleport targets.append({'0x0': shots / 4, '0x1': shots / 4, '0x2': shots / 4, '0x3': shots / 4}) else: # Classical 3-...
4b009e2d0e6885fe27bd3c103b138319c4a61637
654,276
import inspect def is_generator(func): """Check whether object is generator.""" return inspect.isgeneratorfunction(func)
489321c7e197706d541596830aa3f18b6fb01901
654,279
def org(mocker): """Fake Organisation instance.""" org = mocker.Mock() org.id = "003" org.name = "org-003" return org
d01c91c88cd40c9e71c0e589492a855a65211bac
654,282
def normalize_space(data): """Implements attribute value normalization Returns data normalized according to the further processing rules for attribute-value normalization: "...by discarding any leading and trailing space (#x20) characters, and by replacing sequences of space (#x20) ...
e95b0178e54312c7ab329bc982f8add632709c3b
654,283
def lstrip_docstring(docstring: str) -> str: """ Strips leading whitespace from a docstring. """ lines = docstring.replace('\t', ' ').split('\n') indent = 255 # highest integer value for line in lines[1:]: stripped = line.lstrip() if stripped: # ignore empty lines ...
587905876f031b5eae6e7c42e7e5b1b08d11e5d4
654,288
def PROPER(text): """ Capitalizes each word in a specified string. It converts the first letter of each word to uppercase, and all other letters to lowercase. Same as `text.title()`. >>> PROPER('this is a TITLE') 'This Is A Title' >>> PROPER('2-way street') '2-Way Street' >>> PROPER('76BudGet') '76Bu...
ec47ee1805daad73cbf44915fcc2d889d8725747
654,290
def split(l: list, n_of_partitions: int) -> list: """ Splits the given list l into n_of_paritions partitions of approximately equal size. :param l: The list to be split. :param n_of_partitions: Number of partitions. :return: A list of the partitions, where each partition is a list itself. """ ...
54252151dd5577673e5ead7884c087d28ea9190a
654,292
def new_value_part_2(seat: str, visible_count: int) -> str: """ Returns the next state for one seat. """ if seat == "L" and visible_count == 0: return "#" elif seat == "#" and 5 <= visible_count: return "L" else: return seat
6b8dcaecfd5a62fbb8a5c9333dc8ec180cc814ca
654,295
import torch def euler_to_q(euler): """Converts an Euler angle vector to Quaternion. The Euler angle vector is expected to be (X, Y, Z). Arguments: euler (B,3) - Euler angle vectors. Returns: q (B,4) - Quaternions. """ euler *= 0.5 cx = euler[:, 0].cos() sx = euler[:,...
8ffdce3ad43cf47000f50c0fb8807d2e6cef603d
654,301
import torch import math def mean_logits(logits, dim=0): """Return the mean logit, where the average is taken over across `dim` in probability space.""" # p = e^logit / (sum e^logit) <=> log(p) = logit - log_sum_exp(logit) log_prob = logits - torch.logsumexp(logits, -1, keepdim=True) # mean(p) = 1/Z s...
c54250b6083fdaafcc544ca7c9ebfca18ae8efd6
654,302
def rotate(string, n): """Rotate characters in a string. Expects string and n (int) for number of characters to move. """ if type(n) != int: return "Not an integer" if n == 0: return string if n > 0: s_new = string[0:n] l = list(string) l[0:n] = "" ...
0044e7d6f4bdf5dd96e256e0d9f911263aa5cf28
654,304
def get_seating_row(plan, seat_number): """ Given a seating plan and a seat number, locate and return the dictionary object for the specified row :param plan: Seating plan :param seat_number: Seat number e.g. 3A :raises ValueError: If the row and/or seat number don't exist in the seating plan ...
e6cee54011e3c14fb362ad8e92641b2712b2ad7c
654,307
def hex_to_int(hexa): """Convert a hexadecimal string to an int""" vals = {'a': 10, 'b': 11, 'c': 12, 'd': 13, 'e': 14, 'f': 15} num = 0 power = 0 for d in hexa[::-1]: try: num += int(d) * 16 ** power except ValueError: num += vals[d] * 16 ** power po...
77edf012bcc3a0ebacbd0d2cfee99ee4c028b8fd
654,308
def get_e_rtd(e_dash_rtd, bath_function): """「エネルギーの使用の合理化に関する法律」に基づく「特定機器の性能の向上に関する製造事業者等の 判断の基準等」(ガス温水機器) に定義される「エネルギー消費効率」 から 当該給湯器の効率を取得 (9) Args: e_dash_rtd(float): エネルギーの使用の合理化に関する法律」に基づく「特定機器の性能の向上に関する製造事業者等の 判断の基準等」(ガス温水機器)に定義される「エネルギー消費効率」 bath_function(str): ふろ機能の種類 Returns: ...
91ba3840857d8f22b808a6ab74baa84a51bdcf5b
654,309
import torch def flatten(lst): """ Flattens a list or iterable. Note that this chunk allocates more memory. Argument: lst (list or iteratble): input vector to be flattened Returns: one dimensional tensor with all elements of lst """ tmp = [i.contiguous().view(-1, 1) for i in lst] ...
8a6d38c2e8d8e031f19bd7860237a32475709bea
654,310
import logging def parse_duration(string): """Parse a duration of the form ``[hours:]minutes:seconds``.""" if string == "": return None duration = string.split(":")[:3] try: duration = [int(i) for i in duration] except ValueError: logger = logging.getLogger(__name__) ...
b239cb4c28ac6579c3ad1b42b5b13c33b32a6d64
654,311
def get_all_subclasses(cls): """ Get all subclasses of a given class. Note that the results will depend on current imports. :param cls: a class. :return: the set of all subclasses. """ return set(cls.__subclasses__()).union( [s for c in cls.__subclasses__() for s in get_all_subclasses(c...
7dff16dc4dbd481558f86fb8ac17a273ee0c742a
654,312
def module_level_function(param1, param2=None, *args, **kwargs): """Evaluate to true if any paramaters are greater than 100. This is an example of a module level function. Function parameters should be documented in the ``Parameters`` section. The name of each parameter is required. The type and descr...
b3a6ca94904bf1f1fe4d0b69db03df9f87bb1e26
654,314
def readList_fromFile(fileGiven): """Reads list from the input file provided. One item per row.""" # open file and read content into list lineList = [line.rstrip('\n') for line in open(fileGiven)] return (lineList)
e89003bf74abcd805aa4d3718caec32a7aae4df6
654,319
def rho_dust(f): """ Dust density """ return f['u_dustFrac'] * f['rho']
3c4d990b9f2fcb01c0183cedd7b66a2721001de7
654,320
def findMedian(x): """Compute the median of x. Parameters ---------- x: array_like An array that can be sorted. Returns ------- median_x: float If there are an odd number of elements in x, median_x is the middle element; otherwise, median_x is the average of the two...
6717dd19859476708b2dd3fbf5c63eb0a1832559
654,322
from typing import List def remove_existing_nodes_from_new_node_list(new_nodes, current_nodes) -> List[str]: """Return a list of nodes minus the nodes (and masters) already in the inventory (groups 'nodes' and 'masters').""" return [node for node in new_nodes if node not in current_nodes]
e87e29ee0e9592922e568a1eec1f63d5065b7bc5
654,323
from typing import Dict def get_anthropometrics(segment_name: str, total_mass: float) -> Dict[str, float]: """ Get anthropometric values for a given segment name. For the moment, only this table is available: D. A. Winter, Biomechanics and Motor Control of Human Movement, ...
be1f1ebdcbaddcc6e9fd26ab60fb72fccd89acc2
654,324
def flatten_voting_method(method): """Flatten a voting method data structure. The incoming ``method`` data structure is as follows. At the time of writing, all elections have an identical structure. In practice. the None values could be different scalars. :: { "instructions": { ...
14095dc027ea011d4a28df85cf0f1113d04f88e5
654,325
def get_youtube_url(data: dict) -> str: """ Returns the YouTube's URL from the returned data by YoutubeDL, like https://www.youtube.com/watch?v=dQw4w9WgXcQ """ return data['entries'][0]['webpage_url']
076a76f5df6ceb605a201690ac5c39972c3ddf5c
654,326
def expand_request_pixels(request, radius=1): """ Expand request by `radius` pixels. Returns None for non-vals requests or point requests. """ if request["mode"] != "vals": # do nothing with time and meta requests return None width, height = request["width"], request["height"] x1, y1, x2, ...
d0c69a5a722aef3f74863868a8687e6dca0468f2
654,327
def enumerate_tagged_methods(instance, tag, expected_value=None): """Enumerates all methods of instance which has an attribute named tag.""" methods = [] for attr in dir(instance): value = getattr(instance, attr) if callable(value): try: tagged_value = getattr(va...
665a5cd11581ad857cd3242e36ee69f21af92f89
654,330
def get_bit(z, i): """ gets the i'th bit of the integer z (0 labels least significant bit) """ return (z >> i) & 0x1
3d103fd14e13d168b1e89ede01db20a923169ef8
654,334
import torch def unit_sphere(points, return_inverse=False): """Normalize cloud to zero mean and within unit ball""" mean = points[:, :3].mean(axis=0) points[:, :3] -= mean furthest_distance = torch.max(torch.linalg.norm(points[:, :3], dim=-1)) points[:, :3] = points[:, :3] / furthest_distance ...
02814ffee5332448a0427130d4f40352e943b21c
654,337
def check_dims(matIn1, matIn2): """ function to check if dimensions of two matrices are compatible for multiplication input: two matrices matIn1(nXm) and matIn2(mXr) returns: Boolean whether dimensions compatible or not """ m,n = matIn1.shape r,k = matIn2.shape if r == n: return True else: return False
0b3baadb9902b8ad57481f06adf3910b80ba2953
654,343
def check_ascending(ra, dec, vel, verbose=False): """ Check if the RA, DEC and VELO axes of a cube are in ascending order. It returns a step for every axes which will make it go in ascending order. :param ra: RA axis. :param dec: DEC axis. :param vel: Velocity axis. :returns: Step for R...
89e9fb25eab2e0684d18b0c5123cce831521f03b
654,344
import inspect def get_estimator(estimator): """ Returns an estimator object given an estimator object or class Parameters ---------- estimator : Estimator class or object Returns ------- estimator : Estimator object """ if inspect.isclass(estimator): estimator = estimat...
e583f78659c85697e57fe01a718414175fcb2e20
654,347
def cmd_erasure_code_profile(profile_name, profile): """ Return the shell command to run to create the erasure code profile described by the profile parameter. :param profile_name: a string matching [A-Za-z0-9-_.]+ :param profile: a map whose semantic depends on the erasure code plugin :ret...
c17375dc07b1c99e9886fa14bdc10ec5ccd0a022
654,348
from pkgutil import iter_modules from typing import Iterable from typing import List def check_dependencies(dependencies: Iterable[str], prt: bool = True) -> List[str]: """ Check whether one or more dependencies are available to be imported. :param dependencies: The list of dependencies to check the availability ...
d677dcec8a112cba50aa16b37487366e13962c2b
654,352
def outName(finpName): """Returns output filename by input filename""" i = finpName.rfind('.') if i != -1: finpName = finpName[0:i] return finpName + '.hig'
b23092a5356bd6f37ac76bab5af422feb446a3f3
654,353
def _convert_node_attr_types(G, node_type): """ Convert graph nodes' attributes' types from string to numeric. Parameters ---------- G : networkx.MultiDiGraph input graph node_type : type convert node ID (osmid) to this type Returns ------- G : networkx.MultiDiGraph...
388d8b6c148ceebdad85f2b1d4ccbed7ca5d9e32
654,354
import hashlib import requests def resolve_gravatar(email): """ Given an email, returns a URL if that email has a gravatar set. Otherwise returns None. """ gravatar = 'https://gravatar.com/avatar/' + hashlib.md5(email).hexdigest() + '?s=512' if requests.head(gravatar, params={'d': '404'}): ...
91342a976953eafcdf8e6ddbd6881f6722b68034
654,355
import inspect def get_custom_class_mapping(modules): """Find the custom classes in the given modules and return a mapping with class name as key and class as value""" custom_class_mapping = {} for module in modules: for obj_name in dir(module): if not obj_name.endswith("Custom"): ...
c9682ee84c64019a17c5b4b1f3e12cba71e1463e
654,356
def labels_trick(outputs, labels, criterion): """ Labels trick calculates the loss only on labels which appear on the current mini-batch. It is implemented for classification loss types (e.g. CrossEntropyLoss()). :param outputs: The DNN outputs of the current mini-batch (torch Tensor). :param labels...
5f74a1b73b6903816ff12f1e63f403754ed4810e
654,358
def calculate_tweaked_uc_pc(job): """Calculate unit cell and primitive cell coordinates with tweaked Hydrogen coordinates""" return "../../../codes/calc_htweaked_pc_uc"
b4f89b4138ab0abaa6cd4cc09eb03e4ce8e799a0
654,364
def fill_context_mask(mask, sizes, v_mask, v_unmask): """Fill attention mask inplace for a variable length context. Args ---- mask: Tensor of size (B, N, D) Tensor to fill with mask values. sizes: list[int] List giving the size of the context for each item in the batch. Posit...
5eb4e3613ff595a18708dd0130a27ce22bfe0ad4
654,365
def build_dictionary(chars): """ Organizes data read from files in a dictionary :param chars: all chars read from files to learn :return: the dictionary """ d = {} for key in chars: for c in chars[key]: if c[3] not in d: d[c[3]] = set(c[1]) e...
3dacd5e4229d11e6962eb7383cf9259efbb8e194
654,370
def celsius_to_fahrenheit(T_celsius): """ Convert celsius temperature to fahrenheit temperature. PARAMETERS ---------- T_celsiu: tuple A celsius expression of temperature RETURNS ---------- T_fahrenheit: float The fahrenheit expression of temperature T_celsius ...
91196ec090b775681ba0d47fb6f49c485f373522
654,372