content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_shape_tags(tags, font_info=(cv2.FONT_HERSHEY_COMPLEX_SMALL, 0.75, (255,255,255), 1)): """Get information about how much the list of tags will occupy (width and height) with the current configuration. Arguments: tags -- list of strings/tags you want to check shape. Keyword arguments: fo...
a95d546432adb1e0d1656a8420ba63c29e4d23bd
37,400
def Intersection(S1x, S1y, D1x, D1y, S2x, S2y, D2x, D2y): """ Find intersection of 2 line segments :param S1x: x coordinate of segment 1's start point :param S1y: y coordinate of segment 1's start point :param D1x: x coordinate of segment 1's end point :param D1y: y coordinate of segment 1's end...
2dba8839ebf24b55fe3c1b7797e53c7e0c3ed72a
37,401
def optimization_writer(): """ Writes an input file for a geometry optimization. """ return opt_string
b3cc7ba7d96c0f2ee584a09e0dadc8db2b8e3eb4
37,402
def _offset(ax, x, y): """Provide offset in pixels Parameters ---------- x : int Offset in pixels for x y : int Offset in pixels for y Idea borrowed from http://www.scipy.org/Cookbook/Matplotlib/Transformations but then heavily extended to be compatible with many reinc...
e8051a75f5cdcb5de0f36d354ee10bd72398045c
37,403
def augment(input_img, input_angle): """ Increase the training data set. """ output_images, output_angles = [],[] """ Fun fact: I had this condition around the data flipping code but these function calls somehow SIGNIFICANTLY slowed down the training process!!! if ((abs(in...
56b5e06a71631264a897f4b6a7fd78f93410c304
37,404
def check_host(hwaddr, ipaddr, config, args, timestr): """ check host infos against the config returns changes, updated_config """ changes = [] # get hostname hostname = get_hostname(ipaddr) if hwaddr in config: # shortcut c = config[hwaddr] # check statu...
6d20938332dec55acb480abcde32e53cb30c7084
37,405
def Update(dEntities): """This will initiate all of the different updates that need done for the Chunk Manager Entity.""" Update_Load_List({"LoadList":dEntities["ChunkMan"].get_component("LIST:LoadList"), \ "ChunkDataDir":dEntities["ChunkMan"].get_component("MISC:C...
18518cdb7718718599c7943db86e0adfe4e93945
37,406
import sqlite3 def getIdForTable(table): """resolve a table name to an ID""" with sqlite3.connect(DB_PATH) as conn: db = conn.cursor() db.execute('SELECT table_id FROM tables WHERE table_name=?', [table]) return db.fetchone()[0]
8b11309b50d4bc7fef35a3096f5bf8f42e36b0a2
37,407
def blasi(wood, gas, tar, char, T, dt, s=1): """ Primary and secondary kinetic reactions from Table 1 in Blasi 1993 paper. Note that primary reaction parameters in table are not cited correctly from the Thurner and Mann 1981 paper, this function uses the correct parameters. Parameters ---------...
813f532b5750ec6c7e1a402a980ac2041b0bdebf
37,408
import os def run(num, roi_class_name, trials_name): """ For subject <num>, run all models for all ROIs. Note: Must be run from the parent folder of all the fMRI datasets.""" sdir = subdir(num) roi_class_path = roi_class_name.split('.') txt_classes = ['CatMean', 'Nobox', 'CatMeanFir', 'Subtime']...
30f7d68aa28c4c9e821ebf729379ac040b80de3d
37,409
def davis_southern_women_graph() -> nx.Graph: """Returns Davis Southern women social network. This is a bipartite graph. References ---------- .. [1] A. Davis, Gardner, B. B., Gardner, M. R., 1941. Deep South. University of Chicago Press, Chicago, IL. """ G = nx.Graph() # Top n...
af8d628cb03db7a64609b36af59c93b24299f2cc
37,410
def is_extension_enabled(extension_name, service): """A function that will check the list of enabled extensions from config """ config_dict = { 'compute': CONF.compute_feature_enabled.api_extensions, 'volume': CONF.volume_feature_enabled.api_extensions, 'network': CONF.network_featu...
524fc5abb3826058ab16cb3ee4b516d6eb3e2a01
37,411
import requests def existing_droplets(token): """infos about existing Marian droplets.""" params = { 'tag_name': 'marian' } url = 'https://api.digitalocean.com/v2/droplets' request = requests.get(url, headers=headers(token), params=params) return request.json()['droplets']
824a955d4c928004c265991b7268061f24c1cd27
37,412
import io import numpy def overlayLabel(dataSource, labelSource, sink = None, alpha = False, labelColorMap = 'jet', x = all, y = all, z = all): """Overlay a gray scale image with colored labeled image Arguments: dataSouce (str or array): volumetric image data labelSource (str or array): ...
7f84924fac34a0aea0fefc088b45eee32ac24f8d
37,413
def constrain_sum(a, b, result): """Constrain a + b == result. Note that overflows are forbidden, even if the result is never used.""" # This is a ripple-carry adder. c = False # carry bit # Optimization: stop at the the necessary number of bits. max_bit = max([i+1 for i in BITS if a.bits[i].i...
09371cbae682bfdef52b5db95b5dc904b7eb2ca2
37,414
def min_pos_root(a, b, c): """Returns the minimum positive root for the function ax²+bx+c = 0. If no positive roots exist, returns None""" roots = all_pos_roots(a, b, c) if not roots or len(roots) == 0: return None return roots[0]
afd619261002d8f65b982f74858b198d848eb572
37,415
from typing import Iterable def patch_module(module): """ Extends all iterables in the module with ``asq.queryables.Queryable`` methods. Applies the same as ``patch_type`` to every appropriate member of the module. Args: module: Module object or its __dict__. Returns: A ...
d5f0f7e7def1ca0938e0a52930eb3f746996e403
37,416
def trace_func(resource): """Trace calls to function using provided resource name""" @wrapt.function_wrapper def _trace_func(wrapped, instance, args, kwargs): pin = Pin.get_from(molten) if not pin or not pin.enabled(): return wrapped(*args, **kwargs) with pin.tracer.tr...
968fc735e755d8960d5d457f3ae2923a655a087e
37,417
def search_for_item(project): """Generate a string search key for a project""" elements = [] elements.append(project['attributes']['title']) return u' '.join(elements)
3ca0850b0c7b01900609aedfa41fd3fb8b86abac
37,418
def sort_by_status(ori_list): """ sort feature progress :param ori_list: :return: """ for i in range(len(ori_list) - 1): for j in range(len(ori_list) - 1 - i): if compare_two_features(ori_list[j], ori_list[j + 1]): ori_list[j], ori_list[j + 1] = ori_list[j + 1...
389add5b03278b7cee490b507fcc0b9261a2dd4c
37,419
def perturb_word(word: str, skip_stopwords=True, skip_punctuation=True): """ :param skip_stopwords: :param word: :return: pertubed word, None if no perturbation is available """ if skip_stopwords and word.lower() in stopwords.words('english') \ or skip_punctuation and not word.lowe...
6334896e3f489ed1cc0baa7cfe785179579c77c5
37,420
def boxzoom(viewer, event): """Enable box zoom.""" def _get_shape(): if "Control" in event.modifiers: return Shape.VERTICAL elif "Shift" in event.modifiers: return Shape.HORIZONTAL return Shape.BOX # make sure box is visible if not viewer.drag_tool.tool....
49716b217b04a78c4dada95a60c9aa6c4f8e2f4c
37,421
def gen_coeffs(num_dim): """ Helper function for generating a linear simulation. :param num_dim: number of dimensions for the simulation :return: a vector of coefficients """ coeff_vec = np.array([1 / (x+1) for x in range(num_dim)]) return coeff_vec.reshape(-1, 1)
87fe28331ec0be2d4eef59ca68fbd2055d49304f
37,422
def read_passwords(addr): """ read passwords as list from a file """ with open(addr) as f: lines = f.readlines() pwlist = [clean_word(line) for line in lines] pwlist = [x for x in pwlist if x != ""] return pwlist
e2190dee8fe0b5afbc3f0b7e23d7267e837be975
37,423
def get_model(name, version, project_name=None): """ Get a specific model version given a model name and a version. For example if you run this: >>> from hops import model >>> model.get_model('mnist', 1) You will get version 1 of the model 'mnist' Args: :name: name of the model ...
2e82f7b6703df0313abc29cbadbe6e140a01aeb2
37,424
def index(): """Return the home page.""" return render_template('index.html')
193f867973725dc89f5b213217cb15bc6980a66a
37,425
def generate_scope_name(data_loader): """ Generate scope name according to computation graph. Args: data_loader (OnnxDataLoader): Data loader instance. Returns: list[str], generated scope name. """ init_dag = _build_connection(data_loader) try: if USER_DEFINED_PATTE...
d57495866f8c100271b2327669b6245409052060
37,426
import os def write_jobfile(cmd, jobname, sbatchpath='./sbatch/', nodes=1, ppn=1, gpus=0, mem=16, nhours=3): """ Create a job file. Args: cmd : str, Command to execute. jobname : str, Name of the job. sbatchpath : str, Directory to store SBATCH file in. s...
0493f480fa42eb5dc8d108c59999d8a9430e4669
37,427
def get_active_questions(netid, course_id): """Gets all questions that are not yet being helped Returns a list of questions with their question text, id, enqueue_time, and the asking student's name or None if the requester is not a TA """ if not verify_is_ta(netid, course_id): return None ...
95d670927231e20cbbc9f468dace1ebe6c760eef
37,428
def hamiltonian(edges, directed=False, time_limit=5, concorde=False, precision=0): """ Calculates shortest path that traverses each node exactly once. Convert Hamiltonian path problem to TSP by adding one dummy point that has a distance of zero to all your other points. Solve the TSP and get rid of the ...
24a857d2184c20ef00b46fb06aa2a1c87a21299c
37,429
def analytic_kernel(k): """Calculate the X4 kernel from the X2 kernel (for proof see appendix in paper)""" k_size = k.shape[0] # Calculate the big kernels size big_k = np.zeros((3 * k_size - 2, 3 * k_size - 2)) # Loop over the small kernel to fill the big one for r in range(k_size): for ...
385ccd1e2ae4906780df909aa2e7830208466e48
37,430
def simple_3dof_arm(seg1_len, seg2_len, seg3_len, q0, base=None): """Creates a simple human-like robotic arm with 7 links and 2 segments with the desired lengths and starting joint configuration :param seg1_len: The length of the first segment of the arm :type seg1_len: int :param seg2_len: The le...
8a0c211cf72c764dc8b973c04ce8a045397660c8
37,431
def collect_nodes(points, highlighted_nodes=[], color='#79FF06', highlighted_color='blue', width=200, highlighted_width=400): """ Собирает необходимые нам вершины в нужный формат Parameters ---------- points : [str, str, ...] Вершины графа. highlighted_nodes : [str, str, ...], optional ...
a3a218b5f8c8c25a0f13a4154f12779a84726f9d
37,432
def conv3x3(in_planes, out_planes, stride=1): """3x3 convolution with padding""" conv3x3 = nn.Sequential( nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False), nn.BatchNorm2d(out_planes), nn.ReLU(inplace=True), ) return conv3x3
f1c658e9115a741b34ebb9e6c89965d97d18cbf9
37,433
import typing import re from datetime import datetime import requests def check_url_content( url: str, content_match: typing.Optional[re.Pattern] = None ) -> typing.Tuple[str, int, float, bool, datetime.datetime]: """ Get URL and return basic information. Args: url (str): The URL to check. ...
4d7643fd812b499254af74b706acb894f28bad4d
37,434
def post_reasoner_query(request_body): """Get associations for a given ReasonerAPI query. :param request_body: The ReasonerStdAPI query in JSON :return: Results as a ReasonerStdAPI Message """ query_graph = request_body["message"]["query_graph"] print(query_graph) if len(query_graph["ed...
14817b6722bf84aaad440d1cc2758794d5f08f63
37,435
def get_ransac_pipeline(): """ Function return pipeline with lagged transformation in it """ node_ransac = PrimaryNode('ransac_lin_reg') node_final = SecondaryNode('linear', nodes_from=[node_ransac]) pipeline = Pipeline(node_final) return pipeline
4a6e0b21fe35691753885cd509c5344b96f4da67
37,436
def feature_names_from_extractor_list(feature_extractors): """ get a list of feature names from a list of feature extractors :param feature_extractors: a list of feature extractors :return: a list of the feature names for each extractor (think first row of .csv file) """ feature_names = [feature...
2f23aa860137e70270e9c7d564df5dacfa1d22a2
37,437
import os from shutil import copyfile def upload_files(local_path, warm_up=False): """ upload files to hdfs """ remote = os.getenv("OUTPUT_PATH") job_id = os.getenv("SYS_JOB_ID") local = local_path.split('/')[-1] remote_path = "{}/{}/{}/{}".format(remote, job_id, "model", local) client...
7f8e8d92f07905de5d399a488f61cfe15e364f71
37,438
def blank_publish_view(request): """Save posts into db w/o publishing.""" return poster(lambda: tasks.fetch_and_publish(force=True, blank=True))
6883c038bdfbee7d975134152fd83f61f830b22f
37,439
import io def read_txt(filename, encoding='utf-8'): """Text file reader.""" with io.open(filename, 'r', encoding=encoding) as f: return f.read()
2ca0d80bddc49b793e8cbc63c513410154b4d460
37,440
def level_detect(x, fs, attack_ms=0.1, release_ms=100, mode='peak'): """Performs level detection on an input signal Parameters ---------- x : ndarray Input vector fs : float Sample rate [Hz] attack_ms : float, optional Time constant for attack [ms] release_ms : float...
dacde4e210f2d9d821c26cfc7a2965dbc3bcebe4
37,441
import copy def get_doc_permissions(doc, verbose=False, user=None, ptype=None): """Returns a dict of evaluated permissions for given `doc` like `{"read":1, "write":1}`""" if not user: user = frappe.session.user if frappe.is_table(doc.doctype): return {"read": 1, "write": 1} meta = frappe.get_meta(doc.doctype) ...
06698057696dbb6385de951668baddd535ae7b5c
37,442
def get_job_type(name): """Returns job type based on its name.""" if 'phase1' in name: return 'phase1' elif 'phase2' in name: return 'phase2' elif 'dfg' in name: return 'dfg' else: return 'other'
50db4a7833028b0a0944a4b915d82a8cabf91595
37,443
def ames_score(emb): """ Measure the ames positive probability of molecule, more close to 1, more "toxic" Parameters ---------- emb : numpy.ndarray, size (x,512) the cddd descriptor of molecule Returns ------- ames : float ames score """ ames = ames_model.p...
5dc55dd36c8627ea97314227e9f72e168b488da8
37,444
def quadrature(func,a,b,args=(),tol=1.49e-8,maxiter=50, reference=False): """Compute a definite integral using fixed-tolerance Gaussian quadrature. Description: Integrate func from a to b using Gaussian quadrature with absolute tolerance tol. Inputs: func -- a Python function or method to integr...
dc3188ced57ae6d138410bcbd34595f4142f078c
37,445
import argparse def getargs(): """ Parse program arguments. """ parser = argparse.ArgumentParser( description=DESCRIPTION, formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('ori_lst', type=str, help='original image list') parser.add_argumen...
900eedc7e29f4ff2553a1c9c002f00f4fc9e2cfe
37,446
def read_sensor(): """Returns the orientation in quaternion form""" quat = sensor.quaternion return quat
f8dfc128987f03de35ef9ed7e1bd184919411989
37,447
def is_resnet(name): """ Simply checks if name represents a resnet, by convention, all resnet names start with 'resnet' :param name: :return: """ name = name.lower() return name.startswith('resnet')
6310d849b76a1006c7c2e97405aa9f0ebc53a78b
37,448
from typing import Optional def _get_object_system_id(obj) -> Optional[str]: """Finds the System id (as a string) for the supplied object""" system_id = None if isinstance(obj, System): system_id = obj.id elif isinstance(obj, BrewtilsSystem): system_id = ObjectId(obj.id) elif type...
40545e2a572954a8ed1e2e81de17e47a7941616c
37,449
import os def find_closest_config_file(): """ Returns the location of the closest Verta config file. Returns ------- config_filepath: str or None Path to config file. """ for dirpath in get_possible_config_file_dirs(): # TODO: raise error if YAML and JSON in same dir ...
7bf80befdbcc6d7b907e6e32fde7e3bad40b9499
37,450
def _regress_1d(design_matrix, boot_mean, boot_var, Nc_list, treatment_idx, **kwargs): """ Performs hypothesis testing for a single gene for many bootstrap iterations. Here, :X_center:, :X_center_Sq:, :boot_var:, :boot_mean: should have the same number of rows """ num_boot = boot_mean.shape[1] nonneg = Fal...
042f3ea973db7602c7b3e3e712715c39788e1ca4
37,451
import os import re import logging def convert_output_record(data): """Covert data record into a list for output csv """ output_record = [] # Participant ID output_record.append(os.path.basename(data['filename']).replace('.eaf', '')) # Speaker output_record.append(data['speaker']) #...
046fe65ae63e5559e4bccde5817a4c4f238b0467
37,452
def handle_pmid_25502872(filename): """Bergseng, ..., Sollid. Immunogenetics 2015 [PMID 25502872]""" return None
25a11d19293c59e4ae636b0b26389dbfd6b74955
37,453
def expand_schema_for_inheritance(schema): """ Allows the schema to support inheritance. The schema supports configs that (optionally) point to zero or more parent YAML configs (using a path) that will be taken as base configurations to be overwritten. """ return merge({'inherit': stlistorstring...
045505ea4634aef392196c1c174fefd8c1b541e6
37,454
def option_two(choice_two): """Functions to for different methods to search the database""" if choice_two == 1: query_sub = search_record.search_date() elif choice_two == 2: query_sub = search_record.search_time() elif choice_two == 3: query_sub = search_record.search_string() ...
6b1b20f452cfa24eed6c67346215da204a5d3012
37,455
import re def parse_fmt(fmt: str) -> (int, int): """Parse Q<m>.<n> string Parameters ---------- fmt Format string in the form 'Qm.n', where m is the number of integer bits n is the number of fractional bits Returns ------- n, m Number o...
f72133fdef9bbf40eb89d977d217376df8f2a3bd
37,456
from typing import Dict def invert_dictionary(mapping: Dict) -> Dict: """Invert the keys and values of a dictionary.""" remap = {v: k for k, v in mapping.items()} if len(remap) != len(mapping): raise ValueError("Dictionary cannot be inverted; some values were not unique") return remap
911aee48eff3bf0d980e5ad054c77c8a3081e232
37,457
def store_file(file): """Stores the file to specified destination""" destination = "/".join(["api/test_docs", file.name]) file.save(destination) return destination
1118415a1c1b7c2a33ecc539df7bf27dfd783d16
37,458
import torch import os def model_fn(model_dir): """Load the PyTorch model from the `model_dir` directory.""" print("Loading model.") # Determine the device and construct the model. device = torch.device("cuda" if torch.cuda.is_available() else "cpu") name = 'cnn.pth' checkpoint = torch.l...
a677b51daed36cd0d1e50c34cd12a7dbb59aa3e8
37,459
def getNumberedTypedString(items, maxLen=5000, numPrefix=''): """get a string that has each item of the list on its own line, and each item is numbered on the left from zero""" digits = 0 n = len(items) while n > 0: digits += 1 n //= 10 digits = digits format = numPrefix + '%...
4fa1f93c420c555093f1fc3b3ba3e43a4ce839f0
37,460
def mpl_dict(params): """"Convert _ to . for easier mpl rcparams grid definition""" return {k.replace('_', '.'): v for k, v in params.items()}
a8c4ae683205a1412a73f00e6965cb345ec63a3e
37,461
def _format_accelerations(pivot_x, pivot_y, is_acceleration, h): """ Returns the pivot movement as acceleration The user is allowed to enter the pivot's movement as two functions of time. If is_acceleration is set to True, these functions are interpreted as pivot's acceleration. Otherwise, they are int...
51f57ed84e86939db430b45d87dbf99f5ef5ee36
37,462
def data_source_get(context, data_source): """Return the Data Source or None if it does not exist.""" return IMPL.data_source_get(context, data_source)
5da4900f1e1099830253293ddf7391279d75c38e
37,463
def add_pseudo_counts(ccm,ad=None,num=None): """Add a small number of fake mutations or 'pseudo counts' to the co-clustering and ancestor-descendant matrices for subchallenges 2 and 3, each in their own, new cluster. This ensures that there are not cases where either of these matrices has a variance of zero...
f239f26ac0349bb3011b74f8a8d040fb34adb8a9
37,464
def compute_coefficients(xyz): """Fit a plane to the first three dimensions of a matrix Parameters ---------- xyz : array-like The matrix of data to fit the plane to. Returns ------- np.array 1-dimensional array with four values, the coefficients `a`, `b`, `c` and `...
07fb6af0c63a75f2a4e88e2a01836a212b2a8a57
37,465
def _build_step( docker_api, variables, build_config, step_config, from_image, should_ignore_cache, should_remove_container): """ Builds the image for the given step :param docker_api: The api interface that is to be used to connect to the docker daemon :param variables: The list of var...
437a279364bd89e83ffb01d39089bf23f2480994
37,466
from functools import reduce def Sum(onnx_node, ng_inputs): # type: (NodeWrapper, List[TensorOp]) -> Op """Calculate element-wise sum of the input tensors.""" return reduce(ng.add, ng_inputs)
7d1080e490a4cf6d7d06d0f95c903013df730525
37,467
def test_df_keys(): """List of keys to be used for populating a bucket with DataFrames""" return { 'avro': ['df.avro'], 'csv': ['df.csv'], 'csv.gz': ['df.csv.gz'], 'csv.zip': ['df.csv.zip'], 'csv.bz2': ['df.csv.bz2'], 'csv.xz': ['df.csv.xz'], 'psv': ['df.p...
3b008664744fb6abf8960caebe658ecc2f6525af
37,468
def first_existing(d, keys): """Returns the value of the first key in keys which exists in d.""" for key in keys: if key in d: return d[key] return None
eb9f34f1f5adb0a8e44127fe777e35ca8d36dc04
37,469
import os def aseg_stats_subcortical(fspath, subjid): """ Returns all the subcortical volumes found in stats/aseg.stats. Equivalent of load_fs_segstats.m """ ignore_seg_names = cfg.freesurfer_subcortical_seg_names_to_ignore segstatsfile = os.path.join(fspath, subjid, 'stats', 'aseg.stats')...
36c458c4825802c1f87954ded3d1e5c39e647db2
37,470
def _expand_right(a, n): """Insert multiple axes of size 1 at right end of tensor's shape. Equivalent to performing `expand_dims(..., -1)` `n` times. Args: a: tensor into which extra axes will be inserted. n: number of inserted axes. """ return tf.reshape(a, tf.concat([ tf.shape(a), tf.ones([...
69a3acb3aa717070ac3e1410c0f30fa71acbc56b
37,471
def unregister_mod(mod: Mod) -> bool: """ unregisters a mod from the global cache `mods` :param mod: mod to unregister :return: if it successfully unregistered it """ if mod.name_or_class_name() not in mods: return False get_event_loop().create_task(mod.unloaded()) del mods[mod....
48e018ebb2d56fd2e6713a6df4ae3f59160d78a8
37,472
import os def resolve_usr_filename(filename): """Resolve the filename to an absolute path. :param filename: The input file name. """ full_filename = filename if os.path.isabs(full_filename) == False: full_filename = os.path.join(os.path.expanduser("~"), full_filename) retu...
e239c80c9e11f79c786557d4de3e1fc51a4f791d
37,473
def errors(module): """ dict: {name:Exception or None} for tests in module. """ modname = module.__name__ errors = ((k, do(v)) for k, v in all_tests(module)) errors = ((k, v) for k, v in errors if v is not None) return {f"{modname}.{name}": err for name, err in errors}
d60e604a821b4e56f1b560425157d11bc21c0be7
37,474
def add_column(graph, results, selector): """Add a column to `graph`, produce a new graph. Args: graph (:class:`Graph`): Source ArrowProperty graph. results (:class:`Context`): Results that generated by previous app querying. selector (str): Used to select a subrange of data of results,...
947160324c54d7d0d2fb7841513269be53f41642
37,475
def list_templates(sitename): """return a list of template names for this site""" path = WEBROOT / sitename / '.templates' if not path.exists(): return [] return sorted([f.name for f in path.iterdir() if f.suffix == '.tpl'])
05c6501b17ec1d6466aa82e818b95bede51c4713
37,476
def resample(myarray, shift, include_edge=False): """ Resample an array, e.g. duration or start times, with a certain delta step (shift). Parameters: myarray -- input array to resample shift -- unit to shift Outputs: myarray -- resampled """ ishift = int(shift / (myarray[1]-myarr...
8bcd3711a5c0c24a37d82b1ea20a730698e5eba1
37,477
import collections def from_pyqtgraph_struct(dct): """ Get simple structured dict from pyqtgraph params saveState() export. :param dct: dct = parameters.saveState() :return: """ output = {} key = dct["name"] if "children" in dct.keys(): reconstruction_type = "dict" if...
1c8d5b9f5fa10d0feb812e13dc3f7a8435958c61
37,478
def receive_msg(topic): """ Decorator """ def inner(func): @sio.on(topic) async def handle_request(data): # call 'func' to return the data func(data) # returning inner function return inner
5e9ccdf39762777850ba94beb9a46167256ebf3b
37,479
def get_requirements(): """Return a list of package requirements from the requirements.txt file.""" with open('requirements.txt') as f: return f.read().split()
85efbe71d02ced7c5987f08a56a1a966bff2e1ef
37,480
def MissalignmentTest(windows): """Run the test on the windows passed in""" refAlignments = {} #find the controls alligned along each axis for win in windows: if not win.ref: continue for side in ("top", "left", "right", "bottom"): sideValue = getattr(win.ref.r...
77d62d1ba1dcc81170de44c6d92332024eb8a083
37,481
def integer_to_real_mapper(integers): """Define Integer Mapping Function Here(If Needed.)""" real_numbers = [] range_of_integers = 32767 # each value goes from 0-32767(2 ^ length_of_chromosome) integer_to_real_number_mapper = 1 / range_of_integers # will produce number between 0-1 when multiplied by ...
18cc9dc1efe2dd8122d4953a4256cedd5fe234c9
37,482
import os def get_feature_normalizer_filename(fold, path, extension='cpickle'): """Get normalizer filename Parameters ---------- fold : int >= 0 evaluation fold number path : str normalizer path extension : str file extension (Default value='cpickle') R...
c2956766f891b6285dfb8b1d5a0a7f36c160351f
37,483
def fake_post_data(target, data_dict): """ In order for form to don't fail submission, all permission fields need to receive values. This function populates data dict with default values for permissions, making form validation pass """ for form in get_permissions_forms(target): for field...
c9e49956051059a79453c211c7f6fd1ba60c64f4
37,484
def get_3d_kgrid(fk,alat,nk,exclude_gamma=False): """ put a k-space function fk onto an FFT grid for inverse Fourier transform fr = np.fft.ifft(fk)*(alat/nk)**ndim ! Don't forget the normalization! """ kgrid = np.zeros([nk,nk,nk],dtype=complex) kint_unit = lambda x:kint_to_kvec(x,nk,alat) for kx in...
a064d5de47c3db4f872baeabba09df3e64cc93e3
37,485
import torch def prune_equal_fanin(model: torch.nn.Module, k: int = 2, validate: bool = True, device: torch.device = torch.device('cpu')) -> torch.nn.Module: """ Prune the dense layers of the network such that each neuron has the same fan-in. :param model: pyto...
d33271af099f67e5469e3e67534e214b1804cc82
37,486
def filter_files(file_path, selected=('bacteria', 'virus')): """filter files based on filepath""" base = file_path.stem for s in selected: if s in base: return True return False
e666d091eb41a128d39238181b9fef0396432cf8
37,487
import re import json async def _parse_at(text: str): """ @人格式:“@UID ”(注意最后有空格) Args: text (str): 原始文本 Returns: tuple(str, int[], dict): 替换后文本,解析出艾特的 UID 列表,AT 数据 """ pattern = re.compile(r"(?<=@)\d*?(?=\s)") match_result = re.finditer(pattern, text) uid_list = [] ...
ce843adf8e481af0869a055dc1f1d83f1921a74a
37,488
def mask_rcnn(features, mode, params, labels=None, class_targets=None, box_targets=None, box_rois=None, proposal_to_label_map=None, detections=None): """Mask-RCNN mask model. This is the mask part of the model (Mask-RCNN), which generates mask outputs. In addition, it also generates m...
a4ae501c451e8acd69100bb2d806eb203abb89b9
37,489
from numpy.linalg import inv from typing import Tuple def global_phik_from_rebinned_df(data_binned:pd.DataFrame, noise_correction:bool=True, dropna:bool=True, drop_underflow:bool=True, drop_overflow:bool=True) -> Tuple[np.ndarray, np.ndarray]: """ Global correlation values of ...
70fdbc54cd805e736785351c00f0d02a9c91da21
37,490
def findInWorkDir(filename): """Find a file name in user's work directory.""" return findFile(filename, sciflo.grid.getRootWorkDirFromConfiguration())
7a8255ff0bad7651cb30c11a2c998530cc4a8b8a
37,491
import os import glob def get_tfrecords(dset_dir, split='train'): """Get tfrecords that match training, validation, and test sets. Works off the TfSet protobuf. Args: dset_dir: dataset directory of tfrecords. split: train or eval. Returns: Relevant tfrecords from dset_dir. Raises: IOErro...
f014dca8c05bb824c15fe635b186472abe2bae37
37,492
def VerboseCompleter(unused_self, event_object): """Completer function that suggests simple verbose settings.""" if '-v' in event_object.line: return [] else: return ['-v']
e536e221f8f3465f72071d969b11b6623359cf58
37,493
def jpeg_dynamic_quality(original_photo, use_dynamic_quality=True): """Return an integer representing the quality that this JPEG image should be saved at to attain the quality threshold specified for this photo class. Args: original_photo - a prepared PIL JPEG image (only JPEG is supported) """...
1152a1a8e5105ecdcd17b402053dc368cc8f935f
37,494
def load_input_into_list(): """ Takes our input and returns it into a comprehensive list with split terms :return: The list of lists for our input :rtype: list """ return [line.replace('-', ' ').replace(':', '').split(' ') for line in open("inputs/day2_01.txt", "r").read().splitlines()]
9d8f1a313712f11249f4612d38ed9831d666287b
37,495
def isImageValid(img_path: str, min_sz: int = 256): """Validates whether the input image fits for the training/test procedure""" img = Image.open(img_path) if min(img.size) < min_sz or img.layers != 3: return False else: return True
e7062c0f5f29bda8ab8e400fc8253afb65836c5a
37,496
import os def SplitClovisTask(task): """Splits a ClovisTask in smaller ClovisTasks. Args: task: (ClovisTask) The task to split. Returns: list: The list of ClovisTasks. """ # For report task, need to find the traces first. if task.Action() == 'report': trace_bucket = task.ActionParams().get('...
ac855c374274bd4a240f540c6e99184f3ea76cc1
37,497
import datasets import torch import torchvision def load_cifar5(random_state=42): """Loads the datasets for CIFAR5 vs CIFAR5. In-Distribution: 'dog', 'frog', 'horse', 'ship', 'truck' Out-of-Distribution: 'airplane', 'automobile', 'bird', 'cat', 'deer' Args: random_state (int): The ra...
95a22a84ba52e83491d48ce818f64ca67cb06f57
37,498
def MC2000BGetFrequency(hdl,frequency): """ Get the internal reference frequency Args: hdl: the handle of opened MC2000B device frequency:get internal reference frequency Returns: 0: Success; negative number: failed. """ val = c_int(0) ret = GetFrequency(hdl,val) fr...
dff47c645aa0446347c722653f53db2945f73593
37,499