content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def convert_null_to_zero(event, field_or_field_list):
""" Converts the value in a field or field list from None to 0
:param event: a dict with the event
:param field_or_field_list: A single field or list of fields to convert to 0 if null
:return: the updated event
Examples:
.. code-block:: py... | c81bf5909d13b9cb2ce759c3ab0643e03b95c203 | 43,400 |
def is_mul(a):
"""Return `True` if `a` is an expression of the form b * c.
>>> x, y = Ints('x y')
>>> is_mul(x * y)
True
>>> is_mul(x - y)
False
"""
return is_app_of(a, Kind.MULT) | 333fa73e5a1d15df8edb53ce744148a766522eca | 43,401 |
def procura_frase_lacunas_respostas_dicionario():
"""Esta função retorna a frase, as lacunas e as respostas
correspondentes para o nível selecionado pelo usuário.
"""
frase = frases_lacunas_respostas_por_dificuldade[nivel]['frase']
lacunas = frases_lacunas_respostas_por_dificuldade[nivel]['lacunas']... | 0c15e5208b0e0c33a41d909a94b1145b0a94a1fd | 43,402 |
def refresh():
"""Pull fresh data from Open AQ and replace existing data."""
DB.drop_all()
DB.create_all()
api = openaq.OpenAQ()
status, body = api.measurements(city='Atlantic City', country='US', parameter='pm25')
results = body['results']
for ii in range(len(results)):
db_record = ... | b3ef9492d88048fc17efd27c9d8a3df02ac0a029 | 43,403 |
def index():
"""Renders home page."""
return render_template('index.html') | 0ea6f0b0c0f4f2c5596d68d7a4ea8268a7c8f2f6 | 43,404 |
import os
def get_file_parts(filename, prefix="name"):
"""Assign a name to various parts of a file.
Parameters
----------
filename : str
A file name (no leading path is permitted).
prefix : str
Prefix to prepend to the key names.
Returns
-------
A dict mapping each pa... | b114b219103fa959bd37680d26ea0760fff6a263 | 43,405 |
def obtener_cantidad_dias_estancia_media_estimados_en_ciudad_en_rango_anios_mensualmente(Ciudad, AnioInicio, AnioFin):
"""
Dado una ciudad y un año obtiene los dias de estancia media estimados en dicha ciudad en ese rango de años dividido por meses
Dado una ciudad y un año obtiene los dias de estancia media... | d58fe973c5b4197e45d37e76f6a5db6f8d1d7cd7 | 43,406 |
def setBit(int_type, offset, value):
"""following 2 functions derived from https://wiki.python.org/moin/BitManipulation, this one sets a specific bit"""
if value == 1:
mask = 1 << offset
return(int_type | mask)
if value == 0:
mask = ~(1 << offset)
return(int_type & mask) | 642e8ffb41aaf3c5514038e525275c053a4cd8b1 | 43,407 |
def parse_values(params, defaults):
"""Parses a Values parameter which should have only two values separated by
a comma. Used to override ON/OFF type messages.
"""
try:
split = params("Values").split(",")
if len(split) != 2:
return defaults
else:
return sp... | 539fa14aee5133ef3f4d1d4f45f7944da33866ce | 43,408 |
def _get_activation_fn(activation):
"""Return an activation function given a string"""
if activation == "relu":
return F.relu
if activation == "gelu":
return F.gelu
if activation == "glu":
return F.glu
if activation == "leaky_relu":
return F.leaky_relu
raise Runti... | 48fbe91d2f701187a398296c6728744a4c4be6c0 | 43,409 |
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 os
def check_file_access(m): # pragma: no cover
"""Check if we can reach the file directly
or if we have to download it via PMS.
Args:
m (plexapi.video.Episode)
Return:
filepath or http to the file.
"""
LOG.debug('Checking if we can reach %s directly... | e64e8a4a2f1697b45cd40716ea72ddf23e9fc931 | 43,414 |
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 |
import os
def find_repositories_by_walking(path, followlinks):
"""Walk a tree and return a sequence of (directory, dotdir) pairs."""
repos = []
for dirpath, dirnames, filenames in os.walk(path, followlinks=followlinks):
for dotdir in set(dirnames) & DOTDIRS:
repos.append((dirpath, dotd... | cdfacd9faefc794c6ed861110939e6d0c0fc5a23 | 43,430 |
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 |
import os
import codecs
def _clean_inner_tags_file(outfile, stream):
"""Accepts an output filename and a stream of the byte contents of a tags file
and writes the cleaned contents to a new file on disk.
Args:
outfile: the path to which the modified stream should be written
stream: the byt... | 1745569addeefe466d35227749c5dcc5ed0006b1 | 43,442 |
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 process_fovea(fovea, pixel_norm = 'standard', mutation = False) :
"""
Fn preprocesses a single fovea array.
If mutation == True, modifications to input images will be made, each with 0.5
probability:
* smallest dimension resized to standard height and width supplied in size param
*... | bde2d80d6629f3532ebfe99cad42e624e75f1d68 | 43,450 |
import os
def fasta_file_to_lists(path, marker_kw=None):
"""Reads a FASTA formatted text file to a list.
Parameters
----------
path : str
Location of FASTA file.
marker_kw : str
Keyword indicating the sample is a marker.
Returns
-------
dict
Contains list of i... | b8a70b6ee697fdd52d117e4a1bdfed8fe79d84d5 | 43,451 |
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 tqdm
def surrogate_test(
mata,
matb,
pval=0.005,
nshuffles=1000,
return_extra=False,
nworkers=8,
pcalc_discard0=0,
pcalc_discard1=1000,
lrG=0.01,
verbose=False,
):
"""shuffling/permutation strat to compare trajectories
# mata: matrix of dims (ntrajectories, ninte... | b19eb473fbc453a001ca43d712ecebbf1ae9c395 | 43,460 |
from os.path import dirname, join, exists
import metatabdecl
from metatab.exc import IncludeError
def declaration_path(name):
"""Return the path to an included declaration"""
d = dirname(metatabdecl.__file__)
path = join(d, name)
if not exists(path):
path = join(d, name + '.csv')
if n... | 7c227e5294fc1057d564fb56d47a5d3dd42eb65e | 43,461 |
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 |
import os
def FindTestsToRun(env, build, BUILD_TARGETS, otherVars,
component=None, project=None):
"""Find header files defining tests to run.
One of component or project must be specified; this says which Chaste
component or user project to hunt for tests in.
If otherVars['request... | fa6bf9c7bb43801b3283ec57674c3ca02aeb74f4 | 43,476 |
import os
def test_ap_wpa2_eap_aka_prime(dev, apdev):
"""WPA2-Enterprise connection using EAP-AKA'"""
if not os.path.exists("/tmp/hlr_auc_gw.sock"):
logger.info("No hlr_auc_gw available");
return "skip"
params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
hostapd.add_ap(apdev[0]['ifn... | 0b744f8683835795165451197b56f199bf37628c | 43,477 |
def get_CG_bonds_distrib(ns, beads_ids, grp_type):
""""Calculate bonds distribution from CG trajectory.
ns requires:
cg_universe
bw_bonds
bw_constraints
bins_constraints
bins_bonds
"""
bond_values = np.empty(len(ns.cg_universe.trajectory) * len(beads_ids))
fr... | 51eb89128d0df4ed7f109e38cd9123a24cbac70a | 43,478 |
def update_translations(request):
"""
Actualiza las traducciones eliminando las huérfanas y
generando traducciones vacías para todos los objetos que existan en
base de datos.
"""
FieldTranslation.delete_orphan_translations()
num_translations = FieldTranslation.update_translations()
return render_to_response('mo... | b6d0419fcec3130e1a57ba123ca2675d8a8f5ff3 | 43,479 |
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 |
import sys
def main(args=None):
"""
Parse the arguments, get the data in a df, and create the plot
:return: if requested, return the plot as JSON object
"""
if args is None:
args = sys.argv[1:]
parsed_args = parse_arguments(arguments=args)
conn = connect_to_database(db_path=parse... | 87aaf3354c086aebee7e3fd00834761f4ca459c3 | 43,481 |
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 |
import collections
def parse(text: str):
"""Parse the DSL contained in text."""
if not text.strip():
return example_default()
has_index_collision = False
has_index_order_mismatch = False
info_queue, some_axis_maps = [], []
axis_values_rows_req_string: str = unsafe(text)
axis_valu... | 4784da2656eea20d03ad801650665570f6307524 | 43,498 |
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.