content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_tm_team_links(url): """Get links for each team from the league page.""" soup = get_soup(url) table = soup.find_all('table')[3] links = table.find_all('a', class_='vereinprofil_tooltip') links = [l['href'] for l in links] links = list(set(links)) links = [f'https://www.transfermarkt.c...
9bea824be99cb9a7c49deecb4638fecd5b156597
68,400
import os import glob def plot_k_vs_num_tubes(tube_length, num_configs, grid_size, dim, legend=True, exclude_vals='', tunneling=False, max_tube_num=100000, force_y_int=False, y_max=None, dec_fill_fract=True, w_err=True): """Plots REDUCED thermal conductivity k-k_0/k...
74967e0b8f819341a06931d4620a3a6d37721c7f
68,401
import pytz from datetime import datetime def get_now_utc(no_microseconds=True): """ This method returns now's datetime object UTC localized. :param no_microseconds: sets whether microseconds should be cleared. :return: the just created datetime object with today's date. """ if no_microseconds...
86684073044ac42d60a40c0ec3aa6c944614aefb
68,402
import subprocess def os_run(*command, stdout=True): """ Run given command. :param command: command to run :param stdout: prints output to stdout if true, otherwise - returns output :return: Output or None """ to_run = command[0] test = subprocess.Popen(to_run, stdout=subprocess.PIPE)...
46de5d4c5b0ee97dcbdbc2371518e55cca5d33b6
68,403
from bs4 import BeautifulSoup import re def preproces_text(sentence): """ Function that preprocess input sentence: tokenize, lowwer the words and removes speacial characters from each sentence """ soup = BeautifulSoup(sentence, "html.parser") sentence = soup.get_text() sentence = re.sub("\[[^]...
2b72809ffe8639bd6b4dbf068e97d3c0fcb64fdb
68,404
import numpy def CsPadElement(data3d, qn, config): """Construct one image for each quadrant, each with 8 sections from a data3d = 3 x 2*194 x 185 data array. This function was originally written by Ingrid Ofte for pyana's XtcExplorer module. XXX Documentation! """ # If any sections are missing, insert ...
088304c77a37855d57a307827f3ed7ff78e73499
68,405
def to_hcl_map(key: str, config: DictConfig): """ Helper to return a dictionary of config into a HCL map """ hcl_map = f"{key} = {{\n" for key, value in config.items(): hcl_map = f'{hcl_map} {key} = "{get_env_var(value)}"\n' return f"{hcl_map} }}"
3d55c7cd27ff7be034c6f9e9919761285a309d01
68,406
def get_shows(): """ Returns all shows on the minerva DB """ # connect to the database db = connect_minerva_db() # return all the shows as a list shows = list(db.shows.find()) return shows
fba3c3db4a9a559169994f2b1aea224945b6bfaf
68,407
def get_risksense_host_finding_context(resp_hostfinding): """ Prepare context data for "risksense-get-host-findings" and "risksense-get-host-finding-detail" command. :param resp_hostfinding: host finding response :return: list of host finding context """ return { 'HostID': resp_hostfind...
9c454a17956bba5a3c5dfe1ab9f0dd09f841347f
68,408
def comp_stft_average(values): """Computes the average of the Short-Time Fourier Transform Parameters ---------- values: ndarray ndarray of the field Returns ------- Average of the Short-Time Fourier Transform """ # To do nperseg = 3200 noverlap = int(nperseg * 0.75) ...
7c7bebd992999593b55481e8db0783366fc4a555
68,409
def register_encryption_handler(instance, **options): """ registers a new encryption handler or replaces the existing one if `replace=True` is provided. otherwise, it raises an error on adding an instance which it's name is already available in registered handlers. :param AbstractEncrypterBase ...
e9a851a0f2c249580a4bde24fb0d29c62d47987d
68,410
import os def check_converted(file_name, dst_path): """ :param file_name: filename with full path :param dst_path: tfrecord save path :return: flag of converted or new file """ base_name = file_name.split('/')[-1] base_name = base_name.split('.')[0] dst_file = os.path.join(dst_path, ba...
a3fa5a068b9a2a1d8e8a6bc4056ce4b816227423
68,411
def svn_fs_begin_txn(*args): """ svn_fs_begin_txn(svn_fs_txn_t txn_p, svn_fs_t fs, svn_revnum_t rev, apr_pool_t pool) -> svn_error_t """ return apply(_fs.svn_fs_begin_txn, args)
8631f732be827d8c4a481fcd59b14817c6fbd8d6
68,412
import tqdm import torch def train_model_sepQA_v2(net, trainloader, validloader, epochs, lr, grad_accum_steps=1, warmup_epoch=1, milestones=[5, 10], gamma=0.2, pair_w=None, l2=0.0): """ pair """ net = net.cuda() if pair_w is None: PAIR_WEIHGT = 1.0 else: PAIR_WEIHGT = pair_w ...
04c0f43810a33a7847cc7c3f16202a3b543a5f9c
68,413
def region_of_content_of_headline_at_point(view, from_point): """Extract the region of the content of under current headline.""" _, level = headline_and_level_at_point(view, from_point) if level == None: return None if is_content_empty_at_point(view, from_point): return None line_n...
d3c3cdd69313f02621021035acffb1c8764aeec0
68,414
import numpy def summary_bed(args): """Filter bed file on percentage of sites being called and context""" bed_in_handle = open(args.bed,'r') bed_out_handle = open(args.bedout,'w') header = bed_in_handle.readline().split('\t') group_info, header_out = parse_sample_inf(args) bed_out_handle.write...
04505c02c670a8198b88a5f9890c257ccf05af2d
68,415
import os def main(): """ Import image from object storage into custom images repository. Returns ------- int: 0 on success, raises exception on failure. """ # # set locale lc_all_to_set = get_config_data('lc_all') os.environ['LC_ALL'] = "%s" % lc_all_to_set _logger.de...
bb42d1666b170050cf6226d230b9f838321eb980
68,416
def floatdiff(x, y): """ Return the (broadcasted) order difference from x to y. Inputs x and y must be both float32 or both float64. """ x = asanyarray(x) y = asanyarray(y) if x.dtype is not y.dtype: raise TypeError("%s is not %s" % (x.dtype, y.dtype)) if x.dtype.type is float...
94c8b83dbb0b491140545bc195cf24090ab2c5f7
68,417
from typing import Optional import subprocess def execute_extended( cmd: str, *, timeout: Optional[float] = None, stdin: STREAMTYPE = PIPE, stdout: STREAMTYPE = PIPE, stderr: STREAMTYPE = PIPE, ) -> Result[CompletedProcess, Error]: # type: ignore[type-arg] """Execute shell command, get th...
c08dc6a377a98e068fd5cb2a32b64c29e74cd7cd
68,418
def asnr_activate(x, sr, wind, hop, nfft, noise=None, zphase=True, noisesmooth=.98, llkthres=.15, rule='wiener', fn='classic'): """Implement a priori SNR Estimation in the view of nonlinear activation. This implementation should be identital to asnr, except the estimation of mu is interpr...
0d5eff4837fb7b7fe5d6901859bccb7cd978d57b
68,419
def update(table_name, rowid, values): """Updates a table with new field values. Args: table_name: name of table in database. rowid: id of row to be updated. values: dictionary of fields and values to be updated. Returns: Dictionary of newly updated table row. """ table_entry = {tabl...
c43877c4ec1d01b5a98bb36f10ded6965ff9e6f4
68,420
def f(z): """ vector form of sigmoid activation function """ return np.vectorize(sigmoid)(z)
8ee1bfb8520e210095080e1424089155fde92d9f
68,421
def can_t_attack(size, board): """Check that none of the queens can attack each others. Args: size (int): size of the board board (array): 2 dimensional array containing the content of the board Returns: [boolean]: True, if none of them can attack """ if not isinstance(board, Bo...
7a7566e85964ebe03c1b02e571289d54298abfdf
68,422
def get_reader_versions(reader): """Return the available versions for a given reader.""" records = get_reader_output_records([reader]) return {record['version'] for record in records}
802f3e27fbf44739e92c9266f9952891b52fd878
68,423
def launch_from_devices(devices, auto_exit=False): """Alternate entry point for non-cli testing of loader.""" app = get_qapp() suite = TyphosSuite.from_devices(devices) if auto_exit: QTimer.singleShot(0, app.exit) return launch_suite(suite)
a5425200e88dd1e78d3c4dac5f28851529594589
68,424
def playing(): """Retrieve playback status.""" return status().playing
c8c25337b171cfa1eeb0dfc5573673309360a35e
68,425
def shorten(s: str, max_len: int = 60) -> str: """Truncate a long string, appending '...' if a change is made.""" if len(s) < max_len: return s return s[:max_len-3] + '...'
8bafe69253e12a67fdb4c476a2d4b55f6ad4d2af
68,426
import json def elasticsearch_bulk_decorate(bulk_index, bulk_type, msg): """ Decorates the msg with elasticsearch bulk format and adds index and message type""" command = json.dumps({'index': {'_index': bulk_index, '_type': bulk_type}}) return '{0}\n{1}\n'.format(command, msg)
e215ab15b347046b22dcc46317632c68fa9d36c0
68,427
def bbh_final_spin_average_non_precessing( *args, fits=FINALSPIN_FITS, return_fits_used=False ): """Return the final spin averaged across multiple non-precessing fits Parameters ---------- mass_1: float/np.ndarray float/array of masses for the primary object mass_2: float/np.ndarray ...
88f3371fe0fdcb825d7cb216374f59151718e076
68,428
from typing import Optional from typing import List import json import os def split( N: int = 5, seed: int = 1, ddir: Optional[str] = None, use_defaults: bool = True ) -> List[List[str]]: """Split dataset into N parts of equal size. When use_defaults is active, we expect a default_splits.json file in the...
faca066d82aa34f368edb88ddd418789ce40ecf2
68,429
from typing import Any from typing import get_args from typing import get_origin from typing import Collection from typing import Tuple from typing import Literal def get_dims(type_: Any) -> Dims: """Parse a type and return dims. Example: All of the following expressions will be ``True``:: ...
9ed40eda5d206190eace20c4c4502b553c3bd3a5
68,430
import os def CheckForExit(): """Check if the script should exit. If so, return True.""" if not os.path.isfile(RUNNING_FILE): print(" RELION_IT:", RUNNING_FILE, "file no longer exists, exiting now ...") return True return False
b599aa426ceacf67a450838235ba85af038081ee
68,431
import os def get_results(X, y): """Trains batch, stochastic and minibatch gradient descent.""" scores_filename = "GridsearchCV Scores.csv" scores_filepath = os.path.join(datadir, scores_filename) times_filename = "GridsearchCV Times.csv" times_filepath = os.path.join(datadir, times_filename)...
b1075f2d513b0137529a5623b168db409f723281
68,432
import random from jinfo.sequence import DNASeq def random_DNASeq(seq_length: int) -> DNASeq: """ Generate a random DNA sequence Returns: random DNASeq of length seq_length """ dna_base_list = ["A", "T", "C", "G"] seq_list = [random.choice(dna_base_list) for i in range(seq_length)] retu...
d0a3c368837832ad6086388466799701b2e7735d
68,433
def trans(input_seq,stop='*'): """ translate a string this is fast, but note that it doesn't look for invalid characters - it will just translate a codon containing them as "X" """ #import string codon_table['TAA'] = stop codon_table['TGA'] = stop codon_table['TAG'] = stop codon_tabl...
4461fa1b12521b10a7d66dc123f73f403c650bf6
68,434
import itertools def get_hp_fold_iterator(hp_grid, num_folds): """ Create an iterator over all combinations of hyperparameters and folds """ hp_grid = list(hp_grid) folds = list(range(num_folds)) hp_fold_it = itertools.product(hp_grid, folds) hp_fold_it = list(hp_fold_it) return hp_f...
ea16c3b3867dc87a18f2dc1dc2f59e5a48f7c04d
68,435
import re def make_systematic_name(name): """ Something like AddAppealBaseBonusChangingHpRateMax -> Add appeal base bonus changing hp rate max . Word soup for most enumerated skill names but is a good starting point """ return " ".join(re.findall(r"([A-Z]+[a-z]*)", name)).capitalize()
6bd2b1a78091476456b9e2d95a085032c19d28c4
68,436
def yp_processed_reviews(yelp_username): """ Raw form of reviews that contains ony status and reviews. File Type: CSV """ return '../data/processed/{}.csv'.format(yelp_username)
d4be5addf2f8014ebb096493ce9e037b1c4550ac
68,437
def sub_dir_algo(d): """ build out the algorithm portion of the directory structure. :param dict d: A dictionary holding BIDS terms for path-building """ return "_".join([ '-'.join(['tgt', d['tgt'], ]), '-'.join(['algo', d['algo'], ]), '-'.join(['shuf', d['shuf'], ]), ])
73d91f4f5517bbb6966109bd04f111df5f6302e4
68,438
def set_img_path(tgtcmd, new_img_path, cfg) -> (str, list): """ Replace the image path with new_img_path in the program's command and returns the path of the new output image. str is empty if the match failed @return Tuple with first element the new image path and second element the n...
80460d2823618f4ea708dd7871fc8e104b2190a2
68,439
import subprocess def list_snapshots(): """ List snapshots. """ cmd = ['zfs', 'list', '-p', '-t', 'snapshot'] out = subprocess.run(cmd, **SUBPROCESS_KWARGS) lines = out.stdout.splitlines() snapshots = {} if lines: header = lines[0].split() for data in lines[1:]: n...
7d87c2153269771b5d1a34eb210b47134d2b01a0
68,440
def neq(): """ Returns class instance of `Neq`. For more details, please have a look at the implementations inside `Neq`. Returns ------- Neq : Class instance implementing all 'neq' processes. """ return Neq()
1979dc46d4ae59d53aa78cdfbdd5b2940498d352
68,441
def add_conditional_formatting(ws, column, low, high): """Adds conditional formatting to a column in a worksheet Args: ws (worksheet): Worksheet object for the Prompt Payment report column (str): Name of the column to apply the conditional formatting to low (int): The cutoff between gree...
c3539103f70d28707f32c0b7704a907c5e658c87
68,442
def _get_words(data_dir): """Get list of words from history file. Parameters ---------- data_dir : pathlib.Path Directory where data is saved. Returns ------- word_list : list of str List of words. """ words_file = data_dir.joinpath("words.txt") word_list = [] ...
40728b61ed4af05d26a8ece678661cddf838602a
68,443
def list_zoo_datasets(): """Returns the list of available datasets in the FiftyOne Dataset Zoo. Returns: a list of dataset names """ datasets = set() all_datasets = _get_zoo_datasets() for d in all_datasets.values(): datasets |= d.keys() return sorted(datasets)
c5c471608275de783b0fc889e47f3aeb45157cbf
68,444
import os def get_parent_dir_path(path): """ This function is wrapper function for os.path.dirname(os.path.normpath(<path>)). Args: path: a file path [Eg: /home/user/Documents/GitHub/warriorframework] Returns: The parent directory path: [Eg: /home/user/Documents/GitHub] """ r...
e9c3787903799a0962ef2e3ed2444611d327bdcf
68,445
def xception_41(inputs, num_classes=None, is_training=True, global_pool=True, keep_prob=0.5, output_stride=None, regularize_depthwise=False, multi_grid=None, reuse=None, scope=...
98267bad4dcbcaa11c4013379af75dccc15b42e8
68,446
import requests import json def load_data(): """ Get list of events from SloComps. Returns: list: List of telegram messages. """ # Download data. login_url = 'https://comps.sffa.org/user/login' request_utl = 'https://comps.sffa.org/calendar' payload = { 'name': 'teleg...
fa69238a2684c52eb29ef6deda167061638b1d89
68,447
import copy def annotate_paths(paths): """ Annotate a set of paths identifying peculiar types of paths. - **shortest**: topological shortest paths - **fastest**: paths that have minimal duration - **foremost**: first paths that reach the destination - **shortest fastest**:...
a91642bd10fd56e3ac0cad8318a98b68fa93ce35
68,448
def get_task_children_task_types_action(task): """TODO: Add Docstring please """ children_task_types = [] if task.children: for child in task.children: child_children_task_types = get_task_children_task_types_action(child) for type in child_children_task_types: ...
c2fe349832e2086348ab06b7cdcc5fc03b0a8d06
68,449
def random_crop(images, labels, width, height, num_channels, percent): """Randomly crops images with a 20x20 bounding box and resize them to 28x28 Arguments: images: Array of images with shape [batch_size, width * height * num_channels] labels: Array of labels with shape [batch_size...
341b461d4e2755a3e58febe64e8148bb62c0bec9
68,450
import scipy def algebraic_connectivity_directed(G): """ calculate algebraic connectivity a(G) and quantity b(G) of directed graph G, where G is a networkx digraph with Laplacian matrix L Reference: C. W. Wu, "Algebraic connecivity of directed graphs", Linear and Multilinear Algebra, vol. 53, no....
e2df19f36a382ea0b00b9e72b24262e93fc4844e
68,451
def reduction(input_type, output_type): """Define a user-defined reduction function that takes N pandas Series or scalar values as inputs and produces one row of output. Parameters ---------- input_type : List[ibis.expr.datatypes.DataType] A list of the types found in :mod:`~ibis.expr.datat...
1a27ed0ad9004ef655794459abe08340cb5ae67b
68,452
from re import I def repeat_to_match_shape(x, axis, keepdims): """Returns a function that repeats an array along axis to get a given shape. Also returns the number of repetitions of the array.""" if not isarray(x): return I, 1 shape = x.shape if axis is None: dtype=None ...
e3b0948aa8c98911a58eb6ad55ce653076c645bd
68,453
def splitMSOData(cmaxSamples, data): """ splitMSODataPort1( c_int32 cmaxSamples c_int16 array data ) """ # Makes an array for each digital channel bufferBinaryD0 = np.chararray((cmaxSamples.value, 1)) bufferBin...
4e114ada3681b1f3f3d0db89062353868bd96bc5
68,454
def _create_sphere(x0, y0, z0, radius): """ Creates a sphere of a given radius with a given center. Parameters ---------- x0 : int x-coordinate (index) of the sphere's center y0 : int y-coordinate (index) of the sphere's center z0 : int z-coordinate (index) of the sp...
c4479b6724b47e9d4c81950df5c0d9daa56d19f8
68,455
def containsAll(target, keys): """Returns true iff target contains all keys. """ result = ((i in target) for i in keys) return all(result)
75fda44a515e2249bd4c6ee1146c36eb91657b56
68,456
def GetReferenceAssemblies(parentNodes=None): """ Gets the names of USD reference assembly nodes in the scene. If parentNodes is a Maya node name or a list of Maya node names, all assemblies that match or are descendants of those nodes will be returned. Otherwise, all assemblies in the scene will b...
f3c11e2961a735128482c9bd51a70b14271d3580
68,457
def idnencode(domain, encoding='utf-8', errors='strict'): """Encode International domain string.""" if not isinstance(domain, bytes): return domain.encode('idna', errors).decode(encoding) else: return domain.decode(encoding, errors).encode('idna', errors)
3adae031f14a4127b6d2a78f7575b1eb1b165274
68,458
def get_data(cfg): """Gets the Huffman codes table from the source, the current contents of the output file, the new version control string and tells you if the file is up to date The function tries to do the least work possible. If etag or date and file size are the same on the output and the source it will not re...
ed71f5a41a20a21998267e03dd98ab80e7c89234
68,459
def minimize(cost_function): """ Higher order function lifting the cost function into a objective function returning a cipy.algorithms.core.Minimum. Args: cost_function (callable): The cost function to minimize. Returns: callable: Function accepting a solution and returning a ...
f786c774e1f3f6a420f083a732bf54bf82b2fa91
68,460
import time import sys def ldpred_gibbs(beta_hats, genotypes=None, start_betas=None, h2=None, n=None, ns= None, ld_radius=100, num_iter=60, burn_in=10, p=None, zero_jump_prob=0.01, sampl_var_shrink_factor=0.9, tight_sampling=False,ld_dict=None, reference_ld_mats=None, ld_boundaries=...
cd211723528ffadecd1afbc0b347e404eeaedfff
68,461
def dev_version(): """Retrieve the dev version.""" return ver_from_file(DEV_VER_PATH)
67bd0812fb658e15097b1b6497f4bf71c6c42ce6
68,462
def epochs_plot(epochs, legend=True, show=True): """ Plot epochs. Parameters ---------- epochs : dict A dict containing one DataFrame per event/trial. Usually obtained via `epochs_create()`. legend : bool Display the legend (the key of each epoch). show : bool If Tru...
a983bf54a8b8715c91b329e43d9425100e06bf44
68,463
def delete_quiz(request): """AJAX request accessible to teachers to delete quizzes""" if(request.method == "POST" and request.user.is_teacher): quiz = request.POST.get("quiz_pk") try: Quiz.objects.get(pk=int(quiz)).delete() except: raise Exception("unable to dele...
53ea636469683a42a978243c4ce9dbdff3dddcce
68,464
import asyncio def send_custom_message(message, msg, dm=False, user=None, format_content=True): """send_custom_message Sends a message with custom text. :param message: MessageWrapper object with data for formatting. :param msg: str() contents to send. :param dm: [Optional] Whether the message sho...
87416c00903d4deedd1efb42ff06b2ca8363c72d
68,465
def balance_actions(X, y, drop_prob): """ Balance samples. Gets hide of a share of the most common action (accelerate) """ # Condificação da ação acelerar acceler = np.zeros(7) acceler[1] = 1. # Find out what samples are labeled as accelerate is_accel = np.all(y==acceler, axis=1) # Get the i...
a4d5b5bf58156e65001a34ab545b9cd2e46172e1
68,466
def pes_dictionary(mech_str, mech_type, spc_dct, printlog=True): """ Calls mechanalyzer to do the dictionary """ return mechanalyzer.parser.pes.pes_dictionary( mech_str, mech_type, spc_dct, printlog=printlog)
73e8290ee265669ee6b8e28e72019a2527b3fba7
68,467
def cylindrical_bearing_example(): """Create an example of a cylindrical bearing with termo hydrodynamic effects. This function returns pressure and temperature field and dynamic coefficient. The purpose is to make available a simple model so that a doctest can be written using it. Returns -----...
080f37c373ad3fc1a7361a1e6c35149eed1e31ea
68,468
def validate_results(pred_df, labels, thres=0.2): """Compares predicted labels with actual labels Args: pred_df (df): all prediction probabilities labels (series): labels thres (float): minimum threshold to consider a sector present in the predictions """ out = pd.DataFrame( ...
22c2bebd28fbba62bebad3cf2611d4086e1fa74a
68,469
def _roitmpl2roiname(roitmpl): """ generate roiNames out of roitempl written in an amazing function to easyly change pattern for roiNames in all further function at once. This way keep the featureAttributes (fa) consistent """ roiRname = 'Right'+roitmpl roiLname = 'Left...
4e2d198821f8e7cbca80722f41aed811dc0bd598
68,470
def s(feature, n_splines=20, spline_order=3, lam=0.6, penalties='auto', constraints=None, dtype='numerical', basis='ps', by=None, edge_knots=None, verbose=False): """ See Also -------- SplineTerm : for developer details """ return SplineTerm(feature=feature, n_splines=n_splines, spl...
a9673a264ad0c989025fb56f89fe23eaad91d805
68,471
def _strip_external_workspace_prefix(path): """Either 'external/workspace_name/' or '../workspace_name/'.""" # Label.EXTERNAL_PATH_PREFIX is due to change from 'external' to '..' in Bazel 0.4.5. # This code is for forwards and backwards compatibility. # Remove the 'external/' check when Bazel 0.4.4 and...
3fe846b5349f0859fa0bcaa9274a09a64687bc84
68,472
def abs_sobel_threshold(img, direction="x", thresh=(0, 255), ksize=3, bgr=False): """ Applies the Sobel operator in the given direction and return a binary image after applying the threshold. """ gray = convert_to_gray(img, bgr) s = None if direction=="x": s = cv2.Sobel(gray, cv2.C...
f0d10484787e88899fa1c1029d705279caa58f1f
68,473
def convert2gray(img): """ 图片转为灰度图,如果是3通道图则计算,单通道图则直接返回 :param img: :return: """ if len(img.shape) > 2: r, g, b = img[:, :, 0], img[:, :, 1], img[:, :, 2] gray = 0.2989 * r + 0.5870 * g + 0.1140 * b return gray else: return img
42bde7f1c3ced85ea7e2e078063e63361e4d734a
68,474
def decode_status_data(data): """ voltage, current in Amps and Power in Watts data is expected in RAW bytes array converted to int with no command and no checksum """ if len(data) !=7 : print(f"Wrong bytes number in response: '{data}'") return [[]]*3 voltage = bytes_to_in...
80372d8289d94f03f687c08426951be72056a180
68,475
def stub_out_utils_spawn_n(stubs): """Stubs out spawn_n with a blocking version. This aids testing async processes by blocking until they're done. """ def no_spawn(func, *args, **kwargs): try: return func(*args, **kwargs) except Exception: # NOTE(danms): This is ...
e8d920a690d6accd3e6defc63be2c49c4174dae8
68,476
from typing import Tuple def _get_aws_uri_(obj: str) -> Tuple[str, str]: """ Lookup the URI for an AWS S3 object and the profile for accessing it. Lookup the AWS S3 URI and the profile for accessing it. Returns the values as a Tuple (aws_s3_uri, aws_profile) """ aws_bucket = get_setting("AWS...
39f710c484d5fb680e69de9179807bb0bb84428c
68,477
def get_camera_names(inputPath=None): """Read the names of the cameras. Parameters ========== infile : str Full path of the input DL1 file. fileName : str Name of the input DL1 file. Returns ======= camera_names : list(str) Table names as a list. """ if ...
059007b38564024d9b6d2ae7a2ef061894547485
68,478
def after_request(response): """ Enables CORS to allow AJAX requests from the webpage """ response.headers.add("Access-Control-Allow-Origin", "*") response.headers.add("Access-Control-Allow-Headers", "Content-Type,Authorization") response.headers.add("Access-Control-All...
672bbd6637c9a7193ff3e09f83f83a7189cc4120
68,479
import time def return_timestamp(): """ Gets and returns the current local time. :return string timestamp: Current local time in format %Y-%m-%d %H:%M:%S %Z. """ timestamp = time.strftime('%Y-%m-%d %H:%M:%S %Z') return timestamp
a01b6d29e82a8790191626d8e7b155e41b63cf20
68,480
def get_one_differing_var(vars1, vars2): """Checks to see if two sets of variables have one differing one?? """ if len(vars1) != len(vars2): return None ans = None for var in vars1: if var in vars2: if vars1[var] != vars2[var]: if ans is None: ...
64aeb8694331668133dc8ffcf97d32d0bf8ae58b
68,481
import os def query_region_db(ra_center, dec_center, radius, region_dir): """ Returns a list of files relative to regions which are within the provided cone :param ra_center: R.A. of the center of the cone :param dec_center: Dec. of the center of the cone :param radius: Radius of the cone (in arc...
bb4626d4456ed333adeb48601af6960dde2ef2b5
68,482
def _path_to_module_format(py_path): """Transform a python file path to module format.""" return py_path.split("/")[-1].rstrip(".py")
9cf3140edcdf202434da35b35fa219f861b1c20f
68,483
def boolean(value: bool) -> bytes: """Encode a boolean value :param value: Value to encode :raises TypeError: when the value is not the correct type """ if not isinstance(value, bool): raise TypeError('bool required, received {}'.format(type(value))) return common.Struct.short_short.pa...
af8d936ab72b14eff30f3ad6bf191c0dc3ea1669
68,484
import csv def read_csv_file(input_filepath): """ This function reads a .csv file and parses it into a list of dictionaries, where each dictionary is formed from the data on one line of the .csv file. This function takes one argument <input_filepath>, which is the path of the file to be read. You ...
7db24e902c5c8d9086881d3bb8e1fb18e06ccc0d
68,485
def download(cm_response, **data): """ @clmview_user @cm_request_transparent{iso_image.download()} """ return cm_response
ee62f8ed9d870ad720fc064f83d10c0de866d59b
68,486
from typing import Collection from typing import Mapping def _get_val_id_from_collection( val: Collection[object], # noqa: WPS110 ) -> str | object: """Extract a suitible test ID string from a collection, if possible.""" if isinstance(val, Mapping): # static analysis: ignore[undefined_attribute] ...
6fcb2e1b6636decabc29f8508cfa75ac7c12367f
68,487
def get_random_tree(nodes): """ Constructs a dictionary describing a random tree, with the name of the vertices are taken from the 'nodes' :param nodes: list of str Name of the nodes to be used :return: dct keys are the names of the nodes and values their neighbors """ tree = nx....
cf7252d793c803538e8b4c2210772d5e669e56aa
68,488
import os def splitext(p): """パスの拡張子以外の部分と拡張子部分の分割。 os.path.splitext()との違いは、".ext"のような 拡張子部分だけのパスの時、(".ext", "")ではなく ("", ".ext")を返す事である。 """ p = os.path.splitext(p) if p[0].startswith(".") and not p[1]: return (p[1], p[0]) return p
dfbc9599a04b0271e867769566e957a60bb7f87c
68,489
def get_bits_img(image, interval): """Returns only bits specified into the interval Args: image: image to convert using this interval of bits value to keep interval: (begin, end) of bits values Returns: Numpy array with reduced values Raises: ValueError: If min value f...
4bae26013cc811b1efcff0ec76ba599dbf72ec10
68,490
import requests def _konfuzio_session(token: str = KONFUZIO_TOKEN): """ Create a session incl. base auth to the KONFUZIO_HOST. :return: Request session. """ retry_strategy = Retry( total=5, status_forcelist=[429, 500, 502, 503, 504], backoff_factor=2, # allowed_met...
62fd4068f2203a689c4ea652174a1da342c0c1ad
68,491
def markley(k, r0, v0, tof): """Solves the kepler problem by a non-iterative method. Relative error is around 1e-18, only limited by machine double-precision errors. Parameters ---------- k : float Standar Gravitational parameter. r0 : numpy.ndarray Initial position vector wrt a...
620d35424640293ab18a65936f9b63e20c2c98e0
68,492
def disconnect_all_containers_from_network(network_id): """ .. versionadded:: 2018.3.0 Runs :py:func:`docker.disconnect_container_from_network <salt.modules.dockermod.disconnect_container_from_network>` on all containers connected to the specified network, and returns the names of all container...
c9a9751fa9028b6414d4aefcd0adfa44e18ec223
68,493
from typing import List from typing import Tuple def _convert_filters_type( filter: List[Tuple[str, SupportedFilterType]], schema: StateSchema ) -> List[Tuple[str, SupportedFilterType]]: """Convert the given filter's type to SupportedFilterType. This method is necessary because click can only accept a si...
faa7b84b6d91d0878835631875c907152b2c326d
68,494
def enumerate(collection): """ Create a list of lists in which each element of the list is: [index, element]. For example, if you parse a FeatureCollection with 3 Features you'll get: [[0, feat0], [1, feat1], [2, feat2]] :param collection: can be an ImageCollection or a FeatureCollection :return: ee...
aaddc6f53216f1474563d9161fb88e97f7e9fe0e
68,495
import math def scaled_rgb(mag, color_min, color_max): """ Return a tuple of integers, as used in AWT/Java plots. """ try: x = float(mag - color_min) / (color_max - color_min) except ZeroDivisionError: logger.exception("Scaled rgb tried to divide by 0") x = 0.5 # color_max == colo...
242aa4a4032e9198fb94f3201ba6ae863c00031b
68,496
def get_DHT11_output(): """ Gets the data from the DHT11 Temperature and Humidity Sensor. :return: array where index zero is temp and index and index one is humidity. """ data = [] humidity, temperature = Adafruit_DHT.read_retry(11, 4) data.append(temperature) data.append(humidity) r...
ed174a09e3391d8fb15923c64abe1fd4ae397218
68,497
from typing import Union def timezone(name: Union[str, int]) -> Union[Timezone, FixedTimezone]: """ Return a Timezone instance given its name. """ if isinstance(name, int): return fixed_timezone(name) if name.lower() == "utc": return UTC return Timezone(name)
1cbc555a220ef4f02e002ed15cc5fa9be080b98c
68,498
def get_sections(filepath): """Gets the sections from git config.""" reader = get_config_reader(filepath) sections = {} for sec_name in reader.sections(): sections[sec_name] = reader.items_all(sec_name) return sections
708ea648277b68dac8e27d4b799f8930d670eb2b
68,499