content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def getContentType(the_type): """ Get the content type based on the type name which is in settings :param the_type: :return: """ if the_type not in settings.XGDS_MAP_SERVER_JS_MAP: return None the_model_name = settings.XGDS_MAP_SERVER_JS_MAP[the_type]['model'] splits = the_model...
25031eb0dce8fe7828f94bdbc99d5c574f0e5ea6
3,655,565
import scipy import math import numpy def calculateGravityAcceleration(stateVec, epoch, useGeoid): """ Calculate the acceleration due to gravtiy acting on the satellite at a given state (3 positions and 3 velocities). Ignore satellite's mass, i.e. use a restricted two-body problem. Arguments ...
a2ea0ff1c8feb9f0a678911130e3ca6e96838b7c
3,655,566
import math def points_on_line(r0, r1, spacing): """ Coordinates of points spaced `spacing` apart between points `r0` and `r1`. The dimensionality is inferred from the length of the tuples `r0` and `r1`, while the specified `s...
eb2795cba55566823632c75b7a72f34731b5e36e
3,655,567
def index() -> Response: """ Return application index. """ return APP.send_static_file("index.html")
37d299ec548fe4f83d8f55f063e3bf9f5fb64c4e
3,655,568
def compare_files(og_maxima,new_maxima, compare_file, until=100, divisor=1000): """ given input of the maxima of a graph, compare it to the maxima from data100.txt maxima will be a series of x,y coordinates corresponding to the x,y values of a maximum from a file. First see if there is a maxima with t...
86fe2ffd02785d41284b8edfef44d0dc0e097c90
3,655,569
import _datetime def parseDatetimetz(string, local=True): """Parse the given string using :func:`parse`. Return a :class:`datetime.datetime` instance. """ y, mo, d, h, m, s, tz = parse(string, local) s, micro = divmod(s, 1.0) micro = round(micro * 1000000) if tz: offset = _tzoffse...
ce95f42f568b50ffcdc0084dc659a1d5fd0233ff
3,655,570
def median_ratio_flux(spec, smask, ispec, iref, nsig=3., niter=5, **kwargs): """ Calculate the median ratio between two spectra Parameters ---------- spec smask: True = Good, False = Bad ispec iref nsig niter kwargs Returns ------- med_scale : float Medi...
28872a548ce7569f17f155242aaf4377bf0c1b63
3,655,571
def get_tags_from_event(): """List of tags Arguments: event {dict} -- Lambda event payload Returns: list -- List of AWS tags for use in a CFT """ return [ { "Key": "OwnerContact", "Value": request_event['OwnerContact'] } ]
e7a0f7da62a4904dbfb716c57b6811053aff3497
3,655,572
from typing import List def _verify(symbol_table: SymbolTable, ontology: _hierarchy.Ontology) -> List[Error]: """Perform a battery of checks on the consistency of ``symbol_table``.""" errors = _verify_there_are_no_duplicate_symbol_names(symbol_table=symbol_table) if len(errors) > 0: return errors...
da9dd12f01107a0c0ea1a8b2df1aa2fb543391ab
3,655,573
def gsl_eigen_symmv_alloc(*args, **kwargs): """gsl_eigen_symmv_alloc(size_t n) -> gsl_eigen_symmv_workspace""" return _gslwrap.gsl_eigen_symmv_alloc(*args, **kwargs)
54384bfa9787b9a337ad3b9e2d9ea211769238d4
3,655,574
def add_poll_answers(owner, option): """ Add poll answer object. Matching user and option is considered same. :param owner: User object. :param option: Chosen poll option. :return: Poll answer object, Boolean (true, if created). """ ''' owner = models.ForeignKey(User, related_name='poll_...
ac667fbfb47aeb7d2450a3d698b0b678c3bdfdbc
3,655,575
def calculate_rrfdi ( red_filename, nir_filename ): """ A function to calculate the Normalised Difference Vegetation Index from red and near infrarred reflectances. The reflectance data ought to be present on two different files, specified by the varaibles `red_filename` and `nir_filename`. The file...
3b8f4d7eadceb38b7f874bfe0a56827f7a8aab09
3,655,576
import re def strip_price(header_list): """input a list of tag-type values and return list of strings with surrounding html characters removed""" match_obs = [] regex = '\$(((\d+).\d+)|(\d+))' string_list = []#['' for item in range(len(header_list))] for item in range(len(header_list)): ...
7b3d90416e44f8aa61ababc0e7b68f82ae754413
3,655,579
import functools def module(input, output, version): """A decorator which turn a function into a module""" def decorator(f): class Wrapper(Module): def __init__(self): super().__init__(input, output, version) @property def name(self): ...
b7d5afcaa8fa52411024f84f979891d19ccf60c0
3,655,580
def compile_modules_to_ir( result: BuildResult, mapper: genops.Mapper, compiler_options: CompilerOptions, errors: Errors, ) -> ModuleIRs: """Compile a collection of modules into ModuleIRs. The modules to compile are specified as part of mapper's group_map. Returns the IR of the modules. ...
e2ea8a87a1ed2450e4c8ed99c7ca8a3142568f45
3,655,581
def minutes_to_restarttime(minutes) : """ converts an int meaning Minutes after midnight into a restartTime string understood by the bos command """ if minutes == -1 : return "never" pod = "am" if minutes > 12*60 : pod = "pm" minutes -= 12*60 time = "%d:%02d %s"...
6d7807cebb7a474553dda8eadfd27e5ce7b2a657
3,655,582
import tqdm def ccm_test(x, y,emb_dim = "auto", l_0 = "auto", l_1 = "auto", tau=1, n=10,mean_num = 10,max_dim = 10): """ estimate x from y to judge x->y cause :param x: :param y: :param l_0: :param l_1: :param emb_dim: :param tau: :param n: :return: """ if em...
c03a05e62df36910ea05e361c9683b60befc1b9c
3,655,583
def make_indiv_spacing(subject, ave_subject, template_spacing, subjects_dir): """ Identifies the suiting grid space difference of a subject's volume source space to a template's volume source space, before a planned morphing takes place. Parameters: ----------- subject : str Sub...
cbe5120093fdf78913c2386820d3388aca0724d1
3,655,584
def sqlpool_blob_auditing_policy_update( cmd, instance, state=None, storage_account=None, storage_endpoint=None, storage_account_access_key=None, storage_account_subscription_id=None, is_storage_secondary_key_in_use=None, retention_days=None, ...
e99013545172eb03ad5dddeefdb0b36b7bb2edd7
3,655,585
def format_search_filter(model_fields): """ Creates an LDAP search filter for the given set of model fields. """ ldap_fields = convert_model_fields_to_ldap_fields(model_fields); ldap_fields["objectClass"] = settings.LDAP_AUTH_OBJECT_CLASS search_filters = import_func(settings.LDAP_AUTH_FORMA...
b6c5c17b566c583a07ef5e9f3ec61cb868f6f8ab
3,655,587
def normalize_img(img): """ normalize image (caffe model definition compatible) input: opencv numpy array image (h, w, c) output: dnn input array (c, h, w) """ scale = 1.0 mean = [104,117,123] img = img.astype(np.float32) img = img * scale img -= mean img = np.transpose(img, ...
dac9ec8c942d70fb98f0b0989e9643f80dde5448
3,655,589
from typing import List from typing import Any def pages(lst: List[Any], n: int, title: str, *, fmt: str = "```%s```", sep: str = "\n") -> List[discord.Embed]: # noinspection GrazieInspection """ Paginates a list into embeds to use with :class:disputils.BotEmbedPaginator :param lst: the list t...
f8d9471f2d254b63754128a2e2762520f858edbd
3,655,590
import re def Substitute_Percent(sentence): """ Substitutes percents with special token """ sentence = re.sub(r'''(?<![^\s"'[(])[+-]?[.,;]?(\d+[.,;']?)+%(?![^\s.,;!?'")\]])''', ' @percent@ ', sentence) return sentence
61bc6970af09703ef018bfcc9378393241ae21ed
3,655,591
def ready_df1(df): """ This function prepares the dataframe for EDA. """ df = remove_columns(df, columns=[ 'nitrogen_dioxide', 'nitrogen_dioxide_aqi', 'sulfur_dioxide', 'sulfur_dioxide_aqi',...
3776c571d3eabb39ce27017ac1481e2bd469f68c
3,655,592
def _wrap(func, args, flip=True): """Return partial function with flipped args if flip=True :param function func: Any function :param args args: Function arguments :param bool flip: If true reverse order of arguments. :return: Returns function :rtype: function """ @wraps(func) def ...
9ac5a814840f821260d46df64b60cd6d71185dbb
3,655,593
def compute_kkt_optimality(g, on_bound): """Compute the maximum violation of KKT conditions.""" g_kkt = g * on_bound free_set = on_bound == 0 g_kkt[free_set] = np.abs(g[free_set]) return np.max(g_kkt)
216cf110d64d1fd8ec89c0359ebaa9b4e4dcc773
3,655,594
def replace_cipd_revision(file_path, old_revision, new_revision): """Replaces cipd revision strings in file. Args: file_path: Path to file. old_revision: Old cipd revision to be replaced. new_revision: New cipd revision to use as replacement. Returns: Number of replaced occurrences. Raises: ...
f429e74f0dd7180ab4bf90d662f8042b958b81f8
3,655,595
def spectral_derivs_plot(spec_der, contrast=0.1, ax=None, freq_range=None, fft_step=None, fft_size=None): """ Plot the spectral derivatives of a song in a grey scale. spec_der - The spectral derivatives of the song (computed with `spectral_derivs`) or the song itself...
5b683d8c49e9bad2fd1fa029af6bc5660bc0e936
3,655,596
from operator import add from operator import sub def scale_center(pnt, fac, center): """scale point in relation to a center""" return add(scale(sub(pnt, center), fac), center)
f69ca54e25d5eb8008b8f08c40500f236005e093
3,655,597
def gopherize_feed(feed_url, timestamp=False, plug=True): """Return a gophermap string for the feed at feed_url.""" return gopherize_feed_object(feedparser.parse(feed_url), timestamp, plug)
aaf4d35044c873e7d0f1a43c4d001ebe5e30714b
3,655,598
def first_sunday_of_month(datetime: pendulum.DateTime) -> pendulum.DateTime: """Get the first Sunday of the month based on a given datetime. :param datetime: the datetime. :return: the first Sunday of the month. """ return datetime.start_of("month").first_of("month", day_of_week=7)
88c517d1d38785c0d8f9c0f79f3d34199dfceb1e
3,655,599
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
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
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
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
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
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
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
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 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 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 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 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
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
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
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