content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def PublicObject_IsRegistrationEnabled(): """PublicObject_IsRegistrationEnabled() -> bool""" return _DataModel.PublicObject_IsRegistrationEnabled()
c493cd141375938a5c78f9ff780a46ac7dd0ba16
47,200
def element_triple_cross(A, B, C): """Return element-wise triple cross product of three 3D arr in Cartesian""" return ( B * (element_dot(A, C))[:, :, np.newaxis] - C * (element_dot(A, B))[:, :, np.newaxis] )
a66d2a264bf6e6d5035096ada8d745ca1a983a82
47,201
import os def get_anatomical(): """ Get nltools default anatomical image. """ return nib.load(os.path.join(get_resource_path(),'MNI152_T1_2mm.nii.gz'))
3feb0e772ec71628701c66fcc39e58fbb6217ac8
47,202
import random def dict_sample(d, cutoff=-1): """ Sample a key from a dictionary using the values as probabilities (unnormalized) """ if cutoff==-1: cutoff = random() normalizer = float(sum(d.values())) current = 0 for i in d: assert(d[i] > 0) current += float(d[i])...
7d209b8c9ed35c3bccde5cbfdd6e2720e7e8fc78
47,203
def new_options(lights: list[int], exclude: list[int]) -> dict: """Create a standard options object.""" return {CONF_LIGHTS: lights, CONF_EXCLUDE: exclude}
e42c90463e3f3bf66034b32e64056ab8ec066ffa
47,204
import os import aiida.common from aiida.common import aiidalogger from aiida.orm import Group from aiida.common.exceptions import UniquenessError, NotExistent from aiida.backends.utils import get_automatic_user from aiida.orm.querybuilder import QueryBuilder def upload_upf_family(folder, group_name, group_descriptio...
7968495cc6553fcb50dda013b4beb30a96fc9395
47,205
from typing import List from typing import Optional def from_list(leaves: List[hash.Hash]) -> Optional[MerkleTree]: """Create Merkle tree from one or more nodes.""" if not leaves: return None head, tail = leaves[0], leaves[1:] t = from_singleton(head) for leaf in tail: t.insert(le...
874071d7d578e4de74e24402cc90e1791469f0ef
47,206
def get_instance_availability_zone(context, instance): """Return availability zone of specified instance.""" host = instance.host if 'host' in instance else None if not host: # Likely hasn't reached a viable compute node yet so give back the # desired availability_zone in the instance record...
82c194a192b899dfd0c20067539a83b894cd0519
47,207
import json from datetime import datetime def start_collector(): """Endpoint for starting the collector. Route command to CollectorHandler object.""" run_id = None try: data = request.get_json() start_delta = data['start'] stop_delta = data['stop'] interval = data['interva...
363e9e0b5577909a773732b1b48536240198b247
47,208
from typing import Sequence def _distribute_conversion_values( data_consent: pd.DataFrame, conversion_column: str, non_consent_conversion_values: Sequence[float], weighted_conversion_values: Sequence[np.ndarray], neighbors_index: Sequence[np.ndarray], neighbors_distance: Sequence[np.ndarray], ...
27422ae951c88a0f9d60a1e6ba389d74eeb289ca
47,209
def _get_default_frame(instance, shared_tags): """Extracts a metadata from volumetric enhanced instance, drops heavy tags.""" delete_tags(instance, EXCLUDE_TAGS.keys()) for tag in shared_tags: instance.add(tag) return instance
55a4cf9b81fffe46577862af9f4db17fce6b177e
47,210
import stat def download_sst(path, url): """" Download from `url` the zip file corresponding to the Stanford Sentiment Treebank and expand the resulting files into the directory `path` (Note: if the files are already present, the download is not actually run). Arguments --------- ...
7378136402cbb2219f718f8aeeafcd3dc086a139
47,211
def load_csv_to_numpy(dir: str): """ Module to load csv files. Args: dir: """ csv = np.genfromtxt(dir, delimiter=',') csv = csv[1:len(csv), 2:5].astype('uint16') return csv
9b2053066f5d311dd6a8a51b867326d922025fdf
47,212
def comp_cc(x1, x2, maxTimeLag, binSize, numBin): """Compute cross- or auto-correlation from binned data (without normalization). Uses matrix computations to speed up, preferred when multiple processors are available. Parameters ----------- x1, x2 : nd array time-series from binned data (nu...
eb6a6c709270eb628a02ab4f3fea8d4563fa7954
47,213
import tqdm def export_to_obj_file3D(polys, fname=None, scale=1, single_mesh=True, uv_map=False, name="poly"): """ exports 3D mesh result to obj file format """ try: dist = polys["dist"] points = polys["points"] rays_vertices = polys["rays_vertices"] rays_faces = polys["rays_f...
b639353624a677674b367392358ed0db3e73fefb
47,214
def get_objects_from_canvas_by_type(canvas, typename): """ Read objects in canvas and filter by typename :param canvas: canvas :type canvas: TCanvas :param typename: type of object to be filtered :type typename: str :return: objects of type typename in canvas :rtype: list[typename] "...
f0c0ae8813299ce7c337e9fab30adda2b360aa85
47,215
def get_chain_hash(contract, s, u_i, s_i, a, b, bytes_30, dyn_bytes, bar_uint, arr) -> bytes: """Uses the contract to create and hash a Foo struct with the given parameters.""" result = contract.functions.hashFooStructFromParams(s, u_i, s_i, a, b, bytes_30, dyn_bytes, bar_uint, arr).call() return result
2faeb03eff5ee1a4e564a50f8bff78fb99cdd169
47,216
import os import sqlite3 import calendar def update_plot_hover(ser, year, month, hoverdict): """ Update the history plot, as function of: * selected year in year-slider * selected month in month-slider * selected day in hist-slider In case of None use Current year as default year In ...
4144675ed4edd3d4e3c8955aee821735c186bb5a
47,217
def cluster_script(amoptd, python_path="ccp4-python"): """Create the script for ensembling on a cluster Parameters ---------- amoptd : dict An AMPLE option dictionary python_path : str, optional The path to the CCP4 python executable Returns ------- str The path to...
56a40a31f79ab12478c22542837d9606d29022d2
47,218
def build_hooks(model_configs, distributed_mode=False, is_chief=True): """ Builds training hooks. Args: model_configs: A dictionary of all configurations. distributed_mode: Whether is running under a distributed setting. is_chief: Whether this is the chief process. Returns: A list ...
916f84e9b02f9b22618ec55cbd7cf6e9beb46582
47,219
def attribute_vertex_perimeter(graph, edge_length=None): """ Vertex perimeter of the given graph. The perimeter of a vertex is defined as the sum of the length of out-edges of the vertex. If the input graph has an attribute value `no_border_vertex_out_degree`, then each vertex perimeter is assumed to b...
f8b0b9f3cfb4e060d48c1d6291ab75898f2b2af8
47,220
def get_status(dev, recipient, index = 0): """ Get status of the recipient Args: dev - pyusb device recipient - CTRL_RECIPIENT_DEVICE/CTRL_RECIPIENT_INTERFACE/CTRL_RECIPIENT_ENDPOINT index - 0 if recipient is device, interface index if recipient is interface, endpoint index if recipient...
5f05c9235bd180de5528fcfaf64e84087fdf19cd
47,221
from typing import Optional def map_ttf_to_shx(ttf: str) -> Optional[str]: """Map TTF file names to SHX font names. e.g. "txt_____.ttf" -> "TXT" """ return TTF_TO_SHX.get(ttf.lower())
cbb482f6f140c6022e64b358986fa0276be3027b
47,222
from typing import Optional import os def load_kinetics_database(libraries: Optional[list] = None): """ A helper function to load thermo database given libraries used Args: libraries (Optional[list]): A list of libraries to be imported. All libraies will be imp...
1294e1757d384ed2e491a9e18e5ba1d872e63455
47,223
from typing import Collection def edit_beatmap_comment(request, collection_id, beatmap_entry_id): """View for edit beatmap comment in BeatmapEntry""" collection = get_object_or_404(Collection, id=collection_id) beatmap_entry = get_object_or_404(BeatmapEntry, id=beatmap_entry_id, collection=collection) ...
2d1fd8fc1310304aa17d51823ba5c9071679a282
47,224
import os def call_languages(MODE: str, PROCESS_MODE: str, TIMES: int) -> dict[str: float]: """Function that calls the languages and captures the output(version and execution time) and gets the compile time with the GNU Time command. Args: MODE (str): The mode of the program (fast || slow). P...
fd203b212df213f005d5eb3b19edfe85e4cf1fd6
47,225
def oct2text(oct_text): """ Takes in a string oct_text, returns the decoded plain text.""" #Raise exception if there are no spaces in the text if not " " in oct_text and len(oct_text)>3: raise ValueError(noSpaceError.format("oct_text")) oct_text = oct_text.strip() #Converts the oct to text plain_string = ''...
985590fa863bdc7ef648246e150714f2b7d9adef
47,226
def tanh(z): """Hyperbolic tangent function... Args: z (np.array) Returns: f(z) = 2.0 / (1.0 + np.exp(-2.0 * z)) - 1.0 (np.array) """ return 2.0 / (1.0 + np.exp(-2.0 * z)) - 1.0
a87b9a4b04500b0eb1f2ead3ff8fa68977530c7d
47,227
import _warnings def from_qmi_response(problem, response, embedding_context=None, warnings=None, params=None, sampleset=None): """Construct problem data for visualization based on the low-level sampling problem definition and the low-level response. Args: problem ((list/dict...
63b0e957fbc4fb4f291e43369136515566ad3944
47,228
import os def read(files, v2i, r2i, m, U): """ Read data from files Arguments files: list of files (train, test, valid, aux splits) v2i: vertex-to-index map r2i: relation-to-index map m: maximum size of hyperedge U: set of unseen entities Returns inc: the incidence struct...
6263c6d674f3c43acd00b696aef9b634b9726a30
47,229
def graph_search_for_vis(problem): """Search through the successors of a problem to find a goal. The argument frontier should be an empty queue. If two paths reach a state, only use the first one.""" # we use these two variables at the time of visualisations iterations = 0 all_node_colors = [] ...
ad09cd644d7c8661069768dfbd928f7b98ee0d03
47,230
def api_runs(resource_id, run_id=None, content_type='json'): """ Get Runs (History of results) for Resource. """ if run_id: runs = [views.get_run_by_id(run_id)] else: runs = views.get_run_by_resource_id(resource_id) run_arr = [] for run in runs: run_dict = { ...
d6311528c3f9bbf82042313659d1e4776a3fc8da
47,231
def export_document_to_mstr(connection, document_id, instance_id, body, error_msg=None): """Export a specific document in a specific project to an .mstr file. Args: connection: MicroStrategy REST API connection object document_id (string): Document ID instanc...
0ec41f48022d7f5044b91dfa5fba8bafef1df0c7
47,232
import argparse def base_parser(): """Shared arguments for training and evaluation.""" parser = argparse.ArgumentParser() parser.add_argument( '--input-filenames', required=True, nargs='+', type=gcs_file ) parser.add_argument( '--sentence-length', ty...
599d025a507025c6a54cf078ca61112edc9840f1
47,233
def generate(row): """Get china: country, province, city. :param str row: The result of row parsed from qqwry :return: A tuple. """ candicates = Province.china for (cn, province) in candicates: if province in row: _, city = row.split(province) return cn, provi...
878eb7beca9eaa1f888a5fc0f3b0afa01a94c094
47,234
import signal def freqz_cas(sos,w): """ Cascade frequency response Mark Wickert October 2016 """ Ns,Mcol = sos.shape w,Hcas = signal.freqz(sos[0,:3],sos[0,3:],w) for k in range(1,Ns): w,Htemp = signal.freqz(sos[k,:3],sos[k,3:],w) Hcas *= Htemp return w, Hcas
1565a569d4d1e177eb49aa44673ac539062857dc
47,235
def import_dotted_path(path): """ Takes a dotted path to a member name in a module, and returns the member after importing it. """ # stolen from Mezzanine (mezzanine.utils.importing.import_dotted_path) try: module_path, member_name = path.rsplit(".", 1) module = import_module(mod...
677fc7095364bede668ea134997099ac02088823
47,236
import os import glob def getBandNoFilter(folderPath): """ getBand is used for getting image exported from gee. Parameters ---------- [folderPath]: variable read by rasterio Returns ------- [b1,b2]: the target layer """ # read images in the folder searchCriteria = "*.t...
418b97864c5470d88db66262641233d9ccf3d69a
47,237
import binascii def sdm_info(): """ SUN decrypting/validating endpoint. """ enc_picc_data = request.args.get(ENC_PICC_DATA_PARAM) enc_file_data = request.args.get(ENC_FILE_DATA_PARAM) sdmmac = request.args.get(SDMMAC_PARAM) if not enc_picc_data or not sdmmac: raise BadRequest("Par...
11b58fa8da785f5a0ccb392f2dd17b222d4a0066
47,238
import types def get_module_functions(module): """ Helper function to get the functions of an imported module as a dictionary. Args: module: python module Returns: dict: module functions mapping { "func1_name": func1, "func2_name": func2,... }...
d784e7d2d085c5f4f015a6107f9106653fe163ef
47,239
def evaluate_posterior_predictive(samples: xr.Dataset, test: xr.Dataset) -> np.ndarray: """ Computes the predictive likelihood of all the test items w.r.t. each sample. See the class documentation for the `samples` and `test` parameters. :returns: a numpy array of the same size as the sample dimension. ...
23062158b92fb7358c65ae4d36094d9c7c3ecd7f
47,240
from typing import Any def get_logger() -> Any: """ An entry point of the plug-in and return the usage logger. """ return KoalasUsageLogger()
4299dcb722cc06bab360579f379a0a1f487a2100
47,241
def circle_image(shape, center, radii, intensities): """ Creates an image with circle or thickness 2 """ im = np.zeros(shape=shape, dtype=np.float) xx, yy = np.ogrid[0 : shape[0], 0 : shape[1]] xx, yy = xx - center[0], yy - center[1] for radius, intensity in zip(radii, intensities): rr = np....
0441b6f1b06481889f8d8333bc47a68463e969ad
47,242
import time def upsample(prob_maps_multiple_images, output_shape): """ Function for performing upsamping of probability maps :param prob_maps: Probability maps for each class for each resized image :param output_shape: Desired shape to upsample to (should be dimensions of original image) :return: ...
fcea1a68304d74542afc937472d531ddb2a73aa3
47,243
def closest_dataframe_from_origins_destinations(origins, origin_id_fld, destinations, dest_id_fld, gis=None, network_dataset=None, destination_count=4): """ Create a closest destination dataframe using origin and destination Spatially Enabled Dataframes. :para...
98f43f8a2354afdba9d716cb484a7fef403c7728
47,244
def naive(string: str): """ Recognize POS in a string using Regex. Parameters ---------- string: str Returns ------- string : tokenized string with POS related """ string = string.lower() results = [] for i in string.split(): results.append(_naive_POS_word(i)) ...
ec436805a5d9803599ea6f1152c3e9a5cb3d095b
47,245
def main(): """ Runs the main program. """ prob1a() return GOOD_RET
142127860a55edc204dd98c02d467d8df56259d1
47,246
def init_tenses(): """initialises the tenses dict.""" tenses = {} for t in VerbTense: tenses[t] = {} for d in VerbDependency: tenses[t][d] = {} for p in VerbPerson: tenses[t][d][p] = [] return tenses
97cec934b2d971aebd52b6c9337eb2dcff0dde62
47,247
def prim(w_graph_d): """Prim's algorithm for minimum spanning tree in "undirected weighted" graph, G(V, E). Time complexity for : O((|V|+|E|)log(|V|)). Space complexity: O(|V|). """ min_pq = MinBinaryHeapAttribute() key_d = {v: float('inf') for v in w_graph_d.keys()} previous_d = {v: ...
752e3cd5768a176ab1322231e3fd4537402dccdc
47,248
def get_row_headers(data): """ Take a dictionary and walk the dictionary identifying allthe unique row headers. """ headers = set() try: for key, value in data.iteritems(): try: iter(value) if not isinstance(value, basestring): ...
d21eecd1306a052faeb07d305e62f87086881509
47,249
import traceback def Compile(expr): """ Given an XPath expression as a string, returns an object that allows an evaluation engine to operate on the expression efficiently. This "compiled" expression object can be passed to the Evaluate function instead of a string, in order to shorten the amount o...
61e8695e21ce4f3a016a4bb8512a44f6f22a0ef5
47,250
import math def f1(myList): """Solves x = Sqrt((120-y)/8)""" return math.sqrt((120-myList[1])/8) #return 120-8*myList[0]**2
5d84417d52ec3b667862a3750f6d46f74964a586
47,251
from sys import path def get_pet_labels(image_dir): """ Creates a dictionary of pet labels (results_dic) based upon the filenames of the image files. These pet image labels are used to check the accuracy of the labels that are returned by the classifier function, since the filenames of the...
738a6322bb040e51ece0eeff8b6727cc4ea09861
47,252
def mfccf(num, s, Fs): """ 计算并返回信号s的mfcc参数及其一阶和二阶差分参数 :param num: :param s: :param Fs: :return: """ N = 512 # FFT数 Tf = 0.02 # 窗口的时长 n = int(Fs * Tf) # 每个窗口的长度 M = 24 # M为滤波器组数 l = len(s) Ts = 0.01 # 帧移时长 FrameStep = int(Fs * Ts) # 帧移 lifter = np.array([...
4c36d6cb4b248bd081410964f3c72105f06c3444
47,253
import os def checkout_working_copy(request, identifier): """ post: Checkout a working copy (database, file system) A stored data set without a working copy cannot to be edited or changed directly. It is required to checkout a working copy first. To checkout the information package use the f...
dd016d705fda3184bbd08b3e0e4ba20fdb0bc4d7
47,254
def mesh_reader(path): """Read a mesh in using pymeshlab. Parameters ---------- path : str or list of str Path to file, or list of paths. Returns ------- layer_data : list of tuples List of surfaces, one per file path. """ # handle both a string and a list of string...
296332e459837e6c77e0f28ff8a6c0d99bec172c
47,255
def get_git_string(): """ Return a string with information on the git version """ sha = get_git_hash() return "Git branch hash: " + sha
6bd78cb250f6a26b6ed1e79d4d42633efcad961d
47,256
def parse_args(): """Parse command line arguments""" parser = common_exe.cli_parser() parser.add_argument("file", help="Obfuscated file to grab the data from") opts = parser.parse_args() if opts.debug_log: opts.debug = True return opts
4b0a816a465beb68ff5a2597f27e7201f3f90a38
47,257
from typing import List from pathlib import Path def estimate_dmg_size(app_bundles: List[Path]) -> int: """ Estimate size of DMG to hold requested app bundles The size is based on actual size of all files in all bundles plus some space to compensate for different size-on-disk plus some space to hold ...
59261685ecece9128ace2430398e95e9c2ddc985
47,258
import torch from typing import Tuple def _initialize_full_precision( model: torch.nn.Module, optimizer: torch.optim.Optimizer ) -> Tuple[torch.nn.Module, torch.optim.Optimizer]: """ Initialize full precision training - leaves model and optimizer untouched. Flattens fp-32 parameters and gradients. ...
e989edbeccf9bf68acfd68bd8e645fc536091f47
47,259
def serialize(obj: Serializable) -> JSON: """Serialize object to JSON. Args: obj: An object to serialize. Returns: Its JSON representation. """ return _serializers[type(obj)](obj)
c8231dccbfe7bf4ea29636c1c4b0a143a7de9b9d
47,260
def scale_fill_brewer(type=None, palette=None, direction=None, name=None, breaks=None, labels=None, limits=None, na_value=None, guide=None, trans=None): """ Sequential, diverging and qualitative color scales from colorbrewer.org for fill aesthetic. Color schemes provided are particular...
093a4f9ae1634f3f1851d96308d81ef391a08ba0
47,261
def resize_image(image, size=140): """Get squared-resized image """ BLACK = [0, 0, 0] h = image.shape[0] w = image.shape[1] if w < h: border = h-w image = cv2.copyMakeBorder(image, 0, 0, border, 0, cv2.BORDER_CONSTANT, value=BLACK) else: border = w-h image = c...
e9dfcddcfa644bc2dc39651071db1bb6c48d75a8
47,262
from typing import OrderedDict def get_families(cxn): """Extract the families from the taxonomy table.""" sql = """SELECT DISTINCT family FROM taxonomy;""" families = pd.read_sql(sql, cxn).set_index('family') return families.to_dict(orient='index', into=OrderedDict)
3e53d95fd9b9667dd975b1ac2d875aea1c3551ab
47,263
def _filter_by_variance(frame, threshold=0.005): """Removes from frame any columns with a relative variance beneath the given threshold. """ # first, for each column X, compute relative variance as # var((X-min(X))/(max(X)-min(X))) numerators = frame.subtract(frame.min(axis='index'), axis='colum...
f4225fe41adab6f5f1a0189f9eaeae071109a5ee
47,264
def test(p, parameters): """ Runs the quality control check on profile p and returns a numpy array of quality control decisions with False where the data value has passed the check and True where it failed. """ # Get temperature values from the profile. t = p.t() # Make the quality...
9854ddaf5979be6923d09c7293e757c348647fe5
47,265
def getDate(signature): """Function that returns the date present on the signature.""" return getToken(signature, "Date: ", '\x00')
07a738bce3d546f5950b8adda5f30ee6a2662d6a
47,266
import functools def monadic(f): """Decorate a unary function to return a Maybe monad.""" @functools.wraps(f) def wrapped(a): try: b = f(a) except Exception: b = None if b is None: return Nothing() else: return Just(b) ret...
461565ad0edfb5482aacdcaea13543592281f021
47,267
def jacobian(variables, functions): """Returns the Jacobian matrix containing the first derivative of each input function with respect to each input variable""" derivatives = [] try: # Case where functions is a list of AD objects if type(functions) is list: if l...
21cba3592be16c9883ef1a1eb6fd9a7307ac566f
47,268
import sys def parse(filename): """Parse a wheel filename, sdist filename, or setup.py file and return the attributes. Args: filename (str): Filename that ends in .whl, sdist filename that ends with .tar.gz, or setup.py filename. Returns: attrs (dict): Dictionary of attributes "name", "v...
6749e9870ec9ceb69136fb9449c21d1671226675
47,269
from functools import reduce def kron_diag(diags): """Returns diagonal of kronecker product from list of diagonals. """ return reduce(flattened_outer, diags)
e8a5f6ad0c9d02369d31493284cb3a7763e466e4
47,270
def get_nodes_with_services(G): """ Based on the render of app_operator.py for visual inspection :param sim: :return: """ HwReqs = nx.get_node_attributes(G, name="HwReqs") currentOccupation = {} for n in G.nodes: currentOccupation[n] = np.zeros(int(HwReqs[n])).astype(int) ...
a67d04470da4f643e057caed1ad51635828e73f6
47,271
def GetXML(archiveUID=None,table=None): """ :param archiveUID: Archive UID :param table: Table :return: XML String """ sqlXML = "select XMLType.GetClobVal(xml) from ALMA.XXXXYYY where archive_uid='ZZZZCCCC' " sqlXML = sqlXML.replace('XXXXYYY',tables[table]).replace('ZZZZCCCC',archiveUID) ...
4038bab11069a6c15b2a2605c6b1d9158aa6dc75
47,272
def f_to_R(f_df, R_dict): """Calculates robustness from performance values. Uses a set of performance values, `f`, determined from simulations across multiple decision alternatives, `l`, different scenarios, `s`, and calculates robustness, `R`, using a variety of given robustness metrics. Para...
3d11f49f5beec7efa8cb2d1a652bdb6efc99ec3e
47,273
def is_not_csv_file(filename): """Retun an indication if the file entered is the clusterserviceversion (csv) file """ return not filename.endswith('clusterserviceversion.yaml')
3afcecfee95f300b9a5e6128f33a58dcdfc2c443
47,274
from typing import Optional def get_key(app_id: Optional[str] = None, developer_id: Optional[str] = None, key_id: Optional[str] = None, organization_id: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetKeyResult: """ Gets details...
6183059ebca2fd1584bd39f027dc1d747db5d462
47,275
def _shellBucklingOneSection(h, r1, r2, t, gamma_b, sigma_z, sigma_t, tau_zt, E, sigma_y): """ Estimate shell buckling for one tapered cylindrical shell section. Arguments: h - height of conical section r1 - radius at bottom r2 - radius at top t - shell thickness E - modulus of elastici...
b13d1f5d9127cf31712429124e359a8adf78dbf1
47,276
def cc_score_fct(i): """ CC (Chamberlin-Courant) marginal score function. This is the additional (marginal) score from a voter for the `i`-th approved candidate in the committee. Parameters ---------- i : int We are calculating the score for the `i`-th approved candidate in...
2a0cfab120bae500d023d548d06be68c4699fc22
47,277
def create_plan(response): """Create plan""" # if user is logged in if response.user.is_authenticated: if response.method == 'POST': form = CreateNewPlan(response.POST) # chcek form validation if form.is_valid(): # clean data t = f...
572d3fb4e638c624007abc2f82d56ddfb0161182
47,278
from typing import cast from datetime import datetime def sun( hass: HomeAssistant, before: str | None = None, after: str | None = None, before_offset: timedelta | None = None, after_offset: timedelta | None = None, ) -> bool: """Test if current time matches sun requirements.""" utcnow = d...
2e295e233fbe71c5383b912d1527ebf9d98c3fba
47,279
import torch def load_snapshot(model_path): """ Load snapshot :param model_path: path to snapshot :type model_path: str :return: built state :rtype: dict """ state = torch.load(model_path) return state
bdeba078302b8c8c6ac39f156877ef58e91341ec
47,280
import os def find_last_built_pipeline(): """Finds the pipeline config file for the last built pipeline. The last built pipeline is the pipeline whose generated configuration directory has the most recent timestamp. Returns: the path to the pipline config file for the last built pipeline, or...
e6f3664fe86a2eda5ba037e14d60677723a83fb0
47,281
def import_secondary_context_membership(): """Add docstring.""" log.info('Read in secondary context membership') SecondaryContextMembership = pd.read_csv(inputpath + 'SecondaryContextMembership.csv') return SecondaryContextMembership
6e755af43c9022f2137c0e934dc02f688735ea51
47,282
from typing import List from typing import Optional def _parse_tasks(tasks: List, file_name: str, collections: Optional[List] = None) -> List: """ Parse Ansible tasks and prepare them for scanning :param tasks: List of Ansible task dicts :param file_name: Name of the original file with tasks :para...
4b3358b110cdef8144979cd64b5c39b1e9010655
47,283
def _get_compiler_args( compiler_lang, flags, options, **_kwargs): """ Return compiler args when compiling for ocaml. """ _ignore = compiler_lang args = [] # The OCaml compiler relies on the HS2 compiler to parse .thrift sources to JSON args.append("-c") ...
3818896ca3dd099d1ba806cd1b80a53eb183b262
47,284
import os import random def create_dataset(dataset_folder,dataset_name,val_size,gt,horizon,delim="\t",train=True,eval=False,verbose=False): """ gt:obs length horizon:pred length """ if train==True: #训练集 datasets_list = os.listdir(os.path.join(dataset_folder,dataset_...
3d2f7f23bb9abee05ac270bfc43f5c0b466a709a
47,285
import os import re import hashlib def which_set( filename, validation_percentage=VALIDATION_PERCENTAGE, testing_percentage=TESTING_PERCENTAGE): """Determines which data partition the file should belong to. This function is from the dataset github page: https://github.com/tensorfl...
7d04d2f41aa884310fe42db2024c12295ba7bab2
47,286
def view_vote_entities_map_proposal(self, request): """ A static link to the map of the proposal. """ ballot = getattr(self, 'proposal', None) if ballot: return redirect(request.link(ballot, name='entities-map')) raise HTTPNotFound()
42acf262defad98aee6ebd6177fcf644669e753a
47,287
def _format_artifact(tuple, flink_version, scala_version, classifier = None, neverlink = False): """Formats the given artifact tuple. """ group = tuple[0] artifact_id = _replace_scala_artifact_version(tuple[1], scala_version) version = None if group == _FLINK_GROUP: version = flink_versi...
ab935e79edc217eaefb4a48e4ae236e098adf380
47,288
def create_input_list(pdb_list_fname): """ create a list of tuples (pdb_id, chain) from a text file """ pdb_list = [] with open(pdb_list_fname, 'r') as f: for record in f.read().splitlines(): pdb_id, chain = record[:-1], record[-1] # check PDB ID and chain are valid ...
d02588ec1d2ff55454782b337ac15cf9e6f67a80
47,289
def PreDataViewCtrl(*args, **kwargs): """PreDataViewCtrl() -> DataViewCtrl""" val = _dataview.new_PreDataViewCtrl(*args, **kwargs) return val
d522fee41438c7514b2c36b90f8b6c3498b770f2
47,290
def guess_industries(companies, return_prob=False, cutoff=ind_cutoff): """ The function guesses industries and probabilities based on company names. """ try: global _model _model = IndustryModel.load() if companies: return cur_model.predict(_model, companies, return_prob, cut...
ed1e883e26bce9013f08fcf552f6e831e1344fe4
47,291
def get_drawing(doc_id, drawing_num): """Summary Args: doc_id (str): Document identifier (e.g. patent number) drawing_num (str): Drawing number, e.g. "1" Returns: bytes: Image data """ key_prefix = _drawing_prefix(doc_id) key = f'{key_prefix}{drawing_num}.tif' tif_d...
83961a63569aecaa77e0ae3cb587a280e249ec1e
47,292
def _query_worrying_level(time_elapsed, state): """ Gives a "worriness" level to a query For instance, long times waiting for something to happen is bad Very long times sending is bad too Return a value between 0 and 1 rating the "worrying level" See http://dev.mysql.com/doc/refman/5.7/en/genera...
383e36c75d68a9e975d48efc6c68deeee446c987
47,293
def do_color(msg, style): """ print the message in color if it can be handled""" return msg if can_handle_color() else colorit(msg, style)
42ca6f1c883a678e6c9c34bad898a071f94b47a5
47,294
def sce2t_vector(k1, in11): """sce2t_vector(SpiceInt k1, ConstSpiceDouble * in11)""" return _cspyce0.sce2t_vector(k1, in11)
5696292aa1614427d6498216988e100f9416e13e
47,295
def cross_entropy_loss(pred,labels): """ Does an internal softmax before loss calculation. args: pred- batch,seq,input_size labels-batch,seq(has to be transformed before comparision with preds(line-133).) """ checkdatadim(pred,3) checkdatadim(labels,2) batch,seq,size=pred.sha...
13fc0bb5288940db30d4f83b1a92fd4eb6c43d54
47,296
import cartopy.crs as ccrs def latitude_from_cross_section(cross): """Calculate the latitude of points in a cross-section. Parameters ---------- cross : `xarray.DataArray` The input DataArray of a cross-section from which to obtain latitudes. Returns ------- latitude : `xarray.Da...
9c023cb21ae433884db7633601e75d977ed9e202
47,297
def dict_to_casl_rules(rules: dict): """ Given a dict where the keys are the subject and the values are the actions, return a list of dicts ready to be serialized as JSON :return: """ perms = [] for key, actions in rules.items(): perms.append({ 'subject': key, ...
5d0f3dfd610a1cd7deb7f09a668e291997419b2a
47,298
def svn_fs_paths_changed2(*args): """svn_fs_paths_changed2(svn_fs_root_t * root, apr_pool_t pool) -> svn_error_t""" return _fs.svn_fs_paths_changed2(*args)
202f24e3e7a8fdb4c0fafff9efa95cf58b5ecb6d
47,299