content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def generate_new_model_for_dataset():
"""Return a feed forward model from scratch
https://www.kaggle.com/kabure/titanic-eda-model-pipeline-keras-nn"""
model = Sequential()
model.add(Dense(64, activation='relu', input_dim=26))
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.50))
... | d1e39366537f3c00e15c65661840548db0b55bc3 | 45,400 |
def loss(params, batch, model_predict):
"""Calculate loss."""
inputs, targets = batch
preds = model_predict(params, inputs)
return -np.mean(preds * one_hot(targets, preds.shape[-1])) | aa33dbba5939a54a4b18395f33497680dc13399c | 45,401 |
def Action(name):
""" Registers any function with this decorator onto the ACTIONS dict
under the key of it's name; this decorator also registers the
parameters that the function takes, sorting them under
static params (those passed in from the database configuration) and/or
dymanic p... | fe556e767525e2f450566f5368252a31babdb2f2 | 45,402 |
def get_anime_class(url):
"""
Get anime class corresposing to url or name.
See :py:data:`anime_downloader.sites.ALL_ANIME_SITES` to get the possible anime sites.
Parameters
----------
url: string
URL of the anime.
Returns
-------
:py:class:`anime_downloader.sites.anime.Anim... | df785074caef15ca2796e8b496faf04c04fa0098 | 45,403 |
from typing import cast
def create_cross_chain_payment(payment: Payment, dest_account: str) -> Payment:
"""
Creates a cross-chain payment transaction.
Args:
payment: The initial payment transaction. If the transaction is signed, then
it will need to be re-signed. There must be no more... | aefa751e1c8d4169a0cf5836e2f3f1ce7c9f30b5 | 45,404 |
def initialize_schur_ksp_obj(matrix_A, schur_approx):
"""
Creates a right-hand-side and solution PETSc4Py vector for
testing ksp solves.
Parameters
----------
matrix_A: :class:`PETSc.Mat`
Global matrix object.
schur_approx: :class:`LS.SchurPrecon`
Returns
-------
ksp_ob... | a4c3e6c8c7e2fe3f45999171738a0f3aeaa0edcc | 45,405 |
from typing import Mapping
from typing import Collection
import base64
import json
def build_response(
*,
request: reviews.Request,
outcomes: Mapping[ids.HandlerId, execution.Outcome],
warnings: Collection[str],
jsonpatch: patches.JSONPatch,
) -> reviews.Response:
"""
C... | 3cbf25b1a00800de83d7a25312bdbf07a674f6fd | 45,406 |
from operator import and_
def _get_fields_translation_data(session=DBSession):
"""
Obtaining Field table with all translations(TranslationAtom)
of it's name from DB session and returning it as:
dict {
(client_id, object_id): dict {
'field': models.F... | 0262182e7e9a0359ad3c00b0219f36c7c83651cd | 45,407 |
async def get_all_acls(request: web.Request) -> web.Response:
""" Get list of all access control lists in the system
:Example:
curl -H "authorization: $AUTH_TOKEN" -sX GET http://localhost:8081/fledge/ACL
"""
storage = connect.get_storage_async()
payload = PayloadBuilder().SELECT("name", "s... | 3bc04a3ef7ba19a192490266d7e7b4954716cd6f | 45,408 |
def hxltm_hastag_de_csvhxlated(csv_caput: list) -> list:
"""hxltm_hastag_de_csvhxlated [summary]
Make this type of conversion:
- 'item__conceptum__codicem' => '#item+conceptum+codicem'
- 'item__rem__i_ara__is_arab' => '#item+rem+i_ara+is_arab'
- '' => ''
Args:
csv_caput (list): Array o... | 1ab1503c26c86c969e699236f97842ae74ae0ae5 | 45,409 |
def add_payload_parameters(env_params):
"""
Adds the common parameters to be used by the extension scripts
:param dict[str, str] env_params: Dictionary to be added
:return: Dictionary with updated parameters
:rtype: dict[str, str]
"""
env_params["STRATOS_APPLICATION_PATH"] = cartridge_agent_... | 5a74ad9700682d3a865d0d0a080acfc5d322baab | 45,410 |
def sphere(p: np.array, radius: np.float) -> np.float:
"""
Sphere SDF
:param p: vec3 position
:param radius: radius
:return: signed distance
"""
return euclidean_length(p) - radius | 108b3b1a69504f1e29e94b16c670bc1dc42a0c60 | 45,411 |
import math
def conv_node(nodes, children, feature_size, output_size):
"""Perform convolutions over every batch sample."""
with tf.name_scope('conv_node'):
std = 1.0 / math.sqrt(feature_size)
w_t, w_l, w_r = (
tf.Variable(tf.random.truncated_normal([feature_size, output_size], stdd... | f52c84c3e53b55f78a722b63ca37c1f9e984755d | 45,412 |
def response_service_unavailable():
"""Returns a 503 error based on a static template"""
return HttpResponse(loader.render_to_string('503.html'), status=HTTP_SERVICE_UNAVAILABLE) | 919ecbfad29c42e5db9b66bc6b4156f5625df924 | 45,413 |
def little_endian_decode(array, word_size):
"""Transform array of words to one integer."""
return big_endian_decode(reversed(array), word_size) | 53d08792571650d54c1e04777d66e893f81a11d4 | 45,414 |
def plot(var_item, off_screen=False, full_screen=False, screenshot=None,
interactive=True, cpos=None, window_size=None,
show_bounds=False, show_axes=True, notebook=None, background=None,
text='', return_img=False, eye_dome_lighting=False, **kwargs):
"""
Convenience plotting function f... | 965aa70c3d1181ed99c9891c8d52cad4ad27ef4e | 45,415 |
import random
def gen_color():
"""
generate random color for WordCloud
"""
return "rgb(%s,%s,%s)" % (
random.randint(0, 160),
random.randint(0, 160),
random.randint(0, 160),
) | d0dfa4424293e68057c45376f0ccbc028020c66c | 45,416 |
def test_freeze():
"""
Frozen classes are completely immutable.
Users should not be able to mutate or add any
existing properties.
:return:
:rtype:
"""
# Initialize props and set properties to
# 1 and 2, respectively
frozen_class = fd.freeze(Props)(1, 2)
with pytest.raises(I... | 55fe15ff92053ee58e4a596b99533e41686fe18d | 45,417 |
def cmyk_to_rgb(color_values: tp.List[float]) -> tp.List[float]:
"""Converts list of CMYK values to RGB.
:param color_values: (list) 4-member CMYK color value list
:return: (list) 3-member RGB color value list
"""
return [round(1.0 - min(1.0, x + color_values[3]), 3) for x in color_values[:3]] | 09c144acbe83a8d871c8f50949810042cc9772bb | 45,418 |
def cancel_all():
"""Handles SocketIO request to cancel all goals"""
logger.info('Client requests to cancel all goals!')
return vtr_mission_planning.remote_client().cancel_all() | f6058f17cadee09c68706976e2de5b5d6e496a7a | 45,419 |
def group_iou_across_classes(gt_boxes: BoundingBoxGroup, pt_boxes: BoundingBoxGroup, as_iou=False):
"""
Compute the IoU between two boxes group set. For each class in each round, iteratively select a box from gt_boxes
and pick corresponding maximum IoU box in pt_boxes as pairs. After finished, compute I... | 871907abeb82aef4435b8605bcf878aa49adf789 | 45,420 |
def makeAnyJournal(items=3, attrib=None): # noqa
"""
Retorna uma lista de objetos ``Journal`` com atributos ``jid``,
``is_public`` e ``acronym`` limitando a quantidade pelo param ``items``.
Param attrib para adicionar atributo aos objecto do tipo Journal
"""
journals = []
for _ in range(it... | 29863d359a5c612cae0d47e172ba0a722557aa72 | 45,421 |
import urllib
import tempfile
def image_from_url(url):
"""
Read an image from a URL. Returns a numpy array with the pixel data.
Arguments:
url: urls for images for display
Outputs:
img: numpy array for the image
"""
try:
f = urllib.request.urlopen(url)
_, fname ... | e8a9365309bf1c76a9fe236fa99ca48da9ea3ca5 | 45,422 |
def humanify(code):
"""
Tries to interpret a Jpl object or site code as a human readable celestial
object name.
Args:
code (str): the code to be translated.
Returns:
str: the corresponding human readable name.
"""
if code.isdigit():
id_ = int(code)
elif code.sta... | d94d5a4809d3eb5899117a9e67fb3acbf0e116f9 | 45,423 |
from scrounger.utils.general import pretty_grep
import re
def extract_providers(decompiled_app_path):
"""
Extracts provider paths from a decompiled app directory using grep
:param str decompiled_app_path: the directory where to look for the
providers
:return: a sorted list of proviers
"""
... | ef11735abc24a37ede7ec095d6257039f0d0caf0 | 45,424 |
def stateToQd(x):
"""
Converts qd struct used in hardware to x vector used in simulation
x is 1 x 13 vector of state variables [pos vel quat omega]
qd is a struct including the fields pos, vel, euler, and omega
"""
qd = qd_object()
# current state
qd.pos = x[0:3]
qd.vel = x[3:6]
... | 8623592cf6a1703cd9b10eac46e69fde7babab9f | 45,425 |
def get_symbol_size(version, scale=1, border=None):
"""\
Returns the symbol size (width x height) with the provided border and
scaling factor.
:param int version: A version constant.
:param scale: Indicates the size of a single module (default: 1).
The size of a module depends on the us... | f26fb15b4b2bcec934ec2d0455bd04ba33480e82 | 45,426 |
def convert():
""" Writes the convert.inp file.
:return convert_inp_str: String for input file
:rtype: string
"""
convert_inp_str = 'MultiInputFile tst.inp'
return convert_inp_str | 698194568af4a35d4167f5ead7f5ead8f5379e1b | 45,427 |
import pickle
import os
import sys
import signal
def run_from_pickle(pickle_file):
"""
Launch an MPI calibration job from the specified picklefile
(usually built from awrals.calibration.cluster.build_pickle_from_spec)
Args:
pickle_file (str): Input pregenerated pickle file
Retur... | e9b2d812642f4bb3deedd2f75ac6ceb96d59ad43 | 45,428 |
def showVecMatrix(xvec, yvec, vals, full=False, **kwargs):
"""Plot three vectors as matrix.
Parameters
----------
xvec, yvec : iterable (e.g. list, np.array, pg.Vector) of identical length
vectors defining the indices into the matrix
vals : iterable of same length as xvec/yvec
vecto... | 2abcc12ca00ab0c6780af1be341fa3b3a984088d | 45,429 |
def infected_critical_case_rate_30():
"""
Real Name: b'infected critical case rate 30'
Original Eqn: b'Infected symptomatic 30*fraction of critical cases 30/symptomatic duration 30'
Units: b'person/Day'
Limits: (None, None)
Type: component
b''
"""
return infected_symptomatic_30() * ... | bc9ae461df93d070d6063310b2eaa9273192f956 | 45,430 |
def recover_public_key(message, signature, hasher=None):
"""
Recovers public key from signed message
:param message: message
:param signature: signature
:param hasher: hash function to use on message (usually sha256 or keccak_hash)
:return: public key
"""
if len(signature) != eth_common... | b3f9649ffa0d929a4fb7e92b4c5ea0d0fffae44f | 45,431 |
def descriptive_statistics(
master_path,
SG_tabs,
avl_recs_SG,
missing_recs_SG,
all_charts_num_1_,
all_charts_cat_1_,
print_report=False,
):
"""
:param master_path: Path containing the input files.
:param SG_tabs: 'measures_of_counts','measures_of_centralTendency','measures_of_ca... | f86317f3f229dad075aaeb4817bb172822b19545 | 45,432 |
def mocked_operations_create(monkeypatch):
"""Monkeypatch operations.create."""
mock_create = mock.MagicMock()
monkeypatch.setattr(operations, "create", mock_create)
return mock_create | 1732fbd7ba5f4a045d8f020fed1bbef138e0dd6b | 45,433 |
import random
def policy_gradient_loss(policy, model, dist_class, train_batch):
"""Example of using embedded eager execution in a custom loss.
Here `compute_penalty` prints the actions and rewards for debugging, and
also computes a (dummy) penalty term to add to the loss.
"""
def compute_penalty... | d4b71c8612d946d4284ecccb0780b060d757f9bf | 45,434 |
def preprocessing(df, attribute):
"""
This is the base preprocessing for french.
It scapes \ char and replace all ocurrence of -
:df: pandas data frame.
:attribute: atribute of df.
"""
return getattr(df, attribute).map(lambda sent: sent.lower().replace('\'', '\\\' ').replace('-', ' ')) | 6ca98d434ba5a43667b2dfc1501bf152f151c209 | 45,435 |
def ident_snapshot_test(arg):
"""
Used to build identification string for each autogenerated test (for easy recognition of failed tests).
:param arg: dict with information about rules.
:return: identification string with snapshot_id.
"""
if isinstance(arg, bool):
return "remediated" if ... | 2fc320d084294f4963cb60452ee577cc18c45763 | 45,436 |
import warnings
def find_num_fppeak_diff(llprops, blaze, n_init, n_fin, wave_blaze_thres,
xdiff_min, xdiff_max):
"""
:param llprops:
:param blaze:
:param n_init:
:param n_fin:
:param wave_blaze_thres:
:param xdiff_min:
:param xdiff_max:
:return:
"""
... | 0b711a58f3c1f4114ddd399398f5238b9dfdad2c | 45,437 |
def gcj2wgs_rough(gcjLat, gcjLon):
"""
GCJ-02 转 WGS-84 粗略版
"""
if outOfChina(gcjLat, gcjLon):
print("The latitude or longitude is out of China!")
return gcjLat, gcjLon
lat, lng = delta(gcjLat, gcjLon)
return gcjLat - lat, gcjLon - lng | f3c1652685f012f1199a3ef487224b4444ed80da | 45,438 |
import re
def target_expression(environment_file):
"""
Get the target expression from given file.
Parameters
----------
environment_file : str
Path and name of the environment file (giving the target relative
expression levels)
Returns
-------
target_expresstion :... | a8b351c2d57b4e19dcc505dcbcbeb532f2ab5f4d | 45,439 |
from typing import Optional
from typing import Dict
from typing import List
def extract_features(
self,
prev_output_tokens,
encoder_out: Optional[EncoderOut] = None,
incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None,
full_context_alignment: bool = False,
alignment_laye... | 4ef9ae35ecdc2120feffa91925cd4ab973485c3f | 45,440 |
from typing import Tuple
import io
def sanitize_screenshot(raw_png: bytes, real_size: Tuple[int, int]) -> Image.Image:
"""Processing screenshots taken by the browser."""
with io.BytesIO(raw_png) as f:
image = Image.open(f).convert("RGB")
return image.resize(real_size) | c9902cb1db35b17175a4f662b0ea369a6298e392 | 45,441 |
def read_h5_event_components(hdf_path):
"""
Read events from HDF5 file (Monash style).
@param hdf_path Path to HDF5 file
@returns Events as four np arrays with the event components
"""
f = h5py.File(hdf_path, 'r')
if 'events/x' in f:
#legacy
return (f['events/x'][:], f['event... | b13c623fcd208b878b1f7565958aa25a224782f8 | 45,442 |
def complex(real=0.0, imag=0.0):
"""Form a complex number.
Keyword arguments:
real -- the real part (default 0.0)
imag -- the imaginary part (default 0.0)
"""
if imag == 0.0 and real == 0.0:
return complex_zero | 2d7a6489517bf731e263be2a7a9a3a5f5ec9973f | 45,443 |
import operator
def product_upper_triangle(values, include_diagonal=False):
"""
Return an iterator over pairs, (v0, v1), drawn from values.
If `include_diagonal` is True, returns all pairs such that v0 <= v1.
If `include_diagonal` is False, returns all pairs such that v0 < v1.
"""
return all_... | 8741a1a12b38012f7e624116591ff77eb29d74a2 | 45,444 |
def current_filtered_positive_identifier() -> FilteredPositiveIdentifier:
"""Returns the current filtered positive identifier.
Returns:
{FilteredPositiveIdentifier} -- the current filtered positive identifier
"""
return FilteredPositiveIdentifierV3() | 349670a0614f5133776d593d2c01661eb06feb55 | 45,445 |
from typing import Optional
from typing import Dict
async def _create(pea: 'PeaModel', envs: Optional[Dict] = {}):
"""
.. #noqa: DAR101
.. #noqa: DAR201"""
try:
args = ArgNamespace.kwargs2namespace(pea.dict(), set_pea_parser())
return store.add(args, envs)
except Exception as ex:
... | 00ecda8032bed916d14dd418b2e52f442c939f76 | 45,446 |
import re
def non_numeric():
"""\\D: Non-numerical characters."""
return "{}dom is comming, tomorrow".format(
re.search(r'\D+', "4free").group()) | 0de9f4fc01c968bdbff534573071cbf8708842b6 | 45,447 |
def whataremyips():
"""
Get the machine's ip addresses
:returns: list of Strings of ip addresses
"""
addresses = []
for interface in netifaces.interfaces():
try:
iface_data = netifaces.ifaddresses(interface)
for family in iface_data:
if family not... | d4461b90607964362ad86e732221b9a9b496878e | 45,448 |
def update_book(sql: Session, book_id: int, book: BooksUpdate):
"""
Update a specific book
"""
old_data = sql.query(Books).filter(Books.BookId == book_id).first()
if old_data is not None:
new_data = book.dict()
old_data.Title = new_data["Title"]
old_data.AuthorId = new_data[... | 21d1673a1669e7c08fb13b3e60d5d327a820d561 | 45,449 |
def IsJsFile(ref):
"""Returns true if the provided reference is a JavaScript file."""
return ref.endswith('.js') | ad58dd41544c5b92ec629787d674cec34a1126c3 | 45,450 |
def calc_topk_accuracy(output, target, topk=(1,)):
"""
Modified from: https://gist.github.com/agermanidis/275b23ad7a10ee89adccf021536bb97e
Given predicted and ground truth labels,
calculate top-k accuracies.
"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1... | aedd1f4ca1b2b6be411d500ee8f82aef731e8913 | 45,451 |
import os
def inputs(dataset_name, total_batch_size, num_gpus, max_epochs, resized_size,
data_dir, split):
"""
A generalized implementation of input pipeline for different datasets.
:param dataset_name: the name of the dataset
:param total_batch_size: total number of instances per batch
... | cb2c42376420434ad6209a0328f8d89c2d972d36 | 45,452 |
def fix_faulty_url(data: DownloadData):
"""
Removes the tags ("...-OP1-NCBD.webm" -> "...,OP1,NCBD.webm" -> "...-OP1.webm")
Used when themes.moe returns a stupid url.
"""
if data['url'].count('-') == 1:
raise BadThemesUrl(f'Cannot get a good url for {data["url"]}')
else:
url = '-... | 4c606cbdaadce9757e88a7309cf50af0b2347f12 | 45,453 |
import json
def read_anno_Traff_mcl(anno_info):
"""Read the annotation.
if the dataset in ['Trafficlight_mcl'], this function will be used.
:return: boxes, klass, is_crowd
:rtype: tuple
"""
(anno_path, set_ignore, set_fake, label_map, tl_color_map, vehicle_person_id, boxes, klass, is_crowd) =... | 670f19df29de0818af2e57d52b2e9e863faf6f69 | 45,454 |
import asyncio
def get_delayed_hash(delay):
"""
Returns a delayed version for testing hash_func.
"""
async def delayed_hash(left, right):
await asyncio.sleep(delay)
return await hash_func(left, right)
return delayed_hash | b9441c45b51a35a6cbb923cee7f34f9a431e8696 | 45,455 |
def seek_revised(request):
"""Getting the investigations, studies and assays based on the
information given by the user in the upload form. The user selects
the project, investigation, study and assay. After selecting the assay
the user enter a title and description an can upload a data file to the
... | 6a35c3718f477cb1d80ef6d142757aa66b097580 | 45,456 |
def discriminative_instance_loss(y_true, y_pred,
delta_v=0.5,
delta_d=1.5,
gamma=1e-3):
"""Discriminative loss between an output tensor and a target tensor.
Args:
y_true: A tensor of the same shape as `y_... | 9c5b35e395117a7e495cf9cdcac96f7fec4f1caa | 45,457 |
def get_from_konrad(variable,exps):
"""Extracts a variable from the output files of several `konrad` experiments.
Parameters
----------
variable : str
Variable name in the output file.
exps : list
List of strings describing the paths to the output files.
Returns
-------
p,t ... | 5fd5389e1ce79f96632f013c983a371a57a91b20 | 45,458 |
def fence_vegalite(source, language, class_name, options, md, **kwargs):
"""
Inspired by https://github.com/facelessuser/pymdown-extensions/blob/8ee5b5caec8f9373e025f50064585fb9d9b71f86/pymdownx/superfences.py#L146
""" # noqa
if not _validateJSON(source):
raise SuperFencesException from Plugin... | 2194fb7aeb10b255462533dd128c3d116d9c1487 | 45,459 |
def ExportKeypointsToCOCO(image_ids,
detection_keypoints,
detection_scores,
detection_classes,
categories,
output_path=None):
"""Exports keypoints in numpy arrays to COCO API.
This func... | 8ef6a789296c095e6c5e2e2ead5d3f73b7ca0ce0 | 45,460 |
def to_monochrome(source, fmt):
""" Convert an image to monochrome """
img = Image.open(source)
img.convert(mode='1')
img.save(source, format=fmt.replace('jpg', 'jpeg') if fmt else None)
return source | 0eced011d204c362468bb72461a03bd4ba633a1b | 45,461 |
def dark_correct_arimg(
img: arimage.ARImage,
dark: arimage.ARImage) -> arimage.ARImage:
""" Dark corrects image """
logger.info("Dark correcting image: " + img.getFullPath())
logger.info(" with dark: " + dark.getFullPath())
# Load image data into memory if it is not already ... | d646b97473f694043487b6da2efd5779b20cfb09 | 45,462 |
def _inter_glyph_reuse_key(
view_box: Rect, painted_layer: PaintedLayer
) -> InterGlyphReuseKey:
"""Individual glyf entries, including composites, can be reused.
SVG reuses w/paint so paint is part of key."""
# TODO we could recycle shapes that differ only in paint, would just need to
# transfer th... | 3b84ac31b29813921caf0e443007918032af544d | 45,463 |
def isPathPolyIntersect(path, poly):
"""Given a path in the form of np.ndarray, return if it intersects with a given polygon.
:param path: ndarray, (\*, 2) a path represented by N by 2 matrice
"""
line = LineString(path)
intersect = line.intersects(poly)
print(intersect)
if isinstance(inter... | fc1d60a3fbaba2fd0e0b2d61c3e7408c0950f742 | 45,464 |
def convertMDSToCreateObjectExpression(mds, path, allowPrivate, name, pathToCodeDefinitionStrings):
"""given an MDS and a path, return an expression
that creates a module member and the type of module member."""
tree = convertMDSToSourceCodeTree(mds, name)
parser = ForaNative.ModuleParser()
resul... | 2ff722674ca00f06098c6a5a2a766137022750f3 | 45,465 |
import pickle
def load_pickle(file, decompress=True):
"""
Load a .pickle file.
:param file: file .pickle to load.
:param decompress: the compress or not the file
:return: loaded data.
"""
with open(file, "rb") as f:
if decompress:
data = pickle.load(f)
else:
... | ce86a034c87ddd3a74de40465d60cb2f55d1089c | 45,466 |
import os
def _calc_traceback_limit(tb):
"""Calculates limit-parameter to strip away pytypes' internals when used
with API from traceback module.
"""
limit = 1
tb2 = tb
while not tb2.tb_next is None:
try:
maybe_pytypes = tb2.tb_next.tb_frame.f_code.co_filename.split(os.sep)... | cfc02f590e952c3d90b5cef9e602342cfb26729f | 45,467 |
def latex(df):
"""Converte o DF fornecido para tabela LaTeX"""
return print(df.to_latex()) | 6ab524733ac1f9040699f349564cf4321ae6e909 | 45,468 |
def generate_king_attack_bb_from_square(from_square: int) -> np.uint64:
"""
Returns the king attack bitboard on an otherwise empty board from the provided square
:param from_square: starting square from which to generate king attacks
:return: np.uint64 bitboard representation of king attacks on an other... | 4f7d556c67e7897d1502afa82783e811b9739919 | 45,469 |
def get_review_by_product(request, id):
"""get reviews of certain product and return render"""
prod = get_object_or_404(Product, pk=id) # get product
related = Review_Connector.objects.all().select_related().filter(product_id=id)
context = {'review_connected': related,
"product_id": ... | f18b1491c8a81226fc266cf3e9a4df25674d9c7d | 45,470 |
def normalise_operator_input(*args):
"""Input to Operator may contain products of epsilons which are sympy TensMul
objects. This causes problems since I don't want to define products of
epsilons or deltas to be operators.
This function normalises the input to the Operator constructor to avoid
probl... | e1b6df90db1f948f40ceae648111c1b07caf5599 | 45,471 |
from typing import Sequence
from typing import Callable
def make_button(
name: str = '',
parent: QObject|None = None,
slots: Sequence[Callable, ...] = (),
hint: str = ''
):
"""Make a simple, default Qt push button.\n
Slots will be connected to the `clicked` signal.
"""
... | 17aa577acf3820daa263fb7a3ab76b4ac62a7704 | 45,472 |
def _fontValidator(font):
"""Check if font value is valid, regex is too slow.
Checks everything before ``,`` on basic font value. Everything after should
be a valid font-family value.
"""
if u',' in font:
# split off until 1st family
font1, families2 = font.split(u',', 1)
else:
... | 515742f57d630c08d8562baedc90d7b4e55744b0 | 45,473 |
import json
from datetime import datetime
async def edit_event(ctx, client):
"""
Function:
edit_event
Description:
A existing event is edited from the user's schedule file
Input:
ctx: the current context
client: the instance of the bot
Output:
- A reply sayi... | 5a69b88efd37979b3c8618d042e748932c9a0327 | 45,474 |
def plot_country(country, yvals, y2vals):
"""Makes 3-panel plot from country data"""
# Log values
yvals_log = get_log(yvals)
y2vals_log = get_log(y2vals)
# Per-day change
yvals_perday = get_change_per_day(yvals)
y2vals_perday = get_change_per_day(y2vals)
fig = make_subplots(
r... | 37a994efb72647c7c8d047a68c5c31c71d826579 | 45,475 |
def get_accountinfo(msg: dict) -> str:
"""
Returns a dictionary containing the
account id and an array of prowler group checks.
"""
if msg == "":
raise IndexError
else:
try:
account_id = msg['Id']
return account_id
except KeyError as err:
... | 496c3c1f0c64ecb8627f51bce69e6d5672406344 | 45,476 |
def create_observable_df() -> pd.DataFrame:
"""Create empty observable dataframe
Returns:
Created DataFrame
"""
df = pd.DataFrame(data={col: [] for col in OBSERVABLE_DF_COLS})
return df | bd4df4b42115e8ddf74188060412d8a3a0a95437 | 45,477 |
def MST(N_mels,sequence_samples,audio_win,audio_hop):
""" Return SMel as a keras model
Parameters
----------
N_mels : int
Number of mel bands
sequence_samples : int
Number of samples in each input
audio_win : int
Number of samples in each frame
audio_hop : int
... | 34a82fcb1bb87181e0a98c1369e960fd4b381395 | 45,478 |
def maximum_gap_in_days(col: pd.Series) -> int:
"""Compute maximum gap in a series of dates
(2020-01-01 - 2020-01-02 -> gap = 0 days)
:param col: pd.Series of dates
:return: greatest gap
"""
return col.sort_values().diff().max().days - 1 | 6b8e07d87a19e8df15c74105d98689f942c8c06f | 45,479 |
def get_resource_endpoint(host, hpc_backend):
"""
Get ssh URI of remote host
:param host: host to make url for it
:param hpc_backend: hpc_backend integer value according to HPCBackend enum
:return:
"""
# Default SAGA adaptor to ssh
adaptor = 'ssh'
if helpers.is_localhost(host):
... | c389ed510215ff2c2b15b1e31584d9c8bb05f6ab | 45,480 |
def wrap_function(lib, funcname, restype, argtypes):
"""Simplify wrapping ctypes functions"""
func = lib.__getattr__(funcname)
func.restype = restype
func.argtypes = argtypes
return func | c57334afd98c1571a25af7648c81d7058f26e225 | 45,481 |
def get(
policy_class=None,
return_full_policy_names=True,
hierarchical_return=False,
adml_language="en-US",
return_not_configured=False,
):
"""
Get a policy value
Args:
policy_class (str):
Some policies are both user and computer, by default all policies
... | f4c76261c9f8e0f34fd12944e8327ac614cb09c1 | 45,482 |
def add_graph_nodes(data_graph, root_city, wikicities, root_city_attributes):
"""
add_graph_nodes adds nodes to a graph and returns the new graph
@param data_graph: the current graph
@param root_city: the root city
@param wikicities: all catched cities
@param root_city_attributes: attributes of ... | b8faca149e5a1aa068ba01375789ea1b588dc39e | 45,483 |
import os
def add_suffix(img_file,suffix):
"""
add suffix for a given file name, and not change the file type
:param img_file: img file, e.g. "xxx.jpg"
:param suffix: "——abcde"
:return: "xxx——abcde.jpg"
"""
name = os.path.splitext(img_file)[0]
type_ = os.path.splitext(img_file)[1]
... | 06311bab61d084595b7c06fb09750a3d0c0a0abc | 45,484 |
def pairwise_distances_euclidean(points):
"""Return the matrix of pairwise euclidean distances between points.
Parameters
----------
points: 2d numpy.array
The coordinates of the point, points[0, :] and points[1, :] corresponding to x's and y's respectively.
Returns
-------
... | a53d5287b6e6dfc673ced2670b9126a47afe373d | 45,485 |
def check_dtype(h5_dset):
"""
Checks the datatype of the input HDF5 dataset and provides the appropriate
function calls to convert it to a float
Parameters
----------
h5_dset : :class:`h5py.Dataset`
Dataset of interest
Returns
-------
func : callable
function that w... | 438a1655f0c8071f73c5662b2fbc440bedc004b1 | 45,486 |
def stdev_fuel_per_hour(iterable):
"""
>>> round(stdev_fuel_per_hour(clean_data(row_merge(log_rows))), 4)
0.0897
"""
return stdev(row.fuel_per_hour for row in iterable) | ec5d99a81820a43a7be110dec89c9dcf9c2f9017 | 45,487 |
def stratified_mean_squared_error(observed, predicted, idx, verbose=False):
"""
Computes the stratified mean squared error (MSE) values. Stratified MSE is computed separately in each
bin (cluster) of an observed dependent variable, :math:`\\phi_o`.
MSE in the :math:`j^{th}` bin can be computed as:
... | f3e3004680bc38328ed44cbad2e0f6d80f90bfca | 45,488 |
import requests
def retrieve(*, sodar_url, sodar_api_token, project_uuid):
"""Retrieve project information."""
while sodar_url.endswith("/"):
sodar_url = sodar_url[:-1]
url_tpl = "%(sodar_url)s/project/api/retrieve/%(project_uuid)s"
url = url_tpl % {"sodar_url": sodar_url, "project_uuid": proj... | c5cd1d03fd99f57a450a0a051e3ba249584e21ac | 45,489 |
def modify_ldap_config():
"""
修改ldap模块信息
:return:
"""
try:
put_data = request.get_json(force=True)
ldap_host = put_data.get("ldap_host")
bind_dn = put_data.get("ldap_bind_dn")
bind_dn_password = put_data.get("ldap_bind_dn_password")
base_dn = put_data.get("l... | 0ba7af4d7eddd9ca1fc9a1193e3c44ff33fd5eba | 45,490 |
def gallows(wrong_times):
"""
This function is to make the gallows, which is based on the times of wrong guess.
:param wrong_times: N_TURNS - left_turns
:return: The previous 6 steps is to hang man,
if N_TURNS > 7, the 7th to the (N_TURNS -1)th look of gallows would be the same as 'g6'.
... | 090986fbc42075bc8f0ad93b39bcb740a5adc407 | 45,491 |
def create_sorted_poly_list(poly2d_vector:_Poly2DVector):
"""
Create a SortedPolyList from the values provided in metadata classes of base type _Poly2DVector
:param poly2d_vector:
:return sorted_poly_list:
"""
return SortedPolyList(list_generic_poly=[_create_generic_poly(p) for p in poly2d_vect... | dcfedf7bf4189a897f8c721bcd15cfbb51cd8d5e | 45,492 |
def rgb_to_hls(arr):
""" fast rgb_to_hls using numpy array """
# adapted from Arnar Flatberg
# http://www.mail-archive.com/numpy-discussion@scipy.org/msg06147.html
arr = arr.astype("float32") / 255.0
out = np.empty_like(arr)
arr_max = arr.max(-1)
delta = arr.ptp(-1)
arr_min = arr.min(... | 2ea069d17eadda15ee2351957a42358a9475cf06 | 45,493 |
def shp2geojsonOgr(layer):
"""Shapefile to Geojson conversion using ogr."""
cmd = 'ogr2ogr -f GeoJSON -t_srs'\
+ ' crs:84'\
+ ' {layer}.geojson'\
+ ' {layer}.shp'
cmd = cmd.format(layer=layer)
return cmd | a1bbf42d83cf9d26542c02eb1a16da971a7d0a9e | 45,494 |
def gluon_seresnext101_32x4d(pretrained=False, num_classes=1000, in_chans=3, **kwargs):
"""Constructs a SEResNeXt-101-32x4d model.
"""
default_cfg = default_cfgs['gluon_seresnext101_32x4d']
model = ResNet(
Bottleneck, [3, 4, 23, 3], cardinality=32, base_width=4, use_se=True,
num_classes=... | 48d7e43c4c8941da0bdc779ec7d97c0c18d91332 | 45,495 |
def lut_canonical_potential_edge(potential_edge):
"""Returns a canonical name of a potential edge, with respect to LUT height.
Parameters
----------
potential_edge : str
Instantiated name of the potential edge to be canonicized.
Returns
-------
str
A canonical potential edg... | ccae7b98de4aa18a2ffa72c0faf6b0fe7b001db0 | 45,496 |
def safe_std(data):
"""Remove zero std values for ones."""
std = np.std(data, axis=0)
return np.array([val if val != 0.0 else 1.0 for val in std]) | f1d8676a9460d3235e4b8869ec0223da70c1f61d | 45,497 |
def country_list_nlp(cts):
"""NLP countries so we can use for vector comparisons"""
ct_nlp = []
for i in cts.keys():
nlped = nlp(i)
ct_nlp.append(nlped)
return ct_nlp | 4f7c94c0ecd2d82234881b9d11b67f3e3a6de339 | 45,498 |
def is_unique_column(df_column: pd.Series) -> bool:
"""Check if a column has unique non-empty values.
:param df_column: Column of a pandas data frame
:return: Boolean encoding if the column has unique values
"""
return len(df_column.dropna().unique()) == len(df_column) | 2da7bb94f445d556a617d98830e5d4418364d0f8 | 45,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.