content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def create_notification():
"""Allows creation of a new alert
Takes a JSON payload like:
{
"feed_urls": [
"http://feed.com/feed.xml"
],
"subject": "This is an email subject",
"body" : "<p>Some HTML here</p>"
}
"""
# TODO: Should be able to take HTML o... | 5,304,900 |
def ExtractModuleIdIfValidBreakpad(file_path):
"""Extracts breakpad file's module id if the file is valid.
A breakpad file is valid for extracting its module id if it
has a valid MODULE record, formatted like so:
MODULE operatingsystem architecture id name
For example:
MODULE mac x86_64 1240DF90E9AC39038E... | 5,304,901 |
def _timestamp_to_iso_str(timestamp):
"""
Converts the timestamp value into a iso str
Args:
timestamp(float): the timestamp to convert
Returns:
str: converted timestamp
"""
return datetime.fromtimestamp(timestamp).replace(tzinfo=pytz.utc).isoformat() | 5,304,902 |
def load_classifier(clf_name):
"""
Load classifier.
...
Parameters
----------
clf_name : str
Name of classifier to load.
Returns
-------
clf : scikit-learn classifier
Classifier.
"""
clf_path = pkg_resources.resource_filename(
"pybeach", "classifier... | 5,304,903 |
def login():
"""
Try to log a new user in. If a correct username and password have been
provided we return a jwt to the user that can be used to login into any
part of meerkat. Parameters are passed in the POST request data.
Args:
username (str): The users username
password (str): T... | 5,304,904 |
def TournamentSelectDBOne(size, prob_selection,db_list):
"""
Function: SelectDBOne
======================
Select one individual from a database using Tournament selection
@param size: number of individual choosen at random from the population
@param prob_selection: prob of selecting th... | 5,304,905 |
def read(hash, args={}):
"""
Read allowance by hash
"""
return resource.read(**{**{
'type': 'allowance',
'key': hash,
}, **args}) | 5,304,906 |
def test_empty_graph_is_empty(basic_setup):
"""Make sure basic graph instantiates with null values."""
assert basic_setup.node_list == []
assert basic_setup.edges == {} | 5,304,907 |
def predict(request: PredictRequest):
"""
Predict allergens from request
:param request: incoming api request
:return:
"""
check_model_exists(request)
response = modelResolver.predict(model_name=request.model,
data=preprocessor.process(request.data),
... | 5,304,908 |
def validate(data, labels, toStandardise=False,
overSamplingPercentages = None, toShuffle=False,
saveFile = False, randomState=None, samplingMethodology=smoteTransform, kfolds=10):
"""Generates data-points (fp and tp) for generating a ROC curve through oversampling and undersampling of d... | 5,304,909 |
def max_fill(grid, capacity):
"""
Given a rectangular grid representing wells, every column is a one well,
and 1 means "water exists", 0 means no water,
and you have a bucket, and know its capacity,
your task is to use the bucket to empty the wells,
the output will be the number of times that yo... | 5,304,910 |
def assertDimensions(self, x, y, w, h, win=None):
"""Asserts dimensions of window"""
if win is None:
win = self.c.window
info = win.info()
assert info['x'] == x, info
assert info['y'] == y, info
assert info['width'] == w, info # why?
assert info['height'] == h, info | 5,304,911 |
def is_select(a):
"""Return `True` if `a` is a Z3 array select application.
>>> a = Array('a', IntSort(), IntSort())
>>> is_select(a)
False
>>> i = Int('i')
>>> is_select(a[i])
True
"""
return is_app_of(a, Z3_OP_SELECT) | 5,304,912 |
def setup(bot: commands.Bot) -> None:
"""Github Issues Cog Load."""
bot.add_cog(Issues(bot))
log.info("Issues cog loaded") | 5,304,913 |
def log_vector(tag, values):
"""
log_histogram
Logs a vector of values.
"""
values = np.array(values).flatten()
# Fill fields of histogram proto
hist = HistogramProto()
hist.min = 0
hist.max = len(values) - 1
hist.num = len(values)
hist.sum = float(np.sum(np.arange(hist.num)... | 5,304,914 |
def create_mock_app():
""" Patch in a MagicMock() object for QApplication """
with mock.patch("app.APP") as m_app:
yield m_app | 5,304,915 |
def subtract_mean_vector(frame):
"""
Re-center the vectors in a DataFrame by subtracting the mean vector from
each row.
"""
return frame.sub(frame.mean(axis='rows'), axis='columns') | 5,304,916 |
def reduce_level(ast):
"""
The function removes from the abstract syntax tree a declaration current level (pointer or array). For instance it
makes from AST of 'int *a' it makes AST for 'int a'.
:param ast: Current abstract syntax tree.
:return: Abstract syntax tree for the pointer or an array elem... | 5,304,917 |
def to_location(maiden: str, center: bool = False) -> tuple[float, float]:
"""
convert Maidenhead grid to latitude, longitude
Parameters
----------
maiden : str
Maidenhead grid locator of length 2 to 8
center : bool
If true, return the center of provided maidenhead grid square... | 5,304,918 |
def threshold_amplitude(x, metric, samples, percentile, frange, Fs, filter_fn=None, filter_kwargs=None):
"""
Exclude from analysis the samples in which the amplitude falls below a defined percentile
Parameters
----------
x : numpy array
raw time series
metric : numpy array
s... | 5,304,919 |
def opcode_by_value(val: int) -> OpCode:
"""
Mapping: Retrieves the OpCode object with the given value.
Throws:
LookupError: if there is no opcode defined with the given value.
"""
if val not in BYTECODES:
raise LookupError("No opcode with value '0x{:02X}'.".format(val))
return BY... | 5,304,920 |
def random_mini_batches(X, Y, mini_batch_size = 64, seed = 0):
"""
Creates a list of random minibatches from (X, Y)
Arguments:
X -- input data, of shape (input size, number of examples) (m, Hi, Wi, Ci)
Y -- true "label" vector (containing 0 if cat, 1 if non-cat), of shape (1, number of examples... | 5,304,921 |
def flipDP(directionPointer: int) -> int:
"""
Cycles the directionpointer 0 -> 1, 1 -> 2, 2 -> 3, 3 -> 0
:param directionPointer: unflipped directionPointer
:return: new DirectionPointer
"""
if directionPointer != 3:
return directionPointer + 1
return 0 | 5,304,922 |
def test(procedure,delay):
"""delay: delay between two commands in seconds"""
from sys import stderr
OK = 0; attempts = 0
try:
while True:
attempts += 1
OK += procedure(delay)
if attempts % 20 == 0: stderr.write("%d/%d OK\n" % (OK,attempts))
except Keyboar... | 5,304,923 |
def projection_type_validator(x):
"""
Property: Projection.ProjectionType
"""
valid_types = ["KEYS_ONLY", "INCLUDE", "ALL"]
if x not in valid_types:
raise ValueError("ProjectionType must be one of: %s" % ", ".join(valid_types))
return x | 5,304,924 |
def extract_dataset(filepath, dataset_name=''):
"""
extracts the dataset of the dataset you are interested in
:param filepath: the .mat filepath
:param dataset_name: the name of the dataset you are interested in
:return: a n-dimensional array for the dataset.
"""
# print(dataset_name)
wi... | 5,304,925 |
def test_swagger_json_endpoint(app_client: testing.FlaskClient):
"""
Test /health endpoint
"""
response = app_client.get("/swagger.json")
assert response.status_code == 200 | 5,304,926 |
def applyMetadata(fmt="string",scn=1,v="string"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/applyMetadata.html
-----------------------------------------
applyMetadata is undoable, NOT queryable, and NOT editable.
Define the values of a particular set of metadata on selected ... | 5,304,927 |
def get_datatype(data):
"""
rules defining the sidtype, based on the data dict of the sid.
The keys are always given.
The values can be empty.
:param data:
:return:
"""
subtype = "project"
if "entity" in data.keys():
subtype = "entity"
if data.get("type"):
subt... | 5,304,928 |
def register_for_change_events(heosobj, command, data):
"""CLI 4.1.1"""
value = data.split('=')[1]
try:
attrname = '_' + command
setattr(heosobj, attrname, value)
except:
e = sys.exc_info()
raise HEOSException(message=e[1] + ": " + e[2]) | 5,304,929 |
def build(env_meta_path):
"""
Builds the package for `env_meta_path`.
Parameters
----------
env_meta_path : str
path pointing to a 'meta.yaml' file.
Returns
-------
success : the path to the build package
failure : None
"""
if not os.path.exists(env_meta_path):
... | 5,304,930 |
async def app():
"""
For start gunicorn in production
:return:
"""
return create_app() | 5,304,931 |
def AddAutoscalerArgs(parser):
"""Adds commandline arguments to parser."""
parser.add_argument('--scale-based-on-load-balancing',
action='store_true',
help=('Sets autoscaling based on load balancing '
'utilization.'),)
parser.add_argument('--... | 5,304,932 |
def test_driver_set_window_size(bin_path):
"""Assert something after driver.close()"""
expected_width = "800"
expected_height = "800"
with WrappedDriver(
executable_path=f"{bin_path}/chromedriver",
headless=True,
window_size=(expected_width, expected_height),
) as driver:
... | 5,304,933 |
def pre_process_data_frame(data_frame, convert_categorical_to_numeric=False):
"""Pre-process the passed data frame"""
# replace the missing values
data_frame = replace_missing_values(data_frame)
# normalize numeric columns
data_frame = normalize_numeric_columns(data_frame)
# convert categori... | 5,304,934 |
def datestr(then, now=None):
"""
Converts a (UTC) datetime object to a nice string representation.
>>> from datetime import datetime, timedelta
>>> d = datetime(1970, 5, 1)
>>> datestr(d, now=d)
'0 microseconds ago'
>>> for t, v in {
... timedelta(microseco... | 5,304,935 |
def main(input_file):
"""Solve puzzle and connect part 1 with part 2 if needed."""
inp = read_input(input_file)
transformations = get_all_transformations(inp)
p1 = part_1(inp, transformations)
print(f"Solution to part 1: {p1}")
p2 = part_2(transformations)
print(f"Solution to part 2: {p2}")
... | 5,304,936 |
def cluster(sequence, maxgap):
"""get batches of similar numbers"""
batch = []
for prev, val in pairify(sequence):
if val - prev >= maxgap:
yield batch
batch = []
else:
batch.append(val)
if batch:
yield batch | 5,304,937 |
def generate_code(
file: str = typer.Argument(
..., help="Input file which should contain subclass of PluginSpec"
),
output_file: Optional[str] = typer.Option(
None,
"-o",
"--output",
help="Output file to write generated Plugin classes to. If not specified, writes to ... | 5,304,938 |
def wshed_raw(labels, im):
"""
return wshed lines
"""
ia = lambda x: sitk.GetImageFromArray(x)
ai = lambda x: sitk.GetArrayFromImage(x)
feature_img = ia(im)
ws_img = sitk.MorphologicalWatershed(feature_img, level=0, markWatershedLine=True, fullyConnected=True)
ws = ai(ws_img)
ws = ws... | 5,304,939 |
def test_scrub_cache(cache, expected_cache):
"""Test scrub_cache()."""
logger = logging.getLogger()
logger.disabled = True
phpbb2slack.scrub_cache(logger, cache)
assert cache.items == expected_cache | 5,304,940 |
def chunk_list(lst: List[_T], n: int) -> Generator[List[_T], None, None]:
"""Yield successive n-sized chunks from lst."""
for i in range(0, len(lst), n):
yield lst[i : i + n] | 5,304,941 |
def process_link(link):
"""
Get text and link from an anchor
"""
return link.text_content(), link.get('href') | 5,304,942 |
def test_stats_box_with_subset(cubeviz_layout):
"""
Tests the stat box underneath the ImageViewer when there is an ROI
"""
cl_viewer = cubeviz_layout.split_views[1]._widget
# Create a subset (ROI) if there is none
cl_viewer.apply_roi(roi.CircularROI(xc=6, yc=10, radius=3))
assert cl_viewer... | 5,304,943 |
def update_stack(
profile: Optional[Union[str, bool]] = False,
region: Optional[Union[str, bool]] = False,
replace: bool = False,
local_path: Union[str, bool] = False,
root: bool = False,
wait: bool = False,
extra: bool = False,
bucket: str = None,
version: Union[str, bool] = False,
... | 5,304,944 |
def dot_product_attention(
query: jnp.ndarray,
key: jnp.ndarray,
value: jnp.ndarray,
*,
bias: Optional[jnp.ndarray] = None,
bias_kv: Optional[jnp.ndarray] = None,
broadcast_dropout: bool = True,
dropout_rate: float = 0.1,
dtype: jnp.dtype = jnp.float32,
precision: Optional[jax.la... | 5,304,945 |
def saveFig(dir, name, fig=1):
"""Save the fig in the images directory."""
path = dir + name + ".svg"
f = plt.figure(fig)
plt.savefig(path) | 5,304,946 |
def monitor_worker_shutdown(signum, frame):
"""Keeps main process alive until all worker processes shutdown"""
log.warning("Caught SIGTERM, monitoring worker process shutdown")
while len(WORKER_PROCESSES) > 0:
for p in WORKER_PROCESSES:
if p.is_alive():
log.info(f"waitin... | 5,304,947 |
def stringify_children(node):
"""Read and stringify the children of each nxml node."""
section_parts = []
for ch in node.getchildren():
string_text = ''
ch_tag = ch.tag
if ((ch_tag == 'title') or (ch_tag == 'p')):
sec_tree = ch.xpath("text()")
for txt in sec_tree:
txt = txt.rstrip()
if len(txt) >... | 5,304,948 |
def convolutional_block(X, f, filters, stage, block, s=2):
"""
Implementation of the convolutional block as defined in Figure 4
Arguments:
X -- input tensor of shape (m, n_H_prev, n_W_prev, n_C_prev)
f -- integer, specifying the shape of the middle CONV's window for \
the main path
filters ... | 5,304,949 |
def test_setter_error_unequal_rows():
"""Assert that an error is raised when the setter has unequal rows."""
atom = ATOMClassifier(X_bin, y_bin, random_state=1)
with pytest.raises(ValueError, match=r"number of rows"):
atom.X_train = X_bin | 5,304,950 |
def get_alarm_history_collection(alarm_historytype: Optional[str] = None,
alarm_id: Optional[str] = None,
timestamp_greater_than_or_equal_to: Optional[str] = None,
timestamp_less_than: Optional[str] = None,
... | 5,304,951 |
def σ(input, axis=1):
"""Softmax on an axis
Softmax on an axis
Arguments:
input {Tensor} -- input Tensor
Keyword Arguments:
axis {number} -- axis on which to take softmax on (default: {1})
Returns:
Tensor -- Softmax output Tensor
"""
input_size = input.size()
... | 5,304,952 |
def get_xps_list(xps_dict):
"""Convert XPs from internal format to API format"""
xps_list = []
for (filetype, xp) in xps_dict.items():
item = dict(language=get_language_name(filetype), xp=xp)
xps_list.append(item)
return xps_list | 5,304,953 |
def gesvdj(a, full_matrices=True, compute_uv=True, overwrite_a=False):
"""Singular value decomposition using cusolverDn<t>gesvdj().
Factorizes the matrix ``a`` into two unitary matrices ``u`` and ``v`` and
a singular values vector ``s`` such that ``a == u @ diag(s) @ v*``.
Args:
a (cupy.ndarra... | 5,304,954 |
def decide_collocational(accum):
"""
accum is the n-grams sized windows of list of tokens to be analysed.
N-grams size are given in function `decide`
Decide whether there is a collocational evidence against an intervening sentence boundary
"""
global CONTEXT_SIZE, collocations
center = CONT... | 5,304,955 |
def mgsort(nums: List[int]) -> None:
"""Sort an array in-place into ascending order via merge sort."""
def sort(nums, aux, lo, hi):
"""Sort nums[lo:hi] via merge sort."""
if lo+1 >= hi: return
mid = lo + hi >> 1
sort(aux, nums, lo, mid)
sort(aux, nums, mid, hi)
... | 5,304,956 |
def test_from_json(nested_example):
"""
can it be re-created from an actual json string?
"""
json_str = nested_example.to_json()
reconstructed = js.from_json(json_str)
assert reconstructed == nested_example | 5,304,957 |
def create_data_set(data_dir, csv_name, valid_size_frac):
"""
# Import image folder and csv file to create dataset.
:param data_dir: directory of data.
:param csv_name: Image file and the corresponding steering angle.
:param valid_size_frac: Ratio of dividing the data set into validation data.
... | 5,304,958 |
def update_shape(pos):
"""
recalculate the shape structure
"""
global shape
global structured_shape
global locked_vertex
if locked_vertex is None:
for n, vertex in enumerate(shape):
if distance(vertex, pos) <= 20:
shape[n] = [pos[0], pos[1]]
... | 5,304,959 |
def cluster_generated_images(
images: torch.Tensor,
activations: torch.Tensor,
selected_neuron_idx: int,
num_clusters: int = 8,
show: bool = False,
) -> Tuple[List[torch.Tensor], List[torch.Tensor]]:
"""Cluster generated images.
Args:
images (torch.Tensor): generated images.
... | 5,304,960 |
def get_list_of_all_forks():
"""gets the list of all the forked repos"""
url = "https://api.github.com/orgs/mlh-fellowship/repos?type=forks"
all_repos = []
for i in range(1, 6):
each_url = url + '&page=' + str(i)
result = github_api(each_url)
for repo in result.json():
... | 5,304,961 |
def linear(x, y, xref):
"""
Linear interpolation.
:param x:
:param y:
:param xref:
:return:
"""
from numpy import interp
return interp(xref, x, y, left=None, right=None, period=None) | 5,304,962 |
def getMappedObjectsJson(request, object_name, filter=None, range=0, isLive=False, force=False):
""" Get the object json information to show in table or map views.
"""
try:
try:
THE_OBJECT = LazyGetModelByName(getattr(settings, object_name))
except:
THE_OBJECT = LazyG... | 5,304,963 |
def setup(
use_stdout: Optional[bool] = True,
filename: Optional[PathLike] = None,
log_level: Union[int, str] = "INFO",
) -> None:
"""Setup logging for DIRECT.
Parameters
----------
use_stdout: bool
Write output to standard out.
filename: PathLike
Filename to write log t... | 5,304,964 |
def gamma(a):
"""gamma function""" | 5,304,965 |
def generate_grid_ds(
ds,
axes_dims_dict,
axes_coords_dict=None,
position=None,
boundary_discontinuity=None,
pad="auto",
new_name=None,
):
"""
Add c-grid dimensions and coordinates (optional) to observational Dataset
Parameters
----------
ds : xarray.Dataset
Dataset... | 5,304,966 |
def slugify(value):
"""Coerce a value to a slug."""
if value is None:
raise vol.Invalid("Slug should not be None")
slg = utility_slugify(str(value))
if len(slg) > 0:
return slg
raise vol.Invalid("Unable to slugify {}".format(value)) | 5,304,967 |
def is_td3_policy(policy):
"""Check whether a policy is for designed to support TD3."""
return policy in [
TD3FeedForwardPolicy,
TD3GoalConditionedPolicy,
TD3MultiFeedForwardPolicy,
] | 5,304,968 |
def get_generator():
""" construct and return generator """
g_net = gluon.nn.Sequential()
with g_net.name_scope():
g_net.add(gluon.nn.Conv2DTranspose(
channels=512, kernel_size=4, strides=1, padding=0, use_bias=False))
g_net.add(gluon.nn.BatchNorm())
g_net.add(gluon.nn.L... | 5,304,969 |
def test_can_add_markers_with_names():
"""
Test a few things related to naming marker sets
"""
npix_side = 200
image = ImageWidget(image_width=npix_side,
image_height=npix_side)
x = np.array([20, 30, 40])
y = np.array([40, 80, 100])
# This should succeed without ... | 5,304,970 |
def is_wrapped(env: Type[gym.Env], wrapper_class: Type[gym.Wrapper]) -> bool:
"""
Check if a given environment has been wrapped with a given wrapper.
:param env: Environment to check
:param wrapper_class: Wrapper class to look for
:return: True if environment has been wrapped with ``wrapper_class``... | 5,304,971 |
def get_appliance_nat_maps(
self,
ne_id: str,
cached: bool,
) -> dict:
"""Get Edge Connect appliance NAT maps configuration
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - nat
- GET
- /nat/{neId}/maps?cache... | 5,304,972 |
def destroy(context):
"""Destroy all containers and volumes."""
docker_compose(context, "down")
context.run(
f"docker volume rm -f {BUILD_NAME}_pgdata_eox_notices",
env={"NAUTOBOT_VER": NAUTOBOT_VER, "PYTHON_VER": PYTHON_VER},
) | 5,304,973 |
def status() -> str:
"""Returns the status battery ('Full', 'Charging' or 'Discharging')"""
return _get_value("status") | 5,304,974 |
def half_gauss_density(data, sd):
""" Takes a sequence of spike times and produces a non-normalised density
estimate by summing Half-gaussian (asymetric) defined by sd at each spike
time. The range of the output is guessed from the extent of the data (which
need not be ordered), the resolution is autom... | 5,304,975 |
def json_loader(file) -> dict:
"""
Returns json data given a valid filepath. Returns {} if error occurs
"""
try:
with open(file) as my_file:
data = my_file.read()
return json.loads(data)
except Exception as e:
capture_message(str(e), level="error")
return error_msg("The JSON file y... | 5,304,976 |
def get_user_by_email(db_session: Session, email: str) -> Users:
"""Get the User from its email."""
return db_session.query(Users).filter_by(email=email).first() | 5,304,977 |
def merge_unique(list1, list2):
"""
Merge two list and keep unique values
"""
for item in list2:
if item not in list1:
list1.append(item)
return list1 | 5,304,978 |
def handle_vote(session, context, option):
"""Handle any clicks on vote buttons."""
# Remove the poll, in case it got deleted, but we didn't manage to kill all references
if option is None:
if context.query.message is not None:
context.query.message.edit_text(
i18n.t("del... | 5,304,979 |
def increment(number: int) -> int:
"""Increment a number.
Args:
number (int): The number to increment.
Returns:
int: The incremented number.
"""
return number + 1 | 5,304,980 |
def mi(T, Y, num_classes=10):
"""
Computes the mutual information I(T; Y) between predicted T and true labels Y
as I(T;Y) = H(Y) - H(Y|T) = H_Y - H_cond_YgT
@param T: vector with dimensionality (num_instances,)
@param Y: vector with dimensionality (num_instances,)
@param num_classes: number of c... | 5,304,981 |
def render(canvas, fobj=None, animation=False):
"""Render the SVG representation of a canvas.
Parameters
----------
canvas: :class:`toyplot.canvas.Canvas`
The canvas to be rendered.
fobj: file-like object or string, optional
The file to write. Use a string filepath to write data direc... | 5,304,982 |
def by_dist_time_speed(
move_data,
label_id=TRAJ_ID,
max_dist_between_adj_points=3000,
max_time_between_adj_points=7200,
max_speed_between_adj_points=50.0,
drop_single_points=True,
label_new_tid=TID_PART,
inplace=True,
):
"""
Splits the trajectories into segments based on distanc... | 5,304,983 |
def test_default_reparameterisation(proposal):
"""Test to make sure default reparameterisation does not cause errors
for default proposal.
"""
FlowProposal.add_default_reparameterisations(proposal) | 5,304,984 |
def timelockanalysis(data, trials=None):
"""Prototype function for averaging :class:`~syncopy.AnalogData` across trials
Parameters
----------
data : Syncopy :class:`~syncopy.AnalogData` object
Syncopy :class:`~syncopy.AnalogData` object to be averaged across trials
trials : :class:`nump... | 5,304,985 |
def generate_navigator_js(os=None, navigator=None, platform=None,
device_type=None):
"""
Generates web navigator's config with keys corresponding
to keys of `windows.navigator` JavaScript object.
:param os: limit list of oses for generation
:type os: string or list/tuple o... | 5,304,986 |
def show_error(
keyboard,
isNotNumeric=False,
checkSubstitutionAlphabet=False,
duplicate=False):
"""
Displays an error message when the user enters incorrect characters.
"""
print(f"{'-' * 63}\n{' ' * 29}ERREUR\n{'-' * 63}")
if isNotNumeric:
print(
... | 5,304,987 |
def stillinger_weber_neighborlist(displacement,
box_size=None,
A=7.049556277,
B=0.6022245584,
p=4,
lam=21.0,
epsilon... | 5,304,988 |
def mail():
"""
Mail commands.
""" | 5,304,989 |
def sentences(s):
"""Split the string s into a list of sentences."""
try:
s + ""
except TypeError:
print "s must be a string"
pos = 0
sentence_list = []
l = len(s)
while pos < l:
try:
p = s.index('.', pos)
except:
p = l + 1... | 5,304,990 |
def skip_if_import_exception(function):
"""Assist in skipping tests failing because of missing dependencies."""
@functools.wraps(function)
def wrapper(*args, **kwargs):
try:
return function(*args, **kwargs)
except ImportError as err:
pytest.skip(str(err))
return w... | 5,304,991 |
def closest_pair(points):
"""
input: a list of points represented by tuples (x_coordinate, y_coordinate)
output: a tuple(the closest distance, the closest pair)
runtime: O(nlog(n))
"""
# sort only once, keep the sorted copy
points_x = sorted(points, key=lambda p: p[0]) # sort by x_coordinat... | 5,304,992 |
def projects_get(ctx, spec):
"""
Retrieves details of project specified by SPEC which is either ID or Name of the project.
"""
helpers.entity_detail(api.Project, spec, obj=ctx.obj) | 5,304,993 |
def CPP(record):
""" "Channel Process if Passive": a CP input link will be treated as
a channel access link and if the linking record is passive,
the linking passive record will be processed any time the linked record
is updated.
Example (Python source)
-----------------------
`my_record.IN... | 5,304,994 |
def get_mcc_lite_v3(df_c, df_mc, base_call_cutoff):
"""
"""
# get mcc matrix with kept bins and nan values for low coverage sites
df_c_nan = df_c.copy()
df_c_nan[df_c < base_call_cutoff] = np.nan
df_mcc = df_mc/df_c_nan
return df_mcc | 5,304,995 |
def main(args: Optional[Sequence[str]] = None) -> int:
"""Main entrypoint."""
parsed_args, remainder_args = get_args(args=args)
# Detect which CI environment, if any, we are in
ci_env = detect_ci_platform(parsed_args, remainder_args)
# Bail early if there are no changes to the lockfile
print(f... | 5,304,996 |
def hist(x, bins=500, title=None, show=0, stats=0, ax=None, fig=None,
w=1, h=1, xlims=None, ylims=None, xlabel=None, ylabel=None):
"""Histogram. `stats=True` to print mean, std, min, max of `x`."""
def _fmt(*nums):
return [(("%.3e" % n) if (abs(n) > 1e3 or abs(n) < 1e-3) else
(... | 5,304,997 |
def GetJValuesDataset( FileStr='GEOSChem.JValues.*', wd=None ):
"""
Wrapper to get NetCDF photolysis rates (Jvalues) output as a Dataset
Parameters
----------
wd (str): Specify the wd to get the results from a run.
FileStr (str): a str for file format with wildcards (?, *)
Returns
-----... | 5,304,998 |
def _h1_pdf_convex_decreasing_ ( h1 , degree , *args , **kwargs ) :
"""Parameterize/fit histogram with convex decreasing polynomial
>>> h1 = ...
>>> results = h1.pdf_convex_decreasing ( 3 ,)
>>> results = h1.pdf_convex_decreasing ( 3 , draw = True , silent = True )
>>> print results[ 0] ## fit r... | 5,304,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.