content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def fill_zeros(symbol: int):
"""
将 数字 symbol 填满为 00开头的6位号
:param symbol:
:return:
"""
if symbol < 100000:
b_ = 6 - len(str(symbol))
return ('0' * b_ + str(symbol))
else:
return str(symbol) | 63244c8714a4eba12b484d18b313e9770f9c91ce | 46,400 |
import json
import re
import glob
def load_strace_results(target_dir=TARGET_DIR, force=False):
"""Read and search strace results and retain internet addresses
with ports and executed files. Collect the strace results and
serialize to JSON for faster deserialization.
"""
if STRACE_RESULTS_FILE.exi... | 3a3bd6179fc55c522466e9c21d353e0fa49f0819 | 46,401 |
import asyncio
from datetime import datetime
async def get_statistics(request):
"""
Returns summary statistics on all available currencies
"""
version = request.app['openapi']['info']['version']
currency_stats = list()
db = request.app['db']
aws = [get_currency_statistics(request, currency... | 72203baed51af1373c7d9509431722998cb963e2 | 46,402 |
def squeeze_integers(intVec):
"""
Make integers in an array consecutive numbers
starting from 0. ie. [7,2,7,4,1] -> [3,2,3,1,0].
Useful for removing unused class IDs from y_true
and outputting something appropriate for softmax.
This is v2. The old version is busted.
RH 2021
Args:
... | 5975db7907388666ea70d976bcb83ebe13aadf70 | 46,403 |
def get_organization(organization_uri):
"""
Given the URI of an organnization, return an object that contains the
organization it represents.
As for most of the access functions, additional attributes can be added.
"""
organization = {'organization_uri':organization_uri}
organization['uri']... | 49871ef1d817d424d9916e73f97f910a53468003 | 46,404 |
import array
def dist(a=array([]),b=array([])):
"""
Compute euclidean distance between 2 points given by 2 arrays.
"""
n1=len(a)
n2=len(b)
d=0.0
if (n1==n2):
d2 = (a - b)*(a - b)
d = sum(d2,axis=0)
return (sqrt(d)[0])
else :
print("ERROR: Coordi... | 5b8386b24dac32b2473969180a1211df80fd93e7 | 46,405 |
def extract_fields(gh_json, fields):
"""
extract_fields Extract field from GH API data
Extract fields from GH API data and standardize name of keys
Parameters
----------
gh_json : json
JSON content from Github
fields : dict
A list of fields to extract and the name we want t... | 0c14128c6e400075b982e0eb92eca65d329d6b5d | 46,406 |
import math
def define_network_parameters(m, data):
"""Define network parameters"""
# Max voltage angle difference between connected nodes
m.P_NETWORK_VOLTAGE_ANGLE_MAX_DIFFERENCE = pyo.Param(initialize=float(math.pi / 2), mutable=True)
# Branch susceptance matrix elements
m.P_NETWORK_BRANCH_SUS... | 183a226ecf97a66d19d3224f5b9ca4da0fecac71 | 46,407 |
def bayesian_prob(counts, tuning_curves, binsize, min_neurons, min_spikes=1):
"""Computes the bayesian probability of location based on spike counts.
Parameters
----------
counts : nept.AnalogSignal
Where each inner array is the number of spikes (int) in each bin for an individual neuron.
t... | fc2eb2886b31032422888376541b414c76c3d01b | 46,408 |
import math
def distance(waypoints, wp1, wp2):
"""Compute distance between to waypoint indices"""
dist = 0
def d_l( a, b ):
return math.sqrt((a.x - b.x) ** 2 + (a.y - b.y) ** 2 + (a.z - b.z) ** 2)
for i in range(wp1, wp2+1):
dist += d_l(waypoints[wp1].pose.pose.position, waypoints[i]... | 908b16eac01e912011ad436c5be5206f5a21576c | 46,409 |
def clustering_coefficient_weighted(user, interaction=None):
"""
The clustering coefficient of the user's weighted, undirected network.
It is defined the same way as :meth`~bandicoot.network.clustering_coefficient_unweighted`,
except that closed triplets are weighted by the number of interactions. For
... | d9be9be2f819e60329db966613662d7f59c4e893 | 46,410 |
import warnings
def time_lag(lc1, lc2):
"""
Estimate the time lag of two light curves.
Calculate time lag and uncertainty.
Equation from Bendat & Piersol, 2011 [bendat-2011]_.
Parameters
----------
lc1: :class:`stingray.Lightcurve` object
The first light curve data for the channel... | 5f1609978f5e590fbf6eefa42af88e328733b18b | 46,411 |
import torch
def pad_batch_tensorize(inputs, pad, cuda=True):
"""
pad_batch_tensorize
找到最长文章,拉齐,填pad ,tensor化
:param inputs: List of size B containing torch tensors of shape [T, ...] T32
:type inputs: List[np.ndarray]
:rtype: TorchTensor of size (B, T, ...)
"""
tensor_type = to... | 3b01109737da9d9941d6ac09fe51f38f5849e52f | 46,412 |
from typing import Dict
from typing import Any
import json
def as_json(config: Dict[str, Any], **json_args: Any) -> None:
"""Use json standard library to write JSON file"""
return json.dumps(config, **json_args) | 7b88722b41494318068812f50d2fd60b163ac81e | 46,413 |
from typing import Dict
def get_etfs_by_name(name: str) -> Dict:
"""Return a selection of ETFs based on name filtered by total assets. [Source: Finance Database]
Parameters
----------
name: str
Search by name to find ETFs matching the criteria.
Returns
----------
data : Dict
... | 638ecb89f3e8366028904ac1702a2d6ec33fef72 | 46,414 |
def delete_event(id):
"""Deletes an event
:param id: the id of the event
:returns: a dictionary with a response of success or failure
"""
response = db(db.events.id==id).delete()
return dict(response=response) | c28183511846ca7c7fe53cee32af1d0d840969b1 | 46,415 |
def parametric(Class=None, runtime_type_of=False, metaclass=CovariantMeta):
"""A decorator for parametric classes.
When the constructor of this parametric type is called before the type parameter
has been specified, the type parameters are inferred from the arguments of the
constructor by calling the f... | 03862e507a43a08f8f65d781974fe06341659336 | 46,416 |
def add_qartod_ident(qartod_id, qartod_test_name):
"""
Adds attributes to the QARTOD functions corresponding to database fields.
Mostly for internal use
:param qartod_id: The QARTOD test identifier, as represented by an integer
:param qartod_test_name: The test name as stored in the database.
"... | 7ad196388861491bc5d8ff554a30dd6476042674 | 46,417 |
from typing import Optional
async def get_balance(
user_id: int,
db_con: Connection,
convert_to: Optional[str] = None,
) -> Decimal:
"""Get user account balance.
Args:
user_id: user id
db_con: database connection
convert_to: currency for convertation
Returns:
... | 9fd8de687b96bd5e5e90f60e386e7972ea269264 | 46,418 |
def output_factory(writer_format: str = "pqr") -> Writer:
"""Provides the writer based on the output format.
:param writer_format: Format indicating with writer to use
:type writer_format: str
:return: Writer object for a given output factory
:rtype: Writer
"""
writer_type = writer_forma... | 03023f9bb0d2ef9e98368fd9e75fbbbb5316ef76 | 46,419 |
def handlerInit(service,node):
"""pyvel initialization.. This is where we load
our modules and setup the state objects"""
if not service.state.has_key("groups"):
service.state["groups"]={'/':{}}
if not service.state.has_key("games"):
service.state["games"]={}
rdict={}
for n in no... | fb54232b205e04239c4a5f2dda1bdb21bcce5eec | 46,420 |
def unflatten_wave(y, shape):
""" Unflatten a flattened array.
Parameters
----------
y: ndarray 1D
a flattened input array.
shape: list of dict
the output structure information.
Returns
-------
x: list of ndarray
the unflattened dataset.
"""
# Unflatten ... | 48618aaf5b1df7bd154d7f892158393e2ff34e0b | 46,421 |
import typing
def load_all_dicts(gs_files: list = None,
GLMDIR: str = None,
norm: typing.Union[str, bool] = 'bySessVoxZ',
roi: str = 'lang_LH_netw'):
"""Return df of rows = sentence, cols = gs single response for ROI of interest"""
# Load, extract the ROI of interest
lst_responses = []
lst_... | bbd2433a43cc3618c5f3a1f5d42a74602c4245bb | 46,422 |
import scipy
def compute_range_table( stepsize = 0.001, maxextent = 10 ):
"""Compute integrals of the unit normal distribution and return these tabulated. Returns:
- range: NumPy array giving integration range (x) where integration range runs -x to +x
- integral: NumPy arrange giving integrals over specified int... | 45e91d790393c2b03b7c1e98b5964daf0e4c24c5 | 46,423 |
def phred(q):
"""Convert 0...1 to 0...30
No ":".
No "@".
No "+".
"""
n = int(q * 30 + 33)
if n == 43:
n += 1
if n == 58:
n += 1
return chr(n) | 29a61010b1813afc6d32e640bb6865a9e18ac3a0 | 46,424 |
def lemmatize(word):
"""
Out of all the related word forms of ``word``, return the smallest form that appears first in the dictionary
"""
forms = [word for pos_form in get_word_forms(word).values() for word in pos_form]
forms.sort()
forms.sort(key=len)
try:
return forms[0]
except... | 078c90537697c3863542ef6a483561866cdd3a9b | 46,425 |
def write_k(version, internal, boundaries, location=None, file=None):
""" Write a turbulent kinetic energy (TKE) field file.
See :func:`~dafi.random_field.foam_utilities.write` for more
information.
"""
return write(version, 'k', internal, boundaries, location, file) | fd95a2f27529370a1a451f120ba5e75f8f9fa15b | 46,426 |
def HLRBRep_BCurveTool_IsRational(*args):
"""
:param C:
:type C: BRepAdaptor_Curve &
:rtype: bool
"""
return _HLRBRep.HLRBRep_BCurveTool_IsRational(*args) | 8065ef84e294c0b61ffd9a7a66df19829fb15d23 | 46,427 |
def has_footer_comments(content):
"""Determine if the FOOTER_COMMENTS are already present.
"""
for comment in FOOTER_COMMENTS:
if content.find(comment) == -1:
return False
return True | 1a355ee32f8bc21b3c286e1150532057ca6bde9e | 46,428 |
def get_directory_content_ajax(request, region_slug=None):
"""
View provides the frontend with the content of a directory via AJAX.
:param request: The current request
:type request: ~django.http.HttpRequest
:param region_slug: The slug of the current region
:type region_slug: str
:return... | 97c3c512d0f60cfb134e2b9161229505ebc4bf8c | 46,429 |
from typing import Optional
def int(val: 'Optional[b_int]' = None) -> PythonValue:
"""Returns an Int wrapped into a PythonValue"""
return PythonValue(Int(val)) | df8c31966b6d39897440d91ae7281ae7d1fa30cd | 46,430 |
import csv
def compare_files_pr(file1, file2):
""" Calculate simple P/R .
Compare lists of cells, left to right , top to bottom.
"""
cells = [[], []]
for i, fname in enumerate([file1, file2]):
with file(fname) as csvfile:
rd = csv.reader(csvfile, delimiter=',', quotechar='"... | d727fdbb25a60d75616aff41cb408a5395c46b4b | 46,431 |
def read(filename, flags=0):
"""Read an image to a numpy array of shape (height, width) for
greyscale images, or shape (height, width, nchannels) for RGB or
RGBA images.
The `flags` parameter should be one or more values from the IoFlags
class defined in this module, or-ed together with | as appropr... | 30e662ce6d2a38d114cfc9898f970fbb7a708910 | 46,432 |
def _call_with_frames_removed(func, *args, **kwds):
"""
remove_importlib_frames in import.c will always remove sequences
of importlib frames that end with a call to this function
Use it instead of a normal call in places where including the importlib
frames introduces unwanted noise into the traceba... | a4b3d05879c29efc51e07aec9d9fba02254d4504 | 46,433 |
import random
def generate_pose():
""" generate pose from hemisphere-distributed viewpoints
"""
# y axis(yr): -pi - pi
# x axis(xr): 0 - 0.5pi
# view_direction(ar): -0.1pi - 0.1pi
yr = (random.random()*2.0*np.pi)-np.pi
xr = (random.random()*0.5*np.pi)
ar = (random.random()*0.2*np... | c9909e0b4f944410b939a56038a85e089ae02adf | 46,434 |
def _flop_count(idx_contraction, inner, num_terms, size_dictionary):
"""Copied from _flop_count in numpy/core/einsumfunc.py
Computes the number of FLOPS in the contraction.
Parameters
----------
idx_contraction : iterable
The indices involved in the contraction
inner : bool
Doe... | a7fb1d68d36770a69400932fc4f1a3a2461afaf6 | 46,435 |
import pandas
def process_track_data(dataframe_name, concatenated_filepath, concatenated_filename, input_filepath, input_filename, device_id, output_create_files_filepath, output_create_files_filename,
invalid_position_filepath, output_flagging_filepath, output_flagging_filename):
"""Proces... | 0ea89083e95a315e8dc47025be1b4beadef28da9 | 46,436 |
def margin_mortality(t):
"""Mortality margin
Mortality margin is defined :func:`coi` net of :func:`claims_over_av`.
The sum of the expense margin and mortality margin add
up to the net cashflow.
.. seealso::
* :func:`coi`
* :func:`claims_over_av`
"""
return coi(t) - clai... | 72a0b4b795076bd865479bbce7f8f02843460f47 | 46,437 |
from typing import Optional
def getPrintLengthError(printHours: float) -> Optional[str]:
"""Returns a warning message if the print is too long.
:param printHours: Total hours the print will take.
:return: The message to display if the print is too long.
"""
currentLimit, limitEnds = getCurrentTi... | 5a03f3f18790558258e9804b4a8354df827e772b | 46,438 |
def insert_combos(lst, vertical_sudoku, blockified_sudoku, row_index):
"""
Tries all combinations of missing elements and inserts to a list and returns it
args:
-lst - list containing missing elements
-vertical_sudoku - List containing lists of columns of the sudoku
(Will be ... | a2fbe9c003c9611727096500bb8079f68d1aa34a | 46,439 |
import optparse
def options_from(**kwargs):
"""Generate a Values instances with our kwargs."""
kwargs.setdefault('hang_closing', True)
kwargs.setdefault('max_line_length', 79)
kwargs.setdefault('verbose', False)
kwargs.setdefault('stdin_display_name', 'stdin')
return optparse.Values(kwargs) | 1a82c3a2d76ae3aba8cec81ccb01fd976b2ab4c4 | 46,440 |
def connect(server, username, password):
"""
Connect to Seafile server
:param server: address of the seafile server
:param username: username
:param password: password
:return: :class:`SeafileApiClient`.
"""
seafile_client = SeafileApiClient(server, username, password)
return seafile... | a5f3f0d1d68a34cd8d659f802538c647c9f2296b | 46,441 |
def lsolve(A, b):
"""Gaussian elimination with partial pivoting.
This is implemented here to avoid a dependency on numpy. This could be
replaced by :code:`(x, _, _, _) = lstsq(A, b)`, but we prefer the pure
Python implementation here.
"""
N = len(b)
for p in range(N):
# f... | 751300dcca2bdad7c0b8c8618d95ad97092d16a8 | 46,442 |
def show_user():
"""
function to show existing users
:return: existing users
"""
return User.display_all_users() | ee2912a1202dee17ed91f668e2f59e236fc47800 | 46,443 |
from functools import reduce
def sum(l):
"""
Returns the sum of the items in the container class.
This is more general than the build-in 'sum' function, because it is not specific for numbers.
This function uses the '+' operator repeatedly on the items in the contrainer class.
For ... | c64bc8aec1af669af69494aa37fd515d3d7efad5 | 46,444 |
def main(args):
"""Process Glicko2 ratings."""
scrape = args.scrape
tournaments = args.tournaments
output_format = args.output_format
game = args.game
top_amount = int(args.top_amount)
sort = args.sort
if scrape:
scrape_all_tournaments()
if tournaments:
tournaments ... | 251fb57cbfbbccd93d4d717b1f350ff80a5bf14f | 46,445 |
from operator import ne
def extract_z_dec(model, sample_layer_name, vis=False, wt_chk=False):
"""
extract the z_decoder [z = p(x)] and return it as a keras model
Example Layer name:
sample_layer_name = 'img-img-dense-vae_ae_dense_sample'
"""
# need to make new model to avoid mu, sigma output... | d9fa1f16c68ea41d0c8ae8ef2d202c431a4d7a68 | 46,446 |
import webbrowser
def acquire_new_oauth2_credentials(secrets_file):
"""
Args:
secrets_file. The file path to a JSON file of client secrets, containing:
client_id; client_secret; redirect_uris; auth_uri; token_uri.
Returns:
credentials for use with Google APIs
"""
flow =... | 3515eca1fb1795ed8db876a25b0820dd8056f7fc | 46,447 |
def debugInitializeWeights(fan_in, fan_out):
"""
Initializes the weights of a layer with fan_in incoming connections and
fan_out outgoing connections using a fixed set of values.
"""
# Set W to zero matrix
W = np.zeros((fan_out, fan_in + 1))
# Initialize W using "sin". This ensures that W ... | 6ab74a60fa670b775fb3301120e4d9ba64095103 | 46,448 |
def checkValues_coordinate0(coordinate0, reference_point):
"""Function that check the range of the input coordinates to be rigth"""
# AP
if 90 > coordinate0[0] > -90:
pass # Entry in correct range
else:
raise Exception(
"Coordinate AP ({}) out of range for lambda, should be... | d55cbce8cff1fa47b4c958cfcad41c0d0c9a338f | 46,449 |
from typing import List
from typing import cast
def correct_task_suggestions_in_loop_body(pet: PETGraphX, suggestions: List[PatternInfo]) -> List[PatternInfo]:
"""Separate treatment of task suggestions at loop increment CUs.
If regular loop: move taskwait suggested at loop increment line to end of loop body.
... | 0d4349d2afa799919670845cb1ca8c8adf63454a | 46,450 |
import os
import torch
import time
def validate(data_loader, actor, save_dir, **kwargs):
"""Used to monitor progress on a validation set & optionally plot solution."""
actor.eval()
if kwargs['render_fn'] is not None:
if not os.path.exists(save_dir):
os.makedirs(save_dir)
rewards... | c7c72e2848a5e41783b2cd9f41f2c745d8fbe9c1 | 46,451 |
def compare(isamAppliance1, isamAppliance2):
"""
Compare user name mapping
"""
ret_obj1 = get_all(isamAppliance1)
ret_obj2 = get_all(isamAppliance2)
for obj in ret_obj1['data']:
ret_obj = get(isamAppliance1, obj['id'])['data']
del obj['version']
obj['contents'] = ret_ob... | 431b099339fe8bdcacc77d9c71bcb6edb41c2d5a | 46,452 |
import re
def get_keyword(title):
"""
:param title: policy title (str)
:return: keyword (str)
"""
matchObj = re.match('(.*)关于(.*)的(.*)', title)
if matchObj:
title = matchObj.group(2)
matchObj2 = re.match(r'(.*)“(.*)”(.*)', title)
if matchObj2:
title = matchObj2.group(2... | da9a5f5ff9fbc0d9c77057301bb16b578476b9a7 | 46,453 |
def Rotation_calcNForBodyXYZInBodyFrame(*args):
"""
calcNForBodyXYZInBodyFrame(Vec3 q) -> Mat33
Parameters
----------
q: SimTK::Vec3 const &
Rotation_calcNForBodyXYZInBodyFrame(Vec3 cq, Vec3 sq) -> Mat33
Parameters
----------
cq: SimTK::Vec3 const &
sq: SimTK::Vec3 const &
... | aa5886cd5036b1c8f0452524375ab1466dc68a5a | 46,454 |
import re
def get_version(versionfile):
"""Extract the __version__ from a given Python module."""
match = re.search(r'^__version__ = [\'"]([^\'"]*)[\'"]', open(versionfile).read(), re.M)
if match:
return match.group(1)
else:
raise RuntimeError("Unable to find version string in {file}."... | f319b575d74e3ecea3895785e1101f72913488ec | 46,455 |
import random
def create_push_down(target_path, arena_name, time=1000, is_train=True):
""" The reward is on top of a box. agent must push box in the right position to be able to acces the reward platform."""
coin = random.choice([0,1])
if coin == 1:
box_pos = (random.randint(25, 140) / 10., 1.,... | 46e1c1a19ee2285d8aa13735b165275513e9e51b | 46,456 |
import logging
def read_ap_custom_resource(custom_objects: CustomObjectsApi, namespace, plural, name) -> object:
"""
Get AppProtect CRD information (kubectl describe output)
:param custom_objects: CustomObjectsApi
:param namespace: The custom resource's namespace
:param plural: the custom resourc... | e23b6c657aae46f2242b153becf25f91871564b3 | 46,457 |
def get_encoded_logs(job: Job, use_cache: bool = True) -> (DataFrame, DataFrame):
"""returns the encoded logs
returns the training and test DataFrames encoded using the given job configuration, loading from cache if possible
:param job: job configuration
:param use_cache: load or not saved datasets fro... | e422c12487ab0656ea0d08371f4761b85ffea216 | 46,458 |
import subprocess
def readelf_header(bin_file):
"""Read elf header and return dictionary"""
p = subprocess.Popen("readelf -h %s" % bin_file, shell=True, close_fds=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.wait()
attr_map = {}
for l in p.stdout.readlines():
... | 040667204e84476b8b60d42cac38667a0c18eb61 | 46,459 |
from typing import List
def _filter_messages(msgs: List[Message]) -> List[Message]:
"""Filter messages removing those that start with INTENT_MESSAGE_PREFIX"""
filtered_messages = []
for msg in msgs:
if not msg.text.startswith(INTENT_MESSAGE_PREFIX):
filtered_messages.append(msg)
r... | 99ea45a231cdf710ede1df5431776a6bad4fef6a | 46,460 |
import socket
def hostname_resolves(hostname):
"""Checks to see if hostname is DNS resolvable"""
try:
socket.gethostbyname(hostname)
return 1
except socket.error:
return 0 | 7339b03da62863d109c543e85f04eace1261a31e | 46,461 |
def descale_fields(clip: vs.VideoNode, tff: bool = True,
width: int | None = None, height: int = 720,
kernel: Kernel = Catrom(), src_top: float = 0.0) -> vs.VideoNode:
"""
Simple descaling wrapper for interwoven upscaled fields.
This function also sets a frameprop with ... | 20da2724ed701a2c14cb87d96d4636e6f30ed6b1 | 46,462 |
import math
def _gain2db(gain):
"""
Convert linear gain in range [0.0, 1.0] to 100ths of dB.
Power gain = P1/P2
dB = 10 log(P1/P2)
dB * 100 = 1000 * log(power gain)
"""
if gain <= 0:
return -10000
return max(-10000, min(int(1000 * math.log10(min(gain, 1))), 0)) | 1bd602e0db397b3730c4f2b3439aeb351e6bd854 | 46,463 |
def build_aggregation_layer(aggregation_input_layer, model_config,
calibrated_lattice_models, layer_output_range,
submodel_index, dtype):
"""Creates an aggregation layer using the given calibrated lattice models.
Args:
aggregation_input_layer: A list or a... | dd355b75d13b91d9cfd426a53edc7a45761e76f8 | 46,464 |
import random
def generate_int(data_format):
"""
Generate an integer based on the given data width and sign.
"""
is_signed = data_format['is_signed']
width = data_format['width']
if is_signed:
result = random.randrange(-2 ** (width - 1) + 1, 2 ** (width - 1) - 1)
else:
res... | 644d8e71b949ff01290d357732509d1f0a62db08 | 46,465 |
def load(filep):
"""
Read an V_sim .ascii file and returns a pychemia
Structure object
Args:
filep: (string) Path to a .ascii file or an
actual file-like object
Returns:
struct: (object) A pychemia Structure object
"""
if isinstance(filep, str):
f = open... | 4c9127b7ba8f5b6aa553615152ba441d92898397 | 46,466 |
def mock_run_applescript(script):
"""Don't actually run any applescript in the unit tests, ya dingbat.
This function should return whatever type of object
dialogs._run_applescript returns.
Returns:
tuple
"""
return (1, "", "") | fdcb8e1e0e283963cec55c8fa1d98e745bd5e784 | 46,467 |
import numpy as np
import pdb
import astropy.constants as const
import numpy as np
import lib.test as test
def blur_spec(wl,spec,dv,truncsize = 20.0):
"""This function takes a spectrum, and blurs it using either a
Gaussian kernel or a box kernel, which have a FWHM width of dv km/s everywhere.
Meaning that... | 6e3530ab7db573ae0c488d285407db0216166be2 | 46,468 |
import torch
def channel_last_to_first(img: torch.Tensor) -> torch.Tensor:
"""
Converts an image of shape batch_size, height, width, channels into an image of shape batch_size, channels, height,
width.
Parameters
----------
img: Image with shape batch_size, height, width, channels.
Retur... | b5e948e7eb6ba2ac211e8f5d89601f194d391c32 | 46,469 |
def _projector_on_tvl1_dual(grad, l1_ratio):
"""Function to compute TV-l1 duality gap.
Modifies IN PLACE the gradient + id to project it
on the l21 unit ball in the gradient direction and the L1 ball in the
identity direction.
"""
# The l21 ball for the gradient direction
if l1_ratio < 1.:... | 28bb9f8c6cc9c65cb370442c878ef8e0d81ebd05 | 46,470 |
def get_id(psco):
"""
Retrieve the persistent object identifier.
:param psco: Persistent object
:return: <String> Id
"""
return psco.getID() | 84fdf24633adb301411d8c4ad2d6344cd09a63b7 | 46,471 |
def rotate_image(img, angle):
"""
Rotate image by given angle. Adapted from https://stackoverflow.com/a/23316542.
"""
row, col, _ = img.shape
center = tuple(np.array([row, col]) / 2)
rot_mat = cv2.getRotationMatrix2D(center, angle, 1.0)
new_img = cv2.warpAffine(img, rot_mat, (col, row))
... | f492ad345b0f61a463fa29cdd07e821156657816 | 46,472 |
import re
def _defaults_to_code(val):
"""
Make sure that any defaults that are surrounded by << >> are in code quotes so that they render properly.
e.g.: <<display_name>> converts to '<<display_name>>'
"""
return re.sub(r"(<{2}.*>{2})", r"`\1`", val) | f98aa716fab13143a29659ff746336913d9d4ee7 | 46,473 |
def do_label_encoding(
source_train_df,
source_test_df,
target_train_df,
target_test_df,
categorical_features,
feature_name_suffix=None,
):
"""
Label encode the categorical features.
After encdoing, it appends a new set of features with name
<original_feature_name>_label to the t... | 8ed75c13d8c31e5d5b297631d8e69483d0370403 | 46,474 |
from ..tibble import tibble
def sprintf(fmt, *args):
"""C-style String Formatting
Args:
fmt: The formats
*args: The values
Returns:
A scalar string if all fmt, *args are scalar strings, otherwise
an array of formatted strings
"""
if is_scalar(fmt) and all(is_scala... | 92b381ac13fd6bf8089ff820bbc332c384bb114c | 46,475 |
def morphological_process(image, kernel_size=5, func_type=cv2.MORPH_CLOSE):
"""
morphological process to fill the hole in the binary segmentation result
:param image:
:param kernel_size:
:return:
"""
if len(image.shape) == 3:
raise ValueError('Binary segmentation result image should ... | dad5f0205c4728feb0472869210beed7bf39aad0 | 46,476 |
def warm_restart(scheduler, T_mult=2):
"""warm restart policy
Parameters:
----------
T_mult: int
default is 2, Stochastic Gradient Descent with Warm Restarts(SGDR): https://arxiv.org/abs/1608.03983.
Examples:
--------
>>> # some other operations(note the order of operations)
>>... | 2c7fabac807fb9237775a406e8ba9fb0cf6feb76 | 46,477 |
def main() -> None:
"""Start the bot"""
bot_token = get_bot_token()
load_stats()
# Get the updater
updater = Updater(bot_token, use_context=True)
# Get the dispatcher to register handlers
dispatcher = updater.dispatcher
# Command Handlers
dispatcher.add_handler(CommandHandler("star... | 2da7fe1718e643b0ea03e630ee55b5863f91ff9b | 46,478 |
def checkNull(df):
"""
checkNull is a simple function that returns the sum of the number of nulls
you have in each column of your dataframe.
"""
assert isinstance(df, pd.DataFrame), "Please submit a dataframe when using this function."
return df.isnull().sum() | 3bdb380bf4a1710331182796886ad5d14c447fb3 | 46,479 |
def send_action(action=ChatAction.TYPING):
"""Sends `action` while processing func command."""
def decorator(func):
@wraps(func)
def command_func(update, context, *args, **kwargs):
context.bot.send_chat_action(chat_id=update.effective_message.chat_id, action=action)
retur... | 9ceb66c62aee9eb61fe780cdd6e41bfb4f69c799 | 46,480 |
def split_dates(dataframe, date_column):
"""Converts date features into pandas datetime objects.
Args:
dataframe (pandas dataframe)
date_column (dataframe column)
"""
copy_of_df = dataframe.copy()
copy_of_df["Year"] = pd.DatetimeIndex(copy_of_df[date_column]).year
copy_of_df["M... | 59a5dda3c921a12e20ab981559df97b48fcc91b2 | 46,481 |
def total_schedule(schedule):
"""Return the total number of 15 minute windows in which the schedule
is set to replicate in a week. If the schedule is None it is
assumed that the replication will happen in every 15 minute
window.
This is essentially a bit population count.
"""
if schedule i... | 9c0231a0f6e2e4617b5c958ea337420f73811309 | 46,482 |
def diff_mark(m, t):
"""
Subtract from a marking the postset of t and adds the preset
Parameters
------------
m
Marking
t
Transition
Returns
------------
diff_mark
Difference marking
"""
for a in t.out_arcs:
p = a.target
w = a.weight
... | 164480506364779ea562e7e276e2b6ebe3a2f1c6 | 46,483 |
def vatm(model, x, logits, eps, num_iterations=1, xi=1e-6,
clip_min=None, clip_max=None, scope=None):
"""
Tensorflow implementation of the perturbation method used for virtual
adversarial training: https://arxiv.org/abs/1507.00677
:param model: the model which returns the network unnormalized l... | 89faf3f5c4a88ccc77e1b1185ad6c1ea5e5dfafe | 46,484 |
def put_byte(*args):
"""
put_byte(ea, x) -> bool
Set value of one byte of the program. This function modifies the
database. If the debugger is active then the debugged process memory
is patched too.The original value of the byte is completely lost and
can't be recovered by the 'get_original_byte()' functi... | be3ab0dc432f9de4ae257c698f426b410d037d7e | 46,485 |
def get_session():
""" 获取数据库回话对象
如果当前存在事务,则使用最后一个事务的回话对象
否则,新建一个
"""
if hasattr(threadLocal, "sessions") and len(threadLocal.sessions) > 0:
return threadLocal.sessions[-1].session
return _create_session(True) | 641089b48694503b2fae09f5e907e7873b5fd627 | 46,486 |
def recherche_motif_naive(texte, motif):
"""Retourne la position où le motif a été trouvé par fenetre glissante
ou -1 si le motif ne se trouve pas dans le texte
Si n = len(texte) et m = len(motif), la complexité est en O((n-m)*m)"""
for i in range(len(texte) - len(motif) + 1):
if correspondance_... | 89fee413026893dc1f10faa05f159325e34e077e | 46,487 |
def remap_instruction_position(position, mtext_src, mtext_dst):
"""
Remap an instruction position from one mtext to a *similar* position in another.
"""
line_num, x, y = position
line = mtext_src.lines[line_num]
# the block in the source mtext where the given position resides
blk_token_src ... | 4699c63ef88dea8cc8fc487cfe39338f5aa52101 | 46,488 |
import json
def load_hparams(hparams_file, out_dir):
"""Load hparams from an json file.
Partial hparams are augmented using default values for parameters that were
added after the hparams file was written.
Args:
hparams_file: Filename of the hparams file.
out_dir: Directory where the model output wi... | 74fa3d0345ff604e09f2baa7c7556ecfd5660b24 | 46,489 |
import json
import urllib
def get_access_token(tenant_id, resource):
"""
Retrieve an OAuth token by sending an OAuth2 token exchange
request to the local URL that the ManagedIdentity extension is
listening to
"""
# Extract the endpoint that the ManagedIdentity extension is listening on
wit... | ee871be3000fbb01cfb352578c43a60e31623b68 | 46,490 |
from typing import Callable
def f_docstring(docstring: str) -> Callable:
"""Bypass for f formatted docstrings."""
def decorator_doc(func: Callable) -> Callable:
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
wrapper.__doc__ = docstring
ret... | a2d99980d071cf7f5c37a1ac4fdc9cc0f996d50e | 46,491 |
def permutation_cluster_1samp_test(
X, threshold=None, n_permutations=1024, tail=0, stat_fun=None,
connectivity=None, verbose=None, n_jobs=1, seed=None, max_step=1,
exclude=None, step_down_p=0, t_power=1, out_type='mask',
check_disjoint=False, buffer_size=1000):
"""Non-parametric clu... | 77f3c73e2da2baec108e41c5ecbbf6dc0f76444e | 46,492 |
def getOrigShape(transform):
"""
Creates the Orig Shape used by deformers.
Args:
transform (pm.nodetypes.Transform): Transform to create orig shape of.
Returns:
(pm.nodetypes.Mesh): Shape created.
"""
shape = pm.deformableShape(transform, og=True)
shape = list(filter(None, ... | 24a5bf6257fc6081d5d3e1f444c9e29c643b9bc0 | 46,493 |
def get_input():
"""
Ask user for inputs about event: Title, Main Topic, Distance to Location.
Checks for correct types and value ranges. If not correct, restarts asking 5 times.
:return: Tuple(Str, Int, Int) => "Title", [0|1], [0,infinity[ OR None (to quit App)
"""
attempt = 0
title, topic,... | 4c5ef7eea691a5080b61686173faf2530f4586c3 | 46,494 |
import datasets
def get_dataset(args):
""" Returns train and test datasets and a user group which is a dict where
the keys are the user index and the values are the corresponding data for
each of those users.
"""
if args.dataset == 'cifar':
data_dir = '../data/cifar/'
apply_transf... | 1e1edd193e41135b7eda38417073f14c2b96a784 | 46,495 |
from typing import Optional
from typing import Any
def get_roulette(archive: utils.Archive[utils.Value], num: Optional[int] = None) -> Any:
"""Apply a roulette tournament selection.
"""
if num is None:
num = int(.999 + np.sqrt(len(archive)))
# the following sort makes the line deterministic, a... | 03829327d087270083730b1acb48823b39c083a3 | 46,496 |
def process_puzzle_input(ext=".txt"):
""" Process puzzle input """
puzzle_data = []
with open("puzzle_data_" + DAY + "_" + YEAR + ext) as f:
for line in f:
puzzle_data.append([x for x in line.strip()])
return puzzle_data | cb937199a99c7667ac078e332e9330432df7bdb8 | 46,497 |
import subprocess
def run_command(args, **kwargs):
"""Run a command without echo, return returncode, stdout and stderr (always as string)."""
kwargs.setdefault('stdout', subprocess.PIPE)
kwargs.setdefault('stderr', subprocess.PIPE)
if _IN_PY3:
r = subprocess.run(args, universal_newlines=True... | dd11bd0c3f399702ab2f9a1c041b7c3c80a64cd6 | 46,498 |
def minimum_bounding_rectangle(points):
"""
Find the smallest bounding rectangle for a set of points.
Returns a set of points representing the corners of the bounding box.
:param points: an nx2 matrix of coordinates
:rval: an nx2 matrix of coordinates
"""
pi2 = np.pi/2.
# get the conve... | 3cc5b2e59aa54ebf5f78668a029d18c55df97b47 | 46,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.