content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def bin_it(image, threshold): """ converts a single channeled image to a binary image, using upper and lower threshold """ assert len(image.shape) == 2 output_bin = np.zeros_like(image) output_bin[(image >= threshold[0]) & (image <= threshold[1])] = 1 return output_bin
9b339f1c507d08841f220973ad115ee23639558b
60,500
def getEADL(Z): """ EADL DOC: https://drive.google.com/file/d/1i5ndh-G6eD1ginpxNLzBtskJh3XTU5p9/ """ file = str(Z) + ".txt" EADL_path = str(__materials__/'EADL'/file) del file Aw, EADL_dict = get_bookmarked_text_EADL(EADL_path) EADL_dict['Aw'] = Aw EADL_dict['Z'] = Z return EADL_dict
c1d73910be56228181d042d21bfd55ccf4379cf7
60,501
import os from datetime import datetime import shutil import sys def create_logdir(args, base_config): """A helper function that ensures the logdir and log files are setup corretly. Only called in --enable_logs is set. Args: args (dict): Dictionary as returned from get_base_config() base_config (dict)...
633cd9d8f95972f91f9db9ffaf6807e1ee3b2628
60,502
def prepare_pil_image(image: object) -> object: """ Temporarily save a PIL Image object so it can be sent to the client :param `image`: PIL Image object :returns: temporary file object """ img_io = BytesIO() image.save(img_io, "PNG") img_io.seek(0) return img_io
afa870c362e47d7f596108e73114a7005175975d
60,503
from typing import Callable from re import T from typing import Optional from re import U def applicative( function: Callable[[T], Optional[U]], option: Optional[T], ) -> Optional[U]: """ Same as fmap except for the type signature. """ if option is None: return None else: return fu...
1c27cbc3266f5138e9c45106b480dc30caf89a77
60,504
def get_first_pod_name(v1: CoreV1Api, namespace) -> str: """ Return 1st pod_name in a list of pods in a namespace. :param v1: CoreV1Api :param namespace: :return: str """ resp = v1.list_namespaced_pod(namespace) return resp.items[0].metadata.name
ed431009691178bb041c78ee4c3f9aa8c7fd117a
60,505
import random def test_with_script(script_path, output_path='script_output.txt', dump_stats=1): """ tests with a script: a script is a list of link text strings, each indicating the link text to click on. """ script_data = [] with open(script_path) as f: for line in f.readlines(): ...
9552e3dc6c8c8b62b8ee82f8ab0caac1d2c7485e
60,506
from typing import Dict def _classify_edge( parent: V, child: V, vertex_depth: Dict[V, float], search_trees: UnionFind[V] ) -> str: """Helper function to classify non-tree edges in a breadth-first-search (BFS) tree. Args: parent: The parent vertex of the edge being classified in the BFS tree. ...
1cea62087601c3a3db28d6aea95aa6a0246003d5
60,507
import os def is_device_in_ring(dev, skip_rel_check=False, ignore_deactivated=True): """Check if device has been added to the ring. First check local KV store then check storage rel with proxy. """ d = os.path.dirname(KV_DB_PATH) if not os.path.isdir(d): mkdir(d) log("Device '%s' ...
14c4ba80aaab0cde126736d7b4a7d23cf27006c9
60,508
def get_and_set_pymol_instance(pymol_instance=None): """ Get the global *PyMOL* instance. This function is intended for internal purposes and should only be used for advanced usages. Parameters ---------- pymol_instance : module or SingletonPyMOL, optional If a *PyMOL* instance is...
c3a4eecd177d1c273192fa75cd787eb7f0b45432
60,509
import glob def load_tyr2ala(): """Load the NAMD tyrosine to alanine mutation dataset. Returns ------- data : Bunch Dictionary-like object, the interesting attributes are: - 'data' : the data files by alchemical leg - 'DESCR': the full description of the dataset """ ...
d5bf5710e2016e18f93b7316dc6ad1b0559df0c2
60,510
def extract_same_host_pattern(base_url: str) -> str: """Looks at the passed base/start URL to determine which mode for :func:`is_same_host` is appropriate. First looks at whether the given URL contains a non-empty path. If one is found, the number of directories ``X`` is counted and ``directoryX`` is return...
387eb95f5d7c8e1f10a0d4808b2b398492bd20b6
60,511
def crop_max(img, dim, offx=0, offy=0, filtmed=True, f=3): """ Summary ------------- Resize an image on the brightest pixel. Parameters ---------- `img` : {numpy.array} input image,\n `dim` : {int} resized dimension,\n `filtmed` : {boolean}, (optionnal) True ...
ca2f974f5ac005917b7505d8fde85b97f47bb582
60,512
def jaccard_distance_loss(y_true, y_pred, smooth=1): """ Jaccard = (|X & Y|)/ (|X|+ |Y| - |X & Y|) = sum(|A*B|)/(sum(|A|)+sum(|B|)-sum(|A*B|)) """ y_true_f = K.flatten(y_true) y_pred_f = K.flatten(y_pred) intersection = K.sum(y_true_f * y_pred_f) sum_ = (K.sum(y_true_f) + K.sum(y...
4a5017d865275836cd8ae50be7d3924368172bf0
60,513
def unit_test_1(object_id): """ Decorator is nonexistent! Method Function using decorator. """ # if run this function! print('This is method which needs to be tested!') return True
bb1735f77a813cb2ecba0f6af4bda4ed9d8202a4
60,514
import os import random def ch_download_latest_multi(channels=None, repost=True, number=None, shuffle=True, ddir=None, own_dir=True, save_file=True, server="http://localhost:5279"): """Download the ...
f100b52e7a7ef11c17b55e570b3db64460f6a657
60,515
from typing import Dict from typing import Tuple def get_revenues_costs_data( power_data: pd.DataFrame, prices_data: pd.DataFrame, power_forecast_data: pd.DataFrame, prices_forecast_data: pd.DataFrame, metrics: Dict[str, float], unit_factor: float, resolution: str, showing_individual_t...
030b74c87b22078934a83df62eda1bb488d95795
60,516
def bcoef(n1,n2,n3,r): """ Calculates the B coefficient needed for the coupling of two symplectic raising polynomials Args: n1, n2, n3: U3State class variable r: integers, coupling multiplicity of n1xn2->n3 Returns: b coefficient. For example, n1=U3State([2,2,0]) n2=U3State([2,2,0]) n3=U3State([4...
8ad36af9ee28dd979cc06f61c56eda0f664a5207
60,517
def _smoothing_matrix(vertices, adj_mat, smoothing_steps=20, verbose=None): """Create a smoothing matrix. It can be used to interpolate data defined for a subset of vertices onto mesh with an adjancency matrix given by adj_mat. If smoothing_steps is None, as many smoothing steps are applied until ...
0a7d9d913529b79fbb08901cef5c47351f978774
60,518
def user_remove(name, database=None, user=None, password=None, host=None, port=None): """ Remove a cluster admin or a database user. If a database is specified: it will remove the database user. If a database is not specified: it will remove the cluster admin. name User name to remove ...
928e8bb9249c0a3e14f0718014d7664b694a3574
60,519
def reboot(ctx): # type: (ApiCtx) -> dict """ Reboots the modem. """ url = "{}/device/control".format(ctx.api_base_url) headers = { "__RequestVerificationToken": ctx.token, } payload = ( '<?xml version: "1.0" encoding="UTF-8"?><request><Control>1</Control></request>' ...
71450c6cba7b9abfcec10c1bfe2f6afd79428b87
60,520
def api_welcome(): """ welcome page """ return "welcome to the main page"
dc1875694e267950cf1765a01bcdd38a78b3c570
60,521
def DoIt(CodeString,ReturnMessage=""): """ This function takes a string and tries to turn it into valid Python code, then execute it. Its main purpose is for use in debugging, to set variables and the like, but you can execute any valid Python code fragment with it. Be careful! """ try: ...
fbf1ba35775e18e37873d176dd7f4e4b53d41721
60,522
from scipy.misc import imresize def _get_resample_angles_imresize( root, group, dst_shape, interp='bilinear', extrapolate=True ): """Parse angles and resample with scipy.misc.imresize Parameters ---------- root : lxml root root of granule metadata XML doc group : str path ...
95dfabb94a15ba8461487793bee04dfd80be05e3
60,523
def bellman_operator(pgrid, c, f0, f1, L0, L1, J): """ Evaluates the value function for a given continuation value function; that is, evaluates J(p) = min((1 - p) L0, p L1, c + E J(p')) Uses linear interpolation between points. """ m = np.size(pgrid) assert m == np.size(J) ...
5b53cfc9ff2d26805a5b79ad026cc3a3cdc14aba
60,524
def calculate_1d_distributions_distances(real_values, fake_values): """ Calculates an array of distances between fake and real distributions for each detector :param: real_values - np.array with real values of shape [detectors_num, signals_num] :param: fake_values - np.array with real values of shape [d...
22c2d8d597def83292af93279320d584c71396b6
60,525
import math def check_request( tools, req_id, req_type, all_samples, rxn_multiplier=None): """Validates that the request has the correct cost associated with it. Arguments: tools (IlabTools): An authenticated IlabTools object. req_id (string): The unique string of ints that represent ...
1c689c1db1cb43e69dd5ff21244da16ba8cdb11a
60,526
import os def logPath(job, frame=None): """logPath(job, frame=None) Extracts the log path from a job or a job/frame """ if frame: return os.path.join(job.data.log_dir, "%s.%s.rqlog" % (job.data.name, frame.data.name)) else: return job.data.log_dir
068a906af8351e25debc9db7192006fcf5b9efb9
60,527
def checkpoint_filter_fn(state_dict, model): """ convert patch embedding weight from manual patchify + linear proj to conv""" out_dict = {} if 'model' in state_dict: # For deit models state_dict = state_dict['model'] for k, v in state_dict.items(): if 'patch_embed.proj.weight' in...
cc5e5931ebac9368185796d32f646fd30ada4858
60,528
def extract_media(request): """Extract the media from a flask Request. To avoid race conditions when using greenlets we cannot perform I/O in the constructor of GcsObject, or in any of the operations that modify the state of the service. Because sometimes the media is uploaded with chunked encoding, ...
298bb7c5e4dddf02e12c398d55b6d388354a279e
60,529
def LOG10(value): """ Returns the the logarithm of a number, base 10. >>> round(LOG10(86), 9) 1.934498451 >>> LOG10(10) 1.0 >>> LOG10(100000) 5.0 >>> LOG10(10**5) 5.0 """ return _math.log10(value)
a8564928302cf4a1a4e920eff0e61c2f5f62089b
60,530
import requests def get_versions_from_pypi(package_name: str = "") -> dict: """Get package versions from PyPi JSON API. ::package_name:: Name of package to get infos from. ::return:: A list of versions. """ if package_name == "": raise ValueError("Package name not provided.") url = f"...
675d90eb18b775aa0f57223c19d86a568773d72b
60,531
from datetime import datetime def time_string_one(float_time=None, fmt=None): """ Transform a single float daytime value to string. Parameters ---------- float_time : float, optional Input time. The default is None, which returns the time now. fmt : float, optional Tim...
aa74d63300100ae6a6d1225c36269d4029b5b26d
60,532
import time import requests def macro_usa_cftc_c_holding(): """ 美国商品期货交易委员会CFTC商品类非商业持仓报告, 数据区间从 19830107-至今 https://datacenter.jin10.com/reportType/dc_cftc_c_report https://cdn.jin10.com/data_center/reports/cftc_2.json?_=1591536282271 :return: pandas.DataFrame """ t = time.time() para...
a50c3260b3d0cd3edd2b5e360af6c1af390aedfd
60,533
def neatenDMSStr (dmsStr): """Convert a sexagesimal string to a neater version. error conditions: raises ValueError if the string cannot be parsed """ if dmsStr == "": return "" precArry = dmsStr.split(".") if len(precArry) > 1: precision = len(precArry[1]) else: ...
ce55e85627b94d85afd8d42ff5c134a28368dfc2
60,534
def edit_workshop(request, pk): """ Form to edit the details for a workshop series """ context = {'msg': "Edit Workshop"} workshop = Workshop.objects.get(pk=pk) if request.method == 'POST': form = WorkshopForm(request.POST) if form.is_valid(): workshop.name = request.POST['na...
a75dd4b5590559b66c449ef1d3736124b6af4e3a
60,535
import getdist def to_getdist(nested_samples): """Convert from anesthetic to getdist samples. Parameters ---------- nested_samples: MCMCSamples or NestedSamples anesthetic samples to be converted Returns ------- getdist_samples: getdist.mcsamples.MCSamples getdist equival...
17b617524d6f03a12250c7dcd9e753a25329315f
60,536
import torch def angle2class(angles, num_classes=30): """ convert angles between [0, 180] to class index for classification Args: angles (np.ndarray): angle in radian Returns: out_class (np.ndarray): angle is converted to class, the number of which is defined in num_c...
023bd8d37d52a3e7e200a70048978f6c410d7f2c
60,537
def _indent(level): """Returns leading whitespace corresponding to the given indentation `level`. """ indent_per_level = 4 return ' ' * (indent_per_level * level)
4391c308b59db321ef3f810c73b66e35d44566fa
60,538
import math def getClosenessWeight(sigma_g, H, W): """构建空间权重模板""" r, c = np.mgrid[0:H:1, 0:W:1] r -= (H - 1) // 2 c -= (W - 1) // 2 closeWeight = np.exp(-0.5*(np.power(r, 2) + np.power(c, 2)) / math.pow(sigma_g, 2)) return closeWeight
b85bf269d7bc1f20094a51e3c8591017130361b3
60,539
import os def napari_get_reader(path): """A basic implementation of the napari_get_reader hook specification. Parameters ---------- path : str or list of str Path to file, or list of paths. Returns ------- function or None If the path is a recognized format, return a func...
e545eea847eb001ecd564ee1b7f6aa747f774724
60,540
from typing import Optional import torch def random_quaternions( n: int, dtype: Optional[torch.dtype] = None, device=None, requires_grad=False, ): """ Generate random quaternions representing rotations, i.e. versors with nonnegative real part. Args: n: Number to return. ...
abb1e8fe449bba9422a79e43a0f808319a2e9786
60,541
import tqdm import test def train(args, model, device, train_loader, optimizer, epoch,reg_function1=None,reg_function2=None,criterion=F.nll_loss): """ Trains the current inpur model using the data from Train_loader and Updates parameters for a single pass """ model.train() for batch_idx, (dat...
244280053fc1c2748b3ac280703235d6e771f53e
60,542
def logcosh(x): """log(cosh(x))。Smooth L1 lossみたいなもの。""" return x + tf.math.softplus(-2.0 * x) - np.log(2.0)
ede737cfbc0a94821b439dd4d667306769fdbf66
60,543
def create_host(ec2_conn, ipa_client, image_id, count, domain, key, secgroup_ids, instance_type, subnet_id, disk, instance_vars, role=None, instance_profile=None, hostgroups=None, hostname=None): """Adds host defined in manifest to IPA, then adds the OTP from the ...
3908a69e80b0790392ae2f7f308864d88cf6cd12
60,544
import subprocess import json def is_leader_without_successor(): """Checks if the current node is safe to be removed. Check if this node acts as a leader to a cluster with more than one nodes where there is no other node to take over the leadership. :return: True if this node is the leader without a...
0737a7b5768df63fcd2a20679a741a0c6a3ea057
60,545
def uid_gid(): """Return the Unix uid:gid (user ID, group ID) pair.""" return '{}:{}'.format(fp.run_cmdline('id -u'), fp.run_cmdline('id -g'))
9524fd8da5995db9ba2ac816d4cf06e9a8dd776e
60,546
from pytools import any import six def match_dtype_to_c_struct(device, name, dtype, context=None): """Return a tuple `(dtype, c_decl)` such that the C struct declaration in `c_decl` and the structure :class:`numpy.dtype` instance `dtype` have the same memory layout. Note that *dtype* may be modified ...
b05ce6f17742f7a90b1905046ee1a2d7ec0a611c
60,547
import os import fnmatch def find_matches(sdir,pattern): """ Walk sdir and find all files and dirs the match given pattern. """ matches = [] for root, dirs, files in os.walk(sdir): all = [] all.extend(dirs) all.extend(files) for item in fnmatch.filter(all, pattern):...
ffffcc906043606618e5ca7c2f1bee2e8243a916
60,548
import os def file_exists(filename): """ Ensure a path exists Raise ArgumentTypeError if it doesn't. """ if not os.path.exists(filename): raise ArgumentTypeError(f"No such file: {filename}") return filename
edd2ecceea78aa31710847e7aff6cac93b113bdd
60,549
import ctypes def dataSources(): """Return a list with [name, descrition]""" dsn = create_buffer(1024) desc = create_buffer(1024) dsn_len = ctypes.c_short() desc_len = ctypes.c_short() dsn_list = {} try: lock.acquire() if shared_env_h == None: AllocateEnv() ...
92a03ba7833d55aae899f24542d917f27f4b96e6
60,550
def split_grads_by_size(threshold_size, device_grads): """Break gradients into two sets according to tensor size. Args: threshold_size: int size cutoff for small vs large tensor. device_grads: List of lists of (gradient, variable) tuples. The outer list is over devices. The inner list is over in...
cd181c4427b9bcba0356ed813317e182d2bedfeb
60,551
def select_sensor_data(request, sensor_id): """ Afficher les données applicatives et de contrôles mesurées par le capteur d'id sensor_id """ data_app = Donnee_appli.objects.filter(capteur_id=sensor_id) data_ctrl = Donnee_ctrl.objects.filter(capteur_id=sensor_id) return render(request, 'iotCloud/...
6a51b5869b939fb5dcabcc543f943f0239ed3469
60,552
from typing import Tuple def get_dlat_dlng( lat: float, dx: int, dy: int, ) -> Tuple[float, float]: """ Get the latitude and longitude relative to the provided coordinates under the offset in meters. For more information, visit: https://gis.stackexchange.com/a/2980 :param lat: Latitu...
a12cb451c3868cb21a1e34c686a7aadc17364245
60,553
def linear_steer_vector(topo, doa, num_bins, c=340, sr=16000): """ Compute steer vector for linear array: [..., e^{-j omega tau_i}, ...], where omega = 2*pi * f 0 1 ... N - 1 * * ... * 0 d1 ... d(N-1) Arguments: topo: linear topo, N doa: direction o...
2b7d3cf8f2c9ca05931885bbeccd7efd66f1c396
60,554
def get_lr(optimizer): """Assume that the optimizer has single lr""" lr = optimizer.param_groups[0]["lr"] return lr
84a78839e5dfb37214ac5f785ae60813eb6bae23
60,555
def map_string_to_num(stri): """ Take a string, check wether it is an integer, a float or not """ if ('.' in stri) or ('E' in stri): #it's definitely a float return REAL(stri) else: return INTEGER(stri)
f2456be79e1e617405e75670056dbdf4639cf3eb
60,556
def get_converter(type_name, read=True, cache=True): """ Given a type name, attempt to find a type converter with standardised name like `Read_int`.The returned type converter cannot be invoked directly, only passed as a argument to xloil_core functions. """ direction = _READ_CONVERTER_PREFIX ...
8886d8dc13779b9c0708dbe8ffdc6a536e6a0486
60,557
def bag_of_words(data_frame: pd.DataFrame, column: str) -> pd.DataFrame: """Creates a bag of words out of the text in the given column of the data frame. Params: - data_frame (pd.DataFrame): The data frame containing text data - column (str): The name of the column for which to create the bag of words ...
c5ec3f2a22678a77aff5c2944e6f027c6780504c
60,558
def decode_dram(site): """ Decode the modes of each LUT in the slice based on set features. Returns dictionary of lut position (e.g. 'A') to lut mode. """ lut_ram = {} lut_small = {} for lut in 'ABCD': lut_ram[lut] = site.has_feature('{}LUT.RAM'.format(lut)) lut_small[lut] = sit...
ea1b61b1e924c6637cc7a4fe5d523939d19edb5c
60,559
import argparse def parse_args(): """Parses command line arguments. Parameters: nothing. Returns: args : object Containing the image and destination arguments. Outputs: nothing. """ f_help = 'Name of the FITS file.' kw_help = ...
b862085333f428120d5b315759fe1ef1650c9390
60,560
import ast def add(*arguments): """ Add function. """ return ast.Add(*arguments)
6e48ee2cd5a3caf34fdc9b8f6f72313ed85f93c6
60,561
def channel_with_loss_one_duplication(inputs, name=None, state_prefix=None, translate_message=None): """ Makes at most one duplication of a message. """ if translate_message is None: transla...
6d68c88716ab7114da90c2b40890d7c348fc9090
60,562
def perpendicular_vector(v): """ Compute a vector perpendicular to the input vector """ # x = y = z = 0 is not an acceptable solution if v[0] == v[1] == v[2] == 0: raise ValueError("zero-vector") if v[2] == 0: return [-v[1], v[0], 0] else: return [1.0, 1.0, -1.0 * (...
4920eda33090a509617058c9cf392a732726d517
60,563
def get_endpoint_type(app: str, endpoint: str) -> str: """ Parameters ---------- app name of the app endpoint url of the endpoint. Returns ------- "get" | "post" """ return list(get_app_specification(app)["paths"][endpoint].keys())[0]
371e2e2dd01b0db5fa7f99eb14be9fb2e647eea9
60,564
import torch import os import shutil def get_weights( source_feature, validation_feature, target_feature, num_workers, batch_size, temp_folder, framework_cls, ): """ :param source_feature: shape [N_tr, d], features from training set :param validation_feature: shape [N_v, d], fe...
07ebab66adb08fc3d8f57ed493ce792c1d3936c6
60,565
def cnn(n_timesteps, n_features, n_outputs): """ Args: n_timesteps: n_features: n_outputs: Returns: """ model = tf.keras.models.Sequential() model.add( tf.keras.layers.Conv1D(filters=64, kernel_size=3, activation='relu', input_shape=(n_timesteps, n_features))) ...
1f884fb04667f6a0528d7a1333417ef50eb7603d
60,566
import sys def query_yes_no(question, default="yes"): # from http://code.activestate.com/recipes/577058/ """ Ask a yes/no question via raw_input() and return the answer. "question" is a string that is presented to the user. "default" is the presumed answer if the user just hits <Enter>. I...
924cce91c41c49646db54999051b179e39a41487
60,567
def E_freq_norm(omega, alpha_i, tau_i): """ Calculate normalized storage and loss modulus values. Parameters ---------- omega : array-like Angular frequency in rad/s. alpha_i : array-like Normalized relaxation moduli (unitless). tau_i : array-like relaxation times in...
87b94dbbf0c73f529d2ddd671deffbdade59241c
60,568
import ray import logging import time import asyncio def monitor_memory_usage( print_interval_s: int = 30, record_interval_s: int = 5, warning_threshold: float = 0.9, ): """Run the memory monitor actor that prints the memory usage. The monitor will run on the same node as this function is called....
a903394827b174e9da32d0c4496e552095ab4578
60,569
def experiment(mat, nbsimu, independent = False): """ Simulates the network decompositions (in-silico extinction experiments) Parameters ---------- mat : numpy array of shape (S,S), S being the number of species Adjacency matrix of the network. nbsimu : integer Number o...
530583894baca0096645871839b56f17d9e0637b
60,570
import os import io def gen_locustfile(testcase_file_path): """ generate locustfile from template. """ locustfile_path = 'locustfile.py' template_path = os.path.join( os.path.dirname(os.path.realpath(__file__)), "locustfile_template.py" ) with io.open(template_path, encoding='...
3db59e553ad9579c147fcf71a6a034bee719a50b
60,571
from typing import List def filter_objects_by_min_score(objects: List[Object], min_score: float) -> List[Object]: """Filtrar objetos por puntuación mayor que la indicada por el parámetro ``min_score`` :param objects: lista de objetos. :param min_score: puntuación mínima (incluída) que deben tener los obj...
8bb985c680a5ac66bda7214a81a3958edef39cf9
60,572
from datetime import datetime def portfoliodashboard(): """ Displays a dashboard of the portfolio based on portfolio name Input: Header: portfolioName Output: Template Params: title='optiondecision', returnSinceInception=returnSinceInception ...
a312eb5a45b62c07ea2bc5f34b6d0d91948bd9a8
60,573
def flip_allele(allele_seq): """ For alleles (e.g. ['A','G']) on REV strand, return the alternate representation (e.g. ['T','C']) on FWD strand. """ complement = [__ALTERNATE_NUCLEOBASE[x] for x in allele_seq] if isinstance(allele_seq, str): return ''.join(complement) else: retu...
66a8f62dfe2be403ecd2ff4916dd37afd44f5ed0
60,574
from typing import List from typing import Dict from typing import Tuple def __perform_dependency_updates(task_suggestions: List[TaskParallelismInfo], in_dep_updates: Dict[TaskParallelismInfo, List[Tuple[str, bool]]], out_dep_updates: Dict[TaskParallel...
7411c8526b240286ad355aca6bfc5cbff43465ec
60,575
from typing import List def team_direct_members(team: Team) -> List[str]: """Return the list of explicit members of a team.""" return team["members"] if _has_members(team) else []
c663286266834b2adecda63418107c563927f436
60,576
def validate_uwsgi(): """Each django project should have unique uwsgi port""" ports = Project.objects.filter( type='DJ').values_list('uwsgi_port', flat=True) if len(ports) != len(set(ports)): return ['Each django project should have unique uwsgi port!'] return []
fb4d18688247a28782aa70802402fe062b5ea98d
60,577
def synset(name_synsets): """ This function return the synonym set (synset) given the name of synset (i.e. 'dog.n.01', 'chase.v.01'). :param str name_synsets: name of the sysset :return: :class:`Synset` of the given name :rtype: :class:`Synset` :Example: ...
c2f0d969b1e1380aba4561151363d1debb46836f
60,578
def dataset_from_tfrecord(tfrecord_path): """ construct a data set from a tfrecord the tfrecord should be converted from a movie by movie2tfrecord() :param tfrecord_path:path to the tfrecord,can be string,string list or string Tensor :return:a tf.data.Dataset """ dataset = tf.data.TFRecordDa...
163135566f7e3bc02508a19d02840fbf1b72aab6
60,579
def CreateIcoSphere(sphere, subdivisions, multiple=False): """ Constructs a icospherical mesh. A mesh icosphere differs from a standard UV mesh sphere in that it's vertices are evenly distributed. A mesh icosphere starts from an icosahedron (a regular polyhedron with 20 equilateral triangles). It is...
36827755e9de8269399d3be798c40bd90f8e485d
60,580
from typing import Dict def count_sample_token(sample): """ Count sample tokens Args: sample: a piece of samples Returns: - total token numbers """ if isinstance(sample, str): return len(SPACE_NORMALIZER.split(sample)) elif isinstance(sample, list): return...
061f516045a1f18d35df7f28fdf5b90c54cb678c
60,581
import sys def get_server_cert(response, send_cbt=False): """ Get the certificate at the request_url and return it as a hash. Will get the raw socket from the original response from the server. This socket is then checked if it is an SSL socket and then used to get the hash of the certificate. The...
20421dfec83c33091b9fbf32c71a0c5aa8e9a9f0
60,582
import io import struct def PNGEncode(data): """Encode arbitrary data into a PNG file.""" if not type(data) is bytes: raise TypeError('data not of type \'bytes\'') png = io.BytesIO() png.write(PNG_HEADER) # IHDR IHDR = struct.pack(CHUNK_HEADER, struct.calcsize(IHDR_CHUNK), ord('I'), ...
8147627457096eabb724929b2fb629264ec1ed42
60,583
def symbol_w_path_to_telnet(self): """symbol w path to Telnet.""" self.symb = Symbol('telnetlib.Telnet') return self.symb
96f0b133c9d8a3528bb58364c78247208f168ce0
60,584
import json import traceback def websocketchart(request): """ 首页图表websocket :param request: :return: """ try: if request.is_websocket(): set_bigscreen_chart.delay() while True: try: chart_con = get_redis_connection('chart') ...
0330116b5d984b0be52fc7e5e1ed9e6b842f64fd
60,585
import csv import numpy def parse_file(file): """ parses out a csv file into numpy array by column (data), the dimension meta data(dimensions), and sets attributes (attributes) :param file: csv file to be parsed :returns: attributes, dimensions, data """ def isfloat(value): try: ...
d26843cdbb2b9a0fbccf5420f1d54ffefc7ed65e
60,586
def create_tables(client, project_id, fq_table_names, exists_ok=False, fields=None): """ Create an empty table(s) in a project. Relies on a list of fully qualified table names. This is a list of strings formatted as 'project-id.da...
17fc8cb62e704320777ad0543bb6dbe9a52e3d17
60,587
def get_hover_data(df): """ Creates and formats the hover string over the map data points :param df: Pandas dataframe :return: list: A string of dataframe row information formatted for hover. """ details_labels = ["needothers","detailmed", "detailrescue"] hover_string_list = [] for index...
cab8f2a08a3b16e254c8ebfa76196fcdcff06170
60,588
import ast def parse_code(text: str, locs: dict) -> _Result: """Parse given text and decide should it be evaluated as Python code""" result = _Result() # noinspection PyProtectedMember text = app.api._apply_code_transformers(text) try: root = ast.parse(text, '', 'exec') except (Synta...
0d355b0a7ea9e417962dd4f95549cf7120481ac4
60,589
def fcLayer(x, inputD, outputD, reluFlag, name): """fully-connect""" with tf.variable_scope(name) as scope: w = tf.get_variable("w", shape = [inputD, outputD], dtype = "float") b = tf.get_variable("b", [outputD], dtype = "float") out = tf.nn.xw_plus_b(x, w, b, name = scope.name) ...
6a00319be71a40ee68965b240689544d44efb51a
60,590
import json def create_site(api, site): """Post a new site to the API and create it's applicable reference observations. Parameters ---------- api : io.APISession An APISession with a valid JWT for accessing the Reference Data user. site : dict Dictionary describing the site t...
5e33594eda9a6744a9e0d5bd475ad5e1d372b2aa
60,591
def get_link_dicegrimorium(): """ Funtion that returns all the links where to download the sample :return: list of links """ bs = get_page('https://dicegrimorium.com/free-rpg-map-library/') try: content_images = bs.find_all('figure', {'class': 'wp-block-image size-large'}) links_...
300dcd714f3d4ed9f53d79af85ba85150f852092
60,592
from unittest.mock import Mock def editor_bot(qtbot): """ Set up EditorStack with CodeEditors containing some Python code. The cursor is at the empty line below the code. """ editorstack = EditorStack(None, []) editorstack.set_find_widget(Mock()) editorstack.set_io_actions(Mock(), Mock(), ...
3273c2aa976ee114000139174dbfab2b32444ca5
60,593
def update_restaurant(request, id): """ Update restaurant data page. Roure for 'management/r/<int:id>'. """ query = Restaurant.objects.filter(id=id).first() if request.method == "POST": form = CreateRestaurant(request.POST, request.FILES, instance=query) if form.is_valid() and re...
ae2ea0785743888b53cb815d58fd2efa98a318bd
60,594
def format_seconds(duration): """ Utility for converting time to a readable format @param duration : time in seconds and miliseconds @return time in format day,hour, min,sec """ return stats_utils.format_seconds(duration)
ba5b7b8e59b5637feb7cac874aae54c1dc1b0331
60,595
def get_fundamental_matrix(full_mat1, full_mat2, camera_center1=None, pinv_full_mat1=None, batch_shape=None, dev_str=None): """ Compute fundamental matrix :math:`\mathbf{F}\in\mathbb{R}^{3×3}` between two cameras, given their extrinsic matrices :math:`\mathbf{E}_1\in\mathbb{R}^{3×...
0b70d6c4da50cffbd5c0ebdb57a8c6c3d3a8d243
60,596
import os def fixWorkingDirForJEM( filename ): """It prefixes the provided filename with JEM's working directory, if available, only if filename is NOT an absolute path (in which case the user truly knows where they want to store it). """ try: JEM_getMainFilePath # check if function ...
01353975ccd3becd1a47794b3b579b32514c37c9
60,597
def login(user, passwd): """Return True is user/passwd pair matches""" try: db_passwd = user_passwd(user) except KeyError: return False passwd = encrypt_passwd(passwd) return passwd == db_passwd
e9a238f041a5889c3c570749cb1ff00e15489e70
60,598
def join_with_oxford_comma(template, items, separator=','): """Joins template with oxford comma rule""" return template.format(f'{separator} '.join(items))
ef6f8fa3eaea899db36f5ca21b8e2771550d2ca0
60,599