content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def make_attr_string(attr): """Returns an attribute string in the form key="val".""" attr_string = ' '.join('%s="%s"' % (k, v) for k, v in attr.items()) return '%s%s' % (' ' if attr_string != '' else '', attr_string)
7185a6e725349313a4cc67ae643a18d9ab63c871
35,300
def optimize_weights(instrument, sample): """Optimize the weights on a particular sample""" guess = [1.0] * sample.shape[1] bounds = [(0.0,5.0)] * sample.shape[1] def function(w, instrument, sample): """This is the function that is minimized iteratively using scipy.optimize.minimize to find the ...
f5070a76a7cb2a3210caee01928e9ae5b83055a3
35,301
import logging import os import sqlite3 import random def get_random_image_from_database(): """Returns full image path of a random image from the database, if available""" logging.debug('get_random_image_from_database()') dir_path = os.path.join(os.environ['LOCALAPPDATA'],'WarietyWallpaperImages') o...
65babd4a6cfa152f82a3ee08220b78dbe6dde2fb
35,302
from datetime import date def voto(ano): """ FUNÇÃO QUE VALIDA A IDADE DO ELEITOR :param ano: ano de nascimento :return: idade menor que 16 anos: NÃO VOTA idade entre 16 e 17 anos e acima de 65 anos: VOTO OPCIONAL idade entre 18 e 65: APTO A VOTAR """ idade = date.tod...
ccd103a7fcd31d021c1b563df3c883d8ea81d668
35,303
import curses def new_border_and_win(ws): """ Returns two curses windows, one serving as the border, the other as the inside from these *_FRAME tuples above. """ return ( curses.newwin(ws[1][1], ws[1][0], ws[0][1], ws[0][0]), curses.newwin(ws[1][1] - 2, ws[1][0] - 2, ws[0][1] + 1, ws[0][0] + 1), )
cec302bda38ba5fa9d0c88dbfac1c501984a96a0
35,304
import argparse def parse_command_line(): """Parse command line arguments.""" parser = argparse.ArgumentParser( description="Start a MongoDB cluster in a distributed environment" ) parser.add_argument("-d", "--debug", action="store_true", help="enable debug output") parser.add_argument("--...
8aea871bf01fe3b30a6308d024d6a8b00f2c2307
35,305
from scipy.spatial import cKDTree import sys from re import X def merge_models(l): """ (c)rude merging """ # TODO this is going meta, the merging can be done with a clustering # algorithm, why not a DP(G)MM? # Currently using a nearest neighbor's search on means n_clusters = min([len(mixt.params...
f3a2c0176b3073b3f4c0b75ce714dc64569d2dea
35,306
import socket def mk_sock(mcast_host, mcast_ip, mcast_port): """ multicast socket setup """ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.setsockopt( socket.IPPROTO_IP, socket.IP_ADD_M...
702a95e5baec4ecf54206f8f16cfa22d8365f8a0
35,307
import os def count_signals(): """Function counts transaction signals Returns: list: list of dictionaries with signals 1. Dictionary for buy signals 2. Dictionary for sell signals 3. Dictionary for close long position 4. Dictionary for close short position """ ...
5741bf3fe9e2ead9aaa5a2de1b58f4f23db20d79
35,308
def next_line_start_or_here(text, pos): """Find next line start, or `pos` if `pos` is already a line start """ if pos == 0 or (pos-1 < len(text) and text[pos-1] == "\n"): return pos return next_line_start(text, pos)
623be9a39064e2a67fc79ca0a12e95477071fc35
35,309
def getimdata(cubenm, verbose=False): """Get fits image data """ if verbose: print(f'Getting image data from {cubenm}') with fits.open(cubenm, memmap=True, mode='denywrite') as hdu: dxas = hdu[0].header['CDELT1']*-1*u.deg dyas = hdu[0].header['CDELT2']*u.deg nx, ny = hd...
6ea45ba1dbbf46d9d6518a28e643bb67d3a6d627
35,310
import math def N(latitude): """ Transverse radius of curvature. Returns radius of curvature in east-west direction. latitude: Latitude in radians. """ return a/math.sqrt(1-e2*pow(math.sin(latitude),2.0))
ac1bbf3c7f6aa28251d25a584ec283a09b9e01b5
35,311
def cmd(command_id): """ A helper function for identifying command functions """ def decorator(func): func.__COMMAND_ID__ = command_id return func return decorator
cff8664ad18c78629bb3c1b4946be592142711e0
35,312
import json def getBatchExperiments(): """ return the information related to the experiments of a batch :return: informations of the experiment :rtype: Dict """ data = request.json['data'] experiments = [] for key in data: batch_experiments = queueManager.getBatchExperiments(k...
1762c7449800ce38f0ffc867aa0962827b561a5b
35,313
def noiseProb(ksStat, Ntot): """pvalue = noiseProb(ksStat, Ntot) Returns probability of being in same distribution for given K-S statistic""" s = Ntot*pow(ksStat, 2) # For d values that are in the far tail of the distribution (i.e. # p-values > .999), the following lines will speed up the computatio...
2e4a99c631ef8ba7225aa8e328dfa03de68c18ed
35,314
def _check_nmant(np_type, nmant): """ True if fp type `np_type` seems to have `nmant` significand digits Note 'digits' does not include implicit digits. And in fact if there are no implicit digits, the `nmant` number is one less than the actual digits. Assumes base 2 representation. Parameters ...
9e1905d6efb1f2c5dcdc668128a614a48ef6c7f3
35,315
import json import uuid import time def timeboard_send_steps_list(self, steps, scenario_name, timeout): """ Change all steps in timeboard :param steps: The list of steps extracted from the scenario json file :type steps: list :param scenario_name: name of the scenario to which the steps belong ...
8d3cbbd2f61b1f6c4169737f72972c52ebc14fe1
35,316
from typing import Union from typing import Dict def get_indices(s: Union[str, 'ChainedBase']) -> Dict[int, str]: """ Retrieve a dict of characters and escape codes with their real index into the string as the key. """ codeindices = get_code_indices(s) if not codeindices: # This functi...
813c1b23a55400a645f6f79208b86d8c9e9d3905
35,317
import re def parse_shortcodes(post_body): """ I stole this shortcode regex from Wordpress's source. It is very confusing. """ tagregexp = '|'.join([re.escape(t) for t in TAGS_WE_CAN_PARSE.keys()]) pattern = re.compile( '\\[(\\[?)(' + tagregexp + ')\\b([^\\]\\/]*(?:\\/(?!\\])[^\\]...
2a8a76e7b34a4e176a0236740886d4e7dc89bb20
35,318
from typing import Callable def on_start(func: Callable) -> FunctionCallback: """Decorator for creating a callback from a function. The function will be executed when the `Events.START` is triggered. The function should take :class:`argus.engine.State` as the first argument. Example: .. code...
d3e6fbad2932b88d9545c0368b75488b21f5f798
35,319
def conditional_entropy(cond_counts): """ Compute the conditional entropy of a conditional multinomial distribution given a list of lists of counts or Counters for x given each y: H(x|y) = \sum_y p(y) \sum_x p(x|y) \log (1 / p(x|y)) """ if isinstance(cond_counts, dict): cond_counts =...
9695e282f59a6eefe6f83217c554f734d8bdbafb
35,320
def xover_selection(snakes, survivors, opts, num_survivors): """ Picks parents from the current generation of snakes for crossover params: snakes: list, current generation of snakes of class Snake survivors: list, snakes of class Snake that survived opts: dict, contains hyperparamters ...
990e65aac637abe8c4c6c8a661f4a039b0900ca4
35,321
def rgb2hsv(image): """ Convert RGB image to HSV. Parameters ---------- image : af.Array - A 3 D arrayfire array representing an 3 channel image, or - A multi dimensional array representing batch of images. Returns -------- output : af.Array - A RGB image...
72b76e200e1ff1fba05fe7f3211b19b34b1ef982
35,322
def make_colormap(seq,cmapname='CustomMap'): """Return a LinearSegmentedColormap seq: a sequence of floats and RGB-tuples. The floats should be increasing and in the interval (0,1). """ seq = [(None,) * 3, 0.0] + list(seq) + [1.0, (None,) * 3] cdict = {'red': [], 'green': [], 'blue': []} for...
44dd4b40c4519244a857aa1e6d62b5be974f42d0
35,323
def _interp_fit(y0, y1, y_mid, f0, f1, dt): """Fit coefficients for 4th order polynomial interpolation. Args: y0 (Tensor) : Function value at the start of the interval. y1 (Tensor) : Function value at the end of the interval. y_mid (Tensor) : Function value at th...
021b045ca7635471cde1c3e3f6a887d093666bb4
35,324
def interleave_value(t0,series,begin=False,end=False): """Add t0 between every element of *series*""" T = [] if begin: T += [t0] if len(series) > 0: T += [series[0]] for t in series[1:]: T += [t0,t] if end: T += [t0] return T
33e3d8562a482e897bb3fd8d49f33a1dfed9bfb9
35,325
def menu(): """Menu grafico testuale per programma di gestione Immobili """ x = 1 while x !=0 : print (" Menu'") print(" Gestione Immobiliare") print(" INSERIMENTO IMMOBILE .........digita 1 --> ") print(" MODIFICA IMMOBILE .........digita 2 --> ") print(" CAN...
bfb16f3a50339b6e9ed672e1002e727b10f7cc39
35,326
def named(new_name): """ Sets given string as command name instead of the function name. The string is used verbatim without further processing. Usage:: @named('load') def do_load_some_stuff_and_keep_the_original_function_name(args): ... The resulting command will be a...
c47d71c4d622fdfcba5854d4f01f2148a07c36ff
35,327
def remove_junk_chars(bucket_name): """Remove characters that shouldn't or won't be in a bucket name""" name = bucket_name names = [] #Remove junk chars junk_chars = ["'", '"', "&#39;", "!"] for junk_char in junk_chars: name = name.replace(junk_char, "") #Remove domains (this can b...
cd2a3076215a3a8bb94903e1015391abc00ecfaa
35,328
def create_2x2_arrays(num_arrays): """This creates a multi-dimensional array of n 2x2 arrays Arguments: num_var {[int]} -- [this is the number of desired arrays] Returns: [numpy array] -- [a zero filled n dimensional array with n 2x2 arrays] """ temp_list = [2] for temp in rang...
26994d64e0dde46083481fd9f1594c9c102065f3
35,329
def calculate_gr(fr_pattern, density, composition): """ Calculates a g(r) pattern from a given F(r) pattern, the material density and composition. :param fr_pattern: F(r) pattern :param density: density in g/cm^3 :param composition: composition as a dictionary with the elements as k...
ac2ad0de0a01e9c629a2affa0a943bb6948e014c
35,330
from zfit import settings from zfit import settings from typing import Callable from typing import Optional from typing import Type def mc_integrate(func: Callable, limits: ztyping.LimitsType, axes: Optional[ztyping.AxesTypeInput] = None, x: Optional[ztyping.XType] = None, n_axes: Optional[int] = Non...
ccc216ff92d9c2ee857758b90b6469a269c76fb7
35,331
import os def resolve_path_or_url(path_or_url, allow_caching=True): """ Given either a path (absolute or relative), or a URL, attempt to resolve it. Returns a tuple consisting of: a :py:class:`slicedimage.backends._base.Backend`, the basename of the object, and the baseurl of the object. """ ...
27bdf48023094ed5a3c7a05c268781039dc6ccda
35,332
import random def get_batch(data_bucket, bucket_id, batch_size=1): """ Return one batch to feed into the model """ # only pad to the max length of the bucket encoder_size, decoder_size = config.BUCKETS[bucket_id] encoder_inputs, decoder_inputs = [], [] for _ in range(batch_size): encoder_...
81c17c41021509a82d9fe08f8614997bee937a3b
35,333
import html import json def get_report_formatter(format_name): """ Get the correct report table output function for a named format Args: format_name (str): Name of the desired format Returns: A formatting output function if the format is recognized, or None if it is not. ...
cbb8f623715d3c272e745d3e454053e419e42960
35,334
from typing import Set def print_rule_tree(rt: Set['FlowRule']): """ Recursively explore rt-contained rules' parents. """ rt = rt.copy() res = [] seen = set() while rt: rule = rt.pop() if rule in seen: continue seen.add(rule) res.insert(0, rule...
05b67cda248753042f9f6fbd05dd0b84797a73a3
35,335
def sort(request): """ Valid values for the 'sort' parameter used in the Index setops methods (intersection, union, etc.) Caution: Don't confuse this one with the "sort" fixture used for DataFrame.append or concat. That one has parameters [True, False]. We can't combine...
0f1e7bb570b6f8f617a7564695c1a20d71cfbe80
35,336
from datetime import datetime import pytz def date_string_to_utc_float_string(date_string, timezone=None): """Return a utc_float_string for a given date_string - date_string: string form between 'YYYY' and 'YYYY-MM-DD HH:MM:SS.f' """ dt = None s = None for fmt in [ '%Y-%m-%d %H:%M:%S'...
cd1b1db88d6b9add6dcd252c58877030a31038a8
35,337
import pathlib def _find_nested(d1, d2): """ Find paths in d1 that are nested inside paths in d2. Returns tuples with keys `(d1_key, d2_key)` where `d1_path` was a subdirectory of `d2_path`. """ # Copy to ensure we don't alter # original dicts in parent scope d1 = d1.copy() d2 = d2.co...
21b8a9deab9b4ce57987916e98d8ec8c321fd533
35,338
def safe(method): """ Decorator to return safe in case of error. """ def ret(*args, **kw): try: return method(*args, **kw) except Exception as e: log.exception(e) # return result return ret
9d3d99fec1f2e7e53a35858ad3d5d94d10e443c8
35,339
def flashpoint_alert_list_command(client: Client, args: dict) -> CommandResults: """ List alerts from Flashpoint. :param client: Client object :param args: The command arguments :return: Standard command result or no records found message. """ args = validate_alert_list_args(args) respo...
703f14150c3ac1bce3d70bbe32e2e49f617295e2
35,340
def create_user(db, django_user_model: AbstractUser, test_password: str): """ factory for creating users """ def make_user(username, email, first_name, last_name) -> AbstractUser: new_user: AbstractUser = User.objects.create(username=username, email=email, ...
81390a58e4a30b83515c6fa22cb0d42e16a816e6
35,341
def _read_network_data_from_h5(fname): """Read the network stored by the write_network_to_h5 function""" bias_accumulator = [] weight_accumulator = [] with h5py.File(fname, "r") as hdf: n_dense_layers = hdf["n_dense_layers"][...][0] activation = list(hdf["activation"].keys())[0] # Extra...
e78a0966d9ed30cb1c9d35447f91c5c22009fd40
35,342
import json def credentials_from_file(file): """Load credentials corresponding to an evaluation from file""" with open(file) as file: return json.load(file)
8f73c595b4e61757ae454b1674a7177ab4d05059
35,343
import requests def get_workspace_vars(auth, workspace_id): """ Function to get variables created in a workspace """ headers = {"Content-Type": "application/json"} url = f"https://intersight.com/tfc/api/v2/workspaces/{workspace_id}/vars" response = requests.get(url, headers=headers, auth=auth)...
ed05bc7fee86d0303e25fe6ea0b0fd898a08e347
35,344
def locate_btn(game, team_name, mkt_type, verbose=False): """ given selenium game, team_name, and mkt_type returns find the specific bet button for the givens game: selenium obj team_name: str mkt_type: 0 is point spread, 1 is moneyline, and 2 is over/under """ bet_buttons = get_bet_but...
641412d41a1a90153bac456ed56702a3a5abc09c
35,345
def mailchimp_get_endpoint(**kwargs): """Endpoint that the mailchimp webhook hits to check that the OSF is responding""" return {}, http_status.HTTP_200_OK
6e46145b976dae5c77d5b8049da91464669aab40
35,346
def format_date(value, format='%Y-%m-%d'): """Returns a formatted time string :param value: The datetime object that should be formatted :param format: How the result should look like. A full list of available directives is here: http://goo.gl/gNxMHE """ return value.strftime(fo...
3f094918610617e644db69415d987fa770a06014
35,347
def Transpose(node): """(Simple) transpose >>> print(matlab2cpp.qscript("a = [1,2,3]; b = a.'")) sword _a [] = {1, 2, 3} ; a = irowvec(_a, 3, false) ; b = arma::strans(a) ; """ # unknown datatype if not node.num: return "arma::strans(%(0)s)" """ # colvec -> rowvec ...
16f4eb901ee59c424474b5f55264109dc47e6958
35,348
import numbers import collections def get_xml_type(val): """Returns the data type for the xml type attribute""" if type(val).__name__ in ('str', 'unicode'): return 'str' if type(val).__name__ in ('int', 'long'): return 'int' if type(val).__name__ == 'float': return 'float' ...
95a93523d0c982ed2bbd81bba528198915a7eff3
35,349
def DatetimeToWmiTime(dt): """Take a datetime tuple and return it as yyyymmddHHMMSS.mmmmmm+UUU string. Args: dt: A datetime object. Returns: A string in CMI_DATETIME format. http://www.dmtf.org/sites/default/files/standards/documents/DSP0004_2.5.0.pdf """ td = dt.utcoffset() if td: offset =...
706faec64a116ad4dc255b6ff9b87b4a8488bcff
35,350
def _add_suffix(params, model): """Add derivative suffixes to a list of parameters.""" params_full = params.copy() suffix = { "basic": {}, "derivatives": {"derivative1"}, "power2": {"power2"}, "full": {"derivative1", "power2", "derivative1_power2"}, } for par in param...
178b71bb24dde36c262d115e485b568fe0bef503
35,351
import os def format_config(args): """ Formats default parameters from argparse to be easily digested by module """ fn_train = os.path.abspath(args.dataset_path) #Calculate area_min and area_max if none provided (default) if args.area_min==args.area_max: data = pd.read_csv(fn_train+'....
c94fe235a63574cde1e957fc7466d569044ceb55
35,352
def _random_covariance_matrix(batch_size): """Generate a batch of random covariance matrices. Args: batch_size: Number of elements in the first dimension returned. Returns: A tensor with dimensions [batch_size, 2, 2]. """ # Make a random covariance matrix by taking the outer product of 10 random #...
19ab668bc43e4213ed5b4a042730f9953424b37f
35,353
def parse_ranges_highlight(ranges_string): """Process ranges highlight string. Args: ranges_string: (str) A string representing a numerical range of a list of numerical ranges. See the help info of the -r flag of the print_tensor command for more details. Returns: An instance of tensor_forma...
263c6b11d123277e6a2636c482ba045751a8863d
35,354
def have_instance(nova_connection: NovaConnection, instance_name: str): """ Check if the instance_name is in the same region that nova_connection :param nova_connection: NovaConnection :param instance_name: str content the instance name :return: bool """ for server in nova_connection.conne...
4174a3817301007f3cb5eaab02bfc8c14b7526fd
35,355
import torch def torchify_dict(data: dict): """ Transform np.ndarrays to torch.tensors. Parameters ---------- data : dict property data of np.ndarrays. References ---------- .. [1] https://github.com/ken2403/schnetpack/blob/6617dbf4edd1fc4d4aae0c984bc7a747a4fe9c0c/src/schnetp...
fbfc2a05e6e6710bae1aee8487c277f463b58225
35,356
import io import subprocess import sys def run_command_output_file(cmd, output_file_name, shell_executable=None, directory=None, osenv=None, input_file_name=None, ...
cf51a98d05b7246010da3c98fa7ccae73cacb50b
35,357
def select_black_ou(board): """ 手番側の有効な王の利きを求めるために使う :param board: :return: """ # 桂馬で王手されているかを調べるために、擬似的に王から桂馬の効きを計算する # 王の通常の動きの計算もある # 2回使うので、collectionに登録する name = 'black_short_ou' collection = tf.get_collection_ref(name) if len(collection) == 0: selected = tf.to_...
7b30d104b6fb916b7b70025f7812dc2fd26a4bad
35,358
def bytes_to_decimal_bytes(bytes_decimal_str, is_little_endian=False): """ :param bytes_decimal_str: :param is_little_endian: :return: """ if not bytes_decimal_str.isdigit(): raise Exception('bytes_decimal_str 不是数字字符串!') return length = len(bytes_decimal_str) tmp_list = ...
2a5dbbfe643919c20e764268ca4046151d80eaf2
35,359
import logging def cython_img2d_color_std(img, seg, means=None): """ wrapper for fast implementation of colour features :param ndarray img: input RGB image :param ndarray seg: segmentation og the image :param ndarray means: precomputed feature means :return: np.array<nb_lbs, 3> matrix features pe...
59aba28502c7dd648d1a6768d6eeac9f3a7bd767
35,360
from .. import sim from ..support.morlet import MorletSpec, index2ms from scipy import signal as spsig def prepareSpectrogram( sim=None, timeRange=None, electrodes=['avg', 'all'], pop=None, LFPData=None, NFFT=256, noverlap=128, nperseg=256, minFreq=1, maxFreq=100, st...
209f0f58878a36184d93824d84e07fa4e00a146b
35,361
def mock_func_call(*args, **kwargs): """ Mock function to be used instead of benchmark """ options = Options() cost_func = make_cost_function() results = [] result_args = {'options': options, 'cost_func': cost_func, 'jac': 'jac', 'hes...
9dd8c1e928f649f8acea70e423f08df29fb9c59c
35,362
def _full_gauss_den(x, mu, va, log): """ This function is the actual implementation of gaussian pdf in full matrix case. It assumes all args are conformant, so it should not be used directly Call gauss_den instead Does not check if va is definite positive (on inversible for that mat...
6828755f0dc526009babe48ec31b14977e1187eb
35,363
def load_texture_pair(filename): """ Handles textures """ return[ arcade.load_texture(filename), arcade.load_texture(filename, mirrored=True) ]
20cd31cc09dfc6a503e678135b1de406263c8719
35,364
def set_field_value(context, field_value): """populates variable into a context""" if field_value: context['field_value'] = field_value else: context['field_value'] = '' return ''
68110380f244b78550a04d08ad9bda5df193211e
35,365
def get_bbox(src_bbox, offset): """src_bboxにoffsetを適用し、元の領域を復元する。 RPNから得たoffset予測値をアンカーボックスに適用して提案領域を得る。といったケースで利用する。 Args: src_bbox (tensor / ndarray): オフセットを適用するBoudingBox。 Its shape is :math:`(R, 4)`. 2軸目に以下の順でBBoxの座標を保持する。 :math:`p_{ymin}, p_{xmin}, p_{ymax},...
3afc2cacbd86a6b507c14b7623a1759148ca71fc
35,366
def show_books(object_list): """ 加载指定书籍列表的模板。 :param object_list: Book模型实例的列表 :return: 返回一个字典作为模板的上下文 """ if len(object_list) > 0: try: getattr(object_list[0], 'object') except AttributeError: pass else: object_list = map(lambda ele: e...
034707460c73eed6e69578726c860ee55a070ac6
35,367
def load_mesh_from_file(filepath, color=None, alpha=None): """ Load a a mesh or volume from files like .obj, .stl, ... :param filepath: path to file :param **kwargs: """ actor = load(str(filepath)) actor.c(color).alpha(alpha) return actor
49d4a1aa576d2df3d18647f0b48cd84662f9f713
35,368
import six def find_html_form(forms, form_match): # type: (Dict[AnyKey, Form], FormSearch) -> Optional[Form] """ Searches for the specified form amongst a group of multiple forms. :param forms: Possible forms to distinguish and look for a specific one. :param form_match: Search criteria t...
7168a9b2734a7f67bb0e490700689c5e92f18b6e
35,369
import re from typing import OrderedDict def parse_dict(s, sep=None): """ parser for (ordered) dicts :s: the input string to parse, which should be of the format key1 := value1, key2 := value2, key3 := value3, ...
dcfdec6dcc68661f5d27f49a280326bec6cfd90b
35,370
def compute_pdi(value_matrix, slice_list): """ Computes a 'preference' discordance index :param value_matrix: :param slice_list: :return: """ pdi = ['x'] pdimax = ['x'] for i in slice_list: incident = compute_incident(value_matrix, i) complement = invert_matrix(incide...
e4dafa4259a0d8ecdd496a18cca6dc7cd44c69ad
35,371
def sublist_search(array1, array2): """ :param array1: sublist :param array2: list :return: Whether list contains sublist Time complexity: O(n * m) """ # Empty array if len(array1) == 0: return True for start_idx in range(len(array2)): if check_is_contained(array1, a...
905d89b1a831e5f3d0ae2ee3c7fdbe6956bbd507
35,372
import numpy import itertools import scipy def E_ab(a, b, edgePair, width, height, debug = False): """ Calculate the energy in the inverval a to b. Parameters: a, b - interval to integrate over edgePair - the edge pair to interpolate width, height - texture's dimensions Returns...
efab829ee0689ed57906119b65c2d05cb4e4575d
35,373
def get_instance_names(node: AST) -> list[str]: """Extract names from an assignment node, only for instance attributes. Parameters: node: The node to extract names from. Returns: A list of names. """ return [name.split(".", 1)[1] for name in get_names(node) if name.startswith("self...
c96d4e0b5a79845f695e8ee6c48a1db544670692
35,374
def is_geq_than(x,y): """ x is not None and greater than or equal to y """ if x != None: if x>=y: return True return False
706e801cb23673ed094e330ee8582aaf14fe85c3
35,375
def distr_selectbox_names(): """ Accessing stats.name. """ names = ['alpha', 'anglit', 'arcsine', 'argus', 'beta', 'betaprime', 'bradford', 'burr', 'burr12', 'cauchy', ...
5051cab27bf6497d3dfb4d4828daeaeefa528403
35,376
def read_file(filename): """Read filename; return contents as one string.""" with open(filename) as my_file: return my_file.read()
fa4b47085f5d3ace5c011fcda27e6ffa94c7085a
35,377
def remove_intercept_column(X: np.ndarray) -> np.ndarray: """ Remove the first column """ if len(X.shape) == 1: return X[1:] return X[:, 1:]
40b8bccab207e3293cca69ed99f641dbe4a17198
35,378
from typing import Tuple def get_user_configurations() -> Tuple[list, list]: """ Function that reads the $HOME/.pip folder and return two lists, containing filenames and absolute path from them. """ pip_config_path = UserPath.PIP_CONFIG_DIRECTORY.value config_filenames = read.get_user_config...
422f34ed175a31b3b3070154ecb0c38cd1ca19d9
35,379
from summarycode.copyright_tallies import (author_tallies, copyright_tallies, holder_tallies) def compute_codebase_tallies(codebase, keep_details, **kwargs): """ Compute tallies of a scan at the codebase level for available scans. If `keep_details` is True, ...
c4fbccc707c3791e8994feabdf4eb8c9843a9cc8
35,380
def say(number): """ print out a number as words in North American English using short scale terms """ number = int(number) if number < 0 or number >= 1e12: raise ValueError if number == 0: return "zero" def quotient_and_remainder(number, divisor): """ retu...
42b8d321c001c60e37f6bbd94bd2a3404ddf5c66
35,381
def get_s3_versions(bucket_name, key_name): """Get versioning information for a given key. :param bucket_name: the bucket's name :type bucket_name: string :param key_name: the key's name :type key_name: string :return: for each version, the version id and the last modified date :rtype: a li...
85fc1f51f69e4cc326f043be7c65d48df3343854
35,382
def indentitems(items, indent, level): """Recursively traverses the list of json lines, adds indentation based on the current depth""" res = "" indentstr = " " * (indent * level) for (i, item) in enumerate(items): if isinstance(item, list): res += indentitems(item, indent, level+1) ...
91adea46ab0cda227167869235e5e54311ab199a
35,383
def dcg_at_k(r, k): """ Args: r: Relevance scores (list or numpy) in rank order (first element is the first item) k: Number of results to consider Returns: Discounted cumulative gain """ assert k >= 1 r = np.asfarray(r)[:k] != 0 if r.size: return n...
18b862b819170fb0c8049f57fe2c1448fc277260
35,384
def switch(parser, token): """ Switch tag. Usage:: {% switch meal %} {% case "spam" %}...{% endcase %} {% case "eggs" %}...{% endcase %} {% endswitch %} Note that ``{% case %}`` arguments can be variables if you like (as can switch arguments, buts t...
f4522eaacbca83e17a604c57026a07abeea42fb7
35,385
import re def rm_noise(diff): """Filter out noise from diff text. Args: diff (str): diff text Returns: str: cleaned diff text """ result = diff patterns = ["\n", "\u0020+", "་+?"] for pattern in patterns: noise = re.search(pattern, diff) if noise: ...
8a139f22e30e3c98b1dfef3b47fa623db8b22a29
35,386
async def auth_relogin(sessionid: str = Form(...), clients: ClientStorage = Depends(get_clients)) -> str: """Relogin by username and password (with clean cookies) """ cl = clients.get(sessionid) result = cl.relogin() return result
829981336379e157f164beadffdbc5c576e095a1
35,387
def delete_qsession_command(session_id: str, cloud_request_id: str) -> dict: """ Delete a queued RTR session command by session ID and cloud request ID :param session_id: :param cloud_request_id: """ endpoint_url = '/real-time-response/entities/queued-sessions/command/v1' if he...
dd2bab4531d3a0523022e46245b6d41ef202684d
35,388
def dict_factory(cursor, row): """ convert sursor into dict """ result = {} for idx, col in enumerate(cursor.description): result[col[0]] = row[idx] return result
9de5c6252cb36961c645c9b43bd5f7a8a66b4deb
35,389
def variant_with_no_attributes(category): """Create a variant having no attributes, the same for the parent product.""" product_type = ProductType.objects.create( name="Test product type", has_variants=True, is_shipping_required=True ) product = Product.objects.create( name="Test product...
9bf4f09456d00f638e99cc2b6218f54de627f193
35,390
def spec_resid(pars,wave,flux,err,models,spec): """ This helper function calculates the residuals between an observed spectrum and a Cannon model spectrum. Parameters ---------- pars : array Input parameters [teff, logg, feh, rv]. wave : array Wavelength array for observed spect...
d8ea49975717693ec8b6b4003e035e04a847c9b4
35,391
from typing import Tuple from typing import List from typing import Dict from operator import pos def return_mospp( source_coord: Tuple[float, float], target_coord: Tuple[float, float], ) -> List[Dict[str, str]]: """ Find the least polluted path. secretfile: Path to the database secretfile. instan...
327491a32d854320c6a826889521b10531ec73bb
35,392
import calendar def timestamp_d_b_Y_H_M_S(value): """Convert timestamp string to time in seconds since epoch. Timestamps strings like '18 Jun 2013 12:00:00 GMT' are able to be converted by this function. Args: value: A timestamp string in the format '%d %b %Y %H:%M:%S GMT'. Returns: ...
20484ba19cf54c4b152763a5170568f18d0ca492
35,393
def constrained_fit( model_constructor, pdf_transform=False, default_rtol=1e-10, default_atol=1e-10, default_max_iter=int(1e7), learning_rate=1e-6, ): """ Wraps a series of functions that perform maximum likelihood fitting in the `two_phase_solver` method found in the `fax` python mo...
4febeb404746bd233b7a936826380b5d5b9d49b1
35,394
import numpy def word2array(ft_names, word): """Converts `word` [[(value, feature),...],...] to a NumPy array Given a word consisting of lists of lists/sets of (value, feature) tuples, return a NumPy array where each row is a segment and each column is a feature. Args: ft_names (list): l...
4305f7b85287f70ffc7cb9ade2c8c2663dc11659
35,395
from typing import List from typing import Sequence from typing import Dict from typing import Union import random def random_motif_search( sequences: List[Sequence], pattern_length: int, laplace: bool = True, ) -> Dict[str, Union[List[Sequence], Sequence, int]]: """Finds a motif matrix in a randomize...
5b680f5d0015ce50298156a8e7e7755b2591ee6e
35,396
def get_tweet_sentiment(tweets): """ Uses the VADER SentimentIntensityAnalyzer from NLTK to classify tweet sentiment polarity. Takes in input a list of tweets (text-only, not JSON). Checks which party a tweet refers to and averages the score for all tweets for each party. Returns a dictionary of the...
75edd974b667f1409f9261522c5dd5c338b5ae4b
35,397
import os def find_final_status_files(path): """Find all files named `final_status.json` in qcg-pilotjob auxiliary directories in given path. First we look for auxilary directories, and then in those dirs we look for `final_status.json` files. Args: path (str): path to directory where to look for...
9662888c1ef92ba98b1948769175b3da7158b412
35,398
def external(field): """ Mark a field as external. """ field._external = True return field
83de43305f9655aa2be9c6b7264552bd3e2783f7
35,399