content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Dict def alias(alias: str) -> Dict[str, str]: """Select a single alias.""" return {"alias": alias}
9321f00118658dc74fbc9704f1ea0e4a33e1f7aa
3,603,000
def motion_store( mock_labware_store: MagicMock, mock_pipette_store: MagicMock, mock_geometry_store: MagicMock, ) -> MotionStore: """Get a MotionStore with its dependecies mocked out.""" return MotionStore( labware_store=mock_labware_store, pipette_store=mock_pipette_store, g...
00fdd9bf0763061487ff3356e145d90ed7ddbede
3,603,001
def check_validity(geojson_object): """ Checks if geojson is valid, throws exception otherwise. :param geojson_object: geojson object :return: will return the geo """ if geojson_object.is_valid: return geojson_object else: raise api_exceptions.InvalidUsage(status_code=400, er...
62d25b3b5b409850f6d5b4d15ed33604790c7ec9
3,603,002
import os import urllib import requests import json def geocode(location, verbose=False): """From text location description, find lat/lon coordinates""" url = "https://geocoder.ls.hereapi.com/6.2/geocode.json?apiKey={}&searchtext={}&countryfocus={}".format( os.environ['HERE_APP_CODE'], urllib....
bd72a4644e8d06a7e8c076a6fcaad70db3a59935
3,603,003
def ErrorCalcsL2(R_vals = [3, 4, 5], n_vals = [200, 400, 600], alphaTrue = 1, betaTrue = 1, gammaTrue = 1, n_iter = 100, dataAlpha = 2, alphaMax = 5, gammaMax = 4, step = 0.1): """ Function for simulation of inferring alpha, beta, and gamma. Iterates over each (R, n) pair an equal amount of times INPUTS: ...
06ca8663052036458be669bbabd06b4d55185470
3,603,004
import ipdb def ipdb(element): """ Usage: {{ template_var|pdb }} then inspect 'element' from pdb """ ipdb.set_trace() return element
f393c285b75028d0efd818e0cd7bf3340b1d53cd
3,603,005
def _apply_filter(kspace, filt): """Apply filter to kspace Args: kspace (np.ndarray) -- raw preprocesed kspace, excluding reference scans shape : [rcvrs, time, slice, seg, phase, read] filt (np.ndarray) -- filter to be applied after FFT in RO dimension shape : [r...
42c9b843eddbf9b1eb2894a88afce58f6f00d4d9
3,603,006
def get_member(src: str, member_name: str, fc: context.FunctionContext): """ Src has to be a stack symbolic register with a value of type s RETURNS a stack symbolic register with a value of type m same as the type of s.member_name """ dest = fc.scope_man.new_tmp_var_name("member") fc.types[des...
c4afcf8910cd57cbf0d15b401561db2822a5d010
3,603,007
import os import uuid def _create_symlink(folder): """Create a symbolic link that points to the sql folder.""" # Unique filename for the symlink. include_path = os.path.join('/tmp/', str(uuid.uuid4())) os.makedirs(include_path) os.symlink( os.path.join(PROJECT_PATH, folder), os.path.join...
c74839c230644a797026a0f33fff152643474cbd
3,603,008
def _lz_ema_spre_init(adj:np.ndarray, n_emp=10, rho=0.05)->dict: """ Le-Zhong state initialization :param adj: n_dim x n_dim adjacency matrix :param n_emp: number of observations before switching from emp to moving avg cov :param rho: importance of most recent observation :return: """ ...
6d28b80771bc20851c61ba11291541bd306dcefa
3,603,009
def connect_to_host(conf_vars): """Open a transport connection and authentificate. Return a reference to the open connection. """ port = _DEFAULT_SSH_PORT host = conf_vars['storer']['remotehostname'] username = conf_vars['storer']['remoteusername'] sock = open_socket(host, port) t = pa...
4ab264ed2f43dd451c428ecb7e1d7aa0e9b18269
3,603,010
def declare_variable(processor, composer, searcher): # type: (Parser, Compiler, scanner.Scanner) -> Tuple[Parser, Compiler] """Record the existence of local variable in the compiler.""" if composer.scope_depth == 0: return processor, composer token = processor.previous for i in range(compo...
999e9596c5d830f7a4a3b6d3510172b719c67e75
3,603,011
async def send_private_embed(user: MemberOrUser, embed: discord.Embed) -> bool: """ A helper method for sending an embed to a user's DMs. Returns a boolean indicator of DM success. """ try: await user.send(embed=embed) return True except (discord.HTTPException, discord.Forbidden...
57d09a2b23a9910a5af2eff57797fd3b867200df
3,603,012
from registry.get_service import run as _get_service from registry.register_service import run as _register_service from admin.handler import MissingFunctionError def registry_functions(function, args): """This function routes calls to sub-functions, thereby allowing a single registry function to stay hot ...
56c7fc3f244bd3fcfcff248d5ea740ea2585b75b
3,603,013
def conv1x1(in_channels, out_channels, stride=1, groups=1, dilation=1, bias=False): """ Convolution 1x1 layer. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. str...
f96b2b1aa0375895f7fc080fd47858292df5892c
3,603,014
def _setup_entities(hass: HomeAssistant, device_ids: list): """Set up Tuya Switch device.""" device_manager = hass.data[DOMAIN][TUYA_DEVICE_MANAGER] entities = [] for device_id in device_ids: device = device_manager.device_map[device_id] if device is None: continue i...
8654c53f52134003484c293dfa5b66c696273385
3,603,015
from IPython.display import HTML from IPython.display import display as iDisplay def animate_centroids( lcf, fig=None, frames=None, num_obs_per_frame=240, interval=250, use_relative_time=False, time_range=None, accumulative=True, c=None, display=True, ): """ Animate cen...
237db91a1fdf4f6f83ef7a1bf2e1bba79ff58a39
3,603,016
def x_axis_pseudolandmarks(obj, mask, img, device, debug=None): """Divide up object contour into 20 equidistance segments and generate landmarks for each Inputs: obj = a contour of the plant object (this should be output from the object_composition.py fxn) mask = this is a binary image. The ob...
bb983a40d0e4c439acabfe34faa73a311b4c0a44
3,603,017
async def async_discovery(session): """Find bridges allowing gateway discovery.""" bridges = [] json_dict = await async_request(session.get, URL_DISCOVER) if json_dict: for bridge in json_dict: bridges.append({'bridgeid': bridge['id'], 'host': bridge['inte...
8647b2af8fdac987052fff6f1706cb1914c0f235
3,603,018
def layerZofHit(hit): """ Get layerZ from hit """ return ecal_layerZs[layer(hit)]
6dd3c4df468fb2652ab61feb929bbfa1869dc634
3,603,019
def camera_from_ngl_state(state_d, zoom_factor=300.0): """define a vtk camera from a neuroglancer state dictionary Parameters ---------- state_d: dict an neuroglancer state dictionary zoom_factor: float how much to multiply zoom by to get camera backoff distance default = 30...
e904f4defa3341e7002a80579e9374b6ad6d6b34
3,603,020
import subprocess def pdf(filename): """Generates a .pdf file. Use the pdf latex instance (must be installed) """ p = subprocess.Popen(['/usr/bin/pdflatex', filename +".tex" ], stdout=subprocess.PIPE, stderr=subprocess.PIPE) #bash command in python out, err = p.communicate() ...
7cd8809134bb75ac37caca79f560ca4c600e2348
3,603,021
def fix_hardmix(): """Fixture for a hard mixture""" return { "background": {"markov:rmin_500_rmax_1000_thresh_0.8_priceVarEst_1e9": 1}, "hft": {"noop": 1}, }
dee9b13b6b7f14ae334a6e1eda6c1fd2a362ba32
3,603,022
def max_digits(x): """ Return the maximum integer that has at most ``x`` digits: >>> max_digits(4) 9999 >>> max_digits(0) 0 """ return (10 ** x) - 1
3f0ffdfbbb3fdaec8e77889b3bfa14c9b9829b2e
3,603,023
def crear_sprite(dir_sabana, dimensiones, columnas, filas=1, opcion=None): """ Funcion para recorte de sprites sabana: imagen con los graficos dimensiones: [ancho,alto] del recorte columnas: cantidad de columnas que tiene la sabana filas: filas de la sabana (default 1) opcion: optiene una ma...
0eb87ee318a709f543bf7213ee102506a1c9d8c3
3,603,024
import os def read_data(): """ Reads the IEMOCAP database into np.array. Sample output: (array([ 3.0517578e-05, 3.0517578e-05, 3.0517578e-05, ..., 0.0000000e+00, -3.0517578e-05, 0.0000000e+00], dtype=float32), 0) :return: Tuple of (samples, labels) where the samples are a np.array...
bec9c5d9d5306b10278cba2ad651afbd3e641486
3,603,025
def add_intercept_feature_col(X: np.ndarray) -> np.ndarray: """Add an intercept column to a (n_examples, n_features) data matrix. Args: X: The input array, of shape (n_examples, n_features) Returns: X, but with a column of ones prepended, so that it is of shape (n_examples, n_featu...
d8127b07974a4f0a51efc02e8d81887e05a5825c
3,603,026
def upload_request(self, upload_data, custom_opts=None): """Uploads the given generic data and returns the response object.""" opts = default_upload_options() opts.update(self.custom_opts) if custom_opts is not None: opts.update(custom_opts) # Upload as a directory if the dirname is set, e...
7bb3bbcbf8e123b0df8c20b5c6cefee2fa5d3b8e
3,603,027
def index(): """ Homepage, point visitors to project page """ theme = themes[DEFAULT_THEME] return render_template('index.html', theme=theme)
9ac091b90e3f2bf4f5b2b04ce737afbed78a10c9
3,603,028
def to_numpy(t): """ If t is a Tensor, convert it to a NumPy array; otherwise do nothing """ try: return t.numpy() except: return t
3ac3ef0efd9851959f602d42e7f38bdd7e5da21a
3,603,029
import os def project_root(parser, projdir=os.getcwd()): """try to find project's root and add it to sys.path""" curdir = osp.abspath(projdir) previousdir = curdir testercls = PyTester conf_file_path = osp.join(curdir, CONF_FILE) if osp.isfile(conf_file_path): testercls = load_pytest_c...
0070de3689c9dfc7c6b1622779d707f0c2e4b0b8
3,603,030
def _hamiltonian_expected(cells, periodic, sites_per_cell, freedom): """Expected Hamiltonian for the simple 1D lattice model""" # Within the cell, adjacent sites hop to each other, and it's always # non-periodic. cell = qutip.qdiags([-np.ones(sites_per_cell - 1)]*2, [1, -1]) ...
19c0ad8d71eb6b8c13556c22b27453725c0cb153
3,603,031
import torch import test def train(args, model, train_loader, test_loader, loss_func, optimizer, device): """Function to train a torch model Args: args: command line parsed arguments containing training parameters like epochs, log interval model (torch model): a pytorch model (can...
91bd7536284bcb2df65fffedf96feed8fdfd45e6
3,603,032
def printStateStringLatex(n, l, j, s=None): """ Returns latex code for spectroscopic label for numeric :math:`n`, :math:`l`, :math:`j` label of the state. Args: n (int): principal quantum number l (int): orbital angular momentum j (float): total angular m...
8a95c6441d3396602223efabb5da2385a1f3a4a0
3,603,033
def get_name_from_choice(value, choice): """選択肢から値によって、表示名称を取得する :param value: 値 :param choice: 選択肢 :return: """ for k, v in choice: if k == value: return v return None
00055bc53aeba244a751f9dffe5c1fa2a7c71383
3,603,034
def getOperationCallback(c): """ Get the operation callback. Returns ------- `function` """ global OPERATION_CALLBACK return OPERATION_CALLBACK
c9ec067146a2295a053350425ed50f8ba67d549c
3,603,035
def winding_number(X, Y, Z, contour, x_spacing, y_spacing): """ This method computes the contour integreation around a positively oriented square of corners A, B, C and D. A (x_1, y_2) +---<---+ D (x_2, y_2) | | v ^ | | ...
709163b58aabea7157b97a696927bffced6e1437
3,603,036
from datetime import datetime import hashlib from os.path import getctime import uuid def set_metadata(g): """ Set the rsml 'metadata' element from the graph-properties of mtg `g` The rsml metadata is a dictionary equivalent to the metadata xml element of rsml. Its main purpose is to be used by `rsm...
9a8cf62f465f5a2590a05ec3b4e4c3cf4f693edb
3,603,037
def view_forks(repo, username=None, namespace=None): """Forks""" return flask.render_template( "repo_forks.html", select="forks", username=username, repo=flask.g.repo )
02d4a8dbf17d888f3672c03b45895b21228bc758
3,603,038
def reduce_on_network(value, network): """ Reduces a list of addresses to only the addresses that match a given network. :param: value: The list of addresses to filter on. :param: network: The network to validate against. :return: The reduced list of addresses. """ # normalize network vari...
e42c92d32168c977777de358497846358a5472f4
3,603,039
def clean_text(text, replace_entities=True): """Cleans the text in the same way as in data preprocessing part before training""" if replace_entities: spacy_text = nlp(text) text_ents = [(str(ent), str(ent.label_)) for ent in spacy_text.ents] text = text.lower() # Replace entitie...
a5c30510a3349e1a0a93100e385606745e112f17
3,603,040
import sympy from typing import OrderedDict def get_thermochemical_data(dbf, comps, phases, datasets, model=None, weight_dict=None, symbols_to_fit=None): """ Parameters ---------- dbf : pycalphad.Database Database to consider comps : list List of active component names phases ...
a9e213d3256c2f4edf280cc603823d769c8fbc32
3,603,041
def prep_dataset(): """Fetching the dataset """ def load_triu(S, P, dim): return [extract_triu(s, dim) for s in S], [extract_triu(p, dim) for p in P] folder = join("butadien", "data", "400") dataset, molecules = make_butadien_dataset( np.load(join(folder, "molecules...
9ef15a2bdeffa2fefc333919ec8279eee5495688
3,603,042
def var_series(get_var_series, n) -> list: """ :param get_var_series: func return random value :param n: number of elements :return: variation series """ l = [] for i in range(n): l.append(get_var_series()) l.sort() return l
95400d8f3368d7777ed9bf6d1fb42bc06aa3f17d
3,603,043
import torch def one_hot_argmax(inputs, temperature, axis=-1): """Returns one-hot of argmax with backward pass set to softmax-temperature.""" vocab_size = inputs.shape[-1] z = one_hot(torch.argmax(inputs, dim=axis), vocab_size) soft = F.softmax(inputs / temperature, dim=axis) outputs = soft + (z ...
74a6289a10e5d0e75ceb0e6de74bd13250150a58
3,603,044
import requests import html def generate_token_holdings(n_clicks, address): """ Function takes in n_clicks and Ethereum address and outputs images of the address's ERC20 token holdings """ if n_clicks == 0 or address is None: raise PreventUpdate else: # App section title ...
c2f8f38f7a566291b55796a57dea1897abe82582
3,603,045
def _build_classification_specification(label, num_classes, collapse): """Returns a LinearSpecification for adversarial classification.""" # Pre-construct the specifications of the different classes. eye = np.eye(num_classes - 1) specifications = [] for i in range(num_classes): specifications.append(np.co...
a9657c432792d03679a2ca895aab5fe125d9c0fd
3,603,046
def get_prune_list(database=None): """Return triggers that will be pruned upon next full install Args: database (str, default=None): Only return results from this database. Defaults to returning results from all databases """ installed = { (model._meta.db_table, trigger.get_...
6a0109aab43b0a3569bbc13dd726d61b29cf06a6
3,603,047
def delete_message(user, message_id, basecamp=0): """Return raw response data from deleting a message (ID: message_id) using user (optionally at basecamp)""" if basecamp: location = user.basecamp_location else: location = user.location params = [("accuracy", user.location.accuracy), ...
0e12c9c5b0b73c940966187639e3dac79cb09499
3,603,048
import argparse def get_parser(): """Get parser.""" parser = argparse.ArgumentParser(description="Parameters for H-UCRL.") parser.add_argument( "--agent", type=str, default="RHUCRL", choices=["RARL", "RAP", "MaxiMin", "BestResponse", "RHUCRL"], ) parser.add_argument...
9d815542ee18766da7ca6dc8cb298dc964b58a9a
3,603,049
from typing import List def compute_distances( query_feature: np.array, feature_dict: dict, method: str = "l2" ) -> List: """Computes the distance between query_image and all the images present in feature_dict (query_image included) Args: query_feature: Features for the query image ...
c6bcfb6593248b90a499cefcb1a38a77b902a630
3,603,050
def get_img_channel_num(img, img_channels): """获取图像的通道数""" img_shape = img.shape if img_shape[-1] not in img_channels: img_channels.append(img_shape[-1]) return img_channels
0627cffbb3e80fddccc47a4cc8b697a59cdda077
3,603,051
def _CheckArguments(cmd, args_def, args): """Verifies the arguments using the argument definition. Algorithm: 1. Abort with error if values specified by user but none expected. 1. For each argument in definition 1. Keep running count of minimum number of values (min_count) 1. Keep running co...
ed9fe8ca57d3eaf9f65b2aa9503beac1841a6b49
3,603,052
def count_spikes(in_fnames): """ count spikes """ num_pos = 0 num_neg = 0 nsamp = None for h5file in in_fnames: fid = tables.open_file(h5file, 'r') num_pos += fid.root.pos.times.shape[0] num_neg += fid.root.neg.times.shape[0] # might be a problem if no spike...
c3b50b17042340334128f0d04ed46c5dbc2c76dd
3,603,053
import pandas as pd def keep_common_genes(rna_df, sig_df): """ Given two dataframes, eliminate all genes that are not present in both dataframes. Both dataframes must be indexed with the same gene identifier Inputs: - rna_df: pandas df. Rows are genes (indexed by 'Hugo_Symbol') and columns are...
f934a351a8c5d8f158b33bb9233dbd62f9dd4c8a
3,603,054
def einstein_product(a, b): """AND variant.""" # TODO: Expand.. def f(z): x, y = a(z), b(z) return (x * y) / (2 - (x + y - x * y)) return f
700d186b97ab167a2ccf9f395a1b2e681b64b87b
3,603,055
from typing import Tuple from typing import Any def get_record_command(client: Client, args: dict) -> Tuple[str, dict, Any]: """ Query attributes and relationship information for a specific record. Args: client: Client object with request. args: Usually demisto.args() Returns: ...
9371bfa151b2f4254538e75c09bce440a9d9ea6a
3,603,056
def return_pooling_objective_function(vr_control_func_dict): """This function generates the control objective functions for vehicle-request assignment in pooling operation. The control objective functions contain an assignment reward of LARGE_INT and are to be --------------- -> minimized <- -------...
d92b2970df348800e6b4a84d0b669dc182d727cb
3,603,057
def circulate(number, lower, upper): """ 数を範囲内で循環させる。 Params: number = 数。 lower = 数の下限。 upper = 数の上限。 Returns: 循環させた数。 """ if lower <= number <= upper: return number elif number < lower: return circulate(upper + lower + number + 1, lower, upper) e...
382b82768cc170b27b810c54d0ce753277d1a6f4
3,603,058
import json def connect_to_websocket(ws_endpoint, start_request): """ returns a successful websocket connection which we can use to start reading in data args: - ws_endpoint: your infura project websocket, will look something like - start_request: a dict of the first thing to send to the infura we...
827cb56384cfdc494f8968f08d60247058bb4021
3,603,059
from typing import Callable from typing import Union def vpnn(input_dim: int = None, n_layers: int = 1, n_rotations: int = 1, theta_initializer: str = 'uniform', t_initializer: str = 'uniform', bias_initializer: str = 'uniform', output_dim: int = None, us...
e0f69e35aa627961e2cb3e21ba46ce7e5aef0017
3,603,060
import binascii def to_hexstring(string): """ Convert Bytes or ByteArray to hexadecimal string :param string: Variable to convert to hex string :type string: bytes, bytearray, str :return: hexstring """ string = normalize_var(string) if isinstance(string, (str, bytes)): try:...
aeb7a3abc6f88bbe54900d614f2cbe1bf7f471dc
3,603,061
def get_subs(url: str) -> int: """Получает количество подписчиков""" user_id = calculate_raw_account_id(url) account_type = calculate_account_type(url) if account_type == 'Сообщество': subs = get_group_subs(group_id=user_id) else: subs = get_account_subs(user_id) return subs
f7ace521885af7a35f7d094f53e3e91942bd639b
3,603,062
from unittest.mock import patch def patch_bond_token( enabled: bool = True, return_value: dict | None = None, side_effect=None ): """Patch Bond API token endpoint.""" if not enabled: return nullcontext() if return_value is None: return_value = {"locked": 1} return patch( ...
6ffd6e9168a8a41d760788a688c8f67a2c69377a
3,603,063
def clarifai_analysis(image_url, tag_limit=10): """ Given an image url return the tags as predicted by the Clarifai API. """ res = clarifai_model.predict_by_url(image_url) return [e['name'] for e in res['outputs'][0]['data']['concepts']][:tag_limit]
1c390deb04408c025ac713a08703af813aebe816
3,603,064
def thread_only(): """ A decorator that checks if the command is being ran within a Modmail thread. """ async def predicate(ctx): """ Parameters ---------- ctx : Context The current discord.py `Context`. Returns ------- Bool ...
adec39350f096926e9ab8c5622aa6e5c9dd79570
3,603,065
from typing import Union import types def wal_magneto_conductance( fields: Union[float, np.ndarray], l_phi: float, traces: np.ndarray, lengths: np.ndarray, surfaces: np.ndarray, cosjs: np.ndarray, ) -> Union[float, np.ndarray]: """Compute the magneto conductance using precomputed trajector...
21debc934619cbe7bc71f3ae10a606081333a282
3,603,066
def auto_str(cls): """Auto generate string representation of the object. Args: cls: Class for which to generate the __str__ method. """ def __str__(self): return "%s(%s)" % ( type(self).__name__, ", ".join("%s=%s" % item for item in vars(self).items()), ...
71a95cfeecb00146898656a0150d97fc346ddad3
3,603,067
import argparse def get_train_input_args(): """ Command Line Arguments: 1. Data Folder as data_dir 2. Save Folder for checkpoints as --save_dir with default value 'checkpoints' 3. CNN Model Architecture as --arch with default value 'vgg16' 4. Learning rate as --learning_rate with defau...
1631d63783905f421ed2dc9c702673ff3866153a
3,603,068
def instantiate(process_id: int, customer_category: str) -> dict: """ Returns either a or b :param process_id: specify process :param customer_category: specify customer category :return: 'a' or 'b' """ instantiation_dict = controller.instantiate(process_id, customer_category) return instan...
07308761898efd61ef723b945a73a15ed8c2daf9
3,603,069
import json def _jsonToDict(json_file): """Reads in a JSON file and converts it into a dictionary. Args: json_file (str): path to the input file. Returns: (dict) a dictionary containing the data from the input JSON file. """ with open(json_file, 'r') as fid: dout = json.loa...
6e4b5996d6aaf2982012c6c2f135d7876ee5b3ca
3,603,070
from bigflow import schema_pcollection def _transform_schema_pcollection(pcollection): """ 内部函数 """ return schema_pcollection.SchemaPCollection(pcollection)
2bec989359e42625d76c6b7a5380c3f36095ba60
3,603,071
from typing import Type from typing import Callable def parametrized_test_case(cls: Type[TestCase]) -> Type[TestCase]: """Decorator for TestCase to enable use of parametrize decorator on its test methods""" def test_wrapper(test: Callable, **kwargs): """Create test executor""" def test_executo...
a05e0685e61ef2019ea3a7d6ce9d425f78c2b16f
3,603,072
def get_image_patch(cam, rgb_img, target_category=None, threshold=0.5): """ Get the important part of the image """ input_tensor = preprocess_image(rgb_img) # You can also pass aug_smooth=True and eigen_smooth=True, to apply smoothing. grayscale_cam = cam(input_tensor=input_tensor) grayscal...
eef7311e4c4e3bb8fd00e329b0c4802dc0dde5a3
3,603,073
def get_cfg_set(flag_dict, default_dict): """Get a yacs CfgNode object with default values for my_project.""" # Return a clone so that the defaults will not be altered # This is for the "local variable" use pattern cfg_set = create_cfg_set(flag_dict, default_dict) return cfg_set
3e73ecd0cfba25a82eb3f6f04650ae3246f0afb4
3,603,074
def get_pull_requests_by_label(repo: "Repository", label: str) -> list["PullRequest"]: """获取所有带有指定标签的拉取请求""" pulls = list(repo.get_pulls(state="open")) return [pull for pull in pulls if label in [label.name for label in pull.labels]]
e93c9bedcc568b97e04166b5db1fe933315fc255
3,603,075
def check_checksum(tmpfile, version): """ Creates a SHA512 checksum for the downloaded update package. :param tmpfile: dowloadad update package :param version: version numberof update :return: the two checksums """ # download SHA file: response2 = myurlopen.open('{}/DSR-{}-sha512.sha'.fo...
2026a9e083915c3347dd788cded086b351778d78
3,603,076
import collections def get_ha_regions(reference = None, max_distance = None): """ Get hand-authored sectors, optionally in distance order around a reference point Args: reference: Optional, position or System/Sector-like object. If provided, returned sectors will be ordered by distance from this point ...
36b6954be46414587383823e1cb7a27a85bad985
3,603,077
def _convert_output_type_range(img, dst_type): """Convert the type and range of the image according to dst_type.""" if dst_type not in (np.uint8, np.float32): print('Error,The dst_type should be np.float32 or np.uint8') if dst_type == np.uint8: img = img.round() else: img /= 255....
535cf7a898bf54b28f96beac97ec30c3c5b233ad
3,603,078
def get_mesh_shape(mesh, shape_index = 0): """ Get the first mesh shape, or one based in the index. Args: mesh (str): The name of a mesh. shape_index (int): Usually zero, but can be given 1 or 2, etc up to the number of shapes - 1. The shape at the index will be returned. ...
80d4819dd470198dd36dc4ea609a9354a7e0a944
3,603,079
def _matches_app_id(app_id, pkg_info): """ :param app_id: the application id :type app_id: str :param pkg_info: the package description :type pkg_info: dict :returns: True if the app id is not defined or the package matches that app id; False otherwise :rtype: bool """ ...
4d6cd0d652a2751b7a378fd17d5ef7403cfdc075
3,603,080
def db(x, *, power=False): """Convert *x* to decibel. Parameters ---------- x : array_like Input data. Values of 0 lead to negative infinity. power : bool, optional If ``power=False`` (the default), *x* is squared before conversion. """ with np.errstate(divide='ign...
e3de5c46c76738bd197ccd467afa917e0018b622
3,603,081
from robflask.service import service def download_file(group_id, file_id): """Download a given file that was perviously uploaded for a submission. NOTE: At this point, the user is not authenticated for file downloads to allow download in the GUI via browser redirect. """ with service() as api: ...
a759c44d6e459c96ee40d72bd0b8c168020e21f4
3,603,082
def rivers_by_station_number(stations, N): """Returns a list of the first N (river name, number of stations) tuples with the greatest number of stations. Params: stations - list of stations to be filtered \n N - number of tuples to show \n Pulls river name & list of stations by river fr...
4916dc5f9724cef4502499937892d5b34cb5a36e
3,603,083
def gcd(a, b): """ Return the greatest common divisor of a and b. :Input: * a -- an integer * b -- an integer :Output: * an integer -- the gcd of a and b Examples: >>> gcd(97,100) 1 >>> gcd(97 * 10**15, 19**20 * 97**2) 97L ...
90ee10a78e3902f3e82cc2996b17b347bb792974
3,603,084
def recv_all_chunks(sock, payloadsize, timeout=None): """read a bytearray payload from tcp socket""" current_timeout = sock.gettimeout() if current_timeout != timeout: sock.settimeout(timeout) recvbuf = bytearray() mark = 0 while mark < payloadsize: recv_size = min(CHUNKSIZE, pay...
57b54515777c36a81f81e0d9ec0257b1f64783c3
3,603,085
def create_mechs(param_dict): """Create mechanisms from parameter dictionary. It should be a dict of dict like: {name: {'gbar': gbar_quantity}} except for passive conductance `pas`, which must have {'g': gpas_quantity, 'e': epas_quantity} Returns: a dict of {name: ephys.Mechanism} """ ret = {} ...
19faf0ea33ed24cc6090c6ebf5ec3854ef307957
3,603,086
import re from datetime import datetime import click def switch_vendor( ip, credentials, return_error=False, ): """Get a switch vendor. First try lookup from cache, then from the switch. Args: ip: Switch ip credentials: Switch credentials return_error: If True, raises requ...
b42dcbd89356c885819a58ed9dac6ba457117a19
3,603,087
def quad_pvinfo(tao, ele): """ Returns dict of PV information for use in a DataMap """ head = tao.ele_head(ele) attrs = tao.ele_gen_attribs(ele) device = head['alias'] d = {} d['bmad_name'] = ele d['pvname_rbv'] = device+':BACT' d['pvname'] = device+':BDES' d['bmad_f...
b35e04d78d419673afbc0711f9d454e01bc1dd5d
3,603,088
import collections def flatten(d, parent_key='', sep='.'): """ based on https://stackoverflow.com/a/6027615/1324730 :param d: :param parent_key: :param sep: :return: """ items = [] for k, v in d.items(): new_key = parent_key + sep + k if parent_key else k if isinsta...
a76717f301d053632e0759b7689829fc786cd598
3,603,089
def decimate(stream: Stream, *args, **kwargs) -> FilterableStream: """https://ffmpeg.org/ffmpeg-filters.html#decimate""" return filter(stream, decimate.__name__, *args, **kwargs)
5c72e22e3ad9f48f3eebfde53a8601e2e31213d7
3,603,090
import csv def parse_sample_template(input_file): """ Parse the TSV file and return data objects to run def. @param input_file: @return: """ line_num = 0 options_dictionary = defaultdict(str) sample_dictionary = defaultdict(list) index_file = list(csv.reader(open(input_file), delim...
b662174886c178db7f9e886cf932b1398e9c77d3
3,603,091
def load_pkl(file_path): """ Load pyleecan object from pkl file Parameters ---------- file_path: str file path Returns ------- obj: Pyleecan object """ with open(file_path, "rb") as file_: # file is a group obj = load(file_) return obj
e5ff7de738d369623342b43d4fb35e84e16492f4
3,603,092
import collections import os def read_gathered_las(path): """Return dict of block->[las_paths]. For now, these are ws separated on each line of input. """ result = collections.defaultdict(list) dn = os.path.normpath(os.path.dirname(path)) with open(path) as ifs: for line in ifs: ...
9a03b5bdcd1eba096488ea2ba5faa9f0e2e69e44
3,603,093
def get_connected_vertices(mesh, vertex_selection_set): """ Get list of connected vertices in groups :param mesh: str, name of the mesh to get vertices from :param vertex_selection_set: list<str>, list with vertices indices to get connected vertices of :return: """ # TODO: We need to rewrit...
328433e3f114c05edbe65430b0d1efce57e3963d
3,603,094
from typing import Callable from typing import List def min_weight_simple_path_greedy( graph: nx.Graph, n: int, weight_fun: Callable[[nx.Graph, List], float] = path_weight): """A greedy algorithm that tries to find a simple path consisting of n nodes in the given graph, with minimal to...
2d0b0d02abdd045932a9dae1f565f1412f18ae6d
3,603,095
from typing import List from typing import Callable def check_sso_permissions(permissions: List[str]) -> Callable: """Проверяет права на уровне пермишенов юзера.""" def decorator(func: Callable) -> Callable: @wraps(func) async def wrapper(request: Request, *args, **kwargs): # noqa: ANN201 ...
8e5cdbfc1014b5ed4ef819ae129b2c460124581b
3,603,096
def makeup(formula, multiplier=1, sum=False, count_zero=False, messages=True): """ Python wrapper for the makeup() function in CHNOSZ. Parse a formula into a dictionary of elements and their counts. Parameters ---------- formula : str or list of str Chemical formula or a list o...
99e0289168a1eb6f9aa329d252f565d9b7a6c5fd
3,603,097
from typing import Optional from typing import Tuple from typing import cast import torch def rollout_mujoco_env( env: gym.wrappers.TimeLimit, initial_obs: np.ndarray, lookahead: int, agent: Optional[mbrl.planning.Agent] = None, plan: Optional[np.ndarray] = None, ) -> Tuple[np.ndarray, np.ndarray,...
efdf50263147f85497cb36c7c196e3485d528b53
3,603,098
def chunkit(it, size): """ Chunk an iterator <it> into pieces of <size>. >>> list(chunker('ABCDEFG', 3)) [['A', 'B', 'C'], ['D', 'E', 'F'], ['G']] """ iterable = iter(it) return iter(lambda: list(islice(iterable, size)), [])
45c7842f1ef1512238f7137cff53df09303b96b6
3,603,099