content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_objective_by_task(target, task):
"""Returns an objective and a set of metrics for a specific task."""
if task == 'classification':
if target.nunique() == 2:
objective = 'binary'
else:
objective = 'multi'
elif task == 'regression':
objective = 'regressi... | 7859f84ba89246b735c61b3b31e421b38692de34 | 3,648,108 |
def pileupGenes(GenePositions,filename,pad=500000,doBalance=False,
TPM=0,CTCFWapldKO=False,TPMlargerthan=True,
minlength=0,maxlength=5000000,OE=None, useTTS=False):
"""
This function piles up Hi-C contact maps around genes, centered on TSSs or TTSs.
Inputs
------
Gene... | 671f575b09131f44f07d659bc8e195a16cd9e2f9 | 3,648,109 |
def model_cnn_2layer(in_ch, in_dim, width, linear_size=128):
"""
CNN, small 2-layer (default kernel size is 4 by 4)
Parameter:
in_ch: input image channel, 1 for MNIST and 3 for CIFAR
in_dim: input dimension, 28 for MNIST and 32 for CIFAR
width: width multiplier
"""
model = nn... | a08ec035cde3dd024ec32d85adb0af045fe845eb | 3,648,110 |
def reserve_api():
"""Helper function for making API requests to the /reserve API endpoints
:returns: a function that can be called to make a request to /reserve
"""
def execute_reserve_api_request(method, endpoint, **kwargs):
master_api_client = master_api()
return master_api_client(me... | d9e07fcd72742685443cd83f44eaed074a8152dc | 3,648,113 |
import re
def extract_user_id(source_open_url):
"""
extract the user id from given user's id
:param source_open_url: "sslocal://profile?refer=video&uid=6115075278" example
:return:
"""
if source_open_url[10:17] != 'profile':
return None
try:
res = re.search("\d+$", source_... | 36d3e41c4361a29306650fc67c9f396efe92cd66 | 3,648,114 |
def prolog_rule(line):
"""Specify prolog equivalent"""
def specify(rule):
"""Apply restrictions to rule"""
rule.prolog.insert(0, line)
return rule
return specify | dde4840dc2f8f725d4c4c123aed7c978ec1948f9 | 3,648,115 |
def load_GloVe_model(path):
"""
It is a function to load GloVe model
:param path: model path
:return: model array
"""
print("Load GloVe Model.")
with open(path, 'r') as f:
content = f.readlines()
model = {}
for line in content:
splitLine = line.split()
word = ... | 40e8fe203b195621b776ea3650bb531956769b48 | 3,648,116 |
import numpy
def quadratic_program() -> MPQP_Program:
"""a simple mplp to test the dimensional correctness of its functions"""
A = numpy.array(
[[1, 1, 0, 0], [0, 0, 1, 1], [-1, 0, -1, 0], [0, -1, 0, -1], [-1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0],
[0, 0, 0, -1]])
b = numpy.array([350, 6... | 71d5d9b872572e05b86e640006c58cc407c76ec4 | 3,648,117 |
def snr(flux, axis=0):
""" Calculates the S/N ratio of a spectra.
Translated from the IDL routine der_snr.pro """
signal = np.nanmedian(flux, axis=axis)
noise = 1.482602 / np.sqrt(6.) * np.nanmedian(np.abs(2.*flux - \
np.roll(flux, 2, axis=axis) - np.roll(flux, -2, axis=axis)), \
... | 964362545e2fb8a0e7f15df71d90c5ce3e2f5815 | 3,648,119 |
def subtract_images(img_input, img_output, img_height, img_width):
"""Subtract input and output image and compute difference image and ela image"""
input_data = img_input.T
output_data = img_output.T
if len(input_data) != len(output_data):
raise Exception("Input and Output image have different s... | 7b2b2df57055cc73bec85bed2a5bece8187ddcdf | 3,648,120 |
import ctypes
def k4a_playback_get_track_name(playback_handle, track_index, track_name, track_name_size):
"""
K4ARECORD_EXPORT k4a_buffer_result_t k4a_playback_get_track_name(k4a_playback_t playback_handle,
size_t track_index,
char *track_name,
size_t *track_name_si... | 872c5aa73f9520f178fdbdfe47c314f9043282c0 | 3,648,121 |
def recommend_lowercase_d(data: pd.Series, **kwargs) -> int:
"""Returns the recommended value of differencing order 'd' to use
Parameters
----------
data : pd.Series
The data for which the differencing order needs to be calculated
*kwargs: Keyword arguments that can be passed to the differ... | a249ed104c00e62f386f82c5c4aaecc7cf0c4001 | 3,648,122 |
from typing import Dict
import json
def get_player_current_games_to_move(username: str) -> Dict:
"""Public method that returns an array of Daily Chess games
where it is the player's turn to act
Parameters:
username -- username of the player
"""
r = _internal.do_get_request(f"/player/{use... | 1ce906d24fa278703d708d41ed753c2cb24b48d0 | 3,648,123 |
def get_rb_data_attribute(xmldict, attr):
"""Get Attribute `attr` from dict `xmldict`
Parameters
----------
xmldict : dict
Blob Description Dictionary
attr : str
Attribute key
Returns
-------
sattr : int
Attribute Values
"""
try:
sattr = int(xml... | dfc48ad47f67b2303874154ce4a164a176c1f4bf | 3,648,124 |
def tls_params(mqtt_config):
"""Return the TLS configuration parameters from a :class:`.MQTTConfig`
object.
Args:
mqtt_config (:class:`.MQTTConfig`): The MQTT connection settings.
Returns:
dict: A dict {'ca_certs': ca_certs, 'certfile': certfile,
'keyfile': keyfile} with the TL... | 4b5d214a50fea60f5cb325fc7a0c93dfa9cb3c02 | 3,648,127 |
def is_admin():
"""Check if current user is an admin."""
try:
return flask.g.admin
except AttributeError:
return False | 0922a93afacc4002068b60f1ab8a6594f0ddb44a | 3,648,128 |
def statistic():
""" RESTful CRUD Controller """
return crud_controller() | 02ed03d6d7d159046c12cbea98cc69c7bb0ae024 | 3,648,129 |
def segment_range_to_fragment_range(segment_start, segment_end, segment_size,
fragment_size):
"""
Takes a byterange spanning some segments and converts that into a
byterange spanning the corresponding fragments within their fragment
archives.
Handles prefix, suff... | e20c9bb55d9d3e90beb20bed7a170d1066611ba9 | 3,648,131 |
import collections
def update_dict(d, u):
""" Recursively update dict d with values from dict u.
Args:
d: Dict to be updated
u: Dict with values to use for update
Returns: Updated dict
"""
for k, v in u.items():
if isinstance(v, collections.Mapping):
default ... | e0228d3d0946f20b4bad8bfbc94a725f62bddfc5 | 3,648,132 |
def get_dataset(args, tokenizer, evaluate=False):
"""Convert the text file into the GPT-2 TextDataset format.
Args:
tokenizer: The GPT-2 tokenizer object.
evaluate: Whether to evalute on the dataset.
"""
file_path = args.eval_data_file if evaluate else args.train_data_file
if args.l... | 493bd0a5ca548b08052717d7e343e4f8b8911cb1 | 3,648,133 |
def test_function_decorators():
"""Function Decorators."""
# Function decorators are simply wrappers to existing functions. Putting the ideas mentioned
# above together, we can build a decorator. In this example let's consider a function that
# wraps the string output of another function by p tags.
... | 03b3ba299ceb7a75b0de1674fabe892243abd8b3 | 3,648,134 |
def make_loci_field( loci ):
""" make string representation of contig loci """
codes = [L.code for L in loci]
return c_delim2.join( codes ) | a643f70f02c3b79214d76f82bb4379ea0c0e1e84 | 3,648,135 |
import tqdm
def compute_wilderness_impact1(ground_truth_all, prediction_all, video_list, known_classes, tiou_thresholds=np.linspace(0.5, 0.95, 10)):
""" Compute wilderness impact for each video (WI=Po/Pc < 1)
"""
wi = np.zeros((len(tiou_thresholds), len(known_classes)))
# # Initialize true positive a... | 5f921d93993df1431c7b703df591f710cb2b5628 | 3,648,136 |
def require_client(func):
"""
Decorator for class methods that require a client either through keyword
argument, or through the object's client attribute.
Returns:
A wrapped version of the function. The object client attrobute will
be passed in as the client keyword if None is provided.... | 28cfd4821405a132cde4db8b95c68987db76b99d | 3,648,138 |
import base64
def format_template(string, tokens=None, encode=None):
"""Create an encoding from given string template."""
if tokens is None:
tokens = {}
format_values = {"config": config,
"tokens": tokens}
result = string.format(**format_values)
if encode == "base64":... | 91dafa48c0a9f17bbd663bcc14cfb800f6f57877 | 3,648,140 |
import six
def make_datastore_api(client):
"""Create an instance of the GAPIC Datastore API.
:type client: :class:`~google.cloud.datastore.client.Client`
:param client: The client that holds configuration details.
:rtype: :class:`.datastore.v1.datastore_client.DatastoreClient`
:returns: A datast... | 63ab5acf85bcd2df9d266d285887c624a7554c64 | 3,648,142 |
def _mul_certain(left, right):
"""Multiplies two values, where one is certain and the other is uncertain,
and returns the result."""
if _is_number(left):
return Uncertain(
value=right.value * left,
delta=right.delta,
)
return Uncertain(
value=lef... | ae6159d1f59daea13794aa0ee0fb8baadf647471 | 3,648,143 |
def felica_RequestSystemCode(): # -> (int, List[int]):
"""
Sends FeliCa Request System Code command
:returns: (status, systemCodeList)
status 1: Success, < 0: error
systemCodeList System Code list (Array length should longer than 16)
"""
cmd = bytearra... | ff380077daef948a6a3ad274a9accccea22fcba1 | 3,648,144 |
from typing import Optional
from typing import Callable
import types
def get_regularizer(
regularizer_type: str, l_reg_factor_weight: float
) -> Optional[Callable[[tf.Tensor], Optional[tf.Tensor]]]:
"""Gets a regularizer of a given type and scale.
Args:
regularizer_type: One of types.RegularizationType
... | c9f7f8dd227a7446c9b15aebf1e2f1065a3d810d | 3,648,145 |
def metadata():
"""Returns shared metadata instance with naming convention."""
naming_convention = {
'ix': 'ix_%(column_0_label)s',
'uq': 'uq_%(table_name)s_%(column_0_name)s',
'ck': 'ck_%(table_name)s_%(constraint_name)s',
'fk': 'fk_%(table_name)s_%(column_0_name)s_%(referred_ta... | 25363d243a2474dfbd43d57ff794899bfe30a44d | 3,648,146 |
import time
def date_rss(dte=None):
"""Dtate au format RSS """
ctime = time if dte is None else time.mktime(dte.timetuple())
return ctime.strftime('%a, %d %b %Y %H:%M:%S %z') | 6c343b675be5b89051fe9d76a9fb6437e89611bb | 3,648,147 |
def generate_parallelogrammatic_board(width=5, height=5):
"""
Creates a board with a shape of a parallelogram.
Width and height specify the size (in fields) of the board.
"""
return [[1] * height for _ in range(width)] | 1c9bd6e6e26f6693b434d44e6dbe4085ba9236b8 | 3,648,149 |
def function_is_even(latex_dict: dict) -> str:
"""
colloquially,
sympy.cos(x)==sympy.cos(-x)
sympy.cos(x) - sympy.cos(-x) == 0
>>> latex_dict = {}
>>> latex_dict['input'] = [{'LHS': parse_latex(''), 'RHS': parse_latex('')}]
>>> latex_dict['feed'] = [parse_latex('')]
>>> latex_dict['out... | 0169440f0ebe373efdc18b79a1b8f48220fada13 | 3,648,150 |
def summarize_curriculum(
curriculum: AbstractCurriculum,
) -> str:
"""
Generate a detailed string summarizing the contents of the curriculum.
:return: A string that would print as a formatted outline of this curriculum's contents.
"""
def maybe_plural(num: int, label: str):
return f"{... | 010f3fb38473d0a572616204c381bde04f83fb0e | 3,648,151 |
def get_solarsample():
"""
NAME:
get_solarsample
PURPOSE:
get the RC sample at solar abundances
INPUT:
None so far
OUTPUT:
sample
HISTORY:
2015-03-18 - Started - Bovy (IAS)
"""
# Get the full sample first
data= get_rcsample()
# Now cut it
lo... | e511dbfdf013528f1bba3c7d794d776a2791e918 | 3,648,152 |
from typing import List
def perform_context_selection(
estimation_tasks: List[EstimationTask],
) -> List[EstimationTask]:
"""Changes the circuits in estimation tasks to involve context selection.
Args:
estimation_tasks: list of estimation tasks
"""
output_estimation_tasks = []
for est... | 814a5dd72a6c4b76c52af606c3136a6fd1cb46d9 | 3,648,153 |
import torch
def where(condition, x, y):
"""Wrapper of `torch.where`.
Parameters
----------
condition : DTensor of bool
Where True, yield x, otherwise yield y.
x : DTensor
The first tensor.
y : DTensor
The second tensor.
"""
return torch.where(condition, x, y) | 0ec419e19ab24500f1be6c511eb472d1d929fe2c | 3,648,154 |
def ukhls_wave_prefix(columns, year):
""" Determine wave prefix for ukhls wave data.
Parameters
----------
columns : list
A list of column names to add wave prefixes to.
year : int
Which wave year is being processed.
Returns
-------
columns : list
Column names w... | 726cc3a153ad9c43ebd99b96c405ab4bbd8ff56c | 3,648,155 |
from typing import Iterable
from typing import Optional
from typing import List
from typing import cast
def sort_converters(converters: Iterable[Optional[GenericConverter]]) -> List[GenericConverter]:
"""
Sort a list of converters according to their priority.
"""
converters = cast(Iterable[GenericConv... | 8112bfe4da1154c0b0e5aa421cf3c6d90148cbed | 3,648,156 |
def createPolygon(fire):
"""
create a Polygon object from list of points
"""
points = []
for coordinate in fire["geometry"]["coordinates"][0]:
points.append(tuple(coordinate))
polygon = Polygon(points)
return polygon | ce985b494d0d56f9b44a684ab187fb290d0c5d4f | 3,648,159 |
def change_anim_nodes(node_object="", in_tangent='linear', out_tangent='linear'):
"""
Changes the setting on all anim nodes.
:param node_object:
:param in_tangent:
:param out_tangent:
:return: <bool> True for success. <bool> False for failure.
"""
anim_nodes = object_utils.get_connected_... | 649f740669c2f292bfc180895a2ce5d295b2ef68 | 3,648,160 |
def is_x_degenerated(x, codon, table):
"""Determine if codon is x-fold degenerated.
@param codon the codon
@param table code table id
@param true if x <= the degeneration of the codon
"""
return (x <= len(altcodons(codon, table))) | b6a6bd8afc21a8e9b94dc7aa086255b6dfa44e85 | 3,648,161 |
import torch
def get_long_tensor(tokens_list, batch_size, pad_id=constant.PAD_ID):
""" Convert (list of )+ tokens to a padded LongTensor. """
sizes = []
x = tokens_list
while isinstance(x[0], list):
sizes.append(max(len(y) for y in x))
x = [z for y in x for z in y]
tokens = torch.L... | d088277fcd8f599d142ff7bdb1b8e018c5b6c1cb | 3,648,162 |
def business():
"""
show business posts
"""
business = Post.query.filter_by(category="Business").all()
return render_template('business.html', post=business) | 2fd3a46391681a25cdb3291f0a92e110dc0d4eb3 | 3,648,163 |
def tile_image(x_gen, tiles=()):
"""Tiled image representations.
Args:
x_gen: 4D array of images (n x w x h x 3)
tiles (int pair, optional): number of rows and columns
Returns:
Array of tiled images (1 x W x H x 3)
"""
n_images = x_gen.shape[0]
if not tiles:
for i in range(int(np.sqrt(n_im... | d95a9cd12f6ba4239724b84efd701575678f217f | 3,648,164 |
def note_updated_data(note, role):
"""Return the data for updated date
:param note: the note that holds the data
:type note: :class:`jukeboxcore.djadapter.models.Note`
:param role: item data role
:type role: QtCore.Qt.ItemDataRole
:returns: data for the updated date
:rtype: depending on rol... | 987e78ae0c5a7a4570b619520d8b20f592adae07 | 3,648,165 |
def _xyz_atom_coords(atom_group):
"""Use this method if you need to identify if CB is present in atom_group and if not return CA"""
tmp_dict = {}
for atom in atom_group.atoms():
if atom.name.strip() in {"CA", "CB"}:
tmp_dict[atom.name.strip()] = atom.xyz
if 'CB' in tmp_dict:
... | fd7ef43b1935f8722b692ad28a7e8b309033b720 | 3,648,166 |
import pathlib
def InitBareRepository(path):
"""Returns the Repo object"""
assert isinstance(path, str)
pathlib.Path(path).parent.mkdir(parents=True,exist_ok=True)
return git.Repo.init(path,bare=True) | 84b321c7b27ee8ab7101339671361f45ec474e91 | 3,648,167 |
def get_http_exception(code):
"""Return an exception class based on its code"""
try:
return http_exceptions[int(code)]
except:
return None | f7b5077331b4425d5ee49a8c61849bb6ba822049 | 3,648,168 |
from typing import Union
def _gradients_input(model: Union[tf.keras.models.Model, 'keras.models.Model'],
x: tf.Tensor,
target: Union[None, tf.Tensor]) -> tf.Tensor:
"""
Calculates the gradients of the target class output (or the output if the output dimension is equal... | 816c1f932533de4cdfd96525c44a2c11bae60254 | 3,648,170 |
from typing import OrderedDict
def get_databases():
"""Return an ordered dict of (dbname: database). The order is
according to search preference, the first DB to contain a document
should be assumed to be the authoritative one."""
sql_dbs = [
_SQLDb(
XFormInstanceSQL._meta.db_table... | 01180d4cafbcf0b1d48e7c7554069a7ee5bf1a65 | 3,648,172 |
def list_examples():
"""List all examples"""
examples = ExampleModel.query()
form = ExampleForm()
if form.validate_on_submit():
example = ExampleModel(
example_name=form.example_name.data,
example_description=form.example_description.data,
added_by=users.get_c... | 740e7005e1cadae22ba77095b43dadd6b4219012 | 3,648,174 |
import re
def parse_direct_mention(message_text):
"""
Finds a direct mention (a mention that is at the beginning) in message text
and returns the user ID which was mentioned. If there is no direct mention, returns None
"""
matches = re.search(_MENTION_REGEX, message_text)
# the first g... | b442dc276cde0e28b56fbf855999feaeb199bff2 | 3,648,175 |
import types
def prepare_deep(schema: types.Schema, schemas: types.Schemas):
"""
Resolve $ref and merge allOf including for object properties and items.
Assume the schema is a valid JSONSchema.
Args:
schema: The schema to prepare.
schemas: The schemas from which to resolve any $ref.
... | e77f7f0e59a6400c2e7df78b0ec2a14bcc0b3ea6 | 3,648,176 |
def _resize_and_center_fundus(image, diameter):
"""
Helper function for scale normalizing image.
"""
copy = image.copy()
# Find largest contour in image.
contours = _find_contours(image)
# Return unless we have gotten some result contours.
if contours is None:
return None
... | f301740cec8ca423334ffd127005b90f54105ce5 | 3,648,177 |
def _pad_X_delta(X, delta, indices, padded_group_size):
"""Currently Unused."""
X_group = onp.take(X, indices, axis=0)
X_group = onp.pad(X_group, [(0, padded_group_size - X_group.shape[0]),
(0, 0)])
delta_group = onp.take(delta, indices, axis=0)
delta_group = onp.pad(delta_group... | d286b922efb6482382af8cd804c5e51b15d93088 | 3,648,178 |
def union(x, y=None):
"""Get sorted list of elements combined for two iterables."""
x, y = de_list_pair(x, y)
return sorted(list(set(x) | set(y))) | c24deb82e60569196e7a2d691db192c0ffcf91dd | 3,648,179 |
from typing import get_origin
from typing import Tuple
def is_tuple(typ) -> bool:
"""
Test if the type is `typing.Tuple`.
"""
try:
return issubclass(get_origin(typ), tuple)
except TypeError:
return typ in (Tuple, tuple) | c8c75f4b1523971b20bbe8c716ced53199150b95 | 3,648,180 |
import functools
import unittest
def _skip_if(cond, reason):
"""Skip test if cond(self) is True"""
def decorator(impl):
@functools.wraps(impl)
def wrapper(self, *args, **kwargs):
if cond(self):
raise unittest.SkipTest(reason)
else:
impl(s... | 4141cc1f99c84633bdf2e92941d9abf2010c11f6 | 3,648,181 |
def permute_columns(df,
column_to_order: str,
ind_permute: bool = False,
columns_to_permute: list = []):
"""
Author: Allison Wu
Description: This function permutes the columns specified in columns_to_permute
:param df:
:param column_to_orde... | 89da810d93586d66963d9a3ee3c7d6c0960596c9 | 3,648,183 |
def reset_dismissed(institute_id, case_name):
"""Reset all dismissed variants for a case"""
institute_obj, case_obj = institute_and_case(store, institute_id, case_name)
controllers.reset_all_dimissed(store, institute_obj, case_obj)
return redirect(request.referrer) | c16dcc7e23be620212ee6756051db6e089014678 | 3,648,184 |
def texts_from_array(x_train, y_train, x_test=None, y_test=None,
class_names = [],
max_features=MAX_FEATURES, maxlen=MAXLEN,
val_pct=0.1, ngram_range=1, preprocess_mode='standard', verbose=1):
"""
Loads and preprocesses text data from arrays.
Args:
... | ecb120070ac76d21da34fd5f0d27799fe5ba093b | 3,648,186 |
def display2(depts, level=0):
"""
[[a, 1], [b, 2], [c, 3], [d, 3], [a, 1]]
:param depts:
:return:
"""
lists = []
for d in depts:
lists.append([d, level])
children = Department.objects.filter(parent_id=d.id)
if children:
lists.extend(display2(children, leve... | 6187c91dd5653ab3f7a7e68d6b811ffda2afb035 | 3,648,187 |
def _get_target_id_to_skill_opportunity_dict(suggestions):
"""Returns a dict of target_id to skill opportunity summary dict.
Args:
suggestions: list(BaseSuggestion). A list of suggestions to retrieve
opportunity dicts.
Returns:
dict. Dict mapping target_id to corresponding skil... | faf708abb5876a56b06282b99c4cc7221c33c5bd | 3,648,188 |
def default_loc_scale_fn(
is_singular=False,
loc_initializer=tf.random_normal_initializer(stddev=0.1),
untransformed_scale_initializer=tf.random_normal_initializer(
mean=-3., stddev=0.1),
loc_regularizer=None,
untransformed_scale_regularizer=None,
loc_constraint=None,
untransformed_s... | 54eeec1b5739a71473abfa5a5ffb7aa5aa572505 | 3,648,189 |
from skimage.morphology import disk
from cv2 import dilate
def db_eval_boundary(args):
"""
Compute mean,recall and decay from per-frame evaluation.
Calculates precision/recall for boundaries between foreground_mask and
gt_mask using morphological operators to speed it up.
Arguments:
f... | 0aa23d0d8b45681e50f3b99c72dfcb5851dd92a6 | 3,648,190 |
def angle_trunc(a):
"""
helper function to map all angles onto [-pi, pi]
"""
while a < 0.0:
a += pi * 2
return ((a + pi) % (pi * 2)) - pi | 36e5d97affab5f3a1155b837df9985fe26795d76 | 3,648,191 |
from typing import Optional
def get_tag_or_default(
alignment: pysam.AlignedSegment, tag_key: str, default: Optional[str] = None
) -> Optional[str]:
"""Extracts the value associated to `tag_key` from `alignment`, and returns a default value
if the tag is not present."""
try:
return alignment.g... | bf3b1495224d7409c410f96daa20af8f70a27efa | 3,648,192 |
def vtln_warp_mel_freq(vtln_low_cutoff, vtln_high_cutoff, low_freq, high_freq,
vtln_warp_factor, mel_freq):
"""
Inputs:
vtln_low_cutoff (float): lower frequency cutoffs for VTLN
vtln_high_cutoff (float): upper frequency cutoffs for VTLN
low_freq (float): lower freq... | e6432c0298e559dc958011bdf5d52c3e92544213 | 3,648,193 |
def _squared_loss_and_spatial_grad_derivative(X, y, w, mask, grad_weight):
"""
Computes the derivative of _squared_loss_and_spatial_grad.
Parameters
----------
X : ndarray, shape (n_samples, n_features)
Design matrix.
y : ndarray, shape (n_samples,)
Target / response vector.
... | 05ce984609f5d31fda33d7fb0263ecc056c2f0ed | 3,648,194 |
import ctypes
def destructor(cfunc):
"""
Make a C function a destructor.
Destructors accept pointers to void pointers as argument. They are also wrapped as a staticmethod for usage in
classes.
:param cfunc: The C function as imported by ctypes.
:return: The configured destructor.
"""
... | 05abd181649a2178d4dce704ef93f61eb5418092 | 3,648,195 |
def invalid_auth_header(jwt):
"""Produce invalid JWT tokens for use in tests."""
return {'Authorization': 'Bearer ' + jwt.create_jwt(claims=TestJwtClaims.invalid, header=JWT_HEADER)} | 91f82b4a9be3740e115da4182325c71fa84440b7 | 3,648,196 |
def update_file_info_in_job(job, file_infos):
"""
Update the 'setup.package.fileInformations' data in the JSON to append new file information.
"""
for file_info in file_infos:
try:
job['setup']['package']['fileInformations'].append(file_info)
except (KeyError, TypeError, Attr... | 9902173548d72fcd35c8f80bb44b59aac27d9401 | 3,648,197 |
def _FirstStatementsInScriptElements(contents):
"""Returns a list of first statements found in each <script> element."""
soup = parse_html.BeautifulSoup(contents)
script_elements = soup.find_all('script', src=None)
return [_FirstStatement(e.get_text()) for e in script_elements] | 7b2a3bddfa63a6ab4765906862037adf786c253a | 3,648,198 |
def load_image(input_file_path):
"""
Load the 'input_file_path' and return a 2D numpy array of the image it contains.
"""
image_array = np.array(pil_img.open(input_file_path).convert('L'))
return image_array | b5783b9bcca55be355a91c6e9e2d2fcd09d1989b | 3,648,199 |
def ask_the_user(runner: Runner) -> Direction:
"""Ask the user what to do (in absolute UP, DOWN, etc.)"""
return runner.ask_absolute() | 2f289aba30e1368abd675a9b9bb2be0924984d3d | 3,648,200 |
def optimize_spot_bid(ctx, instance_type, spot_bid):
"""
Check whether the bid is sane and makes an effort to place the instance in a sensible zone.
"""
spot_history = _get_spot_history(ctx, instance_type)
if spot_history:
_check_spot_bid(spot_bid, spot_history)
zones = ctx.ec2.get_all_z... | 25bd3d9c952c256df12c3cc7efa257629d127af9 | 3,648,202 |
def new_hassle_participants():
"""Select participants for the room helpers."""
# Get a list of all current members.
members = helpers.get_all_members()
return flask.render_template('hassle_new_participants.html', members=members) | c8062ae498691ac72a17a969cf2ba7547e08eb9c | 3,648,203 |
import json
def data_store_remove_folder(request):
"""
remove a sub-folder/sub-collection in hydroshareZone or any federated zone used for HydroShare
resource backend store. It is invoked by an AJAX call and returns json object that include a
status of 'success' if succeeds, and HttpResponse of status... | d6583dca0967fdf282a3510defcdeeb70da6c7f7 | 3,648,204 |
import math
def distance(x1: float, y1: float, x2: float, y2: float) -> float:
"""
Finds distance between two given points
Parameters:
x1, y1 : The x and y coordinates of first point
x2, y2 : The x and y coordinates of second point
Returns:
... | 63f103f46b52aae146b52f385e15bc3441f042e5 | 3,648,205 |
def load_target_class(input_dir):
"""Loads target classes."""
df = pd.read_csv(join(input_dir, "target_class.csv"), header=None, index_col=0, names=["Target"])
return df | 58fea2aebd6c04dd0b51ec3ef3fc627212aa2b29 | 3,648,206 |
def fix_labels(ply_gt, ply_seg):
"""
Remove extra vertices from the ground truth
"""
size = len(ply_gt.elements[0]["x"])
gt_x = np.array(ply_gt.elements[0]["x"])
seg_x = np.array(ply_seg.elements[0]["x"])
new_gt_label = np.zeros_like(seg_x)
gt_label = np.array(ply_gt.elements[0]["labe... | 291fedd887b82e6099f5aba6a006fd0e33a7fb18 | 3,648,208 |
import requests
def get_coin_price(api_url: str, currency: str) -> float:
"""
Get the USD price of a coin from Gemini
Args:
api_url: The API URL for Gemini
currency: The cryptocurrency the bot is monitoring
Returns:
coin_price: The price the coin currently holds in USD
"""
# Inst... | 0683554aea85faa1dd105cbf81144685d7d2deec | 3,648,209 |
import hmac
import base64
def GenerateAuthToken(key_name, user_id, action_id='', when=None):
"""Generates a URL-safe token based on XSRFToken but for generla purpose.
Args:
key_name (str): name of secret key to generate token.
user_id (str): the user ID of the authenticated user.
action_id (str): a s... | 8375889ba4cdc1fc996c48330cf0cd23824f5946 | 3,648,210 |
import torch
def get_dataset_psnr(device, model, dataset, source_img_idx_shift=64,
batch_size=10, max_num_scenes=None):
"""Returns PSNR for each scene in a dataset by comparing the view predicted
by a model and the ground truth view.
Args:
device (torch.device): Device to per... | 0ce2274aac72d2510fd0c9c067a6efa542c103ec | 3,648,212 |
def smallest_continuous_multiple(max_multiple):
"""
Function takes an int, and returns the smallest natural number evenly divisible by all numbers
less than or equal to the input max_multiple.
REQ: max_multiple >= 0 and whole
:param max_multiple: {int}
:return: smallest natural number evenly d... | 57423ed0941d18b54a1da33bc561f79ed19ae145 | 3,648,213 |
def context_list_entities(context):
"""
Returns list of entities to be displayed in list view
"""
# log.info(context['List_rows'])
if 'List_rows' in context:
return context['List_rows']['field_value']
elif 'entities' in context:
return context['entities']
log.warning("No enti... | 1b00e5cd6593a7e0c8770e9bbeaae5c3b47ac78a | 3,648,214 |
def run(arg):
"""Entry point"""
error_map = {}
validate_path(arg, None, error_map)
if len(error_map) > 0:
error_count = 0
for file, errors in error_map.items():
print(f"Error in {file}:")
for error in errors:
print(f" {error}")
e... | 0e124b87b62076af713b8caea686e3c44a4e83a2 | 3,648,215 |
import struct
def _bitcode_symbols_partial_impl(
*,
actions,
binary_artifact,
bitcode_symbol_maps,
dependency_targets,
label_name,
output_discriminator,
package_bitcode,
platform_prerequisites):
"""Implementation for the bitcode symbols proce... | 64606e63a7831a110585ceb83fb34699b373db0a | 3,648,216 |
def _str_trim_left(x):
"""
Remove leading whitespace.
"""
return x.str.replace(r"^\s*", "") | 2718086073706411929b45edf80a1d464dfaeff6 | 3,648,217 |
def zipcompress(items_list, flags_list):
"""
SeeAlso:
vt.zipcompress
"""
return [compress(list_, flags) for list_, flags in zip(items_list, flags_list)] | e8f85c058db442a967d89ef2f74e5e32cc58a737 | 3,648,218 |
def test_config_file_fails_missing_value(monkeypatch, presence, config):
"""Check if test fails with missing value in database configuration."""
def mock_file_config(self):
return {'database': {}}
monkeypatch.setattr(presence.builder, "fetch_file_config", mock_file_config)
status, msg = presen... | 34e14fa3b72fbd3a64930b9ce46da61e76138650 | 3,648,219 |
def construct_run_config(iterations_per_loop):
"""Construct the run config."""
# Parse hparams
hparams = ssd_model.default_hparams()
hparams.parse(FLAGS.hparams)
return dict(
hparams.values(),
num_shards=FLAGS.num_shards,
num_examples_per_epoch=FLAGS.num_examples_per_epoch,
resnet_ch... | d2989e795ab14a9931837356cb7a6c3752538429 | 3,648,220 |
def bezier_curve(points, nTimes=1000):
"""
Given a set of control points, return the
bezier curve defined by the control points.
Control points should be a list of lists, or list of tuples
such as [ [1,1],
[2,3],
[4,5], ..[Xn, Yn] ]
nTimes is ... | 3d4ea2a42e3e4bb7ff739b262e3fc69784656fed | 3,648,221 |
def _compact_temporaries(exprs):
"""
Drop temporaries consisting of isolated symbols.
"""
# First of all, convert to SSA
exprs = makeit_ssa(exprs)
# What's gonna be dropped
mapper = {e.lhs: e.rhs for e in exprs
if e.lhs.is_Symbol and (q_leaf(e.rhs) or e.rhs.is_Function)}
... | b28b839cc17124b83b6b26b972394486cd7d8741 | 3,648,222 |
def print_formula(elements):
"""
The input dictionary, atoms and their amount, is processed to produce
the chemical formula as a string
Parameters
----------
elements : dict
The elements that form the metabolite and their corresponding amount
Returns
-------
formula : str
... | a3c404ef0d18c417e44aee21106917f4ee203065 | 3,648,223 |
def try_get_code(url):
"""Returns code of URL if exists in database, else None"""
command = """SELECT short FROM urls WHERE full=?;"""
result = __execute_command(command, (url,))
if result is None:
return None
return result[0] | 63a88471f6fdfc44bc22383edda0eb65f9bf1b84 | 3,648,224 |
import unicodedata
def is_chinese_char(cc):
"""
Check if the character is Chinese
args:
cc: char
output:
boolean
"""
return unicodedata.category(cc) == 'Lo' | d376e6097e628ac2f3a7934ba42ee2772177f857 | 3,648,225 |
def resize_image(image, min_dim=None, max_dim=None, padding=False):
"""
Resizes an image keeping the aspect ratio.
min_dim: if provided, resizes the image such that it's smaller
dimension == min_dim
max_dim: if provided, ensures that the image longest side doesn't
exceed this value.
... | 17c8cb953753321f1aea169ebcb199598b7fd2f1 | 3,648,227 |
def idwt(approx, wavelets, h=np.array([1.0 / np.sqrt(2), -1.0 / np.sqrt(2)]),
g=np.array([1.0 / np.sqrt(2), 1.0 / np.sqrt(2)])):
"""
Simple inverse discrete wavelet transform.
for good reference: http://www.mathworks.com/help/wavelet/ref/dwt.html
@param approx: approximation of signal at low re... | a41cd22d81de733428123681bbea10837d4c7237 | 3,648,228 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.