content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def find_features_with_dtypes(df, dtypes):
"""
Find feature names in df with specific dtypes
df: DataFrame
dtypes: data types (defined in numpy) to look for
e.g, categorical features usually have dtypes np.object, np.bool
and some of them have np.int (with a limited number of unique items)
"""
return np.asarray... | a94177dd24cb96915245959c0a22b254bd2a59df | 28,442 |
def DeConv2d(net, n_out_channel = 32, filter_size=(3, 3),
out_size = (30, 30), strides = (2, 2), padding = 'SAME', batch_size = None, act = None,
W_init = tf.truncated_normal_initializer(stddev=0.02), b_init = tf.constant_initializer(value=0.0),
W_init_args = {}, b_init_args = {}, name ='decnn2d... | c99d717bac217878bc569d7fad4462d5445ac709 | 28,443 |
from typing import List
import re
def parse_release(base: str, path: str) -> List[str]:
"""Extracts built images from the release.yaml at path
Args:
base: The built images will be expected to start with this string,
other images will be ignored
path: The path to the file (release.... | f4fec0908f2975a9ed9eef3e0a3a62549c9f757c | 28,444 |
def build_config(config_file=get_system_config_directory()):
"""
Construct the config object from necessary elements.
"""
config = Config(config_file, allow_no_value=True)
application_versions = find_applications_on_system()
# Add found versions to config if they don't exist. Versions found
... | 148e597f7fd9562f9830c8bd41126dd0efef96f1 | 28,445 |
import re
def preProcess(column):
"""
Do a little bit of data cleaning with the help of Unidecode and Regex.
Things like casing, extra spaces, quotes and new lines can be ignored.
"""
column = unidecode(column)
column = re.sub('\n', ' ', column)
column = re.sub('-', '', column)
column... | fda71aab1b2ce2baedbbc5d2195f115c9561e75d | 28,446 |
def size_to_pnts(size) -> np.ndarray:
"""
获得图片 size 的四个角点 (4,2)
"""
width = size[0]
height = size[1]
return np.array([[0, 0], [width, 0], [width, height], [0, height]]) | ca189cea9201646b0ce4cf2e32c2e21ad26929f3 | 28,447 |
def create_scenario_mms_datasets(variable_name,
scenario_name,
num_chunks,
data_path,
normalized=False):
"""Create the multi-model statistics dataset for a scenario.
Runs the func... | 0bef48bc009b2ee72abec511d9f6f886a8ed289c | 28,448 |
def carla_rotation_to_numpy_rotation_matrix(carla_rotation):
"""
Convert a carla rotation to a Cyber quaternion
Considers the conversion from left-handed system (unreal) to right-handed
system (Cyber).
Considers the conversion from degrees (carla) to radians (Cyber).
:param carla_rotation: the... | 38aed692b0ad7008fff71dc9b31ce03d552ae2f2 | 28,449 |
def _liquid_viscocity(_T, ranged=True):
"""Pa * s"""
OutOfRangeTest(_T, 59.15, 130, ranged)
A, B, C, D, E = -2.0077E+01, 2.8515E+02, 1.7840E+00, -6.2382E-22, 10.0
return exp(A + B / _T + C * log(_T) + D * _T**E) | 2fd29eea442862e4904d3164783694b151cab6c9 | 28,450 |
import re, fileinput
def readConfig(filename):
"""Parses a moosicd configuration file and returns the data within.
The "filename" argument specifies the name of the file from which to read
the configuration. This function returns a list of 2-tuples which associate
regular expression objects to the c... | 3b641686b8e6cfaebec668367a12e32bc59104a8 | 28,452 |
def negative_f1(y_true, y_pred) -:
"""Implements custom negative F1 loss score for use in multi-isotope classifiers.
Args:
y_true: a list of ground truth.
y_pred: a list of predictions to compare against the ground truth.
Returns:
Returns the custom loss score.
... | 255c3e34a17f4301a6c842c4109d930916cac3d5 | 28,453 |
import torch
def cal_gauss_log_lik(x, mu, log_var=0.0):
"""
:param x: batch of inputs (bn X fn)
:return: gaussian log likelihood, and the mean squared error
"""
MSE = torch.pow((mu - x), 2)
gauss_log_lik = -0.5*(log_var + np.log(2*np.pi) + (MSE/(1e-8 + torch.exp(log_var))))
MSE = torch.mea... | b2d4f660c4475a632c649844694ff3f67dc93fca | 28,454 |
def translate_fun_parseInt(x):
"""Converts parseInt(string, radix) to
__extrafunc_parseInt(string, radix=10)
Args:
x (str): JavaScript code to translate.
Returns:
str: Translated JavaScript code.
Examples:
>>> from ee_extra import translate_fun_parseInt
>>> transla... | 9bc63d3e4005fed12209de0169ad2641bcf09f65 | 28,455 |
def simple_intensity_based_segmentation(image, gaussian_sigma=1, thresh_method="Otsu", smallest_area_of_object=5,label_img_depth = "8bit"):
"""Perform intensity based thresholding and detect objects
Args:
raw_image_path : path to a raw image
gaussian_sigma : sigma to use f... | 2f270b38e7f5d07ceb4437d7b9b6d26174af56fc | 28,456 |
import torch
def mish(x):
"""mish activation function
Args:
x (Tensor): input tensor.
Returns:
(Tensor): output tensor and have same shape with x.
Examples:
>>> mish(to_tensor([-3.0, -1.0, 0.0, 2.0]))
tensor([-1.4228e-01, -2.6894e-01, 0.0000e+00, 1.7616e+00]
R... | 73447216f12a2e60e9ccc249eca9abe4baa94be8 | 28,457 |
def text_box_end_pos(pos, text_box, border=0):
"""
Calculates end pos for a text box for cv2 images.
:param pos: Position of text (same as for cv2 image)
:param text_box: Size of text (same as for cv2 image)
:param border: Outside padding of textbox
:return box_end_pos: End xy coordinates for t... | 5bd2b46fe3456ccdef1407b90256edeb310d92bc | 28,458 |
def ticket_competence_add_final(request, structure_slug, ticket_id,
new_structure_slug, structure, can_manage, ticket,
office_employee=None):
"""
Adds new ticket competence (second step)
:type structure_slug: String
:type ticket_id: String... | b3e159494d8f7ecf7603596face065f02e44e00e | 28,459 |
def _find_computecpp_root(repository_ctx):
"""Find ComputeCpp compiler"""
computecpp_path = ""
if _COMPUTECPP_TOOLKIT_PATH in repository_ctx.os.environ:
computecpp_path = repository_ctx.os.environ[_COMPUTECPP_TOOLKIT_PATH].strip()
if computecpp_path.startswith("/"):
_check_computecpp_version(repository_... | 91bc817036a976565434f1a3c52c5bb7e80ed86d | 28,460 |
def distance(v):
"""
Estimated distance to the body of the Mandelbuld
"""
z = v
for k in range(MAX_ITERS):
l = (z**2).sum()
if l > BAILOUT:
escape_time = k
break
z = pow3d(z, ORDER) + v
else:
return 0
return np.log(np.log(l)) / MU_NORM ... | 79a6075da3c022c48c111ffec015835716c12f9a | 28,461 |
def _depol_error_value_two_qubit(error_param,
gate_time=0,
qubit0_t1=inf,
qubit0_t2=inf,
qubit1_t1=inf,
qubit1_t2=inf):
"""Return 2-qubit depolarizing ... | ab779de7d0fac3f828f9fffbb0c13e588c3fc54b | 28,462 |
def get_google_order_sheet():
""" Return the google orders spreadsheet """
return get_google_sheet(ANDERSEN_LAB_ORDER_SHEET, 'orders') | 69ce8dcf03fd31701700eb0515ae7c3b47c9d127 | 28,463 |
def collision_check(direction):
"""
:param direction: Str : example up
:return:
"""
# really scuffed needs hard rework worked on this in night and its bad
# but it dose its job so i guess its ok for now
if mapGen.map[p.position][direction] is not None:
if mapGen.map[mapGen.map[p.pos... | 35b0bd0e6e2811b470bd513ea33c339ed7c7a96b | 28,464 |
def get_freq(freq):
"""
Return frequency code of given frequency str.
If input is not string, return input as it is.
Example
-------
>>> get_freq('A')
1000
>>> get_freq('3A')
1000
"""
if isinstance(freq, compat.string_types):
base, mult = get_freq_code(freq)
... | 16998470970449a9f94758c87c1d42e392c86dc9 | 28,465 |
def OMRSE(
directed = False, preprocess = "auto", load_nodes = True, load_node_types = True,
load_edge_weights = True, auto_enable_tradeoffs = True,
sort_tmp_dir = None, verbose = 2, cache = True, cache_path = None,
cache_sys_var = "GRAPH_CACHE_DIR", version = "2021-08-30", **kwargs
) -> Graph:
"""R... | 2de03cc7da02e58279ed5b576db4cbe14c98e0b5 | 28,466 |
def produce_new_shapedir(verts, n_betas=20):
"""Given a matrix of batch of vertices, run PCA through SVD in order to identify
a certain number of shape parameters to best describe the vert shape.
:param verts: (N x V x 3) array
:param n_betas: Number of betas to be fitted to, B
:return vtempl... | b12008b0c8b3809d211753dab6b89d3fcbb8bbce | 28,467 |
import logging
def get_calibration(
df: pd.DataFrame,
features:pd.DataFrame,
outlier_std: float = 3,
calib_n_neighbors: int = 100,
calib_mz_range: int = 20,
calib_rt_range: float = 0.5,
calib_mob_range: float = 0.3,
**kwargs) -> (np.ndarray, float):
"""Wrapper function to get calib... | af53baf47e1999f5ef421ddb1a12e2a41757f62e | 28,468 |
from typing import Mapping
from typing import Iterable
def _decode_bytestrings(o):
"""Decode all base64-encoded values (not keys) to bytestrings"""
if isinstance(o, Mapping):
return {key: _decode_bytestrings(value) for key, value in o.items()}
elif isinstance(o, Iterable) and not isinstance(o, (st... | 6a4fd49b50df91ee9705eda2192d10cb8f64606b | 28,470 |
def extinction(lambda1in,R,unit = 'microns'):
"""
Calculates A(lambda)/A_V. So, if we know E(B - V), we do
A(lambda) = A(lambda)/A_V * E(B - V) * R.
R is alternatively R_V, usually 3.1---this parameterizes the extinction law, which you should know if you are using this function.
This is the CCM... | d6b7a728de0b861786f6e28d3000f77d90248703 | 28,471 |
def to_rtp(F0, phi, h):
""" Converts from spherical to Cartesian coordinates (up-south-east)
"""
# spherical coordinates in "physics convention"
r = F0
phi = np.radians(phi)
theta = np.arccos(h)
x = F0*np.sin(theta)*np.cos(phi)
y = F0*np.sin(theta)*np.sin(phi)
z = F0*np.cos(theta)
... | dbf89e94d9e66925621969c53b476456a27af93d | 28,472 |
def to_base(num, base, numerals=NUMERALS):
"""Convert <num> to <base> using the symbols in <numerals>"""
int(num)
int(base)
if not (0 < base < len(numerals)):
raise ValueError("<base> must be in the range [1, %i>" % len(numerals))
if num == 0:
return '0'
if num < 0:
si... | aa25cb3f26e855d17c88be25b05251ebec216790 | 28,473 |
def identify_algorithm_hyperparameters(model_initializer): # FLAG: Play nice with Keras
"""Determine keyword-arguments accepted by `model_initializer`, along with their default values
Parameters
----------
model_initializer: functools.partial, or class, or class instance
The algorithm class be... | 5ed499e8b5cf832a75009adf3bb29c7f65d97d35 | 28,474 |
from typing import List
from typing import Tuple
def cnf_rep_to_text(cnf_rep: List[List[Tuple[str, bool]]]) -> str:
"""
Converts a CNF representation to a text.
:param cnf_rep: The CNF representation to convert.
:return: The text representation of the CNF.
"""
lines = []
for sentence in ... | dec3754493cfb0bd9fb5e68d2bab92a40bd0f294 | 28,475 |
def reshape_for_linear(images):
"""Reshape the images for the linear model
Our linear model requires that the images be reshaped as a 1D tensor
"""
n_images, n_rgb, img_height, img_width = images.shape
return images.reshape(n_images, n_rgb * img_height * img_width) | dffc5e7d0f96c4494443a7480be081b8fe6b4abd | 28,476 |
def otp(data, password, encodeFlag=True):
""" do one time pad encoding on a sequence of chars """
pwLen = len(password)
if pwLen < 1:
return data
out = []
for index, char in enumerate(data):
pwPart = ord(password[index % pwLen])
newChar = char + pwPart if encodeFlag else char - pwPart
newChar = newChar + 2... | 34223c69149b09b1cc3bde8bf1c432f21415362b | 28,477 |
from datetime import datetime
def export_actions(path='/tmp', http_response=False):
"""
A script for exporting Enforcement Actions content
to a CSV that can be opened easily in Excel.
Run from within consumerfinance.gov with:
`python cfgov/manage.py runscript export_enforcement_actions`
By d... | f85f095b6c7c3bd5a1a5277125c56e17e9d8cbd9 | 28,478 |
def reduce_load_R():
"""
Used for reconstructing a copy of the R interpreter from a pickle.
EXAMPLES::
sage: from sage.interfaces.r import reduce_load_R
sage: reduce_load_R()
R Interpreter
"""
return r | 858723306137a0e751f25766cbea5609867255f5 | 28,479 |
import urllib
def path_to_playlist_uri(relpath):
"""Convert path relative to playlists_dir to M3U URI."""
if isinstance(relpath, compat.text_type):
relpath = relpath.encode('utf-8')
return b'm3u:%s' % urllib.quote(relpath) | a69c441411b09ccce387ff76d93d17013b960de4 | 28,480 |
from json import load
import logging
def read_drive_properties(path_name):
"""
Reads drive properties from json formatted file.
Takes (str) path_name as argument.
Returns (dict) with (bool) status, (str) msg, (dict) conf
"""
try:
with open(path_name) as json_file:
conf = lo... | 18b9051801b032f5aa5532da0cfcca8793be8c91 | 28,481 |
import math
def proj(
point: np.ndarray, tol: float = 1e-9, bounds: tuple[float, float] = (0, 1)
) -> tuple[np.ndarray, float]:
"""Find projection on true ROC.
Args:
point: A point in [0, 1]^2.
tol: Tolerance.
bounds: Bounds of projection to help with the calculation.
Returns... | c56c1d9beb54f45691d63900e7458ed1ec4218ee | 28,482 |
def _split_on_wildcard(string):
"""Split the string into two such that first part does not have any wildcard.
Args:
string (str): The string to be split.
Returns:
A 2-tuple where first part doesn't have any wildcard, and second part does
have a wildcard. If wildcard is not found, the second part is ... | 09625186d22d50b737c94d2b22156a48bbf9b5ad | 28,483 |
def esgUSPTOPatentGrantsDF(symbol="", **kwargs):
"""Patent grants are indications that a company has successfully signaled that it values its IP, that its IP is unique in the eyes of the USPTO, and that its initial patent application was a reasonable one.
Patent grants data is issued weekly on Tuesdays.
Cur... | 22524f06572dca4fd2118a407273b7d23e68453c | 28,484 |
from typing import Optional
from typing import Dict
def get_web_optimized_params(
src_dst,
zoom_level_strategy: str = "auto",
aligned_levels: Optional[int] = None,
tms: morecantile.TileMatrixSet = morecantile.tms.get("WebMercatorQuad"),
) -> Dict:
"""Return VRT parameters for a WebOptimized COG.""... | 2e108f4619f5bf672981e60114065196f15116d0 | 28,487 |
from sage.misc.superseded import deprecation
def AlternatingSignMatrices_n(n):
"""
For old pickles of ``AlternatingSignMatrices_n``.
EXAMPLES::
sage: sage.combinat.alternating_sign_matrix.AlternatingSignMatrices_n(3)
doctest:...: DeprecationWarning: this class is deprecated. Use sage.com... | 3fad083e18ded990b62f2453ba75966fac6df6ed | 28,488 |
def _get_band(feature, name, size):
"""
Gets a band normalized and correctly scaled from the raw data.
Args:
feature (obj): the feature as it was read from the files.
name (str): the name of the band.
size (int): the size of the band.
Returns:
tf.Tensor: the band parsed... | db13abf7dc1cfa1cff88da864c2aaac043f574b2 | 28,489 |
import functools
def rgetattr(obj, attr, default=sentinel):
"""
from https://stackoverflow.com/questions/31174295/getattr-and-setattr-on-nested-objects
"""
if default is sentinel:
_getattr = getattr
else:
def _getattr(obj, name):
return getattr(obj, name, default)
r... | 6b6b7d98e117647a5609e10a499795ad293f1c6d | 28,490 |
def unpack_dims(data, vlabels):
"""
Unpacks an interleaved 4th dimension in an imaging data array
Parameters
----------
data : np array
a numpy array of data. Should have 3 spatial dimensions followed by
one nonspatial dimension of interleaved data
vlabels : pandas DataFrame
... | 1eaf0b00d4dd8be26927845aefa334b84e9264df | 28,491 |
def bash_this(s):
"""produce a shell fragment that runs the string str inside a fresh bash.
This works around potential strange options that are set in the topmost
bash like POSIX-compatibility mode, -e or similar."""
return 'bash -c %s' % shell_quote(s) | e06d287ebdf226ab6f83004c65cea7ada94232e1 | 28,492 |
def multiply_tensors(tensor1, tensor2):
"""Multiplies two tensors in a matrix-like multiplication based on the
last dimension of the first tensor and first dimension of the second
tensor.
Inputs:
tensor1: A tensor of shape [a, b, c, .., x]
tensor2: A tensor of shape [x,... | 374547e03fe95b02a77ef1420e7cac2f07248fb3 | 28,494 |
def get_cumulative_collection():
"""获取设备累积数据表
"""
client = MongoClient(connection_string)
db = client.get_database(database)
collection = db.get_collection('equipment_cumulative')
return collection | 0de651fe424730b2e486298e8e142190514748bb | 28,495 |
import re
def self_closing(xml_str, isSelfClosing):
"""
是否自闭合空标签,
:param isSelfClosing:
:param xml_str:
:return:
"""
if(isSelfClosing=="true"):
xml_str = re.sub(r"<(.*)>(</.*>)", r"<\1/>" , xml_str)
return xml_str
else:
return xml_str | b8b68626549da9a27335c5340db3ba65b753af90 | 28,496 |
def init_weights_he(nin, nout, nd, ny):
""" Sample the weights using variance Var(W) = 2/nin according to He initilization
for ReLU nonlinearities from a normal distribution with zero mean.
"""
sigma = np.sqrt(2/(nin))
weights = np.random.normal(0, sigma,((nd, ny))) # Weight vector (nd x ny)
return weights | fdb9fcef6888ea8513b22e84207f67cd71d90a9e | 28,498 |
def get_all_message_template():
"""returns all drivers or none"""
try:
return MessageTemplates.objects.all(), "success"
except Exception as e:
return None, str(e) | 1e63e73776b5b15d1cd7512fec32cea14454d717 | 28,499 |
def request_pet_name():
"""Requests users pet name as input.
Args:
NONE
Returns:
User's name.
Raises:
ValueError: If input is not a character.
"""
while True:
try:
if (pet_name := input("Enter your pet's name: \n")).isalpha():
break
... | efef2cfb0792b89f158f5a0bb42d10cf9bd1655d | 28,500 |
def butter_bandpass_filter(voltage, lowcut, highcut, fs, order=5):
"""Filter data with a bandpass, butterworth filter
Args:
voltage: array of voltage data from an ECG signal
lowcut: low frequency cutoff
highcut: high frequency cutoff
fs: sampling frequency
... | 31892cc5c98289f2e8af3a610b9f4ad1f1cbb58b | 28,501 |
def _get_variable_names(expression):
"""Return the list of variable names in the Numexpr `expression`."""
names = []
stack = [expression]
while stack:
node = stack.pop()
if node.astType == 'variable':
names.append(node.value)
elif hasattr(node, 'children'):
... | db75b0066b89bc7a6a022a56b28981910836524c | 28,502 |
def add(data_path, _):
"""add templates based on arguments and configurations."""
ask_option = AskOption(data_path)
library_chosen = LibraryChosen()
confirmation = Confirmation()
add_library = AddLibrary()
type_library_name = TypeLibraryName()
possible_states = [
ask_option, librar... | 09472c91394e41d345d5ac648c7b90a0e80cfcf3 | 28,504 |
from scipy.special import gamma
def GGD(x,d=2,p=1):
"""Two parameter generalized gamma distribution (GGD)
Parameters
----------
x : array_like (positive)
d : float (positive)
p : float (positive)
Returns
-------
pdf : array_like
Notes
-----
.. math::
G(x;d,p... | c18914f118870ff535d039f136e08a21e386ba43 | 28,505 |
def update_imported_docs(version_pk):
"""
Check out or update the given project's repository.
"""
version_data = api.version(version_pk).get()
version = make_api_version(version_data)
project = version.project
# Make Dirs
if not os.path.exists(project.doc_path):
os.makedirs(proj... | c9bcbf369cbe329c6e82c3634b537a2d31df995a | 28,506 |
def t(string):
"""
add \t
"""
return (string.count(".")) * "\t" + string | a394ac3983369836666d0610c345c6ef3c095994 | 28,507 |
def get_boundary_levels(eris):
"""Get boundary levels for eris."""
return [func(eris.keys()) for func in (min, max)] | 20d98447e600fecc3b9495e9fb5e5d09ff3b3c1e | 28,508 |
import json
def team_changepass():
"""The ``/team/changepass`` endpoint requires authentication and expects
the ``team_id`` and ``password`` as arguments. The team's password
will be set to ``password``
Note that this endpoint requires a POST request.
It can be reached at ``/team/changepass?secr... | 47f9921e9e457828a44e27f2b055ab47df52142e | 28,510 |
def load_options(parser=None, argv=[], positional_args=True):
""" parses sys.argv, possibly exiting if there are mistakes
If you set parser to a ConfigParser object, then you have control
over the usage string and you can prepopulate it with options you
intend to use. But don't set a ``--config`` / ``... | d0114ba8473b7a0b9283d65ec9fe97a19f54019f | 28,511 |
def read_spans(fname, separator = ';'):
"""
Read in a span file, of the form
Polynomial;NumberOfComplexPlaces;Root;SpanDimension;VolumeSpan;ManifoldSpan;FitRatio
Returns a dictionary object (certainly NOT a Dataset) such that they
keys are polynomials, and the values are dictionaries. These
dic... | 3bec0157f5905dd1c3ffa80cc0d1999f50ecc48c | 28,512 |
from typing import Dict
def merge_hooks(hooks1: Dict[str, list], hooks2: Dict[str, list]) -> Dict[str, list]:
"""
Overview:
merge two hooks, which has the same keys, each value is sorted by hook priority with stable method
Arguments:
- hooks1 (:obj:`dict`): hooks1 to be merged
- ho... | add5ae72917ca9aff109e8ac86a4d6902c14b298 | 28,514 |
def get_max_assocs_in_sample_csr(assoc_mat):
"""
Returns the maximum number of co-associations a sample has and the index of
that sample.
"""
first_col = assoc_mat.indptr
n_cols = first_col[1:] - first_col[:-1]
max_row_size = n_cols.max()
max_row_idx = n_cols.argmax()
return max_ro... | a341153afa0398cb2a43b97614cd39129e6b2ac5 | 28,516 |
def command_mood(self, args):
"""
/mood [<mood> [text]]
"""
if not args:
return self.xmpp.plugin['xep_0107'].stop()
mood = args[0]
if mood not in pep.MOODS:
return self.information('%s is not a correct value for a mood.'
% mood,
... | 43d383711f56e70440dd61ff5485f649ad96626b | 28,517 |
def putativePrimer(seq,lastShared):
"""
Generate a mock primer based on desired TM or length
and end position. This is used to estimate whether an
exact match restriction site found in the shared region
of two sequences is likely to be captured by a primer
(rendering it necessary to modify the site or throw o... | 0efa964ba834735bb71f3c8e2d565762ec7cfb8d | 28,518 |
import random
def get_config(runner,
raw_uri: str,
root_uri: str,
target: str = BUILDINGS,
nochip: bool = True,
test: bool = False) -> SemanticSegmentationConfig:
"""Generate the pipeline config for this task. This function will be called
... | d30651205d500850a32f0be6364653d4d7f638fa | 28,520 |
def readfmt(s, fmt=DEFAULT_INPUTFMT):
"""Reads a given string into an array of floats using the given format"""
ret = map(float, s.strip().split())
return ret | 30024e27450ab6f350d7829894865f68e13d95f2 | 28,521 |
def is_image_sharable(context, image, **kwargs):
"""Return True if the image can be shared to others in this context."""
# Is admin == image sharable
if context.is_admin:
return True
# Only allow sharing if we have an owner
if context.owner is None:
return False
# If we own the... | 778ca70c4b12c0f20586ce25a35551e1356d20c8 | 28,522 |
def ksz_radial_function(z,ombh2, Yp, gasfrac = 0.9,xe=1, tau=0, params=None):
"""
K(z) = - T_CMB sigma_T n_e0 x_e(z) exp(-tau(z)) (1+z)^2
Eq 4 of 1810.13423
"""
if params is None: params = default_params
T_CMB_muk = params['T_CMB'] # muK
thompson_SI = constants['thompson_SI']
meterToMega... | 64551363c6b3c99028ebfd3f7cee69c0c273a2e2 | 28,524 |
def find_commits(repo, ref='HEAD', grep=None):
"""
Find git commits.
:returns: List of matching commits' SHA1.
:param ref: Git reference passed to ``git log``
:type ref: str
:param grep: Passed to ``git log --grep``
:type grep: str or None
"""
opts = []
if grep:
opts +... | 8adb5e0dfebfc5ef86f0a17b2b4a7596ab91a382 | 28,525 |
def findMatches(arg_by_ref, checkForName=False):
"""Finds POIs with the same geometry in 2 datasets.
For each POI in the first dataset, check whether there is a corresponding POI in the 2nd one.
If it exists, move the POI from the second dataset to a resulting dataset B. In any case, the
POIs from the first dataset... | 68f32bc29b970bb86663060c46490698a0e1b3b9 | 28,528 |
def _decicelsius_to_kelvins(temperatures_decicelsius):
"""Converts from temperatures from decidegrees Celsius to Kelvins.
:param temperatures_decicelsius: numpy array of temperatures in decidegrees
Celsius.
:return: temperatures_kelvins: numpy array of temperatures in Kelvins, with
same sha... | 880d42637970c680cd241b5418890468443c6a5b | 28,529 |
def emails_to_warn():
""" who should get warning about errors messages in the chestfreezer? """
emails_for_escalation = _get_array_option_with_default('emails_to_warn', DEFAULT_EMAILS_TO_WARN)
return emails_for_escalation | f7135f2b55e813391ee86fae65e8f6cc10ccd31e | 28,530 |
import types
from typing import Sequence
from typing import Tuple
def get_public_symbols(
root_module: types.ModuleType) -> Sequence[Tuple[str, types.FunctionType]]:
"""Returns `(symbol_name, symbol)` for all symbols of `root_module`."""
fns = []
for name in getattr(root_module, '__all__'):
o = getattr(... | 96be2bf9d2548f1c7b5b8b12b926996105b084ca | 28,532 |
def NewStandardEnv(packager, provider):
"""NewStandardEnv(object packager, object provider) object
NewStandardEnv returns a new *Env with the given params plus standard declarations.
"""
return Env(handle=_checker.checker_NewStandardEnv(packager.handle, provider.handle)) | ff8842553a2dc1676c0b4abe4b8f1f5bee41b753 | 28,533 |
def get_ecs_secret_access_key(config_fpath, bucket_name):
"""Return the ECS secret access key.
:param config_fpath: path to the dtool config file
:param bucket_name: name of the bucket in a ECS namespace
:returns: the ECS secret access key or an empty string
"""
key = ECS_SECRET_ACCESS_KEY_KEY_... | 3583d5d45a9d8f70f839c33ab7007b85977483e4 | 28,534 |
def solve_naked_quads(sudoku, verbose):
"""Exclude the candidates of seen quad-value cell quads from unsolved cells
in their unit."""
return solve_naked_n_tuples(sudoku, 4, verbose) | 0a8a67928e7c3cb65fa5868cc30b60c08823ce6a | 28,535 |
def prototypical_spectra_plot(
dataset,
results_df,
plot_type="imshow",
fig=None,
fig_kws={},
plot_kws={},
cbar_kws={},
**kwargs
):
"""Plot the prototypical spectra from the calibration samples.
Args:
dataset (pyeem.datasets.Dataset): [description]
results_df (pa... | 96bd2d6b283b01257b35c4ec436ecc9e3457db7b | 28,536 |
def generate_gate_piover8(
c_sys: CompositeSystem, is_physicality_required: bool = True
) -> "Gate":
"""Return the Gate class for the pi/8 (T) gate on the composite system.
Parameters
----------
c_sys: CompositeSystem
is_physicality_required: bool = True
whether the generated object is... | 5c3cd7721a3bf7de2eb96521f2b9c04e82845dee | 28,538 |
def get_ftext_trials_fast(review_id):
"""
retrieve all ftext trials related to a review
@param review_id: pmid of review
@return: all registered trials and their linked publications
"""
conn = dblib.create_con(VERBOSE=True)
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cur... | e4fd91e93a5b32b083ddf9d0dccd282dee339601 | 28,539 |
from typing import List
from typing import Tuple
def find_edges(names: List[str]) -> List[Tuple[str, str]]:
"""
Given a set of short lineages, return a list of pairs of parent-child
relationships among lineages.
"""
longnames = [decompress(name) for name in names]
edges = []
for x in longn... | 9fd254de99a1be4647c476cfcd997b580cb44605 | 28,540 |
def get_plot_spec_binstat_abs(energy, bins = 50, range = (0, 5)):
"""
Create `PlotSpec` for plot of some stat of abs energy resolution vs TrueE.
"""
# pylint: disable=redefined-builtin
return PlotSpec(
title = None,
label_x = 'True %s Energy [GeV]' % (energy),
label_y = '(R... | 4b6b1d5e32234ac3d5c3b9acece4b4fcae795fee | 28,542 |
def generate_token(data):
"""Generate a token for given data object"""
serializer = URLSafeTimedSerializer(current_app.config['SECRET_KEY'])
return serializer.dumps(data, salt=current_app.config['SECURITY_PASSWORD_SALT']) | 0df4e85179da9b4d5bf56a868b652f490df4887a | 28,543 |
import time
def monitor_gcp(vm_name: str, job_arguments: dict):
"""Monitor status of job based on vm_name. Requires stable connection."""
# Check VM status from command line
while True:
try:
check_cmd = (
[
"gcloud",
"alpha",
... | ba78353b84267a48e0dbd9c4ae7b8da280ddf471 | 28,544 |
def five_top_workers(month, year):
"""
Top 5 presence users with information about them.
"""
dict_months = []
monthly_grouped = group_by_month(get_data(), year)
for user in monthly_grouped:
try:
dict_months.append((user.items()[0][0], user.items()[0][1][month]))
excep... | 75a63d49e11f528b90a90509b87ab22d58a87c72 | 28,546 |
import collections
import re
def get_assignment_map_from_checkpoint(tvars, init_checkpoint, prefix=""):
"""Compute the union of the current variables and checkpoint variables."""
name_to_variable = collections.OrderedDict()
for var in tvars:
name = var.name
m = re.match("^(.*):\\d+$", name)
if m is not None:... | 5469356a8b70da9268f42c08588bed0c765446c8 | 28,547 |
def u_rce_hh80(lats, thermal_ro, rot_rate=ROT_RATE_EARTH, radius=RAD_EARTH):
"""Zonal wind in gradient balance with equilibrium temperatures."""
return rot_rate*radius*cosdeg(lats)*((1 + 2*thermal_ro)**0.5 - 1) | 2fe0aba3f66a6429cbeb6674a46769d4474e31a4 | 28,548 |
def CreatePiecewiseFunction(**params):
"""Create and return a piecewise function. Optionally, parameters can be
given to assign to the piecewise function.
"""
pfunc = servermanager.piecewise_functions.PiecewiseFunction()
controller = servermanager.ParaViewPipelineController()
controller.Initial... | 6d0e55676a7abf98e967a354e321524b82f2c674 | 28,549 |
import json
def cancelCardTransactionPayload(cancel_time):
"""
Function for constructing payload for cancelCardTransaction API call.
Note: All parameters are of type String unless otherwise stated below.
:param cancel_time: Date and time of the request. Format - YYYY-MM-DD HH:mm:ss
:return: JSON ... | e96ee75bbc4c20a094283fa664bca6ddd6b9556c | 28,550 |
import re
def remove_elongation(word):
"""
:param word: the input word to remove elongation
:return: delongated word
"""
regex_tatweel = r'(\w)\1{2,}'
# loop over the number of times the regex matched the word
for index_ in range(len(re.findall(regex_tatweel, word))):
if re.search(regex_tatweel, wo... | a0b4be8640193568075f053009e5761894f302c1 | 28,551 |
def coevolve_alignment(method,alignment,**kwargs):
""" Apply coevolution method to alignment (for intramolecular coevolution)
method: f(alignment,**kwargs) -> 2D array of coevolution scores
alignment: alignment object for which coevolve scores should be
calculated
**kwargs: para... | 056813427f21b806742fd2bf613dcd2b769e709f | 28,552 |
from textwrap import dedent, wrap
def compute_known_facts(known_facts, known_facts_keys):
"""Compute the various forms of knowledge compilation used by the
assumptions system.
This function is typically applied to the results of the ``get_known_facts``
and ``get_known_facts_keys`` functions defined a... | 39744ee1bd56ad0bc2fc6412a06da772f45d1a2b | 28,553 |
def mro(*bases):
"""Calculate the Method Resolution Order of bases using the C3 algorithm.
Suppose you intended creating a class K with the given base classes. This
function returns the MRO which K would have, *excluding* K itself (since
it doesn't yet exist), as if you had actually created the class.
... | bbc3fde351c92c4ae0a5c82a3e06e95de29e2e8d | 28,554 |
def CalculatepHfromTA(param, TA, val, TP, TSi):
""" SUB CalculatepHfromTATC, version 04.01, 10-13-96, written by Ernie Lewis.
Inputs: TA, TC, TP, TSi
Output: pH
This calculates pH from TA and TC using K1 and K2 by Newton's method.
It tries to solve for the pH at which Residual = 0.
The starting ... | b160decae54b25677b1158f77bbc9818abcfd0df | 28,556 |
from operator import inv
def transform_image(image, shiftx, shifty, angle, order=1):
"""
Apply shift and rotation to the image.
The translation is applied first, then the rotation. If no rotation is
requested (``angle=0``), then ``scipy.ndimage.shift()`` is called to
perform a translation. Otherw... | 203f06c42b68de0db834924fd302193c37629669 | 28,557 |
import json
import time
from typing import Callable
import dill
def instate():
"""
Same as calculate() but the results are not saved to the database
Use this to update the state of the server to further analyse the model
:return: id of the simulation and result of the calculation
"""
# get th... | e50549ff8ae5e9e49cd972799ce0abffed213912 | 28,558 |
import pickle
def pickler(obj=None, filename: str= None, mode: str = 'pickle'):
"""
pickles the file to filename, or
unpickles and returns the file
(to save the result of long running calculations)
Parameters
----------
obj :
the object to pickle
filename : str
file to pickle to
mode:
... | b57e85a15099b5eed4e6c3d425bc4df7ff73d657 | 28,559 |
def csrgeam(m, n, descrA, csrValA, csrRowPtrA, csrColIndA, descrB, csrValB,
csrRowPtrB, csrColIndB, handle=None, alpha=1.0, beta=0.0,
nnzA=None, nnzB=None, check_inputs=True):
""" add two sparse matrices: C = alpha*A + beta*B.
higher level wrapper to cusparse<t>csrgemm routines.
""... | c51338336fda4a6e49529cee1f2137a826eb0b4d | 28,560 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.