content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def calc_pair_scale(seqs, obs1, obs2, weights1, weights2):
"""Return entropies and weights for comparable alignment.
A comparable alignment is one in which, for each paired state ij, all
alternate observable paired symbols are created. For instance, let the
symbols {A,C} be observed at position i and {A... | 43386ead1c621f265ed95662d78b817c378e1875 | 43,410 |
from typing import Dict
from typing import Any
def get_xml_config_gui_settings(xml_dict: Dict[Any, Any]) -> Dict[Any, Any]:
"""
Get the tool configuration from the config XML.
Parameters
----------
xml_dict: OrderedDictionary
Parsed XML Tool configuration
Returns
-------
Orde... | a13168d8441093f8fb6ce341fd07c5e51d4169a7 | 43,411 |
def deduplicate_list(list_with_dups):
"""
Removes duplicate entries from a list.
:param list_with_dups: list to be purged
:type lost_with_dups: list
:returns: a list without duplicates
:rtype: list
"""
return list(set(list_with_dups)) | 7034f1d8533613f9478916ce7f4b18fd9f94bfe4 | 43,412 |
def get_safe_name(name: str) -> str:
"""Returns the safe version of a username."""
return name.lower().replace(' ', '_') | b08cfca3c8855f41074ec8fdbba8ff520fe42103 | 43,413 |
import json
def ImportExcel(request, **response_kwargs):
"""Receives excel, outputs json"""
o = []
if request.method == 'POST':
form = FileUploadForm(data=request.POST, files=request.FILES)
if form.is_valid():
workbook = xlrd.open_workbook(file_contents=request.FILES['file_sour... | 63fa3ffb29012f98d4a4fed2e197dd96cc7efc4e | 43,415 |
def adjust_factor(x, x_lims, b_lims=None):
"""
:param float x: current x value
:param float x_lims: box of x values to adjust
:param float b_lims: bathy adj at x_lims
:rtype: float
:returns: b = bathy adjustment
"""
if b_lims is None:
return 0
if x < x_lims[0] or x > x_lims[... | b0f92eef6098894fa54a3a3ed55fc01b7f6dae95 | 43,416 |
def init_operation(mocker):
"""Fixture to initialize an operation."""
mocker.patch.object(logoutput.LogOutput, "__init__", lambda x, y: None)
def _create():
return logoutput.LogOutput(None)
return _create | 2e6dfa3c682352f6e4dadf1a0336330500bc1d26 | 43,417 |
from typing import Dict
from typing import Tuple
from typing import Any
def get_best_currencies(currency: str) -> Dict[str, Tuple[str, Any]]:
"""Get best sell and buy rates for available banks"""
parser_classes = get_parser_classes()
parsers = [parser(cache=default_cache) for parser in parser_classes
... | 5a303f825f392f794c332bb90178f7fea27421e6 | 43,418 |
def bellman_ford(*args):
"""
bellman_ford(int const num_rows, int const [] Ap, int const [] Aj, int const [] Ax, int [] x, int [] z)
bellman_ford(int const num_rows, int const [] Ap, int const [] Aj, float const [] Ax, float [] x, int [] z)
bellman_ford(int const num_rows, int const [] Ap, int const [] ... | a7f31d9d42d6a6f5825daf9f92aa7439c004a547 | 43,419 |
import numpy
def calc_LS_displacement(cor, Lval, Lvec, Lrho, Lpitch, position, prob):
"""Returns the amount of rotational displacement from L for an atom at the
given position.
"""
Lrot = Gaussian.GAUSS3C[prob] * calc_rmsd(Lval)
Lorigin = cor + Lrho
D = AtomMath.dmatrixu(Lvec, Lrot... | 980319ea617ea7e220217f8c298278208dc56b86 | 43,420 |
from typing import Optional
from typing import List
def get_all_enabled_by_role(
*, db_session, role: ParticipantRoleType, project_id: int
) -> Optional[List[IncidentRole]]:
"""Gets all enabled incident roles."""
return (
db_session.query(IncidentRole)
.filter(IncidentRole.enabled == True)... | ff9b40fbed692f5231d2107c9f696a0a04cc78eb | 43,421 |
def update_eigensystem(L, U, v, sigma):
"""
Perform rank one update to eigensystem. Requires the eigenpairs to be
ordered
Parameters
----------
L : numpy.ndarray, 1d
Current eigenvalues
U : numpy.ndarray, 2d
Current eigenvectors
v : numpy.ndarray, 2d
Column vecto... | b6530bbb484de5d85f83d3db7114cf2edfaa7b4f | 43,422 |
def is_cooled_down(token: str, event_type='normal', **kwargs) -> Rule:
"""
检查冷却事件是否已经结束的规则。如果仍在生效则为 `False`,反之为 `True`。
参数:
- `token: str`:事件标签。
关键字参数:
- `type: str`:事件类型,默认为 `normal`。包括:
- `global`:全局冷却事件;
- `group`:群组冷却事件,需要额外的关键字参数 `group: int` 指定群组 ID;
- `normal`:一般... | 0b61443e1fbed4eb2a4b258665dba341ea34cece | 43,423 |
from scipy.sparse import coo_matrix
from scipy.sparse.linalg import spsolve
def solve(c4n,n4e,n4db,ind4e,f,u_D,degree):
"""
Computes the coordinates of nodes and elements.
Parameters
- ``c4n`` (``float64 array``) : coordinates for nodes
- ``n4e`` (``int32 array``) : nodes for elements
- ``n4db`` (``int32 ar... | b1cbe5c88f2dcab813d7d0a3cf6e5edcf5c1b1a2 | 43,424 |
def is_empty_element_tag(tag):
"""
Determines if an element is an empty HTML element, will not have closing tag
:param tag: HTML tag
:return: True if empty element, false if not
"""
empty_elements = ['area', 'base', 'br', 'col', 'colgroup', 'command', 'embed', 'hr',
... | 429129246c7458f0928f22f8b99db03763c2b699 | 43,425 |
def bad_request(error):
"""Redirect all bad requests."""
results = {
"message": HTTPStatus.BAD_REQUEST.phrase,
"status-code": HTTPStatus.BAD_REQUEST,
}
return results | d4c5767fe96ef15bfda4c3bfadcb2a50a36f519c | 43,426 |
def get_outlier_definition(biomarker):
"""
Centralised definitions of biomarker outliers for filtering
"""
if biomarker == "APHalfWidth":
outlier_definition = 100.0 # ms
else:
raise ValueError(f"Biomarker {biomarker} not found.")
return outlier_definition | 27876fd83c644d7c4f751b99ab2703044e54f41d | 43,427 |
def _symbol(s, matching_symbol=None):
"""Return s if s is a Symbol, else return either a new Symbol (real=True)
with the same name s or the matching_symbol if s is a string and it matches
the name of the matching_symbol.
>>> from sympy import Symbol
>>> from sympy.geometry.util import _symbol
>... | 019ebeba151eb31c879ba0a89e969651dfec24dd | 43,428 |
def code_to_string(code: StatusCode) -> str:
"""
Args:
code (StatusCode): a value from the StatusCode enumeration
Returns:
str: A string explanation of the error
"""
if code == StatusCode.OK:
return "OK"
elif code == StatusCode.TensorLoadFailure:
return "Error: fa... | 3bb8ccc354acb968f1cfd9f028b936d62fe9efb7 | 43,429 |
def recurse_filestats(dir: PathLike, *, channel: Channel = None) -> Channel:
"""
Starts a worker thread that finds all files in `dir` (recursively) and
writes them to a :obj:`Channel`. Each file found is written as a
:obj:`FileStats` object.
:param dir: The directory to search.
:param channel: ... | f5c904d5fcc3d12fec32340927001239cc09f4cb | 43,431 |
def correl(df,periods=21,columns=None,include=True,str=None,detail=False,how='value',**correl_kwargs):
"""
how : string
value
pct_chg
diff
"""
def _correl(df,periods=21,columns=None,include=True,str=None,detail=False,**correl_kwargs):
study='CORREL'
df,_df,columns=validate(df,columns)
_df['CORREL']... | e22ec0b13aa0c5b0d4594a9ede7efb3594d58d5c | 43,432 |
def silhouette_score_inner_loop(i, cluster_ids, cluster_labels, all_pcs):
"""
Helper to loop over cluster_ids in one dimension. We dont want to loop over both dimensions in parallel-
that will create too much worker overhead
Args:
i: index of first dimension
cluster_ids: iterable of clus... | 9d6ba457ace5ec2204c5805b56303fedf224c496 | 43,433 |
def problem_5_14_9(scalars, vectors):
"""
Problem c cutoff in Kindle edition. Using value from Coursera course:
https://github.com/jimcarson/Coursera/blob/master/CodingTheMatrix/hw12_basis_problems/The_Basis_problems.py#L118
>>> zero_vec_4 = zero_vec_n(4)
>>> a_vectors = list_of_lists_to_vecs([[one... | edc83e7933d195768ea4742ac6112ecf1847c9f6 | 43,434 |
from typing import Tuple
from typing import Union
def get_csv(url: str, comment_prefix: str = None, **kwargs) -> Tuple[pd.DataFrame, Union[bytes, None]]:
"""Remove comments in csv-like files.
But unlike pandas.read_csv, this function only removes comments at the beginning of the file.
Args:
url (... | 02a9a9e10762c2b6ab812fd7584eb0b289f8253e | 43,435 |
def start_all_harvesters(request):
"""
This function starts all harvesters.
:param request: the request
:return: an HttpResponseRedirect to the Main HCC page
"""
harvesters = Harvester.objects.all()
for harvester in harvesters:
if harvester.enabled:
api = InitHarvester(h... | 61137a8ce0de51e72b63ef8ba639537a434cc76d | 43,436 |
def get_incident_message_ids(client, incident_id):
"""
Returns the message ids for all the events for the input incident.
"""
detail_response = client.get_incident_details(incident_id)
message_ids = []
# loop through all the events of this incident and collect the message ids
if 'events' in... | 3067eb438effb2977fd3a724a284bd58f485b743 | 43,437 |
def _Dirname(path):
"""Returns the parent directory of path."""
i = path.rfind("/") + 1
head = path[:i]
if head and head != "/" * len(head):
head = head.rstrip("/")
return head | 075063a6dd29456f4adb969621d9727aa187d53b | 43,438 |
def unshare_resource_with_user(request, shortkey, user_id, *args, **kwargs):
"""this view function is expected to be called by ajax"""
res, _, user = authorize(request, shortkey, needed_permission=ACTION_TO_AUTHORIZE.VIEW_RESOURCE)
user_to_unshare_with = utils.user_from_id(user_id)
ajax_response_data =... | c9954ef84145ca103c35d74115aedd65f594efaa | 43,439 |
def coords_distance(coords0, coords1):
""" Euclidean distance between two coordinates """
total = 0
for x0, x1 in zip(coords0, coords1):
total += (x0 - x1) ** 2
return sqrt(total) | 4b15748d83c0c44e194c1af55e7553f9111c1b14 | 43,440 |
def create_url(artist, song, language):
"""Create the URL in the LyricWikia format"""
url = __BASE_URL__ + '/wiki/{artist}:{song}'.format(artist=urlize(artist), song=urlize(song))
if language:
url += '/{language}'.format(language=urlize(language).lower())
return url | c8531cf6db71bd9e1d93ec147e1a09788d00aacd | 43,441 |
def bound_free_absorption(wavelength_um, temperature):
"""bound free absorption of H-
Note:
alpha has a value of 1.439e4 micron-1 K-1, the value stated in John (1988) is wrong
"""
# here, we express alpha using physical constants
alpha = CONST_C*CONST_H/CONST_K*10000.0
lambda_0 = 1.... | 8df6c50301e7f51be3d84cdbf195bb0b05c686cd | 43,443 |
import numpy
def get_representative_time_series(path_to_irf: PathLike) -> numpy.array:
"""
Extract a time series from a representative voxel in the occipital pole.
Args:
path_to_irf (PathLike): Path to the IRF image.
Returns:
numpy.array: Vector containing time series of voxel from o... | b500469559a2860b6577798bfcdfd6a2fcb70af4 | 43,444 |
def outlierCleaner(predictions, ages, net_worths):
"""
Clean away the 10% of points that have the largest
residual errors (difference between the prediction
and the actual net worth).
Return a list of tuples named cleaned_data where
each tuple is of the form (age, net_worth... | 7ceaab7c3f8b301b688eb144bbbd511248bd3f05 | 43,445 |
import torch
def test_unit_Validators__validate_training_data(custom_models_simple_training_data_4elements, monkeypatch):
"""
unit test __validate_training_data. Use monkeypatching for embedded call to Validators.__validate_num_covars.
"""
# initialize the class
cls = Validators()
# data
... | 62391505605ef011ffb0f6f8792374496c6a1605 | 43,446 |
def retrieve_context_connectivity_service_end_point_end_point_by_id(uuid, local_id): # noqa: E501
"""Retrieve end-point by ID
Retrieve operation of resource: end-point # noqa: E501
:param uuid: ID of uuid
:type uuid: str
:param local_id: ID of local_id
:type local_id: str
:rtype: Connect... | 6691970f791fce27609caf4f6e144eff7e8770cc | 43,447 |
def IsLoopExit(op):
"""Return true if `op` is an Exit."""
return op.type == "Exit" or op.type == "RefExit" | dbc24fa0efa69447416963a9911c7fae3fd1f244 | 43,448 |
import json
from datetime import datetime
def update_covid_data(name="covid update", repeat=False, is_both=False) -> None:
"""Updates all relevant data for the index template and stores it in CSV files.
:param name: User-defined name of the update. defaults to 'covid update'.
:param repeat: Boolean varia... | f54fcc0f39836e6cc7b673668191ceca237c83bd | 43,449 |
def _get_fallback_text(data: Data) -> str:
"""Get a fallback text from data."""
return data.get("text/plain", "Image") | 73e5c99424a1cf5b9ef49ccb4a5cc3abcea5a802 | 43,452 |
import typing
def decode_cl_value(obj: typing.Union[dict, str]) -> CLValue:
"""Decodes a CL value.
"""
cl_type = decode_cl_type(obj["cl_type"])
as_bytes = bytes.fromhex(obj["bytes"])
if isinstance(cl_type, (CLType_Simple, CLType_ByteArray, CLType_Option)):
parsed = byte_array_decoder(cl_t... | 64a0bbf731f7341b2356a9d1ad3d0e2c850c5058 | 43,453 |
def probability_sum_weight(probability, token_frequency, n, word, alpha, original_tokens, top_expansion, wv):
"""Assigns weighted score to document based on summation of probabilities.
Args:
probability (float): Previously calculated probability.
token_frequency (float): Number of appearanc... | 375b827808616ee142ac9d864b2f88cb2e465a6d | 43,454 |
def _make_builder_configs():
"""Construct a list of BuilderConfigs.
Construct a list of CityscapesCorruptedConfig objects, corresponding to
the corruptions in _CORRUPTIONS and 5 severities.
Returns:
A list of CityscapesCorruptedConfig objects.
"""
config_list = []
for corruption in _CORRUPTIONS:
... | 9b87f605b95a2f14089873e21a53b86e2dd67206 | 43,455 |
import torch
def validation_early_stopping(model, device, valid_loader):
"""
Evaluates the validation set. This is done during early stopping.
Parameters
----------
model : PyTorch model class
device : device
Options are torch cpu or cuda.
valid_loader : Dataloader
Da... | 05bd9802b61eb6c217c7c2f9d4dc44fc5bc2df0c | 43,456 |
def islazy(f):
"""Internal. Return whether the function f is marked as lazy.
When a function is marked as lazy, its arguments won't be forced by
``lazycall``. This is the only effect the mark has.
"""
# special-case "_let" for lazify/curry combo when let[] expressions are present
return hasattr... | 7dd0a09f6a0e60b252ece344d62a937393598167 | 43,457 |
def wind12():
"""Sends all 12 hour wind forecasts.
Returns:
str: JSON response.
"""
return util.returnMany({'type': 'WINDS_12_HR'}, request) | bc553e4a0d4bba495ba7cb5b6c76e3b9e363b9dd | 43,458 |
def transform_data(df, mva=30):
"""
This is for scaling the original data for use in machine learning.
Takes a numpy array as input, divides by a moving average with period mva (integer),
and returns the scaled data as well as the scaler
and moving average (needed for returning the data to its orig... | 86fa4f5f204800e2d19f8e766568b409077269d2 | 43,459 |
import itertools
def _pop_complex_predicates(args):
"""
Compute the cartesian product of "accept" and "content_type"
fields to establish all possible predicate combinations.
.. seealso::
https://github.com/mozilla-services/cornice/pull/91#discussion_r3441384
"""
# pop and prepare in... | c920773987eccae01be23cdee9a4ebe5f33e1243 | 43,462 |
def cifar10_fp_net_resnet23_prediction(image, maps=64, n=8, delta=2**-4,
test=False):
"""
Construct FixedPointNet using resnet23.
"""
# Residual Unit
def res_unit(x, scope_name, dn=False):
C = x.shape[1]
with nn.parameter_scope(scope_name):
... | b5f924e2cd2ccacbe3b3f7ad9c32681bbb11b7a5 | 43,463 |
def _get_agenda_event_range():
"""Get times from now until the end of the day."""
start = now_tz()
stop = end_of_day_tz()
_logger.info("agenda range: %s - %s", start.isoformat(), stop.isoformat())
return start.isoformat(), stop.isoformat() | 33171633f9f77e8faa67048f181bf395419cdfc4 | 43,464 |
def _fake_networks(network_count, tenant_id):
"""id is the id from melange
network_id is the id from quantum. Dumb"""
return [{'id': str(uuidutils.generate_uuid()),
'name': 'net%d' % i,
'network_name': 'qnet%s' % i,
'cidr': '10.0.0.0/8',
'network_id': str(... | b3ccc4295521729259507dc40c0b402c4d4435d9 | 43,465 |
import math
def oligoTm(seqobj):
"""
Takes either a SeqRecord object, a Seq object, or a string
and computes the melting temp based on the NN model (yes?).
This is Kun's code
CHECK THE NN PARAMETERS
From Uri Laserson
"""
if isinstance(seqobj,SeqRecord):
seq = str(seqo... | cd9c6b197442a9fd8e9c38f2f516e0f89b19e398 | 43,466 |
def _helper(node: BST, target: int, diff: int):
"""
:param node:
:param target:
:param diff:
:return:
"""
if node is None:
return diff
val = node.value
new_diff = abs(val - target)
if abs(diff - target) > new_diff:
diff = val
a = _helper(node.left, target, di... | b9fd6fb22103339f409a9cc9193708351673114a | 43,467 |
import torch
def compensation(module_name: str, original_weights_2: torch.Tensor,
scaling_matrix: torch.Tensor) -> torch.Tensor:
"""
[Inputs]
original_weights_2: (N[i+2], N[i+1], K, K)
scaling_matrix: (P[n+1], N[i+1])
[Outputs]
new_weights_2: (N[i+2], P[i+1])
"""
if mo... | c808cfa41ffcdb3690414c9b040298f6b810c233 | 43,468 |
import time
def cookRedirectObject(repos, db, cfg, recipeClass, sourceVersion, macros={},
targetLabel = None, alwaysBumpCount=False,
ignoreDeps = False):
"""
Turns a redirect recipe object into a change set. Returns the absolute
changeset created, a list of the name... | 46650acca03e64c2acbb9f8219c5eb6fece882ad | 43,469 |
def obter_ganhadores(tab):
"""
Obtem os jogadores que fizeram 3 em linha.
:param tab: tabuleiro
:return: tuplo
Recebe um tabuleiro e retorna um tuplo com as pecas dos jogador(es) que ganharam o jogo.
Caso nao haja nenhum jogador ganhador, a funcao retorna um tuplo com uma peca vazia.
"""
... | 0b8569343c952eebf233d5389b02e7cef06a5ec6 | 43,470 |
import secrets
def login():
"""
Handles login of a user and returns a session_token if supplied password and username is correct.
Token and Username needs to be supplied with every request in order to access restricted routes.
Example:
{
"username": "Chris",
"token": "0e45b5df2e6c42ae9b69... | 89d5d8bb561a840d28c12fcbdb5d61a19f680563 | 43,471 |
import time
def screen_refurbs_deglassing_batch_complete():
"""This route is for processing refurb completions, generating associated reports and adding to stock'"""
start_time = time.time()
webhook = flask.request.get_data()
# Authenticate & Create Object
data = monday_handshake(webhook)
if ... | 4793a3427c341fc1a35b23dd65d8e546d4f942f5 | 43,472 |
import csv
def get_csv_header(data_location,
delimiter):
"""Gets the CSV header from the input files.
This function assumes that the header is present as the first line in all
the files in the input path.
Args:
data_location: Glob pattern(s) specifying the location of the input data
... | f108e419fb824304ec9991ff6fd031a45248f721 | 43,473 |
import requests
import json
def get_stats(stats_type):
"""[Get statistic by type from bind]
Arguments:
stats_type {[String]} -- [Type of statistic]
Returns:
[dict] -- [statistic value get follow input type]
"""
url = "http://{}:{}{}".format(
BIND_CONFIGURATION["host"],
... | fd2d82e35c47234b874f9af8be58c436b0346beb | 43,474 |
import logging
def pack_dataframe(dt_targ, times, paths,
history=HISTORY,
tol_time=TOLERANCE_TIME_SEC,
):
"""Export a pandas dataframe to extract background.
DataFrame contains the time, the relative path to the
original filename (including its par... | 47fa950c0127b4b20b4313c8f5c0509ccf596d4c | 43,475 |
def _sample_ncols(col_limits, random_state):
""" Sample a valid number of columns from the column limits. """
integer_limits = []
for lim in col_limits:
try:
integer_lim = sum(lim)
except TypeError:
integer_lim = lim
integer_limits.append(integer_lim)
re... | e31f2e290910b9e7376750b18a6ca6436a82a0cb | 43,480 |
def resamb_lambda(nav, sat):
""" resolve integer ambiguity using LAMBDA method """
nx = nav.nx
na = nav.na
xa = np.zeros(na)
ix = ddidx(nav, sat)
nb = len(ix)
if nb <= 0:
print("no valid DD")
return -1, -1
# y=D*xc, Qb=D*Qc*D', Qab=Qac*D'
y = nav.x[ix[:, 0]]-nav.x[ix... | 1ca9c18730b6ab69ca49b300523f8308ec14edd8 | 43,482 |
def handle_list_datasets_by_run_id(project_id,
experiment_id,
run_id,
operator_id):
"""Handles GET requests to /."""
accept = request.headers.get('Accept')
application_csv = False
if accept and 'appl... | c0b78c772d0fc771d4eae2f061e1ff31c87251d9 | 43,483 |
def smiles_to_seq(smiles, seq_length, char_dict=smiles_dict):
""" Tokenize characters in smiles to integers
"""
smiles_len = len(smiles)
seq = []
keys = char_dict.keys()
i = 0
while i < smiles_len:
# Skip all spaces
if smiles[i:i + 1] == ' ':
i = i + 1
# F... | 00509702f779e55be69cd6664c8b1e148e7436ea | 43,484 |
from typing import Dict
def create_worker(doc: Dict) -> Worker:
"""Factory pattern for workers.
Create an instance of a worker implementation from a given worker
serialization.
Parameters
----------
doc: dict
Dictionary serialization for a worker.
Returns
-------
flowser... | 339354b383a8e75b9f4858fc8b41008beac6abc4 | 43,485 |
import logging
import tqdm
def load_some_app_reviews(app_ids: list) -> pd.DataFrame:
"""
Load reviews for a given set of Play Store apps
Args:
app_ids: list - a list of app ids whose reviews will be loaded
Returns:
Pandas DataFrame
"""
data_types = {
"appId": str,
... | 26ebc64ada782468ac51785ed2fd6adde0b90dea | 43,486 |
def highpass(x, fs, fc, order=4):
"""
Applies highpass filter
Parameters:
- x: numpy.array, input signal, sampled at fs
- fs: float, sampling frequency
- fc: float, cutoff frequency
- order: filter order
Returns: numpy.array
"""
nyq = 0.5 * fs
norm_fc = fc / n... | 3861f0737f30ea888b29529b8691772a79c6ad52 | 43,487 |
import string
def is_printable(s: str) -> bool:
"""
does the given string look like a very simple string?
this is just a heuristic to detect invalid strings.
it won't work perfectly, but is probably good enough for rendering here.
"""
return all(map(lambda b: b in string.printable, s)) | 78941ba7daca94274fc1b238b6f411f73fc875f6 | 43,488 |
def sync_redis_delete(username: str, email: str):
"""MySQL数据库删除数据同步到Redis
:param username: 需要删除的用户名
:param email: 用户的邮箱
:return: bool
"""
# db = pymysql.Connect(host='localhost', user='root', password=mysql_passwd,
# database=mysql_base, charset='utf8')
# 通过docker部署... | 42c084e631ce25411bb11a6e4471b8a4d454b17f | 43,489 |
def sigmoid(t):
"""
apply the sigmoid function on t.
Output:
- 1/(1+exp(-t))
"""
return 1 / (1 + np.exp(-t)) | d577c1c3c8f28d6c818cc387a38b81edef4a2e95 | 43,490 |
from typing import Optional
def get_reservation(location: Optional[str] = None,
project: Optional[str] = None,
reservation_id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetReservationResult:
"""
Returns informatio... | 8b0c7c2681554ae4f38d10b651074a1c0c7119e0 | 43,491 |
import http
def checksession(request):
"""
@params:
request, django请求实例
@function:
判断是否已经登录
"""
if not settings.LOGIN_KEY in request.session:
raise http.ErrorResp(err_code.NO_LOGIN)
return err_code.OK | c877c19f4f4e49ccd70d8ed70497d134577e7bf7 | 43,492 |
def try_dbfield(fn, field_class):
"""
Try ``fn`` with the DB ``field_class`` by walking its
MRO until a result is found.
ex::
_try_dbfield(field_dict.get, models.CharField)
"""
# walk the mro, as field_class could be a derived model field.
for cls in field_class.mro():
# sk... | decfdf65afaa2ffd4e14aac7ce41f6710ad54137 | 43,493 |
def missing_tag_translations(request, tag_id):
"""Returns a JSON object hash of languages for which there are no
translations for this Tag."""
tag = get_object_or_404(Tag, id=tag_id)
data = {}
langs = [tag.site.default_language, ]
for lang in tag.site.alternate_language.all():
langs.appe... | 11544794f34333c16294307d50cac93fff22651e | 43,494 |
import yaml
def from_yaml(file):
"""Load configuration from YAML file with include constructor.
To include another file use "!include filename".
Examples:
.. code-block::
# file: bar.yaml
- 3.6
- [1, 2, 3]
# file: foo.yaml
a: 1
... | 756ca18d7c9f037edf2a5051f2f2e43d2f949b5e | 43,495 |
def listResources(request):
""" Generates an HTML page listing all resources. """
resources = models.Resources.objects.all().order_by('resource_name')
#
return render(request, "list_resources.html",
{'resources' : resources}) | d3f1509c4dbe48a7ed59c8f3578107b11cf41517 | 43,496 |
def publish_as_gist_file(ctx, path, name="index"):
"""Publish a gist.
More information on gists at http://gist.github.com/.
"""
github_config = get_github_config(ctx, allow_anonymous=False)
user = github_config._github.get_user()
with open(path, "r") as fh:
content = fh.read()
conte... | c6e455765f18df25682a6e7aeeeafdd49aa624c3 | 43,497 |
from typing import Union
import json
def read_diff_file(data_path: str, otu_id: str, otu_version: Union[int, str]) -> dict:
"""
Read a history diff file from disk.
:param data_path: the application data path
:param otu_id: the change's OTU ID
:param otu_version: the change's OTU version
:retu... | 79f7c9949cfb9a988bbd7a363d3d566de7e15cd5 | 43,499 |
def create_app(config):
"""Docstring for create_app method."""
app = Flask(__name__, instance_relative_config=True)
app.config.from_object(app_config[config])
jwt = JWTManager(app)
app.register_blueprint(version_2)
create_tables()
return app | 5b263fff394ca99df4d581bc1add0e6f10222d89 | 43,500 |
import re
def get_index_of_tone_vowel(syllable):
"""
Returns the index of the vowel that should be marked with a tone accent in a given syllable.
The tone marks are assigned with the following priority:
- A and E first
- O is accented in OU
- otherwise, the *final* vowel
Returns -1 if n... | 97d4f724f56ce3270e317b4d885b3ac5730e59f5 | 43,502 |
def IterateQueue(queue_head, element_ptr_type, element_field_name, backwards=False, unpack_ptr_fn=None):
""" Iterate over an Element Chain queue in kernel of type queue_head_t. (osfmk/kern/queue.h method 2)
params:
queue_head - value : Value object for queue_head.
element_ptr... | 7d2b0192286f50217e374965578dff277462b3c3 | 43,503 |
import glob
import random
def mediaGenerator(request):
"""Randomly picks an content file from the requested database.
`request`: selects prefered database
"""
folder = 'content/' + request
mediaPaths = glob(folder + '/*')
return random.choice(mediaPaths) | d8a6c68ba98b8ae905319e44b901a5c9553b0f42 | 43,504 |
def filter_factory(global_conf, **local_conf):
"""Returns a WSGI filter app for use with paste.deploy."""
conf = global_conf.copy()
conf.update(local_conf)
def auth_filter(app):
return FederatedAuthentication(app, conf)
return auth_filter | 9d75d3ecd01cbba8046a470b3cfc4b4e595fb637 | 43,505 |
def create(document_dir):
"""
creates an inverted index given an English text corpus
for movies. If the directory provided does not exist,
the program will print an error. If the filenames
in the test corpus do not match with the description,
the program will print an error and will skip the
... | 757aa0b974972bcb751a84d4e7cbb76d425e10fc | 43,507 |
from typing import List
def filter_violations(violations: List[Violation],
exclude_categories: List[str],
exclude_severities: List[int]) -> List[Violation]:
"""
Filter violations according to rules specified by the user.
:param violations: all violations
:pa... | dfa7ac8acc72d3c4350e2592149fcd840086e29b | 43,509 |
def notary_info(request):
"""get notary details"""
name = request.POST.get('name')
if not name:
return format_return(13000)
msg_code, msg_data = interface.get_notary_info(name=name.strip(''))
return format_return(msg_code, data=msg_data) | cb379479f816d4037d34f5c98af05f0693d9fe95 | 43,510 |
from unittest.mock import Mock
def get_mock_discovery(host_list, invalid_interface=False, invalid_key=False):
"""Return a mock gateway info instance."""
gateway_discovery = Mock()
gateway_dict = {}
for host in host_list:
gateway = Mock()
gateway.ip_adress = host
gateway.port ... | d99e01cdcc856ca8d193893e229be76d005ac3db | 43,512 |
def get_raw_text(xml_tree_element):
""" get raw text with xml encodings a string """
text = ET.tostring(xml_tree_element)
return text | caaa94ae3dd5be182bb55632d203e54767a0eccc | 43,513 |
def rankingMinPath(matrix,seeds,levels):
"""
errado, analisar
"""
chosen = np.full(matrix.shape[0], np.inf)
height_vector = np.zeros(matrix.shape[0],dtype=int)
parent = np.full(matrix.shape[0], np.inf)
fila = []
for s in seeds:
fila.append(s)
height_vector[s] = 0
parent[s]=-1
chosen[s] = 0
print(fil... | fde9a5908dd53cddf7d7963147b80e5afddbe191 | 43,514 |
def register_run_config(name):
"""Registers a run configuration class."""
basecls = BaseConfig
registry = RUN_CONFIG_REGISTRY
reg_func = partial(_register, name=name, basecls=basecls, registry=registry)
return reg_func | 871d6cfa0952c38dee08159610c66c8aadd4e272 | 43,515 |
def statement_block(evaluator, ast, state):
"""Evaluates statement block "{ ... }"."""
state.new_local_scope()
for decl in ast["decls"]:
evaluator.eval_ast(decl, state)
for stmt in ast["stmts"]:
res, do_return = evaluator.eval_ast(stmt, state)
if do_return:
state.remo... | e38575e5e2119cd9794ea5f0b1629cecf411a0e9 | 43,516 |
def _create_query_dict(query_text):
"""
Create a dictionary with query key:value definitions
query_text is a comma delimited key:value sequence
"""
query_dict = dict()
if query_text:
for arg_value_str in query_text.split(','):
if ':' in arg_value_str:
arg_valu... | 2e4478bdf110911d4ca9fcc6c409aab3504a0b8a | 43,517 |
def nan_gaussian_filter(T, fwhm, mode="constant", cval=0, preserve_nan=True, **kwargs):
"""default parameters mimic
convolve(x,kernels.Gaussian2DKernel(fwhm),preserve_nan=True,boundary='fill',fill_value=np.nan)
fill_value = np.nan basically continues the interpolation beyond the boundary
"""
V = T.c... | fd97a3c36332aa36df59781224eddb4cc12ecfc5 | 43,518 |
def _getVersionString(value):
"""Encodes string for version information string tables.
Arguments:
value - string to encode
Returns:
bytes - value encoded as utf-16le
"""
return value.encode("utf-16le") | 36646a686c17f2c69d71a0cdeede56f0a1e514e2 | 43,519 |
def h_n(n, z):
""" Spherical Hankel function of order n
Parameters
----------
n : numpy.array(M,N)
Order of the function
z : numpy.array(M,N)
Function argument
Returns
-------
yn(z) : numpy.array(M,N)
Function value
"""
return ... | c253db485dfca3949a1ba6a9895576a5c11a833d | 43,520 |
from typing import List
from typing import Optional
def get_shift_of_one_to_one_match(matches: List[List[bool]]) -> Optional[int]:
"""
Matches is an n x n matrix representing a directed bipartite graph.
Item i is connected to item j if matches[i][j] = True
We try to find a shift k such that each item ... | f8168e72dab64acc26841a49122dcf08d473ea1f | 43,522 |
from bs4 import BeautifulSoup
import urllib
from datetime import datetime
def parse_zebet(url=""):
"""
Retourne les cotes disponibles sur zebet
"""
if not url:
url = "https://www.zebet.fr/fr/competition/96-ligue_1_conforama"
if "/sport/" in url:
return parse_sport_zebet(url)
tr... | e29bd5093c65511507a8c2dc227b62bdcdfc381a | 43,523 |
def background(f):
"""
Call a function in a simple thread, to prevent blocking
Taken from the Jupyter Qtconsole project
"""
t = Thread(target=f)
t.start()
return t | d231192f895c5e5914f375172e045b4d7cc52ee2 | 43,524 |
from joblib import Parallel, delayed, parallel_backend
from typing import Union
def calculate_entropy_batch_mixing(
adata: ad.AnnData,
use_rep: str = "delta",
batch_col: str = "batch_indices",
n_neighbors: int = 50,
n_pools: int = 50,
n_samples_per_pool: int = 100,
random_state: int = 0,
... | 8c62a9ee0b951bfab6b307efcde853494868ec90 | 43,525 |
import re
from datetime import datetime
def get_leap_seconds(truncate=True):
"""
Gets a list of GPS times for when leap seconds occurred
Keyword arguments
-----------------
truncate: Reduce list of leap seconds to positive GPS times
Returns
-------
GPS time (seconds since 1980-01-06T... | c2bf09bf4dbfb734adccd13a4a6a259a6ffe64c7 | 43,526 |
from typing import Any
import json
def serialize(obj: Any) -> str:
"""
Serializes object into a string JSON
DEPRECATED use json_encoder.to_json directly
:param obj: object to serialize
:return: JSON string
"""
return json.dumps(obj, cls=EnhancedJSONEncoder) | 52fa105779465cf3ca2ee9d9a6b4cf16cfe1dd60 | 43,527 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.