content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import string
def equationMaker(congruency=None, beat_type=None, structure=None, n=None, perms=None, catch = False):
"""
Function to create equation stimuli, like in Landy & Goldstone, e.g. "b + d * f + y"
required inputs:
congruency: 'congruent' or 'incongruent'
... | b2a81696055c77fa8803ab218e7b115a66a542aa | 13,500 |
def get_deadline_delta(target_horizon):
"""Returns number of days between official contest submission deadline date
and start date of target period
(14 for week 3-4 target, as it's 14 days away,
28 for week 5-6 target, as it's 28 days away)
Args:
target_horizon: "34w" or "56w" indicating whe... | df09b04fc2e7065056b724cfe5d8966c06240b79 | 13,501 |
def perform_tensorflow_model_inference(model_name, sample):
""" Perform evaluations from model (must be configured)
Args:
model_name ([type]): [description]
sample ([type]): [description]
Returns:
[type]: [description]
"""
reloaded_model = tf.keras.models.load_model(model_n... | 3c374dd76d4d40dbaffc7758694ff358ad1aefeb | 13,502 |
def check_ntru(f, g, F, G):
"""Check that f * G - g * F = 1 mod (x ** n + 1)."""
a = karamul(f, G)
b = karamul(g, F)
c = [a[i] - b[i] for i in range(len(f))]
return ((c[0] == q) and all(coef == 0 for coef in c[1:])) | 1c2ff2fbaadcdf80e5fd9ac49f39a301c9606ada | 13,503 |
import json
def edit_user(user_id):
"""
TODO: differentiate between PUT and PATCH -> PATCH partial update
"""
user = User.from_dict(request.get_json())
user.id = user_id
session_id = request.headers.get('Authorization', None)
session = auth.lookup(session_id)
if session["user"].role ... | 2459911c2c65bf4e3e5ddbfa347c16ec39c9fc2b | 13,504 |
def Search_tau(A, y, S, args, normalize=True, min_delta=0):
"""
Complete parameter search for sparse regression method S.
Input:
A,y : from linear system Ax=y
S : sparse regression method
args : arguments for sparse regression method
normalize : boolean. Normalize co... | 30c74b0fed304df8851b9037e7091fb95be58554 | 13,505 |
def get_entry_accounts(entry: Directive) -> list[str]:
"""Accounts for an entry.
Args:
entry: An entry.
Returns:
A list with the entry's accounts ordered by priority: For
transactions the posting accounts are listed in reverse order.
"""
if isinstance(entry, Transaction):
... | dec8da3ced1956b4ae4dca08e2de812c66dcb412 | 13,506 |
def enter_fastboot(adb_serial, adb_path=None):
"""Enters fastboot mode by calling 'adb reboot bootloader' for the adb_serial provided.
Args:
adb_serial (str): Device serial number.
adb_path (str): optional alternative path to adb executable
Raises:
RuntimeError: if adb_path is invalid or adb e... | 9f7a8dfe8d0ce47a172cf7d07feb1bd5d2e8b273 | 13,507 |
def thesaurus_manager_menu_header(context, request, view, manager): # pylint: disable=unused-argument
"""Thesaurus manager menu header"""
return THESAURUS_MANAGER_LABEL | 7c37e69d4a662e4a155ed6a63a473e2eb52fe28b | 13,508 |
def create_compiled_keras_model():
"""Create compiled keras model."""
model = models.create_keras_model()
model.compile(
loss=tf.keras.losses.sparse_categorical_crossentropy,
optimizer=utils.get_optimizer_from_flags('client'),
metrics=[tf.keras.metrics.SparseCategoricalAccuracy()])
return mo... | 252fe18678e302e216b7b05121dfedd3bb46a180 | 13,509 |
import os
def train_sedinet_cat(SM, train_df, test_df, train_idx, test_idx,
ID_MAP, vars, greyscale, name, mode, batch_size, valid_batch_size,
res_folder):
"""
This function trains an implementation of SediNet
"""
##================================
## cr... | 830306ac4d3c6c8b43f763bc1b4cbb96ad8109f6 | 13,510 |
def psycopg2_string():
"""
Generates a connection string for psycopg2
"""
return 'dbname={db} user={user} password={password} host={host} port={port}'.format(
db=settings.DATABASES['default']['NAME'],
user=settings.DATABASES['default']['USER'],
password=settings.DATABASES['defaul... | 187fe1b576337613f791df657fd76ca8a4f783df | 13,511 |
def get_phase_relation(protophase: np.ndarray, N: int = 0) -> np.ndarray:
"""
relation between protophase and phase
Parameters
----------
protophase : np.ndarray
N : int, optional
number of fourier terms need to be used
Returns
-------
np.ndarray
... | 828f200f55f8d17071a51244465311f8c99866f7 | 13,512 |
import re
def handle_articlepeople(utils, mention):
"""
Handles #articlepeople functionality.
Parameters
----------
utils : `Utils object`
extends tweepy api wrapper
mention : `Status object`
a single mention
Returns
-------
None
"""
urls = re.findall(r'(h... | efdf2d7cda6124a163290aa7c3197a7462703749 | 13,513 |
from pathlib import Path
def bak_del_cmd(filename:Path, bakfile_number:int, quietly=False):
""" Deletes a bakfile by number
"""
console = Console()
_bakfile = None
bakfiles = db_handler.get_bakfile_entries(filename)
if not bakfiles:
console.print(f"No bakfiles found for {filename}")
... | 3ded066c23708a3fdcc2e38fb07706dc0e0cd628 | 13,514 |
def fetch_county_data(file_reference):
"""The name of this function is displayed to the user when there is a cache miss."""
path = file_reference.filename
return (pd
.read_csv(path)
.assign(date = lambda d: pd.to_datetime(d.date))
) | d29459efc5a46901cce970c2ddf4e499094f1aea | 13,515 |
def preston_sad(abund_vector, b=None, normalized = 'no'):
"""Plot histogram of species abundances on a log2 scale"""
if b == None:
q = np.exp2(list(range(0, 25)))
b = q [(q <= max(abund_vector)*2)]
if normalized == 'no':
hist_ab = np.histogram(abund_vector, bins = b)
if ... | 97eec01c5d23ca7b48951d4c62c7066b77ffb467 | 13,516 |
def exp_rearrangement():
"""Example demonstrating of Word-Blot for pairwise local similarity search on
two randomly generated sequencees with motif sequences violating
collinearity :math:`S=M_1M_2M_3, T=M'_1M'_1M'_3M'_2` where motif pairs
:math:`(M_i, M'_i)_{i=1,2,3}` have lengths 200, 400, 600 and are ... | fdd7650d2ab0340bd11d150f7f6ad5e60ddd2d09 | 13,517 |
def package_install_site(name='', user=False, plat_specific=False):
"""pip-inspired, distutils-based method for fetching the
default install location (site-packages path).
Returns virtual environment or system site-packages, unless
`user=True` in which case returns user-site (typ. under `~/.local/
... | 31b477208954886f847bd33651464f386a4e6adf | 13,518 |
def atlas_slice(atlas, slice_number):
"""
A function that pulls the data for a specific atlas slice.
Parameters
----------
atlas: nrrd
Atlas segmentation file that has a stack of slices.
slice_number: int
The number in the slice that corresponds to the fixed image
for r... | bafe5d886568203792b0f6178302f3ca5d536e5b | 13,519 |
def enviar_cambio_estado(request):
"""
Cambio de estado de una nota técnica y avisar
por email al personal de stib
"""
if request.method == "POST" or request.POST.get("nota_tecnica"):
try:
nota_tecnica = get_object_or_404(NotasTecnicas, pk=request.POST.get("nota_tecnica"))
... | 176a9a9d1bf7fd0ba1bec0c34526180581d33a8d | 13,520 |
def post_auth_logout(): # noqa: E501
"""Logout of the service
TODO: # noqa: E501
:rtype: None
"""
return 'do some magic!' | 3b24c61a301d08b1f2bbce76fe068f7adeb4a10b | 13,521 |
from typing import Dict
import aiohttp
async def head(url: str) -> Dict:
"""Fetch headers returned http GET request.
:param str url:
The URL to perform the GET request for.
:rtype: dict
:returns:
dictionary of lowercase headers
"""
async with aiohttp.request("HEAD", url) as re... | b4decbfb4e92863c07c5202e2c884c02e590943f | 13,522 |
from scapy.all import sr, srp
def send_recv_packet(packet, iface=None, retry=3, timeout=1, verbose=False):
"""Method sends packet and receives answer
Args:
packet (obj): packet
iface (str): interface, used when Ether packet is included
retry (int): number of retries
ti... | ea8967096e376f91cc2ce5435d178f8b56429a86 | 13,523 |
def node_vectors(node_id):
"""Get the vectors of a node.
You must specify the node id in the url.
You can pass direction (incoming/outgoing/all) and failed
(True/False/all).
"""
exp = Experiment(session)
# get the parameters
direction = request_parameter(parameter="direction", default="... | c61d85e4f4ae975bdd015f6bd181d1ae78aa245d | 13,524 |
def newFlatDict(store, selectKeys=None, labelPrefix=''):
"""
Takes a list of dictionaries and returns a dictionary of 1D lists.
If a dictionary did not have that key or list element, then 'None' is put in its place
Parameters
----------
store : list of dicts
The dictionaries would be e... | d44dec60de06779a8e965eb9e3771c66dd25e10b | 13,525 |
from typing import Any
from typing import List
from typing import Union
async def get_races(
db: Any, token: str, raceplan_id: str
) -> List[Union[IndividualSprintRace, IntervalStartRace]]:
"""Check if the event has a races."""
races = await RacesService.get_races_by_raceplan_id(db, raceplan_id)
if le... | 393a38992be404e5a82517b13d24e85b42b57b30 | 13,526 |
def _reshape_vectors(v1, v2, axis, dim, same_shape=True):
""" Reshape input vectors to two dimensions. """
# TODO v2 as DataArray with possibly different dimension order
v1, axis, _, _, _, _, coords, *_ = _maybe_unpack_dataarray(
v1, dim, axis, None, False
)
v2, *_ = _maybe_unpack_dataarray(... | 90c1dbf66f12fbc0bfa6e2ddede7530dbcbdf52b | 13,527 |
from typing import Any
def yaml_load(data: str) -> Any:
"""Deserializes a yaml representation of known objects into those objects.
Parameters
----------
data : str
The serialized YAML blob.
Returns
-------
Any
The deserialized Python objects.
"""
yaml = yaml_import... | 2e721698ef0bde3bd084127556d41503417ee516 | 13,528 |
def _get_current_branch():
"""Retrieves the branch Git is currently in.
Returns:
(str): The name of the current Git branch.
"""
branch_name_line = _run_cmd(GIT_CMD_GET_STATUS).splitlines()[0]
return branch_name_line.split(' ')[2] | 1b0d93d6e69205981c06f4dc8a45cf21259f4ccd | 13,529 |
from models.progressive_gan import ProgressiveGAN as PGAN
def PGAN(pretrained=False, *args, **kwargs):
"""
Progressive growing model
pretrained (bool): load a pretrained model ?
model_name (string): if pretrained, load one of the following models
celebaHQ-256, celebaHQ-512, DTD, celeba, cifar10. D... | cb78031a6aeca887c2ed17d02419c2b551a4b1ba | 13,530 |
import logging
def compare_environment(team_env, master_env, jenkins_build_terms ):
"""
compare the versions replace compare_environment
Return types
1 - Matches Master
2 - Does not match master. Master is ahead(red)
3 - branch is ahead (yellow)
:param team_env:
:param master_env:
... | 4c126d6119cfc4f506cffbcbc0324afa1694320e | 13,531 |
def _runge_kutta_step(func,
y0,
f0,
t0,
dt,
tableau=_DORMAND_PRINCE_TABLEAU,
name=None):
"""Take an arbitrary Runge-Kutta step and estimate error.
Args:
func: Function to evaluate... | f106c6842a7f9faed6e37bcb4305adbd4bd83146 | 13,532 |
def _create_serialize(cls, serializers):
"""
Create a new serialize method with extra serializer functions.
"""
def serialize(self, value):
for serializer in serializers:
value = serializer(value)
value = super(cls, self).serialize(value)
return value
serialize._... | 522f6a14fe3e2bca70c141f14dc8b400be1ca680 | 13,533 |
def confusion_matrix(y_true, y_pred, labels=None):
"""Compute confusion matrix to evaluate the accuracy of a classification
By definition a confusion matrix cm is such that cm[i, j] is equal
to the number of observations known to be in group i but predicted
to be in group j.
Parameters
-------... | 53d143a5388b23a61f927f4b8b4407cf8a051d3f | 13,534 |
def dialect_selector(s):
"""Return a dialect given it's name."""
s = s or 'ansi'
lookup = {
'ansi': ansi_dialect
}
return lookup[s] | e9232e22e2ef0789d98a16c8e2f3fd7efa5a7981 | 13,535 |
import unittest
def importlib_only(fxn):
"""Decorator to skip a test if using __builtins__.__import__."""
return unittest.skipIf(using___import__, "importlib-specific test")(fxn) | 3cdc1ac5e0a2062b6822291973770459f6bf2318 | 13,536 |
def bf(x):
""" returns the given bitfield value from within a register
Parameters:
x: a pandas DataFrame line - with a column named BF_NUMBER which holds the definition of given bit_field
reg_val: integer
Returns:
--------
res: str
the bit field value from within the register
"""... | 6167666cf7c6c5df8b121b2f418d29ff95df8898 | 13,537 |
from typing import Union
def get_mean_brightness(
frame: np.ndarray,
mask: Union[
np.ndarray,
None,
] = None,
) -> int:
"""Return the mean brightness of a frame.
Load the frame, calculate a histogram, and iterate through the bins until half or more of the pixels have been counted.... | 825afe97500f247aee4b1ccb045555fb21300cfe | 13,538 |
def rearrange(s):
"""
Args:
s
Returns:
[]
"""
if not can_arrange_palindrome2(s):
return []
m = {}
for c in s:
if c in m:
m[c] += 1
else:
m[c] = 1
middle = ""
for k in m:
if m[k] % 2 == 0:
m[k] /= 2... | bb6e03d35cc3f786c52ce7535628e02b51abd3a0 | 13,539 |
def get_org_memberships(user_id: str):
"""Return a list of organizations and roles where the input user is a member"""
query = (
model.Session.query(model.Group, model.Member.capacity)
.join(model.Member, model.Member.group_id == model.Group.id)
.join(model.User, model.User.id == model.M... | eaa5ba796798289185816719a176efb31d7f25e6 | 13,540 |
def standardize_concentration(df, columns, unit="nM"):
"""Make all concentrations match the given unit.
For a given DataFrame and column, convert mM, uM, nM, and pM concentration
values to the specified unit (default nM). Rename the column to include
({unit}).
Parameters
----------
d... | 79f889640faf10e5b66989b0444a235cba872fd2 | 13,541 |
from visonic import alarm as visonicalarm
def setup(hass, config):
""" Setup the Visonic Alarm component."""
global HUB
HUB = VisonicAlarmHub(config[DOMAIN], visonicalarm)
if not HUB.connect():
return False
HUB.update()
# Load the supported platforms
for component in ('sensor', '... | be11f167b393ed97d318f6f516c353ad1df39670 | 13,542 |
def moreparams():
""" Read list of json files or return one specific for specific time """
hour_back1 = request.args.get('hour_back1', default=1, type=int)
hour_back2 = request.args.get('hour_back2', default=0, type=int)
object_of_interest = request.args.get('object_of_interest', type=None)
#print(... | 0a1efd4d504ad0825a59b13ba6ce985c72b0f339 | 13,543 |
def generate_http_request_md_fenced_code_block(
language=None,
fence_string='```',
**kwargs,
):
"""Wraps [``generate_http_request_code``](#generate_http_request_code)
function result in a Markdown fenced code block.
Args:
fence_string (str): Code block fence string used wrapping the cod... | a34581e8c0d40542a625d222183adb601c60b408 | 13,544 |
def confident_hit_ratio(y_true, y_pred, cut_off=0.1):
"""
This function return the hit ratio of the true-positive for confident molecules.
Confident molecules are defined as confidence values that are higher than the cutoff.
:param y_true:
:param y_pred:
:param cut_off: confident value that defi... | 0a7dbe9f3d81b877c309fd1fffb2840ec71dbeee | 13,545 |
import click
def onion(ctx, port, onion_version, private_key, show_private_key, detach):
"""
Add a temporary onion-service to the Tor we connect to.
This keeps an onion-service running as long as this command is
running with an arbitrary list of forwarded ports.
"""
if len(port) == 0:
... | 7f36e967fc30877b504fda79699c7d3347a4f410 | 13,546 |
def determine_if_pb_should_be_filtered(row, min_junc_after_stop_codon):
"""PB should be filtered if NMD, a truncation, or protein classification
is not likely protein coding (intergenic, antisense, fusion,...)
Args:
row (pandas Series): protein classification row
min_junc_after_stop_codon (... | 29ab7ce53ac7569c4d8a29e8e8564eab33b3f545 | 13,547 |
import queue
def calculate_shortest_path(draw_func, grid, start, end):
"""https://en.wikipedia.org/wiki/A*_search_algorithm"""
count = 0
open_set = queue.PriorityQueue()
open_set.put((0, count, start))
open_set_hash = {start}
came_from = {}
# g_score: Distance from start to current node
... | 52cbdc4a8e9114395d6349e58cba11bb2b6ab84f | 13,548 |
from typing import MutableMapping
import hashlib
def _get_hashed_id(full_name: str, name_from_id: MutableMapping[int,
str]) -> int:
"""Converts the string-typed name to int-typed ID."""
# Built-in hash function will not exceed the range of int64, whi... | 2eadfac0369d33ae29e4c054691180720995ef93 | 13,549 |
def find_adjustment(tdata : tuple, xdata : tuple, ydata : tuple,
numstept=10,numstepx=10,tol=1e-6) -> tuple:
"""
Find best fit of data with temporal and spatial offset in range. Returns
the tuple err, dt, dx.
Finds a temporal and spatial offset to apply to the temporal and spatial
locatio... | 4efe607c40606b1235a5f9d62c3002a673a47828 | 13,550 |
import yaml
def get_params():
"""Loads ./config.yml in a dict and returns it"""
with open(HERE/'config.yml') as file:
params = yaml.load(file)
return params | 8e2e1b3ae47ff9a296aab7945562e3ea8ad43598 | 13,551 |
import argparse
import logging
def parse_args(args, repo_dirs):
"""
Extract the CLI arguments from argparse
"""
parser = argparse.ArgumentParser(description="Sweet branch creation tool")
parser.add_argument(
"--repo",
help="Repository to create branch in",
choices=repo_dir... | b745e9aedc03857101c4faa4c9a126b8b19a093d | 13,552 |
def get_textgrid(path_transcription):
"""Get data from TextGrid file"""
data = textgriddf_reader(path_file=path_transcription)
text_df = textgriddf_df(data, item_no=2)
sentences = textgriddf_converter(text_df)
return sentences | d3e037ff10488eb1eed777e008599769ddf9d81f | 13,553 |
import http
def accessible_required(f):
"""Decorator for an endpoint that requires a user have accessible or read permission in the
given room. The function must take a `room` argument by name, as is typically used with flask
endpoints with a `<Room:room>` argument."""
@wraps(f)
def required_acc... | e4e13632963fb80377dcbdaa36e90c4c62dd9a1f | 13,554 |
import warnings
def make_erb_cos_filters_nx(signal_length, sr, n, low_lim, hi_lim, sample_factor, padding_size=None, full_filter=True, strict=True, **kwargs):
"""Create ERB cosine filters, oversampled by a factor provided by "sample_factor"
Args:
signal_length (int): Length of signal to be filtered with the ... | 207a9d3be6b732c1d86a5ed5bde069d5ea760347 | 13,555 |
def button_ld_train_first_day(criteria, min_reversal_number):
"""
This function creates a csv file for the LD Train test. Each row will be the first day the animal ran the
test. At the end, the function will ask the user to save the newly created csv file in a directory.
:param criteria: A widget that ... | 9de68279f6ffb8253275a7a7051a1ed9b2df8f8e | 13,556 |
def analyze_video(file, name, api):
"""
Call Scenescoop analyze with a video
"""
args = Namespace(video=file, name=name, input_data=None, api=True)
scene_content = scenescoop(args)
content = ''
maxframes = 0
for description in scene_content:
if(len(scene_content[description]) > maxframes):
con... | 92e176a5c951d038aa8477db7aec0705fba0152c | 13,557 |
from osgeo import ogr
import jsonschema
import json
import mimetypes
import os
def validategeojson(data_input, mode):
"""GeoJSON validation example
>>> import StringIO
>>> class FakeInput(object):
... json = open('point.geojson','w')
... json.write('''{"type":"Feature", "properties":{}, "... | 41fc1283469d28b8f422564303b17d80407e7893 | 13,558 |
def encdec_model(input_shape, output_sequence_length, english_vocab_size, french_vocab_size):
"""
Build and train an encoder-decoder model on x and y
:param input_shape: Tuple of input shape
:param output_sequence_length: Length of output sequence
:param english_vocab_size: Number of unique English ... | 47fa1893cc04b491292461db6c8a3418b464ba45 | 13,559 |
def close_to_cron(crontab_time, time_struct):
"""coron的指定范围(crontab_time)中 最接近 指定时间 time_struct 的值"""
close_time = time_struct
cindex = 0
for val_struct in time_struct:
offset_min = val_struct
val_close = val_struct
for val_cron in crontab_time[cindex]:
offset_tmp = v... | 7ce04d9b4260e7ea1ed7c3e95e7c36928989024e | 13,560 |
def remove_stop_words(words_list: list) -> list:
""" Remove stop words from strings list """
en_stop_words = set(stopwords.words('english'))
return [w for w in words_list if str(w).lower not in en_stop_words] | a6e3c117ea805bdfaffe80c17fc5e340a869d55d | 13,561 |
import os
def build_jerry_data(jerry_path):
"""
Build up a dictionary which contains the following items:
- sources: list of JerryScript sources which should be built.
- dirs: list of JerryScript dirs used.
- cflags: CFLAGS for the build.
"""
jerry_sources = []
jerry_dirs = set()
... | 77a26d0f94bc82881e86e9f0fc40915a66bc3914 | 13,562 |
def min_geodesic_distance_rotmats_pairwise_tf(r1s, r2s):
"""Compute min geodesic distance for each R1 wrt R2."""
# These are the traces of R1^T R2
trace = tf.einsum('...aij,...bij->...ab', r1s, r2s)
# closest rotation has max trace
max_trace = tf.reduce_max(trace, axis=-1)
return tf.acos(tf.clip_by_value((m... | a4da40aa9594c301b0366da0a26d73afce83e05f | 13,563 |
def project_to_2D(xyz):
"""Projection to (0, X, Z) plane."""
return xyz[0], xyz[2] | c6cdb8bd6dce65f6ce39b14b9e56622832f35752 | 13,564 |
def Geom2dInt_Geom2dCurveTool_D2(*args):
"""
:param C:
:type C: Adaptor2d_Curve2d &
:param U:
:type U: float
:param P:
:type P: gp_Pnt2d
:param T:
:type T: gp_Vec2d
:param N:
:type N: gp_Vec2d
:rtype: void
"""
return _Geom2dInt.Geom2dInt_Geom2dCurveTool_D2(*args) | 6ac157e171af9d4bab852a9677287e33bb1d90f2 | 13,565 |
def notfound(request):
"""
Common notfound return message
"""
msg = CustomError.NOT_FOUND_ERROR.format(request.url, request.method)
log.error(msg)
request.response.status = 404
return {'error': 'true', 'code': 404, 'message': msg} | b690d9b879db15e192e8ee50d4ea2b0847ba658b | 13,566 |
def l2norm(a):
"""Return the l2 norm of a, flattened out.
Implemented as a separate function (not a call to norm() for speed)."""
return np.sqrt(np.sum(np.absolute(a)**2)) | b5ce94bfc0f3472e60a4338c379bc4dfe490e623 | 13,567 |
def create_container(request):
""" Creates a container (empty object of type application/directory) """
storage_url = get_endpoint(request, 'adminURL')
auth_token = get_token_id(request)
http_conn = client.http_connection(storage_url,
insecure=settings.SWIFT_INSEC... | 15c25df933f7620cee71319f9f41e92e29880d1c | 13,568 |
import os
def check_all_data_present(file_path):
"""Checks the data exists in location file_path"""
filenames = [
"t10k-images-idx3-ubyte",
"t10k-labels-idx1-ubyte",
"train-images-idx3-ubyte",
"train-labels-idx1-ubyte",
]
data_path = os.path.join(file_path, "data")
... | b15759f7f6849829f853d49c1c2c4a117ce28613 | 13,569 |
def get_searchable_models():
"""
Returns a list of all models in the Django project which implement ISearchable
"""
app = AppCache();
return filter(lambda klass: implements(klass, ISearchable), app.get_models()) | ad7c56f17ec4e0fc77942fe1466b879bd45eb191 | 13,570 |
def create_updated_alert_from_slack_message(payload, time, alert_json):
"""
Create an updated raw alert (json) from an update request in Slack
"""
values = payload['view']['state']['values']
for value in values:
for key in values[value]:
if key == 'alert_id':
cont... | a685a0c0da472f055dc8860bdf09970a1ecc8aff | 13,571 |
def enforce(*types):
"""
decorator function enforcing, and converting, argument data types
"""
def decorator(fn):
def new_function(*args, **kwargs):
# convert args into something mutable, list in this case
newargs = []
for original_argument, type_to_convert in... | 217ad3adccdaa9fc83ceaf5ef2c0905b8d54f1ed | 13,572 |
from typing import Type
from typing import Any
from typing import Sequence
from enum import Enum
from datetime import datetime
def modify_repr(_cls: Type[Any]) -> None:
"""Improved dataclass repr function.
Only show non-default non-internal values, and summarize containers.
"""
# let classes still cr... | ddc860bbe3c9d04723a3cc0b4cdcce960d0ecf71 | 13,573 |
def _is_binary(path):
"""Checks if the file at |path| is an ELF executable.
This is done by inspecting its FourCC header.
"""
with open(path, 'rb') as f:
file_tag = f.read(4)
return file_tag == '\x7fELF' | 0c5bc0917f405604a6d36495b786c9fbc9268ad1 | 13,574 |
from typing import Optional
import typing
def update_item(*, table: str, hash_key: str, sort_key: Optional[str] = None, update_expression: Optional[str],
expression_attribute_values: typing.Dict, return_values: str = 'ALL_NEW'):
"""
Update an item from a dynamoDB table.
Will determine the ... | a6efc6638708d1c5dfc79d89216cfa866e3a24fa | 13,575 |
def get_configuration(configuration_path=DEFAULT_CONFIGURATION_FILE):
"""
Return a dict containing configuration values.
:param str configuration_path: path to parse yaml from.
:return: dict
"""
global _configuration
if _configuration is None:
LOGGER.debug('Loading configuration: %s... | 99c9e53242e34495d872cc9131961ab7878c641a | 13,576 |
import re
def google_login_required(fn):
"""Return 403 unless the user is logged in from a @google.com domain."""
def wrapper(self, *args, **kwargs):
user = users.get_current_user()
if not user:
self.redirect(users.create_login_url(self.request.uri))
return
email_match = re.match('^(.*)@(.... | 1e45f2ea026e772b6b4c9048dddf93b2fe3ec991 | 13,577 |
def init_res_fig(n_subplots, max_sess=None, modif=False):
"""
init_res_fig(n_subplots)
Initializes a figure in which to plot summary results.
Required args:
- n_subplots (int): number of subplots
Optional args:
- max_sess (int): maximum number of sessions plotted
... | 3c12c18c16a371d10977d165875a2aa346c009bf | 13,578 |
import json
def change_personal_data_settings(request):
"""
Creates a question with summarized data to be changed
:param request: POST request from "Change personal data settings" Dialogflow intent
:return: JSON with summarized data to be changed
"""
language = request.data['queryResult']['lan... | c18641ea4cc32e8d2703dfca90066b6736c5103a | 13,579 |
def get_selected_cells(mesh, startpos, endpos):
"""
Return a list of cells contained in the startpos-endpos rectangle
"""
xstart, ystart = startpos
xend, yend = endpos
selected_cells = set()
vertex_coords = mesh.coordinates()
for cell in dolfin.cells(mesh):
cell_vertices = cell.... | c637bfa195aae4125e65553b1f4023cc3dae1f3a | 13,580 |
def flip_axis(array, axis):
"""
Flip the given axis of an array. Note that the ordering follows the
numpy convention and may be unintuitive; that is, the first axis
flips the axis horizontally, and the second axis flips the axis vertically.
:param array: The array to be flipped.
:type array: `n... | e2839125ddf3b22dea732857763fda636b748dda | 13,581 |
def fizz_buzz_tree(input_tree):
""" traverses a tree and performs fizz buzz on each element, agumenting the val """
input_tree.in_order_trav(lambda x: fizzbuzz(x))
return input_tree | 29b7380fb6215bf8ecf67fa85321445b8954abdc | 13,582 |
def scan_to_headerword(serial_input, maximum_bytes=9999, header_magic=HeaderWord.MAGIC_MASK):
"""
Consume bytes until header magic is found in a word
:param header_magic:
:param maximum_bytes:
:param serial_input:
:rtype : MTS.Header.Header
"""
headerword = 0x0000
bytecount = 0
... | 5a59d934426559f0aa7d9357740b007c16dc8f90 | 13,583 |
def _c2_set_instrument_driver_parameters(reference_designator, data):
""" Set one or more instrument driver parameters, return status.
Accepts the following urlencoded parameters:
resource: JSON-encoded dictionary of parameter:value pairs
timeout: in milliseconds, default value is 60000
Sample:... | 4a54b4b8e79c089657e5e63347bac4109d056834 | 13,584 |
def generate_key(keysize=KEY_SIZE):
"""Generate a RSA key pair
Keyword Arguments:
keysize {int} -- Key (default: {KEY_SIZE})
Returns:
bytes -- Secret key
bytes -- Public key
"""
key = RSA.generate(keysize)
public_key = key.publickey().exportKey()
secret_key = key.ex... | 0a38221269b167c4ceefc95eb4cee3452f2aaffe | 13,585 |
import functools
def get_api_endpoint(func):
"""Register a GET endpoint."""
@json_api.route(f"/{func.__name__}", methods=["GET"])
@functools.wraps(func)
def _wrapper(*args, **kwargs):
return jsonify({"success": True, "data": func(*args, **kwargs)})
return _wrapper | d49dc725e7538374910e3819f8eae647250747f7 | 13,586 |
import sys
def scrape_radio_koeln():
"""
Fetch the currently playing song for Radio Köln.
:return: A Song, if scraping went without error. Return None otherwise.
"""
url = 'http://www.radiokoeln.de/'
tag = get_tag(url, '//div[@id="playlist_title"]')[0]
artist = tag.xpath('.//div/b/text()'... | 34c9dc15345d7b4e9921e6fe0d134b68bf8f2b65 | 13,587 |
def get_mt4(alias=DEFAULT_MT4_NAME):
"""
Notes:
return mt4 object which is initialized.
Args:
alias(string): mt4 object alias name. default value is DEFAULT_MT4_NAME
Returns:
mt4 object(metatrader.backtest.MT4): instantiated mt4 object
"""
global _mt4s
if alias in _mt4s:
... | ee228ced5790124768c8a41e70bf596181a55ca2 | 13,588 |
import warnings
def get_log_probability_function(model=None):
"""
Builds a theano function from a PyMC3 model which takes a numpy array of
shape ``(n_parameters)`` as an input and returns returns the total log
probability of the model. This function takes the **transformed** random
variables defi... | 8e4332ce6943341b196d1628942f3360ce9f4e05 | 13,589 |
def get_health(check_celery=True):
"""
Gets the health of the all the external services.
:return: dictionary with
key: service name like etcd, celery, elasticsearch
value: dictionary of health status
:rtype: dict
"""
health_status = {
'etcd': _check_etcd(),
'sto... | 95fec6ee762ab81a8e27ebe796b914be6d38c59d | 13,590 |
def add_quotation_items(quotation_items_data):
"""
添加信息
:param quotation_items_data:
:return: None/Value of user.id
:except:
"""
return db_instance.add(QuotationItems, quotation_items_data) | 09f60cc4e8182909acb34bb0b406336849bf8543 | 13,591 |
def load_cifar10_human_readable(path: str, img_nums: list) -> np.array:
"""
Loads the Cifar10 images in human readable format.
Args:
path:
The path to the to the folder with mnist images.
img_nums:
A list with the numbers of the images we want to load.
Returns:
... | 991ff4cd7192c0ed4b1d6e2d566ed1f0ce446db5 | 13,592 |
import os
def identity(target_ftrs, identity_ftrs, output_name=None, output_folder=None, cluster_tolerance="",
problem_fields={}, full_out_path=""):
""" perform identity analysis on target feature class with identity
feature class """
try:
output_location = IN_MEMORY
out_f... | 1d0e9cc4e4d68cc8da8ddbefff18629ccc01266c | 13,593 |
import typing
def get_project_linked_to_object(object_id: int) -> typing.Optional[Project]:
"""
Return the project linked to a given object, or None.
:param object_id: the ID of an existing object
:return: the linked project or None
:raise errors.ObjectDoesNotExistError: if no object with the giv... | 189282be5acfb063678ca2c6765eeb1a7fa6b6c5 | 13,594 |
from typing import Union
from pathlib import Path
import os
def processor(template: Union[str, Path] = None, format_name: str = None) -> Union[None, RecordProcessor]:
"""
Configures the record level processor for either the template or for the format_name
Args:
template: path to template or templ... | 7cbe291f1a41e9d00e15c721ad73ffc69e0f49e0 | 13,595 |
def calc_distances_for_everyon_in_frame(everyone_in_frame, people_graph, too_far_distance, minimum_distance_change):
"""
:param everyone_in_frame: [PersonPath]
:type everyone_in_frame: list
:param people_graph:
:type people_graph: Graph
:param too_far_distance:
:param minimum_distance_... | 83dcb204b53d2ac784d1cc8bb0da61a114a41768 | 13,596 |
import torch
def conv2d(input: torch.Tensor,
weight: torch.Tensor,
bias: torch.Tensor = None,
stride=1,
padding=0,
dilation=1,
groups=1,
mode=None):
"""Standard conv2d. Returns the input if weight=None."""
if weight is None:
... | b43b975d96d273fa1ee1cfe4034ca1fd195b5019 | 13,597 |
import tqdm
import torch
def infer(model, loader_test):
"""
Returns the prediction of a model in a dataset.
Parameters
----------
model: PyTorch model
loader_test: PyTorch DataLoader.
Returns
-------
tuple
y_true and y_pred
"""
model.eval()
ys, ys_h... | 956b17d8b3869eeff6d35019ac82cd3ca5d4092e | 13,598 |
import keyword
def validate_project(project_name):
"""
Check the defined project name against keywords, builtins and existing
modules to avoid name clashing
"""
if not project_name_rx.search(project_name):
return None
if keyword.iskeyword(project_name):
return None
if proje... | 569fdb1d6d37ce50b144facc6cba725a0575b2f6 | 13,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.