content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def _is_test_file(filesystem, dirname, filename): """Return true if the filename points to a test file.""" return (_has_supported_extension(filesystem, filename) and not is_reference_html_file(filename))
ba161818a6f2497e1122519945f255d56488f231
3,955
def kitchen_door_device() -> Service: """Build the kitchen door device.""" transitions: TransitionFunction = { "unique": { "open_door_kitchen": "unique", "close_door_kitchen": "unique", }, } final_states = {"unique"} initial_state = "unique" return build_d...
700a1d92087ac91f5311b4c55380f1a6f18860b4
3,956
import http def sql_connection_delete( request: http.HttpRequest, pk: int ) -> http.JsonResponse: """AJAX processor for the delete SQL connection operation. :param request: AJAX request :param pk: primary key for the connection :return: AJAX response to handle the form """ conn = mode...
754e7d7f15a0be843b89c89446a7d4f39bc1401f
3,957
from sage.all import solve import html def simpson_integration( title = text_control('<h2>Simpson integration</h2>'), f = input_box(default = 'x*sin(x)+x+1', label='$f(x)=$'), n = slider(2,100,2,6, label='# divisions'), interval_input = selector(['from slider','from keyboard'], label='Integration inte...
45e575e9ebda475a613555dfcb43ae7d739131c9
3,958
def object_reactions_form_target(object): """ Get the target URL for the object reaction form. Example:: <form action="{% object_reactions_form_target object %}" method="post"> """ ctype = ContentType.objects.get_for_model(object) return reverse("comments-ink-react-to-object", args=(ct...
5bcd4d9fa8db783c78668820326dd55038ef609e
3,959
def check_args(**kwargs): """ Check arguments for themis load function Parameters: **kwargs : a dictionary of arguments Possible arguments are: probe, level The arguments can be: a string or a list of strings Invalid argument are ignored (e.g. probe = 'g', level=...
3e25dc43df0a80a9a16bcca0729ee0b170a9fb89
3,960
def make_theta_mask(aa): """ Gives the theta of the bond originating each atom. """ mask = np.zeros(14) # backbone mask[0] = BB_BUILD_INFO["BONDANGS"]['ca-c-n'] # nitrogen mask[1] = BB_BUILD_INFO["BONDANGS"]['c-n-ca'] # c_alpha mask[2] = BB_BUILD_INFO["BONDANGS"]['n-ca-c'] # carbon mask[3...
f33c1b46150ed16154c9a10c92f30cf9f60c2f51
3,961
def create_keypoint(n,*args): """ Parameters: ----------- n : int Keypoint number *args: tuple, int, float *args must be a tuple of (x,y,z) coordinates or x, y and z coordinates as arguments. :: # Example kp1 = 1 kp2 = 2 crea...
e498e36418ec19d2feef122d3c42a346f9de4af7
3,962
import time def wait_for_sidekiq(gl): """ Return a helper function to wait until there are no busy sidekiq processes. Use this with asserts for slow tasks (group/project/user creation/deletion). """ def _wait(timeout=30, step=0.5): for _ in range(timeout): time.sleep(step) ...
7fe98f13e9474739bfe4066f20e5f7d813ee4476
3,963
def insert_node_after(new_node, insert_after): """Insert new_node into buffer after insert_after.""" next_element = insert_after['next'] next_element['prev'] = new_node new_node['next'] = insert_after['next'] insert_after['next'] = new_node new_node['prev'] = insert_after return new_node
e03fbd7bd44a3d85d36069d494464b9237bdd306
3,965
def apply_wavelet_decomposition(mat, wavelet_name, level=None): """ Apply 2D wavelet decomposition. Parameters ---------- mat : array_like 2D array. wavelet_name : str Name of a wavelet. E.g. "db5" level : int, optional Decomposition level. It is constrained to retur...
d91f534d605d03c364c89383629a7142f4705ac8
3,966
import math def ACE(img, ratio=4, radius=300): """The implementation of ACE""" global para para_mat = para.get(radius) if para_mat is not None: pass else: size = radius * 2 + 1 para_mat = np.zeros((size, size)) for h in range(-radius, radius + 1): for w ...
6809067ec1aed0f20d62d672fcfb554e0ab51f28
3,967
def classname(object, modname): """Get a class name and qualify it with a module name if necessary.""" name = object.__name__ if object.__module__ != modname: name = object.__module__ + '.' + name return name
af4e05b0adaa9c90bb9946edf1dba67a40e78323
3,968
import time def demc_block(y, pars, pmin, pmax, stepsize, numit, sigma, numparams, cummodels, functype, myfuncs, funcx, iortholist, fits, gamma=None, isGR=True, ncpu=1): """ This function uses a differential evolution Markov chain with block updating to assess uncertainties. PARAMETERS ---------- ...
414168976c732d66165e19c356800158b2056a1e
3,969
def shape5d(a, data_format="NDHWC"): """ Ensuer a 5D shape, to use with 5D symbolic functions. Args: a: a int or tuple/list of length 3 Returns: list: of length 5. if ``a`` is a int, return ``[1, a, a, a, 1]`` or ``[1, 1, a, a, a]`` depending on data_format "NDHWC" or "NCDH...
fe6d974791a219c45a543a4d853f5d44770d0c9a
3,970
def resnet152(pretrained=False, num_classes=1000, ifmask=True, **kwargs): """Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ block = Bottleneck model = ResNet(block, [3, 8, 36, 3], num_classes=1000, **kwargs) if pretrained: ...
8b72a8e284d098a089448e4a10d5f393345d7278
3,972
def register_driver(cls): """ Registers a driver class Args: cls (object): Driver class. Returns: name: driver name """ _discover_on_demand() if not issubclass(cls, BaseDriver): raise QiskitChemistryError('Could not register class {} is not subclass of BaseDriver'.fo...
82eca23a5cf5caf9a028d040ac523aa6e20ae01d
3,973
def ceil(array, value): """ Returns the smallest index i such that array[i - 1] < value. """ l = 0 r = len(array) - 1 i = r + 1 while l <= r: m = l + int((r - l) / 2) if array[m] >= value: # This mid index is a candidate for the index we are searching for ...
689148cebc61ee60c99464fde10e6005b5d901a9
3,974
import copy def FindOrgByUnionEtIntersection(Orgs): """Given a set of organizations considers all the possible unions and intersections to find all the possible organizations""" NewNewOrgs=set([]) KnownOrgs=copy.deepcopy(Orgs) for h in combinations(Orgs,2): #checks only if one is not contained in the other Ne...
6e2450f49522186094b205dd86d8e698aca708bc
3,975
def get_sf_fa( constraint_scale: float = 1 ) -> pyrosetta.rosetta.core.scoring.ScoreFunction: """ Get score function for full-atom minimization and scoring """ sf = pyrosetta.create_score_function('ref2015') sf.set_weight( pyrosetta.rosetta.core.scoring.ScoreType.atom_pair_constraint, ...
b82b352f3fc031cc18951b037779a71247e5095f
3,976
from typing import Optional from typing import List def make_keypoint(class_name: str, x: float, y: float, subs: Optional[List[SubAnnotation]] = None) -> Annotation: """ Creates and returns a keypoint, aka point, annotation. Parameters ---------- class_name : str The name of the class for...
bc4a96c8376890eaaa2170ab1cc1401dcb2781a4
3,977
def plane_mean(window): """Plane mean kernel to use with convolution process on image Args: window: the window part to use from image Returns: Normalized residual error from mean plane Example: >>> from ipfml.filters.kernels import plane_mean >>> import numpy as np >>> wi...
7383078ec3c88ac52728cddca9a725f6211b2d2c
3,978
def _eval_field_amplitudes(lat, k=5, n=1, amp=1e-5, field='v', wave_type='Rossby', parameters=Earth): """ Evaluates the latitude dependent amplitudes at a given latitude point. Parameters ---------- lat : Float, array_like or scalar latitude(radians) k : Int...
db74c50ef6328055ab2a59faecba72cc28afd136
3,979
def get_uframe_info(): """ Get uframe configuration information. (uframe_url, uframe timeout_connect and timeout_read.) """ uframe_url = current_app.config['UFRAME_URL'] + current_app.config['UFRAME_URL_BASE'] timeout = current_app.config['UFRAME_TIMEOUT_CONNECT'] timeout_read = current_app.config['UFRA...
921f42d59af265152d7ce453a19cb8057af8415e
3,980
def yd_process_results( mentions_dataset, predictions, processed, sentence2ner, include_offset=False, mode='default', rank_pred_score=True, ): """ Function that can be used to process the End-to-End results. :return: dictionary with results and document as key. """ assert...
32352c6aabea6750a6eb410d62232c96ad6b7e7d
3,981
import re def valid(f): """Formula f is valid if and only if it has no numbers with leading zero, and evals true.""" try: return not re.search(r'\b0[0-9]', f) and eval(f) is True except ArithmeticError: return False
1303729dc53288ea157687f78d7266fa7cb2ce79
3,982
def user_info(): """ 渲染个人中心页面 :return: """ user = g.user if not user: return redirect('/') data={ "user_info":user.to_dict() } return render_template("news/user.html",data=data)
54c6c6122f28553f0550a744d5b51c26221f7c60
3,983
def _check_X(X, n_components=None, n_features=None, ensure_min_samples=1): """Check the input data X. See https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/mixture/_base.py . Parameters ---------- X : array-like, shape (n_samples, n_features) n_components : integer Returns...
429120092a963d1638e04cc96afdfe5979470fee
3,984
def read_viirs_geo (filelist, ephemeris=False, hgt=False): """ Read JPSS VIIRS Geo files and return Longitude, Latitude, SatelliteAzimuthAngle, SatelliteRange, SatelliteZenithAngle. if ephemeris=True, then return midTime, satellite position, velocity, attitude """ if type(filelist) is str: fi...
1b8bbd34651e13aabe752fa8e3ac8c6679d757ca
3,985
def _in_terminal(): """ Detect if Python is running in a terminal. Returns ------- bool ``True`` if Python is running in a terminal; ``False`` otherwise. """ # Assume standard Python interpreter in a terminal. if "get_ipython" not in globals(): return True ip = globa...
9716c2a1809f21ed8b827026d29b4ad69045f8d5
3,986
import re def create_text_pipeline(documents): """ Create the full text pre-processing pipeline using spaCy that first cleans the texts using the cleaning utility functions and then also removes common stopwords and corpus specific stopwords. This function is used specifically on abstracts. :...
d31632c7c1d9a2c85362e05ae43f96f35993a746
3,987
def giou_dist(tlbrs1, tlbrs2): """Computes pairwise GIoU distance.""" assert tlbrs1.ndim == tlbrs2.ndim == 2 assert tlbrs1.shape[1] == tlbrs2.shape[1] == 4 Y = np.empty((tlbrs1.shape[0], tlbrs2.shape[0])) for i in nb.prange(tlbrs1.shape[0]): area1 = area(tlbrs1[i, :]) for j in range...
40dcd6b59f350f167ab8cf31be425e98671243d4
3,988
def easter(date): """Calculate the date of the easter. Requires a datetime type object. Returns a datetime object with the date of easter for the passed object's year. """ if 1583 <= date.year < 10000: # Delambre's method b = date.year / 100 # Take the firsts two digits of t...
90bfaf56fb5164cdfb185f430ca11e7a5d9c2785
3,989
from typing import Dict def state_mahalanobis(od: Mahalanobis) -> Dict: """ Mahalanobis parameters to save. Parameters ---------- od Outlier detector object. """ state_dict = {'threshold': od.threshold, 'n_components': od.n_components, 'std_clip...
7be602c5a0c89d67adc223c911abccd96d359664
3,990
def show_table(table, **options): """ Displays a table without asking for input from the user. :param table: a :class:`Table` instance :param options: all :class:`Table` options supported, see :class:`Table` documentation for details :return: None """ return table.show_table(**options)
ec040d4a68d2b3cb93493f336daf1aa63289756e
3,991
def create_client(name, func): """Creating resources/clients for all needed infrastructure: EC2, S3, IAM, Redshift Keyword arguments: name -- the name of the AWS service resource/client func -- the boto3 function object (e.g. boto3.resource/boto3.client) """ print("Creating client for", name) ...
a688c36918ebb4bc76ee1594c6f4cca638587d7d
3,992
def hamming(s0, s1): """ >>> hamming('ABCD', 'AXCY') 2 """ assert len(s0) == len(s1) return sum(c0 != c1 for c0, c1 in zip(s0, s1))
efaba3e6aca8349b0dc5df575b937ba67a148d0e
3,993
import pickle def load_embeddings(topic): """ Load TSNE 2D Embeddings generated from fitting BlazingText on the news articles. """ print(topic) embeddings = pickle.load( open(f'covidash/data/{topic}/blazing_text/embeddings.pickle', 'rb')) labels = pickle.load( open(f'covidash/d...
de2f74c7e467e0f057c10a0bc15b79ee9eecb40f
3,994
def mosaic_cut(image, original_width, original_height, width, height, center, ptop, pleft, pbottom, pright, shiftx, shifty): """Generates a random center location to use for the mosaic operation. Given a center location, cuts the input image into a slice that will be concatenated with other slices...
2874ea65a695d7ebebf218e5a290069a9f3c1e8e
3,996
import requests def get_children_info(category_id: str) -> list[dict]: """Get information about children categories of the current category. :param: category_id: category id. :return: info about children categories. """ # Create the URL url = f'{POINT}/resources/v2/title/domains/{DOMAIN}/' \ ...
f5a651c1f58c75ee56d1140ee41dc6dd39570f88
3,997
from datetime import datetime def GetTypedValue(field_type, value): """Returns a typed value based on a schema description and string value. BigQuery's Query() method returns a JSON string that has all values stored as strings, though the schema contains the necessary type information. This method provides ...
8e6198d089bae4e1044b2998da97a8cbcf6130b2
3,998
def predict_from_file(audio_file, hop_length=None, fmin=50., fmax=MAX_FMAX, model='full', decoder=torchcrepe.decode.viterbi, return_harmonicity=False, return_periodic...
7e1f8036e5d0506f28a4b36b9e23c2d4a0237218
3,999
import unittest def test(): """Runs the unit tests without test coverage.""" tests = unittest.TestLoader().discover('cabotage/tests', pattern='test*.py') result = unittest.TextTestRunner(verbosity=2).run(tests) if result.wasSuccessful(): return 0 return 1
bcb57638bea41f3823cd22aa7a43b159591ad99b
4,000
def nm_to_uh(s): """Get the userhost part of a nickmask. (The source of an Event is a nickmask.) """ return s.split("!")[1]
5e6c07b7b287000a401ba81117bc55be47cc9a24
4,001
def upload_example_done(request, object_id): """ This view is a callback that receives POST data from uploadify when the download is complete. See also /media/js/uploadify_event_handlers.js. """ example = get_object_or_404(Example, id=object_id) # # Grab the post data sent by our ...
b748cb1708ddfdd2959f723902c45668c8774df2
4,002
def epoch_in_milliseconds(epoch): """ >>> epoch_in_milliseconds(datetime_from_seconds(-12345678999.0001)) -12345679000000 """ return epoch_in_seconds(epoch) * 1000
75ae0779ae2f6d1987c1fdae0a6403ef725a6893
4,003
def get_workspaces(clue, workspaces): """ Imports all workspaces if none were provided. Returns list of workspace names """ if workspaces is None: logger.info("no workspaces specified, importing all toggl workspaces...") workspaces = clue.get_toggl_workspaces() logger.info("T...
aae8b5f2585a7865083b433f4aaf9874d5ec500e
4,004
import pprint def create_hparams(hparams_string=None, hparams_json=None, verbose=True): """Create model hyperparameters. Parse nondefault from given string.""" hparams = tf.contrib.training.HParams( training_stage='train_style_extractor',#['train_text_encoder','train_style_extractor','train_style_att...
d4d255241b7322a10369bc313a0ddc971c0115a6
4,005
def ChromiumFetchSync(name, work_dir, git_repo, checkout='origin/master'): """Some Chromium projects want to use gclient for clone and dependencies.""" if os.path.isdir(work_dir): print '%s directory already exists' % name else: # Create Chromium repositories one deeper, separating .gclient files. par...
8bb0f593eaf874ab1a6ff95a913ef34b566a47bc
4,006
def kld_error(res, error='simulate', rstate=None, return_new=False, approx=False): """ Computes the `Kullback-Leibler (KL) divergence <https://en.wikipedia.org/wiki/Kullback-Leibler_divergence>`_ *from* the discrete probability distribution defined by `res` *to* the discrete probabilit...
430ad6cb1c25c0489343717d7cf8a44bdfb5725d
4,007
def article_detail(request, slug): """ Show details of the article """ article = get_article_by_slug(slug=slug, annotate=True) comment_form = CommentForm() total_views = r.incr(f'article:{article.id}:views') return render(request, 'articles/post/detail.html', {'article': ar...
079d31509fe573ef207600e007e51ac14e9121c4
4,008
def deactivate(userid, tfa_response): """ Deactivate 2FA for a specified user. Turns off 2FA by nulling-out the ``login.twofa_secret`` field for the user record, and clear any remaining recovery codes. Parameters: userid: The user for which 2FA should be disabled. tfa_response: Use...
1ac0f5e716675ccb118c9656bcc7c9b4bd3f9606
4,009
def hsi_normalize(data, max_=4096, min_ = 0, denormalize=False): """ Using this custom normalizer for RGB and HSI images. Normalizing to -1to1. It also denormalizes, with denormalize = True) """ HSI_MAX = max_ HSI_MIN = min_ NEW_MAX = 1 NEW_MIN = -1 if(denormalize): scaled...
7f276e90843c81bc3cf7715e54dadd4a78162f93
4,010
from typing import Optional def safe_elem_text(elem: Optional[ET.Element]) -> str: """Return the stripped text of an element if available. If not available, return the empty string""" text = getattr(elem, "text", "") return text.strip()
12c3fe0c96ffdb5578e485b064ee4df088192114
4,011
def resource(filename): """Returns the URL a static resource, including versioning.""" return "/static/{0}/{1}".format(app.config["VERSION"], filename)
b330c052180cfd3d1b622c18cec7e633fa7a7910
4,012
import csv def read_q_stats(csv_path): """Return list of Q stats from file""" q_list = [] with open(csv_path, newline='') as csv_file: reader = csv.DictReader(csv_file) for row in reader: q_list.append(float(row['q'])) return q_list
f5bee4859dc4bac45c4c3e8033da1b4aba5d2818
4,014
def _validate(config): """Validate the configuation. """ diff = set(REQUIRED_CONFIG_KEYS) - set(config.keys()) if len(diff) > 0: raise ValueError( "config is missing required keys".format(diff)) elif config['state_initial']['status'] not in config['status_values']: raise ...
07c92e5a5cc722efbbdc684780b1edb66aea2532
4,015
def exp_by_squaring(x, n): """ Compute x**n using exponentiation by squaring. """ if n == 0: return 1 if n == 1: return x if n % 2 == 0: return exp_by_squaring(x * x, n // 2) return exp_by_squaring(x * x, (n - 1) // 2) * x
ef63d2bf6f42690fd7c5975af0e961e2a3c6172f
4,016
def _compare(expected, actual): """ Compare SslParams object with dictionary """ if expected is None and actual is None: return True if isinstance(expected, dict) and isinstance(actual, SslParams): return expected == actual.__dict__ return False
4a82d1631b97960ecc44028df4c3e43dc664d3e5
4,017
def update_token(refresh_token, user_id): """ Refresh the tokens for a given user :param: refresh_token Refresh token of the user :param: user_id ID of the user for whom the token is to be generated :returns: Generated JWT token """ token = Token.query.filter_by(refr...
0b91cf19f808067a9c09b33d7497548743debe14
4,018
from re import X def minimax(board): """ Returns the optimal action for the current player on the board. """ def max_value(state, depth=0): if ttt.terminal(state): return (None, ttt.utility(state)) v = (None, -2) for action in ttt.actions(state): v =...
8de42db3ad40d597bf9600bcd5fec7c7f775f84d
4,019
import random def random_order_dic_keys_into_list(in_dic): """ Read in dictionary keys, and return random order list of IDs. """ id_list = [] for key in in_dic: id_list.append(key) random.shuffle(id_list) return id_list
d18ac34f983fbaff59bfd90304cd8a4a5ebad42e
4,020
from typing import Union from pathlib import Path from typing import Dict import json def read_json(json_path: Union[str, Path]) -> Dict: """ Read json file from a path. Args: json_path: File path to a json file. Returns: Python dictionary """ with open(json_path, "r") as fp:...
c0b55e5363a134282977ee8a01083490e9908fcf
4,021
def igraph_to_csc(g, save=False, fn="csc_matlab"): """ Convert an igraph to scipy.sparse.csc.csc_matrix Positional arguments: ===================== g - the igraph graph Optional arguments: =================== save - save file to disk fn - the file name to be used when writing (appendmat = True by de...
12ea73531599cc03525e898e39b88f2ed0ad97c3
4,022
def xml2dict(data): """Turn XML into a dictionary.""" converter = XML2Dict() if hasattr(data, 'read'): # Then it's a file. data = data.read() return converter.fromstring(data)
0c73989b4ea83b2b1c126b7f1b39c6ebc9e18115
4,023
def balance_dataset(data, size=60000): """Implements upsampling and downsampling for the three classes (low, medium, and high) Parameters ---------- data : pandas DataFrame A dataframe containing the labels indicating the different nightlight intensity bins size : int The number...
93cd5888c28f9e208379d7745790b7e1e0cb5b79
4,024
def updateStopList(userId, newStop): """ Updates the list of stops for the user in the dynamodb table """ response = dynamodb_table.query( KeyConditionExpression=Key('userId').eq(userId)) if response and len(response["Items"]) > 0: stops = response["Items"][0]['stops'] else: ...
433ae6c4562f6a6541fc262925ce0bba6fb742ec
4,025
import re def is_blacklisted_module(module: str) -> bool: """Return `True` if the given module matches a blacklisted pattern.""" # Exclude stdlib modules such as the built-in "_thread" if is_stdlib_module(module): return False # Allow user specified exclusions via CLI blacklist = set.unio...
391d63a4d8a4f24d1d3ba355745ffe0079143e68
4,026
def _build_geojson_query(query): """ See usages below. """ # this is basically a translation of the postgis ST_AsGeoJSON example into sqlalchemy/geoalchemy2 return func.json_build_object( "type", "FeatureCollection", "features", func.json_agg(func.ST_AsGeoJSON(query.s...
dd7a0893258cf95e1244458ba9bd74c5239f65c5
4,029
import urllib def url_encode(obj, charset='utf-8', encode_keys=False, sort=False, key=None, separator='&'): """URL encode a dict/`MultiDict`. If a value is `None` it will not appear in the result string. Per default only values are encoded into the target charset strings. If `encode_keys...
2106032d6a4cf895c525e9db702655af3439a95c
4,030
from datetime import datetime def create_export_and_wait_for_completion(name, bucket, prefix, encryption_config, role_arn=None): """ Request QLDB to export the contents of the journal for the given time period and S3 configuration. Before calling this function the S3 bucket should be created, see :py:...
9fb6f66dc02d70ffafe1c388188b99b9695a6900
4,031
def sample_student(user, **kwargs): """create and return sample student""" return models.Student.objects.create(user=user, **kwargs)
a70c3a181b1ee0627465f016953952e082a51c27
4,032
from datetime import datetime def normalise_field_value(value): """ Converts a field value to a common type/format to make comparable to another. """ if isinstance(value, datetime): return make_timezone_naive(value) elif isinstance(value, Decimal): return decimal_to_string(value) retur...
3cbc4c4d7ae027c030e70a1a2bd268bdd0ebe556
4,033
from typing import Any from typing import Tuple from typing import List import collections import yaml def parse_yaml(stream: Any) -> Tuple[Swagger, List[str]]: """ Parse the Swagger specification from the given text. :param stream: YAML representation of the Swagger spec satisfying file interface :r...
7155520db98bf1d884ba46f22b46297a901f4411
4,035
import itertools def dataset_first_n(dataset, n, show_classes=False, class_labels=None, **kw): """ Plots first n images of a dataset containing tensor images. """ # [(img0, cls0), ..., # (imgN, clsN)] first_n = list(itertools.islice(dataset, n)) # Split (image, class) tuples first_n_imag...
ed8394fc2a1b607597599f36545c9182a9bc8187
4,036
def unit_conversion(thing, units, length=False): """converts base data between metric, imperial, or nautical units""" if 'n/a' == thing: return 'n/a' try: thing = round(thing * CONVERSION[units][0 + length], 2) except TypeError: thing = 'fubar' return thing, CONVERSION[units]...
96bfb9cda575a8b2efc959b6053284bec1d286a6
4,037
import functools def timed(func): """Decorate function to print elapsed time upon completion.""" @functools.wraps(func) def wrap(*args, **kwargs): t1 = default_timer() result = func(*args, **kwargs) t2 = default_timer() print('func:{} args:[{}, {}] took: {:.4f} sec'.format(...
d572488c674607b94e2b80235103d6f0bb27738f
4,038
def fade_out(s, fade=cf.output.fade_out): """ Apply fade-out to waveform time signal. Arguments: ndarray:s -- Audio time series float:fade (cf.output.fade_out) -- Fade-out length in seconds Returns faded waveform. """ length = int(fade * sr) shape = [1] * len(s.shape) shape[0] = length win ...
0b554dbb1da7253e39c651ccdc38ba91e67a1ee4
4,040
def create_arch(T, D, units=64, alpha=0, dr_rate=.3): """Creates the architecture of miint""" X = K.Input(shape=(T, D)) active_mask = K.Input(shape=(T, 1)) edges = K.Input(shape=(T, None)) ycell = netRNN(T=T, D=D, units=units, alpha=alpha, dr_rate=dr_rate) yrnn = K.layers.RNN(ycell, return_sequences=True) Y = ...
cc9723657a7a0822d73cc78f6e1698b33257f9e0
4,041
def redact(str_to_redact, items_to_redact): """ return str_to_redact with items redacted """ if items_to_redact: for item_to_redact in items_to_redact: str_to_redact = str_to_redact.replace(item_to_redact, '***') return str_to_redact
f86f24d3354780568ec2f2cbf5d32798a43fdb6a
4,042
def FibreDirections(mesh): """ Routine dedicated to compute the fibre direction of components in integration point for the Material in Florence and for the auxiliar routines in this script. First three directions are taken into the code for Rotation matrix, so always it should be present i...
9408702e72dde7586f42137ad25a0a944ed28a93
4,043
def put(consul_url=None, token=None, key=None, value=None, **kwargs): """ Put values into Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param value: The value to set the key to. :param flags: This can be used to specify an unsig...
3b80283da426e5515026fb8dc0db619b2a471f41
4,044
def prepare_w16(): """ Prepare a 16-qubit W state using sqrt(iswaps) and local gates, respecting linear topology """ ket = qf.zero_state(16) circ = w16_circuit() ket = circ.run(ket) return ket
74d0599e1520aab44088480616e2062153a789aa
4,045
import requests def get_All_Endpoints(config): """ :return: """ url = 'https://{}:9060/ers/config/endpoint'.format(config['hostname']) headers = { 'Content-Type': 'application/json', 'Accept': 'application/json' } body = {} response = requests.request('GET', url, headers=headers, data=body, auth=HTTPBasi...
f74ad8ba7d65de11851b71318b2818776c5dc29b
4,046
import pandas import numpy def synthetic_peptides_by_subsequence( num_peptides, fraction_binders=0.5, lengths=range(8, 20), binding_subsequences=["A?????Q"]): """ Generate a toy dataset where each peptide is a binder if and only if it has one of the specified subsequences. ...
d4cfa202043e3a98a7960246a7d8775ff147201c
4,049
def gce_zones() -> list: """Returns the list of GCE zones""" _bcds = dict.fromkeys(['us-east1', 'europe-west1'], ['b', 'c', 'd']) _abcfs = dict.fromkeys(['us-central1'], ['a', 'b', 'c', 'f']) _abcs = dict.fromkeys( [ 'us-east4', 'us-west1', 'europe-west4', ...
10e684b2f458fe54699eb9886af148b092ec604d
4,050
def empty_netbox_query(): """Return an empty list to a list query.""" value = { "count": 0, "next": None, "previous": None, "results": [], } return value
9b017c34a3396a82edc269b10b6bfc6b7f878bc3
4,051
import psutil import time def get_process_metrics(proc): """ Extracts CPU times, memory infos and connection infos about a given process started via Popen(). Also obtains the return code. """ p = psutil.Process(proc.pid) max_cpu = [0, 0] max_mem = [0, 0] conns = [] while proc.poll() is No...
7be8688debbde33bbcfb43b483d8669241e029d6
4,052
def tau_from_T(Tobs, Tkin): """ Line optical depth from observed temperature and excitation temperature in Kelvin """ tau = -np.log(1.-(Tobs/Tkin)) return tau
089cdc9ae3692037fa886b5c168e03ee2b6ec9ce
4,053
def create_classes_names_list(training_set): """ :param training_set: dict(list, list) :return: (list, list) """ learn_classes_list = [] for k, v in training_set.items(): learn_classes_list.extend([str(k)] * len(v)) return learn_classes_list
0b30153afb730d4e0c31e87635c9ece71c530a41
4,054
from petastorm.spark import SparkDatasetConverter def get_petastorm_dataset(cache_dir: str, partitions: int=4): """ This Dataloader assumes that the dataset has been converted to Delta table already The Delta Table Schema is: root |-- sample_id: string (nullable = true) |-- value: string (nullable...
27f6777b2c1cebad08f8a416d360a2b7096febec
4,056
def get_corners(square_to_edges, edge_to_squares): """Get squares ids of squares which place in grid in corner.""" return get_squares_with_free_edge(square_to_edges, edge_to_squares, 2)
1370f472aedf83f7aa17b64a813946a3a760968d
4,057
async def get_untagged_joke(): """ Gets an untagged joke from the jokes table and sends returns it :return: json = {joke_id, joke} """ df = jokes.get_untagged_joke() if not df.empty: response = {"joke": df["joke"][0], "joke_id": int(df["id"][0])} else: response = {"joke": "No...
a2dde1d5ddba47beb5e7e51b9f512f0a861336da
4,058
def map_parallel(function, xs): """Apply a remote function to each element of a list.""" if not isinstance(xs, list): raise ValueError('The xs argument must be a list.') if not hasattr(function, 'remote'): raise ValueError('The function argument must be a remote function.') # EXERCISE:...
1fe75868d5ff12a361a6aebd9e4e49bf92c32126
4,059
def log_interp(x,y,xnew): """ Apply interpolation in logarithmic space for both x and y. Beyound input x range, returns 10^0=1 """ ynew = 10**ius(np.log10(x), np.log10(y), ext=3)(np.log10(xnew)) return ynew
16ef0cc494f61c031f9fd8f8e820a17bb6c83df8
4,060
def inten_sat_compact(args): """ Memory saving version of inten_scale followed by saturation. Useful for multiprocessing. Parameters ---------- im : numpy.ndarray Image of dtype np.uint8. Returns ------- numpy.ndarray Intensity scale and saturation of input. """...
9624891f9d09c13d107907fcd30e2f102ff00ee2
4,061
def masseuse_memo(A, memo, ind=0): """ Return the max with memo :param A: :param memo: :param ind: :return: """ # Stop if if ind > len(A)-1: return 0 if ind not in memo: memo[ind] = max(masseuse_memo(A, memo, ind + 2) + A[ind], masseuse_memo(A, memo, ind + 1)) ...
03d108cb551f297fc4fa53cf9575d03af497ee38
4,062
import torch def unique_pairs(bonded_nbr_list): """ Reduces the bonded neighbor list to only include unique pairs of bonds. For example, if atoms 3 and 5 are bonded, then `bonded_nbr_list` will have items [3, 5] and also [5, 3]. This function will reduce the pairs only to [3, 5] (i.e. only the pair i...
e974728ad831a956f1489b83bb77b15833ae9b82
4,063
def permission(*perms: str): """ Decorator that runs the command only if the author has the specified permissions. perms must be a string matching any property of discord.Permissions. NOTE: this function is deprecated. Use the command 'permissions' attribute instead. """ def decorator(func): ...
b0ef0dfec36a243152dff4ca11ab779d2c417ab8
4,064
from re import T def validate_script(value): """Check if value is a valid script""" if not sabnzbd.__INITIALIZED__ or (value and sabnzbd.filesystem.is_valid_script(value)): return None, value elif (value and value == "None") or not value: return None, "None" return T("%s is not a valid...
d4a5d6922fb14524bc9d11f57807d9a7f0e937f1
4,065