content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import click
def varg_command(cli, name, *others):
"""Create positional argument that are of variable length.
The token ``^`` can be used to mark the end of the argument list.
"""
def decorator(func):
r = click.argument(CommandAfterArgs.split_arg, nargs=-1)(func)
for o in reversed(ot... | a6d6d5e828d427e8d0534c36510640f0aa21632e | 3,629,768 |
def get_pipeline_lines(input_pipeline):
"""Returns a list with the lines in the .cppipe file"""
with open(input_pipeline) as f:
lines = f.readlines()
return lines | 403e7531b1cadfe25f519d2b176b97ac344cde6b | 3,629,769 |
def _f3_int_x_ ( self , *args ) :
""" Integrate 3D-function over x
>>> f = ...
>>> g = f.integrate_x ( 'x-range' )
- see ROOT.RooAbsReal.createIntegral
"""
##
vset = ROOT.RooArgSet ( self.xvar )
i = self.fun.createIntegral ( vset , *args )
##
return Fun2D ( i , self.yvar , s... | 2e70642a24f7882a0009e9be54ae903c4bf593cd | 3,629,770 |
def eotvos_number(L, lambda_c):
"""Returns the Eötvös/Bond number for the given liquid and gravity.
Parameters
----------
L : scalar (m) or Quantity
Characteristic length, ie. the radius of curvature at the top of the droplet.
lambda_c : scalar (m) or Quantity
The capillary length o... | e2fe6c435a47b62b29ebef7fc25895aafe4af62a | 3,629,771 |
def simple_update_property(attr_name, can_change=False,
type_cast_method=_string_type_cast):
"""Creates a simple @property corresponding to an attribute.
If can_change is True, also protects updating the value of this attribute.
Args:
attr_name: String; the name of a hid... | 24d91e3548c5c5b04402a2a904fe4c625e832ebf | 3,629,772 |
def _hyphenate_word(word):
""" Memoized hyphenate_word() function. """
cache = _hyphenate_word_cache
if word not in cache:
cache[word] = hyphenate_word(word)
return cache[word][:] | 660c419e5a512cad856b34117075dd984f1caacf | 3,629,773 |
def _rmse(y, y_bin, probs):
"""return 1-rmse since we're maximizing the score for hillclimbing"""
return 1.0 - sqrt(mean_squared_error(y_bin, probs)) | 2d6409ad829ba15fd9ff926708805cadd89c65d9 | 3,629,774 |
def skip_movie():
"""
The judge didn't like the movie they were presented with, so give them a new one.
Returns:
str: response string
"""
room = _get_room(request.args.get('code'))
movie = Movie.get_random()
room.current_round.movie = movie
# Send title & plot to host
sock... | a69e09b390aff269947cf6feeb8c5117bd7fc8ed | 3,629,775 |
def argmin_2d(X):
"""Take the arg minimum of a 2D array."""
assert X.size > 0, "argmin of empty array not defined"
ii, jj = np.unravel_index(X.argmin(), X.shape)
return ii, jj | 1058c5bdce085b1bb953eb9e0d0a62bdc6a357af | 3,629,777 |
def get_cf():
"""
Get an authenticated cloudflare API instance. Authentication resolved in
order from:
1. `.cloudflare.cfg`
2. Environment variables
@see
https://github.com/cloudflare/python-cloudflare#providing-cloudflare-username-and-api-key
"""
return CloudFlare.CloudFlare() | 9eb6e31642254fae0d2a776fa3de7ce4ad85f429 | 3,629,778 |
def remove_user_past_events(user_id):
"""
:Route: DELETE /<user_id>/past?past_event=event_id&past_event=event_id
:Description: Remove past events for a single user with id `user_id`. If no past events are specified, all of the user's past events are removed.
:param user_id: The unique ID of a specific... | 80c83e5953144030ec1780c7127d9b2d5132e1f3 | 3,629,779 |
import requests
from bs4 import BeautifulSoup
def futures_index_dict():
"""
name and code map
:return: name to code
:rtype: dict
index_code
商品期货指数 CCFI
农产品期货指数 CAFI
油脂油料期货指数 OOFI
谷物期货指数 CRFI
油脂期货指数 OIFI
粮食期货指数 GRFI
... | bbe9558346e67473d9be317d14ce3b8aafb617bf | 3,629,780 |
def int_like(value, name, optional=False, strict=False):
"""
Convert to int or raise if not int_like
Parameters
----------
value : object
Value to verify
name : str
Variable name for exceptions
optional : bool
Flag indicating whether None is allowed
strict : bool... | cb70054688bbd08c8ca4ee6f5573e8918d3510aa | 3,629,781 |
def maxmin(*args):
"""
Returns timed ((t,max),(t,min)) values from a (t,v) dataset
When used to filter an array the winndow will have to be doubled to
allocate both values (or just keep the one with max absdiff from previous).
"""
data = args[0]
t = sorted((v,t) for t,v in data)
mn,mx... | 8f76ee029d04a4a35688054512d0a0212adbfede | 3,629,782 |
def from_none(exc):
"""raise from_none(ValueError('a')) == raise ValueError('a') from None"""
exc.__cause__ = None
exc.__suppress_context__ = True
return exc | 86e45ba2df0020c85f13b85d8a98ee693422e922 | 3,629,783 |
def create_1D_velocity_magnitude_array_RHS(number_of_flowrates_analyzed, lower_flowrate_design_value, upper_flowrate_design_value, D_fd):
"""Goal is to create an array of velocity magnitudes. Will be used to create the velocity components in accordance with the angle arrays previously determined.
Args:
... | 24bf026fa97e42e86e68ddbe99422575f2dff80d | 3,629,784 |
def get_interface_type(interface):
"""Gets the type of interface
"""
if interface.upper().startswith("ET"):
return "ethernet"
elif interface.upper().startswith("VL"):
return "svi"
elif interface.upper().startswith("LO"):
return "loopback"
elif interface.upper().startswith... | f770a3ef1c43574d22630a5c4fff2f25d4975279 | 3,629,785 |
from swingers.sauth.models import ApplicationLink
def retrieve_access_token(request, service):
"""
Returns url, access_token for a service and request.
Service should be a string representing a service to connect to.
System will introspect settings.SITE_NAME to find service.
Probably issues if mor... | aa4bdf6610aa63c739d66553868ee30cd0d78bc8 | 3,629,786 |
from typing import Union
from pathlib import Path
from typing import Any
import pickle
def load_pickle(path: Union[Path, str]) -> Any:
"""
Loads a pickle from the path
:param path:
:return:
"""
assert check_file_exists(path), f'"{path}" does not exist'
return pickle.load(open(path, 'rb')) | 33ec2c16e09141fda2faeb4ac20aa80cebf4d1cf | 3,629,787 |
def convolutional_encode2(layers, batch_norm, stim_in,
is_training, reuse_variables=False):
"""Embed stimulus using multiple layers of convolutions.
Each convolutional layer has convolution, batch normalization and soft-plus.
Args :
layers : string description of multiple layers.
... | fa1f8a7ea2ac1a8fdb19afaa3512959350b49195 | 3,629,788 |
def getUniqueExposures(conn, candidateList, limit = 0, mostRecent = True, nonDets = False, discoveryLimit = 10, lastDetectionLimit=20, requestType = REQUESTTYPES['incremental'], ddc = False):
"""getUniqueExposures.
Args:
conn:
candidateList:
limit:
mostRecent:
nonDets:
... | 4101909d59d481509ce90d738b5234574fdf5aba | 3,629,790 |
def rgb2gray(image):
"""Convert 3-channel RGB image into grayscale"""
if image.ndim == 3:
return (0.299 * image[:, :, 0] + 0.587 * image[:, :, 1] +
0.114 * image[:, :, 2])
elif image.ndim == 4:
return (0.299 * image[:, :, :, 0] + 0.587 * image[:, :, :, 1] +
0.... | f87ed301dfd9c13ebfbabf99ad4b56c959a91e46 | 3,629,791 |
def create_variable(workflow_stat):
"""
Generates the javascript variables used to generate the chart.
@param workflow_stat the WorkflowInfo object reference
"""
number_of_jobs = workflow_stat.total_job_instances
# Adding variables
var_str = "<script type='text/javascript'>\nvar initMaxX = " + str(workflow_sta... | d0b55b00952f28242775a297fedab6cf1a69169e | 3,629,792 |
def group_fnames_by_pair_param2_param3_and_param1(directory: str,
param1: str,
param2: str,
param3: str):
"""
:param directory: directory do folder, which contai... | 7598cebac63a26477545935acf51405d037d8edd | 3,629,793 |
def drought_add_facecolor(drought: pd.DataFrame) -> pd.DataFrame:
"""Add facecolor column before drought plot."""
bar_colors = np.array(['blue', 'cyan', 'green', 'orange', 'red'])
drought_index_band = pd.cut(drought.drought_index, [-1.0, -0.99, -0.5, +0.5, +0.99, +1.001], right=False)
drought['facecolor... | a69471c1d8fc8e2b7aa80ef22a5c3274fa0e211d | 3,629,794 |
def aten_le(mapper, graph, node):
""" 构造对比大小的PaddleLayer。
TorchScript示例:
%80 : bool = aten::le(%78, %79)
参数含义:
%80 (bool): 输出,第一个元素是否小于等于第二个元素。
%78 (-): 需对比的输入1。
%79 (-): 需对比的输入2。
"""
scope_name = mapper.normalize_scope_name(node)
output_name = mapper._get_ou... | 45797abf1ec5a97619578dd734c1d9d7fb448aec | 3,629,795 |
def fstr(*args, **kwargs):
"""fstr(format) is f-string format like. Uses locals and globlallas. Useful in Py2."""
if not args:
raise TypeError('missing format in fstr(format, *args, **kwargs)')
fmt, args = args[0], args[1:]
return vfstr(fmt, args, kwargs) | 61843ed4b35c9cb89b3855801097a4961e1f174e | 3,629,796 |
import logging
def race_store(cfg):
"""
Creates a proper race store based on the current configuration.
:param cfg: Config object. Mandatory.
:return: A race store implementation.
"""
if cfg.opts("reporting", "datastore.type") == "elasticsearch":
logging.getLogger(__name__).info("Creat... | 78b1b56d103a47e1ef941674ddd9c9b3debf16de | 3,629,797 |
def getframeinfo(frame, context=1):
"""Get information about a frame or traceback object.
A tuple of five things is returned: the filename, the line number of
the current line, the function name, a list of lines of context from
the source code, and the index of the current line within that list.
Th... | 2d554d9db43fcc5a697e9b5db2486ba91fb59503 | 3,629,798 |
def Adjoint(T):
"""Computes the adjoint representation of a homogeneous transformation
matrix
:param T: A homogeneous transformation matrix
:return: The 6x6 adjoint representation [AdT] of T
Example Input:
T = np.array([[1, 0, 0, 0],
[0, 0, -1, 0],
... | 3894ecec8c4e1de01b550307c7df47fdc959d46e | 3,629,799 |
def get_extensions(dtypes):
"""
Find available extensions for the specified dtypes
"""
return _filter_entities(_tb_extensions, dtypes) | 7fdfcc5919f56568db75a84e496c278cf9f86da5 | 3,629,800 |
def remove_blocks(pattern, source):
"""Given a pattern and a source, replace all matching blocks with a
placeholder and then return the updated source and blocks as a tuple."""
blocks = {}
match = pattern.search(source)
while match:
key = placeholder()
original_block = match.group(0)... | a79ad21ba3702958c9c63c721dde3b70efa7e98f | 3,629,801 |
def asintegerarrays(*arrays, requirements=None, min_itemsize=None):
"""Cast the given array(s) to the same integer type.
Not a public function.
This is useful when calling cython functions.
Args:
*arrays (array-like): At least one array-like.
requirements (str/list[str], optional): S... | 1c61938800ea444bd57f376076c9bd8a3597345c | 3,629,802 |
def tune_hyperparameters(X_train, y_train, group, model, ct, param_dict, n_iter, score):
"""Tunes hyperparameters for a ML model with LOGO randomizedCV.
Note: This function is not included in my final solution, as the time required
to run it (even with GPU) takes much too long in Kaggle.
Parameters
... | 0abe011d3bdb922a6735f80caf472348a7838983 | 3,629,803 |
def _design_matrix(X, fit_intercept=True):
"""Make design matrix
For ordinary linear square, it would be X.T@X, ie the Gram matrix
Override it, if you need.
Arguments:
X {2D array} -- input data
fit_intercept {bool} -- whether to add intercept to the design matrix
Ret... | 6c739a303af0674bbccce6dd832442f673e07016 | 3,629,804 |
def simulate_gym_user(num_days=1000, noise_frac=0.0, periodicity=3, success_prob=0.5):
"""
Small routine returning an artificial binary visit timeseries of a very regular user for regularity analysis.
time_window: pd.DatetimeIndex, used as index for the timeseries
visit_dates: List, values between 0 and... | b48b810dc527325e152a6de7200643e7699d8a2d | 3,629,805 |
def get_new_session_notification_actions(session_id, link):
"""
Get the actions associated with a notification of an event getting a new session proposal.
:param session_id: id of the session.
:param link: link to view the session.
:return: actions
"""
view_session_action = NotificationActio... | fe788e9c64535b29c6c563a71d4ef0a203f740f3 | 3,629,806 |
from typing import Tuple
from typing import Any
def pack_data(*args: Tuple[Any, str]) -> bytes:
"""Normalize data and pack them into a byte array"""
values, abi_types = zip(*args)
normalized_values = map_abi_data([abi_address_to_hex], abi_types, values)
return decode_hex(
"".join(
... | b9ce5c2f06edd05ab053f4d8809a845c5e01afa1 | 3,629,807 |
def cls_list_inputs(cls):
"""Return a list of inputs in a Component class"""
return [k for k, v in cls.__class_traits__.iteritems() if v.iotype == 'in' and k not in Component.__class_traits__ and not v.vartypename == None] | 2f4b40642822e612daf22c007726fafa407bd6d4 | 3,629,809 |
import torchvision
import torch
def load_trained_model(model_name=None, model_path="", class_num=10):
""" Load trained model from .pth file.
Supported models:
* "resnet": resnet18
* "vgg": vgg11
* "inception": inception v3
* "mobilenet": mobilenet v2
"""
model = None
# load models
if mo... | e3e47bede7b8607029b20012e360b3dc35086448 | 3,629,810 |
def get_note(identifier):
"""
Return a Document object for a single note instance.
"""
note = notes[identifier]
return Document(
url='/' + identifier,
title='Note',
content={
'description': note['description'],
'complete': note['complete'],
... | ce193684d24e3d29595db60ba55aea70d42864f4 | 3,629,811 |
from .util import imhist
from .classical import histeq
from .exact import histeq_exact
def contrast_restoration(im, method, remove_bits=1, blur_sigma=0, **kwargs):
"""
Performs contrast enhancement by degrading an image with degrade_image then performing histogram
equalization to restore the original hist... | b11144382e36406df5c4aab899e7fa041f44d5cf | 3,629,812 |
def benchmark_matrix_inverse():
"""
Benchmark the user's setup by measuring the time taken by matrix inversion
Performs a benchmark of the user's setup by inverting a 6400x6400 matrix
filled with random numbers. This function then returns the time in ms taken
for this operation.
Good performan... | 2821ebba8fc74a5a2c3bd34471a834f58ea14bd7 | 3,629,813 |
def psiBlastRun(sequence, cycles=2, filename=None, **kwargs):
"""Returns the results from a full PSI-BLAST run (multiple cycles).
All arguments are the same as psiBlastCycle and are passed to it
except for cycles.
:arg cycles: the number of cycles to run
default is 2
:type cycles: int
"... | d2782d283739dcc65e6a5cf23f69e31d45ab6662 | 3,629,814 |
from pathlib import Path
def filter_files(names: list[Path]) -> list[Path]:
"""只要文件,不要文件夹"""
return [x for x in names if x.is_file()] | 25c1258891e2df7c35f700a26cadf01013329337 | 3,629,815 |
from datetime import datetime
def get_user_input():
"""Returns validated user input for inclusion into a database."""
print('--- New appointment entry ---')
while True:
title = input("Appointment's title? ")
if len(title) == 0:
print('Title can not be empty')
else:
... | f355dd2ab8332f6bcdfb21d4ee16dba47346e253 | 3,629,816 |
def send_data_frame(writer, filename, mime_type=None, **kwargs):
"""
Convert data frame into the format expected by the Download component.
:param writer: a data frame writer
:param filename: the name of the file
:param mime_type: mime type of the file (optional, passed to Blob in the javascript lay... | 77e725c9a2f8178bc573a987011327fdbb3bdc12 | 3,629,817 |
def find_path(node1, node2):
"""Finds the length of the path from node1 to node2
This is done by looking at the list of parents
and finding the first common parent.
"""
parents1 = get_parents(node1)
parents2 = get_parents(node2)
for l1 in range(len(parents1)):
if parents1[l1] in pa... | dd0469d6659e2f2cdc0a85e9d205b94ee656e68b | 3,629,818 |
def load_play_bcc():
"""
Play : 8 samples, 3 features, 2 classifications
"""
FEATURES = ['Temperature', 'Humidity', 'Pressure']
CLASSES = ['Rainy', 'Play']
data = pd.DataFrame(
[
#T,H,P R,P
[0, 0, 0, 1, 0],
[0, 0, 1, 0, 0],
[0, 1, 0, 1... | a543a273331609c4c74d53d0cdf4a63644a7d8db | 3,629,820 |
from typing import Dict
from typing import Any
def _pseudodata2dict(data: PseudopotentialData) -> Dict[str, Any]:
"""
Convert a PseudopotentialData to a compatible dict with:
* Decimals replaced by strings
* the required attrs set on the root
* the key "coefficients" replaced with "coeffs"
"""... | e9feacd5f4ab51b18be92c7ea17bb9372fc59154 | 3,629,821 |
import hashlib
def hashkey(key):
"""Returns the sha1 hash for key"""
# hash keys so we don't pay the sha1 overhead each time we call this one
if key not in HASH_CACHE:
HASH_CACHE[key] = hashlib.sha1(str.encode(key)).hexdigest()
return HASH_CACHE[key] | a301ac524299eea1bbbe684d0a6ad011ca298619 | 3,629,822 |
def get_geocoder(email):
"""Get geocode function for geocoding through Nominatim with supplied
email address as the user_agent, as per Nominatim's usage policy.
This geocoder will take at least 1 second per Address queried in
accordance with Nominatim's terms of service.
Note: this process cannot ... | 1a2ae6ecd0d3e2607bbdaa2f24ae6615e26ddd92 | 3,629,823 |
def move_ship_waypoint(instructions: list) -> list:
"""Move the ship using the waypoint movement rules
:param instructions: List of movement instructions
:return: Final position of the ship
"""
waypoint = [10, 1]
ship = [0, 0]
for instruction in instructions:
cmd, val = instruction
... | 7202392e4826d522287455d94f7b06c0e2f931ee | 3,629,824 |
def within_image_supervised_pixel_contrastive_loss(
features, labels, ignore_labels,
temperature):
"""Computes within-image supervised pixel contrastive loss.
Args:
features: A tensor of shape [batch_size, num_pixels, num_channels]
labels: A tensor of shape [batch_size, num_pixels, 1]
ignore_la... | 8e121d23c0c02b97dc1ad25d0093aff8519d7074 | 3,629,825 |
def _transform_indicators(metadata: dict) -> pd.DataFrame:
"""Transform indicators metadata into a formatted DataFrame."""
df = pd.DataFrame.from_dict(metadata.get("indicators"))
df = df[
["id", "code", "shortName", "name", "numerator", "denominator", "annualized"]
]
df.columns = [
"... | 882b66cf1dbe2e1e5f1189134efec357d5983c5c | 3,629,826 |
def symmetricMatrix(seq):
"""
creates a symmetric 3x3 matrix from
a sequence (list, tuple, Matrix)
with 6 elements
"""
assert isinstance(seq, (list, tuple, symbolics.Matrix))
M=symbolics.Matrix([[seq[0], seq[1], seq[3]],
[seq[1], seq[2], seq[4]],
... | 0b90a12fc0d95b412b142dcbe19dfa7e2910948a | 3,629,827 |
import ray
def get_actor(name: str) -> ray.actor.ActorHandle:
"""Get a named actor which was previously created.
If the actor doesn't exist, an exception will be raised.
Args:
name: The name of the named actor.
Returns:
The ActorHandle object corresponding to the name.
"""
l... | 6856200cf1ee61d3f0e069c048189f37dc0d06ff | 3,629,828 |
import itertools
def get_hyperparams_combinations(hyperparams):
"""Get list of hyperparmeter (dict) combinations."""
# transforms tuning hyperparams to a list of dict params for each option
return [
{k:v for k,v in zip(hyperparams.keys(), hypms)}
for hypms
in itertools.product(*[... | e5f52a8eddb8a2a476e0daa47f63161d440263f2 | 3,629,829 |
from typing import Tuple
def get_cropped_axes(image: np.ndarray, boundary_width: int = 5) -> Tuple[slice, ...]:
"""
Return the min and max values on both x and y axes where the image is not empty
Method: find the min and max of all non-zero pixels in the image, and add a border
:param image: the image... | 9650f114cc9637e09550956c92a29a28d0062147 | 3,629,831 |
def addressable_list(type_constraint):
"""Marks a list's values as satisfying a given type constraint.
Some (or all) elements of the list may be :class:`pants.engine.exp.objects.Resolvable` elements
to resolve later.
See :class:`AddressableDescriptor` for more details.
:param type_constraint: The type cons... | b0769cd11cb4c15e4f1b585141809a5b715a16bf | 3,629,832 |
def user():
"""Returns a user with name='mesh', token='token', trakt={'trakt': 'auth'}"""
return User('mesh', 'token', {'trakt': 'auth'}) | d73d4ae88af53c5b315dcad99510028c75052e6b | 3,629,833 |
from datetime import datetime
import json
import logging
def convert_from_poolfile_to_sequence_set_and_back(inp_fp_path,
op_path, conversion_type, description="", run_id=None):
"""
In this function we take either pool file or Sequence Set
and convert from one to the other. Sequence Set is out... | ad46eb491840aa75764b013495a113ae746144ba | 3,629,834 |
from typing import List
def read_basis_format(basis_format: str) -> List[int]:
"""Read the basis set using the specified format."""
s = basis_format.replace('[', '').split(']')[0]
fss = list(map(int, s.split(',')))
fss = fss[4:] # cp2k coefficient formats start in column 5
return fss | 9701309ab43eb7a0227aa141653688dbdce40811 | 3,629,835 |
def _central_crop(image_list, crop_height, crop_width):
"""Performs central crops of the given image list.
Args:
image_list: a list of image tensors of the same dimension but possibly
varying channel.
crop_height: the height of the image following the crop.
crop_width: the width of the image foll... | 16481f8db0be53b08fe3b4d4173ae3c9bd71ceb2 | 3,629,836 |
def concat_combining_function(a, b):
"""
Combines the tensor `a` and `b` by concatenating them.
:param a: the tensor a
:type a: tf.Tensor
:param b: the tensor b
:type b: tf.Tensor
:return: a combination of the tensors
:rtype: tf.Tensor
"""
if a.shape.rank == 2:
a = tf.ex... | 6c96fac311ef4085f282e8419ffa8d7b98ad38ed | 3,629,837 |
def filter_list_zones(auth_context, cloud_id, zones=None, perm='read',
cached=False):
"""Filter the zones of the specific cloud based on the RBAC policy"""
if zones is None:
zones = list_zones(auth_context.owner, cloud_id, cached=cached)
if auth_context.is_owner():
retu... | 11e1d099d1af9f46379f6c8f4f6b63d3d9bf4280 | 3,629,838 |
def pixel_weighted_categorical_crossentropy(weights,target, output, from_logits=False, axis=-1):
""" pixel weighted version of tf.keras.backend.categorical_crossentropy
copy of https://github.com/tensorflow/tensorflow/blob/v2.3.1/tensorflow/python/keras/backend.py#L4640-L4708
except for last line where wei... | f54117bd362ff0e3e01d77f16650f98bd832402a | 3,629,839 |
def auth_required(f):
""" Decorator for aiohttp web handlers with primitive auth check
"""
@wraps(f)
async def _wrapper(request):
if 'auth' not in request:
raise HTTPUnauthorized()
return await f(request)
return _wrapper | 03a71418314b1caf7f40d95c41a6386f8d4eb10e | 3,629,840 |
def p_to_stars(p, thres=(0.1, 0.05, 0.01)):
"""Return stars for significance values."""
stars = []
for t in thres:
if p < t:
stars.append("*")
return "".join(stars) | d88c2fd6c1b4e2d75a9cb664dfc10fab308bc6ee | 3,629,841 |
def permuteToBlocks(arr, blockshape):
"""Permute an array so that it consists of linearized blocks.
Example: A two-dimensional array of the form
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
would be turned into an array like this with (2, 2) blocks:
... | b5edc7c64ed3facf39354e7c38955cd5e218d3a3 | 3,629,842 |
from typing import Iterable
from typing import Dict
from typing import Tuple
def _polygonise_splits(
arr: np.ndarray, named_slices: Iterable[Dict[str, Tuple]]
) -> Dict[str, gpd.GeoDataFrame]:
"""
Create polygons from multiple sub-arrays of the given array.
Note:
Indices for `named_slices` mu... | 41eea39a96e1dbacb161c4e160ae73ed49762deb | 3,629,843 |
import warnings
def getPointInTheMiddle(start_point, end_point, time_diff, point_idx):
"""
Calculates a new point between two points depending of the
time difference between them and the point index.
Parameters
----------
start_point: DataFrame
end_point: DataFrame
time_diff: float
... | b5b76bbb1bc4b5cb37e5959b009106d1d50369a6 | 3,629,844 |
def get_style_dependencies(style_name=None, base_url=DEFAULT_BASE_URL):
"""Get the values of dependencies in a style.
Args:
style_name (str): Name of style; default is "default" style
base_url (str): Ignore unless you need to specify a custom domain,
port or version to connect to th... | 8d297294c7f5da5f4f2bbea80c659a57e2207aba | 3,629,845 |
import logging
def bpt_nii(maps, ax = None,
snr_min = None,
deredden = False,
return_figure = True,
plot_map = False,
plot_kde = False,
radial_bin = None,
return_data = None,
overplot_dk_bpt = False,
dk_bpt_k... | a45801c3672cae2750133dbf7011dd7dfad50b3d | 3,629,846 |
def correct_dcm(dcm):
""" Correct DCM image which were actually signed data, but were treated as unsigned """
x = dcm.pixel_array + 1000
px_mode = 4096
x[x>=px_mode] = x[x>=px_mode] - px_mode
dcm.PixelData = x.tobytes()
dcm.RescaleIntercept = -1000
return dcm.pixel_array, dcm.RescaleIntercep... | 0186ab3fc4b606902da3a50a5835eb227a1b7733 | 3,629,847 |
def multiaz_subnets(
name_prefix: str,
cidr_block: str,
region: str,
vpc: object = None,
vpc_id: str = None,
no_of_subnets: int = 4,
network_acl: object = None,
network_acl_id: str = None,
route_table: object = None,
route_table_id: str = None,
) -> list:
"""Split given CIDR ... | 58cd2d5eea2873683202907a1c91dc4dbefcb9d6 | 3,629,848 |
def EPdiv(a, da, b, db, covar=0):
"""
C = A / B
"""
return (
a / b,
np.sqrt(
((da / b) ** 2 + ((a ** 2) * (db ** 2) / (b ** 4)))
- (2 * covar * a / (b ** 3))
),
) | ec8fa19845e4c014c271badfba3d7ad6a503e096 | 3,629,849 |
def factorial_r(number):
"""
Calculates the factorial of a number, using a recursive process.
:param number: The number.
:return: n!
"""
# Check to make sure the argument is valid.
if number < 0:
raise ValueError
# This is the recursive part of the function.
if number == 0... | e5c28edac93b965f438bd61c5bb1c0a935c96700 | 3,629,850 |
def obstacles_to_grid(obstacles):
"""
Transforms a list of obstacles into an m x n grid where 1 represents the cell is covered by
an obstacle and 0 represents no obstacle. m and n are derived by the canvas height/width and
grid width. The assumption is that the obstacles fall precisely on grid lines.
... | 15034a36bda253d6b045926291c2996c5867b272 | 3,629,851 |
def get_gps_data(filename, traversal_id):
"""
Gets GPS time series gathered from a traversal
:param filename: <String> csv file from GPS team in format |date|time|name|latitude|longitude|heading
:return: <pandas DataFrame> time_stamp|latitude|longitude
"""
delimiter = r"\s+" # some of the column... | 2aeaa6b06025951c48cb9213dd9994d0e1dbb61d | 3,629,852 |
def infection_rate_symptomatic_30x60():
"""
Real Name: b'infection rate symptomatic 30x60'
Original Eqn: b'Susceptible 60*Infected symptomatic 30x60*contact infectivity symptomatic 30x60*(self quarantine policy SWITCH self 60\\\\ *self quarantine policy 60+(1-self quarantine policy SWITCH self 60))/non cont... | af8f774612cfd866b6931690ecff9c986f415769 | 3,629,853 |
def _translate_args(t=tuple(), d=dict(), unfreeze=False):
"""
_make_wrapper_argsでラッパー関数を作成する際の補助関数。
関数呼び出しを行うS式の引数部分に埋め込む文字列を作成する。
e.g.)
(func)なるS式を送り込む場合 ""を生成することを担当する。
(func args)なるS式を送り込む場合 " args"を生成することを担当する。(冒頭のスペースに留意)
文字列を埋め込む際変数は適切に評価を行ってから埋め込む。
Euslispにはハッシュのリテラル表現はな... | 25ca61d7a0682ad817a2b4d6a4103ad25ba47fbe | 3,629,855 |
def merge_date_time2(data, date_column, time_column=None):
"""This method merges columns date and time
.. note: If time is missing default is 00:00.
.. note: Also convert date using dt.apply(str).
import datetime
datetime.time.fromisoformat()
Parameters
----------
Returns
-------... | 3d4ecf8e67b7bfa3cb3b967332c1878f8a1d7293 | 3,629,856 |
def logistic(x):
"""
A function that returns a value between 0 and 1 for x in the
range [0, infinity] and -1 to 1 for x in the range [-infinity, infinity].
Useful for cost functions.
"""
return 2.0 / (1 + exp(-x)) - 1.0 | 39c45ebbcef74c11bbb4bd554757b0c738dfc99e | 3,629,857 |
def make_perturbed_cmtsolution(py, src_frechet_directory, cmtsolution_directory, output_directory):
"""
make the pertured cmtsolution based on src_frechet.
"""
script = f"ibrun -n 1 {py} -m seisflow.scripts.source_inversion.make_perturbed_cmtsolution --src_frechet_directory {src_frechet_directory} --cmt... | 07bb69751ddaee9d7aa6389c6cab9bc6021758ed | 3,629,858 |
def weight_correct_incorrect(rslt):
"""Return a pair of floating-point numbers denoting the weight of
(correct, incorrect) instances in EvaluationResult rslt.
>>> listInstCorrect = [Instance([],True,0.25)]
>>> listInstIncorrect = [Instance([],False,0.50)]
>>> rslt = EvaluationResult(listInstCorrect, listInstIncor... | 5a7ef1d338821f10b58ba06224059e532180c50d | 3,629,859 |
import pathlib
import csv
def get_data_info(path):
"""
Get metadata of the iamges.
"""
samples = []
# the data is in subfolders
parent = pathlib.Path(path)
for csv_file in parent.glob('**/*.csv'):
with open(str(csv_file), 'r') as f:
reader = csv.reader(f)
f... | 53f3dd1b6ff18d43a656f4a3f6da26ab1e60a6c2 | 3,629,860 |
import math
def BmatPRV(q):
"""
BmatPRV(Q)
B = BmatPRV(Q) returns the 3x3 matrix which relates the
body angular velocity vector w to the derivative of
principal rotation vector Q.
dQ/dt = [B(Q)] w
"""
p = np.linalg.norm(q)
c = 1 / p / p * (1 - p / 2 / math.tan(p / 2))
B... | f1977d5eb0c3913454dd692861c8f32e80fbb035 | 3,629,861 |
import random
def shuffle(x, y):
""" Shuffle the datasets. """
for n in range(len(x) - 1):
rnd = random.randint(0, (len(x) - 1))
x1 = x[rnd]
x2 = x[rnd - 1]
y1 = y[rnd]
y2 = y[rnd - 1]
x[rnd - 1] = x1
x[rnd] = x2
y[rnd - 1] = y1
y[rnd... | c9f198d3796c5d64eba818753701957ea1a0e924 | 3,629,862 |
from typing import FrozenSet
def induced_subgraph(G: Graph, S: FrozenSet[Ind]) -> Graph:
"""
Generate the subgraph of G induced by the set of nodes S.
See Also
--------
https://en.wikipedia.org/wiki/Induced_subgraph
Parameters
----------
G : Graph
S : Set of nodes
Returns
... | 488a97e278abb8961abaf4b889525123d5588ab8 | 3,629,863 |
def make_peptide_bond(mol, res = None, start = "N", end = "C", delete = "OXT"):
"""Performs one condesation rxn between a molecule and residue/itself
default creates peptide bond
Parameters
----------
mol : rdkmol
Main molecule on which reaction is performed
res : rdkmol
... | fcf167b259a016ebaf0b82d2cee219f1c24646ce | 3,629,865 |
def get_data_names(data, data_names):
"""
Get default names for data fields if none are given based on the data.
Examples
--------
>>> import numpy as np
>>> east, north, up = [np.arange(10)]*3
>>> get_data_names((east,), data_names=None)
('scalars',)
>>> get_data_names((east, nort... | e2097d6dbf2c8cc52fd4a60124727cad5fe9fbc4 | 3,629,866 |
import pandas
def get_labels_from_file(filename):
"""Get labels on the last column from file.
Args:
filename: file name
Returns:
List[str]: label list
"""
data_frame = pandas.read_csv(filename)
labels = data_frame['summary'].tolist()
return labels | 605e9a464eb9fc007d2421fadcab362b7c22ebf5 | 3,629,867 |
def css3_lists():
"""Return a list of all css3 color names, and a corresponding list of the colors' RGB values."""
css3_db = CSS3_HEX_TO_NAMES
names = []
rgb_values = []
for color_hex, color_name in css3_db.items():
names.append(color_name)
rgb_values.append(hex_to_rgb(color_hex))
... | f1656566f8099b2dd5cc9f5c5662d45e9e820f84 | 3,629,868 |
from typing import Union
def kmeans(
embedding: np.ndarray,
n_clusters: int = 1,
init: Union[str, np.ndarray] = 'k-means++',
n_init: int = 10,
max_iter: int = 300,
tolerance: float = 0.0001,
precompute_distances='auto',
verbose: int = 0,
random_s... | 4738a2b9b77c8812017b37cce0d80c0d028854c2 | 3,629,869 |
import six
from datetime import datetime
def get_json_struct(jsonobj, template=None):
"""
:param jsonobj: Object to parse and adjust so could be loaded into big query
:param template: An input object to use as abasis as a template defaullt no template provided
:return: A json object that is a templ... | f4c505fa6a593ab9fa1df5ab47f986f11f854d57 | 3,629,870 |
import logging
def pin_to_cpu(op):
"""Returns a CPU device for the given node."""
device = op.device if op.device is not None else ""
dev = pydev.from_string(device)
if not dev.device_type:
return set_cpu0(device)
if dev.device_type == "CPU":
return device
logging.info("Operation %s has been ass... | 0b9f248e53f2df5e26945bb0bfb5bac2544d1d45 | 3,629,871 |
def build_df(data):
"""
Creates and returns a pandas DataFrame from the given pandas Series with the original index as a column.
It also extracts and returns the original column and index name to restore the DataFrame to its original column
and index name.
:param data: pandas Series
:return: tu... | 0f34a6787a452b6d4e1cbcf2d99807c0e7d75141 | 3,629,872 |
def _map_spectrum_weight(map, spectrum=None):
"""Weight a map with a spectrum.
This requires map to have an "energy" axis.
The weights are normalised so that they sum to 1.
The mean and unit of the output image is the same as of the input cube.
At the moment this is used to get a weighted exposure... | c27b1c342e51ed47270648f8598b6f66c3538f23 | 3,629,873 |
def clean_date_metadata(df):
"""Clean the collection and submission date metadata
"""
df.loc[:, "collection_date"] = df["covv_collection_date"].astype(str).str.strip()
df.loc[:, "submission_date"] = df["covv_subm_date"].astype(str).str.strip()
# Filter out really unspecific collection dates
# ... | 6b407c57cc998dee31d2f169c9f45a91a125a1a8 | 3,629,874 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.