content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import argparse import logging import sys import os def open_output_file(options: argparse.Namespace): """Open Output File.""" if options.output is None: logging.debug("Piping output to stdout.") def close_output(): pass return sys.stdout, close_output filepath = os.p...
1f4317d5b2628318ca7ee6639782f049d2eef7db
30,700
def filter_labels(a, min_size, max_size=None): """ Remove (set to 0) labeled connected components that are too small or too large. Note: Operates in-place. """ if min_size == 0 and (max_size is None or max_size > np.prod(a.shape)): # shortcut for efficiency return a try: compone...
5754959bd2f404fa0189aee406c08745f236c294
30,701
def mask(bigtiff,profile,out_mask): """ mask a 1 or 3 band image, band by band for memory saving """ if profile['count']==4: bigtiff1 = bigtiff[0,:,:] bigtiff1[out_mask==1] = profile['nodata'] bigtiff[0,:,:] = bigtiff1 del bigtiff1 bigtiff2 = bigtiff[1,:,:] ...
0e31612da8d80f5fb4d8f35a0664708294e98312
30,702
def quadratic_sum(n: int) -> int: """calculate the quadratic num from 1 ~ n""" sum = 0 for n in range(1, n + 1): sum += n ** 2 return sum
e47a3ee49888c85cc06c72c428d983885ed7009f
30,703
def dag_rules(rules, required_keys): """ Serializing dag parameters from variable. Checking for required fields using required_keys :return dict dag_rules. An example of how they should look, in ..._settings.json, "airflow_settings" """ is_exists_rule_keys = all(key in rules.keys() for key in requir...
319096f113ff82c783266d83d8e194badeb7ec7d
30,704
import socket def ip_address(value): """Get IPAddress""" return write_tv(ASN1_IPADDRESS, socket.inet_aton(value))
beb56177436f7a67abbd2627ebf681eef3ed6352
30,705
def _GetUpdatedMilestoneDict(master_bot_pairs, tests): """Gets the milestone_dict with the newest rev. Checks to see which milestone_dict to use (Clank/Chromium), and updates the 'None' to be the newest revision for one of the specified tests. """ masters = set([m.split('/')[0] for m in master_bot_pairs]) ...
d3f8f78bb6aed29d2a7a932b288a84adf22e323b
30,706
def _hrv_nonlinear_poincare_hra(rri, out): """Heart Rate Asymmetry Indices. - Asymmetry of Poincaré plot (or termed as heart rate asymmetry, HRA) - Yan (2017) - Asymmetric properties of long-term and total heart rate variability - Piskorski (2011) """ N = len(rri) - 1 x = rri[:-1] # rri_n, x...
fff7f5c071b64fb44f7e8155a5ddf350a4586517
30,707
def headers(sheet): """Returns the values of the sheet's header row (i.e., the first row).""" return [ stringify_value(h) for h in truncate_row(next(sheet.iter_rows(values_only=True))) ]
26160064a3f0509d343140e3018e96fb1f7b91b4
30,708
def internal_server_error(message='Internal server error'): """500 Internal server error response""" errors = { '_internal': message } return error(500, errors)
d4ed017f6720ae3e62e5d6e66eb4d2cabd2a0775
30,709
def get_model(args, test=False): """ Create computation graph and variables. """ nn_in_size = 513 image = nn.Variable([args.batch_size, 3, nn_in_size, nn_in_size]) label = nn.Variable([args.batch_size, 1, nn_in_size, nn_in_size]) mask = nn.Variable([args.batch_size, 1, nn_in_size, nn_in_si...
9199034f0776e6d291185d130aadd78d7bf11ea0
30,710
import random def post_config(opt): """post_config""" # init fixed parameters opt.noise_amp_init = opt.noise_amp opt.nfc_init = opt.nfc opt.min_nfc_init = opt.min_nfc opt.scale_factor_init = opt.scale_factor opt.out_ = 'TrainedModels/%s/scale_factor=%f/' % (opt.input_name[:-4], opt.scale_f...
b7b7127e560b24a0d8242dfb9912852e2cd33c7d
30,711
import collections def select_device_with_aspects(required_aspects, excluded_aspects=[]): """Selects the root :class:`dpctl.SyclDevice` that has the highest default selector score among devices that have all aspects in the `required_aspects` list, and do not have any aspects in `excluded_aspects` list...
3f34baff8aab39ef88d20c610b203723712823af
30,712
import os def get_block_path(tag, block_number): """ Get the absolute path of a specific block identified by a tag and its unique identifier Args: tag: The tag used to identify the type of data stored in the block block_number: The unique identifier of the block Returns: The absolute path to the block "...
f151a7058efcbb04f30160f0028a6ec0b315f5fe
30,713
def plus(a:int,b:int)->int: """ plus operation :param a: first number :param b: second number :return: a+b """ return a+b
f54224b8f8c0b599b7cd799aba0d291f11c4c16f
30,714
def linear_upsample_3d(inputs, strides=(2, 2, 2), use_bias=False, trainable=False, name='linear_upsample_3d'): """Linear upsampling layer in 3D using strided transpose convolutions. The upsampling kernel size will be...
42613b0aa245f53cc381a1c0b29ee5de67441c5c
30,715
def sample_ingredient(user: User, name: str = "Cinnamon") -> Ingredient: """Create a sample ingredient""" return Ingredient.objects.create(user=user, name=name)
c3ca73ece2c015608f54dd372749364c6d63b595
30,716
def naive_sample_frequency_spectrum(ts, sample_sets, windows=None, mode="site"): """ Naive definition of the generalised site frequency spectrum. """ method_map = { # "site": naive_site_sample_frequency_spectrum, "branch": naive_branch_sample_frequency_spectrum} return method_map[mod...
0aeb561437a521757fe1c884a063592b8ca2eb2e
30,717
from matplotlib.gridspec import GridSpec def show_spectral_sources( sources, observation=None, norm=None, channel_map=None, show_observed=False, show_rendered=False, show_spectra=True, figsize=None, ): """Plot each source individually. The functions provides an more detailed in...
5c0e6af0189848c9264cb3b19ba09b6018ee79aa
30,718
import six import requests import json def make_server_request(request, payload, endpoint, auth=None, method='post'): """ makes a json request to channelstream server endpoint signing the request and sending the payload :param request: :param payload: :param endpoint: :param auth: :return:...
99c1bac6c3f010692f6e4b94b93ea77b4b655fde
30,719
import numpy as np def nan_helpfcn(myarray): """ Helper function to return the locations of Nan values as a boolean array, plus a function to return the index of the array. Code inspired by: http://stackoverflow.com/questions/6518811/interpolate-nan-values-in-a-numpy-array Input: - myarray, 1d ...
b5770e6bdfda85bc71fd954aacc4c31dbbd47f13
30,720
def _get_norm_layer(normalization_type='no_norm', name=None): """Get normlization layer. Args: normalization_type: String. The type of normalization_type, only 'no_norm' and 'layer_norm' are supported. name: Name for the norm layer. Returns: layer norm class. """ if normalization_typ...
8aa307db8c1ea93905cc5adddcec4a04f8718195
30,721
def run_single_camera(cam): """ This function acts as the body of the example; please see NodeMapInfo example for more in-depth comments on setting up cameras. :param cam: Camera to setup and run on. :type cam: CameraPtr :return: True if successful, False otherwise. :rtype: bool """ ...
b7a3df5fb0e44ac4ce293d6ff89d4955d662f482
30,722
import six def all_strs_text(obj): """ PyYAML refuses to load strings as 'unicode' on Python 2 - recurse all over obj and convert every string. """ if isinstance(obj, six.binary_type): return obj.decode('utf-8') elif isinstance(obj, list): return [all_strs_text(x) for x in obj]...
20b27cf809ed7fbf12b30a357d6aecfeeed88461
30,723
async def login_user(credentials: OAuth2PasswordRequestForm = Depends()): """Endpoint for logging user in.""" user = services.authenticate_user(email=credentials.username, password=credentials.password) if not user: raise HTTPException(status_code=401, detail="I...
d8e304b7cf718afce7a61c74ab38769d5695e7f5
30,724
from template import template def javascript(): """ Return javascript library for the Sage Notebook. This is done by reading the template ``notebook_lib.js`` where all of the javascript code is contained and replacing a few of the values specific to the running session. Before the code is re...
70e28b39f5f4a249c8273dd92f493cc172c1d0a5
30,725
import os def load_coedit_data(resource_dir): """Load preprocessed data about edit overlap between users.""" app.logger.info("Loading co-edit data") expected_header = ["user_text", "user_neighbor", "num_pages_overlapped"] with open(os.path.join(resource_dir, "coedit_counts.tsv"), "r") as fin: ...
146a908f42a55ba14e2a2b8cd4bb61b5ef2b17c0
30,726
def fahrenheit2celsius(f: float) -> float: """Utility function to convert from Fahrenheit to Celsius.""" return (f - 32) * 5/9
5161b29998553ad6ff497e698058f330433d90b3
30,727
def loadFireTurnMap(): """load in hard-coded 11x11 fire turn map, then flip so that access is [x][y] to match Board access""" boardSize = 11 fireMapFile = open( "fireTurnMap.txt", "r" ) data = [[int(n) for n in line.split()] for line in fireMapFile] fireMapFile.close() rotated = [[None for j in ...
a22350cf8ab488d719cdbaa0e3900c446b59b6f3
30,728
import itertools def get_param_list(params, mode='grid', n_iter=25): """ Get a list with all the parameter combinations that will be tested for optimization. Parameters ---------- params: dictionary Each key corresponds to a parameter. The values correspond to a list of p...
ed99bdff2a27df05e81f04e0495b60fc845ec5c3
30,729
def _apple_universal_binary_rule_transition_impl(settings, attr): """Rule transition for `apple_universal_binary` supporting forced CPUs.""" forced_cpus = attr.forced_cpus platform_type = attr.platform_type new_settings = dict(settings) # If forced CPUs were given, first we overwrite the existing C...
e672473db5b117102a2147445c0416f3a22b2b2d
30,730
def xml_get_text(_node): """Helper function to get character data from an XML tree""" rc = list() for node in _node.childNodes: if node.nodeType == node.TEXT_NODE: rc.append(node.data) return unquote(''.join(rc))
0b611c0a95707b4220a114c7fe76c4fefd9d1615
30,731
def volume_get_all(context, marker, limit, sort_keys=None, sort_dirs=None, filters=None, offset=None): """Retrieves all volumes. If no sort parameters are specified then the returned volumes are sorted first by the 'created_at' key and then by the 'id' key in descending order. :...
664807482b6e26c6e96f8ec697d7d70a5c53d087
30,732
def merge_multirnn_lstm_state(states, w, b): """ Given two multirnn lstm states, merge them into a new state of the same shape, merged by concatation and then projection Args: state1: the first state to mergem, of shape (s1, s2, s3, ...), each s is of shape LSTMStateTuple(c,...
7ccc6666fafd1e1b6e117dc257598d88777c3e40
30,733
def gen_iocs(indicator_list): """ Generates a list of IOCs from a list of Anomali indicators :param indicator_list: list of Anomali indicators, types ip_address, url, or domain :return: list of IOC objects """ ioc_list = list() for i in indicator_list: pp = process_pattern(i.get('pat...
48bb07cf726f9052abbfc7de59e78f49f4b111d3
30,734
from core.controller.jobcontroller import JobController import logging def run_job(job_id, run_date, user_id, rerun_flag, schedule_id, schedulelog_id, mark_complete=False): """ run the job """ logging.debug('run_job for id: %s', str(job_id)) """ status: job_id, succ...
33b21bc491d9759ab5e5bbf156c7182e546ed386
30,735
import csv def parse_input_specifications() -> dict[str, InputFile]: """ Ingest the input specs file and return a dictionary of the data. """ with open(PATH_INPUT_SPECS, 'r') as f: reader = csv.reader(f) next(reader) input_files = {} for row in reader: if...
fddc4b3ff1e9a45f09a62981fc12e7da1fa4e25c
30,736
import base64 def image_base64(img): """Return image as base64.""" if isinstance(img, str): img = get_thumbnail(img) with BytesIO() as buffer: img.save(buffer, "jpeg") return base64.b64encode(buffer.getvalue()).decode()
9a7cbbf9fd973831875ea0643547fd5abff2aa69
30,737
def read_file(file): """This function reads the raw data file, gets the scanrate and stepsize and then reads the lines according to cycle number. Once it reads the data for one cycle, it calls read_cycle function to denerate a dataframe. It does the same thing for all the cycles and finally returns a di...
8eb59ad8f8b700a0d0c26386644be97aa2417bb7
30,738
import collections import os def data_loader(parent_dir='', dataset_list=('HD1', 'HD2', 'HD3', 'HD4', 'HD5', 'HD6'), min_gap=1, max_gap=4, min_stride=1, max_stride=2, epochs=-1, batch_size=1, ...
a0d96d71c4a37e812f4cd9b81d80283128f0a4d6
30,739
def calculate_performance(data): """Calculates swarm performance using a performance function""" df = pd.DataFrame(data) prev_column = None V = 0 G = 0 C = 0 vcount = 0 gcount = 0 ccount = 0 for column in df: v = calculate_max_speed(df, column, prev_column) g = calculate_vertical_mse(df, column) c = c...
dbf060501991b5408f8d102f35dbe60b34fae0a9
30,740
def ipn(request): """ Webhook handling for Coinbase Commerce """ if request.method == 'POST': request_sig = request.META.get('HTTP_X_CC_WEBHOOK_SIGNATURE', None) ''' # this was done in flask = request.data.decode('utf-8') try: # signature verificatio...
774ad9ebe0f1be9b65c73e90627640f66fe16d4c
30,741
def get_decomposed_entries(structure_type, species): """ Get decomposed entries for mix types Args: structure_type(str): "garnet" or "perovskite" species (dict): species in dictionary. structure_type(str): garnet or perovskite Returns: decompose entries(list): ...
0db24d7be2cacc2c0aed180cf5d31ccde057e358
30,742
import os def create_job_script(m): """ This is the first function that runs when a user initializes a new untargeted workflow """ #setup directories if not os.path.isdir(m['basedir']): os.mkdir(m['basedir']) dirs_to_make = ['job_scripts','logs','intermediate_results','%s_%s'%(m['ba...
0e38443b74e87c243ee1604425ae5f1773165533
30,743
def closest_point(p1, p2, s): """closest point on line segment (p1,p2) to s; could be an endpoint or midspan""" #if the line is a single point, the closest point is the only point if p1==p2: return (0,p1) seg_vector = vector_diff(p2,p1) seg_mag = mag(seg_vector) #print( "seg_ve...
5fbce0ac5b2d87f15b6dd5a146e77b23dba3d743
30,744
def new_name(): """ Returns a new legal identifier in C each time it's called Note: Not thread-safe in its current incarnation >>> name1 = new_name() >>> name2 = new_name() >>> name1 != name2 True """ global _num_names _num_names += 1 return '_id_{}'.format(_num_names)
bd72bfdedc7ccd00e973d9677e116cf5afe07314
30,745
def pollard_brent_f(c, n, x): """Return f(x) = (x^2 + c)%n. Assume c < n. """ x1 = (x * x) % n + c if x1 >= n: x1 -= n assert x1 >= 0 and x1 < n return x1
5037b3feac2f131645fbe6ceb00f0d18417a7c04
30,746
def morphological_transformation(input_dir): """ Performs advanced morphological transformations. Args: input_dir: Input Picture Data Stream. Returns: Picture Data Stream after Rotation Correction Processing. """ raw_image = cv2.imread(input_dir) gray_image = cv2.cvtColor(raw_...
b5db242cd39a71aea570d3f61b4c7a217565aa5d
30,747
import sys def fmt_to_datatype_v3(fmt, shape, array=False): """convert numpy dtype format string to mdf versions 2 and 3 channel data type and size Parameters ---------- fmt : numpy.dtype numpy data type shape : tuple numpy array shape array : bool disambiguate bet...
b63d85663b4f1cf45e176f893980479af9f71383
30,748
import this # noqa: F401 def import_this(**kwargs): """Print the Zen of Python""" # https://stackoverflow.com/a/23794519 zen = io.StringIO() with contextlib.redirect_stdout(zen): text = f"```{zen.getvalue()}```" return text
1a80b384154f4cfa8b71eeb57807b8e9e3fce322
30,749
def getCurrentPane(): """Retrieve the current pane index as an int.""" return int(tget("display-message -p '#P'"))
f7439d407ef618c7d516ad9eed5c925c49639533
30,750
def get_lcc_size(G,seed_nodes): """ return the lcc size """ # getting subgraph that only consists of the black_nodes g = nx.subgraph(G,list(seed_nodes)) if g.number_of_nodes() != 0: # get all components max_CC = max(nx.connected_component_subgraphs(g), key=len) return ...
6582ab76a5b7a178d22592305d134529b327a2ec
30,751
def IsParalogLink(link, cds1, cds2): """sort out ortholog relationships between transcripts of orthologous genes. """ map_a2b = alignlib_lite.makeAlignmentVector() alignlib_lite.AlignmentFormatEmissions( link.mQueryFrom, link.mQueryAli, link.mSbjctFrom, link.mSbjctAli).copy(map_a2b...
012ad1a195c42127a39cabee9f7380c7cb8f6f9b
30,752
from numpy import array, vstack from scipy.spatial import Voronoi def segments(points): """ Return the bounded segments of the Voronoi diagram of the given points. INPUT: - ``points`` -- a list of complex points OUTPUT: A list of pairs ``(p1, p2)``, where ``p1`` and ``p2`` are the endp...
5d4c62455a605dfb09c1009b44e12ecd726e4c84
30,753
def tpu_ordinal_fn(shard_index_in_host, replicas_per_worker): """Return the TPU ordinal associated with a shard.""" return shard_index_in_host % replicas_per_worker
773313750ce78cf5d32776752cb75201450416ba
30,754
import string def replace_example_chapter(path_to_documentation, chapter_lines): """func(path_to_doc._tx, [new_chapter]) -> [regenerated_documentation] Opens the documentation and searches for the text section separated through the global marks START_MARK/END_MARK. Returns the opened file with that secti...
c4bb2285a55b0235d44a2550a3bad5a9d83583ad
30,755
def terminal(board): """ Returns True if game is over, False otherwise. """ if(winner(board)): return True for i in range(3): for j in range(3): if(board[i][j]==EMPTY): return False return True
0dd194c8281539977596779209d59533022ad16c
30,756
from typing import OrderedDict def get_network(layers, phase): """Get structure of the network. Parameters ---------- layers : list list of layers parsed from network parameters phase : int 0 : train 1 : test """ num_layers = len(layers) network = OrderedDict()...
cfbbcc99195a4e81503a89ce80a6d2314c2deb30
30,757
def create_category_hiearchy(cats, categoryType): """A function that creates a dict of the root and subroot categories""" dict_out = {} for key in cats.keys(): name = cats[key]['name'] parent_name = cats[key]['parent']['name'] cat_type = cats[key]['categoryType'] if cat_typ...
f0b19f2a6f56e49855a019a18d9357a31cfaeb2a
30,758
import os def run(event, _context): """ save string API Key as SecureString """ graphql_api_key_key_path = os.environ.get('GRAPHQL_API_KEY_KEY_PATH') print("graphql_api_key_key_path =", graphql_api_key_key_path) graphql_api_key = _get_parameter(graphql_api_key_key_path) if graphql_api_key: ...
4681bb3b5799457bef313bcdf0313575941a025e
30,759
import time def date(): """ Returns the current time formated with HTTP format. @return: `str` """ return time.strftime('%a, %d %b %Y %H:%M:%S GMT')
909f1f31c6c7f0ed03fe0b30785ff454f541a5fc
30,760
def _estimate_gaussian_covariances_tied(resp, X, nk, means, reg_covar): """Estimate the tied covariance matrix. Parameters ---------- resp : array-like of shape (n_samples, n_components) X : array-like of shape (n_samples, n_features) nk : array-like of shape (n_components,) means : arra...
3bf510982698643afd9377e64d8fe569d7626452
30,761
from re import A def rights(value_strategy: SearchStrategy[A] ) -> SearchStrategy[either.Right[A]]: """ Create a search strategy that produces `pfun.either.Right` values Args: value_strategy: search strategy to draw values from Example: >>> rights(integers()).example() ...
867db62f02955bf226109bf1cb8f04d4fb3f578c
30,762
def lpad(col, len, pad): """ Left-pad the string column to width `len` with `pad`. >>> df = spark.createDataFrame([('abcd',)], ['s',]) >>> df.select(lpad(df.s, 6, '#').alias('s')).collect() [Row(s=u'##abcd')] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.lp...
b2a8b01b06166b4fd4ec09b76b634c8b2e231d86
30,763
import torch def get_audio_features(audios_data, audio_tStamp, frameRate, video_length, device='cuda'): """audio feature extraction""" extractor = ResNet50().to(device) output1 = torch.Tensor().to(device) output2 = torch.Tensor().to(device) extractor.eval() patchSize = 224 frameSkip = 2 ...
149f22fe855f52d63ffc2174800a83afb2568246
30,764
import asyncio async def node_watch_profile_report_builder(data_id: str): """ Allows the front-end to update the display information once a profile report builds successfully. Necessary because the profile report entails opening a separate tab. """ time_waited = 0 while time_waited < 600: ...
6cb6552d1a05726e77a0f31e5b3f4625752b2d1b
30,765
def write_report_systemsorted(system, username): """ function that prepares return values and paths """ """ the return values (prefix 'r') are used for the `mkdocs.yml` file they build the key-value-pair for every system """ # return system_id for mkdocs.yml rid = str(system.system_id) ...
f080203b1384277a9c6a0c934758d13674978df0
30,766
def compute_entailment_graph_agreement(graph1, graph2): """ Compute the agreement for the entailment graph: entities, arguments and predicates :param graph1: the first annotator's graph :param graph2: the second annotator's graph :return: """ # Compute the agreement for the entity entailmen...
6479f106df736a6a39149af546593a13ae81d9a2
30,767
import os def main(argv=None): """ Runs the main program. :param argv: The command line arguments. :return: The return code for the program's termination. """ args, ret = parse_cmdline(argv) if ret != GOOD_RET or args is None: return ret kbt = calc_kbt(args.temp) if args.src...
1fd21028373d07eee76aff63b0882c9b139cded8
30,768
def is_outlier(points, threshold=3.5): """ This returns a boolean array with "True" if points are outliers and "False" otherwise. These are the data points with a modified z-score greater than this: # value will be classified as outliers. """ # transform into vectors if len(points.shape) =...
edc28706b37a6c1cfef356f45dd87c076779fe6d
30,769
def hill_climbing_random_restart(problem,restarts=10): """From the initial node, keep choosing the neighbor with highest value, stopping when no neighbor is better. [Figure 4.2]""" # restarts = cantidad de reinicios aleatorios al llegar a un estado inmejorable current = Node(problem.initial) best =...
78846f5d67465c981b712d00da7a0d76bbf152bd
30,770
def ordinal(n): """Converts an integer into its ordinal equivalent. Args: n: number to convert Returns: nth: ordinal respresentation of passed integer """ nth = "%d%s" % (n, "tsnrhtdd"[(n // 10 % 10 != 1) * (n % 10 < 4) * n % 10 :: 4]) return nth
7f438c89a6b0f7adbc42f2eb1e619ca4bf862b4a
30,771
def check_date(date): """check if date string has correct format. Args: date as a string mmddyyyy Returns: a boolean indicating if valid (True) or not (False) """ if len(date) != 8: return False if not date.isdigit(): return False # months are between '01' ~...
8972498d94d459ba48851049780e46b057855d9f
30,772
async def expected_raceplan_individual_sprint_27_contestants( event_individual_sprint: dict, ) -> Raceplan: """Create a mock raceplan object - 27 contestants.""" raceplan = Raceplan(event_id=event_individual_sprint["id"], races=list()) raceplan.id = "390e70d5-0933-4af0-bb53-1d705ba7eb95" raceplan.no...
969cba41b0cdcdd83317cd98a57b437f66981dbe
30,773
def signal_to_m_converter(dataframe, dbm="4(dBm)"): """ This function convert a (beacon)dataframe with signal values from the tracer to the corresponding *m*eter values, depend on dBm power that was used. By default dbm = 4(dBm) """ # extract all different values from dataframe dataframe_uni...
55e58553a8685287a0d07e3c3d2432408e46ba04
30,774
def return_lines_as_list(file): """ :rtype: list of str """ # read lines lines = file.readlines() def strip(string): """ Removes whitespace from beginning and end of string :type string: str """ return string.strip() # Coverts our lines to list ...
69e3d45fa3df107a8852d10e104a543c014a6c79
30,775
def cvInitMatNDHeader(*args): """cvInitMatNDHeader(CvMatND mat, int dims, int type, void data=None) -> CvMatND""" return _cv.cvInitMatNDHeader(*args)
152f49b20a858e7bbb7229d77cdeffa6fd1ed049
30,776
def getObjectInfo(fluiddb, objectId): """ Get information about an object. """ return fluiddb.objects[objectId].get(showAbout=True)
baad59e6585e04a8c2a8cca1df305327b80f3768
30,777
def calculate_logAUC(true_y, predicted_score, FPR_range=(0.001, 0.1)): """ Calculate logAUC in a certain FPR range (default range: [0.001, 0.1]). This was used by previous methods [1] and the reason is that only a small percentage of samples can be selected for experimental tests in consideration of...
fc75fd9a361435f31c4f089e7c6e2976330affd7
30,778
def format_inline(str_, reset='normal'): """Format a string if there is any markup present.""" if const.regex['url'].search(str_): text = slugify(str_.split('[[')[1].split('][')[1].split(']]')[0]) str_ = const.regex['url'].sub(const.styles['url'] + text + const.styles[reset], str_) for key,...
9cd6819bff098051812f23825bcdb61e7305d650
30,779
import logging def procces_data(formatted_input): """ Purpose: Proccess data Args: formatted_input - formatted input data Returns: proccesed_data - processed input """ # TODO logging.info("Processing Data") return formatted_input
d24f6c83cd718d0ea6dd7f2af7228bd7ff1f31e4
30,780
from typing import Dict from typing import Any import codecs import pickle def serialize_values( data_dictionary: Dict[str, Any], data_format: PersistedJobDataFormat ) -> Dict[str, Any]: """ Serializes the `data_dictionary` values to the format specified by `data_format`. Args: data_dictionar...
9dc1116357c2dd50f16bf9b1b1d5eec56ea6b4f7
30,781
def print_level_order(tree): """ prints each level of k-tree on own line input <--- Tree output <--- Prints nodes level by level """ if not isinstance(tree, KTree): raise TypeError('argument must be of type <KTree>') all_strings = [] def recurse(nodelist): nonlocal all...
7bb5d43725dbe351a85792f685ad504ca1e2d263
30,782
def spark_add(): """ReduceByKey with the addition function. :input RDD data: The RDD to convert. :output Any result: The result. """ def inner(data: pyspark.rdd.RDD) -> ReturnType[pyspark.rdd.RDD]: o = data.reduceByKey(lambda a,b: a+b) return ReturnEntry(result=o) return inner
7cab67ac0f6a55911ca3e46612487bbe329b5d6f
30,783
def edit(): """ Allows the user to edit or delete a reservation """ user = db.session.query(models.Rideshare_user).filter(models.Rideshare_user.netid == session['netid']).first() form = forms.EditReservationFactory() reservation = None rideNumber = request.args.get('rideNo') userHasRev=c...
cfed4d98975d4e7abeb7021eba250c4f1e88c641
30,784
def webapp(): """Create a webapp fixture for accessing the site. Just include 'webapp' as an argument to the test method to use. """ # Create a webtest Test App for use testapp = flask.ext.webtest.TestApp(dnstwister.app) testapp.app.debug = True # Clear the cache dnstwister.cache.clear...
8a4ee5abd157ac41ce4d82969e47506b36765cf8
30,785
from typing import Type from pathlib import Path async def study_export( app: web.Application, tmp_dir: str, project_id: str, user_id: int, product_name: str, archive: bool = False, formatter_class: Type[BaseFormatter] = FormatterV2, ) -> Path: """ Generates a folder with all the d...
c07bf3244323ee5a222ad0339631c704ed10c568
30,786
def gen_fileext_type_map(): """ Generate previewed file extension and file type relation map. """ d = {} for filetype in list(PREVIEW_FILEEXT.keys()): for fileext in PREVIEW_FILEEXT.get(filetype): d[fileext] = filetype return d
3ef34884b5fff37fbf20e7e11c87e2f16310a77a
30,787
def umm_fields(item): """Return only the UMM part of the data""" return scom.umm_fields(item)
65bb71ed27612a3f504b7aae771bff69eff85bbe
30,788
def converts_to_message(*args): """Decorator to register a custom NumPy-to-Message handler.""" def decorator(function): for message_type in args: if not issubclass(message_type, Message): raise TypeError() _to_message[message_type] = function return f...
5fdd5875aec2962b1ee19766f08c522200e8ea0a
30,789
def oil_rho_sat( rho0: NDArrayOrFloat, g: NDArrayOrFloat, rg: NDArrayOrFloat, b0: NDArrayOrFloat ) -> NDArrayOrFloat: """Calculate the gas saturated oil density B&W Eq 24 Args: rho0: The oil reference density (g/cc) at 15.6 degC g: The gas specific gravity rg: The Gas-to-Oil ra...
cca2ccc3934dda8e84db03598d56660cd56edc7a
30,790
def astar(array, start, goal): """A* algorithm for pathfinding. It searches for paths excluding diagonal movements. The function is composed by two components, gscore and fscore, as seem below. f(n) = g(n) + h(n) """ neighbors = [(0, 1), (0, -1), (1, 0), (-1, 0)] close_set = set() cam...
6ddc058246d0ac8db2aa90c847eb3d55d29321c7
30,791
def download_jar(req, domain, app_id): """ See ApplicationBase.create_jadjar This is the only view that will actually be called in the process of downloading a complete CommCare.jar build (i.e. over the air to a phone). """ response = HttpResponse(mimetype="application/java-archive") a...
97c963b3dba3a2c95fcf98b784fc31fb778c2c3d
30,792
def cond(addr, condexpr): """ set a condtion breakpoint at addr. """ return setBreakpoint(addr, False, condexpr)
adf2c21ef4dd32b92f546bc70c3009a47e305ee9
30,793
def get_host_credentials(config, hostname): """Get login information for a host `hostip` (ipv4) from marvin's `config` @return the tuple username, password for the host else raise keyerror""" for zone in config.get('zones', []): for pod in zone.get('pods', []): for cluster in pod.get('c...
82651c247c50d3781c8e96038c373bd6c7fba4e6
30,794
def is_flat_dtype(dtype: np.dtype) -> bool: """ Determines whether a numpy dtype object is flat. Checks whether the ``dtype`` just encodes one element or a shape. A dtype can characterise an array of other base types, which can then be embedded as an element of another array. Parameters --...
08c690e66a3c9303926a8d25c45dace6c2b292c7
30,795
def _solarize_impl(pil_img, level): """Applies PIL Solarize to `pil_img`. Translate the image in the vertical direction by `level` number of pixels. Args: pil_img: Image in PIL object. level: Strength of the operation specified as an Integer from [0, `PARAMETER_MAX`]. Returns: A PIL Image...
615650710266b91c6f91d8b93ab26ef5c5081551
30,796
def version_flash(cmd="flash"): """Return the version of flash (as a short string). Parses the output with ``-v``:: $ flash -v | head -n 1 FLASH v1.2.11 It would capture the version from the first line as follows: >>> version_flash() 'v1.2.11' If the command is not on the pa...
87e9fed11f9d3a3206f4e3a983db1dc165fca576
30,797
def initialise_df(*column_names): """ Initialise a pandasdataframe with n column names :param str column_names: N column names :return: Empty pandas dataframe with specified column names """ return pd.DataFrame(columns=column_names)
8561de29cc6a6aee1752a580c6038a84599a25c0
30,798
def _get_reporting_category(context): """Returns the current member reporting category""" member = _get_member(context) return member[TransactionLoops.MEMBER_REPORTING_CATEGORIES][-1]
64ed9fcaf4fd9459789a1225cf4d9dbfddbfdb49
30,799