content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def fetch_MEN(which="all", form="natural"): """ Fetch MEN dataset for testing similarity and relatedness Parameters ---------- which : "all", "test" or "dev" form : "lem" or "natural" Returns ------- data : sklearn.datasets.base.Bunch dictionary-like object. Keys of interes...
5452ce4451c2da17d6b3bdf01934dd8e3661da4d
3,609,900
from datetime import datetime def custom_payload(claims, expiration): """ Creates JWT payload. Author: Lucas Antognoni Arguments: claims (list): Token payload claims. expiration (datetime.timedelta): Timedelta. Response: pay...
319f89598e1623a746ae4229a262aad0f3b4da65
3,609,901
import base64 def b64s_to_s(b64s: str) -> str: """convert base 64 strting to string :param b64s: input base 64 string :type b64s: str :return: output string :rtype: str """ s = base64.b64decode(b64s.encode('utf8')).decode('utf8') return s
beb49deb87d45da43cc8f12b3aacec37d7bfd1ed
3,609,902
from typing import Optional from typing import Tuple from typing import List from typing import Dict def solve_tsp_dynamic_programming( distance_matrix: np.ndarray, maxsize: Optional[int] = None, ) -> Tuple[List, float]: """ Solve TSP to optimality with dynamic programming. Parameters -------...
ec9a12315b6e1cfd1fd144617005ea9ac3169293
3,609,903
import os def get_c_files(path): # type: (str) -> List[str] """Get C/C++ files in the path""" return [f for f in os.listdir(path) if os.path.splitext(f)[1] in ['.c', '.cc', '.cpp']]
04c56c818866b173a221ff6e7a99ef553b5ad6c3
3,609,904
from typing import Counter def counter(data, n=None): """counter方法用于统计元素数量 Parameters ---------- data : list 列表数据 n : int 前n个元素 Returns ---------- """ ret = Counter(data) if not n: ret = ret.most_common(len(ret)) else: ret = ret.most_common(...
6fed62dd1478992c13c8dee5dd2cbb7556a5d0fe
3,609,905
def col255_from_RGB(red,green,blue): """ returns a term256 colour index from RGB value found at : https://unix.stackexchange.com/questions/269077/ """ if red > 255: red = 255 if green > 255: green = 255 if blue > 255: blue = 255 if red < 75: red = 0...
6d896f557d5903708f5072d1a875313633cea6b4
3,609,906
def first_or_default(iterable, predicate=None, default=None): """First the first value matching a perdicate otherwise a default value. :param iterable: The items over which to iterate. :param predicate: A predicate to apply to each item. :param default: The value to return if no item matches. :retu...
94ee1c97cc752b1f5bb0ac4cc7c3a6a8f3fe4675
3,609,907
import copy import itertools def bin_bp_sparse(M, positions, bin_len=10000): """ Perform binning with a fixed genomic length in base pairs on a sparse matrix. Fragments will be binned such that their total length is closest to the specified input. If a contig list is specified, binning will be per...
1f69207692944dffd0dddab00cc2860a72416590
3,609,908
def process_date(date): """ Returns a dictionary with all of the below processes completed, which can then be imported directly to CalendarDate model. """ metadata = {} metadata["calendar_date"] = date metadata["calendar_day"] = get_calendar_day(date) metadata["calendar_month"] = get_ca...
2191030e2e45df679b87c6794739eb95e955e552
3,609,909
def image_md(image_location, caption="", link=None, tooltip=""): """ Returns the html code for the individual plot """ image = f""" <a href="{link}" name="gallery-href"> <img src="{image_location}" name="gallery-image" alt="{tooltip}" style="width:100%" id="{"".join(image_location.split("-...
3e847459f14d8cfd2c66bed633640bbbb0442321
3,609,910
import msgpack def unpacker(*args, **kwargs): """Return a MessagePack (with extended types support) Unpacker object.""" return msgpack.Unpacker(*args, ext_hook=_decode_ext_type, raw=False, **kwargs)
ac216bb6a45546a8a4ae620d1dad4345f08b72e3
3,609,911
import os def clean_directory(directory, patterns=None): """Clean up all generated files from other commands.""" if not patterns: patterns = [ 'dist', 'build', '.tox', '*.egg-info', '*.egg', 'wheelhouse', '__pycache__'...
fd02f13200b1773a056b30aee34269e544417b34
3,609,912
def water_budget(ds, dim='p'): """Compute water budget if Q2NN is present""" q2_int = (ds.Q2NN * ds.layer_mass).sum(dim) * 86400 q2_ib = q2_int prec = ds.Prec evap = lhf_to_evap(ds.LHF) return xr.Dataset( dict(Prec=prec, evap=evap, Q2=q2_ib, imbalance=q2_ib - (evap - prec)))
12f96fe74a1cc37c41d4186e991815566b8d826a
3,609,913
def atSendCmdGetOptionInfo(market, code): """ 获取期权信息 :param market: str 市场类型 :param code: str 标的代码 :return: Dotdict 期权信息 :: TODO 期权接口 ... """ func_name = 'atSendCmdGetOptionInfo' atserial.ATraderGetOptionInfo_send(market, code) res = recv_serial(func_name) return re...
9222c77dcb916ebff1301bc146aefcf9d4c00cec
3,609,914
def get_split_discordants(data, work_dir): """Retrieve full, split and discordant reads, potentially calculating with samblaster as needed. """ dedup_bam, sr_bam, disc_bam = _find_existing_inputs(data["align_bam"]) if not dedup_bam: dedup_bam, sr_bam, disc_bam = _extract_split_and_discordants(da...
d601fb8ffd41de8247c77ac3b8256810c9276c34
3,609,915
def fuzzy_or(args): """ Or in fuzzy logic. Returns True (any True), False (all False), or None See the docstrings of fuzzy_and and fuzzy_not for more info. fuzzy_or is related to the two by the standard De Morgan's law. >>> from sympy.core.logic import fuzzy_or >>> fuzzy_or([True, False]) ...
4dac12016b95d3713590bd547aeb2d182de7f02e
3,609,916
def data_context_path_computation_context_path_comp_serviceuuid_routing_constraint_cost_characteristiccost_name_delete(uuid, cost_name): # noqa: E501 """data_context_path_computation_context_path_comp_serviceuuid_routing_constraint_cost_characteristiccost_name_delete removes tapi.topology.CostCharacteristic #...
fbfe8be9fcc7f3f96fc502b2d279bef6db292abb
3,609,917
def save_integrator(key_name): """ save the integrator if its explicit Parameters --------- key_name """ RK=loadRKM(key_name) if(RK.is_explicit()): print("Saving "+RK.name+" to file "+str(key_name)+".npz" + " and file "+str(key_name)+".mat") # an integrator tablaeu ex...
e43f7ae42e1f3cdf4c0211cb1dac3deed04bccb9
3,609,918
def get_variables_path(export_dir): """Return the variables path, used as the prefix for checkpoint files.""" return file_io.join( compat.as_text(get_variables_dir(export_dir)), compat.as_text(constants.VARIABLES_FILENAME))
fb3248a99a8a48522c60aa24ac0a58ed1fd4de93
3,609,919
def parse_single_geo_arg(key: str) -> GeoPair: """ parses a single geo pair with only one value """ r = _parse_single_arg(key) return GeoPair(r[0], [r[1]])
fbf9d7a0589881af1cd5a3303fc4ecdf6f5d90a2
3,609,920
from bs4 import BeautifulSoup import re def check_currency(response: str) -> dict: """Check whether the results have currency conversion Args: response: Search query Result Returns: dict: Consists of currency names and values """ soup = BeautifulSoup(response, 'html.parser') ...
679b656e6565fcbdc3011ec9164e57baa6d650f4
3,609,921
from datetime import datetime import math def calculate_mean_anniversary(days_of_interest: list): """The function calculate_mean_anniversary calculates the mean anniversary based on a geometric approach. The mean anniversary is valid for the current year. The list of dates are given as string in the format yy...
431dde8178bed5efb7a5c3967451c7d7fdaa62c2
3,609,922
def fix_models_py(models_py): """ The output of inspectdb is pretty messy, so here we trim down some of the mess, add mandatory ID field and fix the bad conversion to CharField (we use TextField instead). """ lines = models_py.split("\n") fixed_lines = [] for line in lines: # Pos...
428cce3315a2e47d44e35889e0cccd7d840794aa
3,609,923
def _can_extract_intrinsics_to_top_level_lambda(comp, uri): """Tests if the intrinsic for the given `uri` can be extracted. Args: comp: The `tff.framework.Lambda` to test. The names of lambda parameters and block variables in `comp` must be unique. uri: A Python `list` of URI of intrinsics. Return...
99c7f5bb15e11127cc2cbcc82e658722bcc1a9cf
3,609,924
def primitiveValueFrom(interp, s_frame, w_cls, w_obj): """ Creates a value of a given Smalltalk object by copying. :param interp: The interpreter proxy. :param s_frame: The stack frame. :param w_cls: The imutable objects target class. :param w_obj: The Smalltalk object to produce an immutable c...
6d2cdb407b833d540b55d4b45725eb46116b43c1
3,609,925
def entertainment(): """ show entertainment posts """ entertainment = Post.query.filter_by(category="Entertainment").all() return render_template('entertainment.html', post=entertainment)
4759986bfa0f1522983454f4cec4069b7424de8c
3,609,926
def _GetDesiredVsToolchainHashes(version): """Load a list of SHA1s corresponding to the toolchains that we want installed to build with.""" if version == '2015': # Update 3 final with 10.0.15063.468 SDK and no vctip.exe. return ['f53e4598951162bad6330f7a167486c7ae5db1e5'] if version == '2017': # VS ...
72ee6a64e6e68e62d705cde7b847a5dad7f6fff2
3,609,927
def allsum(my_a, axis=None, dtype=None, out=None, comm=MPI.COMM_WORLD): """ Parallel (collective) version of numpy.sum """ my_sum = np.sum(my_a, axis, dtype) if my_sum is np.ndarray: sum = np.empty_like(my_sum) comm.Allreduce( (my_sum, typemap[my_sum.dtype]), (sum, typemap[sum.dtype])) ...
25da66cf2e9c12f2b2c589811625333b3bf8e9be
3,609,928
def sum_of_years_digits(year): """Calculate the sum of years' digits. Arguments: year (``int``): The year to calculate up to. Returns: int: The sum of years' digits. """ if year <= 0: return 0 return year + sum_of_years_digits(year-1)
aa3d67cde4af6c8565ef6fdcd8becb0cb3b1fa95
3,609,929
import subprocess def resolve_ref(repo_url, ref): """ Return resolved commit hash for branch / tag. Return ref unmodified if branch / tag isn't found Notes ----- Author: Yuvi Panda Copied from https://github.com/yuvipanda/repo2charliecloud/blob/ 44a508b632e801d3b1f0dd1360e...
4def5ab1e791ab0d3179418070580a11ac82f75f
3,609,930
def codes_code_id_codes_get(code_id, sab=None): # noqa: E501 """Returns a list of {Concept, Code, Sab} associated with the code_id optionally restricted to SAB # noqa: E501 :param code_id: The code identifier :type code_id: str :param sab: One or more SABs to search :type sab: List[str] ...
eec7fb87f6050783651b62ce4552c11c99550af4
3,609,931
import sys import os def getAbsoluteResourcePath(relativePath): """ Load relative path, in an environment agnostic way""" try: # PyInstaller stores data files in a tmp folder refered to as _MEIPASS basePath = sys._MEIPASS except Exception: # If not running as a PyInstaller created...
91df287c85f68d2ce3976b70618c6e3d42cf50b0
3,609,932
def plot_data_with_anomalies(data, anomalies, as_var=False): """ Plot the data and add anomalies as line on the graph :argument data: dataframe (same as above) :argument anomalies: DatetimeIndex of dates (corresponding to anomalies) - dtype=datetime64[ns] """ fig, ax = plt.subplots(1, 1, figsize=(2...
014732f883f25460b692bd03d6ee3dcf7ef4f51e
3,609,933
def density_supercooled_water(T): """D. E. Hare and C. M. Sorensen: Density of supercooled water 1987 JChemPhys valid between -33.4 to -5/+10 Args: T: in [K] """ a = [0.99986, 6.690e-5, -8.486e-6, 1.518e-7, -6.9484e-9, -3.6449e-10, -7.497e-12] t = T-T0 rho = a[0] + a[1]...
9a368a5905a298595e7b0d5ecd60486ee1a07c7b
3,609,934
def repel_from_near(lerp_point, drone_num, course, radius=1.0): """ Отталкиваемся от дронов если они возши в заданный радиус :param name: :param list: :return: """ repel = [0.0, 0.0, 0.0] for i in range(len(drone_offset_list)): if drone_offset_list[i][0] != drone_offset_list[dro...
ef2162d5b0612aa0feacbe0b1aae9a4c333fbdb8
3,609,935
def get_values(): """ Retrieves two values to multiply """ user_values = input("On the next line, enter the values to multiply,\ separated by commas. \n>> ") input_list = user_values.split(",") final_list = [] #We've split the user's input into a list, but have no idea if it's any good. ...
ea0fb353d61514e67970d673bbe9fb45a9b20123
3,609,936
def spikes(templates, min_amplitude, max_amplitude, n_per_template, spatial_sig, temporal_sig, make_from_templates=True, make_spatially_misaligned=True, make_temporally_misaligned=True, make_collided=True, make_noise=True, return_metadata=True...
f26dcfa6841cd70265be23e25ab9bad68eccb207
3,609,937
def merge_close_peaks(peaks, minimum_distance): """Merge peaks that are too close to each-other vertically. Peaks that fall within the dilation mask are spurious and likely not peaks we want. When two peaks fall below the minimum distance, the smallest one will be discarded. Parameters: ----------...
3b97f8b652550348f944ffd7451a77d4c8dec4f3
3,609,938
def LruCache(maxsize=None): """LRU Cache decorator. Args: maxsize: the maximum cache size, or None for unlimited size. """ def wrapper(fn): return functools32.lru_cache(maxsize=maxsize)(fn) return wrapper
f1182f575a9145ddbf95b29ff3d746ccbe88adc4
3,609,939
import time import shutil import os import json import base64 from bibtexparser.bparser import BibTexParser from pyinspire import pyinspire import urllib def inspire_search(search=""): """Searches Inspire.""" # Path for the temporary bibtex results. tempf = os.path.join(alp.cache(),"results.bib") # ...
fe5620deeca434502f8c7be9f46e2a88c0171de3
3,609,940
def parse_inputs(): """ Parser function to take care of the inputs """ parser = ArgumentParser(description='Argument: python data_preprocess.py <data_direction> <output_annotation_path> <test_ratio>') parser.add_argument('data_dir', type=str, help='Enter path to data direction.') ...
fb7d67a358eef6703dc0c5c4c12514c1c78a6371
3,609,941
from typing import List def concretise_config( config: StrConfig, available_domains: List[Domain] ) -> ObjConfig: """Dereference configuration.""" domain = find_by_repr(available_domains, config.domain) categories = list(gather_categories(domain.tools).keys()) loaders = [find_by_repr(domain.tools ...
1504e4eb650af10eb220315517e909508583859a
3,609,942
def nextDay(year, month, day): """计算指定日期的下一天(假设给定的日期合法)""" if day < daysInMonth(year, month): return year, month, day + 1 else: if month == 12: return year + 1, 1, 1 else: return year, month + 1, 1
7e7c46a88529777694555e71b3d116bd3f46b944
3,609,943
import time def runTestCasesWithInput(test_cases, test_input, yaml_reporter, oonib_reporter=None): """ Runs in parallel all the test methods that are inside of the specified test case. Reporting happens every time a Test Method has concluded running. Once all the test methods have been called ...
88e300a8ff6fdea59c9c6ac809e70c3681000ab1
3,609,944
def load_david_worksheet(fname='fMRI MA significance bias database 03-24-13.xlsx', verbose=False): """load the David et al. data from excel workbook and return ID and sample size""" workbook = xlrd.open_workbook(fname) sheet=workbook.sheet_by_name('Original Sheet') studies={} all_ids=[] ...
19de3c07084450709b3a764c9c8b29f6d3353313
3,609,945
import mmap def file_lines(dictionary_file): """ Counts the number of lines of the given file. Parameters ------- dictionary_file: file The text file Returns ------- int The number of lines of the given file """ buf = mmap(dictionary_file.fileno(), 0) line...
f74de1cddb1e8c022dac06e70ac6df4d3e597cb1
3,609,946
def is_holiday(date): """ check if one date is holiday in China. in other words, Chinese people get rest at that day. :type date: datetime.date | datetime.datetime :rtype: bool """ return not is_workday(date)
d7b4ee9b48216e8d07674eb699f05a3f7fd76029
3,609,947
def read_dataset_and_unit_h5(h5, expected_unit=None, convert=True): """ Reads a dataset that has openPMD unit attributes. expected_unit can be a pmd_unit object, or a known unit str. Examples: 'kg', 'J', 'eV' If expected_unit is given, will check that the units are compatible. If conv...
4f7d562db53c5a793a8c1a3569789596425a515a
3,609,948
def make_sparse_convmodule(in_channels, out_channels, kernel_size, indice_key, stride=1, padding=0, conv_type='SubMConv3d', norm_cf...
29c797f6be6d2830cb9a309b4a105d3fa4ad04c2
3,609,949
def get_zcoeffs(csv, imfreq): """ Given the input frequency of the image, returns the Pandas dataframe with the coefficients corresponding to the input frequency. The frequencies in the input CSV file are expected to be in MHz. Inputs: csv Input CSV filename, string imfreq Imag...
d7f60cfdd4249e98e1991b98f5f508e1aa409c60
3,609,950
import signal def test_func(s, sr, maximum_duration=30, minimum_duration=None, frame_length=256, nb_mixtures=3, threshold=0.3, return_vad=False, return_voices=False, return_cut=False): """ Splitting an audio based on VAD indicator. * The audio is segmented into multiple with length...
3fdd345aa7f465b9501c2cd7e04464d48d0a0cde
3,609,951
import torch from typing import Union def _find_layer(model: torch.nn.Module, target_layer: Union[str, torch.nn.Module]) -> torch.nn.Module: """Find the specified layer in a model. Args: model: a neural network model as a PyTorch Module. target_layer: the target layer in the m...
0d102625102333eb4bd617f14753f1eb46ef6c9d
3,609,952
from typing import Optional def article(topic: str, article_date: str, title_slug: str) -> tuple: """ **article** :param topic: :param article_date: :param title_slug :return: """ link_slug: str = f'{topic}/{article_date}/{title_slug}' article_data: Optional[dict] = Articles....
911f7be750560263671c3636e70cc1eeb3fc58b7
3,609,953
def parse_simple_expression_list(l): """ This parses a comma-separated list of simple_expressions, and returns a list of strings. It requires at least one simple_expression be present. """ rv = [ l.require(l.simple_expression) ] while True: if not l.match(','): break ...
8c3772e1bd4cc9587c8095dcba640878c01fc0f4
3,609,954
def collect_ibkr_listings(exchanges=None, sec_types=None, currencies=None, symbols=None, universes=None, sids=None): """ Collect securities listings from Interactive Brokers and store in securities master database. Specify an exchange (optionally filtering by security type, cu...
2bf05d1e15de4b64fcdaf0270afacab906527841
3,609,955
def largest_indices(x, K): """Returns the indices of K largest entries in x by magnitude Args: x (jax.numpy.ndarray): An data vector/point K (int): The number of largest entries to be identified in x Returns: (jax.numpy.ndarray): An index vector of size K identifying the K largest ...
1ff43b2142abf97946a080fd292d340b37aa8150
3,609,956
from typing import Iterable from typing import Any from typing import List import itertools def flatten(val: Iterable[Iterable[Any]]) -> List[Any]: """ Flatens a list of list into a list >>> flatten( [['abc','def'],[12,34,46],[3.14, 2.22]]) ['abc', 'def', 12, 34, 46, 3.14, 2.22] """ return li...
cd9ae9e393569ba7800735d09c8621f0d64beed3
3,609,957
def surprisal_graph(transition_matrix, states=None, symmetrized=True, stationary_distribution=None): """Return the surprisal graph of a discrete-time Markov chain. Parameters ---------- transition_matrix : (N, N) array_like Transition matrix of a discrete-time Markov chain. Must be a s...
215529a140e80f080cf8a9e69c56826ebb0803fa
3,609,958
def get_output_list(file_row): """Return list of dict for output file""" data = [] list_mammo = get_row_nr(file_row, 'mammo_params') list_us = get_row_nr(file_row, 'us_params') list_mri = get_row_nr(file_row, 'mri_params') all_params = list_mammo + list_us + list_mri for x in range(len(all_p...
c431f6660c65f6ab54bbc4cdf9c50a6d7b93d062
3,609,959
import io import csv def to_csv(members): """Convert JSON data structure to CSV string.""" with io.StringIO() as fp: cw = csv.writer(fp) if len(members): cw.writerow(members[0].keys()) for member in members: cw.writerow(member.values()) value = fp.getval...
0ed85a10417dee1ca98a28e05e1ae2d24dcebfe0
3,609,960
import math def plot_location(latitude, longitude, bearing, distance): """Plot a new location based on starting point, bearing and distance""" bearing_rad = math.radians(bearing) lat1 = math.radians(latitude) lon1 = math.radians(longitude) d_over_r = distance / EARTH_RADIUS lat2 = math.asin...
64e4bd1d1102e4df77ad60c473eee6558f942896
3,609,961
import ipdb import subprocess def get_text_from_html(x): """ """ output = '' try: ps = subprocess.Popen(('echo', x), stdout=subprocess.PIPE) output = subprocess.check_output(('lynx', '--dump', '--stdin'), stdin=ps.stdout) ps.wait() except: pass ipdb.set_trace(...
ceafb1d1d312c23c00f31ccb407f4af7be4237c0
3,609,962
def num_sources(): """Get the number of sources.""" return len({s for s in SourceName})
5539a871717dda34e4cb08f62d07e592d3f2c2f4
3,609,963
def _get_panelargs( side, share=None, width=None, space=None, filled=False, figure=False ): """ Return default properties for new axes and figure panels. """ if side not in ('left', 'right', 'bottom', 'top'): raise ValueError(f'Invalid panel location {side!r}.') space = space_user = ...
0273f7e439e02ed1c8afd98d011395d30bca34f3
3,609,964
def relu(x): """ REctified Linear Unit: y = x if x >= 0; y = 0 if x < 0; :param owl.NArray x: input :return: result ndarray :rtype: owl.NArray """ return _owl.NArray.relu(x)
81459cb70817ce9d658823bbd68165dbc55fe6ad
3,609,965
def find_max_treatment_effect_phenotype(g, zeta_probs, factual_outcomes): """ Find the group with the maximum treatement effect phenotype """ mean_differential_survival = np.zeros(zeta_probs.shape[1]) # Area under treatment phenotype group outcomes_train, interventions_train = factual_outcomes ...
0e6c014002d717355f4c9c1da020a2f8312142fc
3,609,966
def make_random_image(filename=None, dims=(10, 10, 10), xform=None, imgtype=1, pixdims=None, dtype=np.float32): """Convenience function which makes an image containing random data. Saves and returns the...
d66b757c90e9f26f0d3ca6248ca28e578cb80f4c
3,609,967
from tocode.__inner_files__._gen import __code_gen_list__ import sys import traceback def literal_eval(str_list: str, no_string_quotation: bool = False): """ the list parser will convert list in string to the list and there is an option available `no_string_quotation` if you string contains the needed...
e4e0031ae743053221d87861a797ae1d4b1421a6
3,609,968
from typing import Any import re def _check_lat_or_long(val: Any, clean: bool, hor_dir: str) -> Any: """ Function to check if a coordinate instance is valid """ # pylint: disable=too-many-boolean-expressions if val in NULL_VALUES: return (None,) * 4 + (0,) if clean else False pat = LA...
e34a44b562c25ec9dca06136966b24ba30de0321
3,609,969
def integrate(avg_daily_sentiment, interval): """ Takes a list of average daily sentiment scores and returns a list of definite integral estimations calculated with Simpson's method. Each integral interval is determined by the `interval` variable. Shows accumulated sentiment. """ # Split into sliding window list ...
37c36c7a23e7af83cb43789d6401bad01c7ae89c
3,609,970
def split_sentences(inp_text, nlp_model): """ Splits an input string into sentence determined by spacy model :param inp_text: string with input text :param nlp_model: sciSpacy model :return: list of sentences in string format """ doc = nlp_model(inp_text) sentences_list = [sentence.text ...
b5617d9334509edf09bf4a0360d3030e67ddf800
3,609,971
def _get_rotation_indices_gl(self, linkages): """ Precompute indices that are then used to rotate along the i-j axis only the proper portion of the coordinates array. Works only for glycans. Returns rotation_indices : dict of dict of tuples dictionary of residue numbers, dicctiona...
490bcae9dbc8ed74469a7c2aa68566c76e6fdd7c
3,609,972
from typing import Sequence import logging import re def date_from_str(text: str) -> Sequence[str]: """Get the date tuple (year, month) from the text string.""" logger = logging.getLogger('date_from_str') # No leading digit, then 1 or 2 followed by 3 digits (for years 1ddd and # 2ddd), then any of -:...
dbcf6b7dbf302f4b0c3b3a523d5feac54a30d3e7
3,609,973
from typing import Dict from typing import List import collections def get_nodes_for(node_types: Dict[NodeType, NodeTypeConfigDict], existing_nodes: Dict[NodeType, int], head_node_type: NodeType, max_to_add: int, resources: List[ResourceDict], ...
24b8a020066bbc185f9dffaddb155d9f7384d44d
3,609,974
def _point(x,index=0): """Convert tuple to a dxf point""" return '\n'.join([' %s\n%s'%((i+1)*10+index,float(x[i])) for i in range(len(x))])
b5d2b3345b53bf2bd5e7fb93ee57fa9eb2a599b9
3,609,975
import socket def myip() -> str: """returns a string with the computers default IP address """ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) ip = s.getsockname()[0] s.close() return ip
c30a433cc49c4d58a209ded2d00578a11667372c
3,609,976
import timeit import json def edit(token, action_type): """ Edit the labeling of the project and update the project in the database. """ start = timeit.default_timer() # obtain 'info' parameter data sent by .js script info = {k: json.loads(v) for k, v in request.values.to_dict().items()} ...
a61e73ce2969b0dc1df6cbfd97efaa06f4999ec0
3,609,977
def not_empty(message=None) -> Filter_T: """ 验证输入不为空。 返回: nonebot.typing.Filter_T: """ def validate(value): if value is None: _raise_failure(message) if hasattr(value, '__len__') and value.__len__() == 0: _raise_failure(message) return va...
26b09dc50fd9f5eb5bc5ecde424cdfcda78b34d6
3,609,978
def get_video_dimensions(lines): """Has it's own function to be easier to test.""" def get_width_height(video_type, line): dim_col = line.split(", ")[3] if video_type != "h264": dim_col = dim_col.split(" ")[0] return map(int, dim_col.split("x")) width, height = None, No...
7df1dbc3e190908852684735bc1242db4e3c456b
3,609,979
def factorial(x): """ The factorial_ (denoted :math:`n!`) is the product of all positive integers less than or equal to a positive integer (:math:`n`). .. _factorial: https://en.wikipedia.org/wiki/Factorial Equation: .. math:: n! = \\prod_{k=1}^n k Args: x: A numer...
dc9a064d957dbd90b6fc05008eff8166306b271a
3,609,980
def __get_database_filepath(config: ChiaTeaConfig) -> str: """Get the database filepath from the config Parameters --------- config : ChiaTeaConfig config to read filepath for cert and key Returns ------- db_filepath : str path where the database is or will be stored ""...
74648a989c7783aca82bd1d74a6b3ad29e23a983
3,609,981
import torch from typing import Iterable def brownian_bridge(n_step, sample_shape=()) -> torch.Tensor: """ :param n_step: first and last steps are 0 and 1 :param sample_shape: :return: b[step, sample_shape] """ assert n_step >= 2 if not isinstance(sample_shape, Iterable): sample_s...
e71c8e011fe0fc352b053aee39d74b5572740291
3,609,982
def expand_ambiguous_dna(seq): """return list of all possible sequences given an ambiguous DNA input""" d = IUPAC.IUPACData.ambiguous_dna_values return tuple(map("".join, product(*map(d.get, seq))))
f420d2ceeb33ba28a7fb73f276744aa313716cfa
3,609,983
def _check_selection(selection): """Handle default and validation of selection""" available = ["counts", "exposure", "background"] if selection is None: selection = available if not isinstance(selection, list): raise TypeError("Selection must be a list of str") for name in selecti...
454b36833a5117b2d1bab377094e8e3ec0c06969
3,609,984
def read_wgs(filename, wgsname=None, boun_cond=None): """ read a LaWGS file and create a LaWGS object :param filename: filename of the LaWGS file :param wgsname: "name" for the LaWGS object :param boun_cond: a tuple containing the boundary conditions of each network :return: LaWGS object """ ...
03e0bf906a5e8c59f911d08fbae670170f75ecde
3,609,985
def calculate_v6_Psi2(chi_6222, chi_6222_err, vn_array): """ v6(Psi2) = chi_6222*sqrt(<abs(V2)**6>) """ dN = real(vn_array[:, 0]) Q2 = dN*vn_array[:, 2] Q4 = dN*vn_array[:, 4] Q6 = dN*vn_array[:, 6] nev = len(dN) N6_weight = dN*(dN - 1.)*(dN - 2.)*(dN - 3.)*(dN - 4.)*(dN - 5.) ...
9de98855b5ea991e0315897a6ed51028fe93ae5a
3,609,986
def shallTreatUninstalledPython(): """*bool* = derived from Python installation and modes Notes: Not done for standalone mode obviously. The Python DLL will be a dependency of the executable and treated that way. Also not done for extension modules, they are loaded with a Pytho...
a0ea3da4822448452b9d2965e5c885f071381d73
3,609,987
def force(value): """ This helper function forces evaluation of a promise. A promise for this function is something that has a __force__ method (much like an iterator in python is anything that has a __iter__ method). """ f = getattr(value, '__force__', None) return f() if f else value
eccdbfe927eeac54246ac777ed16864a7da38ca7
3,609,988
def _parse_cpu(spec: SpecType) -> ConstraintBase: """ Parse a cpu-related constraints. :param spec: raw constraint block specification. :returns: block representation as :py:class:`ConstraintBase` or one of its subclasses. """ group = And() group.constraints += [ Constraint.from_s...
bd2756e6bef761ff4654d4bb949c72df90dd88ec
3,609,989
def rect(pos: tuple[int, int], size: tuple[int, int], char: str="█", color: Color="white") -> str: """Generate a rectangle.""" return shape( pos, (size[0] - 4, size[1] - 1), sets.CharSet({"corner": char, "horiz": char, "vert": char}), sets.ColorSet({"corner": color, "horiz": color, "vert": color}).parsedVa...
ab550c8a25a1ecd0c389a15d091aa5e5b88b144e
3,609,990
def compton_scatter(photon, compton_angle): """ Changes the direction of the gamma-ray by the Compton scattering angle Parameters ---------- photon : GXPhoton object compton_angle : float Returns ------- float64 Photon theta direction float64 Photon phi directio...
93145d30d7dee81bcfbf3506c7a7a9cc245ef074
3,609,991
from scipy import sparse from scipy import sparse import os def get_flatcache(subject, xfmname, pixelwise=True, thick=32, sampler='nearest', recache=False, height=1024, depth=0.5): """ Parameters ---------- subject : str Subject name in pycortex db xfmname : str ...
8580f78a0fb978249ee98fd5f3334f36fccb70c0
3,609,992
def sumIterable38(iterable): """Full precision summation using multiple floats for intermediate values. Code modified from msum() at code.activestate.com/recipes/393090/, which is licensed under the PSF License. Processes arguments as python3.8+ math module. Original comment below. """ # Rou...
de663242439b724a3b930276cea9f4c2919f182a
3,609,993
def transformBoxInvert_batch(pt, ul, br, inpH, inpW, resH, resW): """ pt: [n, 17, 2] ul: [n, 2] br: [n, 2] """ num_pt = pt.shape[1] center = (br - 1 - ul) / 2 size = br - ul size[:, 0] *= (inpH / inpW) lenH, _ = paddle.max(size, axis=1) # [n,] lenW = lenH * (i...
1b6fa2f6b45ab67840e837212bdcdd5d8308ad79
3,609,994
def get_trading_status(local_client, local_figi): """ Проверка доступности инструмента для трейдинга см. https://tinkoff.github.io/investAPI/marketdata/#securitytradingstatus :return """ stat_ok = 'SecurityTradingStatus.SECURITY_TRADING_STATUS_NORMAL_TRADING' stat_not = 'SecurityTradingStat...
9898cc81d87fdb91678c1d15cd3342a4e8335601
3,609,995
from typing import List from typing import Tuple def compare_key(local_key: str, platform_keys: List[Tuple[str, str]]) -> bool: """Compare Key with fingerprint Args: local_key (str): local GPG Key ID platform_keys (List[Tuple[str, str]]): Platform GPG Key IDs Returns: bool: Local...
23b154f14d5b524044c7aabbe77b7eeb9b758c0f
3,609,996
import base64 def decode_payer(enc): """ Декодирование пользователя-инициатора платежа """ try: secret = base64.decodestring(enc.encode('utf-8')) pk = decrypt(settings.SECRET_KEY, secret) return get_user_model().objects.get(pk=pk) except DecryptionException: logger.warn(u'...
4ccd754d4a9499b5ca41049bd9aa7900b3fb0bab
3,609,997
def _format_row_with_out_of_dateness(readout_locale, eng_slug, eng_title, slug, title, visits, significance, needs_review): """Format a row for a readout that has the traffic-light-style categorization of how seriously out of date a trans...
ad1efb9edb9552aaf4c08c8575b45e8e6914fb14
3,609,998
async def get_player_count(conn : asyncpg.Connection): """Return an integer of the amount of players in the database.""" psql = """ SELECT COUNT(*) FROM players; """ return await conn.fetchval(psql)
3dc031bc295b4b0c3886171cefba179d4f7db115
3,609,999