content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def _is_new_prototype(caller): """Check if prototype is marked as new or was loaded from a saved one.""" return hasattr(caller.ndb._menutree, "olc_new")
1282db1ce6ae2e5f0bb570b036d7166a53287229
69,900
def rotate_from(points, rotation_transform): """Rotate an ndarray of given points(x,y) from a given rotation""" if type(points) != np.ndarray: raise TypeError("rotate_from: takes an numpy.ndarray") new_points = [] for point in points: point_mat = np.mat([[point[0]],[point[1]],[0]], dtype...
42f04a44a527a74b8a447d284a7484823c57b17f
69,901
from typing import Union def pix_rad_to_physical(im_prod: Union[Image, RateMap, ExpMap], pix_rad: Quantity, out_unit: Union[UnitBase, str], coord: Quantity, z: Union[float, int] = None, cosmo=None) -> Quantity: """ Pure convenience function to convert a list of pixel radii to whatever ...
fdac0d35890acee58ab786d0c5fad953cc8c2721
69,902
import sys import re import random def non_aminoacid_converter(seq, amino_con): """ Converts Non amino acid characters from protein sequence """ if amino_con == '': sys.stderr.write("usage: Provide a choice for replacing non amino acid characters\n") sys.exit(-1) flag = 0 if len(ami...
3575aaa6ecf6c8457197ab5c14b82c6eb19d6a0c
69,903
def _ms_dalt_ind(item): """ Sorts elements in a sign-alternating descending order and returns a list of their previous indices compared to their current ones. \> Parameters: `item` : *array-like* """ if type(item) == np.ndarray: raise TypeError('numpy.ndarray not yet supported for...
31d6836227300415c2b59679150966bcb49e4ded
69,904
def wmt_affine_base_trueadam_longer(): """Set of hyperparameters.""" hparams = wmt_affine_base_trueadam() hparams.learning_rate_constant = 4.0 hparams.learning_rate_warmup_steps = 20000 return hparams
a57f749c73288ffd6c397d555844574b63f508a5
69,905
import os def check_pack_content_directory_exists(pack, content_type): """ Check if a provided pack exists in one of the pack paths. :param pack: Pack name. :type pack: ``str`` :param content_type: Content type (actions, sensors, rules). :type content_type: ``str`` :rtype: ``bool`` ...
d705280164036a46ed43641057562c53f80f9228
69,906
def leave(playerName): """ Permet de supprimer un joueur dans la partie en cours ... """ plId = func.recupIdFromName(playerName) # Je le passe a 'false' dans la table Participate db.execute("""UPDATE Participate par SET present = 'false' WHERE par.pl_id = '"""+ str(plId) +"""';""") return "",200
920bc31cb3bfcd9fc6828b65ed930fa2b94ccd72
69,907
def generator(noise_dim=NOISE_DIM, seed=None): """Generate images from a random noise vector. Inputs: - z: TensorFlow Tensor of random noise with shape [batch_size, noise_dim] Returns: TensorFlow Tensor of generated images, with shape [batch_size, 784]. """ if seed is not None: ...
1fc14099e8656fa820446c6698a3de44f60ec5d8
69,908
def get_route_map_entry_by_search(search=dict()): """Return a list of RouteMapEntry's by dict.""" try: objects = RouteMapEntry.objects.filter() object_map = build_query_to_datatable_v3(objects, search) except FieldError as e: raise ValidationAPIException(str(e)) except Exception...
a144abaee91ce3a564a9e6fb25e1d3c62867d76b
69,909
def generate_slug(obj, slug_length): """ A function to generate a slug with a given length and make sure it's unique. """ slug = get_random_string(slug_length) slug_is_not_unique = True while slug_is_not_unique: slug_is_not_unique = False other_objs_with_slug = type(obj).objects.filter(id=slug) if...
1913d7e888a2ffa3be02faa88db03f0544ae6991
69,910
from typing import List import math def diversity(individuals:List[Individual]) -> float: """Computes the diversity of a population. Higher diversity value the better. Citations: J. Hu, J. Zeng, and Y. Tan, ‘‘A diversity-guided particle swarm optimizer for dynamic environments,’’ in Bio-Inspired Com...
339d00261961a1458faea1e412170b8c2ee21020
69,911
import os import random import torch def test_it(fsdp_config, input_cls): """Test FSDP with input being a list or a dict, only single GPU.""" if torch_version() < (1, 6, 0): pytest.skip("older pytorch doesn't support reduce_scatter") # Random port in case the next test run quickly, same port woul...
f634b23d73f1ff8ee51263e0ba38ac278b8f1466
69,912
import uuid def submit_job(function_name, kwargs, queue_name='default'): """ Parameters ---------- function_name: string Name of the function that will be expected by the waiting process. kwargs: dict Keyword arguments to pass to the function. queue_name: string ['defau...
e1455a62ec699c1b293149bd4727a682cf7a1b1a
69,913
def read_md_file(filepath): """Reads an md file and returns the string.""" with open(filepath, "r", encoding="utf-8") as md_file: md_file_str = md_file.read() return md_file_str
35ad658f850be903b6b183e8970c86c894530c62
69,914
def regression_loss(pred_boxes, gt_boxes, weights): """ Regression loss (Smooth L1 loss: also known as huber loss) Args: pred_boxes: [# anchors, 4] gt_boxes: [# anchors, 4] weights: Tensor of weights multiplied by loss with shape [# anchors] """ loss = tf.losses.huber_loss(pr...
e380c9b91269ac6583c1a89b85d2deea3c2db5aa
69,915
def countObjectTypes(objects): """Given a list of objects, returns a count of how many of each type there are.""" results = {"rootgroup": 0, "group": 0, "job": 0} for obj in objects: if isJob(obj): results["job"] += 1 elif isGroup(obj): results["group"] += 1 e...
ab44060e6581d8cbfc8e83d9bb16e308789c6e13
69,916
def input_fn(split, mode, data_dir, batch_size, cutout_size, num_epochs=1): """Input_fn using the tf.data input pipeline for CIFAR-10 dataset. Args: mode: train, valid or test. data_dir: The directory containing the input data. batch_size: The number of samples per batch. num_epochs: The number of ...
6937c6613868f8b852c0c29b17837dac493b9c31
69,917
import array from pathlib import Path def get(java, name): """Returns the value of a Java node property as a Python data type.""" datatype = java.getValueType(name) if datatype == 'Boolean': return java.getBoolean(name) elif datatype == 'BooleanArray': return array(java.getBooleanArray...
aa70914ffe3180de22d7edea0f3c06c9482cdd4c
69,918
def grid(gdf): """ sampling the GNSS data by grids Parameters ---------- gdf: geodataframe geodataframe of all gnss data(population) Returns ------- list: list of each grid which contains all related gnss data """ #create new column to...
f613359a0061fd2975607044ffcaa8b25b53dcfc
69,919
def convertColorTable(table): """Converts a Kaitai Struct-parsed color table to a list of matplotlib color maps""" cdict = { "red": [], "green": [], "blue": [] } countOfColors = len(table.colors) maxColorIndex = countOfColors - 1 for i, col in enumerate(table.colors): for compName in cdict: comp = geta...
2a513a4ecaf60a81c7bf650ba524af29ff51e96f
69,920
def _filter_label_set_to_most_specific( label_set, reversed_normalizer): """Filters label set to most specific. Args: label_set: set of all labels given to protein. reversed_normalizer: output of reverse_map(label_normalizer). Helps this function run fast. Returns: Filtered set of labe...
84397b8a6c208b88c13456805be592d9f2e9a505
69,921
def get_tasks_for_weekly_report(model_obj, company, date_from, date_to): """Отдает отфильтрованный кверисет с уникальными датой и описанием""" return model_obj.objects.select_related( 'tag', 'employees').filter( date__gte=date_from).filter( date__lte=date_to).filter( ...
3b46205d3c1bb5b5d472b350371561167aa2fb5b
69,922
from re import T def local_op_of_op(node): """ Prod(Prod()) -> single Prod() or Sum(Sum()) -> single Sum() """ if isinstance(node.op, T.elemwise.Prod) or isinstance(node.op, T.Sum): opt_type = T.Sum if isinstance(node.op, T.Sum) else T.elemwise.Prod node_inps, = node.inputs ...
59c795e03d5ec26dff8d32aafd5310fb1ab6ccb3
69,923
def detectFallingSeq(points_list): """Find falling temperatures sequences in given list and stores beginnings and ends of them in list. Always with format [seq1 start index, seq1 end index, seq2 start index, seq2 end index, ...] :param points_list: list of pipe temperatures :return: list of indexes ...
e940497b72745af1669062373a6aca025ac0626c
69,924
async def find_app(hass: HomeAssistantType, api): """Find an existing SmartApp for this installation of hass.""" apps = await api.apps() for app in [app for app in apps if app.app_name.startswith(APP_NAME_PREFIX)]: # Load settings to compare instance id settings = await app.settings() ...
57787205e3fd9ea94607d2c4cc62e60d8bd48257
69,925
def count_symbols(atoms, exclude=()): """Count symbols in atoms object, excluding a set of indices Parameters: atoms: Atoms object to be grouped exclude: List of indices to be excluded from the counting Returns: Tuple of (symbols, symbolcount) symbols: The unique symbols in...
31f7c116f07788171828f0e116ef28a43eb0e313
69,926
def extract_bboxes(mask): """Compute bounding boxes from masks. Args: mask [height, width, num_instances]: Mask pixels are either 1 or 0. Returns: bounding box array [num_instances, (y1, x1, y2, x2)]. """ boxes = np.zeros([mask.shape[-1], 4], dtype=np.int32) for i i...
f303ba362be567d8b981630201ba913c4b987bf0
69,927
import functools def ignore_transport(transport): """ If test function is wrapped into this decorator then it should not be tested if test is performed for specified transport """ def wrapper(func): @functools.wraps(func) def test_method(*args, **kwargs): if GRAB_T...
b39d1b7db2b82722e39159cdf7b529d5f88caa65
69,928
import ntpath def lookup_folder(event, filesystem): """Lookup the parent folder in the filesystem content.""" for dirent in filesystem[event.parent_inode]: if dirent.type == 'd' and dirent.allocated: return ntpath.join(dirent.path, event.name)
e18df4610bba9cf71e85fe0038a5daf798822bd3
69,929
import json def parse_response(func): """Parse receive response to json format.""" def wrapper(*args, **kwargs): response = func(*args, **kwargs) try: return response.json() except json.JSONDecodeError: return { "success": False } ...
7ad55e524c52cf151e2de8c29d6c2ea786b21a9a
69,930
def ret (numerator,denominator,code): """ Divides two dataframes by transposing and using linear algebra rules """ df_tradingret = numerator.T / denominator -1 df_tradingret = df_tradingret.T df_tradingret = pd.concat ([df_tradingret, code], axis=1) return df_tradingret
243ab30c44cda82ff7bbf8174a3644efbc22811b
69,931
def read_xyz(filedesc): """Takes a xyz-style file and creates an Atoms object. Args: filedesc: An open readable file object from a xyz formatted file. Returns: An Atoms object with the appropriate atom labels, masses and positions. """ natoms = filedesc.readline() if natoms == "": ...
44444a452bc364ac9df76674ed60e0482666a34d
69,932
import hashlib def create_unique_shape_id(line_string: LineString): """ Creates a unique hash id using the coordinates of the geomtery Args: line_string: Line Geometry as a LineString Returns: string """ x1, y1 = list(line_string.coords)[0] # first co-ordinate (A node) x2, y2 = lis...
afb57e4bef7baab401467e073d484a4131a1d32e
69,933
import logging import sys def initialize_logger(log_file, logAppName): """Set up logging. Returns: logger (:obj:`logging object`): log with file and stream handlers """ logger = logging.getLogger(logAppName) logger.setLevel(logging.DEBUG) file_handler = logging.FileHandler(log_file) ...
433e575edece0262d3b48ad923fe2ecec36bf7ae
69,934
def p27(): """ a and b s.t n*n + a*n + b produces the longest sequence of primes """ maxLen, res = 0, 0 for a in xrange(-999, 1000): for b in xrange(-999, 1000): seqLen = getLen(a, b) if seqLen > maxLen: maxLen = seqLen res = a*b return res
1db5ad6cc2d8484f5494aab5234d3b88e7c97f2f
69,935
def gate_expand_2toN(U, N, control, target): """ Create a Qobj representing a two-qubit gate that act on a system with N qubits. Parameters ---------- U : Qobj The two-qubit gate N : integer The number of qubits in the target space. control : integer The index ...
3501a6b785092b95ce9f95d8b1b617a78c5d8863
69,936
import html def test_cdcb003_dict_callback_strict_true(dash_duo): """ Test if strict is True an extra output keys in output dictionary causes a KeyError At this point I don't know how to write an assertion for this """ lock = Lock() app = dash.Dash(__name__, plugins=[DashCallbackPlugin()]) ap...
044b8ee80d8eebcd32d67aae8494aacfdf532c14
69,937
def extract_user(ops, json_data): """ Extract user from JSON data. """ if json_data is None: return None if 'required_posting_auths' not in ops or 'required_auths' not in ops: return None if ops['required_posting_auths'] is None or ops['required_auths'] is None: return None ...
0722afa2f174628670658fbbc0f1a0ab80cd36fe
69,938
from itertools import izip def _slow_pivot(index, columns, values): """ Produce 'pivot' table based on 3 columns of this DataFrame. Uses unique values from index / columns and fills with values. Parameters ---------- index : string or object Column name to use to make new frame's inde...
f5eab1b016424c0cd4922b537aa573b66f0a663d
69,939
def calculate_adjusted_elo_rating(player_one_rating: int, player_two_rating: int, player_one_win: bool, k_factor=32) -> (int, int): """ Calculates new elo scores for two players :param player_one_rating: first player's original rating :param player_two_rating: second player's origin rating :param player_one_...
2792981c6b50836897c5c2396e35bcce7026a716
69,940
import io def usgs_lead_call(*, resp, year, **_): """ Convert response for calling url to pandas dataframe, begin parsing df into FBA format :param url: string, url :param resp: df, response from url call :param year: year :return: pandas dataframe of original source data """ df_ra...
500e8a61c287b4311f6abd8fe32362b55ac5b544
69,941
def ParseDeviceBlocked(blocked, enable_device): """Returns the correct enabled state enum based on args.""" if enable_device is None and blocked is None: return None elif enable_device is None or blocked is None: # In this case there are no default arguments so we should use or. return blocked is True...
4554ca5e33194fea77516e910516f3937cd61f3a
69,942
import random def blobs( width=8, height=8, k=3, min_extend=0, max_extend=1, random_seed=None): """Generates a 1 to k number of blobs on a 2D grid Args: width: width of grid generated height: height of grid generated k: number of random ...
44fa440913dbf5ecfc16e03972a48c6713d47406
69,943
import torch from re import T import pickle import os def get_data( data_type, train_fraction=1, added_edge_fraction=0, feature_noise_ratio=0, **kwargs): """Get the pytorch-geometric data object. Args: data_type: Data type. Choose from "Cora", "Pubmed", "citeseer". If want the...
ace3dd2bdf9a879c07d8fc6c83a4f0b08ee028ea
69,944
def load_env() -> Environ: """Load environment variables and expand hierarchy as namespace.""" return Environ(prefix='PLOT').expand()
abda28d07ac2205f9bbf45b8dea8c2c6b03ec697
69,945
def squared_pearson_correlation_r2(results, labels, pos=1, neg=0): """ Citation: MITTLBÖCK, M. and SCHEMPER, M. (1996), EXPLAINED VARIATION FOR LOGISTIC REGRESSION. Statist. Med., 15: 1987-1997. doi:10.1002/(SICI)1097-0258(19961015)15:19<1987::AID-SIM318>3.0.CO;2-9. https://pdfs.semanticscholar.org/39f1...
b12de91d6c2e781fe5681f3ac58b07d32bfbe493
69,946
from typing import Dict from typing import Any def grains_filter_by( salt_mock: SaltMock, lookup_dict: Dict[str, Any], grain: str = "os_family", **kwargs: Any, ) -> Any: """Read grains from a SaltMock instance to implement grains.filter_by. See https://github.com/saltstack/salt/blob/v3002.5/s...
bcbf632adf2b5397f67c2b5d223f8cb215884b81
69,947
def exists(reader_name: str) -> bool: """Check whether the given reader exists Args: reader_name: Name of reader. Returns: True if reader exists, False otherwise. """ return plugins.exists(package_name=__name__, plugin_name=reader_name)
99ff673a4110a601500ae4c3e3367c64c21b4d0d
69,948
import os def get_dask_Client(timeout=30, n_workers=None, threads_per_worker=1, processes=True, create_cluster=True): """ Get a Dask.distributed Client for the scheduler defined externally, otherwise create The environment variable ARL_DASK_SCHEDULER is interpreted as pointing to the scheduler. and a cli...
054d660565fab7baf28c95227f98552ed2c22c65
69,949
def is_broken_link(url): """Determine whether the link returns a 404 error.""" try: request = urllib_request.Request( url, headers={'User-Agent': 'Mozilla/5.0'}) urllib_request.urlopen(request).read() return False except urllib_request.URLError: return True ex...
12afac7aec8b8465a968e6bb7a2df9e9bdb0de8d
69,950
def get_education_degrees(education_counts, educations): """ Gets a map count of the formal educations that was provided in the survey """ education_degrees = defaultdict(int) for e in educations: for idx in education_counts.index: if idx in educations[e]: educati...
c9f4948fd19de12ab08f988472e5892e7406b92a
69,951
import re def getNormform(synonym): """ """ a = re.sub("[^a-z0-9]", "", synonym[0:255].lower()) return " ".join(a.split())
36d60ad20ff8adee5e4d6f009119026db8a1b874
69,952
from typing import Union import json async def session_remove_all( handle: SessionHandle, category: str, tag_filter: Union[str, dict] = None, ) -> int: """Remove all matching rows in the Store.""" category = encode_str(category) if isinstance(tag_filter, dict): tag_filter = json.dumps(...
3a5a02328ac40273b3efaa27c7091af0fd07bab9
69,953
def tarjans(complexes, products): """ Tarjans algorithm to find strongly connected components. Dirctly from the peppercornenumerator project. """ stack, SCCs = [], [] def strongconnect(at, index): stack.append(at) at.index = index at.llink = index index += 1 ...
1f81bb8734ad0383dc7aa60e116ac1ac0c20da78
69,954
def verifyNodesValueMatch (datafile, pnode, cnode, cvalue, rnode, rvalue, bnode, bvalue, dnode=None, dvalue=None): """ Searches XML file for the parent node. Finds the 1st child node and checks its value if value is a match, then search for second child and check if its value matches datafile = xml file...
a8b5e014ce2993431544025d6b9b558da7e8ba23
69,955
def conjugate_gradient_ok(f_ax, b_vec, cg_iters=10, callback=None, verbose=False, residual_tol=1e-10): """ conjugate gradient calculation (Ax = b), bases on https://epubs.siam.org/doi/book/10.1137/1.9781611971446 Demmel p 312 :param f_ax: (function) The function describing the Matrix A dot the vector x...
c8815023562b58214584f7f13fd8efe91835f00e
69,956
def parse_grid(rb): """ Parse grid location :param _RawBinaryData rb: Binary data describing the location :returns: Grid location :rtype: GridLocation """ assert rb.location_type == LocationType.GRID bl = _parse_absolute_coordinates(rb) if rb.num_bytes == LARGE_GRID_SIZ...
8c1d047e50d47ebed33ebf891ee690c36afff5e9
69,957
from typing import Sequence from typing import MutableMapping from typing import List def _parse_cell( source: Sequence[str], cell_number: int, temporary_lines: MutableMapping[int, Sequence[NewMagicHandler]], command: str, ) -> str: """ Parse cell, replacing line magics with python code as pla...
f5cb8ba019852db89608e50de34415ff6acdc55a
69,958
def draw_prediction_on_image( image, keypoints_with_scores, crop_region=None, close_figure=False, output_image_height=None): """Draws the keypoint predictions on image. Args: image: A numpy array with shape [height, width, channel] representing the pixel values of the input image....
e295c8ae1d44b854fba4d8dd19bc85c9b0195c97
69,959
def process_spectrum(spectrum: MsmsSpectrum, is_library: bool) -> MsmsSpectrum: """ Process the peaks of the MS/MS spectrum according to the config. Parameters ---------- spectrum : MsmsSpectrum The spectrum that will be processed. is_library : bool Flag specifying whether the s...
ebad54e42ff763d7e27a1e7dd84e8e8e8abce766
69,960
def generate_sensors(k = 7, d = 2): """ Generate sensor locations. Input: k: The number of sensors. d: The spatial dimension. Output: sensor_loc: k * d numpy array. """ sensor_loc = 100*np.random.randn(k,d) return sensor_loc
c7e3d71e565b2d7fd1462f5cdeef69a6cb665910
69,961
import cmd import re def parse_csr (csr): """parse the CSR to find all domains""" out = cmd(["openssl", "req", "-in", csr, "-noout", "-text"], err=f"error loading {csr}") domains = set([]) # Find Common Name in CSR cn = re.search(r"Subject:.*? CN\s?=\s?([^\s,;/]+)", out.decode("utf-8")) if cn...
deb8035c3f4b8fa2929ccae1aa09f01789afc6cb
69,962
import functools def return_as_coroutine(return_value=None): """Creates a function that behaves like an asyncio coroutine and returns the given value. Typically used as a side effect of a mocked coroutine like this: # in module mymod: async def my_coro_under_test(): await asyncio...
92011e2fd12e85cd8afc4bc3a1f98d23e2d38160
69,963
import torch def unscale_transform(x: torch.Tensor, lower: torch.Tensor, upper: torch.Tensor) -> torch.Tensor: """ Denormalizes a given input tensor from range of [-1, 1] to (lower, upper). @note It uses pytorch broadcasting functionality to deal with batched input. Args: x: Input tensor of ...
86aa3a1ac0e15b9f19f5970ece2388de2de3f54d
69,964
def save( name: str, model: "xgb.core.Booster", *, booster_params: t.Optional[t.Dict[str, t.Union[str, int]]] = None, metadata: t.Optional[t.Dict[str, t.Any]] = None, model_store: "ModelStore" = Provide[BentoMLContainer.model_store], ) -> Tag: """ Save a model instance to BentoML modelst...
8f60a8c00345c997262955e87693cba8c5f949e4
69,965
def defaultformatter(default_factory): """The default factory is called without arguments to produce a new value when a field value is not present. All remaining field are treated the same as if they were passed to the str.format, including keyword arguments. """ return DefaultFormatter(default...
800244382025a84583b2cdac6454eb18a105d2ea
69,966
def sigmoid_derivative(x): """ Compute the gradient (also called the slope or derivative) of the sigmoid function with respect to its input x. You can store the output of the sigmoid function into variables and then use it to calculate the gradient. Arguments: x -- A scalar or numpy array ...
0dbc00a502a3eea4d99739a98c541af28264ea76
69,967
def hidden_digits(time_string): """ converts time with unknown digits to max time with respect to hours and minutes given starting digits Args: time_string (str): a string representing an unknown time Returns: max_time_string (str): a string with filled in missing digits for max time """...
15fdefb340ab5fe66b562f0fa642210db138c590
69,968
def is_valid_target(url, request): """ Take a URL string and check if the path component seems to exist on the current site. Returns False if the URL raises a 404, and a UrlResolver object if the URL seems to exist. """ # First, set up a variable for the tentative status: accepts_webmen...
7592979c9e71c186f71a419875617ac86bd27498
69,969
def find_tuple_with_max_vl(base, T, key): """ Scan through the whole table T, and find the i-th tuple that maximizes VL(base, i). Returns ------- :return best: int Unique Id of the found tuple """ max_vl = 0 best = None for k in T.keys(): if k != key: v...
89b0a2b9334c9faeef6065e9e1d92854e6f221e2
69,970
def classification_signature_fn(examples, unused_features, predictions): """Creates classification signature from given examples and predictions. Args: examples: `Output`. unused_features: `dict` of `Output`s. predictions: `Output` or dict of tensors that contains the classes tensor as in {'class...
54802e9846d8604729e7ec134c05b5a07da3d182
69,971
def static_graph(*args, **kwargs): """Decorator to mark a Chain's ``__call__()`` as a static sub-graph. This decorator marks the define-by-run code inside the `__call__()` method of a Chain instance as corresponding to a static computation graph or sub-graph. Such a chain will be referred to as a 'stat...
7fee1141ccd09b7ab7f47a6ab8e96243293eea7f
69,972
def action(method): """ Marks an agent instance method to be registered as an action :param method: :return: """ method._register_action = True return method
15f32f6acd7e31e50ef3b61d0de04e029e65249a
69,973
import pandas import urllib def get_sensor_data( aranet_conf, sensor_id, from_time, to_time, timezone="0000", metrics=list(DEFAULT_METRICS_DICT.keys()), **kwargs) -> pandas.DataFrame: """Get the data for a given sensor from the Aranet Cloud. Args: aranet_conf: Object of the Ar...
a5254e3936a2d47c3bd40807cda7547e29dab4db
69,974
import subprocess import argparse def is_valid_dokku(dokku_command=None): """ Checks whether dokku_command is a well defined path to an executable. args: - dokku_command (optional): str Path to dokku command location returns: - bool Whether dokku_command is a valid dokku command ...
6bb5cafeee22034012c1a7e4eb8271064b104701
69,975
def OutputVector(r, name, mode="python", initial_tabs=3, max_index=30, replace_indices=True, assignment_op="="): """ This method converts into text the RHS vector Keyword arguments: rhs -- The RHS vector name -- The name of the variables mode -- The mode of output initial_tabs -- The number of ...
4043f2d1166a1ebc65ae3120156eb3ebe4402eba
69,976
def create_connection(url, timeout=None, **options): """ connect to url and return websocket object. Connect to url and return the WebSocket object. Passing optional timeout parameter will set the timeout on the socket. If no timeout is supplied, the global default timeout setting returned by g...
2faaa073de7231d3446bcce505c46df9bfcb58db
69,977
def _has_basal(morph_path): """Check if neuron has basal dendrites.""" _morph = Morphology(morph_path) for root in _morph.root_sections: if root.type == SectionType.basal_dendrite: return True return False
799230bd4f16be92e559cb1d199f9626cae25a97
69,978
import re def filter_illegal_chars(dirty, repl=''): """Remove character which allow to inject code which would be run by displaying on the page """ illegal_chars_re = re.compile('[<>="]') return illegal_chars_re.sub(repl, dirty)
d389df644959850ccd4de6dd7ab22f0276b47435
69,979
def get_congress_search( congress=None, chamber=None, versions=None, text=None, page=None, page_size=None ) -> BillSearchList: # noqa: E501 """Your GET endpoint Search for the different bills # noqa: E501 :param congress: Comma separated list of sessions to filter by :type congress: str :para...
5420907bfbf5c02691f0328be0cdbd2cec2c99f0
69,980
def ParseXMLString(raw_xml): """Parses raw_xml and returns an ElementTree node that includes comments.""" return ET.fromstring(raw_xml, _CommentedXMLParser())
84f76b8ef5d1ed57a83c4e1bdf27571db3ea7890
69,981
from typing import OrderedDict def _flatten_obs(obs, space): """ Flatten observations, depending on the observation space. :param obs: (list<X> or tuple<X> where X is dict<ndarray>, tuple<ndarray> or ndarray) observations. A list or tuple of observations, one per environment. ...
1eb81c79f284226887a82a4b7cd7b7a748c4fa00
69,982
from typing import Optional def generate_captcha(seed: Optional[int] = None, length: int = 4, format: str = "png"): """生成验证码(先生成字符,再生成图片)""" code = generate_captcha_code(seed, length) capthca_key = uuid4() # 理论上有碰撞的可能,但验证码嘛,换一个就是了。 key = current_config.CAPTC...
e005603263a5f81cbc901c55c3e1c12065cd80ca
69,983
import re import logging import functools def match(func=None, regex=None, thread=False): """ this decorator is used to create a command the bot will respond to. """ def decorator(func): func.__brutal_event = True func.__brutal_event_type = 'message' func.__brutal_trigger = Non...
8fb06014196ffb1b499ebf172cf4c88f247c100b
69,984
import os def read_firmware_file_tree(glue_database: str, fw_sha256: str) -> DataFrame: """ Reads a firmware file tree from the jsonl files backing the file_tree table defined in the Glue Data Catalog. :param glue_database: The name of the Glue database from which to read the files, e.g. fimrware_prod. ...
47e99256e55ed489d11a14a01957877f2effc5a0
69,985
def gen_task2() -> np.ndarray: """Task 2: head of random sequence.""" seq = rand_syms() return np.concatenate(([2], seq, [seq[0]]))
fe98dbf30be0933f58c06f8914dc8835bcaf12ed
69,986
def download_page(cluster_id): """Handle download of the SSH private key """ cluster = Cluster.query.filter_by(id=cluster_id).first() if cluster and cluster.ssh_private_key: return Response( cluster.ssh_private_key, mimetype="text/json", headers={"Content-disp...
65636f137234c633e9a23d63c667f3bd4365e1b7
69,987
from establishment.errors.errors import BaseError def login_required_ajax(function=None): """ Just make sure the user is authenticated to access a certain ajax view """ def _decorator(view_func): def _wrapped_view(request, *args, **kwargs): if not request.is_ajax(): ...
238e764b855c8766165d105f9094be10ffee75ff
69,988
def analyze_SENTINEL_temperature(sen_directory, sen_shape_path, daytime_S3): """ returns the temperature value for each pixel of each station for each SENTINEL scene prints an array for the scenes according to the stations :return: returns three arrays (1st array displayed for each station is the te...
c270a6176170a73c1cbda728096a010af76e919f
69,989
def exp_np_array_list(lst, power): """ Raise elements of a list (of np.arrays - elementwise) to power @param lst: list of np.arrays @param power: scalar, to which power the elements should be raised @rtype list of np.arrays """ result = [] for nparr in lst: result.append(nparr **...
8c8b80c217f4a381e8514c7fff06dc98114087d9
69,990
def max_layout_dimensions(dimensions): """ Take the maximum of a list of :class:`.LayoutDimension` instances. """ min_ = max([d.min for d in dimensions if d.min is not None]) max_ = max([d.max for d in dimensions if d.max is not None]) preferred = max([d.preferred for d in dimensions]) retu...
67e309465f400334dcd68ff8c8197b5cd641b205
69,991
import os import re def get_ch_names(path, dir): """获取文件中文名称,如无则返回文件名""" file_ch_names = [] reg = r"new Env\(\"[\S]+?\"\)" ch_name = False for file in dir: try: if os.path.isdir(f"{path}/{file}"): file_ch_names.append(file) elif file.endswith(".js") ...
bae20e2a03b188aeb1f6dae33f6c3a66d26ca48e
69,992
def split_dataset(dataset: Dataset, val_split: float = 0.1, seed: int = 17): """Splits dataset into train and validation ones and transform them into dataloaders. Parameters ---------- dataset : Dataset Dataset to split. val_split : float Ratio used in spliting. seed : int ...
5b69ae352c96511546045ecba18a09ced6b1e15a
69,993
def check_if_significant(data, thresh=1e-5): """ trim data based on threshold. Args: pandas DataFrame: data needs to be trimmed. threshold (float): a constant. Default = 1e-5. Returns: pandas DataFrame: data after trimming. pandas DataFrame: corrsponding index of data....
62494c97559632f2d8d3e542320cb72f3da90eab
69,994
import math def _cosine_anneal(x: float, min_y: float = 0.0, max_y: float = 1.0) -> float: """Implements a cosine decay curve. Curve is cos(x) on domain [0, pi], stretched to the domain [0, 1] and range [min_y, max_y]. Additionally, param x is clipped to the interval [0, 1] """ x = min(max(x, 0.0...
ea3b6dfb8158c12d447d1a23cb472f0be5ef46d9
69,995
def log_rebin_pix(lamRange, n, oversample=None, velscale=None, log10=False, newRange=None): """ Determine the number of new pixels and their coordinate step when rebinning a spectrum in geometrically stepped bins. The input spectrum must be sampled linearly in wavelength. This is primarily a support routine for ...
09d46e09cfba6e0fe00c2645ab55446e4cfe6e03
69,996
def is_image_file(filename): """Checks if a file is an image. Args: filename (string): path to a file Returns: bool: True if the filename ends with a known image extension """ filename_lower = filename.lower() return any(filename_lower.endswith(ext) for ext in IMG_EXTENSI...
d87f4d48737292d619f7641f320b32f0ce760581
69,997
import csv def from_line_file(filename, filter_negative=True): """ Loads file from directory ** needs input to be a fully qualified file path. Returns a new list of tuples (x,y) containing points, where x = wavenums and y = intensities. """ spectra = [] # Read in files row by row w...
8ada4018ef0ce4ff874c548f6d12b611dd2ec59d
69,998
from typing import Any def _convert_v_0_1_imported_options(config: dict[str, Any]) -> Any: """Convert a key from the imported configuration.""" code: str | int | None = config.get("code") force_bypass: LegacyArmingOptions | None = config.get("force_bypass") no_entry_delay: LegacyArmingOptions | None ...
8811cee6b9366b9f690f0727ca7a36dae6483859
69,999