content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_maxlevel(divs, maxlevel): """ Returns the maximum div level. """ for info in divs: if info['level'] > maxlevel: maxlevel = info['level'] if info.get('subdivs', None): maxlevel = get_maxlevel(info['subdivs'], maxlevel) return m...
b7153ef84cb260a4b48c58315aa63fc5179fc06c
29,400
def prenut(ra, dec, mjd, degrees=True): """ Precess coordinate system to FK5 J2000. args: ra - arraylike, right ascension dec- arraylike, declination mjd- arraylike """ if degrees: c = np.pi/180. else: c = 1. raout = ra.astype(np.float)*c decout = dec.as...
99cedddc4beacc99c2360ba835f39d927118c683
29,401
def make_model_and_optimizer(conf): """Function to define the model and optimizer for a config dictionary. Args: conf: Dictionary containing the output of hierachical argparse. Returns: model, optimizer. The main goal of this function is to make reloading for resuming and evaluation ...
93a0a7c8f5b31571c5d8a5130c5fd1de0f046adc
29,402
from re import T import numpy def trange(start: int, end: int, step: int=1, dtype: T.Dtype = None) -> T.Tensor: """ Generate a tensor like a python range. Args: start: The start of the range. end: The end of the range. step: The step of the range. Returns: tensor: A v...
140a88069503f2bb372b8f18796a56bb41e465f3
29,403
def get_molecules(topology): """Group atoms into molecules.""" if 'atoms' not in topology: return None molecules = {} for atom in topology['atoms']: idx, mol_id, atom_type, charge = atom[0], atom[1], atom[2], atom[3] if mol_id not in molecules: molecules[mol_id] = {'a...
4bf63000c9d5b56bb9d35922ed521ce81cf3a6c1
29,404
def disk_partitions(all): """Return disk partitions.""" rawlist = _psutil_mswindows.get_disk_partitions(all) return [nt_partition(*x) for x in rawlist]
9c888e365fbd43bacb7ae2a9e025abdf14efcbff
29,405
from typing import Literal def simple_dataset() -> Dataset: """ This is a simple dataset with no BNodes that can be used in tests. Assumptions/assertions should not be made about the quads in it, other than that it contains no blank nodes. """ graph = Dataset() graph.default_context.add((E...
ee897b222d95bc1e92160f925679b9c864c3674a
29,406
import unicodedata import re def slugify(value, allow_unicode=False): """ Taken from https://github.com/django/django/blob/master/django/utils/text.py Convert to ASCII if 'allow_unicode' is False. Convert spaces or repeated dashes to single dashes. Remove characters that aren't alphanumerics, unde...
45a01d4552de0094b56b40a9c13102e59af32b5b
29,407
def is_between(start, stop, p): """Given three point check if the query point p is between the other two points Arguments: ---------- start: array(shape=(D, 1)) stop: array(shape=(D, 1)) p: array(shape=(D, 1)) """ # Make sure that the inputs are vectors assert_col_ve...
f7cf20420115a71fb66ce5f8f8045163fa34c7ff
29,408
def get_elasticsearch_type(): """ Getting the name of the main type used """ return settings.ELASTICSEARCH_TYPE
889cb6e698f88c38229b908dd92d8933ec36ba8e
29,409
def run_cmd_code(cmd, directory='/'): """Same as run_cmd but it returns also the return code. Parameters ---------- cmd : string command to run in a shell directory : string, default to '/' directory where to run the command Returns ------- std_out, std_err, return_code ...
0e001d36df6e0b9b39827f36e1bda369e2185adf
29,410
def unpack_le32(data): """ Unpacks a little-endian 32-bit value from a bytearray :param data: 32-bit little endian bytearray representation of an integer :return: integer value """ _check_input_array(data, 4) return data[0] + (data[1] << 8) + (data[2] << 16) + (data[3] << 24)
c1cdd8f71dbb03769a2e681948300436e6cd735f
29,411
def InductionsFromPrescribedCtCq_ST(vr_bar,Ct,Cq,Lambda,bSwirl): """ Returns the stream tube theory inductions based on a given Ct and Cq. Based on script fGetInductions_Prescribed_CT_CQ_ST """ lambda_r=Lambda*vr_bar # --- Stream Tube theory a_ST = 1/2*(1-np.sqrt(1-Ct)) if bSwirl:...
6b254056b70d65dc20f89811e4938dd7ad5323f6
29,412
from typing import get_origin from typing import Union from typing import get_args def unwrap_Optional_type(t: type) -> type: """ Given an Optional[...], return the wrapped type """ if get_origin(t) is Union: # Optional[...] = Union[..., NoneType] args = tuple(a for a in g...
6ffd9fa6dc95ba669b0afd23a36a2975e29c10da
29,413
import subprocess def tox_get_python_executable(envconfig): """Return a python executable for the given python base name. The first plugin/hook which returns an executable path will determine it. ``envconfig`` is the testenv configuration which contains per-testenv configuration, notably the ``.envn...
f5c7bb8533d55606661a786d1b62ca28cffda778
29,414
def _normalize_angle(x, zero_centered=True): """Normalize angles. Take angles in radians and normalize them to [-pi, pi) or [0, 2 * pi) depending on `zero_centered`. """ if zero_centered: return (x + np.pi) % (2 * np.pi) - np.pi else: return x % (2 * np.pi)
2e73a9fb20743f4721c954a48ca838c1eaca5edd
29,415
def g_fam(arr): """ Returns the next array """ aux = 0 hol = [] while(aux +1 < arr.__len__()): if arr[aux] or arr[aux + 1]: hol.append(True) else: hol.append(False) aux += 1 return hol
4f0ed0d4ba205ef205579a2b150250760e7b38fe
29,416
import time def main_archive(args, cfg: Configuration): """Start running archival""" jobs = Job.get_running_jobs(cfg.log) print('...starting archive loop') firstit = True while True: if not firstit: print('Sleeping 60s until next iteration...') time.sleep(60) ...
17bc1c63896edae46f2db60bd9bbcbd699d6f1ab
29,417
def k2j(k, E, nu, plane_stress=False): """ Convert fracture Parameters ---------- k: float E: float Young's modulus in GPa. nu: float Poisson's ratio plane_stress: bool True for plane stress (default) or False for plane strain condition. Returns ...
7fb34149c7fc9b557ab162632884f605693aa823
29,418
def get_worker_bonus(job_id, worker_id, con=None): """ :param job_id: :param worker_id: :param con: """ bonus_row = _get_worker_bonus_row(job_id, worker_id, con) if bonus_row is None: return 0 return bonus_row["bonus_cents"]
2b58723f275f26c9208a36b650d75596a21354b2
29,419
def get_attribute_distribution(): """ Attribute weights based on position and prototype, in this order: [potential, confidence, iq, speed, strength, agility, awareness, stamina, injury, run_off, pass_off, special_off, run_def, pass_def, special_def] """ attr_dist = { 'QB': { ...
25dc83ba2f4bec4caaa88423e2607af300dcfbc4
29,420
def predict(product: Product): """Return ML predictions, see /docs for more information. Args: product: (Product) the parsed data from user request Returns: A dictionnary with the predicted nutrigrade and the related probability """ sample = { "energy": round(float(...
ca2456989b5cc82f56ed908c5d51471237c68d73
29,421
def get_stock_historicals(symbol, interval="5minute", span="week"): """Returns the historical data for a SYMBOL with data at every time INTERVAL over a given SPAN.""" assert span in ['day', 'week', 'month', '3month', 'year', '5year'] assert interval in ['5minute', '10minute', 'hour', 'day', 'week'] historicals = r...
62612a94e385c8c3703e42f2ace49d4a37d598ef
29,422
import re def re_match_both2( item, args ): """Matches a regex with a group (argument 2) against the column (number in argument 1)""" # setup (re_col1, re_expr1, re_col2, re_expr2 ) = args if re_expr1 not in compiled_res: compiled_res[re_expr1] = re.compile(re_expr1) if re_expr2 not in co...
13ac911e71324f54cde60f8c752603d21df98918
29,423
def at_least(actual_value, expected_value): """Assert that actual_value is at least expected_value.""" result = actual_value >= expected_value if result: return result else: raise AssertionError( "{!r} is LESS than {!r}".format(actual_value, expected_value) )
6897c863d64d1e4ce31e9b42df8aba04f1bbdd7a
29,424
import re import string def clean_text(text): """ Clean text : lower text + Remove '\n', '\r', URL, '’', numbers and double space + remove Punctuation Args: text (str) Return: text (str) """ text = str(text).lower() text = re.sub('\n', ' ', text) text = re.sub('\r', ' ', t...
2d9ddf56a9eeb1a037ec24a8907d3c85c9bbee43
29,425
import fnmatch def fnmatch_list(filename, pattern_list): """ Check filename against a list of patterns using fnmatch """ if type(pattern_list) != list: pattern_list = [pattern_list] for pattern in pattern_list: if fnmatch(filename, pattern): return True return False
72204c3168c0a97ad13134dcb395edf5e44e149f
29,426
def math_div_str(numerator, denominator, accuracy=0, no_div=False): """ 除法 :param numerator: 分子 :param denominator: 分母 :param accuracy: 小数点精度 :param no_div: 是否需要除。如3/5,True为3/5,False为1/1.6 :return: """ if denominator == 0 or numerator == 0: return 0 if abs(numerator) < ab...
bbcead0ec0f79d8915289b6e4ff23b0d6e4bf8ed
29,427
from datetime import datetime def create_comments(post): """ Helper to create remote comments. :param post: :return: """ comment_list = list() post = post.get('posts')[0] for c in post.get('comments'): comment = Comment() comment.author = create_author(c.get('author'))...
48bbad23a60efdd0ad47b2dfeb2e5b943a2743af
29,428
def zero_fuel(distance_to_pump, mpg, fuel_left): """ You were camping with your friends far away from home, but when it's time to go back, you realize that you fuel is running out and the nearest pump is 50 miles away! You know that on average, your car runs on about 25 miles per gallon. There are 2 gal...
67a69b59d6f35a872f87e18ee0e8693af886c386
29,429
import itertools def get_routing_matrix( lambda_2, lambda_1_1, lambda_1_2, mu_1, mu_2, num_of_servers_1, num_of_servers_2, system_capacity_1, system_capacity_2, buffer_capacity_1, buffer_capacity_2, routing_function=get_weighted_mean_blocking_difference_between_two_syst...
fad50cb2a160ba569788ea4f546eb4f0292d47c0
29,430
def astrange_to_symrange(astrange, arrays, arrname=None): """ Converts an AST range (array, [(start, end, skip)]) to a symbolic math range, using the obtained array sizes and resolved symbols. """ if arrname is not None: arrdesc = arrays[arrname] # If the array is a scalar, return None...
eca988aac1d0b69ad45907b4d3dd1c6be2e914b3
29,431
def get_union(*args): """Return unioin of multiple input lists. """ return list(set().union(*args))
18025cfd37d64f15daf92aa2ae3e81176cae6e39
29,432
def retrieve(func): """ Decorator for Zotero read API methods; calls _retrieve_data() and passes the result to the correct processor, based on a lookup """ @wraps(func) def wrapped_f(self, *args, **kwargs): """ Returns result of _retrieve_data() func's return value is p...
8a2b441f42e26c69e39d1f22b7624350f3bef8b0
29,433
def specificity(y, z): """True negative rate `tn / (tn + fp)` """ tp, tn, fp, fn = contingency_table(y, z) return tn / (tn + fp+pseudocount)
bf1c835072463e14420939ef56aade365863f559
29,434
import os import re def untag_file(fname, tag, comment=False): """Removes all of a given tag from a given TeX file or list of files. Positional arguments: fname -- file path of file to be edited, or list of file paths tag -- tag to be removed Keyword arguments: comment -- True to process com...
93a7ce3a7f843942ff79ed729f8c17386e723567
29,435
import json import time def deploy_template(template): """ :type template: WavycloudStack :return: cloudformation waiter object """ stack_name = template.stack_name logger.debug(pformat(get_stacks_by())) logger.debug(pformat(json.loads(template.to_json()))) policy = template.get_templ...
176bc8812f24750cffac7f3ae87911946b4924c2
29,436
def get_model_inputs_from_database(scenario_id, subscenarios, subproblem, stage, conn): """ :param subscenarios: SubScenarios object with all subscenario info :param subproblem: :param stage: :param conn: database connection :return: """ c1 = conn.cursor() new_stor_costs = c1.execut...
b77e4155f89ecae0b0bc5e2517aa05a4291f73b5
29,437
def pad_image(image, padding): """ Pad an image's canvas by the amount of padding while filling the padded area with a reflection of the data. :param image: Image to pad in either [H,W] or [H,W,3] :param padding: Amount of padding to add to the image :return: Padded image, padding uses reflection al...
ac797a201191c78a912f43908b214b3374de45d1
29,438
def delta_obj_size(object_image_size, model_image_size): """To compute the delta (scale b/w -inf and inf) value of object (width, height) from the image (width, height) using sigmoid (range [0, 1]). Since sigmoid transform the real input value between 0 and 1 thus allowing model to learn unconstrained. Paramet...
4ba5935a8b87391ba59623d5de5a86f40f35cacd
29,439
def get_relname_info(name): """ locates the name (row) in the release map defined above and returns that objects properties (columns) """ return RELEASES_BY_NAME[name]
538d564d6d0a67101fa84931fd7f7e69ac83f8b2
29,440
def swap(bee_permutation, n_bees): """Foraging stage using the swap mutation method. This function simulates the foraging stage of the algorithm. It takes the current bee permutation of a single bee and mutates the order using a swap mutation step. `n_bees` forager bees are created by swapping two uni...
4679ebe27cba51c095cd0ece3a4aabfcdb6531a8
29,441
def update_boundaries(x=None): """ This is the main processing code. Every time a slider on a trackbar moves this procedure is called as the callback """ # get current positions of four trackbars maxHSV[0] = cv2.getTrackbarPos('Hmax', 'image') maxHSV[1] = cv2.getTrackbarPos('Smax', 'image') ...
d484d242007f906f5cd707ee02d28c9cd580c844
29,442
def get_stream(stream_id, return_fields=None, ignore_exceptions=False): """This function retrieves the information on a single publication when supplied its ID. .. versionchanged:: 3.1.0 Changed the default ``return_fields`` value to ``None`` and adjusted the function accordingly. :param stream_id:...
14adff8dcff2bd89ace9a5ef642898e15b7eeaa7
29,443
def get_grade_mdata(): """Return default mdata map for Grade""" return { 'output_score': { 'element_label': { 'text': 'output score', 'languageTypeId': str(DEFAULT_LANGUAGE_TYPE), 'scriptTypeId': str(DEFAULT_SCRIPT_TYPE), 'forma...
ab44e7cbf67a050bdb08366ebe933cb62eb9b04c
29,444
def flatten_dict_join_keys(dct, join_symbol=" ", simplify_iterables=False): """ Flatten dict with defined key join symbol. :param dct: dict to flatten :param join_symbol: default value is " " :param simplify_iterables: each element of lists and ndarrays is represented as one key :return: """ ...
a133d1a621e4c1fa7ccce78576527a0cf212c0e3
29,445
import logging def prev_factor(target, current): """Given a target to factorise, find the next highest factor above current""" assert(current<=target) candidates = factors(target) if len(candidates) == 1: return 1 logging.info("Selecting previous factor %d of %d given %d" % (candidates[candidates.index(current...
8190d48ec210670adb8dd0c2d72b1738561191ae
29,446
def compute_weight_BTEL1010(true_energy, simtel_spectral_slope=-2.0): """Compute the weight from requirement B-TEL-1010-Intensity-Resolution. Parameters ---------- true_energy: array_like simtel_spectral_slope: float Spectral slope from the simulation. """ target_slope = -2.62 # sp...
64e126822dda2d6ece24cf95e4aef48a656ba4c6
29,447
def blog_post(post_url): """Render post of given url.""" post = Post.query.filter_by(url=post_url).first() if post is None: abort(404) timezone_diff = timedelta(hours=post.timezone) return render_template('blog_post.html', post=post, tz_diff=timezone_diff)
a87068d4fb6394b452b96b83465529681737fc31
29,448
def l2_normalization( inputs, scaling=False, scale_initializer=init_ops.ones_initializer(), reuse=None, variables_collections=None, outputs_collections=None, data_format='NHWC', trainable=True, scope=None): """Implement L2 normalization on ever...
b595699dcae6efd5c18fddc070905b1f41cc832b
29,449
def generate_com_filter(size_u, size_v): """ generate com base conv filter """ center_u = size_u // 2 center_v = size_v // 2 _filter = np.zeros((size_v, size_u, 2)) # 0 channel is for u, 1 channel is for v for i in range(size_v): for j in range(size_u): _filter[i, j, 0] =...
9797739b05724b104c932e07662278443e15eefb
29,450
from typing import List def retrieve_scores_grouped_ordered_pair_by_slug(panelist_slug: str, database_connection: mysql.connector.connect ) -> List[tuple]: """Returns an list of tuples containing a score and the c...
b8efd970a8adcbcbe6bdf8a737502ce174e01531
29,451
from datetime import datetime def set_job_id(): """Define job id for output paths. Returns: job_id: Identifier for output paths. """ job_id = FLAGS.job_id if not job_id: job_id = datetime.datetime.now().strftime('%Y%m%d-%H%M%S') return job_id
974fa455de363a4c5f3fbcb598a3a002c00c2942
29,452
def is_owner(obj, user): """ Check if user is owner of the slice """ return obj and user in obj.owners
f0c49ffe8a8879d1d052f6fc37df596efa021a84
29,453
from typing import Dict from typing import List from typing import Optional def boxplot_errors_wrt_RUL( results_dict: Dict[str, List[PredictionResult]], nbins: int, y_axis_label: Optional[str] = None, x_axis_label: Optional[str] = None, ax=None, **kwargs, ): """Boxplots of difference betwe...
793f17df520c6474744b7d38055f717e9dfec287
29,454
def create_client(admin_user: str, key_file: str) -> CloudChannelServiceClient: """Creates the Channel Service API client Returns: The created Channel Service API client """ # [START channel_create_client] # Set up credentials with user impersonation credentials = service_account.Credent...
b1af051982ad737bdf66b609416c182e675d91f7
29,455
import warnings def fourier_map(sinogram: np.ndarray, angles: np.ndarray, intp_method: str = "cubic", count=None, max_count=None) -> np.ndarray: """2D Fourier mapping with the Fourier slice theorem Computes the inverse of the Radon transform using Fourier interpolation. ...
0444d888a01fc1785ce8bb638d38b21fa7d4064e
29,456
import string import random def password_generator(length=12, chars=None): """ Simple, naive password generator """ if not chars: chars = string.ascii_letters + string.digits return ''.join(random.choice(chars) for _ in range(length))
e94754e8d8ee3cf806ddbe092033f8cbc89496f7
29,457
def get_node_hint(node): """Return the 'capabilities:node' hint associated with the node """ capabilities = node.get('properties').get('capabilities') capabilities_dict = capabilities_to_dict(capabilities) if 'node' in capabilities_dict: return capabilities_dict['node'] return None
8fb28b38238d5c59db5fd42336d18292f4214963
29,458
def execPregionsExactCP(y, w, p=2,rho='none', inst='none', conseq='none'): #EXPLICAR QUÉ ES EL P-REGIONS """P-regions model The p-regions model, devised by [Duque_Church_Middleton2009]_, clusters a set of geographic areas into p spatially contiguous regions while minimizing within cluster heterogeneit...
ea5d165918c6f203cf3cc42f9a1422a538ff133a
29,459
def generate_scale(name, octave, major=True): """ Generates a sequence of MIDI note numbers for a scale (do re mi fa sol la si do). `name` specifies the base note, `octave` specifies in which octave the scale should be, and `major` designates whether the produced scale should be major or minor. ...
8276101a3ec7ddd340f5fa2c24e13b9b321e4307
29,460
def tensor_product(a, b, reshape=True): """ compute the tensor protuct of two matrices a and b if a is (n, m_a), b is (n, m_b), then the result is (n, m_a * m_b) if reshape = True. or (n, m_a, m_b) otherwise Parameters --------- a : array-like of shape (n, m_a) b :...
f7891d1cffa19fb8bdfd2adaa23d2aa94367b8ab
29,461
def disable_user( request, username ): """ Enable/disable an user account. If the account is disabled, the user won't be able to login. """ userModel = get_user_model() try: user = userModel.objects.get( username= username ) except userModel.DoesNotExist: raise Http...
6500c053ee637cd47a4cec6feb7ec72001ccfb6a
29,462
from datetime import datetime def get_next_event(user: User) -> Event | None: """ Get event that provided user has next. """ current_time = datetime.datetime.now().hour*60 + datetime.datetime.now().minute return Event.query \ .join(Event.subject, aliased=True) \ .filter(Subject.use...
ac52bb2a5b0e9f368fccbf93d05fbcc6184462dd
29,463
import math def affineToText(matrix): """ Converts a libcv matrix into human readable text """ tiltv = matrix[0,0] * matrix[1,1] rotv = (matrix[0,1] - matrix[1,0]) / 2.0 if abs(tiltv) > 1: tilt = degrees(math.acos(1.0/tiltv)) else: tilt = degrees(math.acos(tiltv)) if tilt > 90.0: tilt = tilt - 180.0 if...
14a754d804d509b1029c00ae40fbef70735d072f
29,464
import numpy def createBridgeSets(blocksize,operating,MPSS): """Use this function to create the iidx sets for bridges.""" sets = tuple() xul = blocksize[0]-operating xdl = operating yul = int(blocksize[0]/2+operating) ydl = int(blocksize[0]/2-operating) xts = xul xbs = xdl for i in...
a97f44a44e00f4375c3aae0162edca5b78bcd5f1
29,465
def get_uniq_id_with_dur(meta, deci=3): """ Return basename with offset and end time labels """ bare_uniq_id = get_uniqname_from_filepath(meta['audio_filepath']) if meta['offset'] is None and meta['duration'] is None: return bare_uniq_id if meta['offset']: offset = str(int(round(...
62d93703a8b33bbc3e1a533aedac11fec8d59fb1
29,466
def delete(table, whereclause = None, **kwargs): """Return a ``DELETE`` clause element. This can also be called from a table directly via the table's ``delete()`` method. table The table to be updated. whereclause A ``ClauseElement`` describing the ``WHERE`` condition of the ``U...
49d6d98083d4dee0cf7dac62e30ddf90cd383955
29,467
import random import string def oversized_junk(): """ Return a string of random lowercase letters that is over 4096 bytes long. """ return "".join(random.choice(string.ascii_lowercase) for _ in range(4097))
a7bbaadde1948e1644f708c0166aa7833bb25037
29,468
def dcm_to_unrescaled(dcm_dict, save_path=None, show=True, return_resolution=False): """ just stack dcm files together :param return_resolution: :param show: :param dcm_dict: :param save_path: the save path for stacked array :return: the stacked array in float32 """ array_stacked, re...
b4954c4f89100093b501d6e662a8b03eb247039b
29,469
import os def plot_posterior_pair( hddm_model=None, axes_limits="samples", # 'samples' or dict({'parameter_name': [lower bound, upper bound]}) font_scale=1.5, height=2, aspect_ratio=1, n_subsample=1000, kde_levels=50, model_ground_truth=None, save=False, save_path=None, sh...
b74d9892604718b12ba19fd52c894b9ba3cb0fa3
29,470
def change_unit_of_metrics(metrics): """Change order of metrics from bpd to nats for binarized mnist only""" if hparams.data.dataset_source == 'binarized_mnist': # Convert from bpd to nats for comparison metrics['kl_div'] = metrics['kl_div'] * jnp.log(2.) * get_effective_n_pixels() metri...
0435a4caf8c82587f84fb05ae493e43654bdf22e
29,471
import os def get_ff(filename): """Get path to a file in ffxml directory """ file_path = resource_filename('mosdef_slitpore', os.path.join('ffxml', filename)) return file_path
ddfafa054515dff5e84418eab6e149b43a868832
29,472
def step(ram: dict, regs: dict, inputs: list[int]) -> tuple: """Advance robot by a single step :param ram: memory contents :param regs: register map :param inputs: input queue :return: updated pc; new color and turn direction """ pc = regs['pc'] relative_base = regs['rb'] output_val...
4df0395e88a5ccd9f34edd39ea0841d16df6838a
29,473
def replace_start(text, pattern, repl, ignore_case=False, escape=True): """Like :func:`replace` except it only replaces `text` with `repl` if `pattern` mathces the start of `text`. Args: text (str): String to replace. p...
2296503a1c97cc06fa1fcc3768f54595fbc09940
29,474
def setup(params): """Sets up the environment that BenchmarkCNN should run in. Args: params: Params tuple, typically created by make_params or make_params_from_flags. Returns: A potentially modified params. Raises: ValueError: invalid parames combinations. """ # Set up environment variab...
08fc16d2f4dadafcc1e2b13364d7519e5aac4eba
29,475
import copy def copy_excel_cell_range( src_ws: openpyxl.worksheet.worksheet.Worksheet, min_row: int = None, max_row: int = None, min_col: int = None, max_col: int = None, tgt_ws: openpyxl.worksheet.worksheet.Worksheet = None, tgt_min_row: int = 1, tgt_mi...
b98d2dda9fa0915dcb7bc3f4b1ff1049340afc68
29,476
def index(request): """Home page""" return render(request, 'index.html')
66494cd74d1b0969465c6f90c2456b4283e7e2d3
29,477
import ast def get_teams_selected(request, lottery_info): """ get_teams_selected updates the teams selected by the user @param request (flask.request object): Object containing args attributes @param lottery_info (dict): Dictionary keyed by reverse standings order, with dictionary ...
35edfab322ce5ad039f869027552c664f9e6b576
29,478
from testtools import TestCase def assert_fails_with(d, *exc_types, **kwargs): """Assert that ``d`` will fail with one of ``exc_types``. The normal way to use this is to return the result of ``assert_fails_with`` from your unit test. Equivalent to Twisted's ``assertFailure``. :param Deferred d:...
1ff967f66c6d8e1d7f34354459d169bdfe95987a
29,479
def temporal_affine_backward(dout, cache): """ Backward pass for temporal affine layer. Input: - dout: Upstream gradients of shape (N, T, M) - cache: Values from forward pass Returns a tuple of: - dx: Gradient of input, of shape (N, T, D) - dw: Gradient of weights, of shape (D, M) ...
2cf4ead02fdaa0a54f828d09166128f1b5473d0b
29,480
def _make_cmake(config_info): """This function initializes a CMake builder for building the project.""" configure_args = ["-DCMAKE_EXPORT_COMPILE_COMMANDS=ON"] cmake_args = {} options, option_fns = _make_all_options() def _add_value(value, key): args_key, args_value = _EX_ARG_FNS[key](valu...
fdef36f0875438ed0b5544367b4cb3fb5308f43d
29,481
def box_to_delta(box, anchor): """((x1,y1) = upper left corner, (x2, y2) = lower right corner): * box center point, width, height = (x, y, w, h) * anchor center point, width, height = (x_a, y_a, w_a, h_a) * anchor = (x1=x_a-w_a/2, y1=y_a-h_a/2, x2=x_a+w_a/2, y2=y_a+h_a/2) ...
2033c66c89a25541af77678ab368d6f30628d0f5
29,482
def mutual_information(prob1, prob2, prob_joint): """ Calculates mutual information between two random variables Arguments ------------------ prob1 (numpy array): The probability distribution of the first variable prob1.sum() should be 1 prob2 (numpy array): The probability distrubi...
4d6d2738c84092470b83497e911e767b18878857
29,483
def hog(img, num_bins, edge_num_cells=2): """ Histogram of oriented gradients :param img: image to process :param edge_num_cells: cut img into cells: 2 = 2x2, 3 = 3x3 etc. :return: """ if edge_num_cells != 2: raise NotImplementedError w, h = img.shape[:2] cut_x = w /...
d2b7eadda978896826800c7159a8e4604b150aa6
29,484
def get_graph(adj) -> nx.classes.graph.Graph: """ Returns a nx graph from zero-padded adjacency matrix. @param adj: adjustency matrix [[0. 1. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [1. 0. 0. 1. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [1. 0. 0. 0. 1. 1. 0. 0. 0. 0. ...
a62f1c696111e7c4f97bb6fd858fc3bc9e011f6f
29,485
import re import os import six def cert_config(pth_config, config_str, pth_prepend="cert="): """ Update config file located at pth_config with a string(config_str). """ # Determine path of cert from config_str list of strings (first str containing pth_prepend) path_cert = [x.split(pth_prepend) for x in c...
217810b344000bba4c9ba225ca22a1c4e05771b8
29,486
import logging import os def analysis_directed(net, label, outpath): """ Analyze directed network. """ result_dict = dict() # Check whether graph is directed is_directed = net.isDirected() if not is_directed: logging.error('Input graph should be directed.') else: loggin...
d6af414909c9b8bf82668caabbeacb6897c392e9
29,487
import requests import json import re def build_response_message(object_spec, response_message, namespace): """Function to build the response message used to inform users of policy decisions""" try: opa_response = requests.post( opa_url, json=object_spec, headers...
50c273b7a3e0f8c902770f504d6a781ad088cc66
29,488
def findSamplesInRage(pointIds, minVal, maxVal): """根据样本编号的范围[1, 10]处理ID Args: pointIds (ndarray): 样本的ID minVal (Number): 样本范围的起始位置 maxVal (Number): 样本范围的结束位置 Returns: result (ndarray): 样本的ID """ digits = pointIds % 100 result = (digits >= minVal) & (digits <= m...
d2f040480c6513e9b845aaaa13485ecbe3376c41
29,489
def test_results_form_average(fill_market_trade_databases): """Tests averages are calculated correctly by ResultsForm, compared to a direct calculation """ Mediator.get_volatile_cache().clear_cache() market_df, trade_df, order_df = get_sample_data() trade_df, _ = MetricSlippage().calculate_metric(...
92cb07fe56f026f0b1449e07e635db50581cffa9
29,490
from operator import mod def _prot_builder_from_seq(sequence): """ Build a protein from a template. Adapted from fragbuilder """ names = [] bonds_mol = [] pept_coords, pept_at, bonds, _, _, offset = templates_aa[sequence[0]] names.extend(pept_at) bonds_mol.extend(bonds) offsets...
da182a0dd323db2e3930a72c0080499ed643be1a
29,491
def connect_thread(): """ Starts a SlaveService on a thread and connects to it. Useful for testing purposes. See :func:`rpyc.utils.factory.connect_thread` :returns: an RPyC connection exposing ``SlaveService`` """ return factory.connect_thread(SlaveService, remote_service = SlaveService)
557dfbd7a5389345f7becdc550f4140d74cf6695
29,492
from typing import Tuple def yxyx_to_albu(yxyx: np.ndarray, img_size: Tuple[PosInt, PosInt]) -> np.ndarray: """Unnormalized [ymin, xmin, ymax, xmax] to Albumentations format i.e. normalized [ymin, xmin, ymax, xmax]. """ h, w = img_size ymin, xmin, ymax, xmax = yxyx.T ymin, yma...
d6429ca3c694e5f2fd69dba645e3d97cab4720f8
29,493
def parse_tags(source): """ extract any substring enclosed in parenthesis source should be a string normally would use something like json for this but I would like to make it easy to specify these tags and their groups manually (via text box or command line argument) http://stackoverf...
315ea121cec56a38edc16bfa9e6a7ccaeeab1dc2
29,494
def NonZeroMin(data): """Returns the smallest non-zero value in an array. Parameters ---------- data : array-like A list, tuple or array of numbers. Returns ------- An integer or real value, depending on data's dtype. """ # 1) Convert lists and tuples into arrays if ty...
89d466c9d739dc511cd37fd71283ae8c6b2cc388
29,495
def get_99_pct_params_ln(x1: float, x2: float): """Wrapper assuming you want the 0.5%-99.5% inter-quantile range. :param x1: the lower value such that pr(X > x1) = 0.005 :param x2: the higher value such that pr(X < x2) = 0.995 """ return get_lognormal_params_from_qs(x1, x2, 0.005, 0.995)
2ce424a289ea8a5af087ca5120b3d8763d1e2f31
29,496
def summarize_data(data): """ """ #subset desired columns data = data[['scenario', 'strategy', 'confidence', 'decile', 'cost_user']] #get the median value data = data.groupby(['scenario', 'strategy', 'confidence', 'decile'])['cost_user'].median().reset_index() data.columns = ['Scenario', ...
9964d99ed70a1405f1c94553172fd6830371472a
29,497
def gen_cam(image, mask): """ 生成CAM图 :param image: [H,W,C],原始图像 :param mask: [H,W],范围0~1 :return: tuple(cam,heatmap) """ # mask转为heatmap heatmap = cv2.applyColorMap(np.uint8(255 * mask), cv2.COLORMAP_JET) # heatmap = np.float32(heatmap) / 255 heatmap = heatmap[..., ::-1] # gbr t...
a9d221b6d536aef6c2e2093bb20614cf682de704
29,498
def SetInputFilePath(path): """ Set input file name This function updates the file name that is stored in the database It is used by the debugger and other parts of IDA Use it when the database is moved to another location or when you use remote debugging. @param path: new input file path ...
8e776c24848e040c96b7d1978091ed8861949f74
29,499