content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from sympy import Rational def RK44_family(w): """ Construct a 4-stage fourth order Runge-Kutta method **Input**: w -- family parameter **Output**: An ExplicitRungeKuttaMethod **Examples**:: >>> from nodepy import rk >>> print(rk.RK44_family(1)) ...
18782206cbc77c5b64d188169fa6fea362177e29
3,607,400
import sys def callersContext(): """ get context of caller of a function """ return sys._getframe(2).f_code
d849326202c0062da076f54c379fe5f35b4d35b5
3,607,401
def upload_data_db_for_creat_pass(): """Загружает данные по отцам из базы для паспартов.""" logger.debug("Старт upload_data_db_for_creat_pass") list_col = [ 'name', 'number', 'name_number', 'BM1818', 'BM1824', 'BM2113', 'CSRM60', 'CSSM66', 'CYP21', 'ETH10', 'ETH225', 'ETH3', 'ILSTS6'...
8628d0374b9742367f57f85f77d6a75e3aa0478e
3,607,402
import scipy def arbitrary_rotation_matrix(axis, theta): """ Return the rotation matrix associated with counterclockwise rotation about the given axis by theta radians. # Kudos to # https://stackoverflow.com/questions/6802577/rotation-of-3d-vector #import math # # axis = np.asarray(ax...
e5416f1874820dfbdb5685fdf2daa099edee25df
3,607,403
def Gaussian(shape=(3, 3), sigma=0.5): """ 2D gaussian mask - should give the same result as MATLAB's fspecial('gaussian',[shape],[sigma]) """ m, n = [(ss - 1.) / 2. for ss in shape] y, x = np.ogrid[-m:m + 1, -n:n + 1] h = np.exp(-(x * x + y * y) / (2. * sigma * sigma)) h[h < np.finfo(h....
2f168af07d7b9787f78d9fa413cd6f723cb871cd
3,607,404
import os def loadImage(img_path: str) -> pygame.Surface: """ Load image from File system Parameters: img_path -> Path of image """ if os.path.isfile(img_path): return pygame.image.load(img_path) else: return None
bdcb6053d1f5b798887592b17fff465e96ea0d03
3,607,405
def enableDisableEquipment(enable, names): # type: (bool, Tuple[String, ...]) -> List[unicode] """Enables or disables a Tuple of equipment connections from a script. Args: enable: Set to True to enable equipment connections, or set to False to disable them. names: A Tuple of...
6bb1eca2db62cdabf2748bbe6dcec163e0cf806b
3,607,406
from sys import path def _quote_and_validate_dir(dirpath): """ Checking that the directory exists and is absolute Return quoted directory :param dirpath: path to directory """ assert path.isabs(dirpath) return quote(dirpath)
a3e68cce22834adf5db27ee9796c311895ba654f
3,607,407
import struct def get_arg() -> bytes: """ This function returns the (pre-encoded) `password` argument to be sent to the `sudo` program. This data should cause the program to execute our ROP-chain for printing our message in an endless loop. Make sure to return a `bytes` object and not an `str` objec...
829fbde5c8202ec170850b0e9cff891f9e0f27cc
3,607,408
def delay_frame (delay): """Construct a spacer frame with no content that serves as a delay.""" return ( graphics_control_block(delay) + image_descriptor_block(0, 0, 1, 1) + chr(LZW_palette_bits) + chr(1) + chr(trans_index) + chr(0) )
03b227ad66d8125402f040504c16069747faa152
3,607,409
def get_latest_version(package_name, test_database=False): """ Retrieve the latest version of the given package name from PyPi. Return a version of 0.0.0 if no package version information is found. :param package_name: A string specifying the package name to interrogate. :param test_database: A boo...
c977f95a42399d40e6d9e3571f9d945bc726ff5d
3,607,410
import logging def calc_regional_services( enduse, uk_techs_service_p, regions, spatial_factors, fuel_disaggregated, techs_affected_spatial_f, capping_val=1 ): """Calculate regional specific end year service shares of technologies (rs_reg_enduse_tech...
7fb703fca501b441fa985d7a0a778905cdbf30cb
3,607,411
import os import struct def load_mnist(path, kind='train'): """Load MNIST data from `path`""" labels_path = os.path.join(path, '%s-labels-idx1-ubyte' % kind) images_path = os.path.join(path, '%s-images-idx3-ubyte' % kind) # ファイルを読み込む ...
4e00474dc6585f049fb57514d7a7ce6d2c05aa30
3,607,412
from datetime import datetime def get_daily_demographics_age(tiles: np.array(int), day=datetime(year=2020, month=1, day=27)) -> pd.DataFrame: """Fetches daily demographics of age categories Fetches the daily demographics, age distribution, of the tiles and creates a dataframe of the fetched data. ...
095395e5ac2529bd502d798d9afaaa2643eaf76f
3,607,413
def estimate_magnitude(paz, amplitude, timespan, h_dist): """ Estimates local magnitude from poles and zeros or full response of given instrument, the peak to peak amplitude and the time span from peak to peak. Readings on two components can be used in magnitude estimation by providing lists for ``p...
e79fed699599d665dceb06772173f6768e4486ae
3,607,414
def extract_keypoint_index(scoremap): """ Extract Scoremap. # Arguments scoremap: Numpy aray of shape (crop_size, crop-size). # Returns max_index_vec: List of Max Indices. """ keypoint_index = np.argmax(scoremap) return keypoint_index
3c78c64218b3089b85f151e4328ede6c6ca1ffe2
3,607,415
def transpose(incoming, conv, nonlinearity, *args, **kwargs): """ Convenience function to transpose a convolutional layer and use weight tying """ return TransposedConv2DLayer(incoming, conv.input_shape[1], conv.filter_size, stride=conv.stride, ...
66489060e981f66a36fabc625ff729135b7f577f
3,607,416
def downbin_spec_err(specHR, errHR, lamHR, lamLR, dlam=None): """ Re-bin spectum and errors to lower resolution using :py:obj:`scipy.binned_statistic`. This function calculates the noise weighted mean of the points within a bin such that :math:`\sqrt{\sum_i \mathrm{SNR}_i}` within each :math:`i` bin is ...
9a884ea2e3b9c7136f8f20b1ac8f909f9ca8051b
3,607,417
def timebin_dur_from_vec(time_bins, n_decimals_trunc=5): """compute duration of a time bin, given the vector of time bin centers associated with a spectrogram Parameters ---------- time_bins : numpy.ndarray vector of times in spectrogram, where each value is a bin center. n_decimals_tru...
00b9b31a3edff1ceeacb389a1f2331e8ae3034c4
3,607,418
def rgb_to_hex(color): """Helper function for converting RGB color to hex code Args: color (list): List of R,G,B value Returns: str: Hex code for the RGB value """ r,g,b = color #print('%02x%02x%02x' % (r,g,b)) return '#%02x%02x%02x' % (r,g,b)
9308fa029cb2bfd75495c92a2e145f3439e3b60b
3,607,419
def at(seq, msg, cmd=None, *args, **kwargs): """Push a new command""" return translator(seq + 1, msg + clformat("AT*~a=~s,~{~s~^,~}\r", cmd, seq, map(iso_str, globals()[cmd.lower()](*args, **kwargs))))
1080fb5d044556a31e8a5f3d4786334944c6af7d
3,607,420
def L2(v, *args): """Returns the L2 norm of a vector v INPUTS ======= v: list Vector of which the L2 norm to be calculated *arg: list, optional Weight vector RETURNS ======== L2_norm: float float unless len(v) != len(args[0]) in which case a Value...
fe95415fdfdb433dcf75087b943575bf2b7cee5d
3,607,421
def plot_importances(experiment, n_best=15, sort_by='max', calculator=BuiltinImportance(), fontsize=12): """ Visualize feature importances (max, mean and std) of an experiment using a given calculator. :param experiment: Experiment instance, like lb['012ABC'] :param sort_by: one of 'max', 'mean' and 'st...
1a51bb609a325e92dab1e5f02f81580f7e58f9de
3,607,422
def sort_queryset(queryset, request, allowed_sorts, default=None): """ Sorts the queryset by one of allowed_sorts based on parameters 'sort' and 'dir' from request """ sort = request.GET.get('sort', None) if sort in allowed_sorts: direction = request.GET.get('dir', 'asc') sort = ('-' if ...
7d4ef00e0d345d4636caaa9ca69ade0a09e33ea4
3,607,423
def privacy(request): """ The RMG privacy policy. """ return render(request, 'privacy.html', {'admins': settings.ADMINS})
218f1f24691420e76d562a0251cfce983036ed60
3,607,424
from typing import Union import requests from bs4 import BeautifulSoup def get_schedule(day: str, format_: Union[pd.DataFrame, set] = set): """ Return NBA matchups on queried date. Arguments: ---------- day: str Date for which to get schedule. Format = YYYY-MM-DD format_: Uni...
8b29d175d1a1afab302a054793a101941f4027c6
3,607,425
def match(text): """ Parse calendar entry :param text: The entry to parse :return: A pair of description, project key """ return MATCHER.match(text)
6e5124cf13656661adb8e2f952ea65542f65197e
3,607,426
def partial_pullback(b, c, d, b_d, c_d): """Find partail pullback.""" check_homomorphism(b, d, b_d, total=False) check_homomorphism(c, d, c_d, total=False) bd_dom = subgraph(b, b_d.keys()) cd_dom = subgraph(c, c_d.keys()) bd_b = {n: n for n in bd_dom.nodes()} cd_c = {n: n for n in cd_dom.n...
2e71a8f7f7664e294380cf446ac425f2766ef595
3,607,427
def get_colormap_lut(name='flame'): """Get lookup table from one of pyqtgraph's gradient editor's presets. Result is suitable for ImageItem.setLookupTable. Gradient names listed in Gradients.keys(). Not sure how 'hsv' mode works. """ gradient=Gradients[name] ticks=gradient['ticks'] v=np...
d6bc069c8a54538389995e6dd902ab309b2f7c69
3,607,428
import tempfile import subprocess def make_runner_dir(version): """Extract the runner tar to a temporary directory""" dir = tempfile.TemporaryDirectory() tar = _get_runner_tar(version) subprocess.check_call( ["tar", "-xzf", tar], cwd=dir.name, ) return dir
e452fda7b2dd5d1243141cf177e090bade265e93
3,607,429
from typing import Any import json async def get_messages(number: str) -> Any: """ get messages """ response = await run_signal_cli_command(["-u", quote(number), "--output=json", "receive"]) return [json.loads(m) for m in response.split("\n") if m != ""]
8ec57bff19abce43bd96b48391e3d1f0470e70f0
3,607,430
import gzip import pickle def read_pickle(fname, compress=True): """ read analysis from pickle file """ if compress: with gzip.open(fname, "rb") as f0: return pickle.load(f0) else: with open(fname, "rb") as f0: return pickle.load(f0)
040976647b637ee08f33094e13d3a19605495463
3,607,431
import random def _k_init(X: np.ndarray, n_clusters: int, random_state=None) -> np.ndarray: """Initialize kmeans centers by picking a random point as the center""" return np.array([X[random.randint(0, len(X) - 1)] for i in range(n_clusters)])
b1e117c8dbe6d3c3392dd76f7d10872f343a2795
3,607,432
def post_create(request): """ View function for post-create page of site. Param request post form data. Return post create view. """ user = get_object_or_404(User, pk=request.user.id) formData = None form = PostForm() check_route("post", request.META.get("HTTP_REFERER"), request) ...
6f5c4caeebbbace23dc5a91c25fbb8c385c3a561
3,607,433
def extract_path_from_filepath(file_path): """ ex: 'folder/to/file.txt' returns 'folder/to/' :param file_path: :return: """ st_ind=file_path.rfind('/') foldern = file_path[0:st_ind]+'/' return foldern
7014ac6d4fa47edff3315f7e23688cfe2e28a820
3,607,434
def flip_coordinate_system(q): """ as far as i understand it is assumed that we are already in a different coordinate system so we first flip the coordinate system to the original coordinate system to do the original transformation then flip coordinate system again to go back to the flipped coordinate s...
a15fe27e507d8129d2ad0d7cc28c0a033dcf9e5e
3,607,435
def fname_to_string(fname): """Return given file as sring Parameters ---------- fname : str absolute path to file. """ with open(fname) as fid: string = fid.read() return string
f9a3f94dc4a63c27cadb5c5f9a41eaa942332937
3,607,436
import argparse def parse_args(): """ Parse muCLIar args :return: """ parser = argparse.ArgumentParser(description='muCLIar - Music from CLI') parser.add_argument('-s', '--song', type=str, help='Song name', required=True) parser.add_argument('-c', '--config', action='store_true') return parser.parse_args()
ee55696b68927a6c0ff05ab4536a57f7ece91108
3,607,437
def index(): """ Display the home page. :return: Index template. """ user = g.user # get the currently logged in user return render_template("index.html", title='Home', user=user)
a1356d31270bdfd79e6259eb88b563a786902f90
3,607,438
import os import tqdm def read_labeled_image_list(image_dir, data_set="LIP"): """Reads txt file containing paths to images and ground truth masks. Args: data_dir: path to the directory with images and masks. data_list: path to the file with lines of the form '/path/to/image /path/to/mask'. R...
6741cc7f88ef8db3cd321bc94c5f552140466b4e
3,607,439
from typing import Tuple def create_pca_features(x: pd.DataFrame, x_train: pd.DataFrame, x_test: pd.DataFrame) -> Tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame, pd.DataFrame]: """ Compute PCA of given full/training/test data PCA is fitted on the full dataset x ...
866453fa63aa8181c6d2d48166d55d641fe3b038
3,607,440
import pandas as pd import os def aids(path): """Delay in AIDS Reporting in England and Wales The `aids` data frame has 570 rows and 6 columns. Although all cases of AIDS in England and Wales must be reported to the Communicable Disease Surveillance Centre, there is often a considerable delay between the ...
2e508fcf8b59e1c589e043d3e3e25650c99bbecb
3,607,441
def global_color_table(color_depth, palette): """ Return a valid global color table. The global color table of a GIF image is a 1-d bytearray of the form [r1, g1, b1, r2, g2, b2, ...] with length equals to 2**n where n is the color depth of the image. ---------- Parameters color_depth:...
4fc8b0cad668724b0a6d5735f70dcb16b6b9b140
3,607,442
def feature_extraction_Step(all_s,all_id,all_label,config): """ Extract features for all signals included in all_s Args: all_s (list of numpy arrays): list of signals from which features are extracted. all_id (list of strings): corresponding list of IDs for signals in all_s. all_labe...
729d942e1a5d9b9774594506949aaa918192e944
3,607,443
def match_rule_based(): """ - Create Keyword RuleBased :return: """ item = request.get_json(force=True) key = CutId(_id=ObjectId()).dict()['id'] item['access_token'] = mango_channel item['id'] = key db.insert_one(collection, item) del item['_id'] return jsonify(item)
41c615912f505c15b2a12d0992e361e32a47f6c4
3,607,444
def _create_installation(iid): """Send a request to create an installation (ID: iid). Return the object ID associated with it""" data = { "deviceType": "android", "appVersion": settings.YIKYAK_VERSION, "parseVersion": settings.PARSE_VERSION, "appName": "Yik Ya...
0ca2d19083f7b7d0c1d200bef99b8ad1c1efa6e6
3,607,445
def _optimize_shape(count, width_height_aspect_ratio=1.0): """Computes the optimal X by Y shape of count objects given a desired width-to-height aspect ratio. """ N = count W = np.arange(1, N).astype(np.uint32) H = np.ceil(N / W).astype(np.uint32) closest = np.argmin(np.abs((W / H) - width_h...
3ddc8b636e8d0d1d51bfa7a2e4e2ae915bf9a8a8
3,607,446
def parcellate_func_combine_hemis(lh_func, rh_func, lh_parcel_path, rh_parcel_path): """ #Function that takes functional data in the form <num_verts, num_timepoints> for #both the left and right hemisphere, and averages the functional time series across #all vertices defined in a given parcel, for ...
5e81489c7b961af38e02ea3490afc03549a7b845
3,607,447
import numpy def grpCompose(f1,f2): """ compose two elements of group SE(3). f1.f2 = [R1*R2, (R1*t2)+t1] where, R1,R2 are rotation matrices and t1,t2 are translation vectors. But note that the function expects f1 to contain rotation vector instead of rotation matrix. Inputs: f1 -> Elem...
c807eba92c0b8f1504e2f4229be8b2ac7e564020
3,607,448
def get_rfmid_loaders( size, batch_size=64, num_workers=8, ): """get dataloaders for RFMiD dataset, and also return number of labels""" loaders = [] for split in ["train", "valid", "test"]: tfms = get_tfms(size=size, augmentation=split == "train") D = RFMiD( split=spl...
d632e57aafb4ae16e90b3a36753f5d62a590f4b5
3,607,449
def repos(request): """/repos - Show the list of known Subversion repositories.""" # Clean up garbage created by buggy edits bad_branches = models.Branch.gql('WHERE owner = :1', None).fetch(100) if bad_branches: db.delete(bad_branches) repo_map = {} for repo in models.Repository.all().fetch(1000, batch_...
116b3f58068befaf3ef40a69e5db6307fd8165ce
3,607,450
import torch def upsample_flow(flow, mask): """ upsample a flow field """ flow = flow * torch.as_tensor([8.0, 8.0, 1.0]).to(flow.device) return cvx_upsample(flow, mask)
5eb436d902b778d99079287439d123c6506b689b
3,607,451
def get_workspace_attribute(ns: str, ws: str, attribute_name: str): """ Get value of an existing attribute. :param ns: :param ws: :param attribute_name: :return: """ attributes = _query_workspace(ns, ws)['attributes'] if attribute_name not in attributes: logger.error(f"Queri...
bef84c2996b4494e6869e4690eee63c0a1b02852
3,607,452
import httpx def parse_url(client: httpx.Client, url: str, *, parse_seperate_2p: bool = False) -> Level: """ Parses the level data from an url, uses download_level to download with parse_rdzip to parse. Args: client (httpx.Client): httpx client to use for the request url (str): Url for th...
9621b7967dfb4bb100250f866e91ac249e8f0330
3,607,453
import math def arclen(angle, radius, rad=False): """Calculates the size of an arc of a circle""" if rad: angle = math.degrees(angle) return (angle / 360) * (2 * math.pi * radius)
c94e3a0f838a4ee635da4997da3ac89867d03366
3,607,454
def testapp_with_base64(settings, user_format): """Fixture for setting up a Swagger 2.0 version of the test testapp.""" settings['pyramid_swagger.swagger_versions'] = ['2.0'] settings['pyramid_swagger.user_formats'] = [user_format] return App(main({}, **settings))
8fdd5b835206f6f943d83243bbf1ea21705278b9
3,607,455
from typing import Callable from typing import List def search_result(_: Callable, result: List[FAMovie]) -> Keyboard: """ Keyboard for results of a movie query. """ buttons = [ [ Button.inline( movie['title'], b'film_' + movie['id'].encode('utf8') ...
6bc6c903a1dd4817929b4d864ff30a52cb995649
3,607,456
def fastqs_from_unit(unit): """FIXME is this really needed? """ if unit['fq2']: return objectify_remote(unit['fq1']), objectify_remote(unit['fq2']) else: return objectify_remote(unit['fq1'])
5bd8c53bc0b20f8fb8d1899a1e88ef04c013d92a
3,607,457
def import_obj_file(file_path, force=True, **kwargs): """ Imports OBJ file into current DCC scene :param file_path: str :param force: bool :param kwargs: keyword arguments :return: """ if not is_plugin_loaded('objexport.mll'): load_plugin('objexport.mll', quiet=True) kwargs...
bfd8f56855c6da9695d9498aabaaba1aed9aa306
3,607,458
def translate(seq): """ Translate a DNA sequence into protein. """ # Make sure sequence is upper case seq = seq.upper() # Find start codon i = 0 while i < len(seq) + 2 and seq[i:i+3] != 'ATG': i += 1 # Translate until the stop codon or end of string prot = [] while i < len...
2c04af772a3b6bda6b77d3c6ae1c4f507e6292af
3,607,459
def get_number_of_elements(scaledArr, threshold=2e-4): """ Computes the number of elements displayed on a image, using a threshold. Parameters --------- scaledArr : ScaledArray Contains the data of interest Returns --------- NdArray, Number : Returns the number of e...
1e8ca4f871c7cc2347cb495374cdba443439b18b
3,607,460
from typing import Callable def prepare_image(img_array: npt.ArrayLike, _model_preprocess: Callable) -> npt.ArrayLike: """Prepare any image so that it can be fed into a model predict() function. This includes: - converting to RGB channels - resizing to the appropriate image size expected by the model...
536660fed746e40b76fbaa87a5e86d1f5beb2e35
3,607,461
import torch def precision(label_pred, label_gt) -> float: """ Computes the precision """ with torch.no_grad(): prediction_bin = torch.argmax(label_pred, dim=1) TP = torch.mul(prediction_bin, label_gt).sum() FP = torch.mul(prediction_bin, 1 - label_gt).sum() PC = float(...
039e4c938d5ef6fd27ecda1d1bf027863b973060
3,607,462
from typing import Tuple def _normalize(img: np.ndarray, result_range: Tuple[int, int] = (0, 255)) -> np.ndarray: """ Normalizes given image by performing simple interpolation to given range. """ return np.interp(img, (img.min(), img.max()), result_range).astype(np.uint8)
8d28c4ba21f3e32a1be994f6838bc49d5feb90d9
3,607,463
import hashlib def get_hashes(binary): """Return md5, sha1 and sha256 hashes of input byte string.""" hash_dict = dict() for hash_type in ['md5', 'sha1', 'sha256']: if hash_type == 'md5': hash_alg = hashlib.md5() elif hash_type == 'sha256': hash_alg = hashlib.sha256...
0005a1446b6f58bb6cc6227428a304b0894e6947
3,607,464
def attach_xunit_results(file: str) -> BuiltInCommand: """ Create an Evergreen command to parse results in XUnit test results format. :param file: A .json file to parse and upload. """ params = {"file": file} return BuiltInCommand("attach.xunit_results", params)
e8b305a083707dadcfd5b23733c1a94252cc1732
3,607,465
from typing import Optional from typing import Any def age_to_delete(age: Optional[Any]) -> Optional[dict]: """ TODO: Delete this function once we remove age from details Given an *age*, return a dict containing its 'value' and a boolean for 'ninetyOrAbove'. Currently applys math.ceil() to age to ...
3ff9eb6e7eb9def712fd54bfd698767202a28f0d
3,607,466
def zr_wr_dem(x): """ Real Name: b'Zr wr dem' Original Eqn: b'( [(1,0)-(365,0.04)],(1,0),(2,0),(3,0),(4,0),(5,0),(6,0),(7,0),(8,0),(9,0),(10,0),(11,\\\\ 0),(12,0),(13,0),(14,0),(15,0),(16,0),(17,0),(18,0),(19,0),(20,0),(21,0),(22,0),(23\\\\ ,0),(24,0),(25,0),(26,0),(27,0),(28,0),(29,0),(30,0),(31,0),(32,0),...
20a4fba212b0b950b75e2c048c063db2840ed949
3,607,467
import sys def download_file(file: str): """ Download file from s3 storage :param file: str - path in s3 storage :return: S3 Object """ try: file = remove_start(strip_str(file)) response = s3client.get_object(Bucket=settings.AWS_STORAGE_BUCKET_NAME, Key=file) return res...
ea5fe2635956d4993a42211d05534faa4de2dcc2
3,607,468
import os def getMachineFacts(): """Gets some facts about this machine we use to determine if a given installer is applicable to this OS or hardware""" # pylint: disable=C0103 machine = dict() machine['hostname'] = unicode_or_str(os.uname()[1]) machine['arch'] = os.uname()[4] machine['os_v...
6c03cf15c97e83cbed60c3f605bd665bcbb83fd0
3,607,469
import os import pathlib def get_downloads_dir(): """Returns the downloads directory path""" env_value = os.environ.get(_ENV_PREFIX + "DOWNLOADS_DIR") if env_value: path = pathlib.Path(env_value) if not path.is_dir(): raise NotADirectoryError(env_value) return path ...
35dc1db26c18102ddb741581ae4e878b1d9a5f3f
3,607,470
def parse_json(data, collection): """ Calls the appropriate json parser based on the collection, returns whatever the parser returns, along with the query and num_responses, which it gets from the json response. If there are no results, it returns ([], query, 0)""" # FIRST (only applies to reference...
7a84729e7d907325a10d469ac720069a633426e5
3,607,471
def inner_func_float(): """ Обертка для lambda (двухуровневая, float) """ return defaultdict(inner_lambda_float)
76c8695cfa567dc198af343a75969d65236eab3c
3,607,472
def _reachablerootspure(pfunc, minroot, roots, heads, includepath): """See revlog.reachableroots""" if not roots: return [] roots = set(roots) visit = list(heads) reachable = set() seen = {} # prefetch all the things! (because python is slow) reached = reachable.add dovisit =...
08364dd59bab0136e41893d13328e6665269230a
3,607,473
def Go_NoGo(loaded_file, i): """ :param loaded_file: file output from operant box :param i: number of days analyzing :return: data frame of all analysis extracted from file (one animal) """ (timecode, eventcode) = extract_info_from_file(loaded_file, 500) (dippers, dippers_retrieved, retrieva...
36d56142ffae3d6b42f18760418c6f069a045f27
3,607,474
def read_sfmlearn(ego_path, flip): """ Right-hand coordinate (following SfMLearn paper). X: Pitch, Y: Yaw, Z: Roll """ ego_dict = {} with open(ego_path, "r") as f: for line in f: strings = line.strip("\r\n").split(",") key = strings[0] vx, vy, vz, rx, ...
38d708334f70c3a2abdf8bc28edd3700b9476498
3,607,475
def get_links(soup, artist): """Get the complete link for each song of the artist""" links = f'links_{artist}' links = [] for td in soup.find_all('td'): if "tal" in td.get('class',[]): links.append('https://www.lyrics.com'+td.find('a')['href']) return links
0587286e3bd15abdee0403745b5fc6d5af81ce5c
3,607,476
def colorize_profit(profit): """ Colorize the profit depending on its value. :param profit: Profit. :return: console_colored, html_colored """ color = { 'html': { profit <= -10: RED_HTML, -10 < profit <= 0: YELLOW_HTML, 0 < profit < 10: GREEN_HTML, ...
886823f7aed0fdd9279b487e2dd7f0dabcaa889a
3,607,477
from typing import BinaryIO def _read_ft_cfg(file: BinaryIO) -> Metadata: """ Constructs metadata from fastText config. """ cfg = list(_read_required_binary(file, "<12id")) losses = ['HierarchicalSoftmax', 'NegativeSampling', 'Softmax'] cfg[6] = losses[cfg[6] - 1] models = ['CBOW', 'SkipGr...
8b63714ceb3dd96be5351ea55ba83f93faf1970b
3,607,478
from typing import Callable def named(name: str) -> Callable[[C], C]: """ Change the name of a function to the given name. """ def decorator(original): # type: (C) -> C original.__name__ = str(name) original.__qualname__ = str(name) return original return decorato...
44f755872f627f528964669508072a6f37defe91
3,607,479
def getQuarter(date): """Extracts the quarter from a date, ranging from 1-4. Args: date (Date): The date to use. Returns: int: An integer that is representative of the extracted value. """ return ((date.month - 1) // 3) + 1
26868a8dc6e4fd9e58daccf44b2357529dfdd1fd
3,607,480
def dup_mul(f, g, K): """ Multiply dense polynomials in ``K[x]``. **Examples** >>> from sympy.polys.domains import ZZ >>> from sympy.polys.densearith import dup_mul >>> f = ZZ.map([1, -2]) >>> g = ZZ.map([1, 2]) >>> dup_mul(f, g, ZZ) [1, 0, -4] """ if f == g: ret...
f10628d9054b7dae1a303e841ec69ea5684f53c3
3,607,481
from typing import Type def norm_param(arr_t): """ Returns a transformation that calculates the ``order``-norm (1 output, 1 input, 1 param): ``output = abs(input) ** order``. """ if dtypes.is_complex(arr_t.dtype): out_dtype = dtypes.real_for(arr_t.dtype) else: out_dtype = arr_t...
376741b651f0d3efa572b3fd14baadc9bfb84cfc
3,607,482
def _get_filenames_glob(variable, drs): """Return patterns that can be used to look for input files.""" path_template = _select_drs('input_file', drs, variable['project']) filenames_glob = _replace_tags(path_template, variable) return filenames_glob
13441ed29b7516be09f6855dff10d0f2d19f794e
3,607,483
def _LoadGclientFile(path): """Load a gclient file and return the solutions defined by the gclient file. Args: path: The gclient file to load. Returns: A list of solutions defined by the gclient file or an empty list if no solutions exists. """ global_scope = {} # Similar to depot_tools, we us...
0142ad9b4c87eca35c8b1e5fae30c19c5d8d05a5
3,607,484
def find_closet_match(color, tile_colors): """在tile_colors中寻找与颜色color最接近的颜色,返回下标和差异值""" diff = float('inf') index = 0 for i, c in enumerate(tile_colors): d = get_color_diff(color, c) if d < diff: diff = d index = i return index, diff
d68ead2b8d24114b2f29a77e97c90c93df5a1a64
3,607,485
from enum import Enum from typing import Tuple from typing import Callable from typing import Any def load_conf( conf_type: Enum, conf_data: Tuple[str, FileConfig] = CONFIGS_DATA, load_func: Callable[[FileConfig], Any] = dispatcher ): """ Универсальный кэшируемый загрузчик конфигураций...
8a575c85d375af24cde7b2812ea7d271e004d797
3,607,486
def LicenseFromPath(path): """Try to figure out the license for a given path. Splits path and looks for known license dirs in segments. Args: path: A filesystem path, hopefully including a license dir. Returns: The name of the license, eg OFL, UFL, etc. Raises: ValueError: if 0 or >1 licenses ma...
89f6fee5f0869640ae51f10fb5298930b6be8d9d
3,607,487
def _get_dyson_purecool_device(): """Return a valid device as provided by the Dyson web services.""" device = mock.Mock(spec=DysonPureCool) device.serial = "XX-XXXXX-XX" device.name = "Living room" device.connect = mock.Mock(return_value=True) device.auto_connect = mock.Mock(return_value=True) ...
d4af0ba642bea2fce2bdef222b1b7dfae94b59a0
3,607,488
def list_quicklinks(): """ Returns a list of QuickLinks :return: list<String> list of quick links """ quicklinks_list = [] with open(DEFAULT_FILE) as file: for line in file: quicklinks_list.append(line.strip()) return quicklinks_list
5e3ab8d1840e53fd0218e347961b8217c34eafa6
3,607,489
import hashlib def hash_seqs(sequences): """ Generates hexdigest of Sha1 hash for each sequence in a list of sequences. This function is useful for generating sequence specific identifiers that allow for easier comparison of features from multiple sequencing runs or sequence processing runs. """...
35c3291a58ebc7e053250f7234faacd0356f7df5
3,607,490
def add_myst(original: str) -> str: """Change docs/conf.py to use MyST-Parser, enabling md files""" # add myst_parser extension and its own extensions configuration content = original.splitlines() myst = '\n# Enable markdown\nextensions.append("myst_parser")\n' myst_extensions = template("myst_exten...
64d13a78b12ff856333a65e42de855bfc3eaf33e
3,607,491
def get_paths(link, nb): """ Generate a list containing all URLs Args: link [str]: Base HTML link nb [int]: Number of pages usingHTML link Returns: url [str]: [List containing all URLs] """ url = [] for si in range(2000, 2020): for ti in range(1, nb+1): ...
8fd0a947eeb5435f0df48dc928feb3a10786c2cc
3,607,492
def heaviside(x, bias=0): """ Heaviside function Theta(x - bias) returns 1 if x >= bias else 0 :param x: :param bias: :return: """ indicator = 1 if x >= bias else 0 return indicator
b325a862cbc2cac97b8e4808c6d77b54a0f1d643
3,607,493
def register(message_array, device, auto_mode): """ Message: register """ pwd = pwgen(10, no_symbols=True) if (device.contributor.status == Contributor.UNKNOWN) or (device.contributor.status == Contributor.INACTIVE): device.contributor.status = Contributor.ACTIVE device.contribu...
c4776ad2fe1f953253b0ed6194e89c71f14dc0a8
3,607,494
def lsubstr(view, point, length=1): """ Return the character(s) to the left of the point on the same line. """ col = view.rowcol(point)[1] region = Region(point - min(length, col), point) return view.substr(region)
874511493cf71c508984404780751fc4f59c35c6
3,607,495
def biggest_differences_words(prunedTable): """ Finds the words that are most different from their most frequent alternative across each semantic dimension Parameters ---------- prunedTable : a data frame The data frame representing arousal, valence, and dominance ratings for words and their mo...
2b39a717fbdf7d823a381ff3320e2ac487f65ec3
3,607,496
def centos8(function): """Decorator to set the Linux distribution to CentOS 8""" def wrapper(*args, **kwargs): hpccm.config.g_linux_distro = linux_distro.CENTOS hpccm.config.g_linux_version = StrictVersion('8.0') return function(*args, **kwargs) return wrapper
4fbdc47e00bff3b8967cfa8ba9c422b4586915de
3,607,497
def stats(state): """Return the statistics for given state. Parameters ---------- state : RunningState Returns ------- Stats named tuple """ if not state.count: return Stats(0, 0, 0, 0, 0, 0) mean = state.sum / state.count std = (float(state.sum2 - 2.0 * state.sum ...
731dc9c40db2f459f0bf7419277e9bc4106c2578
3,607,498
import asyncio import concurrent async def get_async_multiprocess(): """Multi Process""" loop = asyncio.get_running_loop() with concurrent.futures.ProcessPoolExecutor() as pool: task1 = loop.run_in_executor(pool, syncFn1, 1) task2 = loop.run_in_executor(pool, syncFn2, 2) res1 = awa...
b1609c2582ff9022bccb15f7d16bb299a991f26a
3,607,499