content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def _from_deflection_angle(M_1, theta, weak, gamma): """Returns oblique shock given upstream Mach number and deflection angle. """ def eq(beta, M_1, theta, gamma): os = _ShockClass(M_1, beta, gamma) return os.theta - theta theta_max, beta_theta_max = max_deflection(M_1) if theta > ...
89f1507124ce48f2c5d69f93cb71540a62a4d4a2
3,601,700
def make_crash_rollup(crashes_json): """ Generates a GeoDataframe with the total number of crashes and a comma-separated string of crash dates per unique lat/lng pair Inputs: - a json of standardized crash data Output: - a GeoDataframe with the following columns: - tota...
5b1a5a79313900d0793e265e43e6170ab87f31bb
3,601,701
import platform import socket def parseargs(p): """ Add arguments and `func` to `p`. :param p: ArgumentParser :return: ArgumentParser """ p.set_defaults(func=func) p.description = "A simple sendmail implementation" p.add_argument('recipient', nargs='*') p.add_argument( "-...
5158665e1a8692d22d7fd59384ac1e946e83eaeb
3,601,702
from pytest_selenium.safety import sensitive_url as orig_sensitive_url def sensitive_url(request, base_url): """Override original fixture to change scope to module (we can have different base_urls for each module)""" return orig_sensitive_url(request, base_url)
339899ab2b12a2eea38abbc683de19ecf3468fc5
3,601,703
import requests def stac_bands(url=None, collection=None, item=None, titiler_endpoint=None, **kwargs): """Get band names of a single SpatialTemporal Asset Catalog (STAC) item. Args: url (str): HTTP URL to a STAC item, e.g., https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spo...
a1b6f2d2c5e57c3d99df1ca02247c6ca8320c19f
3,601,704
def sublists_from_list(input_list, chunk_size): """ Given a list, chunks it into sizes specified and returns the chunks as items in a new list Parameters ---------- input_list: list Original list chunk_size: int Size of sublists Returns ------- sub_lists: list ...
376780702af1ef3fd780f3964ad2cd6094135143
3,601,705
def node_short_name(node, **kwargs): """ Returns short name of the given node :param node: str :return: str """ return node
67d1d5ff172544eb2b233a925d90bbd0ea767e83
3,601,706
import signal import os import psutil def kill_proc_tree(pid, sig=signal.SIGKILL, include_parent=True, timeout=None, on_terminate=None): """Kill a process tree (including grandchildren) with signal. "sig" and return a (gone, still_alive) tuple. "on_terminate", if specified, is a callab...
179e1e2191f0ec844991673998853859a01e1387
3,601,707
def insertAsks(previous_asks, received_asks): """ Inserts multiple new asks in the order book (assumes that the order book AND the new_asks list are sorted)""" new_asks = [] if len(received_asks) < 1: return previous_asks if len(previous_asks) < 1: return received_asks # print("Prev") # ppri...
a984eafb8f93901752ac581ac5a207610e5cdbf6
3,601,708
def identity_loss(_, y_pred): """ :param _: :param y_pred: :return: """ return tf.math.reduce_mean(y_pred)
b9d6eb28a435a0f8dcb55fa13aa470cc9cb23d57
3,601,709
import itertools def minimum_bounding_n(alfa: float) -> int: """Подбор минимального ограничивающего n для заданного уровня значимости. Параметр n в формуле доверительных интервалов при последовательном тестировании отвечает за момент начала тестов. Однако для малых n интервалы имеют ширину больше 0.5, то...
bb532ad50f0187b9884ad365b7c7e772e8a589ba
3,601,710
def create_notify_payload(host, nt, usn, location=None, al=None, max_age=None, extra_fields=None): """ Create a NOTIFY packet using the given parameters. Returns a bytes object containing a valid NOTIFY request. The NOTIFY request is different between IETF SSDP and UPnP SSDP. In IETF, the 'location...
95b6a7ad37ec96d646116451340ed7ee96495632
3,601,711
from typing import Callable from typing import Any def flag(decorator: Callable): """Makes another decorator a flag. `flag` is a high level decorator that should be applied on decorators: @flag def enabled(): ... Here the `enabled` decorator can be considered as a flag, so when a...
00481ca15e1c783437c712ac1b6034ac3630e0b9
3,601,712
import math def runs(bit_str: str): """Runs Test Determine whether the number of runs of ones and zeros of various lengths is as expected for a random sequence. See section 2.3 in this NIST publication: https://tsapps.nist.gov/publication/get_pdf.cfm?pub_id=906762 """ n = len(bit_str) ...
fce124ccf0b3da512c72ae866aca70572a768692
3,601,713
def alert_source_update(context, storage_id, values): """Update an alert source.""" return IMPL.alert_source_update(context, storage_id, values)
4b76cf72f32c5bb2469f5bd41c8392a2af46e00e
3,601,714
import unittest import sys def main(module_file_name): """ > test.py # all tests, one line per test > test.py full # unittest.main(), full stacks for all tests > test.py list # lists tests without testing, one per line > test.py <other_args> errors # only show errors > tes...
16c36c2aa0bc7232c3cd12bd29598228be78decc
3,601,715
def plot_histograms(df, target = None, columns = None, rows = None, cols = None, width = None, height = None, title = None, cumulative = None, barmode = "stack", opacity = 0.65, bins = 0, hovermode = "x unified", template = None, colors = 0, font = {}, title_font = {}, legend_font = {}): """ plot_histog...
ddbe7de5e072dc482a2d390e68dffaa88e149032
3,601,716
def read_pfile(pfile_loc): """ Read in the kinetic profiles from a p file to be used as inputs (successfully tested 2018/1/3) Returns a dictionary with a non-intuitive set of keys (units are included) ** Note: pfiles don't go into the SOL ** """ with open(pfile_loc, mode='r') as pfile: ...
f43668a99648625ae9e3095e2fcd17e5d4077cff
3,601,717
import threading import logging def test(binaries, database): """ Run the test. :param binaries: The directory containing the pstore executables. :param database: The path of the database file to be used for the test :return: EXIT_SUCCESS if the test is successful, EXIT_FAILURE otherwise. """...
50c287e898a7ac827d5c6ccece1270491d54eb6c
3,601,718
def acc1(true_value, estimate_value, tolerance=0.04): """ Accuracy 1. :param true_value: reference value (must not be zero) :param estimate_value: estimated value :param tolerance: tolerance :return: true or false """ return same_tempo(true_value, estimate_value, factor=1.0, toler...
754111efee53beae2b069040b85ef5965f17a2f2
3,601,719
def newer(source, target): """ distutils.dep_utils.newer with zipfile support """ try: return zipio.getmtime(source) > zipio.getmtime(target) except IOError: return True
73373c191d7b51257c9d5b889a1fb4ee0e3582dd
3,601,720
from sys import path def test_adding_object_name(use_list=None, use_obj_dir=None, check_fits_file=None): """ Test adding object name Provide `use_list` to override the default object file name. Provide `use_obj_dir` to specify directory in which...
c1ef7c93aec63aba1ae83163c6668f72a87055df
3,601,721
def config_get(section, option): """ Return the string value for a given option in a section :param section: the named section. :param option: the named option. . :returns: the configuration value. """ return __CONFIG.get(section, option)
6856d3e17f44d5a60469204ed772798be151f6b0
3,601,722
import os import json import pickle def build_temporada( region: str = "Granada", lang_source: str = "es", plot_matrix: bool = False, assets_paths: str = "./assets", verbose: int = 1, ): """Build a sparse seasonality matrix from two text files (local-seasonal + permanent) Args: as...
c22b261a1d5a9a5f161f16290b36ef8bc72f0b0b
3,601,723
def clear_data(table, where): """ Remove all rows from the table matching the expression in the where clause, returning a count of deleted records. :param table: name of table to search :param where: where clause to find records to delete :return: count of deleted rows :rtype int """ ...
d365942d2e9c6eb686d5327f80386e148d050569
3,601,724
def solve_sudoku(sudoku: np.matrix): """Solve the input sudoku puzzle recursively by guessing a number and then trying to solve the remaining puzzle. N.B.: To avoid copying data each time a new recursion level is entered, the input sudoku is solved in-place. """ for y, x in product(range(9), range(9)):...
08a8a8227302c9468ddcd23b0d0c0fbb9f68526a
3,601,725
import pathlib import pickle def positional_data(experiment, dimensions='2d', pattern='pose_result', base_path=None, experiment_path_template=None, positional_data_path_template=None, return_experiment_id=False): """ Returns the positional data for the given experiment. Parameters: ...
c587d5da797e307295a1f7289863f30aa28b6cd6
3,601,726
def conv_relu_forward(x, w, b, conv_param): """ A convenience layer that performs a convolution followed by a ReLU. Inputs: - x: Input to the convolutional layer - w, b, conv_param: Weights and parameters for the convolutional layer Returns a tuple of: - out: Output from the ReLU - cache...
eeb9a3ef903176893892ba484da48cd35a79358b
3,601,727
import numbers import math import cmath def atan(x): """ Uncertain number arctangent function .. note:: In the complex case there are two branch cuts: One extends from :math:`\mathrm{j}` along the imaginary axis to :math:`\mathrm{j}\infty`, continuous from the right. ...
470af67f67a6c5c1aa63fb28b5590c4f699c988c
3,601,728
import os def cpu_time(reference_cpu_time = 0.0): """ Returns current or elapsed value of CPU time used by the process, including both user and system CPU time of both the process itself and its children. """ return sum(os.times()[:4]) - reference_cpu_time
9aee8973bea50d89e08dbf3d0c77ad4cfc252657
3,601,729
from typing import Callable from re import T def is_owner() -> Callable[[T], T]: """A :func:`.check` that checks if the person invoking this command is the owner of the bot. This is powered by :meth:`.Bot.is_owner`. This check raises a special exception, :exc:`.ApplicationNotOwner` that is derived ...
25e59ed874931024cd43738033998b9220cb1344
3,601,730
import os from pathlib import Path def get_config_file_path(): """ Return the config path. ODAHUFLOW_CONFIG environment can override path value :return: Path -- config path """ config_path_from_env = os.getenv('ODAHUFLOW_CONFIG') return Path(config_path_from_env) if config_path_from_env ...
4278080f9b6bd59dc96c1e83652edf009c7f039f
3,601,731
def create_hash_chain(*args: tuple[str, str, int]) -> HashChainNode: """Create a HashChainNode based on the args""" head = None curr = None for sender, recipient, amount in args: if head is None: node = HashChainNode(Transaction( sender, recipient, amount), is_head=Tr...
f2f201b8ecbcf381fc217c84be1409187e246cc9
3,601,732
def dict_option(s): """An option of type 'dict'. The value (on the command-line, in an env var or in the config file) must be eval'able to a dict. """ return _convert(s, (dict,))
93b574b33f44a144c52b0cde3403cba3646fb7a1
3,601,733
import nd2reader from ..app.script_editor import ScriptEditor import skimage.io import os import time import re import subprocess import sys def open_file(filename=None, from_gui=False): """ open_file(filename=None) Opens an image or movie file (.tif, .stk, .nd2) into a newWindow. Parameters: fil...
fc361e81f1f104326bd5dfb1d5e1d4ee76ddb5d9
3,601,734
def get_present_volume(present): """Calculate volume of the box needed for present.""" volume = 1 for side in present: volume *= side return volume
e3df95638a741513307163abd90a68013aa7da3b
3,601,735
def crop_rasters_for_sr(max_sr_factor, *hmaps): """Crop a list of rasters to a size such that they can be evently divided by ``max_sr_factor``. It assumes that each raster is centered identically. I.e. if one raster has size 256x256 and another 254x254, it assumes that it is a border of size 1 that is r...
77b45841cb82bc5475c6343df05c91b04d4e74c8
3,601,736
def fit(model): """Represents a general fit process. Parameters ---------- model : uncertainty-aware model Represents the fitted uncertainty-aware model. Returns ------- ensemble : list Returns a list of fitted base estimators. """ global fit_state # Set global ...
9e1ad91f4919acd4d66ca1b53099aa314eb357f2
3,601,737
from datetime import datetime def beta(pos: TimeSeriesInterface, benchmark: TimeSeriesInterface, lookback: str = None, date: datetime = None, **kwargs) -> float: """ Compute the beta of the returns distribution from a TimeSeries object on a benchmark on the specified time period. :param pos: Tim...
c362fcaa881162dfbeeed36a617710cac90b7f69
3,601,738
def merge_with(x, other): """Returns a shape combining the information in `x` and `other`. The dimensions in `x` and `other` are merged elementwise, according to the rules defined for `tf.Dimension.merge_with()`. For more details, see `help(tf.TensorShape.merge_with)`. Args: x: object representing a sh...
dd38fbfa98d892bbeab58cd76b6304fbeab90c3c
3,601,739
from typing import Tuple def scale_coordinates( reference_coords: CoordinatePair, reference_size: Tuple[int, int], target_size: Tuple[int, int], ) -> CoordinatePair: """Compute the coordinates corresponding to a scaled version of the image. Parameters ---------- reference_coords: Coordina...
eea199864ed73b48859b08b3412b591df2a82f22
3,601,740
def sklearn_flatten(input_xr): """ Reshape a DataArray or Dataset with spatial (and optionally temporal) structure into an np.array with the spatial and temporal dimensions flattened into one dimension. This flattening procedure enables DataArrays and Datasets to be used to train and predict...
6f753b3dc0827b0852f2020e3e374b83ab0678c5
3,601,741
def semeval2conll(dataset): """ transform the format of semeval datasets to conll form :param dataset: input dataset :return: """ conll_lines = [] for record in dataset: ote_raw_tags = record['ote_raw_tags'] ts_raw_tags = record['ts_raw_tags'] words = record['words'] ...
1c6ad2c5e27a1e8c2a5603768c96cc5dc82b8508
3,601,742
def login(): """ Show login form """ session.clear() if request.method == "POST": if not request.form.get("username"): flash("Must provide a Username", "alert-warning") return render_template("login.html") elif not request.form.get("password"): flash("...
47cefc6c1bfaa4c2bee7f66475603cc8bc9ae4f0
3,601,743
def form_folder(groups): """ take in a date tuple and form the folder name """ month = groups[0] day = groups[1] year = groups[2] if month in month_map: month = month_map[month] else: logger.error("month ({}) not in month_map. this should never happen".format(month)) return None if len(day...
1f069e5ea27f5c9bdd1f02d3ff1a0aa31ec69007
3,601,744
def get_user_from_dict(user, data_coleta=None): """Return user metadata.""" # pylint: disable=too-many-locals # remove space and _ from name and screen_name name = _pre_processing(user.get('name')) screen_name = _pre_processing(user.get("screen_name")) background_image = 1 if user.get('profile_...
a3baaf14659dfcaadf46885100e5f12f1d3f4579
3,601,745
def wtap_damage_assessment(probabilities, assignment, target_values): """ :param probabilities: graph. :param assignment: graph :param target_values: dictionary :return: total survival value of the targets. """ assert isinstance(probabilities, Graph) assert isinstance(assignment, Graph) ...
5e7ac8bfc7eda568a4ae2c106e7319a11ea502bf
3,601,746
def track_score(track_path): """ Scoring the proposal tracklet can b associate 2 st_track possibility. Score = weight_motion * score_motion + weight_appearance * score_appearance :return: """ path_score = 0. for each_node in track_path: path_score += each_node.score return path_s...
8633bdbff8520e94e775d34b64bc448fa3b9366b
3,601,747
def interpolate(df, verbose=True, prev_df=None, next_df=None, sr=None, start_time=None, stop_time=None, fill_big_gap_with_na=True, gap_threshold = 1, method="spline"): """Make timestamps with consistent intervals with interpolation. Delete duplicate timestamps, interpolate to make sampling rate consistent wit...
ec96ec758025cffb8b3cd00a09ad5ef5e3554bad
3,601,748
from typing import Mapping from typing import Type from typing import DefaultDict from typing import Dict import difflib def apply_args_filters( args, ) -> Mapping[str, Mapping[str, Mapping[str, Type[InstanceConfig]]]]: """ Take an args object and returns the dict of cluster:service:instances Currentl...
4b8b638899cfce025b508d67c7d9dcb08c969452
3,601,749
import requests def get_sensor_map_request(sensor_class, dates_selected, group, cum_hours, geo_win, interpolator, img_dim, radius, stream=False): """ get a map for the selected sensor on the selected geowindow :param sensor_class: sensor class strin...
912b6b2fb6763fa4b7653a051b0f8d35c85cdda1
3,601,750
from typing import Union from typing import Sequence def repsep( parser: Union[Parser, Sequence[Input]], separator: Union[Parser, Sequence[Input]] ) -> RepeatedSeparatedParser: """Match a parser zero or more times separated by another parser. This matches repeated sequences of ``parser`` separated by ``s...
fc1ac9e5eae16ae1d589a52caea1310d309c9a56
3,601,751
import itertools def get_available_languages(include_default=True): """ Returns a tuple of available languages for django-modeltrans. """ MODELTRANS_AVAILABLE_LANGUAGES = get_available_languages_setting() if include_default: return tuple( set(itertools.chain(MODELTRANS_AVAILAB...
4f61b99e203c07be0329114b44b42b41f7f7b555
3,601,752
def argmin_except_0(x,p): """ argmin_except_0(x,p) Ensure that p is the argmin, i.e. the position of the minimum value in x, but ignores any value of 0. Note: - If there are many minimum values then argmin_except_0(x,p) will find all these values. - We assume that there are at least one value > 0....
26fe8ed14044147bc8963fecdb1f73af17ddee5b
3,601,753
def font_size_norm(x): """the web font size is different from the game client's - try to approximate how it would look without having to know the actual value.""" try: x = int(x) except ValueError: return "100%" ratio = x / 24 return f"{int(ratio * 100)}%"
d70679ec385abe0cb283aa4615853e8b5e1a853e
3,601,754
import sys import os def read_in_file(path: str, filename: str, mode: str = "r"): """Reads in a file and strips off the last index which will be a newline ('\\n') character. imports: os, sys Attributes: path [str]: Path to the file with all forward slashes required. filename ...
2dac0f470af61ba845047260fb36fd1bea577e87
3,601,755
def load_vec_data_year(filename): """ give a save filename with a saved vector data year creates a vector data year from what was saved """ try: npzfile = np.load(filename) x = npzfile["DY_x"] y = npzfile["DY_y"] except KeyError: pass else: temp_tim...
eb2cffd72575166a317af9e67c82858cdb995693
3,601,756
def max_col_by_col(arrays,NaN=False): """Perform column by column max""" colmax=[] for arr in arrays: if not colmax: colmax=arr[:] else: if NaN: colmax=[max_w_nan([colmax[i],arr[i]]) for i in xrange(0,len(arr))] else: c...
6f5fb44bdf3d8eef06b2c8b6f937d0c36d76ddb5
3,601,757
from typing import List from typing import Callable from typing import Optional from typing import Tuple import logging from datetime import datetime def __create_missing_replicas_and_requests( transfer_path: "List[DirectTransferDefinition]", default_tombstone_delay: int, logger: "Callable", ...
3d28144f9f3f54ccaa5e2da749f73bdb3f84aee8
3,601,758
def preprocessIncome(df, numOutliers): """ Function for preprocessing income and adding net income """ #print('Min kereset: ', df['htnetto'].min()) #print('Max kereset: ', df['htnetto'].max()) # Droping out outiers for i in range(0, numOutliers): df.drop(df[df['htnetto'] == df['...
0d0666ce37c1538216766de51d9cc0ea4c2932a1
3,601,759
import dlib def det_landmarks(image_path, dlib_model="E:/ModelZoo/shape_predictor_68_face_landmarks.dat"): """ detect faces in one image, return face bbox and landmarks :param image_path: :return: """ predictor = dlib.shape_predictor(dlib_model) detector = dlib.get_frontal_face_detector() ...
213258555a320274a86d6fd6da603d4518fe9fa0
3,601,760
def all_resolve_success(subdomains): """ 判断是否所有子域都解析成功 :param subdomains: 子域列表 """ resolver = utils.dns_resolver() resolver.cache = None # 不使用DNS缓存 status = set() for subdomain in subdomains: status.add(query_a_record(subdomain, resolver)) return all(status)
ae618a4d41595bc404abe26b761772c56567ca9c
3,601,761
import array def get_Is(self): """Return the stator current DataTime object Parameters ---------- self : OutElec an OutElec object """ # Calculate stator currents if Is is not in OutElec if self.Is is None: # Generate current according to Id/Iq Isdq = array([self....
3a64b6621c3cbaed7c0ef9e5ca6d1f6fbcaa9fbc
3,601,762
import os import shutil def compute_dice(fname_ref_seg, fname_manual_seg): """ Computes dice coefficient between the ground truth segmentation and a candidate's manual segmentation. Args: fname_ref_seg (str): file name of the ground truth segmentation. fname_manual_seg (str): file name of ...
843259a2a2205364343545c47bf07bf4f25254a3
3,601,763
def shared_rid_input(app): """Access DB directly. Get a random msmt that has a match both in the measurement and fastpath tables Returns (rid, input) """ sql = """ SELECT fastpath.report_id, fastpath.input FROM fastpath WHERE input IS NOT NULL AND fastpath.report_id I...
70ef5985de2d29473db8d499e83f5e71be6096a6
3,601,764
def apim_api_operation_get(client, resource_group_name, service_name, api_id, operation_id): """Gets the details of the API Operation specified by its identifier.""" return client.api_operation.get(resource_group_name, service_name, api_id, operation_id)
4101a7aa2b3815856bf852a299698d407af390c0
3,601,765
def excel_to_json(file_path: str, sheet_name: str = None, want_sheet_names: bool = False) -> dict: """ This function reads the excel file and converts it to JSON :param file_path: :param sheet_name: :param want_sheet_names: :return: """ sheet_data = {'columnDefs': [{'headerName': "", 'fi...
ac8245c06b252dfa1a40d34987f530b1dd631673
3,601,766
def getEnumStr(obj, enum): """ Helper function that returns the names of enums for a property" """ enumStr = None for enumName,val in vars(obj).iteritems(): if not enumName.startswith('__') and enumName not in IGNORED_TYPES: if val == enum: enumStr = enumName ...
8474db290e2249c39f4f9cd46a1f5297c2b4ce6f
3,601,767
def _uses_vulnerable_solc_version(version): """Detect if used compiler version is 0.4.[0|1|2|3|4] Args: version (solc version used) Returns: Bool """ if version in ["0.4.0", "0.4.1", "0.4.2", "0.4.3", "0.4.4"]: return True return False
475dff3c6d3ed71317aab79e147f8797bde85f3a
3,601,768
def entries_lto(test_dir): """ Recycle the test cases from pymatgen """ entries = loadfn(test_dir / "LiTiO2_batt.json") for itr, ient in enumerate(entries): ient.entry_id = f"mp-{itr}" return entries
e08c0942c7152582b60a77b752071e19eb801749
3,601,769
import hashlib def get_subscriber_hash(member_email): """ The MD5 hash of the lowercase version of the list member's email. Uses as memeber_id """ member_email = member_email.lower() m = hashlib.md5(member_email) return m.hexdigest()
c2d7c7f4d0da58ec3990cccad865cb53cf2ebe15
3,601,770
def set_ax_info(ax, **kwargs): """Set Axes information Args: ax (Axes) : The ``Axes`` instance. kwargs : ``key`` indicate the method which is start with ``set_``, and the method takes arguments (``val``) according to the type of ``val`` Returns: ax (Axes) : The ``Axes`` instance...
f54d959b83464071eda6efec2a9189b47addec34
3,601,771
import threading def _wait_for_emulator_ready(proc, emulator, indicator, timeout=_EMULATOR_TIMEOUT): """Waits for emulator to be ready.""" def _read_thread(proc, ready_event): """Thread to continuously read from the proces...
3e3274ab214ff1a9c6b02bf500f82812ec3f8b22
3,601,772
def Reverse(action): """Reverses the behavior of the action Example:: # rotates the sprite 180 degrees in 2 seconds counter clockwise action = Reverse( RotateBy( 180, 2 ) ) sprite.do( action ) """ return action.__reversed__()
9bde87421204300e55fff80eed0564f4b4d8e978
3,601,773
def outside_root_to_404(fn): """ Decorator for converting PathOutsideRoot errors to 404s. """ @wraps(fn) def wrapped(*args, **kwargs): try: return fn(*args, **kwargs) except PathOutsideRoot as e: raise HTTPError(404, "Path outside root: [%s]" % e.args[0]) ...
d207eaf44d6be860d6203b802c0768718554e15d
3,601,774
def affine_grid_backward(*grad_hess, grid=None): """Converts ∇ wrt dense displacement into ∇ wrt affine matrix g = affine_grid_backward(g, [grid=None]) g, h = affine_grid_backward(g, h, [grid=None]) Parameters ---------- grad : (..., *spatial, dim) tensor Gradient with respect to a den...
2d09d2ab4bb2e82fa41483f8fa81b72ece8d150c
3,601,775
def SurfaceStart(builder): """This method is deprecated. Please switch to Start.""" return Start(builder)
5d96a51e634aa47479b5a12f4aa8ad4983c89022
3,601,776
def CI_sum_prop(estimates, mul_CIs): """ This function calculates the 95% confidence interval of a sum of two estimates. We assume these estimates are distributed lognormally with 95% confidence interval provided as input Input: estimates: numpy array of the estimates to sum over mul_CI...
7fd582042796aa2441b1ce89920093bb6c8a0cfb
3,601,777
from datetime import datetime def prune(iterable, start, end): """Discard events that fall outside the start-end interval.""" events = sorted(iterable, key=lambda event: event.created_at) events.reverse() # Check if we have at least one event older than the start date. # If so, then we have a com...
d69be8ef507347049b4fc59938378eb108cc8ee4
3,601,778
def get_licenses(obj): """ Returns a list of license under which the given language resource is available. """ result = [] for dist in obj.distributioninfotype_model_set.all(): for licence_info in dist.licenceInfo.all(): result.append(licence_info.licence) return result
09cbadcc55b15d189c0f19095351fdb2d9d526e3
3,601,779
def patches(internal_api_patcher): """ Fixture that resets session-wide patches before each test case function """ for mock in internal_api_patcher.patcher_mocks: mock.reset_mock() return internal_api_patcher
05bacb7491e7178a324c07da4c67fad0b1fed01c
3,601,780
def get_all(isamAppliance, check_mode=False, force=False): """ List the current nodes in the cluster """ return isamAppliance.invoke_get("List the current nodes in the cluster", "/isam/cluster/nodes/v1", requires_model=requires_model)
9a4c50d494facdfa914ae59f6671cc402b788e12
3,601,781
def bin(x, y, bins=10, range=None): """ Bin x and returns lists of the y-values inside each bin. Parameters ---------- x: array-like Variable that is binned. y: array-like Variable that is sorted according to the binning of x. bins: integer or array-like Number of bins or ...
997cee04e25f30979a02ee39dd4019e4af4a5252
3,601,782
import subprocess def get_num_revisions(filepath: str) -> int: """Given a filepath, get the number of revisions made to it""" cmd = ["git", "log", "--pretty=format:%aI", "--", filepath] logger.debug("Running command: %s", " ".join(cmd)) result = subprocess.run(cmd, capture_output=True) history =...
4f2f81cda20f0016d53a1a93d80c9b69c0d0e00d
3,601,783
from typing import List def verify_security(headers_dict: dict) -> List: """ Check the headers contained in the HTTP response against the list of security headers recommended by the OWASP Secure Headers Project Args: headers_dict (dict): dict of header names and descriptions Returns: ...
181a60e7f717f3c89e997820dbc46971179f5e5a
3,601,784
import torch def add_ligand_atom_to_data(data, pos, atom_type, y_ind, type_map=[1,6,7,8,9,15,16,17]): """ """ data = data.clone() data.ligand_context_pos = torch.cat([ data.ligand_context_pos, pos.view(1, 3).to(data.ligand_context_pos) ], dim=0) data.ligand_context_feature_full = tor...
f3d1ca6d961542e6ec029f1d8fa6e2d22a4cc164
3,601,785
def readKiKitProps(footprint): """ Given a footprint, returns a string containing KiKit annotations. Annotations are in FP_TEXT starting with prefix `KIKIT:`. Returns a dictionary of key-value pairs. """ for x in footprint.GraphicalItemsList(): if not isinstance(x, pcbnew.FP_TEXT): ...
98effcdecd5e77eac1fb15ea691a46bd126f6682
3,601,786
import os import re def find_date(filename, header=None): """ Finds the date in the filename or the file's header Parameters: ---------------------------------------------------------------------------- filename: string The name of the file to search header: None or list...
7840033cd5d5d82e9ee8d9d7e5a2f687a09cbdda
3,601,787
def add_dashboard_to_flask(server): """Create a Plotly Dash dashboard with the specified server. This is actually used to create a dashboard that piggybacks on a Flask app, using that app its server. """ dash_app = Dash( __name__, server=server, routes_pathname_prefix='/dash-upload/', ...
06dc62bcc79f29f5414dbc2e024970de96356802
3,601,788
from typing import Dict from typing import Any from typing import Iterable def _get_properties(rsp: Dict[Text, Any]) -> Iterable[CdProperty]: """ Retrieve key properties to be passed onto dynatrace server. """ machine_type = rsp.get("machineType", "/").split("/")[-1] labels = [CdProperty(label, value) for...
3921bc1613bad9166bf2486f5596b88f3af24086
3,601,789
def SplitExpectationsByStaleness(test_expectation_map): """Separates |test_expectation_map| based on expectation staleness. Args: test_expectation_map: A dict in the format returned by CreateTestExpectationMap() with any unused expectations already filtered out. Returns: Three dicts (sta...
4708346a83b6e98bfec35f49ece6a55dda16cd3c
3,601,790
def load_match(fn, create_part=False, pedal_threshold=64, first_note_at_zero=False): """Load a matchfile. Parameters ---------- fn : str The matchfile create_part : bool, optional When True create a Part object from the snote information in the match file. Defaults to False....
e87fb039ccfa6f555b6352cefbf093f18363f5ff
3,601,791
def get_frame_number(frame): """Get frame number by calculating distance to newest frame.""" num = 0 newer = frame.newer() while newer != None: newer = newer.newer() num += 1 return num
1b653a629d9e34af2cfa1ce37bea54644a18236a
3,601,792
from typing import Optional import re def convert_message(message: str) -> Optional[str]: """Extract release note from the commit message, return None if there is no release note""" if RELEASE_NOTES_TAG in message: # new if match := re.findall(RELEASE_NOTES_RE, message): return...
a47281276ca2036917d855b8b92ee543f729a878
3,601,793
def separable_conv_block(inputs, filters, dilation_rates_and_kernel_sizes, **kwargs): """A block of separable convolutions.""" return conv_block_internal(separable_conv, inputs, filters, dilation_rates_and_kernel_sizes, **kwargs)
2de04fd4ec0c13b8cce3fa6ab2e27ab39c9f452e
3,601,794
def make_terminal(edu, edu_i, relation, nuclearity): """ Parameters ---------- edu: str edu_i: int relation: str nuclearity: str Returns ------- Terminal """ # node = Terminal(token=edu, index=edu_i, label="<%s,%s>" % (relation, nuclearity)) node = Terminal(token=edu...
ff9da81f01d69bc865a2f2dd6dde34fc61c9056e
3,601,795
from typing import Tuple from typing import List def get_ema_tick_imbalance_bars(file_path_or_df: Tuple[str, pd.DataFrame], num_prev_bars: int = 3, expected_imbalance_window: int = 10000, exp_num_ticks_init: int = 20000, exp_num_ticks_constraints: List[f...
1ff32901b1c406c54ce43ec95b90c89a2e7d038f
3,601,796
from scipy.stats import norm def match_end(ref, hyp, args): """Match end boundary given distribution.""" score = 0.0 collar = args.collar if args.distribution == "uniform": if (ref - collar < hyp and ref + collar > hyp): score = 1.0 elif args.distribution == "triangular": ...
a3545181eb759af74338fb215b7918f397ebfb2c
3,601,797
import torch def batch_l2(kernels): """ Args: kernels: (num_kernels, bsize, bsize) """ n = kernels.shape[0] kernels = kernels.view(n, -1) # (n, bsize*bsize) distances = torch.cdist(kernels, kernels) distances = distances - torch.diag(torch.diag(distances)) return - distances.m...
0d1d9d1544cf98a0ae92e34e6ed739dadc6ef5f5
3,601,798
def get_problem_summary(category): """Create the summary for the issue title.""" if category == 'unknown_bug': # In this case, we need a special message return 'see bug description' else: # Return the usual message in lowercase # because it is not at the start of the summary....
3b993e8ee2f9e95ea96280c588417550ea0f26a2
3,601,799