content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def check_vacancy_at_cell(house_map, cell): """ Return True if the given cell is vacant. Vacancy is defined as a '0' in the house map at the given coordinates. (i.e. there is no wall at that location) """ x = cell[0] y = cell[1] if not 0 <= x < MAP_WIDTH: return False ...
78a24b25a6954b6411aa686512066b25c6f4e1d5
10,100
from typing import Dict def extract_text_and_vertices(x: Dict[str, str]): """Extracts all annotations and bounding box vertices from a single OCR output from Google Cloud Vision API. The first element is the full OCR. It's equivalent to the output of `extract_full_text_annotation` for the same OC...
6fde2bc71ceccfd580a6f5f0da7fa0b76e045bad
10,101
def cspace3(obs, bot, theta_steps): """ Compute the 3D (x, y, yaw) configuration space obstacle for a lit of convex 2D obstacles given by [obs] and a convex 2D robot given by vertices in [bot] at a variety of theta values. obs should be a 3D array of size (2, vertices_per_obstacle, num_obstacles) bot ...
723e1b885a19ae0416226856f7b03aecb045e139
10,102
from typing import Optional def Graph(backend:Optional[str]=None) -> BaseGraph: """Returns an instance of an implementation of :class:`~pyzx.graph.base.BaseGraph`. By default :class:`~pyzx.graph.graph_s.GraphS` is used. Currently ``backend`` is allowed to be `simple` (for the default), or 'graph_tool' and 'igra...
9d2d759096016e0df770863448305b627df0ce73
10,103
from datetime import datetime def get_carb_data(data, offset=0): """ Load carb information from an issue report cached_carbs dictionary Arguments: data -- dictionary containing cached carb information offset -- the offset from UTC in seconds Output: 3 lists in (carb_values, carb_start_dates,...
cc2e54859f3f4635e9724260f277dd3c191c32ac
10,104
def _discover_bounds(cdf, tol=1e-7): """ Uses scipy's general continuous distribution methods which compute the ppf from the cdf, then use the ppf to find the lower and upper limits of the distribution. """ class DistFromCDF(stats.distributions.rv_continuous): def cdf(self, x): ...
bb882065ed74a34c61c60aa48481b2737a2496da
10,105
def ml_app_instances_ml_app_instance_id_get(ml_app_instance_id): # noqa: E501 """ml_app_instances_ml_app_instance_id_get # noqa: E501 :param ml_app_instance_id: MLApp instance identifier :type ml_app_instance_id: str :rtype: None """ return 'do some magic!'
e702d106b6dd4999ed536f77347ca84675be3716
10,106
import random def generate_name(style: str = 'underscore', seed: int = None) -> str: """Generate a random name.""" if seed is not None: random.seed(seed) return format_names(random_names(), style=style)
2f74460f5492c3b4788800d6e33a44b856df91aa
10,107
def argunique(a, b): """ 找出a--b对应体中的唯一对应体,即保证最终输出的aa--bb没有重复元素,也没有多重对应 :param a: :param b: :return: aaa, bbb 使得aaa-bbb是唯一对 """ # 先对a中元素进行逐个检查,如果第一次出现,那么添加到aa中,如果不是第一次,那么检查是否一致,不一致则设置成-1 # 设置成-1,代表a中当前元素i有过一对多纪录,剔除。同时-1也不会被再匹配到 seta = {} for i, j in zip(a, b): if i not in ...
e804436203496d5f3109511967a0d75eaca330da
10,108
def move(obj, direction): """ Moves object by (dx, dy). Returns true if move succeeded. """ goal = obj.pos + direction if (goal.x < 0 or goal.y < 0 or goal.x >= obj.current_map.width or goal.y >= obj.current_map.height): # try_ catches this for the player, but nee...
23917e448ed953acb2bb864d7a14d01c72f07a85
10,109
def addMedicine(medicine: object): """Data required are "name", "description", "price", "quantity", "medicalId" """ return mr.makePostRequest(mr.API + "/medicine/", medicine)
f488ecd16d6e2986944ae26e5776ca9f9be7e170
10,110
from benchbuild.utils.db import create_run from benchbuild.utils import schema as s from benchbuild.settings import CFG from datetime import datetime def begin(command, project, ename, group): """ Begin a run in the database log. Args: command: The command that will be executed. pname: Th...
a33a5e809b20b6d1f92545bd0df5de9fbc230f91
10,111
def fortran_library_item(lib_name, sources, **attrs ): #obsolete feature """ Helper function for creating fortran_libraries items. """ build_info = {'sources':sources} known_attrs = ['module_files','module_dirs', ...
720802933b9ebcaab566f3deeb063341b85dba7e
10,112
def copy_generator(generator): """Copy an existing numpy (random number) generator. Parameters ---------- generator : numpy.random.Generator or numpy.random.RandomState The generator to copy. Returns ------- numpy.random.Generator or numpy.random.RandomState In numpy <=1.16...
57f5c3b9ad934330b1eedb6460943204f97b9436
10,113
import os, sys import subprocess import datetime def uptime(): """Returns a datetime.timedelta instance representing the uptime in a Windows 2000/NT/XP machine""" if not sys.platform.startswith('win'): raise RuntimeError, "This function is to be used in windows only" cmd = "net statistics server" ...
a5712fa6acc068174b09f942102da6cda48660f9
10,114
from sys import path def sort_from_avro(df: 'pd.DataFrame', cur_filename: str, order_folder: str) -> 'pd.DataFrame': """Shuffle a dataframe with the given seed :param df: the input dataframe :type df: pandas.DataFrame :param cur_filename: the initial file name :type cur_filename: str :param o...
be2d0ec8a69c9df5605e21b9a6643983fd1fa86e
10,115
def test_pages_kingdom_successful(args, protein_gen_success, cazy_home_url, monkeypatch): """Test parse_family_by_kingdom() when all is successful.""" test_fam = Family("famName", "CAZyClass", "http://www.cazy.org/GH14.html") def mock_get_pag(*args, **kwargs): return ["http://www.cazy.org/GH14_all...
b5fdbeac6a4a54170c17a98689ae5cc6bbca9542
10,116
def _truncate_and_pad_token_ids(token_ids, max_length): """Truncates or pads the token id list to max length.""" token_ids = token_ids[:max_length] padding_size = max_length - len(token_ids) if padding_size > 0: token_ids += [0] * padding_size return token_ids
a8f29fdbc99c3dcac42b9275037d3a3c39c22e12
10,117
def build_bundletoperfectsensor_pipeline(pan_img, ms_img): """ This function builds the a pipeline that performs P+XS pansharpening :param pan_img: Path to the panchromatic image :type pan_img: string :param ms_img: Path to the multispectral image :type ms_img: string :returns: resample_ima...
f40aa0828ef50ef8f81f901f93dbaf8690a14d4f
10,118
def get_argparser_ctor_args(): """ This method returns a dict containing the kwargs for constructing an argparse.ArgumentParser (either directly or as a subparser). """ return { 'prog': 'CodeChecker store', 'formatter_class': arg.RawDescriptionDefaultHelpFormatter, # Descri...
9debf6233652052782295aeb5b630ee2b4b3b19e
10,119
def castep_geom_count(dot_castep): """Count the number of geom cycles""" count = 0 with open(dot_castep) as fhandle: for line in fhandle: if 'starting iteration' in line: count += 1 return count
6a619b5853a02a8c118af1fc19da0d803941c84f
10,120
def nav_login(request, text="Login", button=False): """Navigation login button Args: request (Request): Request object submitted by template text (str, optional): Text to be shown in button. Defaults to "Login". button (bool, optional): Is this to be styled as a button or as a link. Def...
ddbc3de38c47425ec9f095577d178c068cce74c2
10,121
def parse_adapter(name: str, raw: dict) -> dict: """Parse a single adapter.""" parsed = { "name": strip_right(obj=name, fix="_adapter"), "name_raw": name, "name_plugin": raw["unique_plugin_name"], "node_name": raw["node_name"], "node_id": raw["node_id"], "status":...
085b8a38561d6ffda12ca27d2f2089759b34e1ed
10,122
def export_phones(ucm_axl): """ Export Phones """ try: phone_list = ucm_axl.get_phones( tagfilter={ "name": "", "description": "", "product": "", "model": "", "class": "", "protocol": "", ...
1487cef48c5666224da57173b968e9988f587a57
10,123
def is_various_artists(name, mbid): """Check if given name or mbid represents 'Various Artists'.""" return name and VA_PAT.match(name) or mbid == VA_MBID
084f1d88b99ec7f5b6eac0774a05e901bd701603
10,124
def validate_ruletype(t): """Validate *bounds rule types.""" if t not in ["typebounds"]: raise exception.InvalidBoundsType("{0} is not a valid *bounds rule type.".format(t)) return t
a8ae173f768837cdc35d1a8f6429614b58a74988
10,125
from pathlib import Path import io import tarfile import sys def download_and_unpack_database(db: str, sha256: str) -> Path: """Download the given database, unpack it to the local filesystem, and return the path. """ local_dir = cache_path(f"state_transition_dataset/{sha256}") with _DB_DOWNLOAD_LO...
e67081a82999ddf524825199acf7338394bb129f
10,126
def decode_section_flags(sflags: str) -> int: """Map readelf's representation of section flags to ELF flag values.""" d = { 'W': elftools.elf.constants.SH_FLAGS.SHF_WRITE, 'A': elftools.elf.constants.SH_FLAGS.SHF_ALLOC, 'X': elftools.elf.constants.SH_FLAGS.SHF_EXECINSTR, 'M': elf...
e007f1f370f6203bafe92a1a6422100f2d9626ae
10,127
def nCr(n,r): """ Implements multiplicative formula: https://en.wikipedia.org/wiki/Binomial_coefficient#Multiplicative_formula """ if r < 0 or r > n: return 0 if r == 0 or r == n: return 1 c = 1 for i in xrange(min(r, n - r)): c = c * (n - i) // (i + 1) return c
8c0dc30b4cdab47c99bf98459e435147ac0b92fd
10,128
import os def get_test_vesselfile(): """ return the necessary paths for the testfile tests Returns ------- str absolute file path to the test file """ testfile = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'test_data', 'vessel_file.kfc') return testfile
4a08f986d06c66766b7a92023c60bebfe7452dc7
10,129
import inspect def _get_init_arguments(cls, *args, **kwargs): """Returns an OrderedDict of args passed to cls.__init__ given [kw]args.""" init_args = inspect.signature(cls.__init__) bound_args = init_args.bind(None, *args, **kwargs) bound_args.apply_defaults() arg_dict = bound_args.arguments d...
116c01f9edb838e4b392fa624a454fdf4c455f1a
10,130
def MatchCapture(nfa: NFA, id: CaptureGroup) -> NFA: """Handles: (?<id>A)""" captures = {(s, i): {id} for (s, i) in nfa.transitions if i != Move.EMPTY} return NFA(nfa.start, nfa.end, nfa.transitions, merge_trans(nfa.captures, captures))
08805d01be73480cfea4d627c6a67969290c1d11
10,131
import os def save_private_file_share(request, token): """ Save private share file to someone's library. """ username = request.user.username try: pfs = PrivateFileDirShare.objects.get_priv_file_dir_share_by_token(token) except PrivateFileDirShare.DoesNotExist: raise Http404 ...
5c0e633070750f0f7e920530e809d55b21535fe0
10,132
def get_all_state_events(log): """ Returns a list of tuples of event id, state_change_id, block_number and events""" return [ (InternalEvent(res[0], res[1], res[2], log.serializer.deserialize(res[3]))) for res in get_db_state_changes(log.storage, 'state_events') ]
c75307c930add3e142996e19c441c84fd663e36a
10,133
def iff(a: NNF, b: NNF) -> Or[And[NNF]]: """``a`` is true if and only if ``b`` is true.""" return (a & b) | (a.negate() & b.negate())
82ea5bfe9c4e1f79361319b2d8455cba898e77ec
10,134
def redact_access_token(e: Exception) -> Exception: """Remove access token from exception message.""" if not isinstance(e, FacebookError): return e e.args = (redact_access_token_from_str(str(e.args[0])),) return e
63d7a7422cb7315866e9c25552fa96b403673261
10,135
def _get_ext_comm_subtype(type_high): """ Returns a ByteEnumField with the right sub-types dict for a given community. http://www.iana.org/assignments/bgp-extended-communities/bgp-extended-communities.xhtml """ return _ext_comm_subtypes_classes.get(type_high, {})
5b5782659f1d261162d8f9d5becfe65b852f3bdc
10,136
import click def _filter_classes(classes, filters, names_only, iq): """ Filter a list of classes for the qualifiers defined by the qualifier_filter parameter where this parameter is a list of tuples. each tuple contains the qualifier name and a dictionary with qualifier name as key and tuple con...
eecee9f5a1ccf6c793000faf11cd0f666a0c0f7b
10,137
def template2(): """load_cep_homo""" script = """ ## (Store,figure) << host = chemml << function = SavePlot << kwargs = {'normed':True} << output_directory = plots << filename = amwVSdensity ...
2d6dfbab0ef3093645b67da756491fd1b1639649
10,138
from typing import Tuple from typing import Any def get_target_and_encoder_gpu(train: GpuDataset) -> Tuple[Any, type]: """Get target encoder and target based on dataset. Args: train: Dataset. Returns: (Target values, Target encoder). """ target = train.target if isinstance(...
64cfee3ec9c58bf07d9eb28977b4e5cb7ebadc80
10,139
import copy import os import _locale import gettext import locale def get_available_languages(domain): """Lists the available languages for the given translation domain. :param domain: the domain to get languages for """ if domain in _AVAILABLE_LANGUAGES: return copy.copy(_AVAILABLE_LANGUAGES...
f28cc90a24d28224e0ad9f10532674151f070848
10,140
import functools def once(f): """Cache result of a function first call""" @functools.wraps(f) def wrapper(*args, **kwargs): rv = getattr(f, 'rv', MISSING) if rv is MISSING: f.rv = f(*args, **kwargs) return f.rv return wrapper
25d096f76d156c7a8a26f8f159b65b9b31c8d927
10,141
import torch def setup(args): """ Create configs and perform basic setups. """ cfg = get_cfg() add_config(args, cfg) cfg.merge_from_file(args.config_file) cfg.merge_from_list(args.opts) cfg.MODEL.BUA.EXTRACTOR.MODE = 1 default_setup(cfg, args) cfg.MODEL.DEVICE = 'cuda:0' if tor...
76a8a21714a1fed96fe7b6f33cb948aee30bffcf
10,142
def build_audit_stub(obj): """Returns a stub of audit model to which assessment is related to.""" audit_id = obj.audit_id if audit_id is None: return None return { 'type': 'Audit', 'id': audit_id, 'context_id': obj.context_id, 'href': '/api/audits/%d' % audit_id, 'issue_tracker...
705f066975bf9dae8704944c71eeb3e313cf445f
10,143
def calculate_widths(threshold_img, landmarks): """ Calcula a largura dos vasos sanguíneos nos pontos de potenciais bifurcação. Esse cálculo é feito pegando a menor distância percorrida a partir do ponto em cada uma das direções (8 direções são utilizadas). A função retorna o que ser...
304ce6bec19faba0a0520b63435fcbf66f8989f0
10,144
from typing import Optional def smi_to_fp(smi: str, fingerprint: str, radius: int = 2, length: int = 2048) -> Optional[np.ndarray]: """fingerprint functions must be wrapped in a static function so that they may be pickled for parallel processing Parameters ---------- smi : s...
fa768c5b53a4a1b637b1928127ef85506d375fd7
10,145
def f(x, t): """function to learn.""" return tf.square(tf.cast(t, tf.float32) / FLAGS.tm) * (tf.math.sin(5 * x) + 1)
9138b7a2acf43a1c62d5da8157725ff10e6f7f78
10,146
def render_cells(cells, width=80, col_spacing=2): """Given a list of short (~10 char) strings, display these aligned in columns. Example output:: Something like this can be used to neatly arrange long sequences of values in ...
714b915430be84980c3a9b74f3c5b2cb89b6acba
10,147
def separate_types(data): """Separate out the points from the linestrings.""" if data['type'] != 'FeatureCollection': raise TypeError('expected a FeatureCollection, not ' + data['type']) points = [] linestrings = [] for thing in data['features']: if thing['type'] != 'Feature': ...
28ab8eb7e2cdf1206f4908a15506a9b9af1aa428
10,148
def state(state_vec): """ Qiskit wrapper of qobj """ return gen_operator.state(state_vec)
74094c7c6e3c33cff28777f54d8852245c31f276
10,149
import os def get_index_path(bam_path: str): """ Obtain path to bam index Returns: path_to_index(str) : path to the index file, None if not available """ for p in [bam_path+'.bai', bam_path.replace('.bam','.bai')]: if os.path.exists(p): return p return None
b8ccf66a89d865f49fdb311f2fcf0c371fe5c488
10,150
def get_games_for_platform(platform_id): """Return the list of all the games for a given platform""" controller = GameController return controller.get_list_by_platform(MySQLFactory.get(), platform_id)
83855b6cdb4d39442e255d14d2f94d76a702a0ea
10,151
def validate_dataset(elem: object) -> Dataset: """Check that `elem` is a :class:`~pydicom.dataset.Dataset` instance.""" if not isinstance(elem, Dataset): raise TypeError('Sequence contents must be Dataset instances.') return elem
d4744b06f0ccdc8dca0deab57585706c1ee91db9
10,152
from typing import Dict from typing import Any import copy def build_array(name: str, variables: Dict[str, Dict[str, Any]], data: np.ndarray): """Builds the array from the data and the variables""" properties = variables[name] attrs = copy.deepcopy(properties["attrs"]) # Reading the s...
f0021bdce68b90b9f88bb715c302a376083e1dce
10,153
def conv3x3(in_channels, out_channels, stride=1): """3x3 convolution """ weight_shape = (out_channels, in_channels, 3, 3) weight = Tensor(np.ones(weight_shape).astype(np.float32)) conv = Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=0, weight_init=weight, has_...
011a3f74e8665669f9ecf5d4b9e8abf14f52e053
10,154
def _workflow_complete(workflow_stage_dict: dict): """Check if the workflow is complete. This function checks if the entire workflow is complete. This function is used by `execute_processing_block`. Args: workflow_stage_dict (dict): Workflow metadata dictionary. Returns: bool, Tr...
4e5be4c4768d82e8b1e76d1964c3effb2e604dd2
10,155
import os def create_output_folder(ProjectDir): """Create the output folders starting from the project directory. Parameters ---------- ProjectDir : str Name of the project directory. Returns ------- type PicturePath, ResultsPath """ npath = os.path.normpath(Proj...
d1f9abf35bf5342707e7928aaa23c699063a3b70
10,156
def get_name(f, opera_format=True): """Load dataset and extract radar name from it""" ds = xr.open_dataset(f) if hasattr(ds, 'source'): radar = ds.source else: filename = osp.splitext(osp.basename(f))[0] radar = filename.split('_')[-1] if opera_format: if '/' in rad...
8c50bebfde1300aa6de55981537cbc23171e6ee8
10,157
import six def range_join(numbers, to_str=False, sep=",", range_sep=":"): """ Takes a sequence of positive integer numbers given either as integer or string types, and returns a sequence 1- and 2-tuples, denoting either single numbers or inclusive start and stop values of possible ranges. When *to_str...
c1b2d10ec1b47fa5c917fccead2ef8d5fc506370
10,158
def power_spectrum(x, fs, N=None): """ Power spectrum of instantaneous signal :math:`x(t)`. :param x: Instantaneous signal :math:`x(t)`. :param fs: Sample frequency :math:`f_s`. :param N: Amount of FFT bins. The power spectrum, or single-sided autospectrum, contains the squared RMS amplitudes ...
f665c529541420ada0ae4819e53de1e73035d83f
10,159
def CreateInstanceTemplate(task, task_dir): """Create the Compute Engine instance template that will be used to create the instances. """ backend_params = task.BackendParams() instance_count = backend_params.get('instance_count', 0) if instance_count <= 0: clovis_logger.info('No template required.') ...
558e4ed3152bb87a51bd2bb7dd107af5dd76bcd1
10,160
def get_config_string(info_type, board_num, dev_num, config_item, max_config_len): """Returns configuration or device information as a null-terminated string. Parameters ---------- info_type : InfoType The configuration information for each board is grouped into different categories. This ...
72a35d984cb35e38a5e0742c7d790dc72ccbc928
10,161
import inspect def _get_kwargs(func, locals_dict, default=None): """ Convert a function's args to a kwargs dict containing entries that are not identically default. Parameters ---------- func : function The function whose args we want to convert to kwargs. locals_dict : dict T...
ae0a06cb4e17b5512a03e89d7ca2119c58ea762b
10,162
from datetime import datetime def iso_to_date(iso_str: str): """Convert a date string with iso formating to a datetime date object""" if not iso_str: return None return datetime.date(*map(int, iso_str.split('-')))
a0d0541298ed538d7df9940ceef7b2bac121af27
10,163
def call_with_error(error_type): """Collects a bunch of errors and returns them all once. Decorator that collects the errors in the decorated function so that the user can see everything they need to fix at once. All errors are thrown with the same error type. The decorated must have an `error` ke...
9a64fb630b0a491bc9e01d77ebe35199df47ab55
10,164
def _get_metadata_and_fingerprint(instance_name, project, zone): """Return the metadata values and fingerprint for the given instance.""" instance_info = _get_instance_info(instance_name, project, zone) if not instance_info: logs.log_error('Failed to fetch instance metadata') return None, None fingerpr...
7049805d538c7942dc8249e91c27faa2c1867936
10,165
def solve_token_pair_and_fee_token_economic_viable( token_pair, accounts, b_orders, s_orders, f_orders, fee, xrate=None ): """Match orders between token pair and the fee token, taking into account all side constraints, including economic viability. If xrate is given, then it will be used instead of...
f6fcf5bccdf498f29852614751cf120a8e2addd4
10,166
def two_categorical(df, x, y, plot_type="Cross tab"): """ ['Cross tab', "Stacked bone_numeric_one_categorical"] """ if plot_type is None: plot_type = 'Cross tab' if plot_type == 'Stacked bar': # 20 df_cross = pd.crosstab(df[x], df[y]) data = [] for x in df_cross....
5c0908055848d9de02920f8e2718de0918f4b460
10,167
def yices_bvconst_one(n): """Set low-order bit to 1, all the other bits to 0. Error report: if n = 0 code = POS_INT_REQUIRED badval = n if n > YICES_MAX_BVSIZE code = MAX_BVSIZE_EXCEEDED badval = n. """ # let yices deal with int32_t excesses if n > MAX_INT...
6a70c4773a6558e068d2bbafb908657d5b5b4d1d
10,168
def showItem(category_id): """Show all Items""" category = session.query(Category).filter_by(id=category_id).one() items = session.query(Item).filter_by( category_id=category_id).all() return render_template('item.html', items=items, category=category)
230cc9b7e8043b0bb3e78866b2a27a0aec287828
10,169
def get_standard_t_d(l, b, d): """ Use NE2001 to estimate scintillation time at 1 GHz and 1 km/s transverse velocity. Parameters ---------- l : float Galactic longitude b : float Galactic latitude d : float Distance in kpc Returns ------- t_d...
e1743ae75a6893376c5e13126deda6f0eb41d38f
10,170
import os import json def get_json_test_data(project, test_name): """Get data from json file. If json data is not of type dict or list of dicts it is ignored. """ json_data = None json_path = json_file_path(project, test_name) if os.path.isfile(json_path): try: with open(js...
1934128e059eb3a521b7e8ee016c87bc0951453e
10,171
def match(pattern: str, text: str) -> bool: """ 匹配同样长度的字符串 """ if pattern: return True elif pattern == "$" and text == "": return True elif pattern[1] == "?": return _match_question(pattern, text) elif pattern[1] == "*": return _match_star(pattern, text) e...
0dc71f00323502de7c1a2e00c502c99d75f56fc1
10,172
def config_func(tools, index, device_id, config_old: {}, config_new: {}): """ CANedge configuration update function :param tools: A collection of tools used for device configuration :param index: Consecutive device index (from 0) :param device_id: Device ID :param config_old: The current device ...
c0585c3a268fb40e3e00a2613e03001bc561566a
10,173
def load_figure(file_path: str) -> matplotlib.figure.Figure: """Fully loads the saved figure to be able to be modified. It can be easily showed by: fig_object.show() Args: file_path: String file path without file extension. Returns: Figure object. Raises: None. ...
76dcc0a27a3ae04e574a3d69fb431eedbc0c618a
10,174
def cluster_vectors(vectors, k=500, n_init=100, **kwargs): """Build NearestNeighbors tree.""" kwargs.pop('n_clusters', None) kwargs.pop('init', None) kwargs.pop('n_init', None) return KMeans(n_clusters=k, init='k-means++', n_init=n_init, **kwargs).fit(vectors)
28984811ea58a2a2c123d36cdb5e56c1d5b8d0db
10,175
import torch import math def positional_encoding(d_model, length): """ :param d_model: dimension of the model :param length: length of positions :return: length*d_model position matrix """ if d_model % 2 != 0: raise ValueError("Cannot use sin/cos positional encoding with " ...
de41f0c99b46f16dbe300d59527e11b98a0b1f14
10,176
def esx_connect(host, user, pwd, port, ssl): """Establish connection with host/vcenter.""" si = None # connect depending on SSL_VERIFY setting if ssl is False: si = SmartConnectNoSSL(host=host, user=user, pwd=pwd, port=port) current_session = si.content.sessionManager.currentSession.key...
2a8d3214f41bc284ef899c6292fb63284954849b
10,177
import os def get_cropped_face_img(image_path, margin=44, image_size=160, folders=None): """return cropped face img if face is detected, otherwise remove the img """ minsize = 20 # minimum size of face threshold = [0.6, 0.7, 0.7] # three steps's threshold factor = 0.709 # scale factor ...
82230dce29bd24967152c6e74c1db3ed7529528d
10,178
def invert_hilbert_QQ(n=40, system='sage'): """ Runs the benchmark for calculating the inverse of the hilbert matrix over rationals of dimension n. INPUT: - ``n`` - matrix dimension (default: ``300``) - ``system`` - either 'sage' or 'magma' (default: 'sage') EXAMPLES:: sage: impo...
153e7400467a57cf07f839042d31d4800fe161bd
10,179
def getModelListForEnumProperty(self, context): """Returns a list of (str, str, str) elements which contains the models contained in the currently selected model category. If there are no model categories (i.e. '-') return ('-', '-', '-'). Args: context: Returns: """ category = con...
46f642933dd220b0f71431ff4a9cb7410858fbf0
10,180
import os import shutil def moveFiles(subsystemDict, dirPrefix): """ For each subsystem, moves ROOT files that need to be moved from directory that receives HLT histograms into appropriate file structure for processing. Creates run directory and subsystem directories as needed. Renames files to convention t...
4755f3d42b5540f8a7422a51c2f0048e49897ea6
10,181
import logging def run_wcs(*args, **kwargs): """ Set up the environment and run the bundled wcs.exe (from the Talon distribution) using the supplied command line arguments """ # Pull out keyword args that we are interested in write_stdout_to_console = kwargs.get("write_stdout_to_console",...
51461fcbc4ed5a08063d630aea926d312b9da825
10,182
import os def read_setup_cfg(): """ Build an absolute path from *parts* and and return the contents of the resulting file. Assume UTF-8 encoding. """ config_file = os.path.join(HERE, "setup.cfg") cp = ConfigParser() cp.read([config_file]) return cp
86979a63d162df682468bbc5163c751d6a75fbca
10,183
def store_exposure_fp(fp, exposure_type): """ Preserve original exposure file extention if its in a pandas supported compressed format compression : {‘infer’, ‘gzip’, ‘bz2’, ‘zip’, ‘xz’, None}, default ‘infer’ For on-the-fly decompression of on-disk data. If ‘infer’ and ...
c187e79d4cce7ea79b66671a2e7378a35de4841f
10,184
def velocity_genes(data, vkey='velocity', min_r2=0.01, highly_variable=None, copy=False): """Estimates velocities in a gene-specific manner Arguments --------- data: :class:`~anndata.AnnData` Annotated data matrix. vkey: `str` (default: `'velocity'`) Name under which to refer to the...
7d2a0b86d2fb4402cdef9ab56fe2638f89d09fac
10,185
def update_graphics_labels_from_node_data(node, n_id_map, add_new_props): """Updates the graphics labels so they match the node-data""" try: gfx = select_child(node, n_id_map, 'nodegraphics').getchildren()[0].getchildren() except: return None node_label = select_child(node, n_id_map, 'l...
c2d3104dbc3a20ff6c34de754ff681b176091787
10,186
import sys def deploy_binary_if_master(args): """if the active branch is 'master', deploy binaries for the primary suite to remote maven repository.""" master_branch = 'master' active_branch = mx.VC.get_vc(SUITE.dir).active_branch(SUITE.dir) if active_branch == master_branch: if sys.platform =...
582e16e9c688b9ec05dfced51e82f48c3e472e7d
10,187
import pandas import numpy def fast_spearman(x, y=None, destination=None): """calculate the spearman correlation matrix for the columns of x (with dimensions MxN), or optionally, the spearman correlaton matrix between the columns of x and the columns of y (with dimensions OxP). If destination is provided, pu...
e2386d6da26a12c87ca1471a5afde8bcd108c30b
10,188
def ProcuraPalavra(dicionário, palavra): """ Procura as possíveis palavras para substituir a palavra passada, e as devolve numa lista """ #Antes de mais nada tornamos a palavra maiuscula #para realizar as comparações palavra = palavra.upper() #Primeiro olhamos para o caso de haver u...
1a283aec6670c0e2fe6ca6f4366ef43c6ba97e9f
10,189
import os def color_parser(color: str, color_dicts: list = None) -> tuple: """ convert a string with RGB/matplotlib named colors to matplotlib HSV tuples. supports RGB colors with ranges between 0-1 or 0-255. supported matplotlib colors can be found here: https://matplotlib.org/3.3.1/gallery/col...
e43fc03add16368d84371dded7f34370b7c8bb9e
10,190
import json import six def _build_auth_record(response): """Build an AuthenticationRecord from the result of an MSAL ClientApplication token request""" try: id_token = response["id_token_claims"] if "client_info" in response: client_info = json.loads(_decode_client_info(response[...
96aed71945c354e41cafd89bf5d7a7d62c31a40a
10,191
def loc_data_idx(loc_idx): """ Return tuple of slices containing the unflipped idx corresponding to loc_idx. By 'unflipped' we mean that if a slice has a negative step, we wish to retrieve the corresponding indices but not in reverse order. Examples -------- >>> loc_data_idx(slice(11, None,...
d30b1b27957e24ff30caf19588487645ac198dc8
10,192
def eat_descriptor(descr): """ Read head of a field/method descriptor. Returns a pair of strings, where the first one is a human-readable string representation of the first found type, and the second one is the tail of the parameter. """ array_dim = 0 while descr[0] == '[': array_di...
411ce48ce250fe15438cd89f43b91ee9b87908a6
10,193
def legendre(a, p): """Legendre symbol""" tmp = pow(a, (p-1)//2, p) return -1 if tmp == p-1 else tmp
66b86dce23ae10ba226ffb19942b98550bb7c218
10,194
import argparse def get_parser(): """ Create a parser with some arguments used to configure the app. Returns: argparse.ArgumentParser: """ parser = argparse.ArgumentParser(description="configuration") parser.add_argument( "--upload-folder", required=True, metava...
0f7a375948d3e45157637647908f5c0e6948083a
10,195
def precheck_arguments(args): """ Make sure the argument choices are valid """ any_filelist = (len(args.filelist_name[0]) > 0 or len(args.output_dir[0]) > 0 or args.num_genomes[0] > 0) if len(args.filelist_name[0]) > 0 and len(args.output_dir[0]) == 0: print("Error: Need to specify output directory with -O if...
984865d214cca63eae8bacf5bc7be238e7209ddb
10,196
def get_image_blob(im): """Converts an image into a network input. Arguments: im (ndarray): a color image Returns: blob (ndarray): a data blob holding an image pyramid im_scale_factors (list): list of image scales (relative to im) used in the image pyramid """ im_...
6d72ea1ffcdf20bbf05f75f6084a9027e771196a
10,197
def get_expr_fields(self): """ get the Fields referenced by switch or list expression """ def get_expr_field_names(expr): if expr.op is None: if expr.lenfield_name is not None: return [expr.lenfield_name] else: # constant value expr ...
103aa0ac54be37b23d9695dddfda9972a9f0d7f0
10,198
import math def add_bias_towards_void(transformer_class_logits, void_prior_prob=0.9): """Adds init bias towards the void (no object) class to the class logits. We initialize the void class with a large probability, similar to Section 3.3 of the Focal Loss paper. Reference: Focal Loss for Dense Object De...
f5b3439fc7fbc987bbcbc3b64fd689208db7c5e6
10,199