content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def define_radius_by_order(node_loc, elems, system, inlet_elem, inlet_radius, radius_ratio): """ This function defines radii in a branching tree by 'order' of the vessel Inputs are: - node_loc: The nodes in the branching tree - elems: The elements in the branching tree - system: 'strahler','hor...
9001a09d22e255d48fd9f0ec715f78d019e3c657
3,608,025
def produce_labels(y, return_stats=True): """Produce labels array from e.g. event (unordered) trigger codes. Parameters ---------- y : ndarray, shape (n_epochs,) Array of trigger codes. return_stats : bool Whether to return optional outputs. Returns ------- inv : ndarr...
d89c419121a6f3ca0eff615d777489b31d7f2b41
3,608,026
def getSampleType(name): """Given a sample name return the sample type""" backgrounds = open("share/sampleNamesShort.txt").readlines() backgrounds = [i.rstrip("\n") for i in backgrounds] signal = ['TTS','BBS','TTD','BBD','XX','YY','zprime'] data = ['data'] sampletype = '' if name=='data': ...
82055b2df095e1771f9bd616d6a04759ef16c7ef
3,608,027
def read_szf_fmv_12(eps_file): """ Read SZF format version 12. beam_num - 1 Left Fore Antenna - 2 Left Mid Antenna - 3 Left Aft Antenna - 4 Right Fore Antenna - 5 Right Mid Antenna - 6 Right Aft Antenna as_des_pass - 0 Ascending - 1 Descending swath_indicator -...
2b4db2a6a2bbfe46302ea4d4d0fff4f7dab72336
3,608,028
def ped_liposarcoma(): """Create pediatric liposarcoma fixture.""" return { "label_and_type": "ncit:c8091##merger", "concept_id": "ncit:C8091", "xrefs": ["mondo:0003587", "DOID:5695"], "label": "Childhood Liposarcoma", "aliases": [ "Liposarcoma", "...
f69e480a449c9ecb8ceda3d8f14ec777afc769f3
3,608,029
def _prepare_float(data: str) -> str: """ Removes unnecessary characters from the string representing an integer """ return data.replace(",", ".")
ef786b391b6b510b95b52958d73efd7890d05b10
3,608,030
def random(self): """ :param seed: Put a seed to generate random FSMs (default: "seed") :param min: The minimum number of inputs or outputs in the FMS (included) :param max: The maximum number of inputs or outputs in the FMS (included) :param states: :return: A pack of random FSMs """ se...
fd2c928485bb5d9c8974f659996291d2b96c2bef
3,608,031
def translate_circuits(circuits, alias_dict): """ Applies :function:`translate_circuit` to each element of `circuits`. Creates a new list of Circuit objects from an existing one by replacing operation labels in `circuits` by (possibly multiple) new labels according to `alias_dict`. Parameters ...
d0722d18fd3ac79f0f17b37804048a82b6562020
3,608,032
import math def place_tacks(start, end, boat, wind): """Places tacks between two waypoints. Algorithm description: If no tacks are required, add the last point and return. Otherwise Get favored side and confidence on [-1, 1] Set lateral boundaries on the beat (r_bound, l_bound) ...
cf99341dfba65c4424e467f30324e30c0301fd17
3,608,033
import numpy def w_cache_predict(theta, lam, uvw, src, guv, wstep=2000, kernel_cache=None, kernel_fn=w_kernel, **kwargs): """Predict visibilities using w-kernel cache :param theta: Field of view (directional cosines) :param l...
1ce7f54ca22690b199cd7db5b57927f4f061fdb0
3,608,034
def eval_trace2vec(log): """Evaluate different parameter sets for trace2vec. This function starts with a baseline trace2vec model and varies different parameters in isolation to check how they affect the resulting accuracy of the model. The parameters under investigation are: window size, batch siz...
16b454d0c22b7243934e88b4a89126aaa3beab5e
3,608,035
import tqdm def find_shortest_time(source, target, cave): """ Use a modified version of Djikstra's algorithm. """ # Initialize algorithm unvisited = set() distances = {} options = SortedList() # Used for finding minimum - stores in format (distance, x, y, t) for x in range(cave.shape[...
24e2d8d242774d2e9b1fec2f4588073ce40f22ee
3,608,036
import numpy.oldnumeric as Numeric def vvmult(a,b): """ Compute a vector product for 3D vectors """ res = Numeric.zeros(3, 'f') res[0] = a[1]*b[2] - a[2]*b[1] res[1] = a[2]*b[0] - a[0]*b[2] res[2] = a[0]*b[1] - a[1]*b[0] return res
0c5f5d80aa716b7dd8d1b0a9193efdeb53450a64
3,608,037
import hashlib def generate_ext(content_type, body): """Implements the notion of the ext as described in http://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-02#section-3.1""" if content_type is not None and body is not None and len(content_type) > 0 and len(body) > 0: content_type_plus_body =...
f4ee3845c68333b51c05ba2bba48e31ac4c989bd
3,608,038
import warnings def fit_2dgaussian(data, error=None, mask=None): """ Fit a 2D Gaussian plus a constant to a 2D image. Parameters ---------- data : array_like The 2D array of the image. error : array_like, optional The 2D array of the 1-sigma errors of the input ``data``. ...
a573ec1def4602dfea7d309c8b7de6d5b325eeab
3,608,039
def auth_backend_configured(name, mount_point, config): """ Configure the already enabled backend. :param name: ID for state definition :param mount_point: The mount point of the backend :param config: Dictionary with the config values to set. """ ret = { 'name': name, 'comm...
ff6a874bc00f853b6855c5a251f55674a5ce7aec
3,608,040
from mashcima.generate_staff_lines import generate_staff_lines from mashcima.transform_image import transform_image as transform_image_function from typing import Optional def multi_staff_annotation_to_image( repo: SymbolRepository, main_annotation: str, above_annotation: Optional[str], ...
1b3814badd4f3831995bab648abf52073239ada3
3,608,041
def _format_headers(tabs, current_tab_number, line_length): """Formats just the tab portion if the config specifies a multi-tab menu Called from format_menu() Args: tabs (list of tab.Tab): list of Tab objects current_tab_number (int): number of currently selected tab (always 0 for single-t...
d99d17790ff9580c2a13dd39876270a1b8b6d9d9
3,608,042
def counting_sort(values, max_value): """Sorts integers using the Counting Sort algorithm. Args: values: iterable, contains the integers to sort should be between 0 and max_value max_value: maximum value the numbers can take Returns: a sorted list of the nu...
fccf1b91bb2c300d22e316057b11dab3bb0ee86f
3,608,043
from typing import Optional def convert_OBvalue( byte_string: bytes, is_little_endian: bool, struct_format: Optional[str] = None ) -> bytes: """Return encoded 'OB' value as :class:`bytes`.""" return byte_string
aebd92207aedbac0dc0c4cfac3e92ac099c5d640
3,608,045
import random import example def add_or_sub_in_base(sample_args): """Module for addition and subtraction in another base.""" context = composition.Context() entropy, sample_args = sample_args.peel() entropy_p, entropy_q = _entropy_for_pair(entropy) p = number.integer(entropy_p, signed=True) q = number.int...
f4fef4647332ede3c791649360c530584d9067bf
3,608,046
def cal_FCNet(ins, num_ins, num_outs, num_layers, hidden_size, dtype='float64', activation='tanh'): """ calculate FCNet api """ net = psci.network.FCNet( num_ins=num_ins, num_outs=num_outs, num_la...
8faa939a9d6efa5db2d2948a38f7039966e8f71c
3,608,047
from typing import Dict from typing import Tuple def merge_model_results(results: Dict[str, Dict[Tuple[str, int], pd.DataFrame]]) -> pd.DataFrame: """ Combine the results of running :func:`util.analyze_model` across a corpus into a single dataframe. :param results: Mapping from model name to dict...
5d8f01201b08a68ea865a331f6be8a6a50dd8786
3,608,048
def find_missing_integer(lst): """Returns the first missing integer in an ordered list. If not found, returns the next integer. """ try: return sorted(set(range(lst[0], lst[-1])) - set(lst))[0] except: return max(lst) + 1
1e8f25f1670933cf57ae042742c175aac7d905fb
3,608,049
def callcongress(): """Verify or collect State intofrmation.""" response = VoiceResponse() from_state = request.values.get('FromState', None) if from_state: gather = Gather( num_digits=1, action='/callcongress/set-state', method='POST', from_stat...
23497f7b16266a1d9cd215c0f1ab5a3f6bf23931
3,608,050
from typing import Dict from typing import Any def is_deprecated(property_dict: Dict[str, Any]) -> bool: """Test. Check if a property is deprecated without looking in description""" return False
2c65c4ead0ba216d26257b3622b074e840f107c8
3,608,051
import socket import errno import select def readNetstring(sock): """ Attempt to read a netstring from a socket. """ # First attempt to read the length. size = '' while True: try: c = sock.recv(1) except socket.error as e: if e.errno == errno.EAGAIN: ...
d4f0994b4c9020f23e970111fcc68be5b6cf55f2
3,608,052
def plug_has_source(plug, nested=False): """Return True if ``plug`` has any source connection, False otherwise. Args: nested (bool): If True, extend the check to all children in ``plug`` hierarchy. Returns: bool: """ stack = deque([plug]) while stack: plug =...
5b8f6a045199cc0f2a86a7da149ab732b2c3af95
3,608,053
import warnings def DeeplabV2(input_shape, upsampling=8, apply_softmax=True, weights='voc2012', input_tensor=None, classes=21): """Instantiate the DeeplabV2 architecture with VGG16 encoder, optionally loading weights pre-trained on VOC2012 segmentation. Note that pre-trained mo...
d78eea82315d2d074b40c1e263eadaf4c7ddd197
3,608,054
import msvcrt def anykeyevent(): """ Detects a key or function key pressed and returns its ascii or scancode. """ if msvcrt.kbhit(): a = ord(msvcrt.getch()) if a == 0 or a == 224: b = ord(msvcrt.getch()) x = a + (b*256) return x else: ...
0c38b6eca60bbb98a77859888e87ad8fc61ccf85
3,608,055
def get_data_month(data: pd.DataFrame) -> pd.Series: """Get month value from data. :param pd.DataFrame data: the data to get months from. :return: (*pd.Series*) -- list of months. """ return data["Date"].dt.month
06d630cc379b32c064273f9b611caebc676dcc50
3,608,056
import logging def parse_csv_data(csv_filename: str) -> list: """Takes in a csv filename and returns a list with each item being a new line of the file. :param csv_filename: The name of a csv filename, '.csv' appendix is optional :type csv_filename: str :return: A list of strings with each ...
ef388507534b6e7e1b82cf5e5f0036e9dd5819dd
3,608,057
from typing import Union def parse_message_data(message: str, user: Union[UserInfo, str] = '', command_prefix: str = '!') -> Message: """ Returns a Message object Parse the standard message data received from twitch IRC """ parts = message.split(' ') prefix = None channel = '' irc_comm...
73e956963ead532a9558f87eff08e61744a6bed3
3,608,058
def getScanDirectory(self): """Displays an open folder dialog window to allow the user to select the folder holding the DICOM files""" try: logger.info('WriteXMLfromDICOM.getScanDirectory called.') #cwd = os.getcwd() scan_directory = QFileDialog.getExistingDirectory( sel...
a14cb40986d5fde70972543161f147425dbc74b2
3,608,059
def format_cron_sec(cron_sec) -> int: """ Format the input second range :param cron_sec: initial second value :return: int(cron_sec) :rtype: int """ if not isinstance(cron_sec, str): raise TypeError( ErrorMsg.DATA_TYPE_ERROR.get_msg( ".The target type is {...
01b74280b7383e001acf27b131a69224fa2767c8
3,608,060
def pearson7(x, amplitude=1.0, center=0.0, sigma=1.0, expon=1.0): """Return a Pearson7 lineshape. Using the wikipedia definition: pearson7(x, center, sigma, expon) = amplitude*(1+arg**2)**(-expon)/(sigma*beta(expon-0.5, 0.5)) where arg = (x-center)/sigma and beta() is the beta function. ...
b5011e341be2988418bcc9157c897594463825c8
3,608,061
def _parse_form(request): """ Parse responses from user purchases. :param request: :return: """ d = request.POST dv = m.Delivery.objects.get(pk=int(d['dv-id'])) od = m.Order(request.user, dv, with_dummies=True) prev_purchases = {pc.product: pc for pc in od.purchases} for pd in dv...
5e46f1f1b8f226d6204a616e88f2800e666c71f6
3,608,062
def calculate_synset_similarity(measure,s1, s2): """ Calculates and returns the similarity between two synsets based on specified measurement """ if measure == 'path': similarity = s1.path_similarity(s2) elif measure == 'lch': similarity = s1.lch_similarity(s2) elif measure == '...
2e90a74af145849cecc79ed91b9640aefe64f197
3,608,063
def load(trained_model): """ Loads a pre-trained model. """ model = load_model(trained_model) return model
dd162a254073cea218a1d66a30c729711b9d6d74
3,608,064
def unafold_parser(lines=None): """Parser for unafold output""" result = ct_parser(lines) return result
5109b818dc64cfd028c6880d2c882ec55d64a416
3,608,065
def search_pubs_by_uuid(uuid): """ Search publications by `uuid`. Args: uuid (str): UUID of publication. Returns: list: List of matching :class:`.DBPublication` or ``[]`` if no match \ was found. """ with transaction.manager: return list(_get_handler()._ze...
ca1a50afe13da3bf87d67b5255415c020927a394
3,608,066
def import_with_fiona(fpath, source): """ Use fiona to import a parcel file. Return a list of dict objects containing WKT-formatted geometries in addition to any metadata. """ shapes = [] try: with fiona.drivers(): data = fiona.open(fpath) for obj in data: ...
663821e4a4cbd0486941b7f1c2b5a650af2bfda2
3,608,067
def aggregate_space_time_average(VarTable, df_dict, suffix, start_date, end_date): """ VarTable: (dataframe) a dataframe with date ranges as the index df_dict: (dict) a dictionary to which computed outputs will be stored suffix: (str) a string representing the name of the original table start_date: ...
cc6c297b3e61e41fe2e169aaf8a3440d8683120f
3,608,069
import array def draw_arrow(gc, pt1, pt2, color, arrowhead_size=10.0, offset1=0, offset2=0, arrow=None, minlen=0, maxlen=inf): """ Renders an arrow from *pt1* to *pt2*. If gc is None, then just returns the arrow object. Parameters ========== gc : graphics context where to ...
bdd7af22baba561e2f6f96d62fbf14639d5b55aa
3,608,070
def sort_return_tuples(response, **options): """ If ``groups`` is specified, return the response as a list of n-element tuples with n being the value found in options['groups'] """ if not response or not options.get("groups"): return response n = options["groups"] return list(zip(*(r...
14b49449d8fda6050bf4223365ba0f93918fe58a
3,608,072
def dare_scalar(A, B, Q, R): """ Solve the discrete-time algebraic Riccati equation for the scalar case of a single state and a single input. In this case the equation is a scalar quadratic equation. """ A, B, Q, R = [float(var) for var in [A, B, Q, R]] A2 = A**2 B2 = B**2 aa = -B2...
20278b42c809a6c4fd894abfb4721b09f15173a4
3,608,073
def _common_prefix(string_list): """ Given a list of pathnames, returns the longest common leading component """ if not string_list: return "" min_str = min(string_list) max_str = max(string_list) for i, c in enumerate(min_str): if c != max_str[i]: return min...
4360e712c6c4d3d650a226c1fe7f3a4941861513
3,608,074
def obs_residual_ssh(name, tides, sdt, edt): """Calculates the observed residual at Point Atkinson, Campbell River, or Victoria. :arg name: Name of station. :type name: string :arg sdt: The beginning of the date range of interest. :type sdt: datetime object :arg edt: The end of the date r...
d80cbefbf904d774144a9248fbffda9447701e73
3,608,075
def readIDMap(options): """ Load the specififed lookup table for hit IDs. If the parseStyle requested is 'gis', convert keys to integers. The values are always convereted to integeres since they are assumed to be taxids """ # map reads to hits if options.parseStyle == GIS: keyType = ...
061700e3797408072408474bb241aa18e9fd4898
3,608,076
def sky_to_camera(alt, az, focal, pointing_alt, pointing_az): """ FUNCTION COPIED FROM lstchain.reco.utils to avoid hiperta depend on lstchain. Coordinate transform from aky position (alt, az) (in angles) to camera coordinates (x, y) in distance Parameters ---------- alt: astropy Quantity a...
8e984ebf8a0a687149adae384e57c0d3ffe180fa
3,608,077
def qualify(func: object) -> str: """Qualify a function.""" return ".".join((func.__module__, func.__qualname__))
bfda7050ff94f407a2a0d4b00b87ecb0370e9110
3,608,078
from typing import Union from typing import List from typing import Tuple from typing import Callable def lives_duration_histogram( datasets: Union[AbstractTimeSeriesDataset, List[AbstractTimeSeriesDataset]], xlabel: str, label: Union[str, List[str]] = "", bins: int = 15, units: str = "m", vli...
8ada53d1fbf9e8998556aa44e48c8abb02d31d35
3,608,079
from datetime import datetime def marshal_background_event_data(request): """Marshal the request body of a raw Pub/Sub HTTP request into the schema that is expected of a background event""" try: request_data = request.get_json() if not _is_raw_pubsub_payload(request_data): # If...
34ae9bb1b9bb61f27dae1a432fb9a36d377faf5d
3,608,080
def render_from_json(file_path: str) -> Image.Image: """Render 2D image from specfile written in json. :param file_path: json specfile path. :type file_path: str :return: rendered and merged image. :rtype: Image.Image """ return PillowProjectSpec.from_json(file_path).render()
440a9177879329f819fff790a2ca514a40c109dc
3,608,081
from cms_mptt import models as mptt_models def install_mptt(cls, name, bases, attrs): """Installs mptt - modifies class attrs, and adds required stuff to them. """ if not Mptt in bases: return attrs if 'MpttMeta' in attrs and not issubclass(attrs['MpttMeta'], MpttMeta): raise Val...
7fd87571c58425c6d02b314002a2a937e4b5733a
3,608,082
def logout(): """ Logout will logout the current session and redirect to the main page. """ try: weblab_api.api.logout() except SessionNotFoundError: # We weren't logged in but it doesn't matter because we want to logout anyway. pass return redirect(url_for(".login", _ex...
e499786b245690a1e28a88ff05809e3edd7c4ac3
3,608,083
def delete_action(system_id: str, action_id: str): """删除Action权限模型""" url_path = f"/api/v1/web/systems/{system_id}/actions/{action_id}" return _call_iam_api(http_delete, url_path, data={})
639ce2b576cf68014d1164c76a5886994e886382
3,608,084
def getPinInfo(pincode = None): """ Gets Info about the given pincode {"district" : "district_name", "state" : "state_name"} """ global intialSetupFlag if not intialSetupFlag: setup() intialSetupFlag = True data, status = utils.custom_request(cowin_config['pinInfo_host'], cowin_config['url_getPinInfo'], urlP...
fe45be2963cc6d19a61e4db89c623ed3f1315488
3,608,085
def replace_node(network, name_to_node, **kwargs): """ name_to_node: map from name of the node to replace, to the new node """ def inner(node): if node.name in name_to_node: return name_to_node[node.name] else: return node return fns.transform_root_node_...
ae7114833f330c7368e8aa000d413b17c4f917e1
3,608,086
def set_buttons_color(text, item=None): """Sets buttons color: background (bg) foreground (fg) disabledforground (dfg) activebackground (abg) activeforeground (afg)""" bg, fg, abg, afg, dfg = None, None, None, None, None if text in ['info', 'rules', 'ok']: bg = color['bg'] ...
f0efa841abf31a9408477a20e05c6a73cabc688f
3,608,087
def forwardPropagation(features, weights): """ Given the input data features and the weights computes the predictions from the neural network. :param features: Numpy matrix of input data used to make prediction. Each row is a training example and each feature is a column. :param w...
bb12caccd3a42d07f0c421b8d49ebf6ee0cf7201
3,608,088
def filter_list_zones(auth_context, cloud, perm='read'): """List zone entries based on the permissions granted to the user.""" zones = list_zones(auth_context.owner, cloud) if not auth_context.is_owner(): try: auth_context.check_perm('cloud', 'read', cloud.id) except PolicyUnauth...
8b641d02de617f661c011f61937e4168b47ef43b
3,608,089
import requests import json def getSearch(request): """ To search datasets based on query - see search(request) in server.py """ # initialise query run summary = {} url = 'https://scicrunch.org/api/1/elastic/SPARC_PortalDatasets_pr/_search?api_key='+api_key size = '200' include...
d1b8d578e8d3647281247aa2d9e397abdee3bebd
3,608,090
def dimension(dim: float, tol: int = 0, step: float = 0.4) -> float: """ Given a dimension, this function will round down to the next multiple of the dimension. An additional parameter `tol` can be specified to add `tol` additional steps to add a tolerance to accommodate for shrinking. """ #...
a63b84bbc73d25da1c86c9919f61bd32071d92f9
3,608,092
def rgb2yuv(r, g, b): """Convert RGB triplet into YUV :return: YUV triplet with values between 0 and 1 `YUV wikipedia <http://en.wikipedia.org/wiki/YUV>`_ .. warning:: expected input must be between 0 and 1 .. note:: the constants referenc used is Rec. 601 """ check_range(r, 0, 1) ch...
0572f43b7e1d5dd0666850b4a41d885ec5892666
3,608,093
import numpy def Projector(wfn, threshold=0.0, n_qubits=None) -> QubitHamiltonian: """ Notes ---------- Initialize a projector given by .. math:: H = \\lvert \\Psi \\rangle \\langle \\Psi \\rvert Parameters ---------- wfn: QubitWaveFunction or int, or string, or array : ...
eb1963c6eca095bac392065250fcb1f629a41e5f
3,608,095
import json import random def tlm(tlm_channel=None,**kwargs): """ This function produces a log message string to be passed into a logger method that captures parameter names and values based on the provided keyword arguments. The keyword arguments and values are encoded into JSON messages. Only values tha...
f4650740ad63d8e1c365da68115761c07d8a16b1
3,608,097
def send_mail(sender: str, recipients: list, title: str, text: str=None, html: str=None, attachments: list=None, **kwargs) -> dict: """ Send email to recipients. Sends one mail to all recipients. The sender needs to be a verified email in SES. """ msg = create_multipart_message(sender, recipients, ...
857e2c20908e3f9a726ba0bb591dad1d76c32ff8
3,608,098
import uuid def create_rand_person(): """Create user with random username, name and email""" user_name = uuid.uuid1() return factories.PersonFactory( # Make User Name different from Name name="User {}".format(user_name), email="{}@example.com".format(user_name) )
4f9744694454a3747bf9a88b324ae4f7051f00c0
3,608,099
def get_task_status(bucket: Bucket, job_id: str, task_id: str) -> TaskStatus: """Get the status of a task. Parameters ---------- bucket : Bucket The Google Cloud Storage bucket that hosts th egiven job and task. job_id : str The ID of the job. task_id : str The ID of the...
f939d85beb8a6927150494e425f5eabad50bb9b5
3,608,100
import json def get_chosen_file_path(file_path='dataset/json/directory.json', key=None): """ This function returns the name of file which is selected from list of default methods. :param file_path: path to file from where the filename should be read against a given key. :param key: key for whi...
54336abd282f63e717c17c19b0d7270b28d29ecf
3,608,101
from ase import Atoms from ase.constraints import FixAtoms, FixScaled from ase.data import chemical_symbols import numpy as np def read_vasp(filename='CONTCAR'): """Import POSCAR/CONTCAR type file. Reads unitcell, atom positions and constraints from the POSCAR/CONTCAR file and tries to read atom types fr...
0eec2146da1ea5e08d10af3c722a5733667d0595
3,608,102
def _subject_update(context, values, subject_id, purge_props=False, from_state=None): """ Used internally by subject_create and subject_update :param context: Request context :param values: A dict of attributes to set :param subject_id: If None, create the subject, otherwise, fi...
ecc1094ef99ed61e72525208c6823f4e4e8e2681
3,608,103
def connect_db(path: str) -> str: """ Set up sqlite3 connection """ return 'sqlite://{}'.format(path)
ace41ad5609d927a987a9ed2d18f7abd64439bb3
3,608,104
import json def read_prediction_tokens(pred_file): """ Reads in the tokens from the tagger's output file. Returns: a String list """ tokens = [] with open(pred_file, encoding="utf-8") as f: for line in f: j = json.loads(line) tokens.extend(j["words"]) retur...
a8da9ff58a83db4df628f1f98b33133ff94805e0
3,608,105
from functools import reduce def get_color_list(timestamps, colors, rgbaf=False): """ Given a list of valid colors (rgb/rgba tuples, shorthand hex string or integer representation) and a list of time-stamps, create a Color object with rgba/rgbaf values of the form: [time_0, r_0, g_0, b_0,..., time_k, r_k,...
95d825eba87cc52fbaf2c2b8f0425088ac976994
3,608,106
def create_random_pdt_agent(depth, n_actions, window=1, temperature=1.0): """ Generate random PDT agent with specified depth and branching factor. Args: depth: int, depth of tree. n_actions: int, number of children at each node. temperature: float, controls entropy of distribution > 1.0 is more random, < 1.0 i...
34af92fed9af84b99b19cf331ca4753e1cf6cc38
3,608,107
import urllib def read_historical_data(start_date, end_date): """Read all of the historical data starting at start_date""" def daterange(start, end): for day in range(int((end-start).days)+1): yield start + dt.timedelta(day) result = [] for day in daterange(start_date, end_date): ...
22ab1099b2ec82237eff321526ed9374efdc0490
3,608,108
import math def LinearizedConv1d(in_channels, out_channels, kernel_size, dropout=0, **kwargs): """Weight-normalized Conv1d layer optimized for decoding""" m = LinearizedConvolution(in_channels, out_channels, kernel_size, **kwargs) std = math.sqrt((4 * (1.0 - dropout)) / (m.kernel_size[0] * in_channels)) ...
f2d2d6a7e731abbd9e4fa50e28abf26d3d691600
3,608,109
def make_test_set(filename): """ Read test data from the file whose path is filename. Return a list with the same form as the training set, except that each dictionary has an additional key "prediction" initialized to "none" that will be used to store the label predicted by the class...
b5603122b6e44e3cb9dd2326de9ce16b54fed59b
3,608,110
def pose_metrics(dE): """ Translation/Rotation/Scaling metrics from Sim3 """ t, q, s = dE.data.split([3, 4, 1], -1) ang = SO3(q).log().norm(dim=-1) # convert radians to degrees r_err = (180 / np.pi) * ang t_err = t.norm(dim=-1) s_err = (s - 1.0).abs() return r_err, t_err, s_err
02d21f7a3711c7f2f8ea852c1e4724c982b92230
3,608,111
def cli(ctx, name="", deleted=False, slug=""): """Get all published histories (by any user), or select a subset by specifying optional arguments for filtering (e.g. a history name). Output: List of history dicts. """ return ctx.gi.histories.get_published_histories(name=name, deleted=deleted, slug=slug...
3a0eca578e105f005d80380043296c9a47ace6a8
3,608,112
from typing import Dict def _deserialize_dict(x: Dict) -> Dict: """Deserialize dict. Args: x (Dict): value to deserialized. Returns: Dict: deserialized dictionary. """ out_dict = {} for k, v in x.items(): if v is None: # if {'key':None} out_dict[k] = None...
e4a609d0935cd08548902e055e3e429559757e84
3,608,113
def mode(numbers: list) -> dict: """ Returns the mode of a list of numbers as a dictionary. Parameters: numbers (list) : A list of numbers """ numbers.sort() ordered_list = [] i = 0 while i < len(numbers): ordered_list.append(numbers.count(numbers[i])) i += 1 ...
f0909d2ffe800c8cf159943bddc02fdced70b17f
3,608,114
def calculate_prior(user_input, DF_obs, obs_flux_arr_dict, obs_err_arr_dict, grids_dict, grid_spec, grid_rel_err): """ Calculate the (linear probability space) prior over the grid, selecting the type of prior based on the request of the user (or the default). In...
f324da5688e1cd811b94b2951055d61f0b2b3791
3,608,116
def infection_rate_symptomatic_80x60(): """ Real Name: b'infection rate symptomatic 80x60' Original Eqn: b'Susceptible 60*Infected symptomatic 60x80*contact infectivity symptomatic 60x80*(self quarantine policy SWITCH self 60\\\\ * self quarantine policy 60+(1-self quarantine policy SWITCH self 60))/non con...
ec2fed1ebba19244c3c97e7723185eacd078cc27
3,608,117
def hamming_dist(a: bytes, b: bytes) -> int: """Find the bitwise Hamming distance between two bytestrings.""" return sum(bin(v).count("1") for v in strxor.strxor(a, b))
b4b682eb6d3aad93f4619407dadff90583ec84b9
3,608,118
def fill_array(blocklist, maxsize, numdata, numblocks, blocksize): """ Fills a new array of integers with the indices corresponding to the specified block structure. Parameters ---------- blocklist : list List of integers describen the block indices that go i...
4440847cb3b1ac07a5c53e76be2387131ddffd3e
3,608,119
from re import L def summarization_splitter(m, arch): """Custom param splitter for summarization models""" model = m.hf_model if (hasattr(m, 'hf_model')) else m if arch in ['bart', 'pegasus']: embeds = nn.Sequential( model.model.shared, model.model.encoder.embed_positions,...
9f855601efdd7ded92245a45b8b8fe4550990c1b
3,608,120
import multiprocessing import random def get_data( path = "../data/", language_list = ["chinese", "english"], encoding_list = ["UTF-8", "UTF-8"], shuffle = True ): """Get data from path Args: path: a string represents corpus path of each language. language_list: a list of string...
9c8f007d4c0ab121c5182817651884a0b9a50455
3,608,121
def birdsong_rec_xml_file(): """annotation file from Birdsong Recognition dataset""" return BIRDSONG_REC_ROOT / 'Bird0/Annotation.xml'
2179439caac004e23312d28dca5f8ee2182384bf
3,608,122
def is_buffer_empty(nvim: Nvim) -> bool: """is_buffer_empty Checks if the buffer is empty. """ return get_buffer_contents(nvim) == [""]
dce9ec9b7d9ac0420a6faeda077412ca149985eb
3,608,125
def _displace_matrix(max_repeat): """This is a helper function for cell_list_nl""" d = [] n_repeat = max_repeat*2 + 1 tot_repeat = tf.reduce_prod(n_repeat) for i in range(3): d.append(tf.cumsum(tf.ones(n_repeat, tf.int32), axis=i) - max_repeat[i] - 1) d = tf.reshape(tf.s...
f4de7b9d13f525b7532a1d4598a99f2101e28cac
3,608,126
def divide_line_by_count(line, n_segments): """ Returns a list whose length is equal to n_segments of LineStrings divided from the line input :param line: LineString :param n_segments: int :return: """ assert len(line) == len(n_segments), AssertionError("Arrays of different sizes") splitters = [[ln.in...
af3de59ee9a6741cc15d44d4f3897169edcd0605
3,608,127
def nuisance_shift_scale(fit): """Determine a shift and scale factor that rescales nuisance parameters to be centered at 0 and varying by O(1).""" return par_shift_scale(fit.par_obj, fit.nuisance_parameters)
23fa32659aa1badf3f7d19e655389ed4c5772d36
3,608,129
import numpy def get_coverage_from_cost(spending, inflection_cost, saturation, unit_cost, popsize, alpha=1.): """ Estimate the coverage associated with a spending in a program. Args: spending: The amount of money allocated to a program (absolute value, not a proportion of all funding) inf...
81ea2c2e2067be8237de3f5f6a134c6c5f1aafee
3,608,130
def expireNonFungible(id): """Expire non fungible product reservation This does not delete the record. This call marks it expired. --- parameters: - in: path name: id required: true description: non fungible product reservation ID type: integer responses: ...
589bf39de78e0330980fd08b0e0a95d0ba72fd12
3,608,131
def str2bool(to_test): """ Convert a string into a boolean. Example: >>> str2bool("False") False >>> str2bool("True") True """ if to_test == "True": return True elif to_test == "False": return False else: return None
73f7e8429dda134cb283e012f0eae853ae5e3eb6
3,608,132
def protected_sqrt(x1): """Closure of square root for negative arguments.""" return cp.sqrt(cp.abs(x1))
5be0d35c0cbd80841acacba98c0132e7eeb9c29c
3,608,133
def falling(n, k): """Compute the falling factorial of n to depth k. >>> falling(6, 3) # 6 * 5 * 4 120 >>> falling(4, 0) 1 >>> falling(4, 3) # 4 * 3 * 2 24 >>> falling(4, 1) # 4 4 >>> falling(4, 10) # 4 * 3 * 2 * 1 # Only n times!! 24 """ if (n > k): tota...
f33935ee505ef2d0c570003ee4661f4c923a1037
3,608,134