content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import OrderedDict def get_generic_path_information(paths, stat_prefix=""): """ Get an OrderedDict with a bunch of statistic names and values. """ statistics = OrderedDict() returns = [sum(path["rewards"]) for path in paths] rewards = np.vstack([path["rewards"] for path in paths])...
56325b4d229a34051fbf981766f4166760d32f6f
45,000
from typing import Iterable from typing import Match import re def snake_case(string: str, bad_casing: Iterable[str] = ()) -> str: """return the snake cased version of a string. bad casings may be specified: if the bad casing is found, the word is replaced with Titlecase: Without bad_casing: ...
5a83aea414c9a7d3e03cf434d7d131aec1c6da78
45,001
def generate_stop_ex_nb(entries, ts, stop, trailing, wait, first, flex_2d): """Generate using `generate_ex_nb` and `stop_choice_nb`. ## Example Generate trailing stop loss and take profit signals for 10%. ```python-repl >>> import numpy as np >>> from vectorbt.signals.nb import generate_stop_e...
9f70593ab4fefcc35362e83b968263de8f2d9fc9
45,002
import struct def pack(header, s): """pack an string into MXImageRecord Parameters ---------- header : IRHeader header of the image record s : str string to pack """ header = IRHeader(*header) s = struct.pack(_IRFormat, *header) + s return s
00bb72e99078d9d43e3637f370f63bd7447c2629
45,003
def inner_product(x, y): """Inner product.""" return x.dot(y)
aa56c71199863b5b8764ce8e96375c8cc61378d4
45,004
import warnings def get_continuous_cmap(hex_list, float_list=None, name=None): """ Creates and returns a color map that can be used in heat map figures. If float_list is not provided, colour map graduates linearly between each color in hex_list. If float_list is provided, each color in hex_list is map...
3f23960559f991b858480a8f21e20968bf636dd3
45,005
def weighted_choice(choices=None, weights=None): """ Chooses an element from a list based on it's weight. :Kwargs: - choices (list, default: None) If None, an index between 0 and ``len(weights)`` is returned. - weights (list, default: None) If None, all choices get e...
79b69fa925af2159029cad0ada04604c59cf5001
45,006
def get_cell_doi_from_link(url): """ Cell and ScienceDirect links have similar properties, but there are several different url types for Cell abstracts and PDFs (much like biomedcentral). Examples: http://www.cell.com/pdf/0092867480906212.pdf --> 10.1016/0092-8674(80)90621-2 http://www.cell...
6651cff123a81dedad2956137a8133c3648fb4d9
45,007
from typing import Dict from typing import Any def gcp_iam_folder_iam_policy_add_command(client: Client, args: Dict[str, Any]) -> CommandResults: """ Add new folder IAM policy. Args: client (Client): GCP API client. args (dict): Command arguments from XSOAR. Returns: CommandRe...
8f1c78e58982f3e3084f3a97bb5c29cc6d4a35d7
45,008
import torch def nn_capacity(dataframe, d_in, H, h_2, d_out, N): """ Takes a dataframe, the number of inputs, the number of nodes for the first hidden layer, the number of nodes for the second hidden layer, the number of outputs, and the total number of datapoints as the input parameters and retur...
0ac4090309177fc2f59f2234540a57f924e70227
45,009
def greedy_best_k_matching(smp, k=1, nodewise=True, edgewise=True, verbose=False): """Greedy search on the cost heuristic to find the best k matchings. Parameters ---------- smp: MatchingProblem A subgraph matching problem. k: int The maximum number of solu...
dbb6684f7aa16125b492da1f325a32a82e5d9247
45,010
from aea_cli_benchmark.case_multiagent_http_dialogues.case import run from typing import Any from typing import List from typing import Tuple def main( duration: int, runtime_mode: str, runner_mode: str, start_messages: int, num_of_agents: int, number_of_runs: int, output_format: str, ) ->...
9d3845d544d73ac4bef457852430ceffd001fb10
45,011
from re import T import logging import copy import itertools def build_examples_from_config(config, variables, product=True, remove_duplicates=True): """Construct Test cases for a task. Args: config: raw dictionary configurary read in from scenario yml file. variables: glob...
5f6c3a8bb173329eba4846182a0ca7c97b253307
45,012
def moments_coords_central(coords, center=None, order=3): """Calculate all central image moments up to a certain order. The following properties can be calculated from raw image moments: * Area as: ``M[0, 0]``. * Centroid as: {``M[1, 0] / M[0, 0]``, ``M[0, 1] / M[0, 0]``}. Note that raw moments ...
e5db83e34fe38350e994e140ca0070876c5a924b
45,013
import google def google_logout(): """Revokes token and empties session.""" if google.authorized: try: google.get( 'https://accounts.google.com/o/oauth2/revoke', params={ 'token': google.token['access_token']}, ...
a8fd75a1d88b308cf6202663ed01d7149d07fb66
45,014
def region_overlap( label_no: int, label_img_outer: np.array, label_img_inner: np.array, overlap_thresh: int = 0.5, ) -> int: """Determine which two regions overlap in two label images. Args: label_no (int): Label number in the inner label image to look for overlap with. label_i...
78cdf69d7c314ff2e3335566e792afcc8a183f7e
45,015
def calc_lambda_r(r, r1, r2, r3, r4, En): """ Mino time as a function of r (which in turn is a function of psi) Parameters: r (float): radius r1 (float): radial root r2 (float): radial root r3 (float): radial root r4 (float): radial root En (float): energy ...
823e209831b90fb7b6bf58bbb12ed35e9244cf74
45,016
from s3db.pr import pr_address_anonymise as anonymous_address, \ def br_person_anonymize(): """ Rules to anonymize a case file """ ANONYMOUS = "-" # Standard anonymizers pr_person_obscure_dob as obscure_dob # Helper to produce an anonymous ID (pe_label) anonymous_id = la...
63eb538f7dce0a7ef58cc3e7125a90e77238ea2f
45,017
def pack_up_static_knapsack_2() -> Knapsack: """ [ Item(name='book', value=1, weight=1), Item(name='food', value=2, weight=1), Item(name='jacket', value=2, weight=2), Item(name='water', value=6, weight=4) ] """ items = ( Item('water', 6, 4), Item(...
cfa2cf72bc549024eea8b549f0f3b97c3d84b680
45,018
from .old import tag from artagger import Tagger import pip from artagger import Tagger def pos_tag(text,engine='old'): """ ระบบ postaggers pos_tag(text,engine='old') engine ที่รองรับ * old เป็น UnigramTagger * artagger เป็น RDR POS Tagger """ if engine=='old': elif engine=='artagger': if sys.version_inf...
62203bf97449a9fca6642add2beed9826f19a585
45,019
import traceback import re def format_exception(exc_type, exc, tb, limit=None, chain=True, _format_exception=traceback.format_exception): """Format a stack trace and the exception information. This wrapper is a replacement of ``traceback.format_exception`` which formats the error and...
5a422f93a9f6e86b25e62940689626ec69aaff8d
45,020
def gen_app_with_di_test() -> UserAppService: """依存解決を実行(テスト用)""" def bind_repository(binder): binder.bind(IUserRepository, to=UserInMemoryRepository(), scope=singleton) class DatabaseModule(Module): @provider @singleton def provide_repo(self, repo: IUserRepository) -> Use...
1a36d72a0fcea88c219d68ddf1188c8dda2b65c9
45,021
def to_millis(seconds): """ Converts the time parameter in seconds to milliseconds. If the given time is negative, returns the original value. :param seconds: (Number), the given time in seconds. :return: (int), result of the conversation in milliseconds. """ if seconds >= 0: return int...
818409afa643dbb8de73c35348a08508227b75a3
45,022
from typing import cast def var(input, axis=None, dtype=None, ddof=0, keepdims=False, name=None): """Variance across an axis. Parameters ---------- input : tensor_like Input tensor. axis : int or None, default=None Axis along which to reduce. If None, flatten the tensor. ...
cdf5a47c48e18bcb0426f8f87d45664afdf2f75c
45,023
def find_closest_pair_edges(edges_a, edges_b): """ Find the edges in edges_a and edges_b that are closest to each other """ def length_func(pair): e1, e2 = pair return (calc_edge_median(e1) - calc_edge_median(e2)).length pairs = [(e1, e2) for e1 in edges_a for e2 in edges_b] return...
b201626597f0a5ecdecd0ceabaacf110e4de84c3
45,024
from pathlib import Path import re def find_version(): """Retrieve the version.""" constpy = Path("dataplaybook/const.py").read_text() version_match = re.search(r"^VERSION = ['\"]([^'\"]+)['\"]", constpy, re.M) if version_match: return version_match.group(1) raise RuntimeError("Unable to f...
a7766a2a3977e0ba2ace33a4c4e9aad64930ace2
45,025
import random def enforce_service_mode(services, FetcherClass, kwargs, modes): """ Fetches the value according to the mode of execution desired. `FetcherClass` must be a class that is subclassed from AutoFallbackFetcher. `services` must be a list of Service classes. `kwargs` is a list of arguments...
7f6164c53bcbb334987b2e81f3dd9c78e569a3c6
45,026
import json def get_all_items(): """ Get all items """ if DATASTORE == "DynamoDB": response = table.scan() if response['Count'] == 0: return [] else: return response['Items'] else: # We want info_hash, peers, and completed. items = ...
3da5bdc760fb497d606a0c16051f4660c965a25a
45,027
def escape_nl(msg): """ It's nice to know if we actually sent a complete line ending in \n, so escape it for display. """ if msg != '' and msg[-1] == "\n": return msg[:-1] + "\\n" return msg
dc30ee05b9985eb69a4e22f2603f739788b22dc8
45,028
def dmp_fateman_poly_F_2(n, K): """Fateman's GCD benchmark: linearly dense quartic inputs """ u = [K(1), K(0)] for i in xrange(0, n-1): u = [dmp_one(i, K), u] m = n-1 v = dmp_add_term(u, dmp_ground(K(2), m-1), 0, n, K) f = dmp_sqr([dmp_one(m, K), dmp_neg(v, m, K)], n, K) g = dmp_...
6c8fe970d1b712355d1f66ba80d768abbfecac1e
45,029
def noun(name: str, num: int) -> str: """ This function returns a noun in it's right for a specific quantity :param name: :param num: :return: """ if num == 0 or num > 1: return name + "s" return name
ccf9fd3f459e8d8946aded4435368231d54cac9f
45,030
def extract_measurements_for_phase(scalars_for_samples): """Convert scalars to simplified dictionary. Returns only uptake and production rates. :param scalars_for_samples: dictionary with lists of replicated scalars across samples :return: list of dictionaries of format {'id': <metabolite id (...
dc6d3ca73677ce1d9cd7ec5e23e52ee05531c08c
45,031
def scrape_all(): """Scrape data from four Mars websites and return dictionary of results.""" # Initiate headless webdriver for deployment # Set up Splinter (prepping the automated browser) executable_path = {"executable_path": ChromeDriverManager().install()} browser = Browser("chrome", **executabl...
258ec8af935e902614cd60721e68f707baa96434
45,032
def filters_from_params(params): """Returns a list of filters (filter context) built from parameters""" filters = [] if params.get('f_list'): filters.append(Q('terms', email_list=params['f_list'])) if params.get('f_from'): filters.append(Q('terms', frm_name=params['f_from'])) if para...
8f91a2695234c69b1c4488e863ac3eba18d8cdc7
45,033
def surface_weighted_three_modes(dp, n1, gm1, gsd1, n2, gm2, gsd2, n3, gm3, gsd3): """ Discrete PDF for a lognormal distribution of particle size for a 3-mode distribution weighted by surface. :param dp: The particle diameters at which to evaluate the PDF...
957cd2bc830bf2ccb633c89a9bde024581227e4f
45,034
def compareChecksum(msgBytes, checksumBytes): """Compute and compare Li-1 message checksum. Args: msgBytes: Raw message bytes. checksumBytes: Checksum to compare against. Returns: A boolean of whether checksum matched or not. """ checksum = calc8bitFletcherChecksum(msgBytes) ...
83a09b55e37e49c7d245d7e47142b5d598324e7e
45,035
def get_assessor_dict(assessor_label, assessor_path): """ Generate the dictionary for an assessor from the folder in the queue :param assessor_label: assessor label :param assessor_path: assessor path on the station :return: None """ assessor_dict = dict() keys = ['project_id', 'subject...
b3fd02f730ef6d966ddec562f0ed40a6ac12ef78
45,036
import os import tqdm import gzip def nonSingletonsPostprocessing(absoluteBGTruth, nsRegionsBedFileName, nsConcordantFileName, nsDisCordantFileName, kbp=10, print_first=False, genome_annotation_dir=os.path.join(data_base_dir, 'genome-annotation')): "...
523dcccefb599977e5d82dfbd0aa95b9f9448ab4
45,037
def token_literal(token_text: str): """ Generates an token lambda file which always returns the same value, this is used for testing, and also as an example of how to write token managers Parameters: token_text(string): the token which should always be returned by the lambda Return: ...
a424211cb527e7acd4eba90c6a4d79505974aac0
45,038
def loop_through_addresses(addresses, recipients, header): """ Loop through all addresses. :param addresses: user address input. :param recipients: list to store all addresses. :param header: message label (To, Bcc or Cc) :return: email addresses. """ try: for recipient in addres...
308689a821cc40d417cf7e81e490050890028f85
45,039
import torch def _rmse(y, y_hat): """RMSE""" y_hat = y_hat.unsqueeze(1) if y_hat.dim() == 1 else y_hat y = y.unsqueeze(1) if y.dim() == 1 else y assert y.shape == y_hat.shape assert y.dim() == 2 assert y.shape[-1] == 1 return torch.nn.functional.mse_loss(y, y_hat).pow(0.5)
b44402511f0e2acf48e9c9210ffa9f023c9a5ca0
45,040
def get_number_as_words(n): """ Gets the integer number returns corresponding string words :param n: integer :return: """ if n == 0: return zero return normalize(abs(n))
944157ec7311c5f52537bfd49b7896ff4e0adde7
45,041
from typing import Any from typing import Mapping def async_replace_list_data( data: list | set | tuple, to_replace: dict[str, str] ) -> list[Any]: """Redact sensitive data in a list.""" redacted = [] for item in data: new_value = None if isinstance(item, (list, set, tuple)): ...
ce2463f5807d053ee642b3acaf4b085aaead6086
45,042
def role_exists(handle, name, **kwargs): """ checks if a role exists Args: handle (UcsHandle) name (string): role name **kwargs: key-value pair of managed object(MO) property and value, Use 'print(ucscoreutils.get_meta_info(<classid>).config_props)' ...
614492a8f3ed2851e287a0fcdbb20781136f6fb2
45,043
def appliance_get_api( self, ne_pk: str, url: str, ) -> dict: """Pass along a GET API call to an appliance .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - appliance - GET - /appliance/rest/{nePk}/{url : (.*...
ef01d3db7cb213438f380e471404605fcd80d892
45,044
from datetime import datetime import csv import requests import time async def main(): """Main method.""" forceQuit = False while not forceQuit: async with ClientSession(headers={'Connection': 'keep-alive'}) as session: print('') print('#####################################...
414cd5bf049fdd053b79de8a01adb726bfab287a
45,045
import re def build_tx_cigar(exons, strand): """builds a single CIGAR string representing an alignment of the transcript sequence to a reference sequence, including introns. The input exons are expected to be in transcript order, and the resulting CIGAR is also in transcript order. >>> build_tx_...
a05211d4dbf04fa6cef8e1e595227985de8e7a36
45,046
import os import logging import functools import time import itertools def train(train_dir, model, dataset_builder, initializer, num_train_steps, hps, rng, eval_batch_size, eval_num_batches, eval_train_num_batches, eva...
be1586025050cdda2e6f749c3899d8fe1a73e652
45,047
def get_toeplitz_dictionary( n_samples=20, n_features=30, rho=0.3, seed=0): """This function returns a toeplitz dictionnary phi. Maths formula: S = toepltiz(\rho ** [|0, n_features-1|], \rho ** [|0, n_features-1|]) X[:, i] sim mathcal{N}(0, S). Parameters ---------- n_samples: int ...
18f6d3c0e13e967f518489e9047a8c34a7157977
45,048
def DictionaryofDate_valuetoArrays(Date_value): """Returns (array): date, value """ date = Date_value.keys() date.sort() value = [] for d in date: value.append(Date_value[d]) return date, value
d4ad630457fc03f9f193515ae51c52f438b0cd81
45,049
from pathlib import Path import re def song_html_file_path(song: Song) -> Path: """Return absolute artist song HTML file path. Parameters ---------- song Song. Returns ------- :cod:`Path` Absolute artist song HTML file path. """ song_file_name = re.sub(r"[\s/]", "...
5cbb8eb4df7d5cb5732b893c9ef9e94e968110d2
45,050
import os def _in_load_test_mode(): """Returns True if the default values should be used instead of the server provided bot_config.py. This also disables server telling the bot to restart. """ return os.environ.get('SWARMING_LOAD_TEST') == '1'
117907bf2bac25e66fdd58ce1fa5b48d68b7e0bb
45,051
def area_separate(cnt): """ Calculates the total area of a list of contours. Args: * cnt - list of contours, as returned by cv2.findContours Returns: * total area """ return sum([cv2.contourArea(x) for x in cnt])
6cdb59b7a3ceef4dc79c8a8742284ce0d62aca21
45,052
def get_id_from_cache(username: str) -> str: """Check if username exists in cache, return their slack_id. Args: username: slack username Returns: slack_id """ dynamodb = boto3.resource("dynamodb") if not CACHE_USERS_TABLE: raise Exception( "env var CACHE_USERS...
6215839febce0f68b1702ab7dabb5b9699dcb09c
45,053
def animate_aux(i, bg_int, faces, face_lines): """perform animation step""" bg_int.sample() for k, f in enumerate(face_lines): f.set_data(face_position(bg_int, k, faces)) ## Fix for multi face animations. #line.set_data(face_position(bg_int, 0, faces)) #line2.set_data(face_position(bg_in...
a56151497d320e344aa7997c956c87cdc597b2be
45,054
import re def cassini_time(time): """Parse Cassini time. Parameters ---------- time: str, int or float Cassini time. Returns ------- float Parsed Cassini time as float. Raises ------ ValueError If the input time pattern is invalid. Examples -...
bc14c2803e04ed690fac75eb32d72b27a803f1ad
45,055
def _onset_by_mfcc(input, framesize=1024, hopsize=512, fs=44100): """ Onset detection by delta MFCC Parameters: inData: ndarray input signal framesize: int framesize of MFCC hopsize: int hopsize of MFCC fs: int samplingrate Returns: ...
6f021326f79905d3424cb3f45ede1419d9b7f129
45,056
def _ClientDataContainer_GetClientObject(self): """ Alias for :meth:`GetClientData` """ return self.GetClientData()
6e8369df36d9c649dca694fe2df240f1ed63cbfa
45,057
def kabsch(test, ref, wgt=None, refl=True): """Returns the Kabsch rotational matrix to map a test geometry onto a reference. If weights are provided, they are used to weight the test vectors before forming the covariance matrix. This minimizes the weighted RMSD between the two geometries. If refl=T...
c503b9e578c6ac6f12f3f69ec715232b8a42abd8
45,058
def _create_run_config(): """Creates a TPU RunConfig if FLAGS.use_tpu is True, else a RunConfig.""" session_config = tf.ConfigProto(allow_soft_placement=True) run_config_kwargs = { "save_summary_steps": FLAGS.save_summary_steps, "save_checkpoints_steps": FLAGS.save_checkpoints_steps, "save_check...
60c7143c44f54fe6056e455e6645c808b9a20680
45,059
def pods_by_uid(pods): """Construct a dict of pods, keyed by pod uid""" return {pod["metadata"]["uid"]: pod for pod in pods}
44b4167c561e494700e56a4967f731e0bef48aab
45,060
def _tags_conform_to_filter(tags, filter): """Mirrors Bazel tag filtering for test_suites. This makes sure that the target has all of the required tags and none of the excluded tags before we include them within a test_suite. For more information on filtering inside Bazel, see com.google.devtools....
1db9528e11d1b513690af14f1d8453f8b0682d34
45,061
def async(startDelaySeconds=None, name=None, maxAllowedRuntime=None, killSwitch=None, ensureOnlyOne=False): """Decorate a function with this to make it run in another thread asynchronously! If defined with a value, it will wait that many seconds before firing. If a name is provided the thread will be named. Handy fo...
a76da9b03d27287fc88c8521a7f58c3dcad7d035
45,062
from typing import Optional from typing import List from typing import Dict def convert_data(csv_data: pd.DataFrame, subset: str = 'all', exclude: Optional[List[str]] = None) -> Dict[str, Dict]: """ :param csv_data: dataframe with columns "mode", "split", "Structure", "seriesId" or "Patient", and "Dice" :...
139683b291f0e076cca4742a9fd932ca4c39e4ed
45,063
from typing import Optional def get_custom_line_item(arn: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetCustomLineItemResult: """ A custom line item is an one time charge that is applied to a specific billing group's bill. :param str arn: ARN ...
23dfa4c57aa5e529aac19818cd26fb735404d9f0
45,064
def boot(name=None, kwargs=None, call=None): """ Boot a Linode. name The name of the Linode to boot. Can be used instead of ``linode_id``. linode_id The ID of the Linode to boot. If provided, will be used as an alternative to ``name`` and reduces the number of API calls to ...
61a2475d5e54281c45b17fe615cf04746ebd01bd
45,065
import os import json def get_model_json_file_or_return_default_values(config, device, camera_id): """ Check if the json file exists and return the information about the ML model within said file. In case the file does not exist, return defaults values from "Detector" in config file. """ base_path...
ff5494532d1b6c7140bbe84af81230721d2b5039
45,066
def create_rating_definition(*, creator: str, bestrating: int, worstrating: int, name: str = None): """Return a mutation for making a Rating definition. A Rating (https://schema.org/Rating) is an evaluation on a numeric scale. A Rating definition describes the structure that a rating can take. It is used so...
19ba58c1a4fcca3a456bd5466eb2b5c1ee74479e
45,067
def generate_clothoid_paths(start_point, start_yaw_list, goal_point, goal_yaw_list, n_path_points): """ Generate clothoid path list. This function generate multiple clothoid paths from multiple orientations(yaw) at start points to multiple orientations...
5f636c085b9e4573d441425ac2a2547e17612145
45,068
import os def getppid(space): """ getppid() -> ppid Return the parent's process id. """ return space.newint(os.getppid())
3c51d9c19460f470980d5c8d180c0d418f88c98a
45,069
def parse_classes(api_classes): """Parse the API classes data into the format required, a list of dict.""" parsed_classes = [] for entry in api_classes: class_ = {} class_[ATTR_ID] = entry["id"] class_[ATTR_CONFIDENCE] = round(entry["score"] * 100.0, 2) parsed_classes.append(...
d6269603e1542b8020300d399f2aba9e97edf9a2
45,070
def mesh_update_attributes(mesh): """Update the attributes of a mesh. Parameters ---------- mesh : compas.datastructures.Mesh A mesh object. Returns ------- bool ``True`` if the update was successful. ``False`` otherwise. See Also -------- * :func:`mesh...
a94d82dc681eb06ead1d657fec3d50268202605f
45,071
def gather_full_backbone(backbone_map: dict): """ Collect all blocks that are part of the backbone Args: backbone_map (dict): map of {state value => backbone block} Returns: set: All BasicBlocks involved in any form in the backbone """ # Get the immediately known blocks from the ma...
58936588d7ddc97ac771825e560d24595dcae1a2
45,072
def get(objectid, worker=global_worker): """Get a remote object or a list of remote objects from the object store. This method blocks until the object corresponding to objectid is available in the local object store. If this object is not in the local object store, it will be shipped from an object store that ...
9728f67ee061c4e6af7d0b9128b3d12997f97e72
45,073
def plot_rboxes_on_image(img, boxes, color=[0, 255, 0], thickness=2): """ 旋转的boxes的结构为外接矩形四个点坐标,boxes=[n,8] or [n,4,2] """ if len(boxes.shape) == 2: h,l = boxes.shape boxes = tf.reshape(boxes,shape=[h,4,2]).numpy() boxes = boxes.astype(int) canvas = np.copy(img) for i in rang...
9294cd03a5f214857204691dfd5ab4b6bb425c77
45,074
import os import contextlib import urllib import sys import io import tempfile import shutil import socket def download_file(remote_url, cache_path, filename=None, timeout=10.*u.second, show_progress=True, block_size=2**16, overwrite=False): """ This is a modified version of `~astropy.utils....
4fbdf2db8e233374ff2ca6410ecd0993dc531b63
45,075
def convertGaiaToXYZUVWDict(astr_file): """ Supposed to generate XYZYVW dictionary for input to GroupFitter Doesn't work on whole Gaia catalogue... too much memory I think TODO: Sort out a more consistent way to handle file names... """ hdul = fits.open(astr_file)#, memmap=True) means, cov...
047d6b3c3f2e00c4a940459ad227dcbe01584257
45,076
import optparse def get_options(): """define options for this script and interpret the command line""" optParser = optparse.OptionParser() optParser.add_option("--nogui", action="store_true", default=False, help="run the commandline version of sumo") options, args = optParser....
ce09dfd6de38781b31b1f07f8f52fd5236c850e5
45,077
def getPixelsForInterp(img): """ Calculates a mask of pixels neighboring invalid values - to use for interpolation. """ # mask invalid pixels invalid_mask = np.isnan(img) + (img == 0) kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)) # dilate to mark borders around invali...
286464f45f79577aa0512efab97bfc53be4b8988
45,078
def set_max_results(uri, max): """Set max-results parameter if it is not set already.""" max_str = str(max) if uri.find('?') == -1: return uri + '?max-results=' + max_str else: if uri.find('max-results') == -1: return uri + '&max-results=' + max_str else: return uri
62793ad686c8abf0e2e750f65d9f709eee2c179e
45,079
def cosine_similarity(a,b): """ Measure of similarity between two vectors in an inner product space. Used for comparing n-gram frequency of e.g. english with the n-gram frequency of a given text, and thus getting a measure of how close the text is to english. """ return dot(a,b) / (norm(a) * nor...
db1fb72fbe519d4809f5c37f0d749435aeea32d8
45,080
def round_frequency(frequency: float) -> int: """Returns the nearest audiologically meaningful frequency. Parameters ---------- frequency : float The frequency to be snapped to the nearest clinically meaningful frequency. Returns ------- float A ``snapped`` frequency value. """ ...
7a66e5a78507a836e80c5a762137bf3fe376894d
45,081
def delete_registry_attr(request, rattr, **kwargs): """ arguments: request, rattr, **kwargs implements: DELETE /api/registry/(RATTR).(FMT) returns: an empty envelope """ m = Registry.get(key=rattr) m.delete() return Envelope(request, result=0)
c3e8ca772e52bdc82c8345638772dde86bc35db1
45,082
def candidates(plist,flist,x,y,dimz,stepsize): """Function to return a list xy-coordinates that indicate which pixels are likely microplastics based on reflectance differences. This function takes the list of pixels with a positive reflectance difference, the whole list of .csv files, the x and y coordi...
ff185c42e3781a5a41aa10fd6ed7c8ba2a497c0a
45,083
import torch def kronecker(mat1, mat2): """ kronecker product between 2 2D tensors :param mat1: 2d torch.Tensor :param mat2: 2d torch.Tensor :return: kronecker product of mat1 and mat2 """ s1 = mat1.size() s2 = mat2.size() return torch.ger(mat1.view(-1), mat2.view(-1)).reshape(*(s1 + s2)).permute([0, 2, 1, 3...
930ac9827b92848656b6579c173b2d7675b7e657
45,084
def from_smile_txt(line_tokens, scale=1): """ line_tokens: a tuple of tokens on a "create" line of a SMILE demo txt file """ kwargs = {"name": line_tokens[2]} def lookup(key): return line_tokens[line_tokens.index(key)+1] if "category" in line_tokens: kwargs["category"] = lookup("category") if "bboxx...
dec892bda2f29d0d71b461e5bd313a3cbdc115b3
45,085
def execute_rule_post(rule_name): """ Use this endpoint to execute the rule engine for a rule for a fact set. --- tags: - Execute Rule Engine parameters: - name: rule_name in: path type: string required: true description: Rule name - na...
fdd0b39baaf1cf7d80f17cd88e3449ffa69a47a0
45,086
def get_mid_geno(np_array, cargs_obj): """ return the genotype with highest probability in the central. """ a_count, b_count, miss_count = _count_genos(np_array) ab_count = a_count + b_count if ab_count > cargs_obj.win_size//2: a_ex_prob = binom.pmf(b_count, ab_count, cargs_obj.error_a) ...
1a6b8f7640602b5967add3a2f24fb5b654b0bb9c
45,087
def current_version(): """Provides version name(not code) : 1.0""" return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName # return "1.0"
fb17040b80cb603cdfccf44920b59a326561624b
45,088
def n2str(num): """ convert a number into a short string""" if abs(num) < 1 and abs(num) > 1e-50 or abs(num) > 1E4: numFormat = ".2e" elif abs(round(num) - num) < 0.001 or abs(num) > 1E4: numFormat = ".0f" elif abs(num) > 1E1: numFormat = ".1f" else: numFormat = ".2f...
42f9f714c49694fdc094ab1802a1c1782e58f942
45,089
def StringCompression(s: str) -> str: """Compresses the specified string using counts of repeated characters. >>> StringCompression("") '' >>> StringCompression("a") 'a' >>> StringCompression("ab") 'ab' >>> StringCompression("abc") 'abc' >>> StringCompression("aba") 'aba...
e23e7f10b4259fed27b57dd3932be53373166821
45,090
from typing import Optional from typing import Literal import os import warnings def load_config_events( run_id: str, source: Optional[Literal["azurebatch", "azureml", "local"]] = None, workspace_name: Optional[str] = None, azureml_run_id: Optional[str] = None, **kwargs, ): """ Try to load con...
0b5af7f25bcd06aeba2fa27682ea8c73a856891a
45,091
import json def _get_json_content(obj): """Event mixin to have methods that are common to different Event types like CloudEvent, EventGridEvent etc. """ msg = "Failed to load JSON content from the object." try: # storage queue return json.loads(obj.content) except ValueError as...
c0ed95cb2a267afa3e0185426a36e9b9225901d2
45,092
import os def compute_target( answers_dset, ans2label, name, dataset, cache_root="data/OK-VQA/cache" ): """Augment answers_dset with soft score as label ***answers_dset should be preprocessed*** Write result into a cache file """ target = [] for ans_entry in answers_dset: answers...
fcf0392267a756dace677b408f04864b91f4411f
45,093
from typing import Optional def form_description(elastic_apartment: ElasticApartment) -> Optional[str]: """ Fetch link to apartment presentation and add it to the end of project description """ optional_text = "Tarkemman kohde-esittelyn sekä varaustilanteen löydät täältä:" main_text = getattr(elas...
8f1c50483a94f6ffb14d132908cec304ee699286
45,094
def extractlocalfeature(point_cloud, is_training, bn_decay=None): """ Classification PointNet, input is BxNx3, output Bx40 """ batch_size = point_cloud.get_shape()[0].value num_point = point_cloud.get_shape()[1].value input_image = tf.expand_dims(point_cloud, -1) # input_image BxNx3x1 with tf.vari...
798825ad8b97fd0bc195e5f1720ac6371e21b63b
45,095
def get_reaction_type(name, path = './data', output_format = 'array'): """to retrieve the type of reactions for reaction dataset Args: name (str): dataset name path (str, optional): dataset path output_format (str, optional): output format in dataframe or in raw array format Returns: pd.DataF...
6c39b74c8a5bab989e4819ccc78273cd6a65fd63
45,096
def beavrsMaterials(): """Dictionary of materials from the BEAVRS specification Currently provides: fuel32 -> 3.2 wt% enriched UO2 air -> air zirc4 -> zircaloy 4 cladding water -> unborated water helium -> helium bglass -> boroscillicate glass ss304 -> s...
6328427d7535501c134daa60f739f1f2d5bc9d05
45,097
import re def possibly_fix_width(text): """Heuristic to possibly mark-up text as monospaced if it looks like a URL, or an environment variable name, etc.""" if text in ['', '--']: return text # stringify the arguments if type(text) not in [type('string'), type(u'Unicode')]: te...
36e72e4578aea9d4be735ecec518bd232e7d40db
45,098
from typing import Dict def dfify_clusters(cols: Dict[str, np.ndarray], df: pd.DataFrame) -> pd.DataFrame: """Concatenate cluster ids with their input features. Args: cols (Dict[str, np.ndarray]): Columns to prepend to df. df (pd.DataFrame): inputrecord ids and their features. Returns: ...
9b0209861562a3f110512012f9a9908b17dee0f4
45,099