content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def dice(labels, predictions, axis, weights=1.0, scope=None, loss_collection=tf.GraphKeys.LOSSES, reduction=Reduction.SUM_BY_NONZERO_WEIGHTS):
"""Dice loss for binary segmentation. The Dice loss is one minus the Dice
coefficient, and therefore this loss converges towards zero.
The Dice loss between predict... | 70e0e44e7d9b07350497a2c048f2bdd1c8ea952e | 3,637,988 |
def air_density(temp, patm, pw = 0):
"""
Calculates the density of dry air by means of the universal gas law as a
function of air temperature and atmospheric pressure.
m / V = [Pw / (Rv * T)] + [Pd / (Rd * T)]
where:
Pd: Patm - Pw
Rw: specific gas constant for water vapour ... | 1af7afbf562fec105566a2c934f83c73f0be1173 | 3,637,989 |
def index(dataset: Dataset, min_df=5, inplace=False, **kwargs):
"""
Indexes the tokens of a textual :class:`quapy.data.base.Dataset` of string documents.
To index a document means to replace each different token by a unique numerical index.
Rare words (i.e., words occurring less than `min_df` times) are... | 8cde5ed740e4879d62f4a73bf06d1da7b78bc22a | 3,637,990 |
def PerpendicularFrameAt(thisCurve, t, multiple=False):
"""
Return a 3d frame at a parameter. This is slightly different than FrameAt in
that the frame is computed in a way so there is minimal rotation from one
frame to the next.
Args:
t (double): Evaluation parameter.
Returns:
... | 14216aa0091f82cb47dafe0970d685463529cfbb | 3,637,991 |
from typing import Collection
def _attributes_cosmo2dict(cosmo):
"""
Converts CoSMoMVPA-like attributes to a dictionary form
Parameters
----------
cosmo: dict
Dictionary that may contains fields 'sa', 'fa', 'a'. For any of these
fields the contents can be a dict, np.ndarray (objec... | 3d3369ce0a1f65cd1bc1b8629ca028a4561224ca | 3,637,992 |
def is_instrument_port(port_name):
"""test if a string can be a com of gpib port"""
answer = False
if isinstance(port_name, str):
ports = ["COM", "com", "GPIB0::", "gpib0::"]
for port in ports:
if port in port_name:
answer = not (port == port_name)
return answ... | f45f47d35a9172264d0474502b0df883685071a0 | 3,637,993 |
import types
def share_data(value):
""" Take a value and use the same value from the store,
if the value isn't in the store this one becomes the shared version. """
# We don't want to change the types of strings, between str <=> unicode
# and hash('a') == hash(u'a') ... so use different stores.
... | 70edaad0ef52e6f6866049bcd199ef109ebb825d | 3,637,995 |
import math
def gaussian_dropout(incoming, keep_prob, mc, scale_during_training = True, name=None):
""" Gaussian Dropout.
Outputs the input element multiplied by a random variable sampled from a Gaussian distribution with mean 1 and either variance keep_prob*(1-keep_prob) (scale_during_training False) or (1-k... | 225c88e0f45c2b319cfabfcb6c65162a5a21f778 | 3,637,996 |
def bottom_up_low_space(N,K,ts):
"""
Recursive algorithm.
args:
N :: int
length of ts
K :: int
ts :: list of ints
returns:
res :: bool
True :: if a subset of ts sums to K
False :: otherwise
subset :: list of tuples
... | 31e810871088309fded97b2ab844c3f910c84ffb | 3,637,998 |
import json
def getInfo(ID):
"""
get info from file
:param ID: meter ID
:return: info = {
"distance": 10,
"horizontal": 10,
"vertical": 20,
"name": "1_1",
"type": SF6,
"template": "template.jpg",
"ROI": {
... | d0e415b547450a84d15c96b3800276f6f566e503 | 3,638,001 |
import tensorflow as tf
def cast_tensor_by_spec(_input, spec):
"""
transform dtype & shape following spec
"""
try:
except ImportError:
raise MissingDependencyException(
"Tensorflow package is required to use TfSavedModelArtifact"
)
if not _isinstance_wrapper(spec, ... | 3cea0851c5cc9d457a05b58b0d2cdde50b3ed1ba | 3,638,004 |
def StopRequestHook(ref, args, request):
"""Declarative request hook for TPU Stop command."""
del ref
del args
stop_request = GetMessagesModule().StopNodeRequest()
request.stopNodeRequest = stop_request
return request | 8eba140a8f9bf59fec293d8f33d4c10bb03c1a99 | 3,638,005 |
def get_bucket(
storage_bucket_name: str,
**kwargs,
) -> Bucket:
"""Get a storage bucket."""
client = get_client()
return client.get_bucket(storage_bucket_name, **kwargs) | ad33ae43f9d8ff2fb087519733931efd3952df18 | 3,638,006 |
def furl_for(endpoint: str, filename: str=None, **kwargs: dict) -> str:
""" Replacement for url_for. """
return URL() + (url_for(endpoint, filename=filename) if filename != None else ("/" if endpoint == "" else url_for(endpoint, **kwargs))) | 2e518ce13bd01771a5daffc111c6adc5d60e40cd | 3,638,007 |
def image_max_value(img, region=None, scale=None):
"""Retrieves the maximum value of an image.
Args:
img (object): The image to calculate the maximum value.
region (object, optional): The region over which to reduce data. Defaults to the footprint of the image's first band.
scale (float... | b7e9c4ece9639fbdad75146021fd16438567b9c7 | 3,638,008 |
def getblock(lst, limit):
"""Return first limit entries from list lst and remove them from the list"""
r = lst[-limit:]
del lst[-limit:]
return r | 8d230dec59fe00375d92b6c6a8b51f3e6e2d9126 | 3,638,009 |
def electrode_neighborhoods(mea='hidens', neighborhood_radius=HIDENS_NEIGHBORHOOD_RADIUS, x=None, y=None):
"""
Calculate neighbor matrix from distances between electrodes.
:param mea: (optional) type of the micro electrode array, default: 'hidens'
:param neighborhood_radius:(optional) depends on mea typ... | 7595b8cbd43bd12db2cb8e8a14d1968152a34fc0 | 3,638,010 |
def lat_from_meta(meta):
"""
Obtains a latitude coordinates array from rasterio metadata.
:param meta: dict rasterio metadata.
:return: numpy array
"""
try:
t, h = meta["transform"], meta["height"]
except KeyError as e:
raise e
lat = np.arange(t[5], t[5] + (t[4] * h), t[4... | dd4624521071788e497dadabdbb3e7716c6132cc | 3,638,011 |
def get_test_class(dbcase):
"""Return the implementation class of a TestCase, or None if not found.
"""
if dbcase.automated and dbcase.valid:
impl = dbcase.testimplementation
if impl:
obj = module.get_object(impl)
if type(obj) is type and issubclass(obj, core.Test):
... | 0ddf0127f87308695fef83001424ce7fa94ca463 | 3,638,012 |
def calc_dp(t_c, rh):
"""Calculate the dew point in Celsius.
Arguments:
t_c - the temperature in °C.
rh - the relative humidity as a percent, (0-100)
Returns:
The dew point in °C.
"""
sat_vp = vapor_pressure_liquid_water(t_c)
vp = sat_vp * rh / 100.0
a = log(vp / 6.1037) / 17.6... | a183a11e6a61e536376802d18b939caa7c02dd28 | 3,638,013 |
def conv_block(input_tensor, kernel_size, filters, stage, block, strides=(2, 2)):
"""conv_block is the block that has a conv layer at shortcut
# Arguments
input_tensor: input tensor
kernel_size: defualt 3, the kernel size of middle conv layer at main path
filters: list of integers, the f... | f54486729405eb1ae41b554842c5942f8ad9483a | 3,638,015 |
from typing import List
from typing import Optional
import tokenize
def _fake_before_lines(first_line: str) -> List[str]:
"""Construct the fake lines that should go before the text."""
fake_lines = []
indent_levels = _indent_levels(first_line)
# Handle regular indent
for i in range(indent_levels... | 9d3a450dce45690e1650ad2f1c86eff5df5d8e36 | 3,638,016 |
def normal_logpdf(x, mu, cov):
"""
Multivariate normal logpdf, numpy native implementation
:param x:
:param mu:
:param cov:
:return:
"""
part1 = 1 / (((2 * np.pi) ** (len(mu) / 2)) * (np.linalg.det(cov) ** (1 / 2)))
part2 = (-1 / 2) * ((x - mu).T.dot(np.linalg.inv(cov))).dot((x - mu)... | 47672093235cdf23562a83eac28ad428c5d4db24 | 3,638,017 |
def criteriarr(criteria):
"""Validate if the iterable only contains MIN (or any alias) and MAX
(or any alias) values. And also always returns an ndarray representation
of the iterable.
Parameters
----------
criteria : Array-like
Iterable containing all the values to be validated by the... | 3f00db0e4a41ab09650b7779819e243c25b6ca35 | 3,638,018 |
import random
def integer_or_rational(entropy, signed, min_abs=0):
"""Returns a rational, with 50% probability of it being an integer."""
if random.choice([False, True]):
return integer(entropy, signed, min_abs=min_abs)
else:
return non_integer_rational(entropy, signed) | 03e11aa082dfdb613f0f1861ff8346b1087b4880 | 3,638,019 |
import functools
import warnings
def ignore_python_warnings(function):
"""
Decorator for ignoring *Python* warnings.
Parameters
----------
function : object
Function to decorate.
Returns
-------
object
Examples
--------
>>> @ignore_python_warnings
... def f()... | 438e54fe927f787783175faacf4eb9608fd27cf0 | 3,638,020 |
def runMetrics(
initWorkingSetName,
stepName,
requestInfo,
jobId,
outputFolder,
referenceFolder,
referencePrefix,
dtmFile,
dsmFile,
clsFile,
mtlFile,
):
"""
Run a Girder Worker job to compute metrics on output files.
Requirements:
- Danesfield Docker image is... | e908191b274e4d55dc77a5686dc462a2f8a43798 | 3,638,021 |
def matplotlib_kwarg_dealiaser(args, kind):
"""De-aliase the kwargs passed to plots."""
if args is None:
return {}
matplotlib_kwarg_dealiaser_dict = {
"scatter": mpl.collections.PathCollection,
"plot": mpl.lines.Line2D,
"hist": mpl.patches.Patch,
"bar": mpl.patches.Re... | 9c267531bde5445d7024bee4860b882044359212 | 3,638,023 |
def volume():
"""
Get volume number
:return:
"""
return Scheduler.ret_volume | 0a39ff47800d04055971e7687b240f0c1e1a2396 | 3,638,024 |
def grid_grad(input, grid, interpolation='linear', bound='zero',
extrapolate=False):
"""Sample spatial gradients of an image with respect to a deformation field.
Notes
-----
{interpolation}
{bound}
Parameters
----------
input : ([batch], [channel], *inshape) tensor
... | 4df566e4612252169f2fab721b62cbd9be8c85ac | 3,638,025 |
def delete_cart_item(quote_id, item_code):
"""Delete given item_codes from Quote if all deleted then delete Quote"""
try:
response = frappe._dict()
item_code = item_code.encode('utf-8')
item_list= [ i.strip() for i in item_code.split(",")]
if not isinstance(item_code, list):
item_code = [item_code]
if n... | f7a17cf74764322136bd3e3940a37399ec1ac53b | 3,638,026 |
def list_methods(f):
"""Return a list of the multimethods currently registered to `f`.
The multimethods are returned in the order they would be tested by the dispatcher
when the generic function is called.
The return value is a list, where each item is `(callable, type_signature)`.
Each type signa... | 97ac92d58ee1edd7c38a2b9c1bcd05f0b7468a24 | 3,638,027 |
def get_requirements(extra=None):
"""
Load the requirements for the given extra from the appropriate
requirements-extra.txt, or the main requirements.txt if no extra is
specified.
"""
filename = f"requirements-{extra}.txt" if extra else "requirements.txt"
with open(filename) as fp:
... | 7ce9e348357925b7ff165ebd8f13300d849ea0ee | 3,638,029 |
def _format_mojang_uuid(uuid):
"""
Formats a non-hyphenated UUID into a whitelist-compatible UUID
:param str uuid: uuid to format
:return str: formatted uuid
Example:
>>> _format_mojang_uuid('1449a8a244d940ebacf551b88ae95dee')
'1449a8a2-44d9-40eb-acf5-51b88ae95dee'
Must have 32 charac... | 517071b28f1e747091e2a539cd5d0b8765bebeba | 3,638,031 |
def generate_uri(graph_base, username):
"""
Args:
graph_base ():
username ():
Returns:
"""
return "{}{}".format(graph_base, username) | 5e3557d300ed1a706e7b5257719135063d8c44e6 | 3,638,032 |
from typing import Type
from typing import Optional
from typing import Dict
from typing import Any
def _combine_model_kwargs_and_state(
generator_run: GeneratorRun,
model_class: Type[Model],
model_kwargs: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
"""Produces a combined dict of model kwargs... | b646b1cd12cdba02e0495e0592790933adadd3c9 | 3,638,033 |
def quick_boxcar(s, M=4, centered=True):
"""Returns a boxcar-filtered version of the input signal
Keyword arguments:
M -- number of averaged samples (default 4)
centered -- recenter the filtered signal to reduce lag (default False)
"""
# Sanity check on signal and filter window
length = s.s... | 64e0a847b05972f674394984fe8799738465b96b | 3,638,034 |
def read_file(file, assume_complete=False):
"""read_file(filename, assume_complete=False) -> Contest
Read in a text file describing a contest, and construct a Contest object.
This adds the ballots (by calling addballots()), but it doesn't do
any further computation.
If assume_complete is True, any... | 2e57353c66b82e73fbc4caace2f2e2e54d486dac | 3,638,036 |
import six
def merge_dict(a, b):
"""
Recursively merges and returns dict a with dict b.
Any list values will be combined and returned sorted.
:param a: dictionary object
:param b: dictionary object
:return: merged dictionary object
"""
if not isinstance(b, dict):
return b
... | 5adddd784ff4facdefebecea3ce2ab5069058885 | 3,638,037 |
def send_message(oc_user,params):
"""留言
"""
to_uid = params.get("to_uid")
content = params.get("content",'')
if not to_uid:
return 1,{"msg":"please choose user"}
if not content:
return 2,{"msg":"please input content"}
if len(content) > 40:
return 3,{"msg":"c... | 6e61bfd8bfd4b94584e093c2bd91e647c39f7f90 | 3,638,038 |
def BDD100K(path: str) -> Dataset:
"""`BDD100K <https://bdd-data.berkeley.edu>`_ dataset.
The file structure should be like::
<path>
bdd100k_images_100k/
images/
100k/
test
train
val... | c154f57e09fac6b01004015bcbebdbd3929a9ac3 | 3,638,039 |
def is_utf8(string):
"""Check if argument encodes to UTF8 without error.
Args:
string(str): string of bytes
Returns:
True if string can be successfully encoded
"""
try:
string.encode('utf-8')
except UnicodeEncodeError:
return False
except UnicodeDecodeError:... | 4ea0f8f9b93976017a8add574098d89f86f1345d | 3,638,040 |
def fixedwidth_bins(delta, xmin, xmax):
"""Return bins of width `delta` that cover `xmin`, `xmax` (or a larger range).
The bin parameters are computed such that the bin size `delta` is
guaranteed. In order to achieve this, the range `[xmin, xmax]` can be
increased.
Bins can be calculated for 1D da... | 5f9e8bc31f44d66323689a1a79d6a597d422fa57 | 3,638,041 |
def get_word(path):
""" extract word name from json path """
return path.split('.')[0] | e749bcdaaf65de0299d35cdf2a2264568ad5051b | 3,638,042 |
def produce_edge_image(thresh, img):
"""
Threshold the image and return the edges
"""
(thresh, alpha_img) = cv.threshold(img, thresh, 255, cv.THRESH_BINARY_INV)
blur_img = cv.medianBlur(alpha_img, 9)
blur_img = cv.morphologyEx(blur_img, cv.MORPH_OPEN, (5,5))
# find the edged
return c... | e269f15f515e8c88da3761306430d4d49c445d3b | 3,638,043 |
def aggregate_dicts(dicts: t.Sequence[dict], agg: str = "mean") -> dict:
"""
Aggregates a list of dictionaries into a single dictionary. All dictionaries in ``dicts`` should have the same keys.
All values for a given key are aggregated into a single value using ``agg``. Returns a single dictionary with the
... | c8a557e26c885fcef381eb21edd27a0fcb91a12e | 3,638,045 |
def aggregation_most_frequent(logits):
"""This aggregation mechanism takes the softmax/logit output of several
models resulting from inference on identical inputs and computes the most
frequent label. It is deterministic (no noise injection like noisy_max()
above.
:param logits: logits or probabili... | 28440569b918a2a58ca0ee1589884948809994c7 | 3,638,046 |
from typing import Dict
def evaluate_submission_with_proto(
submission: Submission,
ground_truth: Submission,
) -> Dict[str, float]:
"""Calculates various motion prediction metrics given
the submission and ground truth protobuf messages.
Args:
submission (Submission): Proto messag... | c777359e6385164a463318f089ceb330e7bad814 | 3,638,049 |
def build_optimizer(args, model):
"""
Build an optimizer based on the arguments given
"""
if args['optim'].lower() == 'sgd':
optimizer = optim.SGD(model.parameters(), lr=args['learning_rate'], momentum=0.9, weight_decay=args['weight_decay'])
elif args['optim'].lower() == 'adadelta':
... | 09677cbd5dc13f0dbab227f64d7724ff653eb9ec | 3,638,050 |
import re
def decorator_matcher(func_names, keyword, fcreate=None):
"""Search pattern @[namespace]<func_name>("<skey>")
Parameters
----------
func_names : list
List of macro names to match.
fcreate : Function (skey, path, range, func_name) -> result.
"""
decorator = r"@?(?P<deco... | 62db3ae8bfaab36266cbe07f886531d60f47905e | 3,638,051 |
def log_binomial(n, k, tol=0.):
"""
Computes log binomial coefficient.
When ``tol >= 0.02`` this uses a shifted Stirling's approximation to the
log Beta function via :func:`log_beta`.
:param torch.Tensor n: A nonnegative integer tensor.
:param torch.Tensor k: An integer tensor ranging in ``[0,... | 6e61ac09020c65202a2ab32134cb0c2ff6ff7f80 | 3,638,052 |
def error_500(request, *args, **kwargs):
"""
Throws a JSON response for INTERNAL errors
:param request: the request
:return: response
"""
message = "An internal server error ocurred"
response = JsonResponse(data={"message": message, "status_code": 500})
response.status_code = 500
ret... | 59f31de52a0d77ca71b3176929cf3142858637cf | 3,638,053 |
from datetime import datetime
import warnings
def datetimes_to_durations(start_times, end_times, fill_date=datetime.today(), freq="D", dayfirst=False, na_values=None):
"""
This is a very flexible function for transforming arrays of start_times and end_times
to the proper format for lifelines: duration and... | f30f64ac90b92a8614e60119d93f14954e24e2ef | 3,638,054 |
from datetime import datetime
import calendar
def offset_from_date(v, offset, gran='D', exact=False):
"""
Given a date string and some numeric offset, as well as a unit, then compute
the offset from that value by offset gran's. Gran defaults to D. If exact
is set to true, then the exact date is figure... | 6b45b553df7926ee0e68ee0e2678d4da5304e9b9 | 3,638,055 |
def _strip(x):
"""remvoe tensor-hood from the input structure"""
if isinstance(x, Tensor):
x = x.item()
elif isinstance(x, dict):
x = {k: _strip(v) for k, v in x.items()}
return x | 74023594b2da6f58dea425411d72ca493fb80f61 | 3,638,056 |
def rank_array(a, descending=True):
"""Rank array counting from 1"""
temp = np.argsort(a)
if descending:
temp = temp[::-1]
ranks = np.empty_like(temp)
ranks[temp] = np.arange(1,len(a)+1)
return ranks | 8f15ab7123aa7652fe5208ef96808791454b876c | 3,638,057 |
def normalize(params, axis=0):
"""
Function normalizing the parameters vector params with respect to the Axis: axis
:param params: array of parameters of shape [axis0, axis1, ..., axisp] p can be variable
:return: params: array of same shape normalized
"""
return params / np.sum(params, axis=ax... | c11ee3ccab492769e8c60cf2057d010190c7362f | 3,638,059 |
from typing import Sequence
from typing import Dict
from typing import List
def estimate_cv_regression(
results: pd.DataFrame, critical_values: Sequence[float]
) -> Dict[float, List[float]]:
"""
Parameters
----------
results : DataFrame
A dataframe with rows contaoning the quantiles and co... | 22e163da18cb7a9707ebba16690788467a4132c9 | 3,638,061 |
def resize(image, size):
"""Resize multiband image to an image of size (h, w)"""
n_channels = image.shape[2]
if n_channels >= 4:
return skimage.transform.resize(
image, size, mode="constant", preserve_range=True
)
else:
return cv2.resize(image, size, interpolation=cv2... | 6a67524552397f1b1c9cd315b2cbaccd624027fb | 3,638,063 |
def version():
"""Return the version of this cli tool"""
return __version__ | 790059de16a48ea7dd5dbcc4470f2be851562146 | 3,638,065 |
def ho2cu(ho):
"""
Homochoric vector to cubochoric vector.
References
----------
D. Roşca et al., Modelling and Simulation in Materials Science and Engineering 22:075013, 2014
https://doi.org/10.1088/0965-0393/22/7/075013
"""
rs = np.linalg.norm(ho,axis=-1,keepdims=True)
xyz3 = np... | be55f70c27be789a51c9aee0ba94b36879755915 | 3,638,067 |
def apparent_resistivity(
dc_survey, survey_type='dipole-dipole',
space_type='half-space', dobs=None,
eps=1e-10
):
"""
Calculate apparent resistivity. Assuming that data are normalized
voltages - Vmn/I (Potential difference [V] divided by injection
current [A]). For fwd modelled ... | ec9cc774b2ae9484916da46083730156c64559d1 | 3,638,068 |
import json
def readJsonFile(filePath):
"""read data from json file
Args:
filePath (str): location of the json file
Returns:
variable: data read form the json file
"""
result = None
with open(filePath, 'r') as myfile:
result = json.load(myfile)
return result | cf15e358c52edcfb00d0ca5257cf2b5456c6e951 | 3,638,069 |
def _sort_torch(tensor):
"""Update handling of sort to return only values not indices."""
sorted_tensor = _i("torch").sort(tensor)
return sorted_tensor.values | 0480d397726f9cd97c9fa9b7e566db1d9266a75a | 3,638,070 |
def lambda_handler(event, context):
"""
Route the incoming request based on type (LaunchRequest, IntentRequest, etc).
The JSON body of the request is provided in the event parameter.
"""
print("event.session.application.applicationId=" +
event['session']['application']['applicationId'])
... | cda1cecdde08ae0cb7c925a5f8b598efd1c47e16 | 3,638,071 |
def get_authorized_client(config):
"""Get an OAuth-authorized client
Following
http://requests-oauthlib.readthedocs.org/en/latest/examples/google.html
"""
client = requests_oauthlib.OAuth2Session(
client_id=config['client']['id'],
scope=SCOPE,
redirect_uri=config['client']['... | 00012be81fed9e29cfabcf81799d887259fa395c | 3,638,072 |
from datetime import datetime
def query_obs_4h(session, station_name: str, start: datetime, end: datetime) -> pd.DataFrame:
"""
SQLite 读取 & 解析数据.
"""
time_format = "%Y-%m-%d %H:00:00"
resp = session.query(
ObsDataQcLinear.time,
ObsDataQcLinear.watertemp,
ObsDataQcLinear.pH,... | 35730e5de1b675dc14ef5771459e7cb9629d34e5 | 3,638,073 |
def get_valid_user_input(*, prompt='', strict=False):
"""Return a valid user input as Fraction."""
frac_converter = parse_fraction_strict if strict else Fraction
while True:
user_input = input(prompt)
try:
user_input_fraction = frac_converter(user_input)
except (ValueErro... | 7726df5b1a57ab9c9122a60e847be95161829a09 | 3,638,074 |
def binary_irrev(t, kf, prod, major, minor, backend=None):
"""Analytic product transient of a irreversible 2-to-1 reaction.
Product concentration vs time from second order irreversible kinetics.
Parameters
----------
t : float, Symbol or array_like
kf : number or Symbol
Forward (bimole... | c399cb13bbe32a066b07e0aaa93fc40ddfd8c6ec | 3,638,076 |
def adapted_rand_error(seg, gt, all_stats=False):
"""Compute Adapted Rand error as defined by the SNEMI3D contest [1]
Formula is given as 1 - the maximal F-score of the Rand index
(excluding the zero component of the original labels). Adapted
from the SNEMI3D MATLAB script, hence the strange style.
... | 0530fad7982e83aaf33e3f190b435bc7e216af00 | 3,638,077 |
from typing import List
def get_knp_span(type_: str, span: Span) -> List[Span]:
"""Get knp tag or bunsetsu list"""
assert type_ != MORPH
knp_list = span.sent._.get(getattr(KNP_USER_KEYS, type_).list_)
if not knp_list:
return []
res = []
i = span.start_char
doc = span.doc
for ... | 90c0f753a6dd4acdbdfebc550fa66b1e8c5f21eb | 3,638,078 |
def get_namespace_leaf(namespace):
"""
From a provided namespace, return it's leaf.
>>> get_namespace_leaf('foo.bar')
'bar'
>>> get_namespace_leaf('foo')
'foo'
:param namespace:
:return:
"""
return namespace.rsplit(".", 1)[-1] | 0cb21247f9d1ce5fa4dd8d313142c4b09a92fd7a | 3,638,079 |
from typing import Tuple
def fft_real_dB(sig: np.ndarray,
sample_interval_s: float) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
"""
FFT, real frequencies only, magnitude in dB
:param sig: array with input signal
:param sample_interval_s: sample interval in seconds
:r... | fc2aec1bad283aa7e1817e6d91c833e3d8c83f8f | 3,638,080 |
from typing import Union
from typing import List
def get_ipv4_gateway_mac_address_over_ssh(connected_ssh_client: SSHClient,
target_os: str = 'MacOS',
gateway_ipv4_address: str = '192.168.0.254') -> Union[None, str]:
"""
Get MA... | 5701aaec179d0d36f38df929d7838fc9e31ebe4f | 3,638,081 |
def sort(list_):
"""
This function is a selection sort algorithm. It will put a list in numerical order.
:param list_: a list
:return: a list ordered by numerial order.
"""
for minimum in range(0, len(list_)):
for c in range(minimum + 1, len(list_)):
if list_[c] < list_[mini... | 99007e4b72a616ae73a20358afc94c76e0011d3e | 3,638,082 |
import requests
import tqdm
def stock_em_xgsglb(market: str = "沪市A股") -> pd.DataFrame:
"""
新股申购与中签查询
http://data.eastmoney.com/xg/xg/default_2.html
:param market: choice of {"全部股票", "沪市A股", "科创板", "深市A股", "创业板"}
:type market: str
:return: 新股申购与中签数据
:rtype: pandas.DataFrame
"""
mark... | 2ea409c176e5a2b266866f5af7bbced291dbadca | 3,638,083 |
def geomfill_Mults(*args):
"""
:param TypeConv:
:type TypeConv: Convert_ParameterisationType
:param TMults:
:type TMults: TColStd_Array1OfInteger &
:rtype: void
"""
return _GeomFill.geomfill_Mults(*args) | d79a857308bb796e08ce3e84f75963d473f37b76 | 3,638,084 |
import ctypes
def PCO_GetRecordingStruct(handle):
"""
Get the complete set of the recording function
settings. Please fill in all wSize parameters,
even in embedded structures.
"""
strRecording = PCO_Recording()
f = pixelfly_dll.PCO_GetRecordingStruct
f.argtypes = (ctypes.wintypes.HAN... | 2d50968e9445f3937726583c00a61c8839b488b2 | 3,638,086 |
import random
def auxiliar2(Letra, tabuleiro):
"""
Função auxiliar para jogada do computador, esta função compõe a estratégia e é responsável por realizar uma das jogadas do computador. Recebe como parâmetro o Simbolo do computador
e retorna a jogada que será realizada.
"""
if Letra == "X":
... | 1db9ca4a9a9e97a3b689efc4295b59ad553cfd7a | 3,638,087 |
def create_task():
"""
处理创建根据相关抓取参数及抓取节点服务的名称,启动数据抓取.
:return:
"""
payload = request.get_json()
# 查找抓取节点信息
node = db.nodes.find_one({"name": payload["node"]})
# 未找到抓取节点返回404
if node is None:
return abort(404)
# 保存任务信息至数据库中
payload["task"] = "%s@%s" % (payload["node... | 4963b66174f57687453a4a59b321d564cbec9225 | 3,638,088 |
def eco_hist_calcs(mass,bins,dlogM):
"""
Returns dictionaries with the counts for the upper
and lower density portions; calculates the
three different percentile cuts for each mass
array given
Parameters
----------
mass: array-like
A 1D array with log stellar ma... | bf4e9ffeec76b2cf7a3e85db73dd1a7fc996ecd9 | 3,638,089 |
def avgSentenceLength(text):
"""Return the average length of a sentence."""
tokens = langtools.tokenize(text)
return len(tokens) / sentenceCount(text) | 4988c4fe945e2eada9abf01aebe0d454620cf565 | 3,638,090 |
def retrieve_context_topology_link_available_capacity_total_size_total_size(uuid, link_uuid): # noqa: E501
"""Retrieve total-size
Retrieve operation of resource: total-size # noqa: E501
:param uuid: ID of uuid
:type uuid: str
:param link_uuid: ID of link_uuid
:type link_uuid: str
:rtype:... | 6c0ee9cbf2784b17a6d624530bdf94875b4e751f | 3,638,091 |
import re
def harmonize_geonames_id(uri):
"""checks if a geonames Url points to geonames' rdf expression"""
if 'geonames' in uri:
geo_id = "".join(re.findall(r'\d', uri))
return "http://sws.geonames.org/{}/".format(geo_id)
else:
return uri | acfb8cb4277363c6bee4844a0a95ed2ea464e741 | 3,638,092 |
def get_apikey(api):
"""Return the API key."""
if api == "greynoise":
return config.greynoise_key
if api == "hybrid-analysis":
return config.hybrid_analysis_apikey
if api == "malshare":
return config.malshare_apikey
if api == "pulsedive":
return config.pulsedive_apike... | bf52c5424c657dc9d2173c0fa7434040daf967f3 | 3,638,094 |
def create_admin_account():
"""
Creates a new admin account
"""
try:
original_api_key = generate_key()
secret_key = generate_key()
hashed_api_key = generate_password_hash(original_api_key)
Interactions.insert(DEFAULT_ACCOUNTS_TABLE,
**{'userna... | 3d9d1c7fdfe0492080930855490eb8f050056c54 | 3,638,095 |
def _arg_wrap(func):
""" Decorator to decorate decorators to support optional arguments. """
@wraps(func)
def new_decorator(*args, **kwargs):
if len(args) == 1 and len(kwargs) == 0 and callable(args[0]):
return func(args[0])
else:
return lambda realf: func(realf, *ar... | a74f7cf363aab33d770c5f7a080b8796d27e91ec | 3,638,096 |
def _point_as_tuple(input_string: str) -> _Tuple[float]:
"""
Attempts to parse a string as a tuple of floats.
Checks that the number of elements corresponds to the specified dimensions.
The purpose of this function more than anything else is to validate correct
syntax of a CLI argument that is suppo... | f828c5ed9cbcf9b1820abaff07c0b646027e6ab9 | 3,638,097 |
import random
def generate_id():
"""Generate Hexadecimal 32 length id."""
return "%032x" % random.randrange(16 ** 32) | 2f9a9eb7cc1808515fb7d71607899bb43d2ac682 | 3,638,098 |
def __charge_to_sdf(charge):
"""Translate RDkit charge to the SDF language.
Args:
charge (int): Numerical atom charge.
Returns:
str: Str representation of a charge in the sdf language
"""
if charge == -3:
return "7"
elif charge == -2:
return "6"
elif charge ... | 1bfda86ee023e8c11991eaae2969b87a349b7f7e | 3,638,099 |
def save_str(self=str(''),
filename=str('output.txt'),
permissions=str('w')):
"""Save a given string to disk using a given file name.
Args:
self(str): String to save to disk. (default str(''))
filename(str): File name to use when saving to disk. (default str('output.tx... | 87df6f654834409397d63e0313d26c70d1944a11 | 3,638,100 |
def balanced(banked_chemicals):
"""return true if all non-ore chemicals have non-negative amounts."""
def _enough(chemical):
return chemical == "ORE" or banked_chemicals[chemical] >= 0
return all(map(_enough, banked_chemicals)) | c42d492bfc67664040095260c24bbff155e98d5e | 3,638,101 |
import bz2
import json
def dict2json(thedict, json_it=False, compress_it=False):
"""if json_it convert thedict to json
if compress_it, do a bzip2 compression on the json"""
if compress_it:
return bz2.compress(json.dumps(thedict).encode())
elif json_it:
return json.dumps(thedict)
el... | b6158427c653a00cc6953ce9f0b0a0fb4881bd7a | 3,638,102 |
def compoundedInterest(fv, p):
"""Compounded interest
Returns: Interest value
Input values:
fv : Future value
p : Principal
"""
i = fv - p
return i | 00f7fd1f141293afe595393eca23c308d3fdd7d0 | 3,638,105 |
def get_volumetric_scene(self, data_key="total", isolvl=0.5, step_size=3, **kwargs):
"""Get the Scene object which contains a structure and a isosurface components
Args:
data_key (str, optional): Use the volumetric data from self.data[data_key]. Defaults to 'total'.
isolvl (float, optional): Th... | 836fb5f3158ed5fe55a2975ce05eb21636584a95 | 3,638,106 |
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OrdinalEncoder
def encode_labels(x, features):
"""
Maps strings to integers
"""
encoder = ColumnTransformer([("", OrdinalEncoder(), features)], n_jobs=-1)
x[:, features] = encoder.fit_transform(x)
return x | 8f318020f663a88733dea9389627cb62d483892c | 3,638,107 |
def get_jogframe(
conx: Connection, idx: int, group: int = 1, include_comment: bool = False
) -> t.Tuple[Position_t, t.Optional[str]]:
"""Return the jog frame at index 'idx'.
:param idx: Numeric ID of the jog frame.
:type idx: int
:param group: Numeric ID of the motion group the jog frame is
as... | 9a1a215311d111c262ab9810c5933a07c39d4def | 3,638,108 |
def rotate(arr, bins):
"""
Return an array rotated by 'bins' places to the left
:param list arr: Input data
:param int bins: Number of bins to rotate by
"""
bins = bins % len(arr)
if bins == 0:
return arr
else:
return np.concatenate((arr[bins:], arr[:bins])) | 0ac038377ed173130d83ef5231bd9678058de28a | 3,638,109 |
from typing import Iterable
from typing import Optional
from typing import List
from typing import OrderedDict
def clear_list(items: Iterable[Optional[Typed]]) -> List[Typed]:
""" return unique items in order of first ocurrence """
return list(OrderedDict.fromkeys(i for i in items if i is not None)) | 511bbfb6b567d494a143fb1e1ee06c39f54c47e8 | 3,638,110 |
def chords(labels):
"""
Transform a list of chord labels into an array of internal numeric
representations.
Parameters
----------
labels : list
List of chord labels (str).
Returns
-------
chords : numpy.array
Structured array with columns 'root', 'bass', and 'interv... | 53d14ab6318dfaeeb77d0dd5f815c8c2f3359918 | 3,638,111 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.