content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_current_branch_name(): """查询当前分支名 :rtype str :return 当前分支名 """ return run_cmd(GitCommand.branch_abbrev).strip()
bce89806b5ee399f51d48966d5218948fe8719f9
68,200
def zeros_like(img, dtype=None): """ :param img: reference image :param dtype: desired data type (optional) :return: an Image with the same shape and header, filled with zeros Similar to numpy.zeros_like(), the goal of the function is to show the developer's intent and avoid doing a copy, whic...
d3744a04afc30e0e6e0dd78e2816c7c42337aad3
68,201
async def get_present_godly_training_description(message_content: str, message: discord.Message) -> str: """Returns the embed description for the lb_omega event""" user_name_end = message_content.find("** !") user_name_start = message_content.rfind('**', 0, user_name_end) + 2 user_name = message_conten...
5c73d2fe4f8e03ace19c2265300c79df51404cde
68,202
import attr def _binary_attrs(stamp_default, is_bootstrap = False): """Attributes allowed in haskell_binary and haskell_test rules.""" return dicts.add( toolchains_attrs, proto_attrs, settings.attributes, compile_srcs_options.attrs, runfile_attrs, dependency_att...
3a848cb60dd4dca6a3d4a4a136024efee503b918
68,203
def pos(number: int) -> int: """Used for indexing.""" return 0 if number < 0 else number
5b4745f067855234fab4f0eb9bc3e8a10d324341
68,204
def result(board, action): """ Returns the board that results from making move (i, j) on the board. """ i, j = action if not 0 <= i < len(board)\ or not 0 <= j < len(board[0]): raise ValueError("This is not a valid position on the board") result_board = deepcopy(board) result_b...
e422ad7fd5044680686fd66db3ef3485bea96b62
68,205
def array2df(X_train, feature_names): """Convert np array to df, use with correlation matrix""" return pd.DataFrame(X_train, columns=feature_names)
55a02a697820157520798d726f890bd0745d905b
68,206
from typing import OrderedDict def _web_edit_enerpi_encryption_key(key_file_lines): """ Return dict for user edition of encryption key Make Ordered dict like: ==> [(section_name, OrderedDict([(VARIABLE, (VALUE, 'text', comment=None))])] :param key_file_lines: Text lines of encryption ...
b0acf82e7c6a2b0755839c09151aa6c7fdb7cfe9
68,207
def loadData(path, bins, string): """Load binned data into a Pandas.DataFrame where first column is datetime, each columns represent a bin and name each column according to a list of floats in argument. Args: path : string path to datafile bins : list List of floats ...
dc8e9819f4b57be36e4fa1c09aa05eec3f10ca69
68,208
import os def get_notebooks(): """ Walks through <pyMG>/notebooks and lists all '.ipynb' files. Jupyter's checkpoint directories ('.ipynb_checkpoints') and temporary directories are skipped. Returns: list of tuples of str: Each tuple contains the absolute path to the file and the file name. ...
02ee5903016c94bcf639b8ba71886f21b3c7ddc6
68,209
def time_reversal_asymmetry_statistic(x, lag): """ This function calculates the value of .. math:: \\frac{1}{n-2lag} \sum_{i=0}^{n-2lag} x_{i + 2 \cdot lag}^2 \cdot x_{i + lag} - x_{i + lag} \cdot x_{i}^2 which is .. math:: \\mathbb{E}[L^2(X)^2 \cdot L(X) - L(X) \cdot X^2] ...
51e4ca243a67acb3194a52c1a2b27d6b13ea7c41
68,210
def main(return_outputs=False): """main""" return parse_command(command_depth=0, return_outputs=return_outputs, **MAIN_CMD_SPEC)
a689b086b0be6b9113733e720740dd323730d78a
68,211
import torch from typing import Optional def graclus_cluster(row: torch.Tensor, col: torch.Tensor, weight: Optional[torch.Tensor] = None, num_nodes: Optional[int] = None) -> torch.Tensor: """A greedy clustering algorithm of picking an unmarked vertex and matching it wit...
636f0ad04443db615bee1afaf241f58145767a28
68,212
def predict_flow(in_planes: int, out_planes: int = 2, bias: bool = False): """ Convenience function for 3x3 conv2d with same padding """ return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=1, padding=1, bias=bias)
c2dc742201a22e84a22e70d2de66e83eaf59d043
68,213
def delete(k): """Returns an Anon instance which performs a deletion, using either __delitem__ or __delattr__ as appropriate. If neither deletion operator makes sense then an exception is raised. Note that the following are the valid ways to call this function. delete(anon[idx]) delete(anon.nam...
5200d05939fc3aaec4092f0772da8da00dadaa58
68,214
def read_prot(filepath): """ This function accepts the filepath of a protein to align, ignores the first line (proceeded by '>' char), strips newlines, and returns the protein as a single string. """ seq = "" with open(filepath) as f: for line in f: if not line.startswith(">"...
e09fab92fca28601d5c92d927ceddccaaf1f5569
68,215
from typing import List import os def try_import(mod: str, only_modules=False) -> List[str]: """ Try to import given module and return list of potential completions. """ mod = mod.rstrip('.') try: m = import_module(mod) except: return [] m_is_init = '__init__' in (getattr(...
abb33662dd5b748b28d37ed6f4bd3793f552ee39
68,216
def welcome(): """List all available api routes.""" return ( f"Available Routes:<br/>" f"/api/v1.0/names<br/>" f"/api/v1.0/tobs" )
edda28124ba8d1eac1fc6bc6931b92743dad0ca5
68,217
def display_user(): """ Function to display existing user """ return User.display_user()
86b39c7463f9ce92428b042a1042602c3206c410
68,218
def test_apply_return_literal(val): """ Test unification codepath for scalars and MaskedType makes sure that numba knows how to cast a scalar value to a MaskedType """ def func(row): x = row["a"] y = row["b"] if x is not NA and x < 2: return val else:...
0a55bbd4fe569ad6be7494024a11030b627ad9e4
68,219
def aumentar(valor, bonus, view=False): """ -> Realiza o calculo de aumento sálarial e retorna seu valor :param valor: Valor do dinheiro :param bonus: Porcentagem do bônus :param view: Verifica se formata ou não o valor :return: Retorna valor com aumento sálarial """ return moeda(valor +...
e7bec1c3ad7d2666401d95457e20c410612aadd7
68,220
import torch def polar_transformer(U, out_size, device, log=True, radius_factor=0.707): """Polar Transformer Layer Based on https://github.com/tensorflow/models/blob/master/transformer/spatial_transformer.py. _repeat(), _interpolate() are exactly the same; the polar transform implementation is in _tr...
edd5d08ef9a3312622ffce69a69d1f2e7d7199c7
68,221
import logging import warnings def Correlate(data, model_orders, debug=False, addmode="ML", orderweights=None, get_weights=False, prim_teff=10000.0): """ This function does the actual correlation. The interface is slightly less useful than GetCCF, but can still be called by the user. Pa...
1348cda454bb6fc939576bbb6b434d3034b5ad3e
68,222
def CSMToBinary(D, Kappa): """ Turn a cross-similarity matrix into a binary cross-simlarity matrix If Kappa = 0, take all neighbors If Kappa < 1 it is the fraction of mutual neighbors to consider Otherwise Kappa is the number of mutual neighbors to consider """ N = D.shape[0] M = D.shape...
6937ea6cfd97d1ced8eabb80c757e09d8985a1c0
68,223
def is_android_project(dirpath): """determines if a given directory is an Android Project. looks for settings.gradle files. Args: dirpath: path of the directory. Returns: bool: True if file is in diretory, False otherwise. """ return "settings.gradle" in [f for f in listdir(dirp...
6620f451d298b8ca979517b751d2a24d3cae4488
68,224
def put_ldap_user_schema( api_client, ldap_user_base=None, ldap_user_id_attribute=None, ldap_user_list_filter=None, **kwargs ): # noqa: E501 """Set LDAP user schema settings # noqa: E501 Set LDAP user schema settings # noqa: E501 This method makes a synchronous HTTP request by defau...
c835c17a4e526bfaa98702cade600b773d26353f
68,225
def get_final_winning_proposal_ready(): """ For cool-off period: tries to find final proposal (available in cool-off when all instances have been evaluated), if none can be found returns 404 """ process_id = int(request.args.get('process-id')) utils.validate_backend_process_id(process_id) if cool_o...
38e2dfeb362ad6294dca6aadfa47c4d4e66bfecf
68,226
import matplotlib.pyplot as plt def shave(signal, factor=4, wn=0.005, plot=False, clip=None): """ This function reduces the number of peaks in a signal. It does this by first passing the signal through a Butterworth low-pass filter to get a trend. Then the a standard deviation of the signal is calcula...
9c1ad5431eccd63bcb9015e6c4f1ec02b9411ca5
68,227
import os import json def get_json_prices(json_path): """ Loading saved the first price all time and last four price for next calculations or analyze. """ if not os.path.exists(json_path): saved_prices = [] with open(json_path, mode="w")as json_file: json.dump(saved_pri...
1e09db1c64f2d81bf9c038e165234ad718fdcfab
68,228
def help(): """Devolve a pagina de Ajuda""" window_id = str(get_window_id()) set_base_context(window_id) ctx_dict = get_context(window_id) ctx_dict['window_id'] = window_id ctx_dict['name'] = 'help' ctx_dict['title'] = 'Ajuda' code = """ <textarea rows="30" class="small-12 larg...
56f1357166b8b96f69057bab153d3c8d46e95949
68,229
def get_action_html(action): """ Get a html respresentation of the Action :param action: Model, Action model instance :returns: String, html description of an Activity Action """ return render_to_string('action.html', {'action': action})
4fba30d16a5c488db249ec1e416cf8e59153581c
68,230
def ifconfig(): """ :return: network mode (AP/STA), ifconfig tuple """ if NW_IF is None: return '', ("0.0.0.0", "0.0.0.0", "0.0.0.0", "0.0.0.0") nw_mode = 'STA' if_tuple = NW_IF.ifconfig() if if_tuple[0] == if_tuple[2]: nw_mode = 'AP' return nw_mode, if_tuple
a0bb6bf38c993d56801b99a6027f43715b66fce4
68,231
def _postprocess_for_report(usage_types, missing_values, unusual_changes): """Post-process the output of `_detect_anomalies` in order to facilitate composing final e-mails with anomaly reports. """ unusual_changes_ = _filter_out_ack(unusual_changes) anomalies_ = _merge_by_type(usage_types, missing_v...
3387328539634b540302c145eb2c4ad50ca5c951
68,232
from typing import Optional def cache_put_all(connection: 'Connection', cache_info: CacheInfo, pairs: dict, query_id: Optional[int] = None) -> 'APIResult': """ Puts multiple key-value pairs to cache (overwriting existing associations if any). :param connection: connection to Ignite ...
0931e6b118e0861860bc6c10a019a03a89aaffd8
68,233
def get_style(forecolor, bold): """Generate a style for specified forecolor and has bold or not :param forecolor: the name of the forecolor. :param bold: has bold or not. :return: a style, an :class:`XFstyle` object. """ # https://secure.simplistix.co.uk/svn/xlwt/trunk/xlwt/Style.py # https:...
86b806f82480127dd6911c90919cfd140233cd03
68,234
def extract_neighborhoods_distributed( spots, segments, radius, ratio=None, nblocks=10, cluster_kwargs={}, ): """ Distribute ``extract_neighborhoods`` with dask Parameters ---------- spots : string The filepath to the spots data on disk segments : ndarray (e.g. z...
8d1cfa724c5ba921919441501b739c1dda50850a
68,235
def _create_table_query(table_name: str) -> str: """Build SQL query to create metrics table.""" return ( f"CREATE TABLE IF NOT EXISTS {table_name}(" f" id SERIAL PRIMARY KEY," f" page_url TEXT," f" http_code SMALLINT," f" response_time INT," f" time...
427bf61a475c0f012b0242880400d1573ae8bbd1
68,236
def fetch_error_status_from_state_db(port, state_db): """Fetch the error status from STATE_DB and return them in a list. Args: port: the port whose error status will be fetched. None represents for all ports. Returns: A list consisting of tuples (port, description) and sorted b...
bf4d7537202dd9101630831b1a7cef5d789f101b
68,237
import numpy def _get_generators_for_reducing_second_m35(diag_entries_first_m35, einsum_spec, rep_action): """Builds the generators for canonicalizing the 2nd 35-irrep.""" gens = _get_residual_symmetry_of_matrix_diagonal(diag_entries_first_m35) m = numpy.zeros([len(ge...
b9ca2b3d66aab6aaebf055d5724c3716a0e817d8
68,238
def count_instance_attributes(listInst): """Return the number of attributes across all instances, or None if the instances differ in the number of attributes they contain. >>> listInst = [Instance([1,2,3],True), Instance([4,5,6],False)] >>> count_instance_attributes(listInst) 3 >>> count_instance_attributes([In...
8fa925d9900973a1e535e7b5a33d2f5fc1f89009
68,239
def basis_string_pn(basis): """ basis_string_pn(basis) -> name Takes basis specified as tuple (basis_name_p, beta_p, basis_name_n, beta_n) and converts to string for use in filename. """ return "%s-%.3f-%s-%.3f" % basis
3c57bc21314dc944f3025b5e992ec9f6dcb0c1dd
68,240
def to_binary(df, variable_names): """ Recode specified variables of dataframe to binary; any positive value is set to 1 and all other values are set to 0. This replaces the existing column(s). Parameters ---------- df : pandas DataFrame dataframe containing variables to be reco...
604b5a84a7ade73b9e569fa4d238f32e9039acee
68,241
import csv def validate(args, limit_to=None): """Validate an input dictionary for Finfish Aquaculture. Parameters: args (dict): The args dictionary. limit_to=None (str or None): If a string key, only this args parameter will be validated. If ``None``, all args parameters will be ...
8d609f5cef6253a014562c12904e8edc84a03a13
68,242
def id_values_map(dataset_path, id_field_names, field_names, **kwargs): """Return mapping of feature ID to attribute value or tuple of values. Notes: There is no guarantee that the ID value(s) are unique. Use ArcPy cursor token names for object IDs and geometry objects/properties. Args: ...
1fe3568be059ef0090ef37c03dd93d17ae9ded9b
68,243
import time import random import json import os def upload_video(self, video, caption=None, upload_id=None, thumbnail=None, options={}): """Upload video to Instagram @param video Path to video file (String) @param caption Media description (String) @param upload_id Unique upload_id (String)....
387be6f222e79e8edfc905534f169ed219a4bc7b
68,244
from typing import Union from typing import Dict from typing import List from typing import Optional def convert_lat_long(obj: Union[Dict, List, None, str]) -> Optional[Coordinates]: """Convert a coordinate pair as a dict, list, or string into a pair of floats, if valid""" if not obj: return None ...
c19fb908d04650ee8de706db4bb1d936da335dab
68,245
def _separate_sentiment_scores(sentiments): """ want separate positive versus negative sentiment scores""" pos_sum = 0.0 neg_sum = 0.0 neu_count = 0 for sentiment_score in sentiments: if sentiment_score > 0: pos_sum += (float(sentiment_score) +1) # compensates for neutral words that are counte...
f00f812806faae2bcdcb4a2402fdf665bbfa0dcf
68,246
from typing import Optional def download_file(url: str, destination: str, timeout: Optional[int] = None, silent: Optional[bool] = False) -> str: """ Downloads file by given URL to destination dir. """ file_name = get_file_name_from_url(url) file_path = join(destination, file_name...
6da1204f6db15df4d5bc677aea3d3b6f243694ef
68,247
def get_http_body(http_request): """Given a HTTP request, return the body.""" return http_request.split("\r\n\r\n")[1]
4a11c97f0eeddac933e8b311d9c1cfda6e61674c
68,248
def JNMF(data, n_components, init='svd', method='Euclidean', maxIter=10000, verbose=True): """Joint Non-negative matrix factorisation. https://github.com/mstrazar/iONMF/blob/master/ionmf/factorization/model.py for similar Parameters ---------- data : dict, data = { ...
6656d674d0788cf42795f7bb03007484f3ab41c9
68,249
def query_reverse(viewname, kwargs=None, query_kwargs=None): """ Custom reverse to add a query string after the url Example usage: url = my_reverse('my_test_url', kwargs={'pk': object.id}, query_kwargs={'next': reverse('home')}) """ url = reverse(viewname, kwargs=kwargs) if query_kwargs: ...
648912377db3d9f3592731c4956f99b7f5b848ec
68,250
def efficientnet_b4(override_params=None, **kwargs): """ Constructs a EfficientNet-B4 model. """ model_name = 'efficientnet_b4' blocks_args, global_params = get_model_params(model_name, override_params) model = EfficientNet(blocks_args, global_params, **kwargs) return model
1563854aba2e7ba78a53d0edbbb3f06cf231c5f0
68,251
from typing import Type import torch import os def data_generator(data_path: str, config: Type[Config]) -> Type[DataLoader]: """ Generates a dataloader for the dataset. Parameters ---------- data_path: str A string indicating the path to the dataset. config: Config Object Configu...
6c54d7857e734fe5da22ec006898860c9b57206e
68,252
def inf_set_max_ea(*args): """ inf_set_max_ea(_v) -> bool """ return _ida_ida.inf_set_max_ea(*args)
c86134aa293dcd68b699d673eeaffa9994d34366
68,253
import numpy def column_period(c:numpy.ndarray, thresh:int=0): """ Guess the periodicity of a column of (image) data Parameters ---------- c : ndarray Column of data (e.g. pixel values) thresh : int Optional threshold (default: 0) Returns ------- p : int (or float...
0f6821832f4e6309da8e8130de27ba9eb7fbf5d4
68,254
import os def find_package_datafiles(package_dir): """ Return a list of non-python files in package source tree File paths are relative to the top of the package directory provided. """ # TODO: Add exclusion list/glob/regex parameter if necessary. non_python = set() for dirpath, _, fnames in ...
e99eaf03a437f0e701326a4d9ea2a3079a6027cb
68,255
def parse_gn_flags(gn_lines): """ Parse lines of GN flags into dictionary """ gn_args = {} for line in gn_lines: name, var = line.strip().partition("=")[::2] gn_args[name.strip()] = var.strip() return gn_args
98d8f91e9defea1484a569deb70fb7cc62b2c743
68,256
def swap_suits(cards): """ Swap suits to remove most symmetries. """ cards_need_swap = cards new_suit = 5 while cards_need_swap.shape[0] > 0: suit = cards_need_swap[0,1] cards[cards[:,1] == suit, 1] = new_suit new_suit += 1 cards_need_swap = cards[cards[:,1] < 5] ...
53b60a6719d7dcb9c1b0b74345f331536e77e0fe
68,257
import sys def apply_global_fixes(source, options): """Run global fixes on source code. Thsese are fixes that only need be done once (unlike those in FixPEP8, which are dependent on pep8). """ for (code, function) in global_fixes(): if code_match(code, select=options.select, ignore=optio...
277f59feb3df703afa5688741ee09c91149e8c74
68,258
def DeleteNode(pListHead, pToBeDeleted): """ 在O(1)时间内删除链表结点 :param pListHead: :param pToBeDeleted: :return: """ if not pListHead or not pToBeDeleted: return None if pToBeDeleted.next_ != None: # 要删除的节点后有节点 pToBeDeleted.val = pToBeDeleted.next_.val pToBeDe...
41bfc3ed1c0d6a2eb796e2d4e2170888a907367c
68,259
def st_status(user): """ Displays the status text. """ return get_st_context(user)
e5112dfcb9c7bb2c316c15a34fdc195718686da7
68,260
def validate_cnpj(cnpj, autopad=True): """Check whether CNPJ is valid. Optionally pad if too short.""" cnpj = clean_id(cnpj) # all complete CNPJ are 14 digits long if len(cnpj) < 14: if not autopad: return False cnpj = pad_cnpj(cnpj) elif len(cnpj) > 14: return ...
41afd824310c92e75bb9ac0bb9ea4537e274f99d
68,261
def make_ps_model(src_vocab, tgt_vocab, emb_size=256, hidden_size=512, dropout=.3, pad_idx=0, embedding_matrix=None): """ Create pointer softmax seq2seq model from given parameters and pass it to GPU """ if embedding_matrix is not None: err_msg = 'Embedding matrix has inconsistent dimensions' ...
ee6dbf0837acf530bfd8c35f2d40c4a70235043a
68,262
import json def get_segment_data_marker(segment, with_marker=None): """ Get openpype track item tag created by creator or loader plugin. Attributes: segment (flame.PySegment): flame api object with_marker (bool)[optional]: if true it will return also marker object Returns: di...
cf37d624fd7a0765c4616b5848418f4719035c21
68,263
def orthogonal(shape, scale=1.1, name=None): """ From Lasagne. Reference: Saxe et al., http://arxiv.org/abs/1312.6120 """ flat_shape = (shape[0], np.prod(shape[1:])) a = np.random.normal(0.0, 1.0, flat_shape) u, _, v = np.linalg.svd(a, full_matrices=False) # pick the one with the correct sh...
93122ef41c3278012860ec715f92abaab40c9653
68,264
def cqt_to_mcft(sig_cqt,fbank_scale_rate): """ This function receives the time-frequency representation (CQT) of an audio signal (complex in general) and generates a 4-dimensional representation (scale,rate,frequency,time) by 2d filtering based on the cortical part of Chi's auditory model. Inpu...
d109efd60373a478dbb18fb0bf8b05b21152e510
68,265
def relbw_pdf_func(x, m, gamma): """Calculate the relativistic Breit-Wigner PDF. Args: x: value(s) for which the CDF will be calculated. m: Mean value gamma: width Returns: `tf.Tensor`: The calculated PDF values. Notes: Based on code from this [github gist](...
135dd085c4e30bd3e9b20516d14c695e4bc5d3f4
68,266
async def http_get(app, url, params=None): """ Helper function - async HTTP GET """ log.info(f"http_get('{url}')") client = get_http_client(app, url=url) url = get_http_std_url(url) status_code = None timeout = config.get("timeout") # TBD: use read_bufsize parameter to optimize read...
f5194fc4762912d72f80058f0ac14694978b1572
68,267
def partition_index(is_missing: np.ndarray) -> np.ndarray: """ Reshuffle the index with index of observed measurement first. For example: is_missing = [True, False, True, False] partition_index(is_missing) returns: np.array([1, 3, 0, 2]) Parameters: ---------- is_missing : li...
dccc6b7e74a90958480ee7408919b4fd0a216d4d
68,268
from typing import Dict def _lower_to_native_backend( model: QuantizedGraphModule, qconfig_map: Dict[str, QConfigAny] ) -> QuantizedGraphModule: """ Lower a quantized reference model (with reference quantized operator patterns) to the native backend in PyTorch (fbgemm/qnnpack), both backends shares th...
4ce101fce1d0f372518cae6e10aec615c8e60108
68,269
def from_json(data: JsonDict) -> AttributeType: """Make an attribute type from JSON data (deserialize) Args: data: JSON data from Tamr server """ base_type = data.get("baseType") if base_type is None: raise ValueError("Missing required field 'baseType'.") for primitive in Primit...
0d85ee57ca148607f0d19501377c52a82df5f558
68,270
from typing import Iterable from typing import Callable from typing import Union from typing import Tuple def group_and_apply( df: pd.DataFrame, group_by_cols: Iterable[str], apply_fn: Callable, output_meta: Union[pd.DataFrame, pd.Series, dict, Iterable, Tuple], num_dask_partitions: int=1, use...
9e78526877dd3d91eed7852312f61e663c89d29e
68,271
from wmiexec import WMIEXEC from wmiexec import WMIEXEC def execute_cmd( cmd_str, ipaddr, username, password, download_url, domain="", share="ADMIN$", noOutput=False, ): """execute command""" try: except ImportError: download_file(download_url + "/wmiexec.py") ...
bf8dc66baebcb721c9cf47519d5e521fa0d764fb
68,272
import os import tarfile import zipfile def open(path): """Auto-detects the type of PATH and returns an instance of the appropriate class.""" path = os.path.realpath(path) if not os.path.exists(path): raise IOError("No such file or directory: '%s'" % path) elif os.path.isfile(path): ...
748a4b96807588371ce10536f5f00dc65d9e0423
68,273
def dist_score(param_list, meta): """ Measure delta between USE endcodings Param 1 - First encoding from text Param 2 - Second ecoding from text """ # data = { # 'op': 'dist_score', # 'encoding': [param_list[0], param_list[1]] # } # return USE_API.post(data)['score'] ...
8aadbf024ef0cf03d3c8b9539f170023390f9951
68,274
from typing import Tuple def scale_minmax(x: np.ndarray, xrange: tuple = None) -> Tuple[np.ndarray, bool]: """ Minmax scaling to [0,1]. Parameters ---------- x Numpy array to be scaled. xrange Tuple with min and max data range. Returns ------- Scaled array and boo...
5186c0a8f0ab039599b622fa0f6f619597838bd7
68,275
def procrustes_align(base_embed, other_embed): """ Align other embedding to base embeddings via Procrustes. Returns best distance-preserving aligned version of other_embed NOTE: Assumes indices are aligned """ basevecs = base_embed.m - base_embed.m.mean(0) othervecs = other_embe...
88773c1bc1939ddb2811e0622315a76d9d39775f
68,276
def format_wal_properties(body: Json) -> Json: """Format WAL properties. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result: Json = {} if "allowOversizeEntries" in body: result["oversized_ops"] = body["allowOversizeEntries"] if "logfil...
7e9b7b2a1a4b69a7d2ca2dfb93938b5121149c90
68,277
def model_fn(features, labels, mode, params): """Estimator のためのモデル定義メソッド # メソッドの構成は以下のとおり # 1. Keras の Functional API 経由でモデルの設定を記述 # 2. Tensorflow を使って,学習・評価時の損失関数を定義 # 3. Tensorflow を使って,学習時のオペレータ・オプティマイザを定義 # 4. Tensorflow の tensors として予測値を取得 # 5. 評価用のメトリクスを生成 # 6. 予測値・損失関数・学習オペ...
361b129513843700da179b6b7b9f9471a8f004ea
68,278
def forcing_accumulator(temperature): """ The accumulated forcing for each observation and doy in the (obs, doy) array. """ return temperature.cumsum(axis=0)
4813d7cb019001b038ef71c143c9e3db696af9ca
68,279
import os def build_mml_matrix_functions(): """Build the mml linear algebra library""" name = '_matfuncs_sq3' mfuncs_pyf = os.path.join(ext_support_dir, 'matrix_funcs.pyf') mfuncs_f90 = os.path.join(ext_support_dir, 'matrix_funcs.f90') dgpadm_f = os.path.join(ext_support_dir, 'dgpadm.f') sourc...
b533f14d527947ad77d232c917c85aa015d01523
68,280
import base64 def FormatVariable(message, output_value=False): """Returns the variable message as a dict with a shortened name. This method first converts the variable message to a dict with a shortened name and an atomicName. Then, decodes the variable value in the dict if the output_value flag is True. ...
844a31c5778896520393c2c18ec2887b3d9a8004
68,281
def _make_body_from_sub_request(sub_request): """ Content-Type: application/http Content-ID: <sequential int ID> Content-Transfer-Encoding: <value> (if present) <verb> <path><query> HTTP/<version> <header key>: <header value> (repeated as necessary) Content-Length: <value> (newli...
c0abceabd8e0047326e0ab2f5e30f6e7dcd4702f
68,282
def floor(x,unit=1): """ Returns greatest multiple of 'unit' below 'x' """ return unit*int(x/unit)
b289bf714eb3ecf23072533a51badeac43743686
68,283
import six import json def http_response_json(dict_data, encoding='utf-8'): """ 返回json数据 :param encoding: :param dict_data: :return: """ # ensure_ascii=False,用来处理中文 try: if six.PY3: # if isinstance(dict_data, binary_type): # dict_data = ...
543993c2a3ade164ee138dfd66c06bcef3db0cfd
68,284
def gen_vault_response_kv1(file_contents): """ Provides the vault response for a given processed configuration file """ def _gen_vault_repsonse(file_contents=file_contents, secret_key=""): if secret_key != "": vault_response = {"data": {secret_key: file_contents}} else: ...
fa9fdda0ac28d2bea2cea4bb4fd24456c1013c2d
68,285
def active_contour_loss(gt, pr, w_region=1.0, w_region_in=1.0, w_region_out=1.0): """ length term """ x = pr[:,1:,:,:] - pr[:,:-1,:,:] y = pr[:,:,1:,:] - pr[:,:,:-1,:] delta_x = x[:,1:,:-2,:]**2 delta_y = y[:,:-2,1:,:]**2 delta_u = K.abs(delta_x + delta_y) length = K.mean(K.sqrt(d...
161beb5a56c5a817cd14e860b1843baabb709c60
68,286
import requests def get_repository(repo_name): """ Fetches a github repository. Receives a repository full name. E.g. 'h3nnn4n/garapa' """ auth = get_auth() result = requests.get( f'https://api.github.com/repos/{repo_name}', auth=auth ) rate_limit_update(result.header...
766f6d2fbf065750ce0167be4cb830020caa8cd8
68,287
import functools def firmware_command(fn): """Check if we are in the firmware before running commands that require it.""" @functools.wraps(fn) def _decorated(self, *args, **kwargs): # if self.status != 'firmware': # # Note: we could instead reset_to_firmware here. # raise Bli...
6941c0a755a208c8fbd7860c716bd2dc6848546f
68,288
import os def _guess_isdir(path: str) -> bool: """ Guess if a path is a directory without performing network requests """ if _is_local_path(path) and os.path.isdir(path): return True elif (_is_google_path(path) or _is_azure_path(path)) and path.endswith("/"): return True return...
61aa11d1103f579be9e449e9ecf67cc3558ebce3
68,289
def have_encoder_for_format(format_id: HeifCompressionFormat) -> bool: """Wrapper around `libheif.heif_have_encoder_for_format`""" return lib.heif_have_encoder_for_format(format_id)
813bf400bde9d5760357ffcfb34de21bc6dfb6fd
68,290
def process_path_for_cand(path, docsents): """ processing the paths for a candidate :param path: :param docsents: :return: """ he_docidx = path['head_ent_docidx'] he_doc_len = get_doc_len(docsents, he_docidx) he_ent_loc_dict = path['head_ent'] he_locs = [] he_words = list(he_...
5998432f69b34f24a85fae25b9fb41d7871e0008
68,291
def ijkl2MN(ijkl): """ Convert (i, j, k, l) indices of a symmetric 4nd-order tensor to its matrix index """ ij = ijkl[:2] kl = ijkl[2:] M = ij2M(ij) N = ij2M(kl) return M, N
6a9630fb386e1b40bb02e7337150bd1c3154b788
68,292
def extract_references(fileName): """Runs the extraction engine over a single file, specified by its name (full or relative path). 1. Convert the PDF to a plain text document 2. Extract references from the text Returns the references """ print "Converting PDF to plain text..." docu...
ecf3518d438259a03551d14d8177a42fa9263c5e
68,293
import hashlib import io def calculate_file_checksum(path): """ Calculate the MD5 sum for a file: Read chunks of a file and update the hasher. Returns the hex digest of the md5 hash. """ hasher = hashlib.md5() with io.FileIO(path, 'r') as fp: while True: buf = fp.read(6...
6bddfd83a8bc326fcfea8fb69affde45f3cb1dd8
68,294
import torch def get_position(lens, maxlen, left_pad=False): """ transform sequence length to a series of positions. e.g., 3 -> 1,2,3""" batch_size = lens.size(0) pos = torch.zeros((batch_size, maxlen), dtype=torch.long, device=lens.device) for i, input_len in enumerate(lens): if not left_pad:...
48c2ac5c0bde1f554b3b44c82177945ab2c667ab
68,295
import os def generate_base(path: str) -> str: """ Convert path, which can be a URL or a file path into a base URI :param path: file location or url :return: file location or url sans actual name """ if ':' in path: parts = urlparse(path) parts_dict = parts._asdict() parts...
42d06e35bf86e21a591de2e9b5463cd0b75fb3e0
68,296
from typing import Iterable from typing import Optional from typing import TextIO from typing import List import sys def handle_facts( facts: Iterable[Fact], output_format="json", output_filehandle: Optional[TextIO] = None, ) -> List[Fact]: """ Handle a list of facts and format and validate all f...
8b4f0c3e4c984c484b42011661ca405df828e0bb
68,297
def memoize(fn): """ args and kwargs to fn must be hashable. """ cache = {} @wraps(fn) def wrap(*args, **kwargs): if args: key_args = frozenset(args) else: key_args = None if kwargs: key_kwargs = frozenset(kwargs.items()) else:...
8f82a92b5edd1e7197395887e4519830f4b04d4b
68,298
import json def allPickupBySite(): """ Récupère la liste de tous les pickup associé au site d'idSite Args: request.form doit contenir : - idSite Returns: code 1, data : data contient la liste des pickup code -1, message : erreur lors de la récupéra...
b04bdc6d04493bc8e57c861193225da1f1569e65
68,299