content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def create_export_settings_window():
"""
This function contains all the logic of the export settings window and will run the window by it's own.
:return: None
"""
window = sg.Window("Export Settings", generate_export_settings_layout(), modal=True, finalize=True,
keep_on_top=... | 9552cfb269cb3e67cf3332783b9a43a674bc9e3d | 6,900 |
def get_vertex_list(session, node_id, part_info):
"""Wrapper for HAPI_GetVertexList
Args:
session (int): The session of Houdini you are interacting with.
node_id (int): The node to get.
part_info (PartInfo): Part info of querying
Returns:
np.ndarray: Array of vertices
"... | dd5a37e248347dc9e9b5f8fba07d202008626ea5 | 6,901 |
def lamb1(u,alpha=.5):
"""Approximate the Lambert W function.
Approximate the Lambert W function from its upper and lower bounds.
The parameter alpha (between 0 and 1) determines how close the
approximation is to the lower bound instead of the upper bound.
:arg float u: Modified argument o... | 1d769ccb74334eef55aa1bc0697328b34ba067bc | 6,902 |
def loglikelihood(time_steps: list) -> float:
"""Calculate the log-likelihood of the time steps from the estimation
Parameters
----------
time_steps : list
estimation time steps
Returns
-------
float
log-likelihood
"""
loglikelihood = 0
for time_step in time_st... | 6761ced2947d9ac382d53eef390bd827ceb51203 | 6,903 |
def get_r0_rm_rp(s, i_delta):
""" compute 3 points r0, r_minus and r_plus to determine apsis
compute these at s.i-i_delta and s.i-2*i_delta
"""
xp = s.Xlast[:, s.i % s.save_last]
x0 = s.Xlast[:, (s.i - i_delta) % s.save_last]
xm = s.Xlast[:, (s.i - 2 * i_delta) % s.save_last]
rp = norm... | 83595b9b15eb9c9373aa4e8f75d2ffc39c8ba248 | 6,904 |
import os
def create_tf_example(image,
image_dir,
seg,
seg_dir):
"""Converts image and annotations to a tf.Example proto.
Args:
image: dict with keys: [u'license', u'file_name', u'coco_url', u'height',
u'width', u'date_captured... | 23afe328d5a5436904cf1700b344d5f7d2c0f722 | 6,905 |
def build_rfb_lite(base, feature_layer, mbox, num_classes):
"""Receptive Field Block Net for Accurate and Fast Object Detection for embeded system
See: https://arxiv.org/pdf/1711.07767.pdf for more details.
"""
base_, extras_, norm_, head_ = add_extras(base(), feature_layer, mbox, num_classes, version='... | c8b1810d088f816d4e3be587cb1085bacde08076 | 6,906 |
def bfunsmat(u, p, U):
"""Computes a matrix of the form :math:`B_{ij}`, where
:math:`i=0\\ldots p` and for each :math:`j` th column the
row :math:`i` of the matrix corresponds to the value of
:math:`(\\mathrm{span}(u_j)-p+i)` th bspline basis function at
:math:`u_j`.
Parameters:
u (np.a... | 6dc260a165c5ae25ac9914ff0b96c1fd8f05b93c | 6,907 |
def getFourgram(words, join_string):
"""
Input: a list of words, e.g., ['I', 'am', 'Denny', 'boy']
Output: a list of trigram, e.g., ['I_am_Denny_boy']
I use _ as join_string for this example.
"""
assert type(words) == list
L = len(words)
if L > 3:
lst = []
for... | 17717bb608a7ef5eff1ac9e1f49d2606b7113360 | 6,908 |
import math
def get_age_carbon_14_dating(carbon_14_ratio):
"""Returns the estimated age of the sample in year.
carbon_14_ratio: the percent (0 < percent < 1) of carbon-14
in the sample conpared to the amount in living
tissue (unitless). """
if isinstance(carbon_14_ratio, str):
raise Type... | 8b0ab86e3c45a97065fefb6c4f02ab87c3e82d23 | 6,909 |
def get_input_definition() -> InputDefinition:
"""
Query ReconAll's input file definition (*t1_files*) to check for existing
runs.
Returns
-------
InputDefinition
ReconAll's *t1_files* input definition
"""
node = get_node()
return node.analysis_version.input_definitions.get(... | 1575bc2521b6f041c4151be6405ac1d458333d62 | 6,910 |
def create_ou_process(action_spec, ou_stddev, ou_damping):
"""Create nested zero-mean Ornstein-Uhlenbeck processes.
The temporal update equation is:
.. code-block:: python
x_next = (1 - damping) * x + N(0, std_dev)
Note: if ``action_spec`` is nested, the returned nested OUProcess will not be... | 292b235863e57b49e531e5e5b091f55688357122 | 6,911 |
def clean_data(df):
"""
remove the duplicates from a dataframe
parameters:
df(Dataframe): data frame
"""
df=df.drop_duplicates()
return df | 7072885f7233c5407060344e6858f89108d61ee8 | 6,912 |
def IssueFactory(data, journal_id, issue_order):
"""
Realiza o registro fascículo utilizando o opac schema.
Esta função pode lançar a exceção `models.Journal.DoesNotExist`.
"""
mongo_connect()
metadata = data["metadata"]
issue = models.Issue()
issue._id = issue.iid = data.get("id")
... | 49ef57cb1c628c05e30a35e10680d34140066182 | 6,913 |
def _is_permission_in_db(permission_name: str):
"""To check whether the given permission is in the DB
Parameters
----------
permission_name: str
A permission name we use internally.
E.g., hazard, hazard:hazard, project...
"""
return bool(
models.Auth0Permission.query.fil... | 6e0e672d5c73e0740b695f29d3459a3b80c86831 | 6,914 |
import sys
import pyflakes
def check(source):
"""Return messages from pyflakes."""
if sys.version_info[0] == 2 and isinstance(source, unicode):
# Convert back to original byte string encoding, otherwise pyflakes
# call to compile() will complain. See PEP 263. This only affects
# Python... | 2b07fc9e7522ca8d356ce6509d93d8d9db04b204 | 6,915 |
from typing import Optional
def get_dataset(dataset_id: Optional[str] = None,
location: Optional[str] = None,
project: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetDatasetResult:
"""
Gets any metadata associated with a datase... | 985a7e9b7b124c0dba37455426889683e5769aaf | 6,916 |
def is_email_available() -> bool:
"""
Returns whether email services are available on this instance (i.e. settings are in place).
"""
return bool(settings.EMAIL_HOST) | c8b8362aed7f2af5dd49070dce7f522fd0c2088a | 6,917 |
def sql2label(sql, num_cols):
"""encode sql"""
# because of classification task, label is from 0
# so sel_num and cond_num should -1,and label should +1 in prediction phrase
cond_conn_op_label = sql.cond_conn_op
sel_num_label = sql.sel_num - 1
# the new dataset has cond_num = 0, do not -1
c... | b25c819e4645c07216970877ac95d20b0f8baab6 | 6,918 |
import time
def retrieveToken(verbose: bool = False, save: bool = False, **kwargs)->str:
"""
LEGACY retrieve token directly following the importConfigFile or Configure method.
"""
token_with_expiry = token_provider.get_token_and_expiry_for_config(config.config_object,**kwargs)
token = token_with_e... | b419934bf2725b46d23abc506c5b5a2828de1d0c | 6,919 |
def format_str_for_write(input_str: str) -> bytes:
"""Format a string for writing to SteamVR's stream."""
if len(input_str) < 1:
return "".encode("utf-8")
if input_str[-1] != "\n":
return (input_str + "\n").encode("utf-8")
return input_str.encode("utf-8") | 1b83a2c75118b03b7af06350e069775c0b877816 | 6,920 |
def reverse_result(func):
"""The recursive function `get_path` returns results in order reversed
from desired. This decorator just reverses those results before returning
them to caller.
"""
@wraps(func)
def inner(*args, **kwargs):
result = func(*args, **kwargs)
if result is not ... | c13d28550e77a8fba149c50673252012c712961f | 6,921 |
def convert_from_opencorpora_tag(to_ud, tag: str, text: str):
"""
Конвертировать теги их формата OpenCorpora в Universal Dependencies
:param to_ud: конвертер.
:param tag: тег в OpenCorpora.
:param text: токен.
:return: тег в UD.
"""
ud_tag = to_ud(str(tag), text)
pos = ud_tag.sp... | 0e650cc4976d408ed88ef9280fe3a74261353561 | 6,922 |
import struct
def reg_to_float(reg):
"""convert reg value to Python float"""
st = struct.pack(">L", reg)
return struct.unpack(">f", st)[0] | f4a2d416e880807503f3c0ba0b042fbbecc09064 | 6,923 |
def wvelocity(grid, u, v, zeta=0):
"""
Compute "true" vertical velocity
Parameters
----------
grid : seapy.model.grid,
The grid to use for the calculations
u : ndarray,
The u-field in time
v : ndarray,
The v-field in time
zeta : ndarray, optional,
The zeta-field ... | 452e84b334b42b9099ed888319a3cc88e7191e9b | 6,924 |
def _as_nested_lists(vertices):
""" Convert a nested structure such as an ndarray into a list of lists. """
out = []
for part in vertices:
if hasattr(part[0], "__iter__"):
verts = _as_nested_lists(part)
out.append(verts)
else:
out.append(list(part))
re... | c69bd2084aa8e76a53adf3e25286a8dd7ae23176 | 6,925 |
def markdown(code: str) -> str:
"""Convert markdown to HTML using markdown2."""
return markdown2.markdown(code, extras=markdown_extensions) | 09f463aa28f9289d05b44244e6ac60ce7905af83 | 6,926 |
import json
import urllib
async def post_notification(request):
"""
Create a new notification to run a specific plugin
:Example:
curl -X POST http://localhost:8081/fledge/notification -d '{"name": "Test Notification", "description":"Test Notification", "rule": "threshold", "channel": "email"... | bdc85dd3d93f51352776a3e63b34a18961014058 | 6,927 |
def test_send_file_to_router(monkeypatch, capsys):
"""
.
"""
# pylint: disable=unused-argument
@counter_wrapper
def get_commands(*args, **kwargs):
"""
.
"""
return "commands"
@counter_wrapper
def add_log(log: Log, cursor=None):
"""
.
... | 739e9d2dbb9adc40b386566b4e73dae98381ed4c | 6,928 |
def smiles2mol(smiles):
"""Convert SMILES string into rdkit.Chem.rdchem.Mol.
Args:
smiles: str, a SMILES string.
Returns:
mol: rdkit.Chem.rdchem.Mol
"""
smiles = canonicalize(smiles)
mol = Chem.MolFromSmiles(smiles)
if mol is None:
return None
Chem.Kekulize(mol)
... | 56a8e0b28f98b1dd920cf03977eb6086a134fd8f | 6,929 |
import sys
def parallel_execute(objects, func, get_name, msg, get_deps=None):
"""Runs func on objects in parallel while ensuring that func is
ran on object only after it is ran on all its dependencies.
get_deps called on object must return a collection with its dependencies.
get_name called on object... | e774ceee6a9289bdbf70e2f7c5055a2f39c9804b | 6,930 |
def build_term_map(deg, blocklen):
"""
Builds term map (degree, index) -> term
:param deg:
:param blocklen:
:return:
"""
term_map = [[0] * comb(blocklen, x, True) for x in range(deg + 1)]
for dg in range(1, deg + 1):
for idx, x in enumerate(term_generator(dg, blocklen - 1)):
... | 3e70cb38314189ff33da3eeb43ca0c68d13904cd | 6,931 |
def gen_sets():
"""
List of names of all available problem generators
"""
return registered_gens.keys() | f5aefd9d480115013ef8423ce6fd173d5acf0045 | 6,932 |
def is_valid_currency(currency_: str) -> bool:
"""
is_valid_currency:判断给定货币是否有效
@currency_(str):货币代码
return(bool):FROM_CNY、TO_CNY均有currency_记录
"""
return currency_ in FROM_CNY and currency_ in TO_CNY | 5b95b0d0a76e5d979e7a560ee14f6adf2c79e140 | 6,933 |
from typing import List
from typing import Tuple
def load_gene_prefixes() -> List[Tuple[str, str, str]]:
"""Returns FamPlex gene prefixes as a list of rows
Returns
-------
list
List of lists corresponding to rows in gene_prefixes.csv. Each row has
three columns [Pattern, Category, Not... | 9fc450636a4b517a79350b9b6131dccfe860c58e | 6,934 |
def create_page_panels_base(num_panels=0,
layout_type=None,
type_choice=None,
page_name=None):
"""
This function creates the base panels for one page
it specifies how a page should be layed out and
how many panels should... | 2503a2e911f877b357c408665f49a385026721f4 | 6,935 |
def uri2dict(uri):
"""Take a license uri and convert it into a dictionary of values."""
if uri.startswith(LICENSES_BASE) and uri.endswith('/'):
base = LICENSES_BASE
license_info = {}
raw_info = uri[len(base):]
raw_info = raw_info.rstrip('/')
info_list = raw_info.split('... | 1f2ccdc52b1dc3424b7554857a87f85a02ea1dbd | 6,936 |
import re
def test_clean_str(text, language='english'):
"""
Method to pre-process an text for training word embeddings.
This is post by Sebastian Ruder: https://s3.amazonaws.com/aylien-main/data/multilingual-embeddings/preprocess.py
and is used at this paper: https://arxiv.org/pdf/1609.02745.pdf
"... | 683f6d27e7486990d0b2a11dd5aeb78f2c1bab07 | 6,937 |
from ..loghelper import run_cmd
from ..loghelper import noLOG
import sys
import os
def run_venv_script(venv, script, fLOG=None,
file=False, is_cmd=False,
skip_err_if=None, platform=None,
**kwargs): # pragma: no cover
"""
Runs a script on a vritual e... | 5f0ae63a2f9ee4a5c666e679141c8fb68e63896b | 6,938 |
def calc_iou(boxes1, boxes2, scope='iou'):
"""calculate ious
Args:
boxes1: 5-D tensor [BATCH_SIZE, CELL_SIZE, CELL_SIZE, BOXES_PER_CELL, 4] ====> (x_center, y_center, w, h)
boxes2: 5-D tensor [BATCH_SIZE, CELL_SIZE, CELL_SIZE, BOXES_PER_CELL, 4] ===> (x_center, y_center, w, h)
Return:
iou... | e5714cf74be851b6b6003458c44e3308308907a3 | 6,939 |
def not_before(cert):
"""
Gets the naive datetime of the certificates 'not_before' field.
This field denotes the first date in time which the given certificate
is valid.
:param cert:
:return: Datetime
"""
return cert.not_valid_before | e5e269e67de3059fe0ddfa9a35fb13e7f124d798 | 6,940 |
def get_data_from_dict_for_2pttype(type1,type2,datadict):
"""
Given strings identifying the type of 2pt data in a fits file
and a dictionary of 2pt data (i.e. the blinding factors),
returns the data from the dictionary matching those types.
"""
#spectra type codes in fits file, under hdutable... | d8656e6274dd8fb4001d477572220f2c51c08e01 | 6,941 |
def simple_unweighted_distance(g, source, return_as_dicts=True):
"""Returns the unweighted shortest path length between nodes and source."""
dist_dict = nx.shortest_path_length(g, source)
if return_as_dicts:
return dist_dict
else:
return np.fromiter((dist_dict[ni] for ni in g), dtype=in... | d82742ac88f26db8296dec9d28794d3e6d60eec7 | 6,942 |
def A070939(i: int = 0) -> int:
"""Length of binary representation of n."""
return len(f"{i:b}") | 31b12e493645c3bdf7e636a48ceccff5d9ecc492 | 6,943 |
import time
def feed_pump(pin: int, water_supply_time: int=FEED_PUMP_DEFAULT_TIME) -> bool:
"""
feed water
Parameters
----------
pin : int
target gpio (BCM)
water_supply_time : int
water feeding time
Returns
-------
bool
Was water feeding successful ?
... | c45b1775991a4914116468961ae979dae71f6caf | 6,944 |
def app_nav(context):
"""Renders the main nav, topnav on desktop, sidenav on mobile"""
url_name = get_url_name(context)
namespace = get_namespace(context)
cache_id = "{}:{}x".format(context['request'].user.username, context.request.path)
cache_key = make_template_fragment_key('app_nav', [cache_id])... | 8e9cc5428b9af22bad13c6454f462d585a04c005 | 6,945 |
def centre_to_zeroes(cartesian_point, centre_point):
"""Converts centre-based coordinates to be in relation to the (0,0) point.
PIL likes to do things based on (0,0), and in this project I'd like to keep
the origin at the centre point.
Parameters
----------
cartesian_point : (numeric)
... | f0ddd632650127e3bb1ed766191950ccf7f06d87 | 6,946 |
def get_all_stack_names(cf_client=boto3.client("cloudformation")):
"""
Get all stack names
Args:
cf_client: boto3 CF client
Returns: list of StackName
"""
LOGGER.info("Attempting to retrieve stack information")
response = cf_client.describe_stacks()
LOGGER.info("Retrieved stack... | 47a36e15651495cc0b5c80e642bb5154640d6b7d | 6,947 |
import calendar
def match_date(date, date_pattern):
"""
Match a specific date, a four-tuple with no special values, with a date
pattern, four-tuple possibly having special values.
"""
# unpack the date and pattern
year, month, day, day_of_week = date
year_p, month_p, day_p, day_of_week_p =... | d794cf211589840697007ecec7cd9e3ba0655b0f | 6,948 |
def get_heating_features(df, fine_grained_HP_types=False):
"""Get heating type category based on HEATING_TYPE category.
heating_system: heat pump, boiler, community scheme etc.
heating_source: oil, gas, LPC, electric.
Parameters
----------
df : pandas.DataFrame
Dataframe that is updated... | 5707975a63aca4778e8dbdd70670e317c777c998 | 6,949 |
def integrate_eom(initial_conditions, t_span, design_params, SRM1, SRM2):
"""Numerically integrates the zero gravity equations of motion.
Args:
initial_conditions (np.array()): Array of initial conditions. Typically set
to an array of zeros.
t_span (np.array()): Time vector (s) over whi... | 07574c775268798371425b837b20706ac9af5f52 | 6,950 |
def activation_sparse(net, transformer, images_files):
"""
Activation bottom/top blob sparse analyze
Args:
net: the instance of Caffe inference
transformer:
images_files: sparse dataset
Returns:
none
"""
print("\nAnalyze the sparse info of the Activation:")... | da138764d002e84bdee306e15b6c8524b223bcbc | 6,951 |
def cfg_load(filename):
"""Load a config yaml file."""
return omegaconf2namespace(OmegaConf.load(filename)) | 2aa5f808f89d1f654cd95cd6a1c8f903d4baade6 | 6,952 |
def char_to_num(x: str) -> int:
"""Converts a character to a number
:param x: Character
:type x: str
:return: Corresponding number
:rtype: int
"""
total = 0
for i in range(len(x)):
total += (ord(x[::-1][i]) - 64) * (26 ** i)
return total | f66ee13d696ec1872fbc2a9960362456a5c4cbe9 | 6,953 |
from typing import Callable
import time
def time_it(f: Callable):
"""
Timer decorator: shows how long execution of function took.
:param f: function to measure
:return: /
"""
def timed(*args, **kwargs):
t1 = time.time()
res = f(*args, **kwargs)
t2 = time.time()
... | bc7321721afe9dc9b4a2861b2c849e6a5d2c309a | 6,954 |
def has_prefix(sub_s, dictionary):
"""
:param sub_s: (str) A substring that is constructed by neighboring letters on a 4x4 square grid
:return: (bool) If there is any words with prefix stored in sub_s
"""
s = ''
for letter in sub_s:
s += letter
for words in dictionary:
if words.startswith(s):
return True
... | b45f3bf7ed699bc215d1670f35ebc0f15b7ec0ff | 6,955 |
import os
def search_paths_for_executables(*path_hints):
"""Given a list of path hints returns a list of paths where
to search for an executable.
Args:
*path_hints (list of paths): list of paths taken into
consideration for a search
Returns:
A list containing the real pat... | f6546fba4c3ac89b975d2c0757064edae3dca340 | 6,956 |
def tf_center_crop(images, sides):
"""Crops central region"""
images_shape = tf.shape(images)
top = (images_shape[1] - sides[0]) // 2
left = (images_shape[2] - sides[1]) // 2
return tf.image.crop_to_bounding_box(images, top, left, sides[0], sides[1]) | 1b1c8bcab55164a04b0ac6109a7b91d084f55b7b | 6,957 |
from datetime import datetime
import pytz
def convert_timezone(time_in: datetime.datetime) -> datetime.datetime:
"""
用来将系统自动生成的datetime格式的utc时区时间转化为本地时间
:param time_in: datetime.datetime格式的utc时间
:return:输出仍旧是datetime.datetime格式,但已经转换为本地时间
"""
time_utc = time_in.replace(tzinfo=pytz.timezone("UT... | 3843aa62a5ff29fd629776e69c52cd95c51fac5d | 6,958 |
from typing import Any
def convert_bool(
key: str, val: bool, attr_type: bool, attr: dict[str, Any] = {}, cdata: bool = False
) -> str:
"""Converts a boolean into an XML element"""
if DEBUGMODE: # pragma: no cover
LOG.info(
f'Inside convert_bool(): key="{str(key)}", val="{str(val)}", ... | 2ed2a92506189803cb2854bff9041c492ff479dc | 6,959 |
from IPython import display
import os
def plot_model(model,
to_file='model.png',
show_shapes=False,
show_dtype=False,
show_layer_names=True,
rankdir='TB',
expand_nested=False,
dpi=96,
layer_range=No... | 772032a8e3117ae6128b5ce957b1e59bea79866b | 6,960 |
import numpy
from sys import path
import warnings
def catalog_info(EPIC_ID=None, TIC_ID=None, KIC_ID=None):
"""Takes EPIC ID, returns limb darkening parameters u (linear) and
a,b (quadratic), and stellar parameters. Values are pulled for minimum
absolute deviation between given/catalog Teff and lo... | 86583524d074fd93bf0a124a64bf26cb1e7e5d83 | 6,961 |
import six
def classifier_fn_from_tfhub(output_fields, inception_model, return_tensor=False):
"""Returns a function that can be as a classifier function.
Copied from tfgan but avoid loading the model each time calling _classifier_fn
Args:
output_fields: A string, list, or `None`. If present, assume ... | e7f54a4c46519465460cc0e97b0f6f12f91a98d4 | 6,962 |
import json
def get_rate_limit(client):
"""
Get the Github API rate limit current state for the used token
"""
query = '''query {
rateLimit {
limit
remaining
resetAt
}
}'''
response = client.execute(query)
json_response = json.loads(respo... | ec5f853014f25c841e71047da62ca41907b02e13 | 6,963 |
import functools
import pprint
def pret(f):
"""
Decorator which prints the result returned by `f`.
>>> @pret
... def f(x, y): return {'sum': x + y, 'prod': x * y}
>>> res = f(2, 3)
==> @pret(f) -- {'prod': 6, 'sum': 5}
"""
@functools.wraps(f)
def g(*args, **kwargs):
... | fedb8cf19913042d0defef676db6b22715e8c572 | 6,964 |
def parse_arguments() -> tuple[str, str, bool]:
"""Return the command line arguments."""
current_version = get_version()
description = f"Release Quality-time. Current version is {current_version}."
epilog = """preconditions for release:
- the current folder is the release folder
- the current branch... | 7b58b2b3c99a4297bb12b714b289336cdbc75a5e | 6,965 |
import os
def process_submission(problem_id: str, participant_id: str, file_type: str,
submission_file: InMemoryUploadedFile,
timestamp: str) -> STATUS_AND_OPT_ERROR_T:
"""
Function to process a new :class:`~judge.models.Submission` for a problem by a participant.... | 6104eef6f32ba68df05e64cd2cc869bde0fcb318 | 6,966 |
import sys
def eq_text_partially_marked(
ann_objs,
restrict_types=None,
ignore_types=None,
nested_types=None):
"""Searches for spans that match in string content but are not all
marked."""
# treat None and empty list uniformly
restrict_types = [] if restrict_types is N... | cf7a3b272f7e9de7812981642c20dbef5f31e895 | 6,967 |
def wait_for_status(status_key, status, get_client, object_id,
interval: tobiko.Seconds = None,
timeout: tobiko.Seconds = None,
error_ok=False, **kwargs):
"""Waits for an object to reach a specific status.
:param status_key: The key of the status fiel... | 5384dec0c4a078c5d810f366927d868692ae6bf3 | 6,968 |
def can_hold_bags(rule: str, bag_rules: dict) -> dict:
"""
Returns a dict of all bags that can be held by given bag color
:param rule: Color of a given bag
:param bag_rules: Dictionary of rules
:type rule: str
:type bag_rules: dict
:return:
"""
return bag_rules[rule] | b7554c32bd91f9a05cd84c9249d92cc6354458a9 | 6,969 |
def fix_levers_on_same_level(same_level, above_level):
"""
Input: 3D numpy array with malmo_object_to_index mapping
Returns:
3D numpy array where 3 channels represent
object index, color index, state index
for minigrid
"""
lever_idx = malmo_object_to_index['lever']
con... | d1727e188f9a5935a660d806f69f9b472db94217 | 6,970 |
def iv_plot(df, var_name=None, suffix='_dev'):
"""Returns an IV plot for a specified variable"""
p_suffix = suffix.replace('_','').upper()
sub_df = df if var_name is None else df.loc[df.var_name==var_name, ['var_cuts_string'+suffix, 'ln_odds'+suffix, 'resp_rate'+suffix, 'iv'+suffix]]
sub_df['resp_rate_t... | dd35329b5b91a19babdfa943c2f7688bb013c680 | 6,971 |
from py._path.local import LocalPath
def is_alive(pid):
"""Return whether a process is running with the given PID."""
return LocalPath('/proc').join(str(pid)).isdir() | e6086b79aa648dc4483085e15f096152185aa780 | 6,972 |
from pyspark import SparkContext
from typing import Callable
import functools
from typing import Any
def inheritable_thread_target(f: Callable) -> Callable:
"""
Return thread target wrapper which is recommended to be used in PySpark when the
pinned thread mode is enabled. The wrapper function, before call... | 02d2e58449c736bf8ef19354bfd8f7a21066615b | 6,973 |
import scipy
def build_grad(verts, edges, edge_tangent_vectors):
"""
Build a (V, V) complex sparse matrix grad operator. Given real inputs at vertices, produces a complex (vector value) at vertices giving the gradient. All values pointwise.
- edges: (2, E)
"""
edges_np = toNP(edges)
edge_... | 8faeea92e132afcf1f612cd17d48ef488fc907bb | 6,974 |
from typing import OrderedDict
def join_label_groups(grouped_issues, grouped_prs, issue_label_groups,
pr_label_groups):
"""Combine issue and PR groups in to one dictionary.
PR-only groups are added after all issue groups. Any groups that are
shared between issues and PRs are added a... | b51a70a60bde3580326816eaf0d3b76cb51062ac | 6,975 |
def healpix_ijs_neighbours(istar, jstar, nside):
"""Gets the healpix i, jstar neighbours for a single healpix pixel.
Parameters
----------
istar : array
Healpix integer i star index.
jstar : array
Healpix integer i star index.
nside : int
Healpix nside.
Returns
... | 48cae5cd13101529c7d03f9c08ed0f2c2d77a7b8 | 6,976 |
def micropub_blog_endpoint_POST(blog_name: str):
"""The POST verb for the micropub blog route
Used by clients to change content (CRUD operations on posts)
If this is a multipart/form-data request,
note that the multiple media items can be uploaded in one request,
and they should be sent with a `na... | 3d8f4b80099ca77d2f7ad2ec13f4a45f4102dc8c | 6,977 |
def create_parser(config: YAMLConfig) -> ArgumentParser:
"""
Automatically creates a parser from all of the values specified in a config
file. Will use the dot syntax for nested dictionaries.
Parameters
----------
config: YAMLConfig
Config object
Returns
-------
ArgumentPar... | 8fcf886448061b7f520d133bbf9bb66047e9f516 | 6,978 |
def detect_version(conn):
"""
Detect the version of the database. This is typically done by reading the
contents of the ``configuration`` table, but before that was added we can
guess a couple of versions based on what tables exist (or don't). Returns
``None`` if the database appears uninitialized, ... | 6429dbb1e1767cf6fd93c3fd240ce095f1b50ef7 | 6,979 |
def nIonDotBHmodel2(z):
"""Ionization model 2 from BH2007: constant above z=6.
"""
return ((z < 6) * nIonDotLowz(z) +
(z >= 6) * nIonDotLowz(6)) | 438cdd69a229e445f8e313145e84ed11618ee2cb | 6,980 |
def answer(input):
"""
>>> answer("1234")
1234
"""
lines = input.split('\n')
for line in lines:
return int(line) | b9ce42d88a09976444563493a01741475dce67c5 | 6,981 |
def get_leading_states(contributions):
"""
Return state contributions, names as lists in descending order of contribution amount
:param contributions:
:return:
"""
contributions['state'] = contributions['clean_fips'].apply(get_state)
states = contributions.groupby('state')
state_sums = s... | 7028f87ad7b106e267104dddebc2fe42546d3cfd | 6,982 |
def contacts_per_person_normal_self_20():
"""
Real Name: b'contacts per person normal self 20'
Original Eqn: b'30'
Units: b'contact/Day'
Limits: (None, None)
Type: constant
b''
"""
return 30 | 4a240066b2aefd8af2e19f174632e1bf854bf7d3 | 6,983 |
def __compute_partition_gradient(data, fit_intercept=True):
"""
Compute hetero regression gradient for:
gradient = ∑d*x, where d is fore_gradient which differ from different algorithm
Parameters
----------
data: DTable, include fore_gradient and features
fit_intercept: bool, if model has int... | e987fc53b1f1ee8cc7a0ddbe83de23b1623b532e | 6,984 |
def calc_nsd(x, n=21):
"""
Estimate Noise Standard Deviation of Data.
Parameters
----------
x : 1d-ndarray
Input data.
n : int
Size of segment.
Returns
-------
result : float
Value of noise standard deviation.
"""
x_diff = np.diff(x, n=2)
x_frag ... | 23b0041fc1a9bde364828a0a94b12fc7292a391a | 6,985 |
def deflection_from_kappa_grid_adaptive(kappa_high_res, grid_spacing, low_res_factor, high_res_kernel_size):
"""
deflection angles on the convergence grid with adaptive FFT
the computation is performed as a convolution of the Green's function with the convergence map using FFT
The grid is returned in th... | cc71b9bd35c5e09e45815cf578870c481a03b8ed | 6,986 |
from params import pop_sizes
def remove_sus_from_Reff(strain, data_date):
"""
This removes the inferred susceptibility depletion from the Reff estimates out of EpyReff.
The inferred Reff = S(t) * Reff_1 where S(t) is the effect of susceptible depletion (i.e. a
factor between 0 and 1) and Reff_1 is t... | 9342896ff84507ecbe93b96a81b781ed6f8c336e | 6,987 |
def word2bytes(word, big_endian=False):
""" Converts a 32-bit word into a list of 4 byte values.
"""
return unpack_bytes(pack_word(word, big_endian)) | 9c208efc87bb830692771f3dacb1618a1d8d7da4 | 6,988 |
def statfcn(status, _id, _ret):
"""
Callback for libngspice to report simulation status like 'tran 5%'
"""
logger.warn(status.decode('ascii'))
return 0 | 344210160227ae76470f53eecd43c913b9dec495 | 6,989 |
def decode_eventdata(sensor_type, offset, eventdata, sdr):
"""Decode extra event data from an alert or log
Provide a textual summary of eventdata per descriptions in
Table 42-3 of the specification. This is for sensor specific
offset events only.
:param sensor_type: The sensor type number from th... | 7a90810657edd017b42f7f70a7a0c617435cb14f | 6,990 |
def get_log_path():
"""
Requests the logging path to the external python library (that calls
the bindings-common).
:return: The path where to store the logs.
"""
if __debug__:
logger.debug("Requesting log path")
log_path = compss.get_logging_path()
if __debug__:
logger.d... | ccb7adf37df06de721f53253a86cc2ecdff962b9 | 6,991 |
def about_incumbent(branch_df):
"""
number of incumbent updates
incumbent throughput: num_updates / num_nodes
max_improvement, min_improvement, avg_improvement
avg incumbent improvement / first incumbent value
max, min, avg distance between past incumbent updates
distance between last update... | 309dd09a6fcad58064e98c79536ca73256fe3ac2 | 6,992 |
from typing import List
def unique_chars(texts: List[str]) -> List[str]:
"""
Get a list of unique characters from list of text.
Args:
texts: List of sentences
Returns:
A sorted list of unique characters
"""
return sorted(set("".join(texts))) | 02bc9ce28498bd129fdb68c2f797d138ca584490 | 6,993 |
def adaptive_max_pool1d(input, output_size):
"""Apply the 1d adaptive max pooling to input.
Parameters
----------
input : dragon.vm.torch.Tensor
The input tensor.
output_size : Union[int, Sequence[int]]
The target output size.
Returns
-------
dragon.vm.torch.Tensor
... | 06556ea06ebe282bf24739d56ff016924a730c8b | 6,994 |
def get_return_nb(input_value, output_value):
"""Get return from input and output value."""
if input_value == 0:
if output_value == 0:
return 0.
return np.inf * np.sign(output_value)
return_value = (output_value - input_value) / input_value
if input_value < 0:
return_... | fe9ef59feb7b4e9797a74258ecbf890171f6df59 | 6,995 |
def get_rocauc(val,num_iterations):
""" Trains a logistic regression and calculates the roc auc
for classifying products as >=4 stars """
recalls = np.zeros(num_iterations)
precisions = np.zeros(num_iterations)
f1s = np.zeros(num_iterations)
roc_aucs = np.zeros(num_iterations)
factory = lr_wrapper(val,featur... | d2b2ceae240db6c3ce474d74aea1ebd4d1ed9830 | 6,996 |
def split_expList(expList, max_nr_of_instr: int=8000,
verbose: bool=True):
"""
Splits a pygsti expList into sub lists to facilitate running on the CCL
and not running into the instruction limit.
Assumptions made:
- there is a fixed instruction overhead per program
- th... | 0c006b3026bfd11f28a3f1ecfc40e6e87801759e | 6,997 |
def __make_node_aliases(data: list[str]):
"""Alias a genes ID to their families
in order to build edges between them"""
famcom = {}
elems = [tokens for tokens in data if tokens[2] in ["FAMILY", "COMPLEX"]]
# Add all (gene) containers first
for tokens in elems:
famcom[tokens[1]] = AliasIt... | 3372d41de2b8a4caf5cf599ff09a0491af7740f9 | 6,998 |
import torch
def poly_edges_min_length(P, T, distFcn=norm):
"""
Returns the per polygon min edge length
Parameters
----------
P : Tensor
a (N, D,) points set tensor
T : LongTensor
a (M, T,) topology tensor
Returns
-------
Tensor
the (T, M,) min edge length... | efa68aa752d0f3c1efc29a846f06e006bd8bceb9 | 6,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.