content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def group_metrics(metric): """Return the group of a metric""" if metric in ['nme', 'mbe', 'sd_diff', 'corr']: return "common" elif metric in ['extreme_5', 'extreme_95']: return 'extremes' elif metric in ['skewness', 'kurtosis', 'overlap']: return 'distribution' else: ...
d34d3b9f31e3186579e82d6083d5330c1d31c4ab
625,682
def dereference_id(model_class, model_id): """Dereference a single object by id. :parameters: - `model_class`: The class of a model to be dereferenced. - `model_id`: The id of the model to be dereferenced. """ meta = model_class._mongometa document = meta.collection.find_one({'_id': met...
45c9cc8cca3edea8c9a4af13d714553aa093029b
625,683
def _parse_bool_str(attr, key, default='False'): """Parse bool string to boolean.""" return attr.get(key, default).strip().lower() in ['true', '1', 't', 'y', 'yes']
92adfff0d95df5054d6ad01802460b81d7e40eb5
625,684
def arrayCheck(nums): """ Function to find a sequence 1, 2, 3. Given a list of integers, return True if the sequence of numbers 1, 2, 3 appears in the list somewhere. Args: nums (Array): Array of integer """ for i in range(len(nums)-2): if nums[i] == 1 and nums[i+1] == 2 a...
22b871e12e49fbd215ca517ff1071d38f06c26cc
625,685
import requests def weather(ctx, where=None): """ Weather. Get the weather for a location. """ if where is None: where = ctx.origin try: geocode = ctx.provider_for("geocode") except KeyError: ctx.respond(ctx._("Sorry, I don't have a geocode provider loaded.")) ...
5887ed8b8ab805eb1df2bde95324d75bb3e2c349
625,686
def normal_prior(): """Give string format of normal distribution prior""" return "normal(0, 1)"
5a35441c24ad2a80e6f3fad0f29785a2026de944
625,687
import pathlib def _extract_serialization_type(first_file: pathlib.Path) -> str: """ Deduce the serialization type :param first_file: serialized file :return: one from ["msgpack", "pickle", "json"]. """ msg_pack = first_file.suffixes == ['.msgpack', '.xz'] msg_pickle = first_file.suffixes ...
924584ea2fa834b79ff458c448dde8cdb5a8e293
625,688
def edges_between_nodes(graph, nodes): """ Return all edges in graph that connect the nodes :param graph: :param nodes: :return: """ edge_selection = [] for edge in graph.edges: if edge[0] in nodes and edge[1] in nodes: edge_selection.append(edge) return edge_s...
ab679b0f89920dc89f4928aa3da7e8b6f9bab2c7
625,689
def pos2iso6709(lat: float, lon: float, alt: float, crs: str = "WGS_84") -> str: """ convert decimal degrees and alt to iso6709 format. :param float lat: latitude :param float lon: longitude :param float alt: altitude :param float crs: coordinate reference system (default = WGS_84) :return:...
e1dbf684402504f93f44f7607d755bb17c6c5546
625,690
import argparse def initParser(): """ https://docs.python.org/3/howto/argparse.html https://docs.python.org/3/library/argparse.html#module-argparse Returns argparse.Namespace object. """ p = argparse.ArgumentParser() p.add_argument("-v", "--verbose", action="count", hel...
89dab00645789d27d9d092ff43210591ac018042
625,691
def lowercase(word): """ LOWERCASE word outputs a copy of the input word, but with all uppercase letters changed to the corresponding lowercase letter. """ return word.lower()
965713e650c08b0b336a3b17c046ccee605053f0
625,692
def bookmark(information:dict) -> str: """ input: item:dict ={"url":str,"text":str,"caption":str} """ if information['caption']: return f"![{information['caption']}]({information['url']})" else: return f"![]({information['url']})"
b2de9c25243450d170ce7c8bf9d6458a6b8ae2a5
625,693
import re def get_day_number_from_heading_string(heading_string: str) -> int: """ Extract day number from heading string. >>> get_day_number_from_heading_string( ... "Day 1: October 16, 2019, Wednesday", ... ) 1 Arguments: heading_string (str): Day's log header string from whi...
77662cd0c6a89fcb649b12e6f374981bef8243aa
625,694
import re def get_name_server(): """Return IP address of private name server.""" with open('/etc/resolv.conf') as f: s = re.search(r"nameserver[\W](.*)\s", f.read()) if s: return s.groups()[0]
28f69f4a1d7f68f75b296c577cf1edea5d35414f
625,695
def is_informational(code): """Return that the code is a provisional response.""" return 100 <= code <= 199
4fb136e3e6fda8d626219c50d7314be0757fecea
625,696
def solution(limit: int = 1_000_000) -> int: """ Returns an integer, the solution to the problem >>> solution(10) 31 >>> solution(100) 3043 >>> solution(1_000) 304191 """ phi = [i - 1 for i in range(limit + 1)] for i in range(2, limit + 1): if phi[i] == i - 1: ...
bd79e7dc232872ff7011f7be8d3e79cdda87bae2
625,697
def TEMPtoYxy(TempK): """ convert white temperature between 1000K & 25000K to xy chromacity :param TempK: temperature (in Kelvin) :return: Yxy tuple """ if TempK > 25000 or TempK < 1000: raise ValueError elif TempK >= 4000: if TempK > 7000: x = (-2.0064e9 / pow(TempK, 3))...
883c00b427db2fbe9c74bca21ca636d64d855a15
625,698
import json def parse_sns_message(event: dict) -> dict: """ Parses SNS record and returns its message. :param event: SNS event that triggered the lambda :return: parsed SNS message """ return json.loads(event["Records"][0]["Sns"]["Message"])
3d741bd6aa454e9301fa5c3f5b2fd35ed9300859
625,700
def generate_interpolation_trajectory(x_start, x_final, traj_to_match): """Generate a 1d interpolation profile, where the velocity is constant over the duration of the trajectory. Args: x_start: Start position of the trajectory. x_final: End position of the trajectory. traj_to_match:...
392cb050bb0b0452a9d1bc564bbeb3406d4dbe2b
625,701
def c_to_int(c, x_width): """ Takes a complex number and a width. Converts to an integer of length x_width*2 bits. """ # Real part in high x_width bits. # Imag part in low x_width bits. # Complex components must be between -1 and 1. if c.real < -1 or c.real > 1 or c.imag < -1 or c.imag >...
4e0fd78c224f1dbeb12cb14894d0901da3de6662
625,702
def deal(deck): """Draws a card and returns card""" card = deck.draw_card() return card
d8373040d9762542ba6eeb1322d38ff87dfb9e02
625,703
def step_reduce(reducee, reducer, order): """ Return the reduced polynomial of reducee by reducer. That is, if one of reducee's bases is divisible by the leading base of reducer with respect to the order, the returned polynomial is the result of canceling out the term. """ lb, lc = order.le...
a98db8a9627f27670d8236f39339979a79a5ab11
625,704
def func_4(mol, bits): """ *Internal Use Only* saturated or aromatic heteroatom-containing """ AllRingsBond = mol.GetRingInfo().BondRings() ringSize = [] temp = {3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0} for ring in AllRingsBond: ######### saturated nonsingle = False...
1343643c3dea07466e606ea417fb22ede0bcca82
625,705
def readme(): """ Return the README text. """ with open('README.md') as fh: return 'empty'
cfa80319884ebc0dbe14e63deb40dae5118de5dd
625,706
def _get_param_vals(param): """Gets the value of the parameters :param param: The parameter triple whose values are to be generated. :returns: The value of the parameter on a five-point stencil. """ return [ param[1] + i * param[2] for i in range(-2, 3) ]
e724012c84054da7fff801a037246aed54889eb7
625,707
import re def _extract_parameters(s:str)->dict: """ The functions parses all parameters from a ShipFlow Motions indata file. The function searches for: x = ... and saves all those occurences as a key value pair in a dict. Parameters ---------- s : str Motions indata file c...
e1c50dee22f78af16a5e5567f4ac70d389e6b9b3
625,708
from datetime import datetime def get_readable_date(datetime_str): """ Convert UTC datetime to readable form of date """ date_str = datetime_str.split('T')[0] return datetime.strptime(date_str, "%Y-%m-%d").strftime("%d/%m/%Y")
1d6090e2cf77805ce5dd5f8db6e2624f1273f202
625,709
def get_valid_actions(board): """ get possible valid actions """ return [c for c in range(0,7) if board[0][c]==0]
ff9cfcd310d65cc7d0be95da3d82f62f95a403c2
625,710
def crop_center(im): """ Crops the center out of an image. Args: im (numpy.ndarray): Input image to crop. Returns: numpy.ndarray, the cropped image. """ h, w = im.shape[0], im.shape[1] if h < w: return im[0:h, int((w - h) / 2):int((w - h) / 2) + h, :] else: ...
b98639419c0b792366273ddd8c90c5370292a73e
625,711
import yaml def get_cache_data(filepath): """Read the cache file and return the data. @param filepath: string. Specify a path to a file to read. """ with open(filepath) as user_data_file: user_data = user_data_file.read() # user-data.txt is in yml, so convert it to json cache_data = ya...
adb03269a8be0b3b6c413c6951d6909375a6d849
625,712
import subprocess def get_short_hostname(): """Returns the local short hostname :return string """ p = subprocess.Popen(["hostname", "-s"], stdout=subprocess.PIPE, universal_newlines=True) return p.communicate()[0].rstrip().lower()
09d8432dcba2b56ac4da7eb1656ab3679ce68e90
625,713
import numpy def calc_chiral_term_cos_sq_mix( tensor_sigma, f_m_perp, flag_tensor_sigma: bool = False, flag_f_m_perp: bool = False): """Calculate the term M3 for the case of coexistiong paramatic and magnetically ordered sublattices. For details see documentation "Integrated intensity from powder diff...
73f018dffb844607e764406a28da46748eba3f0e
625,714
def get_search_query(list2, t): """Create a query, that we will parse. __Attributes__ list2: List, which contain start and end date. t: if 1 change search query (look below) __Returns__ search_query: List, which contain search query. """ if t > 1: search_query = ("...
2846a328cde683534bf452c74ec3139d868dccbc
625,715
import requests def read(uri): """ Abstract read function. EDeN can accept a URL, a file path and a python list. In all cases an iteratatable object should be returned. """ if hasattr(uri, '__iter__'): # test if it is iterable: works for lists and generators, but not for # strings ...
390b0b07b085c48dc87037c1881080794af28129
625,716
def update_param_vals(pars, prefix, **kwargs): """Update parameter values with keyword arguments.""" for key, val in kwargs.items(): pname = "%s%s" % (prefix, key) if pname in pars: pars[pname].value = val return pars
bde24b19dc0597690f74f66ccd6e7c195d1e2267
625,717
def predictionToOutputTask1(modelPrediction, singleTokenizedSentence): """ Converts the prediction vector to the respective entities identified in the text :param modelPrediction: :param singleTokenizedDocument: :return: """ observationsList = list() familyMemberList = list() observa...
0cc8848548fcca135f5df7e524527fa521d5b1d7
625,718
import glob import json def load_recipes(path): """Load recipes from json files Parameters ---------- path : str Path to json files e.g. ./json/*.json Returns ------- list List of dicts """ jsonfiles = glob.glob(f'{path}/*.json') recipes = [] ...
1d0fafbaddabe91ef28220c1bbd91e8e59a6ac0a
625,720
import binascii def get_partition(num_partitions, queue, project=None): """Get the partition number for a given queue and project. Hashes the queue to a partition number. The hash is stable, meaning given the same queue name and project ID, the same partition number will always be returned. Note also...
2ef0cede503eb7abc361b8b7cebae65805fbec38
625,721
import pathlib import io import yaml def load_nondev_yaml(dev_path: pathlib.Path) -> bool: """ Partially reads a yaml file and stores results in a dictionary. Parameters ---------- dev_path : pathlib.Path Path to the conda file with dependencies (e.g. `environment-dev.yml`). This ...
8b110beec4fd93d9274d3606b0dfa7c12153892a
625,722
def id_transform(): """Returns the identity transform. >>> it = id_transform() >>> it [[1, 0, 0], [0, 1, 0], [0, 0, 1], [0, 0, 0]] >>> v = [4,-10,1] >>> apply_transform_vec3(it, v) == v True """ return [[1, 0, 0], [0, 1, 0], [0, 0, 1], [0, 0, 0]]
0af9895df623addbfa10e2144ad332f3bf803707
625,723
def upper(text): """ Creates a copy of ``text`` with all the cased characters converted to uppercase. Note that ``isupper(upper(s))`` might be False if ``s`` contains uncased characters or if the Unicode category of the resulting character(s) is not "Lu" (Letter, uppercase). The uppercas...
b4d2b1b03240e78a3c4113dd66e98e29419f91d5
625,724
def return_nearest_time_index(desired_time,time_series,index=True): """ input the desired time, double, and time_series, pd.Series, returns the index of the time_series. If you want the actual time value, change index=False """ # commented out due to error in mp.argmin #nearest_value = lamb...
22c58450b205377ce6d301038d73e02e72d9bc75
625,725
def FileName(dir,stat,alg,avg,min,max): """get svg graph file name from dimensions. For stat use 'perf|size(min|avg|max)' used for the y axis. Use 't' for the dimension used as the timeseries label. Use 'x' for dimension used as x axis. Use 'o' for the optimal value for the algorithm. Use 's' for the stand...
3342f403281b31c5d6fbda96c7340cf74b89c00f
625,726
import os import torch def load_quiver_feature_partition(partition_idx: int, result_path:str): """ Load partition result for partition ${partition_idx} Args: partition_idx (int): Partition idx partition_result_path (str): partition result path Returns: partition_book (tor...
04db6e4baefe47b20a3d43bac2462d0730fa7801
625,727
import random def get_next(th): """ Decide if will proceede to next stage or not """ sort = random.randint(0, 100) if (sort < th): return True return False
8410cb08b803f36bd7dac2ed68cdd307582f1256
625,728
def _prepare_toc(toc): """Prepare the TOC for processing.""" # Drop toc items w/o links toc = [ii for ii in toc if ii.get('url', None) is not None] # Un-nest the TOC so it's a flat list new_toc = [] for ii in toc: sections = ii.pop('sections', None) new_toc.append(ii) if ...
c2a7bb66def461ec0533cad8c109b77114282de1
625,730
def number_of_publications(publications: list[dict]) -> int: """Computes the number of publications. (This function exists rather for consistency.) :param: a list of publications. :return: the number of publications. """ return len(publications)
f8e9927f8d0aa91982abfc5e905fbac2fe6ef6d5
625,731
from typing import Tuple from pathlib import Path import argparse def parse_arguments() -> Tuple[str, Path, Path]: """Parse command line arguments Returns: Tuple[str, Path, Path]: (identifier, path to save log, path to VLC) """ parser = argparse.ArgumentParser( description="Connect to...
d3c794a2828468dd8e03de1cb08cdd8875d1648e
625,732
import csv def seemsLikeGTF(cols): """ Does a line look like it could be from a GTF file? Column contents must be: 3: int 4: int 5: '.' or float 6: '+', '-', or '.' 7: 0, 1 or 2 8: matches the attribute regular expression """ try: int(cols[3]) int(cols[4]) ...
2160e5bb60c7f4cff2855c394d16d2551d0d5f33
625,733
import os def build_dir(*path_parts): """ Utility for building and creating directory Args: path_parts (str): parts of directory for building Returns: out_dir (str): created local path """ out_dir = os.path.join(*path_parts) if not os.path.exists(out_dir): os.mak...
965f496f2512cfe45fcbd26a5ab8433f8be0ef1d
625,734
import torch def calculate_R_pi(R, pi): """ calculates R_pi R_pi(s) = \sum_a pi(s,a) r(s,a) :param R: reward matrix of size |S| x |A| :param pi: matrix of size |S| x |A| indicating the policy :return: """ return torch.einsum('sa,sa->s', R, pi)
5897287b08cd0747d21a907f06d86324912b94fc
625,735
import os def load_phi_locations(path='data/notes/id.phi'): """ Returns the locations of PHI within each nursing note. The locations are character offsets within each note of the form begin/begin/end offset. Format (tab delimited): Patient 1 Note 1 23 23 42 114 114 121 ...
5e73157dabadfad1115b40f404ba71576c27f5ce
625,736
def rename_list_to_dict(rlist): """ Helper for main to parse args for rename operator. The args are assumed to be a pair of strings separated by a ":". These are parsed into a dict that is returned with the old document key to be replaced as the (returned) dict key and the value of the return ...
a22b0931580488b9b3e8457eeb49a8509695e7fd
625,737
import io import gzip import json def load_cloudtrail_log(s3_client, bucket, key): """ Loads a CloudTrail log file, decompresses it, and extracts its records. :param s3_client: Boto3 S3 client :param bucket: Bucket where log file is located :param key: Key to the log file object in the bucket ...
a043e1b9172404f67b70d1cb42f64fc5e6603836
625,738
import requests def bio(name): """ Provides paragraph biography/background description of 1 individual or entity from an entity get request on LittleSis API. Resorts to entity with the highest number of relationships listed for entries that point to multiple entites (like last name only entries). ...
9cf3b61f24eae9cb0f8ce5c2b7ae24331a099ad5
625,739
def expand_call(kwargs): """Execute function from dictionary input""" func = kwargs['func'] del kwargs['func'] optional_argument = None if "optional_argument" in kwargs: optional_argument = kwargs["optional_argument"] del kwargs["optional_argument"] transform = None if 'tran...
b5a9c324dd93ea118f84bfff64222918d123ba3e
625,740
def get_device_family_chipset(vendor_id, device_id, device_map): """Get the family and chipset strings given the vendor and device ids. Args: vendor_id: a string representing the vendor id (e.g. '0xabcd'). device_id: a string representing the device id (e.g. '0xbcde'). Returns: A s...
f45e8174cd67d7351079c7f11eee54e9e4645276
625,742
def keep_in_dict(obj, allowed_keys=list()): """ Prune a class or dictionary of all but allowed keys. """ if type(obj) == dict: items = obj.items() else: items = obj.__dict__.items() return {k: v for k, v in items if k in allowed_keys}
ee2f478d597689735f5bbd7325dd53dac0a189d7
625,743
import os def get_bm_fix_path(bm_info, key_seq, last_path=None): """Get model path of benchmark yaml.""" _bm_path_seq = [bm_info[_key] for _key in key_seq] if last_path: _bm_path_seq += [last_path] # model_path = os.path.join(bm_info["archive_root"], bm_info["id"], "models") target_path = ...
a988fecbe9366a4a6ab9ff88834b0491c2d9b797
625,744
def kingmaker(to_parse=None): """ Outputs a link to the recap episodes. :param to_parse: :return: """ return "The story so far: https://www.youtube.com/playlist?list=PLSQSsMCgp5bCn9dGMsCvSYRazL-VHW_j7"
dac8d487fb2eb858060c1d2a9d2367b224d362b0
625,745
import zipfile import sys def read_version(): """Read the version number from the VERSION file""" version_file = 'VERSION' with zipfile.ZipFile(sys.argv[0]) as zf: try: with zf.open(version_file) as f: version = f.read() version = version.decode('ascii')...
97ec046b314275df2f4130ee7bc1e8cddce2f5f8
625,746
import numpy def constant(t_predict, value): """Generates a time series array with constant value. Generates a time series array with constant value `value` for all elements in `t_predict`. Args t_predict: Numpy array containing the points in time where you want to generate a prediction us...
1944ed0dd1b16d2368007fa97c88393b2f927ace
625,747
import numpy def make_grid_hermitian(guv): """ Make a grid "hermitian" by adding it to its own conjugated mirror image. Just as baselines can be seen from two sides, the grid is "hermitian": Mirrored coordinates yield complex-conjugate uv-cells. However in practice, it is less computationally...
ec9adb6e28c0cecff38496f3062342173c4ce394
625,748
import numpy as np def fix_node_size_issue(da): """i calculate node size (city total pop) by the migration dataframe where only cities the was migration has the OutPop field no NaN""" for node in da['node']: da_node = da.sel(node=node, parameter='size').astype(float) da_node[da_node ==...
a00f011191fcd7ed5ee5f4a94b8859a1d6cdca96
625,751
def insertSort(arr): """ docstring """ for i in range(1, len(arr)): j = i while j > 0: if arr[j] < arr[j-1]: arr[j-1], arr[j] = arr[j], arr[j-1] j-=1 return arr
2c1c5761ff17e7063909c0e86c00a0822d969585
625,752
def check_status(tc_code): """ Get the pass/fail status of each testcase :param tc_code: a list containing every test case's .xml text as separate elements (the output of parse_test_cases) :return: a list containing all test case's pass or fail status """ status_val = tc_code.find_all("status") ...
cf76fcce7af246e54888bf9aef68050b38ba88d0
625,753
def estimate_clock_offset(list_realtime_ets, set_last_at_realtime=True): """ Estimate event timer clock offset Given a list of (realtime, AntEventTimerSample), work out the offset between the ANT+ event timer clock and real clock time. Optionally update the last_at_realtime field in each of the sample object...
904fd72c98ba3edeb34843b3d40053f1db4233be
625,754
import time def timer(func): """ 计时器修饰器 :param func: """ def wrapper(*args, **kwargs): _start = time.time() _result = func(*args, **kwargs) print("%s's result is %s, time cost: %s" % (func, _result, time.time() - _start)) return _result return wrapper
c420fe94529d14924c8356925ee44bd3ad88d24d
625,755
def default_split(data: str, separator: str=' ', default: str='', maxsplits: int=0) -> list: """ Function to split a string and return a list of substring. If more splits requested than there are substrings then a default value is used. Args: data (str): String to be split. separato...
9ca07068e9c291ff9cf2ee1bda8f8a61201b47ba
625,756
def descriptor2colspecs(descriptor_str): """ Convert fortran format string, e.g., `2I4,4I3,3I4,2I7,F6.2,I7, 8F8.2,4F8.1,F7.2,F9.0,F6.2,2F7.2,F6.1,6F8.2,7I6,F7.2,F5.1`, to the list of fixed columns tuples expected by :func:`pandas.read_fwf`. """ colspecs = [] i = 0 for tok in descriptor_s...
1283f50319df8337ca961b804b8f13bc3af283fb
625,757
import torch def mu(X, J): """ computes mean vector for given set of locations/response indices. """ return torch.zeros(X.shape[0])
7e7f5523666bb57603ab53dfc0ba416c0bf7b25c
625,758
def read_file(file_str): """ Return file lines for a file """ file_obj = open(file_str, "r") file_lines = file_obj.readlines() return file_lines
eee386bd7478c70680bf5a8e6997a8cd4f73f872
625,759
import itertools def generate_test_list(settings): """All options that need to be tested are multiplied together. This creates a full list of all possible benchmark permutations that need to be run. """ loop_items = settings["loop_items"] dataset = [] for item in loop_items: resul...
1addf07dd99085d4aab0e4a2198dc42634a9c47b
625,760
import spwd import crypt import grp def auth(username, domain, password=None): """Check if user is allowed to login.""" password = '' if (password == 0) or (password is None) else password try: storedPassword = spwd.getspnam(username)[1] givenPassword = crypt.crypt(password, storedPassword...
c8c8ec050ba5878afa1d75e8320535df3db0231b
625,761
def sortByDate(msg): """ helper function in redis search. unused during communication """ return msg['createdDate']
c8b59694cfee594ef9ec5a649f38053c457c674f
625,763
import string def process_embed_content(template, content): """Embedd content into html template.""" txt = string.Template(template) html = txt.safe_substitute({'content': content}) return html
993611ec8df6941ea1b277c33ffe48e97b37b7ee
625,764
import os import json def __get_db_dict(): """ Get the list of sources as a json, e.g: { "monit_idb_monitoring": { "type": "influxdb", "id": 9109, "database": "monit_production_monitoring" }, "monit_idb_cmsjm_old": { "type": "...
7d4b0afb94eacd78b1e5aa0852b1164b19892a5d
625,765
def solve(passphrases): """Calculate number of valid passphrases. :passphrases: string of passphrases, separated by newlines :return: number of valid passphrases >>> solve('abcde fghij') 1 >>> solve('abcde xyz ecdab') 0 >>> solve('a ab abc abd abf abj') 1 >>> solve('iiii oiii o...
288fc700eea2235e90be2a0c3f1d5e5e4db138f3
625,766
def dms2dd(degrees, minutes, seconds, direction): """ http://en.proft.me/2015/09/20/converting-latitude-and-longitude-decimal-values-p/ Args: degrees: minutes: seconds: direction: Returns: """ dd = float(degrees) + float(minutes)/60 + float(seconds)/(60*60) ...
ccde68be833cf0878ca5ee03113a109f03f7eb14
625,767
def group_by_xs(datasets): """ Return datasets grouped by polarization cross section. """ cross_sections = {} for data in datasets: cross_sections.setdefault(data.polarization, []).append(data) #print("datasets", [":".join((d.name, d.entry, d.polarization, d.intent)) for d in datasets])...
768d044a23836e0ece52950145621c5f5f15d50a
625,768
import csv def update_list(request): """ Adds the url to list of feeds than the bot can consult """ entities = request['entities'] context = request['context'] url = entities['url'][0]['value'] name = entities['name'][0]['value'] with open('list.csv', 'a') as f: feed_writer = c...
84ac9e2b5e851ee7d211c1434b54a45f471d0db6
625,769
def _comment_ipython_line_magic(line, magic): """Adds suffix to line magics: # [magic] %{name} Converts: %timeit x = 1 Into: x = 1 # [magic] %timeit """ return line.replace(magic, '').strip() + f' # [magic] {magic.strip()}'
e9419fdbe54978eb65d3cadf1c98095f74daaa72
625,770
def tfe_to_v(atoms): """Замена пар (плавающая t, e) на v""" atomsv = [] for atom in atoms: if atom.type == 'e': continue if atom.type == 'tf': atom.val = 'v' + atom.val[2:] atom.type = 'v' atomsv.append(atom) return atomsv
c08d1859df493084a899201cecb056a1546ef25a
625,771
def set_variables_in_pao_mod(ion_name, variables, n, l, pao_mod, global_splitnorm, charge_conf): # noqa """ Changes the pao_mod dictionary to include variables for obtimization """ ang_to_bohr = 1.8897161646321 save_z1 = pao_mod._gen_dict[n][l][1] for z in pao_mod._gen_dict[n][l]: strin...
d86a45b58bcf2222a79bbcd9f93053bf3dbc8aac
625,772
def event_cd(u0, u1, k, ep=None, en=None, cd=True): """ Return the events of the process of encrypt and decrypt :param u0:-> previous reding :param u1:-> current reading :param k:-> current key part :param ep:-> forbidden event :param en:-> null event :param cd:-> choose encryption or de...
00978a4eef926aa25a7420c4cbe88ab30c80b07e
625,773
def _compose_sources(compose): """ Get compose sources . :param compose dict: Compose info from ODCS. :return: a list of lists in format [[N1, S1, V1, C1], [N2, S2, V2, C2]...]. :rtype: list """ source_value = compose.get("source", "") sources = [] for source in source_value.split()...
f7729e841b1ad7266531c5e96b980d4e63ff33be
625,775
def SeparaPontoFinal(s): """Toqueniza reticências e pontos finais delimitadores de sentenças, mas não pontos que constituem parte de palavras. """ s=s.rstrip() if s.endswith("..."): return "%s ..." % s[:-3] elif s.endswith("."): return "%s ." % s[:-1] else: return s
72d83fe640161a84950de9a83b9965ede38154e3
625,776
import importlib def import_func(func): """ Imports a function from the autocnet package. Parameters ---------- func : str import path. For example, to import the place_points_in_overlap function, this func can be called with: 'spatial.overlap.place_points_in_overlap' R...
f7830c3d26e02349c7f4a8f7ae0b790b98b0e7d4
625,777
def race_by_grade(races): """ Separa as corridas do dia em categorias """ output = {"A": [], "D": [], "S": [], "HP": [], "OR": [], "ALL": []} for race in races: if "A" in race.grade: output['A'].append(race) elif "D" in race.grade: output['D'].append(race) eli...
0e294e9ea1f2601b1c292ee76951dbcef7baf76b
625,778
def calc_delta_capacitance_ratio(capacitance_doublelayer, capacitance_dielectric): """ Ratio of the double layer to dielectric capacitance units: ~ Notes: Squires, 2010 - "Ratio of the double layer to dielectric capacitance" Adjari, 2006 - "Surface capacitance ratio" ...
e4863a5920548e7335aedd07176bb6d67e048590
625,779
import torch def load_waveglow_model(waveglow_path): """ Loads the Waveglow model. Uses GPU if available, otherwise uses CPU. Parameters ---------- waveglow_path : str Path to waveglow model Returns ------- Torch Loaded waveglow model """ waveglow = torch....
2289ef4649c54f746c86bbea2f8a2e0038da4e05
625,780
def _to(f, x, nearest): """ :param f: rounding function, e.g. ceiling, floor, round :param x: number to round :param nearest: number to round to :return: x rounded to `nearest` """ return nearest * f(float(x) / nearest)
119e3569cd16cc4eeea9316b4ad24e27ca91719e
625,781
import re def clean_unicode(full_txt): """Deal with some escaped unicode issues. Parameters ---------- full_txt: str String that may contain unicode. This function focuses on text from xDD highlights. Notes ---------- Short term solution, reported to xDD """ full_...
cf0710f259f6a93d11d58511d33562fac3cbd951
625,782
import json def read_JSON_file(path): """ Given a line-by-line JSON file, this function converts it to a Python dict and returns all such lines as a list. :param path: the path to the JSON file :returns items: a list of dictionaries read from a JSON file """ items = list() with open(...
3de5dff408e8ca9ee0840617214fdef558acd153
625,783
def unesc(s, esc_chars): """ UnEscape special characters """ for c in esc_chars: esc_str = '\\' + c s = s.replace(esc_str, c) return s
030d4102825fef7a3ca5e3e2cdcb764dea77dbc8
625,784
def quicksort (a): """quick sorter""" if len(a) <= 1: return a else: return quicksort ([e for e in a[1:] if e < a[0]]) + [a[0]] + quicksort([e for e in a[1:] if e >= a[0]])
f8e0005e50970c57d3c949835802b432ad677d1a
625,785
def _read(filename: str) -> str: """ Reads in the content of the file. :param filename: The file to read. :return: The file content. """ with open(filename, "r") as file: return file.read()
f2cbf7dba5df7044dfde49e2dd9dfd6be73aae08
625,786
def all_boolean_reductions(request): """Fixture for boolean reduction names.""" return request.param
f4ac578c5ab5777872c9345182b5f1081bd0f00d
625,787
from pathlib import Path import sys import subprocess import json def run_notebook(fn: Path) -> dict: """Run a notebook, returning the raw json dict""" jupyter = Path(sys.executable).parent / "jupyter" if not jupyter.exists(): raise Exception(f"Cannot find jupyter in {str(jupyter)}") cmd = [st...
403069248a6a89c000b756715fde64626660da7e
625,789
def _mid(pt1, pt2): """ (Point, Point) -> Point Return the point that lies in between the two input points. """ (x0, y0), (x1, y1) = pt1, pt2 return 0.5 * (x0 + x1), 0.5 * (y0 + y1)
a1095d46c01772ff3de373ccb91c626bf9222814
625,790