content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def offset_zero_by_one(feature): """Sets the start coordinate to 1 if it is actually 0. Required for the flanking to work properly in those cases. """ if feature.start == 0: feature.start += 1 return feature
3c8fb9754bde7b7efaa5d092e8239aeb099e26a4
200
def smilesToMolecule(smiles): """ Convert a SMILES string to a CDK Molecule object. Returns: the Molecule object """ mol = None try: smilesParser = cdk.smiles.SmilesParser(silentChemObjectBuilder) mol = smilesParser.parseSmiles(smiles) except cdk.exception.InvalidSmilesExcep...
9a50a21c77a5306de47b39d2290e3e6c04184acc
201
from typing import OrderedDict def build_pathmatcher(name, defaultServiceUrl): """ This builds and returns a full pathMatcher entry, for appending to an existing URL map. Parameters: name: The name of the pathMatcher. defaultServiceUrl: Denotes the URL requests should go to if none of the path pat...
e21a79d51b41bd393a8fa2e254c6db7cf61bd441
202
def gaussian1D_smoothing(input_array, sigma, window_size): """ Function to smooth input array using 1D gaussian smoothing Args: input_array (numpy.array): input array of values sigma (float): sigma value for gaussian smoothing wi...
1e7185e358c3dba77c584e072537c7c3b5d9ca4c
203
import re def add_whitespace(c_fn): """ Add two spaces between all tokens of a C function """ tok = re.compile(r'[a-zA-Z0-9_]+|\*|\(|\)|\,|\[|\]') return ' ' + ' '.join(tok.findall(c_fn)) + ' '
57d59a5956c3914fa01587b6262e7d4348d77446
204
def readFlow(fn): """ Read .flo file in Middlebury format""" with open(fn, 'rb') as f: magic = np.fromfile(f, np.float32, count=1) if 202021.25 != magic: print('Magic number incorrect. Invalid .flo file') return None else: w = np.fromfile(f, np.int32, ...
d9e5ab6f661d904755c0457827e3cfed87752f95
205
def plot_umap_list(adata, title, color_groups): """ Plots UMAPS based with different coloring groups :param adata: Adata Object containing a latent space embedding :param title: Figure title :param color_groups: Column name in adata.obs used for coloring the UMAP :return: """ try: ...
a5fc70fb507b575a4b8ab2b0a57bb01f55e390ff
206
import re import os def _filename(url, headers): """Given the URL and the HTTP headers received while fetching it, generate a reasonable name for the file. If no suitable name can be found, return None. (Either uses the Content-Disposition explicit filename or a filename from the URL.) """ fil...
84492ec86a704221cb029c4172a9b42faa075593
207
def MatrixCrossProduct(Mat1, Mat2): """ Returns the cross products of Mat1 and Mat2. :param: - Mat1 & Mat2 - Required : 5D matrix with shape (3,1,nz,ny,nx). :return: - Mat3 : 5D matrix with shape (3,1,nz,ny,nx). """ Mat3 = np.zeros_like(Mat1) Mat3[0] = ...
5789209c1fbd8bfacff3e48e844aa0454f94958d
208
import collections import json def partition_preds_by_scrape_type(verify_predictions, evidence_predictions, val_examples): """Partition predictions by which scrape_type they come from. The validation fold contains four sets of evidence: drqa, ...
137fdfb4bf1f837c087f597eedd4ce4229b33a02
209
def apply_delay_turbulence(signal, delay, fs): """Apply phase delay due to turbulence. :param signal: Signal :param delay: Delay :param fs: Sample frequency """ k_r = np.arange(0, len(signal), 1) # Create vector of indices k = k_r - delay * fs # Create vector ...
f5801b3888867b05c890e4dba8f64d0cd273f610
210
def binaryContext(): """Return the registered context for the binary functions. Return Value: Ctor() for the binary function context """ return bin_func_class
93ed6627d90e4dfb493b8b851c35b59d56fd558f
211
from pathlib import Path def validate_vm_file(file_name: Path, nx: int, ny: int, nz: int): """ Validates that a velocity model file has the correct size, and no 0 values in a sample of the layers :param file_name: A Path object representing the file to test :param nx, ny, nz: The size of the VM in gri...
0f0cd5a1bb13038ca0455770f4c240973775b891
212
import traceback def format_assignment_html(recording, debug=False): """Given a single recording, format it into an HTML file. Each recording will only have one student. Returns a {content: str, student: str, type: str, assignment: str} dict. """ try: files = format_files_list(recording...
474c9b3ec95f8b217fe413c2619fa37fb450d649
213
def compute_xlabel_confusion_matrix(y_true, y_pred, labels_train=None, labels_test=None, normalize=True, sample_weight=None): """Computes confusion matrix when the labels used to train the classifier are different than those of the test set. Args: y_true: Ground...
10f8e8767b98979d0d07dcb6ccfdddfaa8b78c1c
214
def generate_synthetic_data(n=50): #n is the number of generated random training points from normal distribution """Create two sets of points from bivariate normal distributions.""" points = np.concatenate((ss.norm(0,1).rvs((n,2)),ss.norm(1,1).rvs((n,2))), axis=0) #norm(mean, standard deviation) #'.rvs' Ran...
e63bc114a1b69dc841f439486fc0b455698a4529
215
def mask_array(array, idx, n_behind, n_ahead): """[summary] Args: array ([type]): [description] idx ([type]): [description] n_behind ([type]): [description] n_ahead ([type]): [description] Returns: [type]: [description] """ first = max(0, idx - n_behind) ...
04781f75bd1b0cae5b690759b5da475f59a43fe8
216
from typing import Set def get_nfs_acl(path: str, user: str) -> str: """ Retrieve the complete list of access control permissions assigned to a file or directory. """ raw = command(["/usr/bin/nfs4_getfacl", path], output=True).stdout.decode("utf-8") allowed: Set[str] = set() denied: Set[str] =...
bca401e9da9ddcb9419359024268362082c3f64b
217
def PolyMult(p1, p2, debug=False): """ Multiply two numbers in the GF(2^8) finite field defined See http://stackoverflow.com/questions/13202758/multiplying-two-polynomials For info """ binP2 = bin(p2)[2:].zfill(8) mult = 0 if p1 == 0 or p2 == 0: return 0 for i in range(8): ...
30e9f7b9d567ab93e27702d6db5813e8b650442a
218
from hdbscan import HDBSCAN def run_hdbscan(X_df, X_tsne, output_dir, transparent): """Cluster using density estimation Parameters ---------- X_df: DataFrame X_tsne: array-like, [n_samples, 2] output_dir: str, path transparent: bool Returns ------- clusterer: HDBSCAN object ...
5b5b89f792cbf5acc3ab3681e0ac8d9ea6ce1705
219
def check_min_sample_periods(X, time_column, min_sample_periods): """ Check if all periods contained in a dataframe for a certain time_column contain at least min_sample_periods examples. """ return (X[time_column].value_counts() >= min_sample_periods).prod()
074c196a169d65582dbb32cc57c86c82ce4cb9c9
220
def get_quest_stat(cards): # pylint: disable=R0912,R0915 """ Get quest statistics. """ res = {} encounter_sets = set() keywords = set() card_types = {} for card in cards: if card.get(lotr.CARD_KEYWORDS): keywords = keywords.union( lotr.extract_keywords(c...
33de1c65288a82c91dd3ee6f4e31c2ea54f938d8
221
def bind_type(python_value): """Return a Gibica type derived from a Python type.""" binding_table = {'bool': Bool, 'int': Int, 'float': Float} if python_value is None: return NoneType() python_type = type(python_value) gibica_type = binding_table.get(python_type.__name__) if gibica_t...
ff1ac8d907a90584694408b8e60996fb7be25eab
222
import traceback import requests def delete_server(hostname, instance_id): """ Deletes a server by hostname and instance_id. """ host = get_host_by_hostname(hostname) if not host or not instance_id: return None try: r = requests.delete("%s/servers/%i" % (host['uri'], instance_...
9456e45d49be61672b89427c93542374ff0359e2
223
def quote_ident(val): """ This method returns a new string replacing " with "", and adding a " at the start and end of the string. """ return '"' + val.replace('"', '""') + '"'
452058861fb5be138db3599755fbf3c6d715c0a8
224
def TFC_TDF(in_channels, num_layers, gr, kt, kf, f, bn_factor=16, bias=False): """ Wrapper Function: -> TDC_TIF in_channels: number of input channels num_layers: number of densely connected conv layers gr: growth rate kt: kernel size of the temporal axis. kf: kernel size of the freq. axis ...
b1d4aa007b40c920f4c985d102a4094821fbf228
225
import json def barplot_data(gene_values, gene_names, cluster_name, x_label, title=None): """ Converts data for top genes into a json for building the bar plot. Output should be formatted in a way that can be plugged into Plotly. Args: gene_values (list): list of tuples (gene_id, ...
67879df5d4918dddc8f46fd6fa975f3bf53de2b4
226
def logic_not(operand: ValueOrExpression) -> Expression: """ Constructs a logical negation expression. """ return Not(operators.NotOperator.NOT, ensure_expr(operand))
9b3755e00afc9aa8a843358ef83442614bda0feb
227
def webpage_attribute_getter(attr): """ Helper function for defining getters for web_page attributes, e.g. ``get_foo_enabled = webpage_attribute_getter("foo")`` returns a value of ``webpage.foo`` attribute. """ def _getter(self): return getattr(self.web_page, attr) return _getter
3626f8e2d8c6fb7fbb490dc72f796599cdbc874e
228
def diff_with_step(a:np.ndarray, step:int=1, **kwargs) -> np.ndarray: """ finished, checked, compute a[n+step] - a[n] for all valid n Parameters ---------- a: ndarray, the input data step: int, default 1, the step to compute the difference kwargs: dict, Returns ---...
8475ec66a983f32d4ed7c06348a8607d335dbdca
229
def rmse(y_true: np.ndarray, y_pred: np.ndarray): """ Returns the root mean squared error between y_true and y_pred. :param y_true: NumPy.ndarray with the ground truth values. :param y_pred: NumPy.ndarray with the ground predicted values. :return: root mean squared error (float). """ return...
42d08e8bfd218d1a9dc9702ca45417b6c502d4c5
230
def party_name_from_key(party_key): """returns the relevant party name""" relevant_parties = {0: 'Alternativet', 1: 'Dansk Folkeparti', 2: 'Det Konservative Folkeparti', 3: 'Enhedslisten - De Rød-Grønne', 4: 'Liberal...
86041235738017ae3dbd2a5042c5038c0a3ae786
231
import os def GetOutDirectory(): """Returns the Chromium build output directory. NOTE: This is determined in the following way: - From a previous call to SetOutputDirectory() - Otherwise, from the CHROMIUM_OUTPUT_DIR env variable, if it is defined. - Otherwise, from the current Chromium source direct...
57f48d9d34a82997e98c8a74e44f799e8f3a6736
232
def __imul__(self,n) : """Concatenate the bitstring to itself |n| times, bitreversed if n < 0""" if not isint(n) : raise TypeError("Can't multiply bitstring by non int"); if n <= 0 : if n : n = -n; l = self._l; for i in xrange(l//2) : self[i],self[l-1-i] = self[l-1-i],self[i]; ...
3305fd98899d0444aea91056712bae1fd4a6db2f
233
import os def update_cache(force=False, cache_file=None): """ Load a build cache, updating it if necessary. A cache is considered outdated if any of its inputs have changed. Arguments force -- Consider a cache outdated regardless of whether its inputs have been modified. """ ...
31fc3419e18fa08a124f5424db2753ef8513a310
234
from pyrado.environments.pysim.quanser_qube import QQubeSim def create_uniform_masses_lengths_randomizer_qq(frac_halfspan: float): """ Get a uniform randomizer that applies to all masses and lengths of the Quanser Qube according to a fraction of their nominal parameter values :param frac_halfspan: fr...
87fc94d17b3fab77b175139d2329c0d67611d402
235
def compress_table(tbl, condition, blen=None, storage=None, create='table', **kwargs): """Return selected rows of a table.""" # setup storage = _util.get_storage(storage) names, columns = _util.check_table_like(tbl) blen = _util.get_blen_table(tbl, blen) _util.check_equal_len...
eb675913da51b48fc6a663ddb858e70abee3f1ce
236
def validate_schedule(): """Helper routine to report issues with the schedule""" all_items = prefetch_schedule_items() errors = [] for validator, _type, msg in SCHEDULE_ITEM_VALIDATORS: for item in validator(all_items): errors.append('%s: %s' % (msg, item)) all_slots = prefetch_...
8f6d0f9670b25c22e4518b53327dffc4fa897a6e
237
from typing import Any from typing import Dict from typing import Union from typing import Callable from typing import Tuple def train_gridsearchcv_model(base_model: Any, X: np.array, y: np.array, cv_splitter, ...
7fe8677f985db7d3518c7b68e5005fde1dee91c6
238
def set_resolmatrix(nspec,nwave): """ Generate a Resolution Matrix Args: nspec: int nwave: int Returns: Rdata: np.array """ sigma = np.linspace(2,10,nwave*nspec) ndiag = 21 xx = np.linspace(-ndiag/2.0, +ndiag/2.0, ndiag) Rdata = np.zeros( (nspec, len(xx), nwave)...
49aac12441c1ef793fa2ded4c5ac031df7ce8049
239
def assembleR(X, W, fct): """ """ M = W * fct(X) return M
c792da453b981cc3974e32aa353124f5a5e9c46d
240
import logging def generate_dictionary_variable_types( dict_name, key_name, search_dict, indent_level=0 ): """Generate a dictionary from config with values from either function, variable, or static""" out_str = [] # Don't escape these: types_used = ["None", "True", "False", None, True, False] ...
82a7282bc999dcf049ff6fbe6329271577908775
241
import uuid def make_uuid(value): """Converts a value into a python uuid object.""" if isinstance(value, uuid.UUID): return value return uuid.UUID(value)
b65b5739151d84bedd39bc994441d1daa33d1b51
242
def create_config(config_data, aliases=False, prefix=False, multiple_displays=False, look_info=None, custom_output_info=None, custom_lut_dir=None): """ Create the *OCIO* config based on the configuration ...
c036094b3a8a3debc80d2e66141f8b95e51a41d0
243
import re from pathlib import Path import json def parse_json_with_comments(pathlike): """ Parse a JSON file after removing any comments. Comments can use either ``//`` for single-line comments or or ``/* ... */`` for multi-line comments. The input filepath can be a string or ``pathlib.Path``. ...
e79a461c210879d66b699fe49e84d0d2c58a964b
244
def _unpack_available_edges(avail, weight=None, G=None): """Helper to separate avail into edges and corresponding weights""" if weight is None: weight = "weight" if isinstance(avail, dict): avail_uv = list(avail.keys()) avail_w = list(avail.values()) else: def _try_getit...
0c4ac0afc209544e385f9214f141cde6f75daa4a
245
import uuid def triple_str_to_dict(clause): """ converts a triple (for a where_clause) in the form <<#subj, pred_text, #obj/obj_text>> to dictionary form. it assumed that one of the three entries is replaced by a "?" if the obj memid is fixed (as opposed to the obj_text), use a "#" in fron...
48c2dff6f0d4cceb7f4d3edca6a498573360b45a
246
import json def reddit_data(subreddit, time_request = -9999): """ @brief function to retrieve the metadata of a gutenberg book given its ID :param subreddit: the name of the subreddit :param time_request: unix timestamp of when requested subreddit was generated :return: a list of reddit objects wi...
78d79e2e917aaa892b4122d657c30a7cd13dfc4b
247
def write_velocity_files(U_25_RHS_str, U_50_RHS_str, U_100_RHS_str, U_125_RHS_str, U_150_RHS_str, U_25_LHS_str, U_50_LHS_str, U_100_LHS_str, U_125_LHS_str, U_150_LHS_str, path_0_100, path_0_125, path_0_150, path_0_25, path_0_50): """Create the details file for the surrounding cases, and write the velocities in line...
6c4af67ea659c09669f7294ec453db5e4e9fb9df
248
def datetime_to_bytes(value): """Return bytes representing UTC time in microseconds.""" return pack('>Q', int(value.timestamp() * 1e6))
e8b1d78615a84fb4279563d948ca807b0f0f7310
249
from typing import Sequence from typing import List def _f7(seq: Sequence) -> List: """order preserving de-duplicate sequence""" seen = set() seen_add = seen.add return [x for x in seq if not (x in seen or seen_add(x))]
f4dde886503754a09ac4ff545638750bf8fc6d94
250
def get_config(cfg): """ Sets the hypermeters for the optimizer and experiment using the config file Args: cfg: A YACS config object. """ config_params = { "train_params": { "adapt_lambda": cfg.SOLVER.AD_LAMBDA, "adapt_lr": cfg.SOLVER.AD_LR, "lamb...
a88bc3c8057d969998ab286aaa15ee5e8768c838
251
def get_nas_transforms(): """ Returns trajectory transformations for NAS. """ return [ PadActions(), AsArray(), RewardsAsValueTargets(), TileValueTargets() ]
f323ef2cd40af81fdd230e4bbb53cfa2ba6e4450
252
from datetime import datetime def epoch_to_datetime(epoch): """ :param epoch: str of epoch time :return: converted datetime type """ return datetime.datetime.fromtimestamp(float(epoch) / 1000)
59d9b85489320f5b1db93e6513fc375b9b58b151
253
def qe_m4(px,mlmax,Talm=None,fTalm=None): """ px is a pixelization object, initialized like this: px = pixelization(shape=shape,wcs=wcs) # for CAR px = pixelization(nside=nside) # for healpix output: curved sky multipole=4 estimator """ ells = np.arange(mlmax) #prepare temperature map ...
f2b6c7fe03a5dae34aaa58738684e37cf30efc01
254
def seasonality_plot_df(m, ds): """Prepare dataframe for plotting seasonal components. Parameters ---------- m: Prophet model. ds: List of dates for column ds. Returns ------- A dataframe with seasonal components on ds. """ df_dict = {'ds': ds, 'cap': 1., 'floor': 0.} for n...
ae362631659ec1652eb1798a73dce786cd269ee5
255
async def response(request: DiscoveryRequest, xds_type: DiscoveryTypes, host: str = 'none'): """ A Discovery **Request** typically looks something like: .. code-block:: json { "version_info": "0", "node": { "cluster": "T1", "build_version": "...
3ffa2ec8c64dd479ea6ecf3494a2db23b95f2ef2
256
def count_inner_bags(content, start_color): """Count inner bags""" rules = process_content(content) bags = rules[start_color] count = len(bags) while len(bags) != 0: new_bags = [] for bag in bags: count += len(rules[bag]) new_bags += rules[bag] bags =...
f6e188d548beaa5f1b24d96e6394c2bdbfaefd0b
257
def build_generation_data( egrid_facilities_to_include=None, generation_years=None ): """ Build a dataset of facility-level generation using EIA923. This function will apply filters for positive generation, generation efficiency within a given range, and a minimum percent of generation from the ...
32a2f1757419e52b7d8ea5b198a70bfd36f7dd4c
258
def get_nessus_scans(): """Return a paginated list of Nessus scan reports. **Example request**: .. sourcecode:: http GET /api/1.0/analysis/nessus?page=1 HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0...
1828d42baff7e16c8dac6b1e5ab6c66c14834c3c
259
from doctest import TestResults from _doctest26 import TestResults def count_failures(runner): """Count number of failures in a doctest runner. Code modeled after the summarize() method in doctest. """ try: except: return [TestResults(f, t) for f, t in runner._name2ft.values() if f > 0 ]
0e755114f5c23be0bdac11876f32bd2ac4ad9625
260
def fnv1_64(data, hval_init=FNV1_64_INIT): """ Returns the 64 bit FNV-1 hash value for the given data. """ return fnv(data, hval_init, FNV_64_PRIME, 2**64)
3981677c02317f63ae62cab75ee0d5db2fec7dc2
261
import os import traceback def recongnize_image_file(args, image_file, output_dir): """ 遍历图片文件 :param input_dir: :return: """ temp_name = image_file.split('/')[-1].split('.')[0] textract_json = None label_file = os.path.join( output_dir, temp_name + '.txt') #print("label_file ", ...
09dbf852e3243468b34901c50cff8ad5e2034d31
262
from pathlib import Path import tqdm def parse_data_sp(source_root, parallel_roots, glob_str="**/*.wav", add_source=False): """ assert that parallel_root wil contain folders of following structure: PARALLEL_ROOT/record_17/IPhone 12 Pro Max/JBL CLIP3/distance=60-loudness=15-recording_mode=default/RELATIVE_...
d23613c63d904ca5adb23c10c670ddab2d4148e7
263
def heat_diffusion(A, t, L, k, eps=0.0001): """ Computes the heat diffusion equation Parameters ---------- A : Tensor or SparseTensor the (N,N,) density matrix t : float the diffusion time L : Tensor or SparseTensor the (N,N,) Laplacian matrix k : Tensor ...
56ee07ed473463116b045700e4923218d72b5aca
264
def unpack_ad_info(ad_info: dict, param_name: str) -> bytes: """Проверяет наличие ожидаемой структуры и возвращает значение.""" # Красиво не сработает, потому что применение условий должно быть последовательным if ( isinstance(ad_info, dict) and ad_info.get(param_name) # noqa: W503 ...
85a6c95bac7e35bed4f478b352b2a56203818139
265
def _read_file(file, sheet_name=0): """ Helper function used to read the file and return a pandas dataframe. Checks if file type is a .csv or excel. If not, returns a ValueError. Parameters ---------- file : str the name of the file, including the filetype extension sheet_name : ...
fbe9212084062233ca2073af57b401afc9532701
266
def get_school_total_students(school_id, aug_school_info): """ Gets total number of students associated with a school. Args: district_id (str): NCES ID of target district (e.g. '0100005'). aug_school_info (pandas.DataFrame): Target augmented school information (as formatted by...
d0d2ea36a2e3f4b47992aea9cc0c18c5ba7e0ff3
267
def loci_adjust(ds, *, group, thresh, interp): """LOCI: Adjust on one block. Dataset variables: hist_thresh : Hist's equivalent thresh from ref sim : Data to adjust """ sth = u.broadcast(ds.hist_thresh, ds.sim, group=group, interp=interp) factor = u.broadcast(ds.af, ds.sim, group=group,...
2bb833a33bf32ed308137342007f7c62acfabe82
268
def _ClientThread(client_ip, client_user, client_pass, mvip, username, password, purge): """delete the volumes for a client, run as a thread""" log = GetLogger() SetThreadLogPrefix(client_ip) log.info("Connecting to client") client = SFClient(client_ip, client_user, client_pass) account_name = ...
258531ac383271c1a637b38ed3ff4f7a358c1dbc
269
import json def objective(args: Namespace, trial: optuna.trial._trial.Trial) -> float: """Objective function for optimization trials. Args: args (Namespace): Input arguments for each trial (see `config/args.json`) for argument names. trial (optuna.trial._trial.Trial): Optuna optimization trial...
629711996034664654430fba8af541fc934e143a
270
def read_gdwarfs(file=_GDWARFALLFILE,logg=False,ug=False,ri=False,sn=True, ebv=True,nocoords=False): """ NAME: read_gdwarfs PURPOSE: read the spectroscopic G dwarf sample INPUT: logg= if True, cut on logg, if number, cut on logg > the number (>4.2) ug= if Tru...
da073917d825dac283d8157dec771036588b0cec
271
def add_item(category_slug=None): """ Add a new Item Form. :param category_slug: The category slug """ # Get the current category using the slug current_category = Category.where('slug', category_slug).first() return render_template( 'items/add.html', categories=Category.a...
6bbaabdab6da6290c1de17ecbc36e849b7fd4c5e
272
def track_type(time, lat, tmax=1): """ Determines ascending and descending tracks. Defines unique tracks as segments with time breaks > tmax, and tests whether lat increases or decreases w/time. """ # Generate track segment tracks = np.zeros(lat.shape) # Set values ...
5872deaf6ff5d5e651705f40b8ad3df192ec98de
273
def get_installed_procnames(): """Get a list of procs currently on the file system.""" return set(get_procs())
6f3f83d579033ef407c72ccbd8d973f39d41ae22
274
def pam_bw_as_matrix(buff, border): """\ Returns the QR code as list of [0, 1] lists. :param io.BytesIO buff: Buffer to read the matrix from. :param int border: The QR code border """ res = [] data, size = _image_data(buff) for i, offset in enumerate(range(0, len(data), size)): ...
0360ee9d9e22fd667bc80063bd799fbaa2cb3a44
275
def delete_task(task_id: int): """Remove task with associated ID from the database.""" send_to_login = ensure_login() if send_to_login: return send_to_login else: old_task = Task.delete(task_id) flash(f'You deleted "{old_task.title}"', "info") return redirect(url_for("ta...
976c8aedc47ca342809d82904c4a1eab31e8886f
276
def KDPReboot(cmd_args=None): """ Restart the remote target """ if "kdp" != GetConnectionProtocol(): print "Target is not connected over kdp. Nothing to do here." return False print "Rebooting the remote machine." lldb.debugger.HandleCommand('process plugin packet send --command 0x1...
bcd4bab8fcb3abb1f512b349ce8468e7a09ceab0
277
def get_version(): # noqa: E501 """API version The API version # noqa: E501 :rtype: str """ return '1.0.0'
75df6627bb2aaec205a0679d86c190d7b861baf5
278
import tqdm import torch def bert_evaluate(model, eval_dataloader, device): """Evaluation of trained checkpoint.""" model.to(device) model.eval() predictions = [] true_labels = [] data_iterator = tqdm(eval_dataloader, desc="Iteration") for step, batch in enumerate(data_iterator): i...
3534796f06a89378dec9c23788cb52f75d088423
279
def get_cached_scts(hex_ee_hash): """ get_cached_scts returns previously fetched valid SCT from this certificate. The key to perform this search is the hex-encoded hash of the end-entity certificate :param hex_ee_hash: the hex-encoded hash of the end-entity certificate :return: a dictionary of SCTs whe...
5f86f1ccd7488f9712b16d1c71077ceb73098ea3
280
import torch def all_gather_multigpu( output_tensor_lists, input_tensor_list, group=None, async_op=False ): """ Gathers tensors from the whole group in a list. Each tensor in ``tensor_list`` should reside on a separate GPU Only nccl backend is currently supported tensors should only be GPU te...
e948709a209877c0d994699106e06bd13ddb46a7
281
import uuid def get_uuid_from_str(input_id: str) -> str: """ Returns an uuid3 string representation generated from an input string. :param input_id: :return: uuid3 string representation """ return str(uuid.uuid3(uuid.NAMESPACE_DNS, input_id))
51ce9ceab7c4f9d63d45fbee93286711bcba3093
282
import requests def extend_request(request_id=None, workload_id=None, lifetime=30): """ extend an request's lifetime. :param request_id: The id of the request. :param workload_id: The workload_id of the request. :param lifetime: The life time as umber of days. """ return requests.extend_r...
4b5c523f1af2b1c7c6f55bf522bb2c32e0f14995
283
def from_bytes(buf: bytes) -> str: """Return MIME type from content in form of bytes-like type. Example: >>> import defity >>> defity.from_bytes(b'some-binary-content') 'image/png' """ _guard_buf_arg(buf) # We accept many input data types just for user's convenience. We still c...
5b997bc8d9b6d5e3fc7e38c5956bcefe3f0244cc
284
def pl__5__create_train_frame_sequences(ctvusts_by_tcp__lte_1, frame_sequences__by__tcpctvustsfs, train_tcpctvustsfs__gt__1): """ returns: train_tcpctvustsfs__all ( <TokenID>, <CameraPerspective>, <ASLConsultantID>, <TargetVideo...
1824b26a449a24ae02e72c1fe1fc6931c9658875
285
def createList(value, n): """ @param value: value to initialize the list @param n: list size to be created @return: size n list initialized to value """ return [value for i in range (n)]
ff419e6c816f9b916a156e21c68fd66b36de9cfb
286
def label_class_num(label): """ 标签的种类 :param label: :return: """ return label.shape[1]
d3b9f6e7b84c10af289878587d7f36bf18147b9e
287
def heur(puzzle, item_total_calc, total_calc): """ Heuristic template that provides the current and target position for each number and the total function. Parameters: puzzle - the puzzle item_total_calc - takes 4 parameters: current row, target row, current col, target col. Returns i...
bed67110858733a20b89bc1aacd6c5dc3ea04e13
288
def make_argparse_help_safe(s): """Make strings safe for argparse's help. Argparse supports %{} - templates. This is sometimes not needed. Make user supplied strings safe for this. """ return s.replace('%', '%%').replace('%%%', '%%')
3a1e6e072a8307df884e39b5b3a0218678d08462
289
import os def _file_content_hash(file_name, encoding, database=None, newline=None): """ Returns the file content as well as the hash of the content Use the database to keep a persistent cache of the last content hash. If the file modification date has not changed assume the hash is the same and ...
eb544ea82ce6baeb8260627d15da3bd5b8e964ba
290
import tempfile import os def leaderboard(avatars, usernames, levels): """ Draw the leaderboard. Return the path of the image. The path points to a temporary file with extension png. The caller is responsible for removing this temporary file. avatars is 10 top users' avatar images. It should ...
a8607ab75856a208a1e950ddde7b8253173db34c
291
def create_pysm_commands( mapfile, nside, bandcenter_ghz, bandwidth_ghz, beam_arcmin, coord, mpi_launch, mpi_procs, mpi_nodes, ): """ Return lines of shell code to generate the precomputed input sky map. """ mpistr = "{}".format(mpi_launch) if mpi_procs != "": ...
f0528968096f41a291a369477d8e2071f4b52339
292
def edits1(word): """ All edits that are one edit away from `word`. """ letters = 'abcdefghijklmnopqrstuvwxyz' splits = [(word[:i], word[i:]) for i in range(len(word) + 1)] deletes = [L + R[1:] for L, R in splits if R] transposes = [L + R[1] + R[0] + R[2:] for L, R in spli...
ec78ba3648e04c59b380cd37760b7865e5f364ea
293
def process_text_cn(text: str): """中文文本处理""" text = del_white_chars(text) text = sub_punctuation(text) return text
18fd44ee2c5929fd6fe3c4aef9fde332773b016c
294
import math def total_elastic_cross_section_browning1994_cm2(atomic_number, energy_keV): """ From browning1994 Valid in the range 100 eV to 30 keV for elements 1 to 92. """ Z = atomic_number E = energy_keV factor = 3.0e-18 power_z = math.pow(Z, 1.7) power_e = math.pow(E, 0.5) n...
bf12a49e3aba07a44e44bfb6df87212745fd5ed3
295
def plot_fancy(nodes, elems, phi=None, charge=None, u=None, charge_max=None, show=False, save=None, num_intp=100, title=None, clabel=None, animation_mode=True, latex=False): """ Plots fancily. """ if animation_mode: fig = Figure(colorbar=False, tight_layout=True, show=show,...
a334c581b9601c73a1b003aec14f4f179dab5202
296
def buildModelGPT(modelType='gpt2-medium'): """ This function builds the model of the function und returns it based on GPT """ ## Create Model # Load pre-trained model tokenizer (vocabulary) tokenizer = GPT2Tokenizer.from_pretrained(modelType) # Load pre-trained model (weights) model = GPT2LMHeadMo...
51b2dca333a06ed9168d3056b681b1ed192c5761
297
def vid_to_list(filepath): """ Converts a video file to a list of 3d arrays of dim (h, w, c) Input: filepath: (str) full filepath of video Output: vid: (ndarray) list of 3d numpy arrays, of shape (height, width, color) """ cap = cv.VideoCapture(filepath) list_of_frames = ...
062423bcf10749705e767edf6721dd20903653ef
298
import pickle def from_pickle(fname=interpolator_path): """Loads grid inperpolator from pickle located at `fname`. """ with open(fname, "rb") as f: grid = pickle.load(f) return grid
5b4f2a94ba3024ea63a5859284f1b6877bac1623
299