content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def series_phrase_serial(items, separator=', ', last_separator=' and '): """Join items into a grammatical series phrase using a serial separator, e.g., ``"item1, item2, item3, and item4"``. Args: items (list): List of string items to join. separator (str, optional): Item separator. Defaults...
7cc023500193407dddfedfb9872bc0e0e99a7a38
62,700
def file_deleted_from_playlist(*args, **kwargs) -> str: """ Audio-file deletion validation message :param args: :param kwargs: :return: Generated validation message """ text = f"{_check_mark_button} " \ f"فایل با موفقیت حذف شد" return text
f76e550009e64bdc66609567d192be9fb9361f6a
62,701
def focal_plane_to_sky(cartrep): """ Convert physical position in focal plane to sky offset from FoV """ cartrep = cartrep.transform(flip_y) with u.set_enabled_equivalencies(gtc_focalplane_equivalencies): return CartesianRepresentation(cartrep.xyz.to(u.arcsec))
f5c7bba935f58ef4f4b72356c0956a3ffc60fdea
62,702
from pathlib import Path def find_file(search_file: str, search_path: str): """This api find the file in sub-directories and returns absolute path of file, if file exists""" for File in Path(search_path).glob(f"**/{search_file}"): return File
a776bb599c60d4bd532cdd05fe5e2b8b9ef5ccf0
62,703
import torch from typing import List def flatten2float_list(t: torch.Tensor) -> List[float]: """ Maps a tensor to a flatten list of floats :param t: :return: """ t = t.view(-1).detach().numpy().tolist() # t = torch_uu.flatten(t).numpy().tolist() return t
4feb1d702106bcfc45472c21903c38fb71e45d21
62,704
def pad_image(image, pad=0, pad_mode='constant', pad_value=0.0): """Pads a batched image array.""" batch_shape = image.shape[:-3] padding = [ *[(0, 0) for _ in batch_shape], (pad, pad), (pad, pad), (0, 0), ] if pad_mode == 'constant': return np.pad(image, padding, pad_mode, constant_values=pad...
744d6c00f85eafb720ead9711cb5d121d4eb4a88
62,705
def scalar_cast(input_x, input_y): """ Casts the input scalar to another type. Args: input_x (scalar): The input scalar. Only constant value is allowed. input_y (mindspore.dtype): The type to be cast. Only constant value is allowed. Returns: Scalar. The type is the same as the ...
e9aed0f58c3294626cfdb684976659517c4dfd5f
62,706
def get_directory_instance(ns, directory): """ Retrieve LMIInstance of a directory. :type directory: string :param directory: Full path to the directory. :rtype: LMIInstance """ name = ns.LMI_UnixDirectory.new_instance_name(get_directory_name_properties(ns, directory)) return name.to_in...
1301138a8b11820b832027f68d016bb59cac3a6c
62,707
import torch def compute_scores(users_embeds: torch.Tensor, items_embeds: torch.Tensor, items_bias: torch.Tensor) -> torch.Tensor: """ Args: users_embeds(torch.Tensor): shape (batch_size, items_total, embed_dim) items_embeds(torch.Tensor): shape (items_total, embed_dim) items_bias(torc...
8528963a23efef270b467ec6f039b5a8733d3b4f
62,708
def max_height(target): """ Solved using this racionale: ignore x -- it's independent and can adapt to any value we specify for each starting y velocity (vy) with positive vy necessary for reaching height, vy will be -vy when y is 0 again so, the heighest initial velocity is reaching the...
feeba57a4abaf7359ff2bf32a6b95ebe818c2d62
62,709
def extract_fplus_include_file(code_line): """ Extracts the included file path from an include statement """ return ( code_line .replace("#include <fplus/", "") .replace("#include \"", "") .replace("\"", "") .replace(">", "")[:-1] )
c969fcb633332b05aec93f2998065d34b2d99c2f
62,710
def merge_sort(lst): """Merge Sort.""" if len(lst) <= 1: return lst mid = len(lst) // 2 left = lst[mid:] right = lst[:mid] left = merge_sort(left) right = merge_sort(right) output = [] while left and right: if right[0] < left[0]: output.append(right.po...
16bb2351efc133c11e0b6d51b7dae908260c0422
62,711
import copy from datetime import datetime def parse_case_data(config=None, ped=None, owner=None, vcf_snv=None, vcf_sv=None, vcf_cancer=None, vcf_str=None, peddy_ped=None, peddy_sex=None, peddy_check=None, delivery_report=None, multiqc=None): """Parse all data necessary for ...
2e812a74f78d4625405d14573ae18feeb5637ce5
62,712
def gene_group_replacement(x1, x2, group, config): """ Metoda buduje genom dziecka przekazując mu geny z wyselekcjonowanej grupy od rodzica x2 i pozostałe geny od rodzica x1. :param x1: list :param x2: list :param group: list :return: new_x: list """ interval_in_indices =...
770eebd91b4e5c82303d974e5545874c4f1aad49
62,713
import scipy def compute_elastic_score(xyz,mean=None,neighbour_radius=5.0): """ compute_elastic_score : mean should not be None, but maybe something could be worked out for that case too... Description ----------- the idea is to compute the elastic energy of the mode. For atom pairs within a...
79ddcfcdb8b428abec616eb71481a37c1ae9bc39
62,714
def check_id_username(userid, pdpath): """ Check blobs for usernames in primary.docobjects :param userid: :param pdpath: :return: """ check = checkPD(userid, pdpath) if check != "": return check else: pass
797bd4edd5f6d19c0d02d928a7091cb70be9ac77
62,715
def check_def_has_docstring(def_docstring, context, is_script): """Exported definitions should have docstrings. ...all functions and classes exported by a module should also have docstrings. Public methods (including the __init__ constructor) should also have docstrings. """ if is_script: ...
d9bb7ff278102e78505d77b28eb42010d7a13338
62,716
def full_service_acct_email(account_id, project_id): """Generate the full service account email. Args: account_id (str): The service account id, i.e. the part before the "@". project_id (str): The project id the service account belongs to Returns: str: The full service ...
42c55bb0e813830d406110cba833b2d49d0b224e
62,717
def pre_process(iid, image): """Data augmentation function.""" image = image.transpose((1, 2 ,0)) if not isinstance(image, Image.Image): image = Image.fromarray(image) image_size = cfg.img_shape image, image_size = _infer_data(image, image_size) return { 'x': Tensor(image), ...
23684df73709a18b232112e0f0dce432aed5d63d
62,718
def update_youth_profile(input, youth_profile, staff_update=False) -> YouthProfile: """Update the given youth profile. :param staff_update: Calling user has manage permission on youth membership service. """ contact_persons_to_create = input.pop("add_additional_contact_persons", []) contact_persons...
7ae12a21ead9b49b612d0dc786ff96b4212617a6
62,719
def hello(): """ Return a greeting. """ return "Greetings from Python!"
871175e50ee4e2d2ebd33829f1dff568cdfd0bb7
62,720
from typing import Callable from typing import NamedTuple def get_market_value() -> Callable[[str], NamedTuple]: """ 获取上市公司的最近交易日的市值和相关信息 Precondition ===================================================================================================== ../data/jq.db 存在 jq.db中存在'market_value'表,其内容...
5fb47eb25bc20608125535190f5ad6d3065e3b30
62,721
import sys def get_new_log(infile_logs=None): """Generate command log for output file. Args: infile_logs (dict) : keys are file names, values are the command log """ repo_dir = sys.path[0] try: repo = git.Repo(repo_dir) repo_url = repo.remotes[0].url.split('.git')[0...
f1784e02dc9f1465cf93bf19868e5c111e1df0b8
62,722
def dump(txblkhash): """ /dump/<hash> return state dump after transaction or block """ try: blk = chain_manager.get(txblkhash.decode('hex')) except: try: # index test_blk, tx, i = _get_block_before_tx(txblkhash) except (KeyError, TypeError): re...
967a30707c2bb21a3420cbed3ebeabc2b6c5f76c
62,723
from typing import Tuple import subprocess import shlex import re def zsh_version() -> Tuple[int, ...]: """Try to guess zsh version, return (0, 0) on failure.""" try: out = subprocess.run(shlex.split('zsh --version'), check=True, stdout=subprocess.PIPE).stdout except (...
5e1ca9c55b005864d8eebff90f1bc15c74de82c0
62,724
import aiohttp import os import json async def query(beacon, q, access_token, ws): """Query the beacon endpoint.""" headers = {'User-Agent': 'ELIXIR Beacon Aggregator 1.0'} if access_token: headers.update({'Authorization': 'Bearer ' + access_token}) # Create a new session for querying a beaco...
146feaf29da6699c2aa3a044d5277e6a4a2df8f6
62,725
import click import logging def init(): """Return top level command handler.""" @click.group(cls=cli.make_multi_command(__name__)) @click.option('--zookeeper', required=False, envvar='TREADMILL_ZOOKEEPER', callback=cli.handle_context_opt, expose_value...
3806b2c651f423c55128f72c0ae78437c1fd6a60
62,726
import os def read_ratings(data_dir, tmp_dir=_LOCAL_DIR): """Read movielens ratings data into dataframe.""" if not tf.io.gfile.exists(os.path.join(tmp_dir, _RATINGS_FILE_NAME)): tf.io.gfile.copy( os.path.join(data_dir, _RATINGS_FILE_NAME), os.path.join(tmp_dir, _RATINGS_FILE_NAME)) ratings_d...
9512865b9b324e8d5acbe8d8cb8606b04070d11d
62,727
def split_byte(x): """Split byte into groups of bits: (2 bits, 3 bits, 3 bits)""" return x >> 6, x >> 3 & 7, x & 7
7743fdf78c201dce66803ae0eb62cbdf58cccc7d
62,728
def total_histogram_diff(pixel_diff): """ Sums up all histogram values of an image. When used with the black/white pixel-diff image this gives the difference "score" of an image. :param pixel_diff: the black/white image containing all differences (output of imagecompare.pixel_diff function) :return...
93675cafcb82513513ddd5d078ab91e36c52de27
62,729
def predict_genre_prob(img_file): """ Given an image file, returns the top five genre predictions and their percent confidence. """ prediction = genre_learn.predict(open_image(img_file)) probs_list = prediction[2].numpy() # format and round results probs_dict = { c: probs_list[i] for (i,...
413518f08a8d9a24de5857290805272717b69f20
62,730
def shared_nx_struct_data(): """ Return a tuple of shared probes. The second is a nx_varied_struct_t rebinding. """ return (loader.lookup("ProbeTestC$nx_struct_data").bind(1), loader.lookup("ProbeTestC$nx_struct_data", ["", "nx_varied_struct_t"]).bind(1))
0e1bffa7a877525e0ad3299c96b23950ee52b4eb
62,731
def _counts_to_probs(counts, foll_gids, trial_count, adjust_missing): """ Normalise the number of times a follower takes a particular rank over all trials. Because not all followers fire on all trials, high-rank values are typically empty. This gives them a very low entropy. In Hemberger 2019 they ...
c94d73324b73657213c5849173e20dac7d2dbe7b
62,732
import requests import json def send_request(sub_url, data): """ Send a POST request with form-data to a given sub-URL and retrieve the JSON response. Throws a RuntimeError if there was an error while submitting :param sub_url: Sub-URL to send the POST request to :param data: Data dictionary that...
8a40d5abf91463b439b3606a4b025795418b2db7
62,733
def resolve_partitions(patterns): """ Given a list of patterns, returns all the files matching or in folders matching one of them. The file are returned in a list of tuple of 2 elements: - The first tuple is the file path - The second being the partition keys and values if any were encountered ...
1e3292235b79e3fdf3a89f0bbc50e3e428e589d3
62,734
def get_palette(categories, cmap): """ Generate dictionary mapping categories to color. """ cc = plt.get_cmap(cmap) if len(categories) > len(cc.colors): raise ValueError("Number of categories more than number of colors in cmap.") palette = {x: cc(i) for i, x in enumerate(categories)} ...
20e5ea98e126df87dfcc18db368976851514bd13
62,735
import logging def geocoded_hitlist_cache(key,couple_key,update=False): """Get a list of eatery entities that have been geocoded""" geocoded_hitlist = memcache.get(key) if not geocoded_hitlist or update: geocoded_hitlist = [] hitlist_keys = hitlist_cache("Hitlist|" + str(couple_key...
8ee899dae9aef297203d87f42f7b82bbe6fd6c3e
62,736
def random_std(loc, scale): """ Draws a random std from a gaussian distribution with mean ``loc`` and std ``scale``. """ def wrapper(): return np.clip(np.random.normal(loc=loc, scale=scale), np.finfo(float).eps, np.inf) return wrapper
2cc33df0f8ba6e8639676446c08a0afa615e8cc5
62,737
from typing import Sequence def isin( arg: ir.ValueExpr, values: ir.ValueExpr | Sequence[ir.ValueExpr] ) -> ir.BooleanValue: """Check whether `arg`'s values are contained within `values`. Parameters ---------- arg Expression values Values or expression to check for membership ...
40ea4907147cd421afec476c2cfdc4cdeb6c2b0f
62,738
def test_decompose(): """ Test cases for the functions in decompose.py Returns True if passed all test cases, otherwise returns False """ print("Testing: decompose.py") for n in range(1, 6): top = np.hstack((np.zeros((n, n)), np.identity(n))) bottom = np.hstack((np.identity(n), ...
f612d79e57ad26de6d37b55e59323dc966a098e2
62,739
from typing import Optional from datetime import datetime import asyncio def get_persistence_data(item_name: str, persistence: Optional[str], start_time: Optional[datetime.datetime], end_time: Optional[datetime.datetime]) -> OpenhabPersistenceData: """Query histor...
e0becca1972d28e4de716985a5ed9451b0cf684a
62,740
def create_diag_ping(): """ Generate a TR50 JSON request for a diagnostic ping """ cmd = {"command":TR50Command.diag_ping} return cmd
8024a8799a66fcfa7b2a54915a87414b64544760
62,741
def __plot_contours(ax, clf, xx, yy, **params): """Plot the decision boundaries for a classifier. Parameters ---------- ax: matplotlib axes object clf: a classifier xx: meshgrid ndarray yy: meshgrid ndarray params: dictionary of params to pass to contourf, optional """ Z = clf.predict(np.c_[xx.rave...
c2ed896ccf69ebf824c1c643e628cb8f02023249
62,742
import tqdm def cosine_similarity_matrix(vocab, d): """ Create the cosine similarity matrix. Input vocab -- a list of words derived from the keys of d d -- a two-dimensional defaultdict mapping word pairs to counts, as created by cooccurrence_matrix() Output cm -- a two-dimensional d...
d7aa3540df44730842e121adab57d25b53a52738
62,743
def dict_to_asc(dict_item: dict, filename: str) -> bool: """ Save a dict into an asc file. :param dict_item: The dict object to save. :param filename: The file path to be saved to. :return bool: True on success. """ return list_to_asc(dict_to_list(dict_item), filename)
7b4f7d5b5b1b8376103677b1e40cce31cb59e6fe
62,744
async def claim(client_discord, connectionBDD, args, message): """claim: Args: client_discord ([discord.Client]): [un client pour l'API discord] connectionBDD ([database_outils.appelsBDD]): [un connecteur a la BDD] args ([list]): [les arg...
d73cbe971e6ef710e5055fdb6e872846269e6949
62,745
def distance(point1, point2): """ calc distance between two 3d points """ return ((point1[0]-point2[0])**2 + (point1[1]-point2[1])**2 + (point1[2]-point2[2])**2)**0.5
bb9e56b786daf085f5d4fec02001ec561ae77a3c
62,746
import requests def fetch_uniprot_mapping(ids, from_="ACC", to="ACC", format="fasta"): """ Fetch data from UniProt ID mapping service (e.g. download set of sequences) Parameters ---------- ids : list(str) List of UniProt identifiers for which to retrieve mapping from_ : st...
2e8fcc2a27e6f6519b5c286ec7be8302fd88f1a5
62,747
import requests def ngram_book(word = ['.'], title = None, period = None, publisher = None, lang=None, city = None, ddk = None, topic = None): """Get a time series for a word as string, title is name of book period is (year, year), lang is three letter iso code. Use % as wildcard where appropriate - no wildca...
7a56e0b107930e89ba1be1edfa35bd0e03fc762d
62,748
from typing import Callable import functools import collections def recursive_repr(maybe_func=None, max_depth=1, max_repr="..."): """ Decorate a representation method/function to prevent infinite recursion. :param maybe_func: The '__repr__' and/or '__str__' method/function or None. :param max_depth: ...
22266e4eec51c9e8d6ae2afaba1e534938a2f3c8
62,749
def get_process_list(node: Node): """Analyse the process description and return the Actinia process chain and the name of the processing result layer which is a single raster layer :param node: The process node :return: (output_objects, actinia_process_list) """ input_objects, process_list = c...
f1a029652c369ee4629cf4832ee3c439ad7ec41c
62,750
import binascii def _request_message(worker): """ Transform HTTP message into an action that can be invoked by a worker """ message = request.form["message"] message = binascii.unhexlify(message[2:-1]) response = worker._recv_msg(message) response = str(binascii.hexlify(response)) retu...
0443009a13f3ba61589393a60bd6932e81b2264d
62,751
def soil_adjusted_vegetation_index(Red, Near, L=.5): """ References ---------- .. [1] Huete, "A soil vegetation adjusted index (SAVI)" Remote sensing of environment, vol.25 pp.295–309, 1988. """ SAVI = np.divide(np.multiply(1+L, Near - Red), Near + Red + L) return...
86fe47f69b44a9ea3d650a8893497cd5b5b97523
62,752
import os import re def read_vasp_pressure(path: str) -> float: """Utility for reading external pressure (kbar) from PSTRESS INCAR tag. Used for extracting energy from VASP enthalpy (H = E + PV)""" fname_incar = os.path.join(path, "INCAR") fname_outcar = os.path.join(path, "OUTCAR") fname_vasprun ...
c2cf406abc81061a09972b14f2c9539d15c0a7ee
62,753
import socket import time def udp(q, where, timeout=DNS_QUERY_TIMEOUT, port=53, af=None, source=None, source_port=0, ignore_unexpected=False): """coro friendly replacement for dns.query.udp Return the response obtained after sending a query via UDP. @param q: the query @type q: dns.message.Me...
bfc401d85a0ecc1232181c078ed31a1967c2eaa2
62,754
import collections def load_vocab(vocab_file): """Loads a vocabulary file into a dictionary.""" vocab = collections.OrderedDict() index = 0 with open(vocab_file, "r", encoding="utf-8") as reader: while True: token = convert_to_unicode(reader.readline().strip()) if not t...
7dffc713f267183b48e90eca58840ab96b7d006a
62,755
def angle_from_DDDMMSSs(DDDMMSSs): """ Returns a decimal angle provided a string in right ascension DDDMMSSs format. Input can be in the forms: DDDMMSSs (unsigned right ascension) +DDMMSSs (signed declination / elevation) """ DDDMMSSs = right_zero_pad(DDDMMSSs) if (DDDMMSSs[0] in ("+","-")): SIGN = DDDMMSSs...
0eb4e9775f11115b757d32be8ef7c7cd4034e9af
62,756
from typing import List def ogc_wmts( endpoint: str, tms: morecantile.TileMatrixSet, bounds: List[float] = [-180.0, -90.0, 180.0, 90.0], minzoom: int = 0, maxzoom: int = 24, query_string: str = "", title: str = "Cloud Optimizied GeoTIFF", ) -> str: """ Create WMTS XML template. ...
61e3a2ae7573a4c2204a4b635210b7c7205254f3
62,757
from typing import Dict from typing import Any import json async def apiDiscordLogsListEvents(cls:"PhaazebotWeb", _WebRequest:ExtendedRequest) -> Response: """ Default url: /api/discord/logs/list """ result:Dict[str, Any] = dict( result=TRACK_OPTIONS, status=200 ) return cls.response( text=json.dumps(re...
240a0de379acb8a2361c57026389c2735d2c0601
62,758
def _is_transition_allowed(from_tag: str, from_entity: str, to_tag: str, to_entity: str): """ BIO 是否被允许转移。比如: "B-Per" "I-Per" 这是被允许的; 而 "B-Per" "I-Loc" 或者 "O", "I-Per" 这是不被允许的 :param from_tag: The tag that the transition origin...
dbbef187e9444eb11b95b4a0bf84d29ccf604bcd
62,759
from pathlib import Path def root_path() -> str: """Fixture that returns the root path of this git repository""" return str((Path(__file__).parent / "..").resolve())
9b9ef56614ea22cca222f21254ab611ae04da364
62,760
import re from pathlib import Path import shutil import subprocess def gphoto(command: Command): """Perform arbitrary gphoto2 command.""" logger.info(f'Received command={command!r}') # Fix the filename. filename_match = re.search(r'--filename (.*.cr2)', command.arguments) if filename_match: ...
2213edf46e77092b1b40e1503792189d46f50855
62,761
def filter_type_between(left, right, supports_midi = False, is_drum_pad = False, supports_instrument = False): """ Given 'left' and 'right' are two consecutive devices in a valid device chain, returns the appropriate browser filter type for valid devices fitting between them. Either 'left' or 'right' ca...
c7b7455cbdfae0dc596c775f5779104a1b7fa435
62,762
import multiprocessing as mp import psutil def nproc_use_ng(det): """Optimize processor usage. Attempt to estimate a reasonable number of processes to use for multiple simultaneous slope_to_ramp() calculations. We attempt to estimate how many calculations can happen in parallel without swapping...
0fa6bdf26e7145a96be46d0342716f806233a288
62,763
def preserve_patron_loan(data, prev_record=None): """Preserve `patron_loan` system field.""" if not has_request_context(): return data if prev_record and "patron_loan" in prev_record: data["patron_loan"] = deepcopy(prev_record["patron_loan"]) return data
5750f7f54a3d2a8c89f2bb45af502da8ed046f24
62,764
def preprocess_data(data, desired_length): """Forces the data to be the desired length. Input is a 2D matrix of [timestep, features]. desired_length is in the first (time) dimension. Output is another 2D matrix. """ if len(data) < 1: raise Exception('Input score is length 0.') if l...
80132a5d6e23e9fd19427808dd6ef1f35a490dde
62,765
import json def test_platform_declaration(): """Test platform declaration generation runs without error, and can be saved to JSON file (ChemifyAPI needs this functionality). """ return json.dumps(PlaceholderPlatform().declaration)
6523e314a48584b47826933393303ab66fbf6b12
62,766
def randint(low, high=None, size=None): """ Return random integers from low (inclusive) to high (exclusive). Return random integers from the “discrete uniform” distribution in the “half-open” interval [low, high). If high is None (the default), then results are from [0, low). """ if high is No...
848ceb46246501198f2cb2f852984ef84dc5c2d1
62,767
def remove_odd_whitespaces(text): """Remove multiple and trailing/leading whitespaces.""" return " ".join(text.split())
09e0fe6088ad14e58c8cbc0571f72d304a1a43d6
62,768
def jinja2_getattr(self, obj, attribute): """Get an item or attribute of an object but prefer the attribute. Unlike :meth:`getitem` the attribute *must* be a bytestring. This is a customised version to work with properties """ try: value = getattr(obj, attribute) if isinstance(value...
cdd84d4a69ad16b03aa20e79ac019699f2b3506b
62,769
def gradient_d4(dem, dx, dy, aspect_rad=False): """Calculate the slope and aspect for provided dem, this will mimic the original IPW gradient method that does a finite difference in the x/y direction. Given a center cell e and it's neighbors: | a | b | c | | d | e | f | | g | h | i | ...
8ef1909055cde77f3ea9519a7eb36fd2ab4afdea
62,770
def select_angle(attr_a, attr_b=0, condition=False): """Create math_SelectAngle-node to get one of the given attrs, depending on condition-state. Args: attr_a (NcNode or NcAttrs or string): Maya node attribute. attr_b (NcNode or NcAttrs or float): Maya node attribute. condition (NcNode ...
24f898bf5dcf88fb64964b73a996d1189e6cfa92
62,771
from typing import Dict def build_census_df( admits_df: pd.DataFrame, lengths_of_stay: Dict[str, int], ) -> pd.DataFrame: """Average Length of Stay for each disposition of COVID-19 case (total guesses)""" return pd.DataFrame({ 'day': admits_df.day, 'date': admits_df.date, **{ ...
9402d0b51720fe18c5f74592789bcd670956451a
62,772
import sys import re def validateInputs(argv): """ Validate the input variables """ nInputs = len(argv) # Validate that 2 input variables are given if nInputs!=3: print("Error: You must specify 3 input parameters.") print("newAuthors.py authorInitials \"name\" \"email\"") ...
6c040c411c43a14bf9995066964f94a94c237f5f
62,773
import json def get_all_user_stats(user_ids, user_records=None): """Get some additional information about observers""" iconic_taxa_lookup = {v.lower(): k for k, v in ICONIC_TAXA.items()} iconic_taxon_id = iconic_taxa_lookup[ICONIC_TAXON.lower()] user_ids = set(user_ids) user_info = {} user_rec...
f8b9a22125eacf0c95e25c9d6edee6bc933459ee
62,774
def create_opssat_devices(): """Returns a list of 3 devices instances representing OPS-SAT optical devices""" return [Device(DeviceId.STAR_TRACKER, DeviceState.ON, PhotoDiode.PD3, PD_ELEVATION_THRESHOLD_IADCS_ST), Device(DeviceId.HD_CAMERA, DeviceState.ON, PhotoDiode.PD6, PD_ELEVATION_THRESHOLD_HD_C...
98a16a7b974b1bfe1ea4ef2a583cad8ed61e3fad
62,775
import json def add_loc_data(reduced_df, all_data, to_csv=False): """ Adds location data generated by `generate_spatial_data` to the `all_data` dataframe in a new `final_df`. """ # Load in the data file = open('../data/arcgis_latlong_data.json') data = json.load(file) # Creating a map...
71ffcbfb49143ff5183e01de332d188e4abe2da0
62,776
import random import re def sf_prepare(u_boot_console, env__sf_config): """Check global state of the SPI Flash before running any test. Args: u_boot_console: A U-Boot console connection. env__sf_config: The single SPI Flash device configuration on which to run the tests. Retur...
01cb5931a47dd225a21d146754709e6c56021fcd
62,777
def _next_power_of_2(x): """ Calculate the closest power of 2, greater than the given x. :param x: positive integer :return: int - the closest power of 2, greater than the given x. """ return 1 if x == 0 else 2**(x - 1).bit_length()
616c01f6aacb7442ce1b2afbcac35b26c8f79701
62,778
import os import pickle def load_db(DB_NAME): """ Loads the database from the path given If the path doesnt exists, create a new database """ if os.path.exists(DB_NAME): with open(DB_NAME, 'rb') as rfp: return pickle.load(rfp) else: with open(DB_NAME, "wb") as wfp:...
0d61a226c1bfb49249911b8311f8b311740aa281
62,779
def chrono(alg, coalg): """ Performing a histomorphism right after a futumorphism. """ return lambda a: histo(alg)(futu(coalg)(a))
bd44baa1efef93837d891654f64dfeba4442a14c
62,780
import torch def f_score(pr, gt, beta=1, eps=1e-7, threshold=None, activation='sigmoid'): """ Args: pr (torch.Tensor): A list of predicted elements gt (torch.Tensor): A list of elements that are to be predicted eps (float): epsilon to avoid zero division threshold: threshold f...
e6b6f381c15906b9accf88374c88d781ae94f6ca
62,781
import functools import os def with_cleared_umask(func): """ Decorator which clears the umask for a method. The umask is a permissions mask that gets applied whenever new files or folders are created. For I/O methods that have a permissions parameter, it is important that the umask is cleared...
df0f2f91273f90f5d791c8e9b56ac5081f9dbfe0
62,782
def getExtremeN(toSort, N, keyFunc): """ Returns the indices """ enumeratedToSort = [x for x in enumerate(toSort)] sortedVals = sorted(enumeratedToSort, key=lambda x: keyFunc(x[1])) return [x[0] for x in sortedVals[0:N]]
0a8d4979cd5179fa65d02f5c8362581134abea8c
62,783
def is_available(): # type: () -> bool """Returns whether visualization is available or not. .. note:: :mod:`~optuna.visualization` module depends on plotly version 4.0.0 or higher. If a supported version of plotly isn't installed in your environment, this function will return :obj...
ffb8110a7e4672af1f11ab972e3416dc2b6afc34
62,784
import numpy as np import pandas as pd import matplotlib.pyplot as plt import xarray as xr from matplotlib import cm def example_sugihara2012(): """ Reconstruction of the figure's in Sugihara's 2012 paper on CCM """ print('work in progress. the plots arent in amazing agreement for some reason') de...
8b3d94acf8a5d28d4372116d5779f0f1ea58b2e0
62,785
def dict_representer(dumper, data): """ Dumper with OrderedDict """ return dumper.represent_mapping(BaseResolver.DEFAULT_MAPPING_TAG, iter(data.items()))
c0d7d959c926dc5983fc5a16759c46be114ab945
62,786
from typing import Dict from typing import Callable from typing import Optional def build_dataloader( cfg: Dict, split: str, data_manager: DataManager, dataset_class: Callable, rasterizer: Rasterizer, perturbation: Optional[Perturbation] = None, combine_scenes: bool = False, ) -> DataLoade...
414fd79f313fb1ec763bb19872c9e8f0d0e81f28
62,787
def delete_user(request): """delete a user completely""" user_id = int(request.matchdict["user_id"]) if asbool(get_settings().get("enable_user_authentication", False)): # ensure that the user exists and we have the permission to update it may_delete = request.has_perm(perm_global_delete_use...
65d7d3816fe938f3ca6197129062ffab7b7a6fe4
62,788
async def test_do_api_call_async_patch_method_with_success(mock_get_connection, mock_session): """ Asserts the _do_api_call_async for PATCH method. """ async def mock_fun(arg1, arg2, arg3, arg4): return {"status": "success"} mock_session.return_value.__aexit__.return_value = mock_fun m...
9797f0e4797bfd902b4e1c1a3a048c80dd33e754
62,789
def ffmpeg_get_audio_buffer_size(audio_format): """Return the audio buffer size Buffer size can accomodate 1 sec of audio data. """ return audio_format.bytes_per_second
adfb290b9377d680c0a3b0f79adb8f01dcf131fa
62,790
def check_osd_tree_3az_aws(osd_tree, number_of_osds): """ Checks whether an OSD tree is created/modified correctly. This can be used as a verification step for deployment and cluster expansion tests. This function is specifically for ocs cluster created on 3 AZ AWS config Args: osd_tree (di...
ba459d91af0ae5b6796602825e4cfd744a4b087b
62,791
def set_bdev_options(client, bdev_io_pool_size=None, bdev_io_cache_size=None): """Set parameters for the bdev subsystem. Args: bdev_io_pool_size: number of bdev_io structures in shared buffer pool (optional) bdev_io_cache_size: maximum number of bdev_io structures cached per thread (optional) ...
1eaa1403a45845a3d742438cb9ff5f8b408f0684
62,792
def mask_pos_lt(source_length, target_length): """A mask with 1.0 wherever source_pos < target_pos and 0.0 elsewhere. Args: source_length: an integer target_length: an integer Returns: a Tensor with shape [1, target_length, source_length] """ return tf.expand_dims( tf.cast(tf.less(tf.expand...
9f56fdaa30adc31a0407f964117a1c00feead352
62,793
def get_requirement_items(filename): """ Get install requirements from a file. :param filename: A file path to a requirements file. :return: A list of requirement items. :rtype: A `list` of :class:`pip.req.InstallRequirement` """ with PipSession() as session: return list(parse_requir...
dd48ba7417cdfc9758d55001c90c01a179ff3de2
62,794
def hasanyattrs (object ,returnlist = False): """ Checks if the object has any attributes (rather than a particular attribute as implemented in python 2.7.5 function hasattr ) args: object : name of object returns: tuple, ( Bool, listof attributes) example usage: >>> import typeutils as tu >>> p...
4ad87d0026cf443e2b968c16c0ac85158149f348
62,795
def calc_mod3D_ls(data, periods, nphases): """ Need to change this so that it: - first tries to fit only the amplitude and phase - if that doesn't work, estimate amp and only fit phase - then do full fit Also, add a Jacobian for the curve_fit """ # only deal with finite data # N...
e64909355158f4ae9d40dfc38c898a90f7ad2321
62,796
import random def roll_nl(n=2, d=6): """ >>> random.seed("test") >>> roll_nl() 12 """ def dice(): nonlocal total points= tuple(random.randint(1,d) for _ in range(n)) total = sum(points) return points total= 0 dice() return total
07e2a245820896e26c462ac59251c55591bdff76
62,797
from typing import Dict from typing import Any from typing import List def check_md5_command(client: Client, args: Dict[str, Any], params) -> List[CommandResults]: """ Performs the api call to cofense threts-search endpoint to get all threats associated with the given file hash, analyze the response and gene...
00870c61382e403f97321970b50106df985b593a
62,798
from typing import List import glob import os def field_names() -> List[str]: """ Get all available fields """ fnames = glob(os.path.join(PATH, 'rf', '*.png')) basenames = [os.path.basename(name) for name in fnames] return [os.path.splitext(name)[0] for name in basenames]
fd67e55ab41b9f6f03c820d2348e511f894441f7
62,799