content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Optional from typing import List def get_plugins( user_id : Optional[int] = None, search_term : Optional[str] = None, ) -> List[str]: """ Return a list of registered plugins. """ return get_api_connector().get_plugins(user_id=user_id, search_term=search_term)
da314ee59182360461e86ad19f76d89165a4c132
38,700
def get_tile_rect(x, y): """Converts tile indices to a pygame.Rect""" return Rect(x*SIZE, y*SIZE, SIZE, SIZE)
70b9b514037fa5916bbccd771766bc20d693a438
38,701
from scipy.spatial import Delaunay def checkBlockageQHull(plane1,plane2,planeB,nargout=1): """ Using ConvexHull. This is slower, but worth having as it's more intuitive. We can use this to have a third opinion. Check wheter plane1 and plane2 are blocked by planeB. plane1, plane2, planeB are...
ea8b20d16baf3bc62701e7c4322967326f03dedf
38,702
def getLinks(laneID): """getLinks(string) -> list((string, bool, bool, bool)) A list containing ids of successor lanes together with priority, open and foe. """ return _getUniversal(tc.LANE_LINKS, laneID)
9066791739da9ad7b869fabb99f08a0551c3e13a
38,703
from typing import Tuple def calc_center_position(pos: Tuple[int, int]): """ ボックスの中央の座標を取得する Parameters ---------- pos : (int,int) ボックスの座標(左上を原点とし、(横、縦)する) Returns ------- position : (int,int) ボックスの中央の座標 """ box_size = calc_box_size(row, column) pos_x, pos...
7127a9063b451aedd206e8e4c2f65b2ed762db71
38,704
def ws_sheet_names(xlsx_file, log_on_open=True): """Return the sheet names in the XLSX file.""" if log_on_open: log('SCAN: [!c]{:s}[!/c]', xlsx_file) with closing(load_ro_workbook(xlsx_file)) as wb: return [str(i) for i in wb.sheetnames]
39e97f0bc170acb9f30f669afc3a2a939a2554d2
38,705
def process_citeauthor( s: str, lang: str, **kwargs ) -> str: """ Transforms all citeauthor to [cite]. For example: ``'This is from \citeauthor{Pizarro}, and that is from \citeauthor{cite1, cite2}'`` to ``'This is from [author], and that is from [authors]'``. :param s: Latex...
2622e2b2d8e59a34f4dbd1d1968eb7bd4a181871
38,706
import re def normalize_newlines(text): """Normalizes CRLF and CR newlines to just LF.""" # text = force_text(text) re_newlines = re.compile(r'\r\n|\r') # Used in normalize_newlines return re_newlines.sub('\n', text)
835f038f0873546db96d8e9d2a0d622b4e974f7d
38,707
def power_curve_se_42m140(): """Power curve for Senvion 4.2M140 Extracted by hand from offial spec-sheet at: https://www.senvion.com/global/en/products-services/wind-turbines/4xm/ """ wind_speeds = np.hstack(([0., 1., 2., 3.], np.arange(4, 27, step=2), [27., 40.])) generation_kw = [0., 0., 0., 0...
40c1823242c4f2f2fbd3c50c0b2e6b9cae926c09
38,708
import json import os import importlib def load_service(config_path, base_config=None): """Loads a service configuration. Args: config_path: Path the service configuration to load. base_config: The shared configuration to include in this service. Returns: name: The service name s...
77cbf733ddb0c0ea6660b04154e12a30085e27ed
38,709
def close_ring(coordinates): """ checks if the first and last points of a ring are equal and closes the ring """ if not points_equal(coordinates[0], coordinates[len(coordinates) - 1]): coordinates.append(coordinates[0]) return coordinates
14d121dc25dd774f326845b3c83d2d605d1d69d2
38,710
def check_families(trace_events, families, event_definitions): """ Looks for event types found in the trace that are not specified in the event definitions. :param trace_events: Events found in the trace (filtered by family). :param families: Families to look for. :param event_definitions: Even...
2533835283d388ad2fe37d79f6e87f14103a5bee
38,711
def broken_search(nums, target): """ Функция должна вернуть индекс элемента, равного k Eсли такой есть в массиве (нумерация с нуля). Если элемент не найден, функция должна вернуть -1 Изменять массив нельзя. """ return binary_s(nums, target, left=0, right=len(nums)-1)
f427cad35db6ea641e33d26054e64aec9721a462
38,712
def str_to_timedelta(td_str): """ Returns a timedelta parsed from the native string output of a timedelta. Timedelta displays in the format ``X day(s), H:MM:SS.ffffff`` Both the days section and the microseconds section are optional and ``days`` is singular in cases where there is only one day. ...
dc86def0716afda5e1e4808281275ed2e9514ace
38,713
import os import requests def download_file(url, download_dir, path=None, clobber=False): """ thanks to: https://stackoverflow.com/questions/16694907/how-to-download-large-file-in-python-with-requests-py path : str local path to download to. """ if path is None: local_filename = os...
1290a9b87cad2b6278f36b157cae9dd1d2a8a272
38,714
def get_distribution_strategy(): """Returns the current `DistributionStrategy` object. Prefer to use `get_tower_context()` or `get_cross_tower_context()` instead when possible. Returns: A `DistributionStrategy` object. Inside a `with distribution_strategy.scope()` block, it returns `distribution_s...
4a20795c098c6b7ad8e7e1f6f42fead24c55e771
38,715
def exists_project_slug(slug): """ Whether the slug has been taken by an existing project of any kind. """ return bool(ActiveProject.objects.filter(slug=slug) or ArchivedProject.objects.filter(slug=slug) or PublishedProject.objects.filter(slug=slug))
ce2baf58cab1227b9a1a480c1fed0c2ba8da235f
38,716
import logging def main(args): """ Main entry point for program :param args: :return: """ desc = """ Version {version} Annotates NDEx with INDRA and optionally loads networks into NDEx (http://ndexbio.org). To connect to NDEx server a configuration file must be passed ...
243d65d41f92615bd87a41db52097b7873193099
38,717
import os def coupling_rate(): """Return fraction of women by age who will form a couple that year.""" path_marriage = os.path.join(INPUT_DIR, 'ONS/cohabitationandcohortanalyses11.xls') path_births = os.path.join(INPUT_DIR, 'ONS/birthsbyparentscharacteristics2014final.xls') n_female = n_age_sex().valu...
e8561f0a2289cbd51dab4d4831a3a6854a561a65
38,718
def merge_dupes(list_cxs, cutoff, func=cp.bader_score, npasses=1): """ cxs: list of sets Requires multiple passes to be more certain of fewer complex pairs passing the merge threshold. But higher passes results in overcollapse when cutoff < 1. """ cxs = list(list_cxs) cxs_remaining = lis...
e397ccfa2715882ab200be5a66767197b9e8eb97
38,719
import re def convertSQL_LIKE2REGEXP(sql_like_pattern): """Convert a standard SQL LIKE pattern to a REGEXP pattern. Function that transforms a SQL LIKE pattern to a supported python regexp. Returns a python regular expression (i.e. regexp). sql_like_pattern[in] pattern in the SQL LIKE form to be con...
16589a99327885dc034fb33af1e69a42a453ccbd
38,720
from typing import Any def diag(tensor: ChargeArray) -> Any: """ Return a diagonal `BlockSparseTensor` from a `ChargeArray`, or return the diagonal of a `BlockSparseTensor` as a `ChargeArray`. For input of type `BlockSparseTensor`: The full diagonal is obtained from finding the diagonal blocks of the ...
996cea2164d867fa67812fac8f156d4851eaaf6e
38,721
def _setup(app): """Hooks for actions performed before each request. """ if settings.ROLLBAR_API_KEY: @app.before_first_request def init_rollbar(): # pylint: disable=unused-variable """If rollbar is not installed but ROLLBAR_API_KEY is set, there will be an exception...
50ded12be19dd9f97b1459ee445ef83169580f5b
38,722
import math def box_heightmap(box: BoxCorner, hm: HeightMap, qp_a: QP, qp_b: QP) -> Contact: """Returns contact between a box corner and a height map.""" # Note that this only checks box corners against height map surfaces, and is # missing box planes against height map points. pos, vel = qp_a.to_world(box.co...
ac7e63eba9c29fa945710aa05a958f97083a7804
38,723
def rjmcmc_chisq_convergence(k, thin=1, sparse=False, split=True, merge_cells=True, correction=True, use_likelihood_ratio=False, class_lookup=None, min_expected_count=5): ...
a91033ce32dc164591cd070144e8da0b99a50f37
38,724
def remove_vars_match(mat,fmla): """ Remove the variables bindings from a match. This is used to prevent variable capture when applying the match to premises. Make sure free variables are not captured by fmla """ res = dict((s,v) for s,v in mat.iteritems() if il.is_ui_sort(s)) sympairs = [(s,v) for ...
ed8082e28ee5195a7d8a6f3a54d510509759b477
38,725
def str_exp(exp, ak, den, diff=0.05): """ Function that returns a string k^(a/den) if the absolute difference between the value a/den and the exponent ak is below diff. Arguments: exp -- initial string (given by the previous best estimation) ak -- slope den -- denominator of th...
deb5c74a938b81bb10f81724bcd50c7c683e901c
38,726
def search(*, common: dict = Depends(common_parameters), type: SearchTypes): """Perform a search.""" if common["query_str"]: models = [get_class_by_tablename(t) for t in type] results = composite_search( db_session=common["db_session"], query_str=common["query_str"], ...
2b123874fcfd1aa174e5554a71ad669d575ea090
38,727
from re import T def stack(x, axis=0): """Join a sequence of tensors along a new axis """ return T.stack(x, axis=axis)
76dd3b65db7d3011ba5d223104a686ee5ed9e219
38,728
import typing def or_value( maybe_value: typing.Optional[typing.Any], fallback_value: typing.Any, ) -> typing.Any: """Return maybe_value if not None; otherwise, return fallback_value. Parameters ---------- maybe_value The value to test and return if it is not None. fallback_value ...
6f67fac29fb56b68ef5701a30b0fd6527fb1cc1b
38,729
import argparse def parse_arguments(solving_methods): """ Main CLI for interfacing with Monte Carlo Sudoku Solver. Arguments: solving_methods: tuple(str) Methods for solving sudoku puzzles. Returns: argparse.Namespace Argparse namespace containg CLI inputs. ...
33c5419f4cd3944ee2fe39adbb2cd9776bb5a566
38,730
def form_from_fields(name, form=forms.Form, fields={}): """ Returns a forms.Form class with a name, `name`, a Form baseclass, `form`, and a dictionary of fields, `fields`. """ return DeclarativeFieldsMetaclass(name, (form,), fields)
16d355a14257b430b1eb802ca7b4996562351f48
38,731
def make_enumeration(entries, divider=', '): """ :param entries: :param divider: :return: """ enumeration = { 'type': 'enumeration', 'entries': entries, 'divider': divider } return enumeration
0fee40bf69613944b57f2d1967ee0cdb87e7493b
38,732
def list_available_node_types(): """returns the friendly names of all available node types """ return list(type_map.keys())
f51536b4a399f6dd73a491f6cf48f954946a1ef3
38,733
from typing import Union def sitk_binary_fill_holes(labels: np.ndarray, fill_border: bool = True, iterations: Union[int, bool] = False, kernel_radius: int = 4, max_length: int = 45, i...
d228bdcedda3a21450fb4e4e7f2d2823fe493c92
38,734
def h(P, T, region = 0): """Specific enthalpy [kJ / kg]""" if region is 0: region = idRegion(P, T) if region is 1: return region1.h(P, T) elif region is 2: return region2.h(P, T) else: return 0.000
6b38283b79eb6bc63088885aac5e0096c37064bd
38,735
def instagram_posts(username, limit=12): """ Put a list of Instagram posts into the template context. """ CACHE_KEY = "instagram_%s" % username posts = cache.get(CACHE_KEY) # Serve from cache if available if posts is not None: return posts[:limit] # Else, fetch and store in cac...
e8f9c94fa5d472921c271cd8f30b36d293139a54
38,736
from chainer import gradient_check from chainer import testing import numpy import unittest import attr def unary_math_function_unittest(func, func_expected=None, label_expected=None, make_data=None): """Decorator for testing unary mathematical Chainer functions. This decorat...
9d9e8ef3f8948d56be4f5c547c9aaed4e2d68a04
38,737
def establish_connection() -> storage.client.Client: """ Establish a connection to Google Cloud Storage storing agriculture data. :return: client connection """ storage_client = storage.Client.from_service_account_json(find('Agriculture.json', '/home')) return storage_client
e2409745ddc0174f2feb242789de437998f1170b
38,738
def is_authenticated_decorator(function): """Декоратор, чтобы не пускать неавторизованных пользователей""" def wrapper(request, *args, **kwargs): """Если пользователь авторизован -> вернем функцию, иначе переведем на страницу логина""" if is_authenticated_user(request): return functi...
2a5f894dc45abcecd8bf4591116d90bc18cb1d42
38,739
def preprocess_text(sentence): """ 前處理,處理奇怪的輸入。例如:'i',需要轉成大寫。 """ cleaned = [] words = sentence.split(' ') for w in words: if w == 'i': w = 'I' if w == "i'm": w = "I'm" cleaned.append(w) return ' '.join(cleaned)
b70bf2f454dba8de6bf639f66369755bcf474948
38,740
import subprocess import sys def start_generator(name): """ Start a generator, given its partial name. * Closes stdin * Redirects stdout to stderr (so that it doesn't conflict with i3bar) Returns a Popen object of the started process. """ exename = find_generator(name) proc = subproc...
fd8003f4ac31b6ac63ccd0e12b3ff255399d1baf
38,741
def compact(number): """Convert the number to the minimal representation. This strips surrounding whitespace and separation dash.""" return clean(number, '.,- ').upper().strip()
2b1471cdc8d524bf02d18719acb708ebbe8cdd13
38,742
import os import time def predict_bert_multitask( inputs, problem='weibo_ner', model_dir='', params=None, problem_type_dict={}, processing_fn_dict={}, model=None): """Evaluate Multi-task Bert model Available eval_scheme: ner, cws, acc Keywo...
948c7c5d7c9fc4e7a10c5518287053be9feda4b4
38,743
import os def get_season_team_pbp_folder(season): """ Returns the folder containing team pbp logs for given season :param season: int, current season :return: str, /scrape/data/teams/pbp/[season]/ """ return os.path.join(get_team_data_folder(), 'pbp', str(season))
2c62834edfa590c320356224bfb33a51e82999c8
38,744
def draw_candidate_matchings(members, min_size, n_candidates, initial_seed=0): """Create multiple random groupings in list-format. Args: members (pd.Series): Integer series with indeces over which we group. min_size (int): Minimum group size. n_candidates (int): Number of candidate grou...
a927242dcb130e1b881605f595961d777a7bc7d3
38,745
def get_module_name(): """ モジュール名取得 Return: モジュール名 """ return __name__
45836eb290ff628baf9082829b9e95d9d4e45d78
38,746
import torch def torch_ravel_multi_index(multi_index, dims=None, device=None, strides_=None): """ Implementation of `numpy.ravel_multi_index` for torch Tensors Args: multi_index (List[Tensor] | Tensor) : either a list of indices for each dimension, or a tensor containing the same infor...
d7f79c6266b75aab29974e698e5d62ef6319f952
38,747
def get_base_folder(image_file): """The base folder""" return '/'.join(image_file.split('/')[:-6])
14f212e80d57b71d2b379d2f5024c8f89ea438f3
38,748
def parse(fname): """ XMLファイルから内容をパースしてフィールドと値を格納した辞書を返す """ tree = ET.parse(fname) root = tree.getroot() parsed = [] for e in root.getiterator(): cur_dict = e.attrib.copy() cur_dict['elem'] = e.tag parsed.append(cur_dict) # for child in root: # ...
89ea2c62c64f09be9a99c0bd86b83854c83d4c20
38,749
import requests import os import tqdm def download(url, dst, verbosity=True): """ @param: url to download file @param: dst place to put the file """ file_size = int(requests.head(url).headers["Content-Length"]) if os.path.exists(dst): first_byte = os.path.getsize(dst) else: ...
8a5371cd909c644ad57faa6b1a8723cddb64cac7
38,750
import tqdm def optimization_hyperopt_loo(imgs, grades, args, loss, groups=None): """Optimizes hyperparameters for MRELBP and local standardization using tree of Parzen estimators and leave-one-out split for training multiple optimizations. Parameters ---------- imgs : list List of input ...
8935728576840238fdb8694612c2015de01fd071
38,751
def latex_plt(matplotlib): """ This function updates the matplotlib library to use Latex and changes some default plot parameters :param matplotlib: Matplotlib instance :return: Updated matplotlib instance """ # Use Latex for matplotlib pgf_with_latex = { "font.family": "serif", ...
06042b9625d6cf1a7d56144962ae0795f1f73e34
38,752
def _str_n_grade(df: pd.DataFrame, grade: str) -> str: """Print the number of cards with grade `grade`.""" n_cards = len(df) n_grade = len(df[(df["grade"]) == grade]) perc = round((n_grade / n_cards) * 100, 2) return ( f"– The number of cards with grade {grade} is {n_grade} " f"of {...
91cee7bb1f8faae1cf60c279b95d1cca7912fb19
38,753
def add_nodes_elements_from_bmesh(structure, bmesh, line_type=None, mesh_type=None, thermal=False): """ Adds the Blender mesh's nodes, edges and faces to the Structure object. Parameters ---------- structure : obj Structure object to update. bmesh : obj Blender mesh object. ...
d91515963245554df2c5a09a2a0b2827c13e5314
38,754
from datetime import datetime def _makefilename(lidvid: str, ts: datetime, kind: str, ext: str) -> str: """Make a filename. Make a PDS filename for the given ``lidvid`` by dropping its URN prefix, splitting it into LID and VID, adding the date part of the ``ts`` timestamp, slapping on the ``kind`` of fil...
6d9cc048ccb61d51c1ee328edc8da15a2ae3797f
38,755
import logging def extract(client, output_path, index): """ Scroll an index with a match-all query, dumping document source to ``outdir/documents.json``. :param client: Elasticsearch client used to extract data :param output_path: Destination directory for corpus dump :param index: Name of index ...
089abc87d722adb000d9db4c7f125ee21e12aa3d
38,756
from astroquery.gaia import Gaia import getpass def gaia_log_in(gaia_user = None, gaia_paswd = None): """ This routine log in to the Gaia archive. """ while True: try: Gaia.login(user=gaia_user, password=gaia_paswd) print("Welcome to the Gaia server!") break except...
76d004d22ac981fc635279b70652c899c903a1c7
38,757
import re def parse_class(name, doc): """ Extract a class declaration from a docstring. """ match = re.search(r"class ({}(\([^)]*\))?):".format(name), doc) csig = match.group(1) start = match.start() end = doc.find("```", start) doc = doc[start:end] variables = [] start = doc...
ed42aa330cf817df7fd35dced37b55010e38ff71
38,758
def is_acceptable_smiles(smile: str, allowed_chars=SMILES_ENCODING_['indices_token'].values(), min_len=SMILES_ENCODING_['min_smiles_len'], max_len=SMILES_ENCODING_['max_smiles_len']): """ Checks which smiles Args: smile: (str) smiles string allowed_chars: (lst) list of ...
7bef7d266caf9bfd540cc1d53b99bbc887bca140
38,759
from typing import List from typing import Union def parse_planes( planes_to_parse: List[Union[int, str]], n_planes: int, default: Union[int, List[int]] = 0, name: str = 'planes' ) -> List[int]: """ Get a set of planes from a list of plane indexes and ranges. Parameters ---------- planes_...
5bed291bf525fe06a709563f73490277aff6a600
38,760
def get_api(api_id): """Get a single api. Args: api_id (int): The id of the api. Returns: dict: The api. """ api = API.query.get(api_id) if not api: abort(404) return api.to_dict()
3031ff5ad6b0b0eaa0f57d9c1a1e706a08afa246
38,761
import math def calc_distance(x1, y1, x2, y2): """ Calculate the distance between 2 point given the coordinates :param x1: Point 1 X coordinate :param y1: Point 1 Y coordinate :param x2: Point 2 X coordinate :param y2: Point 2 Y coordinate :return: Double. Distance between point 1 and poi...
dd143ed5dd088c8a4d205c47363cd463798796d9
38,762
def list_perceel_adapter(obj, request): """ Adapter for rendering a list of :class: `crabpy.gateway.capakey.Perceel` to json. """ return { 'id': obj.id, 'sectie': obj.sectie, 'capakey': obj.capakey, 'percid': obj.percid }
7c20a79e492433acdbc31014ed4f9ab8f3d18115
38,763
def parse_fqdn(session, fqdn): """ Break an fqdn (string) and get some useful information from it. Returns a tuple of the shortname (string), and DnsDomain object """ if not fqdn: raise ArgumentError("No fully qualified name specified.") (short, _, dns_domain) = fqdn.partition(".") ...
9487d74b411f0d5aebfe857378983df8f69c093a
38,764
def uniform_pdf(x): """ Uniform Distribution(균등 분포) 확률 밀도 함수 """ return 1 if 0 <= x < 1 else 0
8aa049fc5ce2524edbfed892e4c0de1ce439ff58
38,765
def read_package_data_files(): """Read package data files and return the text.""" with open(package_data_file(DATA_HTML_BASE), 'rt', encoding='utf-8') as f: base_html = f.read() with open(package_data_file(DATA_HTML_LICENSE), 'rt', encoding='utf-8') as f: lic...
03a96d7cb8f43f7588a51efa4f0816a3c01030cb
38,766
def unit(value, unit, parenthesis=True): """Formats the numeric value of a unit into a string in a consistent way.""" formatted = f"{value:,g} {unit}" if parenthesis: formatted = f"({formatted})" return formatted
fe039ec681a16e4a317f1a500c29ab44615addd1
38,767
from typing import Callable from typing import Any from typing import List import numpy def apply_along_axis( func1d: Callable[[PolyLike], PolyLike], axis: int, arr: PolyLike, *args: Any, **kwargs: Any, ) -> ndpoly: """ Apply a function to 1-D slices along the given axis. Execute `fun...
00d537ec6dc12e421344064b236f209d0d8d2846
38,768
def get_matrix(vocab, token_pairs): """Get normalized matrix""" # Build matrix vocab_size = len(vocab) g = np.zeros((vocab_size, vocab_size), dtype='float') for word1, word2 in token_pairs: i, j = vocab[word1], vocab[word2] g[i][j] = 1 # Get Symmetric matrix g = symmetrize(g...
aaf5737f06438d02c039c6b57e346967bd176967
38,769
def decode_landm_in_numpy(pre, priors, variances): """Decode landm from predictions using priors to undo the encoding we did for offset regression at train time. Args: pre (tensor): landm predictions for loc layers, Shape: [num_priors,10] priors (tensor): Prior boxes in center-of...
9e30bae72b3a4e9711a9ff38fa675af95e355235
38,770
def bulk_add_songs_to_playlist(playlist_id, songs, *args, **kwargs): """ """ playlist = Playlist.objects.get(id=playlist_id) songs_added = 0 failures = 0 failure_details = [] for song in songs: try: platform = get_platform(song.get('platform', 'revibe')) so...
ae413eca648c41d0421f138d7abd9ae49302389d
38,771
def execute_query(spec, connection_string=None): """ Setup a connection to a mongodb server and execute the given query. :param spec: Mongo query spec. :returns: Mongo curser. """ if connection_string is None: connection_string = "mongo://localhost:27017/test" if connection_string: ...
2f23b2e32cdd004c836b12b6fd32010e224c17e3
38,772
def untlpydict2xml(untl_filename, untl_dict): """Return a UNTL file. Takes a UNTL filename and a UNTL Python dictionary. """ return pydict2xml(untl_filename, untl_dict)
c2e1b1bef7484fc7761a775abfeeee18f1f7ceb4
38,773
def cityInit(ifInput, cityInput, *txtPath): """ 随机产生城市矩阵 :param ifInput: 是否输入城市数量 bool :param cityInput: 如果第一个参数为True, 填任意值, 否则填城市数量 int :param txtPath: (可选)如果第一个参数为False, 也可以选择文件输入, 文件有三列, 第一列是序号, 第二列是横坐标, 第三列是纵坐标 string :return: 城市数量 int, 城市坐标 list, 城市之间的距离矩阵 ndarray city.txt示例: 1 9860 14152 ...
004e68d459f325a141a4ca3865bef874699e030e
38,774
def deduce_left_margin(properties_of_keywords_in_resume, structural_properties_of_resume): """Takes the smallest left margin that has more than 2 occurrences in all_caps_properties and entire_match_properties. If both left_margin matched it returns the left_margin immediately. If not, it returns the left_ma...
a5abdf66814d00b5edd85f77a262e02da134890b
38,775
def __datetime_representer(dumper, data): """ Ensures that datetime objects are represented correctly.""" value = data.isoformat("T") return dumper.represent_scalar("tag:yaml.org,2002:timestamp", value)
b1a51f29d17b40223595723474c605e430a80aa1
38,776
def normalize_val_list(val_list): """Returns a list of numeric values by the size of their maximum value.""" max_val = float(max(val_list)) return [ val/max_val if max_val != 0 else 0 for val in val_list ]
f594a6c281253bc181e436d1e1e3e1a83d07b56c
38,777
def policy_threshold(threshold, belief, loc): """ chooses whether to switch side based on whether the belief on the current site drops below the threshold Parameters ---------- threshold (float): the threshold of belief on the current site, when the belief is lower than the...
31b50a3093ba60d59e0c23eb11f2f20f76065e81
38,778
import click def run(torrent, output_location): """Console script for pytorrent.cli.run.""" click.echo("Replace this message by putting your code into " "pytorrent.cli.run") pt = PyTorrent(torrent) pt.start() pt.create_files(output_location) return 0
8529c2eb3e1a59c3945a264f4458e06f981ceafc
38,779
def create_standard_serializer_class(model_cls): """Creates serializer class for the Django model specified. Created serializer will declare all model fields, will have "url" #HyperlinkedIdentityField pointing at detail view for the entity and will inherit #OptimizeUrlFieldsSerializer and #JsFriendlyFi...
59df8920281a38e9651efdeb4be014535c519229
38,780
import warnings def choose_representation(adata, rep=None, n_pcs=None): """Get representation of multivariate data. Args: adata (anndata.AnnData): Multidimensional morphological data. rep (str): Key in .obsm. n_pcs (int): Number of p...
85938af3be930ce707a5f9a51992da373686498b
38,781
def sieve(iterable, indicator): """Split an iterable into two lists by a boolean indicator function. Unlike `partition()` in iters.py, this does not clone the iterable twice. Instead, it run the iterable once and return two lists. Args: iterable: iterable of finite items. This function will sca...
55f64a2aea55af05bd2139328157e3a877b8f339
38,782
import datasets import torch def Flowers_dataloader(root, quat_data, img_size, normalize, batch_size, num_workers=2, eval=False): """102 Oxford Flowers dataloader with resized and normalized images.""" name = '102 Oxfrod Flowers' print('Dataset:', name) if not eval: dataset = datasets.ImageFol...
373c15c4ff23a91309235d6ed8de9e0700ce2939
38,783
import logging def documents(title): """Document page.""" logging.debug("Calling document page endpoint...") logging.info("Get textfiles...") text = get_textfile(title) logging.info("Get document-topics distributions...") document_topic = pd.read_json(get_document_topic_distributions(), orient...
1297e94c589301040c42201aee050c244c633b47
38,784
import re def property_to_snake_case(property_type): """Converts a property type to a snake case name. Parameters ---------- property_type: type of PhysicalProperty of str The property type to convert. Returns ------- str The property type as a snake case string. """ ...
fc0aa1c811a2de0bbd77f146a1816e8d7a31e08a
38,785
import argparse def get_args(): """ Supports the command-line arguments listed below. function to parse through args for connecting to ESXi host or vCenter server function taken from getallvms.py script from pyvmomi github repo """ parser = argparse.ArgumentParser( description='Pro...
2162e8df47c6c72bec08d16a45bfa754b4f223df
38,786
def standardize(data: np.ndarray) -> list: """ Standardize input values (x - x.mean) / x.standard_deviation Args: data (np.ndarray): Input data Returns: [type]: Standardized input data """ return np.array((data - np.mean(data)) / np.std(data), dtype=np.float32)
d1c7d5571f745c6f426772987be69c08faee88c1
38,787
def add_component(componentName, entityId, entity_type=entity.EntityType().Game): """ Given a component name, finds component TypeId, adds to given entity, and verifies successful add/active state. :param componentName: String of component name to add. :param entityId: Entity to add component to. :r...
29c53076e2a6eb6a13e6cfc0611f01803d3cbf7c
38,788
def pad_sequence(sequence, max_length, embeddings_dict, pad_token = 'EOS'): """ Adds EOS tokens until sequence length is max_length. """ n = len(sequence) padded = sequence.copy() if n < max_length: if type(padded) is np.ndarray: padded = np.append(padded, [embeddings_dict[pad_toke...
8f31ffa8ba5e9a7d96913564164670196d833b1d
38,789
from typing import Tuple from typing import List from operator import concat def _parse_frequencies(result: Tuple, frequency_ids: List[int], frequencies: List[float], amplitudes: List[float]) -> df: """ Parses the list of frequencies from the result of FCombLibrary. The resulting frequencies are simply a list...
07964a8cc31a0665598b68129d4b64ac8bc873c8
38,790
def read_binary(filepath): """return bytes read from filepath""" with open(filepath, "rb") as file: return file.read()
98587f79b5a2d8b8ff82909cb03957c0b3e2db7d
38,791
def sra_valid_accession(accession): """ Test whether a string is an SRA accession """ if accession.startswith('SRR') and len(accession) == 10: return True return False
3a4c5f40490f68490620ddacb430a0fcc8dfdd89
38,792
import pickle def get_model_names(): """Helper function that abstracts logic for getting names of all models associated with the function""" if 'models' in session: models = pickle.loads(session.get('models')) else: models = {} return list(models.keys())
dbcee7582cf5e9118fc63d8c7a5bbb09f66f669a
38,793
def alaska_transform(xy): """Transform Alaska's geographical placement so fits on US map""" x, y = xy return (0.3*x + 1000000, 0.3*y-1100000)
3f86caeee7b34295ce0680017dd70d6babea2a62
38,794
async def mb(bucket: str) -> bool: """ Make bucket """ async with _create_client() as client: try: await client.create_bucket(Bucket=bucket) logger.info(f'Make bucket "{bucket}".') except ClientError: return False return True
6b6ff926870204f9028f3c482df94ea44f763480
38,795
import requests import json def get_user_simple_list(access_token, dept_id): """ 获取部门用户信息 :return: { "errcode": 0, # 返回码 "errmsg": "ok", # 对返回码的文本描述内容 "hasMore": false, # 在分页查询时返回,代表是否还有下一页更多数据 "userlist": [ { "userid": "zhangsan", # 员工id "name": "张三" #...
4fe63f8a8554015e02193005023181aa22ec23a5
38,796
import json def err_resp(code: int, msg: str, err_subcode=None): """ generate error response :param code: error code :param msg: error msg :param err_subcode: specific error details :return: JsonResponse """ return json({ "ok": False, "code": code, "msg": msg, ...
4de735610564989ba5fdd1d581cd3b0525a1778b
38,797
def req(reqrep, address, rep): """The REQ socket.""" req, rep = reqrep req.connect(address) return req
3cb4deb9e29256fc591ac59c3a1f756e48ff844b
38,798
def networkIPv4_deploy(request, network_id): """Deploy network L3 configuration in the environment routers for network ipv4 Receives optional parameter equipments to specify what equipment should receive network configuration """ log.debug("networkIPv4_deploy") networkipv4 = NetworkIPv4.get_by_...
70964ba00dc31b36c813d11c7ce4dbf0743935b9
38,799