content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import inspect def override(func: FuncType) -> FuncType: """Decorator to indicate that the decorated method overrides a method in superclass. The decorator code is executed while loading class. Using this method should have minimal runtime performance implications. This is based on my idea about ...
2031eabea5041285e23aad3afcf99f8ec2d25ceb
80,288
def _make_pr(source_repo, source_branch, base_ref, base_url=''): """Create a PR JSON object.""" return { 'head': { 'repo': { 'full_name': source_repo, }, 'ref': source_branch, }, 'base': { 'ref': base_ref, 'repo'...
d32e9748608bea7f491db39a750f64cea463b50b
80,289
from typing import Dict from typing import Any from typing import Callable def recurse_dict(jdict: Dict[str, Any], pred: Callable[[str, Any], bool], repl: Callable[[str, str], str], repl_only: bool = False) -> Dict[str, Any]: """Recurse over a :class:`dict` and p...
93d7a3b5777db8b1bf41e3ee314e0a611aa2f498
80,291
def _isFloat(argstr): """ Returns True if and only if the given string represents a float. """ try: float(argstr) return True except ValueError: return False
414e802de9557b531e881a5c8430a9a2cb295339
80,292
def flatten_list(list_of_list): """Input a list of list, return a list that all items are in a list. Parameters ---------- list_of_list : a list of list Examples -------- >>> tl.utils.flatten_list([[1, 2, 3],[4, 5],[6]]) [1, 2, 3, 4, 5, 6] """ return sum(list_of_list, [])
5bf2187db9da2cdc9aa765442057a299afecd384
80,293
def comp_sqfnrm_factrd_sum(zone, ztwo, ret_sing_norms=False): """compute the squared Frobenius norm of z1*z1.T + z2*z2.T using the linearity traces and that tr.(z1.dot(z2)) = tr(z2.dot(z1)) and that tr(z1.dot(z1.T)) is faster computed via (z1*z1.sum(-1)).sum() """ ata = np.dot(zone.T, zone) bt...
df7a226ba66fffb27128f7202faa75957e6da72f
80,294
import pathlib import cmake def enable_gem_in_project(gem_name: str = None, gem_path: pathlib.Path = None, project_name: str = None, project_path: pathlib.Path = None, enabled_gem_file: pathlib.Path = None) -> int:...
6f355bb7a43466768cb955427ea5a2cf9e311e7a
80,295
from typing import OrderedDict def get_metrics_with_answer_stats(long_answer_stats, short_answer_stats): """Generate metrics dict using long and short answer stats.""" def _get_metric_dict(answer_stats, prefix=''): """Compute all metrics for a set of answer statistics.""" opt_result, pr_table = compute_p...
e758b64b4ccc7ac8f48c475a509da96308caa46e
80,296
def get_attrs(str): """ Parse attribute list and return a list of attribute tuples. """ return _scanner.scan(str)[0]
d8752a4b0ff2ee1df5dd947a36a8e58a24c97421
80,297
def _tokenize_chinese_chars(text): """ :param text: input text, unicode string :return: tokenized text, list """ def _is_chinese_char(cp): """Checks whether CP is the codepoint of a CJK character.""" # This defines a "chinese character" as anything in the CJK Unicode block: ...
a26602c32a1c396b9fe9f7362b9ae3d8c9096059
80,298
def diff_qu_cl(qu_payoff_sim, cl_payoff): """Calculation of the error from the simulated results and the classical expeted value. Args: qu_payoff_sim (real): estimated payoff from the probability of the ancillary qubit. cl_payoff (real): exact value computed classically. Returns: er...
0dc2812df4fb2ad1bb94f012743affb13dcee318
80,299
from typing import List def convex_hull_bf(points: List[Point]) -> List[Point]: """ Examples --------- >>> convex_hull_bf([[0, 0], [1, 0], [10, 1]]) [(0.0, 0.0), (1.0, 0.0), (10.0, 1.0)] >>> convex_hull_bf([[0, 0], [1, 0], [10, 0]]) [(0.0, 0.0), (10.0, 0.0)] >>> convex_hull_bf([[...
ebd9d450ead40d3838d6db78cdac2c790ec301d2
80,300
def generate_html_tree(subtree, request, id_prefix=None): """Use the HTMLBuilder to generate a version of this subtree with appropriate markup. Currently, includes no layers""" doc_id = '-'.join(subtree['label']) layers = list(generator.layers( utils.layer_names(request), 'preamble', doc_id, sec...
8b0ef72506a7779262f3b3de0c0198914427ac12
80,302
import struct import re import io def get_size(data: bytes): """ Returns size of given image fragment, if possible. Based on image_size script by Paulo Scardine: https://github.com/scardine/image_size """ size = len(data) if size >= 10 and data[:6] in (b'GIF87a', b'GIF89a'): # GIFs ...
1b45563b0f59f5670638d554821406389b5333a6
80,303
def field_name_to_echo_top_refl(field_name): """Parses critical echo-top reflectivity from name of radar field. :param field_name: Field name (must be in list `ECHO_TOP_NAMES`). :return: critical_reflectivity_dbz: Critical reflectivity. """ if field_name not in ECHO_TOP_NAMES: error_string...
d218eebaba864cb62ee54c4bcc0bd79dafb030f5
80,305
def category_grouping(data): """ Each of the features "TrafficType", "OperatingSystems", and "Browser" contain categorical values with less than 1% (123) overall datapoints. Since these "categorical outliers" could potentially skew a clustering algorithm, we will combine each value with ten or fewer...
25a461688c13b8e583cc2748c252b4035c789f48
80,306
def srgb_to_linear(c): """Convert SRGB value of a color channel to linear value.""" assert 0 <= c <= 1 if c <= 0.03928: return c /12.92 else: return ((c + 0.055) / 1.055)**2.4
805960e67b40923608d51cab2a1915aae3d1e3ba
80,308
def train_val_test_split_tabular(*arrays, train_size=0.5, val_size=0.3, test_size=0.2, stratify=None, random_state=1234): """ Split the arrays or matrices into random train, validation and test subsets. Parameters ---------- *arrays : sequence of indexables with same...
56ed30c28ad65fb1c715a008844b1f77359926e8
80,309
def _df_to_html(df): """Converts DataFrame to HTML table with classes for formatting. Parameters --------------- df : pandas.DataFrame Returns --------------- str HTML table for display. """ classes = ['table', 'table-hover'] html_raw = '<div id="config_table">{src}</di...
e1310947ff84178e0da32a8be4cda35d9ea16326
80,311
from typing import Dict import torch from typing import Optional def inference_onnx_binding( model_onnx: InferenceSession, inputs: Dict[str, torch.Tensor], device: str, device_id: int = 0, binding: Optional[IOBinding] = None, clone_tensor: bool = True, ) -> Dict[str, torch.Tensor]: """ ...
c7a31736f769f5f2a635dd7db5c4cc24376225c9
80,312
import re def _slug_strip(value, separator='-'): """ Cleans up a slug by removing slug separator characters that occur at the beginning or end of a slug. If an alternate separator is used, it will also replace any instances of the default '-' separator with the new separator. """ separato...
e60d83df1b6b11a888ef44cb297e895a4f9715ff
80,313
def farmyard_problem(heads, legs): """ There are x heads and y legs. How many chickens and pigs are on the farm? Brute-Forcing is often the easiest solution for these problems """ chickens = heads pigs = 0 for i in range(heads): if chickens*2 + pigs*4 == legs: logger...
dacf34062587d324d396da90cbf4d42ae3aa7be8
80,315
import random import colorsys def random_color(): """Generates a random color. Returns: Color as string in HEX """ hue = random.random() golden_ratio_conjugate = (1 + 5 ** 0.5) / 2 hue += golden_ratio_conjugate hue %= 1 rgb = tuple(int(i * 256) for i in colorsys.hsv_to_rgb(hue...
1e9230834cd8ddad080fcbbd52f092da5c1239f5
80,316
def get_events_form_input(request): """ Extract a dictionary of input for processing from the events form. Args: request (Request): A Request object containing user data from the validation form. Returns: dict: A dictionary of events processing parameters in standard form. """ ar...
9e09d457b2658ddf46aee9f673874640c07c06cf
80,317
def choose_theory(proc_keyword_dct, spc_mod_dct_i): """ choose between theories set in models.dat and in run.dat """ if proc_keyword_dct['geolvl']: # thy_info = tinfo.from_dct(thy_dct.get( # proc_keyword_dct['geolvl'])) spc_mod_dct_i = None # else: # thy_info = spc_mod_...
e548775d4376a6cd4d364c4820db4999dcc79062
80,318
def apply_player_action(board: np.ndarray, action: PlayerAction, player: BoardPiece, copy: bool = False) -> np.ndarray: """ Sets board[i, action] = player, where i is the lowest open row. The modified board is returned. If copy is True, makes a copy of the board before modifying it. Arguments: b...
285b56acb4200af2a0abf489b786d34283906f89
80,319
from typing import Dict import collections import csv def from_csv(path: str) -> Dict[str, str]: """Load a CSV into a dictionary.""" result = collections.OrderedDict({}) # type: Dict[str, str] with open(path, "r") as csv_file: reader = csv.reader(csv_file) for row in reader: a...
270cd3b3afe9927fffc737b57b8f49a9e6e051e4
80,320
import requests def getBidOffer(): """ Retrieves bid-offer values. """ headers = { 'accept': 'application/json', } bidOfferData = requests.get( APIUrls.lnapi+APIUrls.bidOfferUrl, headers=headers, ) if bidOfferData.status_code == 200: return bidOfferDat...
9e19e5dc1e3ebc3ac1965f9c6b9f4ca4bae81612
80,321
def loading_img_list_from_files(path): """ loading image pair list from the file :param path: path of the file to read :return: source_path_list, target_path_list, l_source_path_list ( None if there is no label), l_target_path_list (None if there is no label) """ path_list = read_txt_into_list(p...
9f4fd174fc2e373d2584565d733a26796973e7b4
80,322
def getVerifiedManagerIds(container): """Gets the list of cache managers in a container, verifying each one.""" ids = getattr(container, ZCM_MANAGERS, ()) rval = [] for id in ids: if getattr(getattr(container, id, None), '_isCacheManager', 0): rval.append(id) return tuple(rval)
8d6f0c720bfaf6b7f57ac7dbc7ae0b10de043ea2
80,324
def get_NICMOS3_G141_WCS(): """ Defines parameters for the NICMOS/G141 slitless mode @return: slitless mode parameters @rtype: dictionary """ wcs_keys = {} # WCS from NICMOS G141 image n6le01upq #/ World Coordinate System and Related Parameters wcs_keys['grism'] = [ ['WCSAX...
6f342930d4daa4c76de5ce85cbc44a976d0e6bd0
80,326
def _contextual_TokenNewlines(newlines=2, blockquoted=None, codeblocked=None): """ This function generates a TokenNewlines/TokenNewline and applies `token_apply_prefix` to it if necessary. """ if newlines == 2: token = TokenNewlines(blockquoted=blockquoted, codeblocked=codeblocked) else:...
8a3d7682d4d7a7b53d4f1e6ee48fb41b25868d5d
80,327
def parse_bucket_key_names(http_url): """Convert http url to s3 url. Convert the HTTP URL https://bucket-name.s3.Region.amazonaws.com/key-name or https://s3.Region.amazonaws.com/bucket-name/key-name to S3 URL s3://bucket-name/key-name. Args: http_url Returns: s3_url """ ...
ada48cf831138a1c836026bbe6946d96cb1a681a
80,328
def create_app(): """Create Flask Application""" app = Flask(__name__) app.config["SQLALCHEMY_DATABASE_URI"] = getenv("DATABASE_URI") app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False DB.init_app(app) @app.route("/") def root(): """At end point '/'""" return render_templ...
cf4f1ad52a17c7f917496d3e0c27c79c819ab5c5
80,329
def ask_for_matrix(initial_message, second_message): """Obtain an input in the way supported by the task""" def take_input(message, type_of_value): return (type_of_value(x) for x in input(message).split()) n, _ = take_input(initial_message, int) values = [list(take_input(second_message if i ==...
873a9b767f11eaaf59165fbc4d1a3dcb53adbd29
80,330
def ign2arr(ign_poses, robot_name): """Convert Ignition state poses into array""" arr = [] prev_seconds = None for timestamp, data in ign_poses: if robot_name in data: pos = data[robot_name] if prev_seconds != timestamp.seconds: # store only position every...
591bcd0edf981b1ff36cb725317780b5cdbf8faa
80,331
def separate_coords(df): """Separate the coordinates into a list of 'lats' and 'longs'.""" return df['coordinates'].apply(lambda x: x['latitude']), df['coordinates'].apply(lambda x: x['longitude'])
5141431e5d1d9a2a60e31867c07b50a645d48165
80,335
import math def calc_gps_distance(lat1, long1, lat2, long2): """ All calculations need to be done in radians, instead of degrees. Since most GPS coordinates tend to use degrees, we convert to radians first, and then use the Haversine formula. The Haversine formula gives the shortest great-circl...
4c38ad7a7d468b137834d87959d1c45bd00df9fb
80,336
def get_class_avg_no_0(course, assessment): """Returns the average score of the class (excluding 0s)""" scores = [result_set.get_overall_avg_no_0() for result_set in assessment.result_sets.all()] scores_no_nan = [score for score in scores if not isnan(score)] return round(np.mean(scores_no_nan), 2)
0ae1d26fc50517e8b78d0494ef4702e5d2ba96cd
80,337
def patch_workflow(workflow): """ :type workflow: dart.model.workflow.Workflow """ p = JsonPatch(request.get_json()) return update_workflow(workflow, Workflow.from_dict(p.apply(workflow.to_dict())))
754c14d3548fced85e3cf9c551b0d2a41a916e79
80,338
def _fix15_to_rgba(buf): """Converts buffer from a 15-bit fixed-point representation into uint8 RGBA. Taken verbatim from the C code for libmypaint. Args: buf: 15-bit fixed-point buffer represented in `uint16`. Returns: A `uint8` buffer with RGBA channels. """ rgb, alpha = np.split(buf, [3], axis...
9f1a4c839ad95cd590124178de6fa5f1e1fcd1b7
80,339
def get_frame_description(header, i): """ This function ... :param header: :param i: :return: """ planeX = "PLANE" + str(i) # Return the description if planeX in header: return header[planeX] else: return None
33d4b57cd936e1d0eb4b3557b8b8496b5e67db08
80,340
import typing import types import time import random import json import hashlib def generate_cn_dynamic_secret( body: typing.Any = None, query: typing.Optional[typing.Mapping[str, typing.Any]] = None, *, salt: str = constants.DS_SALT[types.Region.CHINESE], ) -> str: """Create a new chinese dynamic...
0d0f0f4c2319a8a61388f6dab1dba2590827245e
80,341
def topic_edit(request, topic_id, template_name='groups/topic_form.html'): """ Returns a group topic form page. Templates: ``groups/topic_form.html`` Context: form GroupTopicForm object topic GroupTopic object """ group = get_object_or_404(Group, slug=slu...
ebcdbff85271cfa75af8fa4698bb0f7f4da1fc84
80,342
def daily_mean(data): """Calculate the daily mean of a 2D inflammation data array. :param: 2D array of data :returns: vector of arithmetic means of data""" return np.mean(data, axis=0)
df96313ce7a49bcb970c8e9c741bc776f55eec42
80,343
def render_preamble(): """Renders HTML preamble. Include this in the HTML of each cell to make sure that #NOTEBOOK_FILES# in links is correctly substituted """ return "" # return """<script>document.radiopadre.fixup_hrefs()</script>"""
4aa366901a6ab67b30a29beb7a25844b7122a306
80,345
from datetime import datetime def parse_interval(interval: str) -> datetime.timedelta: """Parse a time interval.""" if interval in ["Y", "year"]: return datetime.timedelta(days=365) if interval in ["m", "month"]: return datetime.timedelta(days=31) if interval in ["w", "week"]: ...
10340ce33e969383471168d11913f48bcb166983
80,346
from bs4 import BeautifulSoup def process_heading(heading: BeautifulSoup, textf: str, is_toplevel: bool, single_file: bool) -> TocItem: """ Generate and return a TocItem from this heading. INPUTS: heading: a BeautifuSoup tag representing a heading tag text: the path to the file is_toplevel: is this heading at ...
218e1da630f96dabab09b4fb7e2f1f3b2534b962
80,347
import ephem def pyephem_earthsun_distance(time): """ Calculates the distance from the earth to the sun using pyephem. Parameters ---------- time : pd.DatetimeIndex Returns ------- pd.Series. Earth-sun distance in AU. """ sun = ephem.Sun() earthsun = [] for thetime ...
066af01eec671de30e85a753c831f52eef44a380
80,349
def get_shifts(n, sw, offset=None, flip=True): """Generates the frequencies that the FT of the FID is sampled at, given its sweep-width, the transmitter offset, and the number of points. Parameters ---------- n : [int] or [int, int] The number of points in each dimension. sw : [float] ...
79681580b058727ee8891b577b767c568d0a2ac1
80,350
import re def load_requirements(fpath: str) -> list: """Load requirements from file.""" with open(fpath, encoding="utf-8") as fpt: data = list(fpt) imp = re.compile(r"^(-r|--requirement)\s+(\S+)") reqs = [] for i in data: # pylint: disable=invalid-name m = imp.match(i) ...
a35b80ac2b8bdf8db15d6f2e109d494c4d9dfc79
80,351
from typing import List def _build_baseline_model(graph: Graph, interest_points: List[BaseNode]) -> Model: """ Build a Keras baseline model to compare inferences of the MP model to. The baseline model is the float model we build from the graph. Args: graph: Graph to ...
835f098a268186d07b04067d9b0da6aa6dc09030
80,352
def get_shape_ba(e): """ Return minor-to-major axis ratio ``ba`` given ellipticity ``e``. Parameters ---------- e : float, ndarray Ellipticity. Returns ------- ba : float, ndarray Minor-to-major axis ratio (b/a). References ---------- https://www.legacysurv...
0aad33ec061443d2db8dcdf03ce91f8b024170aa
80,353
from pathlib import Path def parse_layout(layout_file: Path) -> Table: """ Parses a layout in the TSV format. """ assert layout_file.match("*.tsv") file_text = layout_file.read_text(encoding="UTF-8") if "\n--\n" in file_text: raise NotImplementedError("NDS YAML header not supported")...
1a6e24a634a126536430b378becdb13688d8030c
80,354
def compare_lists(l1, l2, diff_dict): """ Compares l1 and l2 lists and adds the items that are different to the diff_dict dictionary. Used in recursion with compare_dictionaries() function. Args: l1: first list to compare l2: second list to compare diff_dict: dictionary to st...
197ea4d4fb28fc03e116ee232c356ff505c58174
80,355
def get_train_test_data(thread_fp, label_fp, train_ratio=0.6, meta_cols=["id_str","usr_id_str"], drop_irrelevant=False, visualize=True, verbose=True): """Load data with temporal train-test split""" # reading in data thread_df, seed_df = original_data(thread_fp) label_df = labeled_data(label_fp) if v...
f4a41617ac2d35cfad142797211eae5f74ecb7e0
80,357
def make_status_view(): """ Get all Ruleset object and generate the list of ruleset that show in status page Return the list for each source type of the ruleset. - GitHub with github_download_filename : [ruleset, 'github_with_direct', [download_link, latest_release, RulesetStatus]] - GitHub withou...
50135c77ca911d5b82f84f61168070458860a031
80,358
def box3d_remove_roof(boxes3d, h_prop=0.35): """ :param boxes3d: (N, 7) [x, y, z, h, w, l, ry] """ if isinstance(boxes3d, np.ndarray): rf_boxes3d = boxes3d.copy() else: rf_boxes3d = boxes3d.clone() dh = rf_boxes3d[:, 3] * h_prop rf_boxes3d[:, 3] -= dh return rf_boxes3d
d650e818ed37a4ed895850200d5a6aeb4eea4b69
80,359
def coverage_80p(y_test, y_pred, std_pred, y_pred_1d=None, y_pred_9d=None): """ Determine the fraction of the true data that falls into the 80p coverage of the model. For homoscedastic and heteroscedastic models the standard deviation prediction is used. For quantile model, if first ...
015a1e2f52fa9560de9e4fa3b6e8bd9fad68f039
80,360
def contained_coalescent_tree(containing_tree, gene_to_containing_taxon_map, edge_pop_size_attr="pop_size", default_pop_size=1, rng=None): """ Returns a gene tree simulated under the coalescent contained within a population or species tree. ``containing_tree`` ...
735ffd909cd9dec5310c0099ae1b40a9e06be106
80,362
def get_own_ip(): """Returns the IP of the current data server""" return flask.request.url_root
83671e36a8fac31b9871bdf616247e38a4f1adf6
80,363
import warnings def quiet_load(*args, **kwargs): """Like iris.load but quieter. When using `iris.load` it often generates a whole bunch of warnings, this wrapper simply supresses them. Args: See `iris.load`. Returns: See `iris.load`. """ with warnings.catch_warnings(): ...
50b7ea9d84ec6884a8047aeb2e657c971258ce3d
80,364
def interpret_float(arg): """Interpret a string representing a float, as specified by GTP. Returns a Python float. Raises GtpError with an appropriate message if 'arg' isn't a valid GTP float specification. Accepts strings accepted as a float by the platform libc; rejects infinities and NaNs....
8c143dc1f7988d75ac9680875057a49610da502c
80,365
from pathlib import Path from typing import Optional from typing import cast def get_irl_message_path( run_path: Path, irl_experts_path: Path, result: Optional[dict] = None ) -> Path: """Get the path to the IRL expert message pickle file for a specific run. Parameters ---------- run_path : Path ...
eb5a97a02b683b6a8edf6c5e2738f845341f1a40
80,366
import ctypes def ENgetpatternlen(index): """Return the number of time periods in a specific time pattern. Arguments --------- index:pattern index """ j = ctypes.c_int() ierr = _lib.ENgetpatternlen(index, ctypes.byref(j)) if ierr: raise ENtoolkitError(ierr) return j.va...
e56d2166de98bbc010497c5ea1bb4c5b3d9e5195
80,367
from typing import Union from typing import Sequence from typing import Mapping from typing import Tuple from typing import BinaryIO def Plts10(keys: Union[Sequence[str], Mapping[str, str]], tile_xyz: Tuple[int, int, int] = None, *, tile_size: Tuple[int, int] = None) -> BinaryIO: """Return...
7662d6607b1d2f13a6bb1ba4e1f71b5b9315e545
80,368
def get_model_from_type(activity_type): """given the activity, what type of model""" models = apps.get_models() model = [ m for m in models if hasattr(m, "activity_serializer") and hasattr(m.activity_serializer, "type") and m.activity_serializer.type == activity_type ...
97cd6a5e088b9dc981eb490ba12f60ed3ea26e3e
80,369
from .errors import WrongConfigFile import warnings from .errors import VerificationWarning from pathlib import Path def config(file : str = None) -> dict: """Read a defined configuration file from home-path, and set it to be used module wide.""" if file: file = join(__homepath__, file) i...
1109d8aa9f30936b16f9f11d1977070756e0d23e
80,370
import json def update_params(): """Update the params with new params. :return: (dict) spotify params """ new_params = json.loads(request.data) return status.get_resource(SONICROAD.add_config_dict(new_params))
97cc4ae6d6a762694542bd592adbeedee4397b40
80,371
def chk_win(*, end_game=True, winner=None): """ Returns True if someone won """ lpl = len(get_players()) if var.PHASE == "join": if lpl == 0: reset_modes_timers(var) reset() # This must be after reset() if var.AFTER_FLASTGAME is not None: ...
5ac88226d333c3e7129cd59213613158adcc9561
80,372
from datetime import datetime def weekday_initials(): """ Returns a list of abbreviations for the days of the week, starting with Sunday. """ # Get a week's worth of date objects week = [today() + datetime.timedelta(i) for i in range(7)] # Sort them so that Sunday is first week = sort...
09ce7eb3cb65055121bdc84b73b74528458aea44
80,373
def fibonacci(n): """returns a list of the first n fibonacci values""" n0 = 0 n1 = 1 fib_list = [] if type(n) != type(0) or n<=0: raise Exception("'%s' is not a positive int" % str(n)) for i in range(n): fib_list.append(n1) (n0, n1) = (n1, n0+n1) return fib_list
eb680c89d9d66647b24b5d27dbb34e1a8bb4352c
80,374
def get_techniques_addressed_data(mitigation, reference_list, next_reference_number): """Given a mitigation, returns a list of techniques addressed by the mitigation """ techniques_data = [] for technique in config.mitigates_techniques.get(mitigation['id']): t_id = util.get_attack_i...
ef2cccc27482d27a1d4f3d800b191b24f5db1d89
80,375
def get_layer_json(s3_layer_path, affine_matrix, output_resolution): """Generate Neuroglancer JSON for single layer. Args: s3_layer_path (str): S3 path to precomputed layer. affine_matrix (np.ndarray): Affine matrix to apply to current layer. Translation in this matrix is in microns. ou...
b145d5d21e6897e24b640ac83d540eb937d385e6
80,376
def sanitize_mobile_number(number): """Add country code and strip leading zeroes from the phone number.""" if str(number).startswith("0"): return "+254" + str(number).lstrip("0") elif str(number).startswith("254"): return "+254" + str(number).lstrip("254") else: return number
8f08563f015d77722f5dec0d07686956b4f46019
80,377
from typing import Iterable from typing import Tuple import tqdm def generate_discrete_tic(sequence: Iterable[str]) -> Tuple[list, list]: """ Generate Transcendental Information Cascades node network from the given input sequence. Args: sequence: Input sequence Returns: Tuple of ...
6cb4a59ed99e11982c965dd146ff3c30e736d7e2
80,378
def sizes(path, values): """Transform sizes.""" return free_text_list('sizes', 'size', values)
491642eb8ff2d291e27df1a2c50efeff67435d78
80,379
def send_tweet(tweet): """ Send tweet as @pythonpackages """ return twitter.PostUpdate(tweet)
fd9efb2aa818b09daf84c9beddd011e8a2976ceb
80,381
def populate(benchmark, **opts): """given a minimal dict of benchmarks, calculate hash if missing.""" fetch_expr = fetch.nixexpr(benchmark["repo"]); pop = dict(benchmark); pop.update( nixutils.verify( """ let jbx = import {filename} {{}}; inherit (jbx.p...
101be7a238a767d6f877bc505a4a292424da1cf6
80,382
import re def tokenize(sent, mimic3_embedding): """Tokenize the sentences accoring to the existing word from embedding. Args: sent: input a sentence mimic3_embedding: find the existing word in embedding files cleaned_tokens: the tokens are cleaned and mapped to the mimic embeddin...
362b8d59cc2663b9287b12e7a9faa8d689197225
80,383
def highlight(parser, token): """ Allows you to put a highlighted source code <pre> block in your code. This takes two arguments, the language and a little explaination message that will be generated before the code. The second argument is optional. Your code will be fed through pygments so you ca...
337514b382dd3ebc42623fac553996b87abfeac9
80,384
import torch def get_model(config): """Get model loaded on the device ('cpu' or 'cuda') and with pre-trained weights if specified. Args: config (YACS CfgNode): config. Raises: ValueError: Returns: torch.nn.Module: model loaded on the device ('cpu' or 'cuda') and with pre-tra...
aef501764ba0911a9dc9f89510180d79c7b60ef0
80,385
def RSI(df, columns, n, join=None, dropna=False, normalize=False, dtype=np.float32): """ Relative Strength Index :param normalize: Normalized RSI, range -1.0 to 1.0 """ sel_df = sel_columns(df, columns, join) change = sel_df.diff(1) up = change.clip_lower(0) assert len(up) > n, ...
1842e4d91098186683a48e79c0d05b8dfc789a38
80,386
def delaunay_areas(box, ch, selection): """Compute areas of selected simplices. :param ch: Convex Hull :param selection: indices of selected simplices. :return: ndarray of areas, having same shape as `selection`. """ a, b, c = ch.points[ch.simplices[selection]][:,:,:box.dim].transpose([1,0,2]) ...
61132622f90b2aae447914692d0fade893e32fab
80,387
def calculate_duration_info(sequence_durations): """Use Transition matrix to calculate serverel infos about the agent """ # Calculate ratio of each action compared to the total relative_duration = [sum(l) for l in sequence_durations] relative_duration = np.array(relative_duration) relative_durat...
7e340192e93537d37af6d829f5a26ef27f97362a
80,388
def total_seconds(timedelta): """ Some versions of python don't have the timedelta.total_seconds() method. """ if timedelta is None: return None return (timedelta.days * 86400) + timedelta.seconds
800c70a2855034563ab9baf1ca12032677889f5b
80,389
import configparser def get_smtp_parameters(config_file_sequence): """ Read the configuration files in config_file_sequence and return a dictionary of the parameter specified in their 'default' section. """ config_parser = configparser.SafeConfigParser() config_parser.read(config_file_sequ...
3517102e359973e70cbeed1e9ea3eef8fbf7c69c
80,390
def is_system_event(event: Event, before: Submission, after: Submission) -> bool: """Only for system-created events.""" return type(event.creator) is System
ad1c6df11afef768226d2c1e87ccf4fa7426d12b
80,392
def weight_name_to_layer_name(weight_name): """Convert the name of weights to the layer name.""" tokens = weight_name.split("_") type_name = tokens[-1] # Modern naming convention. if type_name == "weights" or type_name == "bias": if len(tokens) >= 3 and tokens[-3] == "input": re...
6818eb9a1aa61d7f34db6e42ad5a7872029e562f
80,393
def get_area_occupancy_hourly_report(areas: str = "", date: date = Query(date.today())): """ Returns a hourly report (for the date specified) with information about the occupancy in the areas <areas>. """ return get_hourly_metric(AREAS, areas, OCCUPANCY, date)
8b0f2a779f8fa7003f56b6231c0b24325ab985ce
80,394
from typing import Iterable def split_and_adjust_wikilinks(sentence: str, separator: str = "|", lparen: str = "[", rparen:str = "]") -> Iterable[str]: """ Simple wikilinks detector and handler for cases where there are wikilinks in wikibreaks E.g: {{wikibreak|[[User:Foo|Foobar]]|motivation}} The o...
9c791e0cfbbf46bc9abacfa2f4184701dd324b40
80,397
from typing import Iterable from typing import List from typing import Tuple def wkt_to_centers(wkt_array: Iterable[str]) -> List[Tuple[float, float]]: """ Convert an array of geometries in wkt format to their center coordinates Args: wkt_array: An array of string wkt of geometries Returns: ...
ce9d243473415fa8802c068d5d292cb901ad291e
80,399
def find_minimal_helices(nturn_starts): """ Find helices on the basis of the n-turn beginnings lists Minimal helices are defined as consecutive n-turns """ min_helices = { "3-min_helices": [], "4-min_helices": [], "5-min_helices": [] } for n in [3, 4, 5]: na...
2ceaa35efdd09de8b943c96e1caa70d86fcc8832
80,400
def _degrees_to_meters(dlon, dlat, lon, lat): """Converts lat/lon differentials into distances in meters PARAMETERS ---------- dlon : xarray.DataArray longitude differentials dlat : xarray.DataArray latitude differentials lon : xarray.DataArray longitude values l...
751550a67aa8d62d9b1a494a655b41bc3ce46118
80,401
def unscale_action(scaled_action: np.ndarray, space) -> np.ndarray: """ Rescale the action from [-1, 1] to [low, high] (no need for symmetric action space) :param scaled_action: Action to un-scale """ if not isinstance(space, gym.spaces.Box): return scaled_action low, high = space.lo...
8d73b93193a716016bfa80232ee5cd80e38a4804
80,402
def get_max_seq_len(indexed_pairs): """Return max sequence length computed from index pairs. indexes already include SOS/EOS/SEP. """ max_seq_len = 0 # max_seq = '' for indexed_pair in indexed_pairs: max_seq_len = max(max_seq_len, len(indexed_pair[0])) max_seq_len = max(max_seq_...
1830334bdea69cad996caf78e9225f70eda48dd0
80,403
def check_relationship_before_delete(object_to_del, **kwargs): """Switch to trigger differents methods depend object's type""" _, idx = get_specific_obj_type_and_idx(object_to_del) switch_check = { 0: check_function, 1: check_data, 2: check_state, 3: check_transition, ...
5db21ccb6a5cc052dd5edc0f269ab763096245ae
80,404
def test_update_word_pattern(): """Function that test several inputs for the function "update_word_pattern from hangman.py""" words = [ 'hello', 'hello', 'hello', 'hello' ] patterns = [ '_____', 'hell_', 'hell_', 'h____' ] lett...
a9aa0c5b53d1b854acbd6a1f36fa90eaa3c298c6
80,405
import inspect def class_vars(obj): """Code from https://github.com/devsisters/DQN-tensorflow/blob/master/dqn/base.py""" return {k:v for k, v in inspect.getmembers(obj) \ if not k.startswith('__') and not callable(k)}
94112e3b5746e9c16294701a0446febb9a39da13
80,406
def rssfeedmanager_manage(request, item_container): """ Pflegemodus des Ordners """ user_perms = UserEditPerms(request.user.username, request.path) add_ons = {} add_ons[0] = [ { 'url' : get_site_url(item_container, 'index.html/add/rssfeed/'), 'info': _(u'RSS-Feed')}, ] add_ons[1] = [] ad...
573f9cca55e364c8dde7de4164168b080152b5e7
80,407