content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import pickle def evaluate_single_model( model_path, model_index, save_preds_to_db, save_prefix, metrics, k_values, X, y, labeled_indices): """ Evaluate a single model with provided model specifications and data. Arguments: - model_path: path to load the model - model_index: index...
311589284c46d19e04cd04fd36056e1b53c4bb52
3,655,600
import argparse def parse_args ( ) -> argparse.Namespace: """ Parser for cli arguments. Returns: A Namespace containing all parsed data """ # The parser itself parser = argparse.ArgumentParser(add_help=False) parser.description = "Evaluates single choice sheets" # Groups...
0e65705a421734c7c1deda55cc70a9ff9c7bbde3
3,655,601
def sigmoid(x: np.ndarray, derivative: bool = False) -> np.ndarray: """ The sigmoid function which is given by 1/(1+exp(-x)) Where x is a number or np vector. if derivative is True it applied the derivative of the sigmoid function instead. Examples: >>> sigmoid(0) 0.5 >>> abs(sigmo...
7a80b978a9dd8503ba6ec56ce11a5ee9c0564fdb
3,655,602
def create_hierarchy( num_samples, bundle_size, directory_sizes=None, root=".", start_sample_id=0, start_bundle_id=0, address="", n_digits=1, ): """ SampleIndex Hierarchy Factory method. Wraps create_hierarchy_from_max_sample, which is a max_sample-based API, not a numSam...
6d41b995d664eec2c9d6454abfc485c2c4202220
3,655,603
def eval_sysu(distmat, q_pids, g_pids, q_camids, g_camids, max_rank = 20): """Evaluation with sysu metric Key: for each query identity, its gallery images from the same camera view are discarded. "Following the original setting in ite dataset" """ num_q, num_g = distmat.shape if num_g < max_rank: ...
ccf61aa9f91e95cebfd63855aea366cb50de8887
3,655,604
import getpass def espa_login() -> str: """ Get ESPA password using command-line input :return: """ return getpass.getpass("Enter ESPA password: ")
3ba61567d23ba3771effd6f0aa1a4ac504467378
3,655,605
def row_up1_array(row, col): """This function establishes an array that contains the index for the row above each entry""" up1_array = np.zeros((row, col), dtype=np.uint8) for i in range(row): up1_array[i, :] = np.ones(col, dtype = np.uint8) * ((i - 1) % row) return up1_array
19cf1e3ceb9fe174c5cc3c6ba2c336fc58412037
3,655,606
def lcm(a, b): """Return lowest common multiple.""" return a * b // gcd(a, b)
27a7d5af9001015a0aff459af274a45921d2bc94
3,655,607
from typing import Callable def chl_mean_hsl(weights: np.ndarray) -> Callable[[np.ndarray], np.ndarray]: """ return a function that can calculate the channel-wise average of the input picture in HSL color space """ return lambda img: np.average(cv2.cvtColor(img, cv2.COLOR_BGR2HLS), axis=(0, 1), w...
b5e337fb3bee18762e31aef3d666906975305b4b
3,655,608
def cosine_mrl_option(labels, predicts): """For a minibatch of image and sentences embeddings, computes the pairwise contrastive loss""" #batch_size, double_n_emd = tensor.shape(predicts) #res = tensor.split(predicts, [double_n_emd/2, double_n_emd/2], 2, axis=-1) img = l2norm(labels) text = l2norm(...
e103b1b0075438270e79913bb59b1117da09b51f
3,655,609
def escape_cdata(cdata): """Escape a string for an XML CDATA section""" return cdata.replace(']]>', ']]>]]&gt;<![CDATA[')
c38b934b4c357e8c15fd1f3942f84ca3aaab4ee1
3,655,610
import inspect import pprint def _collect_data_for_docstring(func, annotation): """ Collect data to be printed in docstring. The data is collected from custom annotation (dictionary passed as a parameter for the decorator) and standard Python annotations for the parameters (if any). Data from cust...
32a7ac62506dfc04157c613fa781b3d740a95451
3,655,611
def _strip_unbalanced_punctuation(text, is_open_char, is_close_char): """Remove unbalanced punctuation (e.g parentheses or quotes) from text. Removes each opening punctuation character for which it can't find corresponding closing character, and vice versa. It can only handle one type of punctuation ...
db4b8f201e7b01922e6c06086594a8b73677e2a2
3,655,612
def read(fin, alphabet=None): """Read and parse a fasta file. Args: fin -- A stream or file to read alphabet -- The expected alphabet of the data, if given Returns: SeqList -- A list of sequences Raises: ValueError -- If the file is unparsable """ seqs = [s for s...
1ff492ac533a318605569f94ef66036c847b21d5
3,655,613
def get_min_max_value(dfg): """ Gets min and max value assigned to edges in DFG graph Parameters ----------- dfg Directly follows graph Returns ----------- min_value Minimum value in directly follows graph max_value Maximum value in directly follows grap...
17a98350f4e13ec51e72d4357e142ad661e57f54
3,655,614
import os def process_post(category_id, post_details, user): """Check topic is present in Discourse. IF exists then post, otherwise create new topic for category """ error = False error_message = '' # DISCOURSE_DEV_POST_SUFFIX is used to differentiate the same target name from different dev syste...
6634d9f3c302e85c5cb0504cc4474364191a14a8
3,655,615
def vgg_fcn(num_classes=1000, pretrained=False, batch_norm=False, **kwargs): """VGG 16-layer model (configuration "D") Args: num_classes(int): the number of classes at dataset pretrained (bool): If True, returns a model pre-trained on ImageNet batch_norm: if you want to introduce batch n...
73c1e80e0ffc6aff670394d1b1ec5e2b7d21cf06
3,655,616
from typing import Union def apply_heatmap( frame: npt.NDArray[np.uint8], cmap: Union[str, Colormap] = "Pastel1", normalize: bool = True, ) -> npt.NDArray[np.uint8]: """Apply heatmap to an input BGR image. Args: frame (npt.NDArray[np.uint8]) : Input image (BGR). cmap (Unio...
6965420744ab27c7d5d2ebf10c518105d9ba8191
3,655,617
import time def fmt_time(timestamp): """Return ISO formatted time from seconds from epoch.""" if timestamp: return time.strftime('%Y-%m-%dT%H:%M:%S', time.localtime(timestamp)) else: return '-'
c87f1da7b6a3b1b8d8daf7d85a2b0746be58133b
3,655,618
def lislice(iterable, *args): """ (iterable, stop) or (iterable, start, stop[, step]) >>> lislice('ABCDEFG', 2) ['A', 'B'] >>> lislice('ABCDEFG', 2, 4) ['C', 'D'] >>> lislice('ABCDEFG', 2, None) ['C', 'D', 'E', 'F', 'G'] >>> lislice('ABCDEFG', 0, None, 2) ['A', 'C', 'E', 'G'] """...
6c7eb26a9ab5cb913c17f77c2a64929cfc7ebb06
3,655,619
def calculate_transition_cost(number_objs: int, target_storage_class: str) -> float: """ Calculates the cost of transition data from one class to another Args: number_objs: the number of objects that are added on a monthly basis target_storage_class: the storage class the objects will resid...
01ec7d3e7149dadc020ab6f82033a178366c6ebf
3,655,620
import sys def _exceptionwarning(ui): """Produce a warning message for the current active exception""" # For compatibility checking, we discard the portion of the hg # version after the + on the assumption that if a "normal # user" is running a build with a + in it the packager # probably built f...
585e9db21957fdc52bd9d5d80bb977ccc326b6d8
3,655,621
def get_covid(): """This module sends off a covid notification. You can't get covid from this.""" covid_data = covid_handler() covid_content = Markup("Date: " + str(covid_data["date"]) + ",<br/>Country: " + str( covid_data["areaName"]) + ",<br/>New Cases: " + str( covid_data["newCasesByPubli...
0c6e4c8e5df7b7e13212eabe46f8a72a7874fde5
3,655,622
def send_songogram(your_name, artist_first_name, artist_last_name, song_name, number_to_call): """ Function for sending a Sonogram. :param your_name: string containing the person sending the sonogram's name. :param artist_first_name: string containing the musician's first name. :param artist_last_name: ...
84e67f7b8b185817596f0fd0173e4cc989616687
3,655,623
def segm_and_cat(sersic_2d_image): """fixture for segmentation and catalog""" image_mean, image_median, image_stddev = sigma_clipped_stats(sersic_2d_image, sigma=3) threshold = image_stddev * 3 # Define smoothing kernel kernel_size = 3 fwhm = 3 # Min Source size (area) npixels = 4 ** ...
2a6018f7b4c2a1aea946b6744840bd2216352002
3,655,624
from typing import Tuple def break_word_by_trailing_integer(pname_fid: str) -> Tuple[str, str]: """ Splits a word that has a value that is an integer Parameters ---------- pname_fid : str the DVPRELx term (e.g., A(11), NSM(5)) Returns ------- word : str the value not ...
e9b9c85b4225269c94918ce1cc2e746d3c74aa5c
3,655,625
import argparse import os def parse_args(): """ parse command line arguments :return dict: dictionary of parameters """ argparser = argparse.ArgumentParser() # training data argparser.add_argument('--trainfiles', nargs='*', default=['./data/valid.tfrecords'], help='Data file(s) for trai...
12afdc5cfa3acf033d529c6be9765642995946c7
3,655,626
def preprocess_data(image, label, is_training): """CIFAR data preprocessing""" image = tf.image.convert_image_dtype(image, tf.float32) if is_training: crop_padding = 4 image = tf.pad(image, [[crop_padding, crop_padding], [crop_padding, crop_padding], [0, 0]], 'REFLECT') ima...
642f384fbf1aa2f884e64de2edf264890317b258
3,655,627
def load_Counties(): """ Use load_country() instead of this function """ # Get data # Load data using Pandas dfd = { 'positive': reread_csv(csv_data_file_Global['confirmed_US']), 'death': reread_csv(csv_data_file_Global['deaths_US']), } return dfd
098d08f3720b6c6148c51000e6e1512d382adeaf
3,655,628
def extract_parmtop_residue_with_name(filename, resname): """ fixme - update doc Extract residue name and atom name/type mapping from input parmtop. Note: Only one residue must be present in the topology. Parameters ---------- filename: Path Filename of the input parmtop. Retur...
b2fc9ebc44e0ecd2f33108e7878e5f37d4eead2f
3,655,629
from typing import Iterator from typing import Any def issetiterator(object: Iterator[Any]) -> bool: """Returns True or False based on whether the given object is a set iterator. Parameters ---------- object: Any The object to see if it's a set iterator. Returns ------- bool ...
07ecdcc72c62c4ce3d5fb91181cd1bc785d6cb4d
3,655,630
def temporal_discretization(Y, method='ups_downs', kwargs={}): """This function acts as a switcher for temporal discretizations and wraps all the functions which carry out discretization over time of time-series. Parameters ---------- Y : array_like, shape (N, M) the signal of each element ...
98393c838eed156947ccec931477b2011f5951b9
3,655,631
from mpl_toolkits.mplot3d import Axes3D def plotModeScatter( pc , xMode=0, yMode=1, zMode=None, pointLabels=None, nTailLabels=3, classes=None): """ scatter plot mode projections for up to 3 different modes. PointLabels is a list of strings corresponding to each shape. nTailLabels defines number of points that are...
72bc671d9d4fc0fc8df26965fd4d24d91ab51b72
3,655,632
import re def cron_worker(request): """Parse JSON/request arguments and start ingest for a single date export""" request_json = request.get_json(silent=True) request_args = request.args if request_json and 'image' in request_json: image_id = request_json['image'] elif request_args and 'im...
e4fa2bc92ec85d70e8c2ca7967d792686220204b
3,655,633
import math def calculatetm(seq): """ Calculate Tm of a target candidate, nearest neighbor model """ NNlist = chopseq(seq, 2, 1) NNtable = ['AA', 'AC', 'AG', 'AT', 'CA', 'CC', 'CG', 'CT', 'GA', 'GC', 'GG', 'GT', 'TA', 'TC', 'TG', 'TT'] NNendtable = ['A', 'C', 'G', 'T'] NNcount = np.zeros(16) N...
f53c1aa09cd335d603c721fa9922d85e2de0f612
3,655,634
def share_article_to_group(user, base_list_id, article_id, group_id, target_list_id): """ @api {post} /user/list/:id/article/:id/share/group/:id/list/:id Share a article to group list. @apiName Share a article into a group list. @apiGroup Share @apiUse AuthorizationTokenHeader @apiUse Unauthor...
7074c43b9c51fb7959a4e835d3bff493b72980cc
3,655,635
def get_data_shape(X_train, X_test, X_val=None): """ Creates, updates and returns data_dict containing metadata of the dataset """ # Creates data_dict data_dict = {} # Updates data_dict with lenght of training, test, validation sets train_len = len(X_train) test_len = len(X_test) d...
231a334b625d0bfe6aa6e63b79de2b2226b8e684
3,655,636
def setupAnnotations(context): """ set up the annotations if they haven't been set up already. The rest of the functions in here assume that this has already been set up """ annotations = IAnnotations(context) if not FAVBY in annotations: annotations[FAVBY] = PersistentList() r...
f427c8619452d7143a56d4b881422d01a90ba666
3,655,637
def _get_media(media_types): """Helper method to map the media types.""" get_mapped_media = (lambda x: maps.VIRTUAL_MEDIA_TYPES_MAP[x] if x in maps.VIRTUAL_MEDIA_TYPES_MAP else None) return list(map(get_mapped_media, media_types))
4dbbcf87c717fca2e1890a5258df023ebbca31c5
3,655,638
import ctypes def get_int_property(device_t, property): """ Search the given device for the specified string property @param device_t Device to search @param property String to search for. @return Python string containing the value, or None if not found. """ key = cf.CFStringCreateWithCString...
75bc08117bb838e8070d3ea4d5134dfbeec9576c
3,655,639
def _get_unique_barcode_ids(pb_index, isoseq_mode=False): """ Get a list of sorted, unique fw/rev barcode indices from an index object. """ bc_sel = (pb_index.bcForward != -1) & (pb_index.bcReverse != -1) bcFw = pb_index.bcForward[bc_sel] bcRev = pb_index.bcReverse[bc_sel] bc_ids = sorted(li...
bdfb386d26415a7b3f9f16661d83a38a63958ad0
3,655,640
def clean_logs(test_yaml, args): """Remove the test log files on each test host. Args: test_yaml (str): yaml file containing host names args (argparse.Namespace): command line arguments for this program """ # Use the default server yaml and then the test yaml to update the default #...
229f34615dc9a6f7ab9c484b9585151814656a77
3,655,641
def call_posterior_haplotypes(posteriors, threshold=0.01): """Call haplotype alleles for VCF output from a population of genotype posterior distributions. Parameters ---------- posteriors : list, PosteriorGenotypeDistribution A list of individual genotype posteriors. threshold : float ...
46c26eb38c693d979ea4234af606b3b07ad1e75e
3,655,642
def to_linprog(x, y, xy_dist) -> LinProg: """ Parameters ---------- x : ndarray 1 - dimensional array of weights y : ndarray 1 - dimensional array of weights xy_dist : ndarray 2 - dimensional array containing distances between x and y density coordinates Returns ...
e792e6b701216cb232dcb823c6d32386d87e3be8
3,655,643
def get_discorded_labels(): """ Get videos with citizen discorded labels Partial labels will only be set by citizens """ return get_video_labels(discorded_labels)
6f3cbaf09b43956d14d9abf5cf4e77734c152d2f
3,655,644
def set_common_tags(span: object, result: object): """Function used to set a series of common tags to a span object""" if not isinstance(result, dict): return span for key, val in result.items(): if key.lower() in common_tags: span.set_tag(key, val) re...
365230fb6a69b94684aeac25d14fa4275c1549f8
3,655,645
import time def local_timezone(): """ Returns: (str): Name of current local timezone """ try: return time.tzname[0] except (IndexError, TypeError): return ""
c97c11582b27d8aa0205555535616d6ea11775b9
3,655,646
import getpass def ask_credentials(): """Interactive function asking the user for ASF credentials :return: tuple of username and password :rtype: tuple """ # SciHub account details (will be asked by execution) print( " If you do not have a ASF/NASA Earthdata user account" " g...
a601a460b3aeddf9939f3acf267e58fdaf9ed7cd
3,655,647
def lab2lch(lab): """CIE-LAB to CIE-LCH color space conversion. LCH is the cylindrical representation of the LAB (Cartesian) colorspace Parameters ---------- lab : array_like The N-D image in CIE-LAB format. The last (``N+1``-th) dimension must have at least 3 elements, correspondi...
711d23d452413d738af162ac5b9e3f34c1a4eab6
3,655,648
def get_valid_principal_commitments(principal_id=None, consumer_id=None): """ Returns the list of valid commitments for the specified principal (org or actor. If optional consumer_id (actor) is supplied, then filtered by consumer_id """ log.debug("Finding commitments for principal: %s", principal_id...
2e86f491acb583f349aec16c613552068b01de6f
3,655,649
def callattice(twotheta, energy_kev=17.794, hkl=(1, 0, 0)): """ Calculate cubic lattice parameter, a from reflection two-theta :param twotheta: Bragg angle, deg :param energy_kev: energy in keV :param hkl: reflection (cubic only :return: float, lattice contant """ qmag = calqmag(twotheta...
2718e4c44e08f5038ff4119cf477775ed9f3a678
3,655,650
def reset_password( *, db: Session = Depends(get_db), current_user: User = Depends(get_current_active_user), background_tasks: BackgroundTasks, ): """reset current user password""" email = current_user.email # send confirm email if settings.EMAILS_ENABLED and email: ...
1f292188b3927c26eb41634acb7fb99e398e94b6
3,655,651
def rule_valid_histone_target(attr): """ { "applies" : ["ChIP-Seq", "experiment_target_histone"], "description" : "'experiment_target_histone' attributes must be 'NA' only for ChIP-Seq Input" } """ histone = attr.get('experiment_target_histone', [''])[0] if attr.get('experiment_type', [""])[0].lo...
0a10f09c6b9e50cf01583d0c803e5112629e503b
3,655,652
def extend(curve: CustomCurve, deg): """returns curve over the deg-th relative extension""" E = curve.EC q = curve.q K = curve.field if q % 2 != 0: R = K["x"] pol = R.irreducible_element(deg) Fext = GF(q ** deg, name="z", modulus=pol) return E.base_extend(Fext) ch...
8d750b40d91d10d6b51c75765e2083300d7dccf6
3,655,653
def flatten3D(inputs: tf.Tensor) -> tf.Tensor: """ Flatten the given ``inputs`` tensor to 3 dimensions. :param inputs: >=3d tensor to be flattened :return: 3d flatten tensor """ shape = inputs.get_shape().as_list() if len(shape) == 3: return inputs assert len(shape) > 3 retu...
11c9c7f7ab955594401468c64323f8f3a52dbe81
3,655,654
def get_classes(dataset): """Get class names of a dataset.""" alias2name = {} for name, aliases in dataset_aliases.items(): for alias in aliases: alias2name[alias] = name if mmcv.is_str(dataset): if dataset in alias2name: labels = eval(alias2name[dataset] + '_cla...
d307793a85deef3be239d7dbff746c7c9643dc1b
3,655,655
def split_exclude_string(people): """ Function to split a given text of persons' name who wants to exclude with comma separated for each name e.g. ``Konrad, Titipat`` """ people = people.replace('Mentor: ', '').replace('Lab-mates: ', '').replace('\r\n', ',').replace(';', ',') people_list = peop...
5748a52039548175923f53384474f40ac8fb5e38
3,655,656
from datetime import datetime def now(tz=DEFAULT_TZ): """ Get the current datetime. :param tz: The preferred time-zone, defaults to DEFAULT_TZ :type tz: TzInfo (or similar pytz time-zone) :return: A time-zone aware datetime set to now :rtype: datetime """ return datetime.now(tz=tz)
1dcdd78898b726576f69f01cb9f4bfe3aeaef29d
3,655,657
def peek_with_kwargs(init, args=[], permissive=False): """ Make datatypes passing keyworded arguments to the constructor. This is a factory function; returns the actual `peek` routine. Arguments: init (callable): type constructor. args (iterable): arguments NOT to be keyworded; order...
d06df21ab439da1cacb52befa6c619f1efa23d1a
3,655,658
def idc_asset_manage(request,aid=None,action=None): """ Manage IDC """ if request.user.has_perms(['asset.view_asset', 'asset.edit_asset']): page_name = '' if aid: idc_list = get_object_or_404(IdcAsset, pk=aid) if action == 'edit': page_name = '编辑ID...
7fbf1729c87e9e9921f19cf5cba2810879958848
3,655,659
import os import json import time def set_justspeaklasttime(speackdata): """ Adds a warning to user """ data_file_path = os.getcwd() + '/just_speack_data.json' if not os.path.exists(data_file_path): with open(data_file_path, 'w', encoding='UTF-8') as data_file: data_file.write...
2420ef414eff4bb9b2ec36d055152cd1ce3afdf3
3,655,660
def get_detected_column_types(df): """ Get data type of each columns ('DATETIME', 'NUMERIC' or 'STRING') Parameters: df (df): pandas dataframe Returns df (df): dataframe that all datatypes are converted (df) """ assert isinstance(df, pd.DataFrame), 'Parameter must be DataFrame' ...
23647127d0e5a125e06fb1932e74ba5f9c885ded
3,655,661
def distance(coords): """Calculates the distance of a path between multiple points Arguments: coords -- List of coordinates, e.g. [(0,0), (1,1)] Returns: Total distance as a float """ distance = 0 for p1, p2 in zip(coords[:-1], coords[1:]): distance += ((p2[0] - p1[0]) ** 2...
9c6088b740f42b839d4aa482c276fe4cc5dc8114
3,655,662
def roll_dice(dicenum, dicetype, modifier=None, conditional=None, return_tuple=False): """ This is a standard dice roller. Args: dicenum (int): Number of dice to roll (the result to be added). dicetype (int): Number of sides of the dice to be rolled. modifier (tuple): A tuple `(operator, val...
acbc97e4b7720129788c8c5d5d9a1d51936d9dc1
3,655,663
import math def build_central_hierarchical_histogram_computation( lower_bound: float, upper_bound: float, num_bins: int, arity: int = 2, max_records_per_user: int = 1, epsilon: float = 1, delta: float = 1e-5, secure_sum: bool = False): """Create the tff federated computation for cent...
fcd35bc2df5f61174d00079638dda0c04c1490ff
3,655,664
def initialise_halo_params(): """Initialise the basic parameters needed to simulate a forming Dark matter halo. Args: None Returns: G: gravitational constant. epsilon: softening parameter. limit: width of the simulated universe. radius: simulated radius of each particle ...
ee3311fd17a40e8658f11d2ddf98d0ff8eb27a6d
3,655,665
def read_data(image_paths, label_list, image_size, batch_size, max_nrof_epochs, num_threads, shuffle, random_flip, random_brightness, random_contrast): """ Creates Tensorflow Queue to batch load images. Applies transformations to images as they are loaded. :param random_brightness: :param...
2bbb7f1be38764634e198f83b82fafb730ec3afa
3,655,666
def reorder_matrix (m, d) : """ Reorder similarity matrix : put species in same cluster together. INPUT: m - similarity matrix d - medoid dictionary : {medoid : [list of species index in cluster]} OUTPUT : m in new order new_order - order of species indexes in matrix """ new_or...
5d203ec6f61afe869008fa6749d18946f128ac87
3,655,667
import subprocess def extract_sound(video_filename): """Given the name of a video, extract the sound to a .wav file, and return the filename of the new file.""" # Generate a filename for the temporary audio file with NamedTemporaryFile(suffix='.wav') as tf: wave_filename = tf.name # Extract ...
25551239d084ee7240a341394bb20b44a150c907
3,655,668
def reward_penalized_log_p(mol): """ Reward that consists of log p penalized by SA and # long cycles, as described in (Kusner et al. 2017). Scores are normalized based on the statistics of 250k_rndm_zinc_drugs_clean.smi dataset :param mol: rdkit mol object :return: float """ # normalizat...
e3e5ebfabf31e4980dc6f3b6c998a08444ce9851
3,655,669
def loadmat(filename, variable_names=None): """ load mat file from h5py files :param filename: mat filename :param variable_names: list of variable names that should be loaded :return: dictionary of loaded data """ data = {} matfile = h5py.File(filename, 'r') if variable_names is N...
3b9183968fba56d57c705bce0ec440c630cc0031
3,655,670
def date_start_search(line): """予定開始の日付を検出し,strで返す.""" # 全角スペース zen_space = ' ' # 全角0 zen_zero = '0' nichi = '日' dollar = '$' # 全角スペースを0に置き換えることで無理やり対応 line = line.replace(zen_space, zen_zero) index = line.find(nichi) # 日と曜日の位置関係から誤表記を訂正 index_first_dollar = line.find(dol...
f89e332a2a0031acdf6fa443ea9752e528674b32
3,655,671
def train_sub1(sess, x, y, bbox_preds, x_sub, y_sub, nb_classes, nb_epochs_s, batch_size, learning_rate, data_aug, lmbda, aug_batch_size, rng, img_rows=48, img_cols=48, nchannels=3): """ This function creates the substitute by alternatively augmenting the training d...
a5433f78c60f6beec14a6d4fd414d45dc8c65999
3,655,672
def divideArray(array, factor): """Dzielimy tablice na #factor tablic, kazda podtablica ma tyle samo elem oprocz ostatniej""" factor = min(factor, len(array)) length = floor(len(array) * 1.0 / factor) res = [] for i in range(factor - 1): res = res + list([array[i * length:(i + 1) * length]]...
d94441e6036e78f9b541b9d170d03681740c81d3
3,655,673
def argMax(scores): """ Returns the key with the highest value. """ if len(scores) == 0: return None all = scores.items() values = [x[1] for x in all] maxIndex = values.index(max(values)) return all[maxIndex][0]
9310988a0f8aa1279882d060ade7febdc102b0c5
3,655,674
def rotateright(arr,k)->list: """ Rotate the array right side k number of times. """ temp=a[0] poi=0 for i in range(len(arr)): for j in range(0,k): poi+=1 if(poi==len(arr)): poi=0 temp1=arr[poi] arr[poi]=temp temp=temp1 return arr
7d303f5b57cb10a1a28f5c78ffa848d2a9cb593f
3,655,675
import os def get_video_chunk_path(instance, filename): """ Get path to store video chunk the path will be of format : project_id/chunks/chunk_no.mp3 """ if (not instance.project_id) and (not instance.chunk_no): raise ValidationError('Invalid Project ID') return os.path.join(instance....
c917529699a2bafdf9124eca81b23c5971a97a50
3,655,676
def get_ratio(numerator, denominator): """Get ratio from numerator and denominator.""" return ( 0 if not denominator else round(float(numerator or 0) / float(denominator), 2) )
e51a860292d54d2e44909ad878d0b1d8e66c37c2
3,655,677
import io def create_app(): """ Create a Flask application for face alignment Returns: flask.Flask -> Flask application """ app = Flask(__name__) model = setup_model() app.config.from_mapping(MODEL=model) @app.route("/", methods=["GET"]) def howto(): instruction ...
d9a5d59f64dc9227949bbe73065d18bcc8142b9d
3,655,678
def grad_clip(x:Tensor) -> Tensor: """ Clips too big and too small gradients. Example:: grad = grad_clip(grad) Args: x(:obj:`Tensor`): Gradient with too large or small values Returns: :obj:`Tensor`: Cliped Gradient """ x[x>5] = 5 x[x<-5] = -5 ...
5c07c4432fda16d06bda8569aca34cbbaf45b076
3,655,679
def unfold_kernel(kernel): """ In pytorch format, kernel is stored as [out_channel, in_channel, height, width] Unfold kernel into a 2-dimension weights: [height * width * in_channel, out_channel] :param kernel: numpy ndarray :return: """ k_shape = kernel.shape weight = np.zeros([k_shape[...
7106ead9b4953024731d918fb3c356b056bca156
3,655,680
def _parse_polyline_locations(locations, max_n_locations): """Parse and validate locations in Google polyline format. The "locations" argument of the query should be a string of ascii characters above 63. Args: locations: The location query string. max_n_locations: The max allowable numbe...
3ebff7a35c86bad5986ee87c194dd9128936abb0
3,655,681
def dense(data, weight, bias=None, out_dtype=None): """The default implementation of dense in topi. Parameters ---------- data : tvm.Tensor 2-D with shape [batch, in_dim] weight : tvm.Tensor 2-D with shape [out_dim, in_dim] bias : tvm.Tensor, optional 1-D with shape [o...
ac5550f901d1a7c94fee4b8e65fa9957d4b2ff78
3,655,682
from typing import Union from re import T from typing import Any import inspect from enum import Enum from typing import Type from typing import OrderedDict import warnings def choice(*choices: T, default: Union[T, _MISSING_TYPE] = MISSING, **kwargs: Any) -> T: """Makes a field which can be chosen from the set of...
1316b6541d4c9dd0b03ddbbdbb41eee906c12aa1
3,655,683
def modulelink(module, baseurl=''): """Hyperlink to a module, either locally or on python.org""" if module+'.py' not in local_files: baseurl = 'http://www.python.org/doc/current/lib/module-' return link(baseurl+module+'.html', module)
b907d013b25570d062d49314bbbab637aeb4ffec
3,655,684
from typing import Optional from typing import Callable import inspect def add_reference( *, short_purpose: str, reference: Optional[str] = None, doi: Optional[str] = None ) -> Callable: """Decorator to link a reference to a function or method. Acts as a marker in code where particular alogrithms/data/.....
8e1a4c6425213779edabdb0879eacbb44d4e479a
3,655,685
import logging import subprocess def get_capital_ptd_act(): """Get chart of accounts from shared drive.""" logging.info('Retrieving latest CIP project to date') command = "smbclient //ad.sannet.gov/dfs " \ + "--user={adname}%{adpass} -W ad -c " \ + "'prompt OFF;" \ + " cd \"FMGT-Sh...
6d6c56da0216a063fd2b7b1f3f30c2a3c390f713
3,655,686
def eval_curvature(poly, x_vals): """ This function returns a vector with the curvature based on path defined by `poly` evaluated on distance vector `x_vals` """ # https://en.wikipedia.org/wiki/Curvature# Local_expressions def curvature(x): a = abs(2 * poly[1] + 6 * poly[0] * x) / (1 + (3 * poly[0] * x...
0e0e04b7c49b0cdfaa0658df23816d61ac19141c
3,655,687
import subprocess def calculate_folder_size(path, _type="mb") -> float: """Return the size of the given path in MB, bytes if wanted""" p1 = subprocess.Popen(["du", "-sb", path], stdout=subprocess.PIPE) p2 = subprocess.Popen(["awk", "{print $1}"], stdin=p1.stdout, stdout=subprocess.PIPE) p1.stdout.clos...
cad7441e4f5a5f4c95eaecd6b2a5df77989b3737
3,655,688
def templates(): """Return all of the templates and settings.""" return settings
6cf1c151f2e0798e1b26002c29db898bcd3c42cf
3,655,689
def get_semitones(interval_tuplet): """ Takes an interval tuplet of the form returned by get_interval() Returns an int representing the semitones within the interval. """ return mintervals.semitones_from_shorthand(interval_tuplet[0]) + 12*interval_tuplet[1]
179f3894da3607b4fd4aa7915ec5e9c38fcdc592
3,655,690
import numpy def svds(a, k=6, *, ncv=None, tol=0, which='LM', maxiter=None, return_singular_vectors=True): """Finds the largest ``k`` singular values/vectors for a sparse matrix. Args: a (cupy.ndarray or cupyx.scipy.sparse.csr_matrix): A real or complex array with dimension ``(m,...
9a96fc2fbca100a53ba81f609a58fc0934b5c524
3,655,691
def register_mongodb(app: Flask) -> Flask: """Instantiates database and initializes collections.""" config = app.config # Instantiate PyMongo client mongo = create_mongo_client(app=app, config=config) # Add database db = mongo.db[get_conf(config, "database", "name")] # Add database collec...
6b5bd3f5694470b3ba7dbbf94bacb9beb8ee55cd
3,655,692
def look(table, limit=0, vrepr=None, index_header=None, style=None, truncate=None, width=None): """ Format a portion of the table as text for inspection in an interactive session. E.g.:: >>> import petl as etl >>> table1 = [['foo', 'bar'], ... ['a', 1], .....
356d6fb1f0afe0f8812e460b8ee3b13f7c4ded4b
3,655,693
def refresh_devices(config, cache_path): """Refresh devices from configuration received""" global DEBUG, m_devices, Device_Cache if DEBUG: print("DEBUG: Refreshing device database") print_progress("Refresh devices") try: m_devices = config['devices'] except: print("ERROR: No devi...
650b174689777dc5da6f10b2d8b0715432541f9c
3,655,694
def warn_vars_naming_style(messages, line, style): """ Check whether varibales and function argumens fit the naming rule.""" naming_style_name = style.Get('CHECK_VAR_NAMING_STYLE') if not naming_style_name: return def is_expr(uwl): return (uwl.tokens and _find_parent(uw...
4b8d4cf72395d66ea80f5fbd364cdd47973bb332
3,655,695
import json def validate_schema(path, data, schema): """ Warns and returns the number of errors relating to JSON Schema validation. Uses the `jsonschema <https://python-jsonschema.readthedocs.io/>`__ module. :param object schema: the metaschema against which to validate :returns: the number of e...
abd6a2a05021586da41fd597eb4137d706c08b41
3,655,696
import os def class_dict(base_module, node): """class_dict(base_module, node) -> dict Returns the class dictionary for the module represented by node and with base class base_module""" class_dict_ = {} def update_dict(name, callable_): if class_dict_.has_key(name): class_dict_...
96a156b4eb5ac3342131f41d85070f7cfe1aea53
3,655,697
def get_playlist_decreasing_popularity(): """This function is used to return playlists in decreasing popularity""" all_ = PlaylistPopularityPrefixed.objects.all() results = [{"playlist_name": obj.playlist_name, "popularity": obj.played} for obj in all_] return results
45c8bb79af32cba58282910d1841611bc7f42d84
3,655,698
from typing import Any def validate_numeric_scalar(var: Any) -> bool: """Evaluates whether an argument is a single numeric value. Args: var: the input argument to validate Returns: var: the value if it passes validation Raises: AssertionError: `var` was not numeric. """ ...
4db95a31021fd6c8ab0c31d9077a12fa5edd580b
3,655,699