content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
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 | 5,315,200 |
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... | 5,315,201 |
def tee_streams(name: Path, zone_id: int) -> None:
"""
Tee stdout and stderr also to the named log file.
Note: we intentionally don't provide a way to clean up the stream
replacement so that any error handling from Python which causes us to exit
is also captured by the log file.
"""
log_fi... | 5,315,202 |
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... | 5,315,203 |
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... | 5,315,204 |
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][:] | 5,315,205 |
def do_monitor_rds_check_list(client, args):
""" List monitor items """
kwargs = {}
if args.tenant:
kwargs['tenant'] = args.tenant
if args.system:
kwargs['is_system'] = True
monitors = client.rdscheck.list(**kwargs)
utils.print_list(monitors, client.rdscheck.columns) | 5,315,206 |
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)) | 5,315,207 |
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... | 5,315,208 |
def static(req, resp):
"""Serves files from static directory"""
resp.content_type = const.TEXT_HTML
static = g.app.config.get('application', 'static').strip('/')
static_path_re = re.compile("^\/%s\/%s" %
(req.app.strip('/'), static,))
sfile_path = '/' + req.app.strip(... | 5,315,209 |
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 | 5,315,210 |
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() | 5,315,211 |
def single_turtle_permutations(top_dir: Path) -> "List[Path]":
"""Yield list of a single turtle file and permutations of it.
The permutations are restructuring of the list of classes.
"""
import os
from shutil import copy
from tempfile import TemporaryDirectory
turtle_files = list((top_dir... | 5,315,212 |
def test_format():
"""
Assert the server responds with a string
"""
response = predict('oh hi')
assert type(response) == dict
assert type(response['toxicity']) == float
assert type(response['severe_toxicity']) == float
assert type(response['obscene']) == float
assert type(response['... | 5,315,213 |
def transactionTest(card):
"""Submit a simple JSON-based request to the Notecard.
Args:
card (object): An instance of the Notecard class
"""
req = {"req": "card.status"}
try:
rsp = card.Transaction(req)
print(rsp)
except Exception as exception:
print("Transacti... | 5,315,214 |
def process_invoice_details(invoice_input_filename, invoice_details_output_filename):
"""
Converts raw invoice details data into usable format for BI.
:param invoice_input_filename: The file to open. Format: `<filename>.xls`
:param invoice_details_output_filename: The file to write to. Format as `<filen... | 5,315,215 |
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... | 5,315,216 |
def prepare_mano_model():
"""
Convert the official MANO model into compatible format with this project.
"""
with open(OFFICIAL_MANO_PATH, 'rb') as f:
data = pickle.load(f, encoding='latin1')
params = {
'pose_pca_basis': np.array(data['hands_components']),
'pose_pca_mean': np.array(data['hands_mean... | 5,315,217 |
def futures_index_dict():
"""
name and code map
:return: name to code
:rtype: dict
index_code
商品期货指数 CCFI
农产品期货指数 CAFI
油脂油料期货指数 OOFI
谷物期货指数 CRFI
油脂期货指数 OIFI
粮食期货指数 GRFI
软商品期货指数 SOFI
饲料期货指数 FEFI
... | 5,315,218 |
def tunnelMain():
"""Run a meshtastic IP tunnel"""
our_globals = Globals.getInstance()
parser = argparse.ArgumentParser()
our_globals.set_parser(parser)
initParser()
args = our_globals.get_args()
args.tunnel = True
our_globals.set_args(args)
common() | 5,315,219 |
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... | 5,315,220 |
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... | 5,315,221 |
def from_none(exc):
"""raise from_none(ValueError('a')) == raise ValueError('a') from None"""
exc.__cause__ = None
exc.__suppress_context__ = True
return exc | 5,315,222 |
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:
... | 5,315,223 |
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... | 5,315,224 |
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 more than one link, will default to using latest
mo... | 5,315,225 |
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')) | 5,315,226 |
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.
... | 5,315,227 |
def get_headers_and_fields(fileobject) -> list[str]:
"""
Add processed event fieldnames to fields.
"""
try:
headers = fileobject.readline().strip().split(",")
except Exception as e:
logging.exception("Error in reading mongoexport header")
sys.exit(1)
cols_to_add = [
... | 5,315,228 |
def populate_tlds(drop):
"""
Populate default set of TLDs into the system.
:param drop: Drop the existing collection before trying to populate.
:type: boolean
"""
if not drop:
print "Drop protection does not apply to effective TLDs"
TLD.drop_collection()
f = os.path.join(settin... | 5,315,229 |
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:
... | 5,315,230 |
def compute_coverage(full_onto_df, result_df, result_folder):
"""Compute the coverage and print the results in a file.
Args:
full_onto_df (pd.DataFrame): the DataFrame containing the information
of the ontology.
result_df (pd.DataFrame): the DataFrame containing the information
... | 5,315,231 |
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.... | 5,315,232 |
def normal_update(headers_dict, req_type):
"""Updates internal rate limit state, so that calls to check() are informed
Args:
headers_dict:
raw headers for a specific request
req_type:
one of RequestType enum
"""
rl = extract_ratelimit(headers_dict)
# 1) Id... | 5,315,233 |
def write_dump(data: list, station: str, year: int = None) -> None:
"""
Convert DataFrame to CSV and export to bulk server
"""
# The file path
path = "/hourly"
# Filter rows by year if set
if year is not None:
path += f"/{year}"
data = list(filter(lambda row: int(row[0].year... | 5,315,234 |
def cusolverDnCgesvd(handle, jobu, jobvt, m, n, a, lda, s, U,
ldu, vt, ldvt, work, lwork, rwork, devInfo):
"""
Compute complex single precision singular value decomposition.
References
----------
`cusolverDn<t>gesvd <http://docs.nvidia.com/cuda/cusolver/index.html#cuds-lt-t-gt-... | 5,315,235 |
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... | 5,315,236 |
def validate_portal_config(
etl_mapping_file, manifest_file, portal_config_file, repository, pull_request_number
):
"""Validate a PORTAL_CONFIG_FILE against the dictionary specified in the MANIFEST_FILE
and an ETL_MAPPING_FILE"""
logger.info("Validating portal config file {}".format(portal_config_file)... | 5,315,237 |
def test_runner_metrics_for_init_and_destroy(sdc_builder, sdc_executor):
"""Ensure that we properly update metrics when the runner is in starting phase."""
SCRIPT = "sleep(5*1000)"
pipeline_builder = sdc_builder.get_pipeline_builder()
# Super simple cluster pipeline
dev_data_generator = pipeline_b... | 5,315,238 |
def check_arguments(parser, args):
""" Exit if invalid options specified"""
if args.make_tables:
if not all([args.input_fasta, args.otu_map, args.taxa, args.db]):
parser.print_help()
print('\n\nMust specify an input_fasta, otu_map, taxa, and db file if making database\n\n')
... | 5,315,239 |
def group_fnames_by_pair_param2_param3_and_param1(directory: str,
param1: str,
param2: str,
param3: str):
"""
:param directory: directory do folder, which contai... | 5,315,240 |
def syncdb():
"""Create a database for testing in the shell or server."""
if south:
_local('django-admin.py syncdb')
else:
_local('django-admin.py migrate') | 5,315,241 |
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... | 5,315,242 |
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... | 5,315,243 |
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) | 5,315,244 |
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("Creating ES race store... | 5,315,245 |
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... | 5,315,246 |
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],
... | 5,315,247 |
def get_extensions(dtypes):
"""
Find available extensions for the specified dtypes
"""
return _filter_entities(_tb_extensions, dtypes) | 5,315,248 |
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)... | 5,315,249 |
def nyquist_plot(z_list, grid_flag=False, fig_title=''):
"""
:param
z_list:
grid_flag:
plot_label:
:return:
"""
z_real_list = [z.real for z in z_list]
z_imag_list = [z.imag for z in z_list]
z_inv_imag_list = [-z_imag for z_imag in z_imag_list]
fig = plt.figure()
... | 5,315,250 |
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... | 5,315,251 |
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
... | 5,315,252 |
def test_find_corp_type_by_id(session):
"""Assert that the method returns the corp type matching the id."""
corp_type = CorpType.find_by_id(Business.LegalTypes.BCOMP.value)
assert corp_type
assert corp_type_json == corp_type.json | 5,315,253 |
def test_masked():
""" Test masked numpy array """
filename, mode = 'test.h5', 'w'
a = np.ma.array([1, 2, 3, 4], dtype='float32', mask=[0, 1, 0, 0])
dump(a, filename, mode)
a_hkl = load(filename)
try:
assert a_hkl.dtype == a.dtype
assert np.all((a_hkl, a))
except AssertionE... | 5,315,254 |
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... | 5,315,255 |
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... | 5,315,256 |
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... | 5,315,257 |
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(
remove_0x_prefix(hex_encode_abi_type(abi_type, va... | 5,315,258 |
def _get_gh_issue_title(issue_id: int, repo_short_name: str) -> str:
"""
Get the title of a GitHub issue.
:param repo_short_name: `current` refer to the repo_short_name where we are, otherwise
a repo_short_name short name (e.g., "amp")
"""
repo_full_name_with_host, repo_short_name = _get_re... | 5,315,259 |
def read_and_write_pin():
"""Example code for reading and writing individual inputs and outputs.
This approach should be the most familiar to CircuitPython users. It uses
the same mechanisms as reading and setting standard GPIO pin values, but may
involve more operations than other approaches since on... | 5,315,260 |
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] | 5,315,261 |
def search_dict(partial, key):
"""Recursive search in dictionary
:param partial: Dictionary to search in
:type partial: dict
:param key: Key that you want to search in dictionary
:type key: str
:return: Value in dictionary of targeted key
:rtype: Any
"""
if isinstance(partial, dict)... | 5,315,262 |
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 model_name == "resnet":
model = ... | 5,315,263 |
def test_hve_simple():
""" A simple test
"""
print("Start test_hve_simple()")
run_test_hve_simple((hve.setup, hve.encrypt, hve.gen_token, hve.query)) | 5,315,264 |
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'],
... | 5,315,265 |
def DataIterator(Dataset, Start = 0, End = -1,
process_img = lambda img : img, process_gt = lambda gt: gt):
"""
Iterator over the desired slice of the data
:param Dataset (str or Dataset) Name of the dataset to be used or individual dataset defined
as instance of the cl... | 5,315,266 |
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 histogram and hopefully the original image. The restored
image and the number of failures... | 5,315,267 |
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... | 5,315,268 |
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
"... | 5,315,269 |
def filter_files(names: list[Path]) -> list[Path]:
"""只要文件,不要文件夹"""
return [x for x in names if x.is_file()] | 5,315,270 |
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:
break
while True:
... | 5,315,271 |
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... | 5,315,272 |
def draw_k(x, y, letter_color="lime green"):
""" Draws letter "K" using SimpleGraphics.point() in for loops.
:param x: top right horizontal position of letter on canvas
:type x: int
:param y: top right vertical position of letter on canvas
:type y: int
:param letter_color: Color of letter, defa... | 5,315,273 |
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... | 5,315,274 |
def save_model(filename,model):
"""Saves trained model
Args:
filename (string): name of the model file to write to
model (python object): trained model object
"""
dir = "models"
os.makedirs(dir,exist_ok = True) # create model folder & intermediate directories, if it doesn't exist
filepath = os... | 5,315,275 |
def _load_test_config():
"""Loads information of the pre-configured gcp project."""
dirname, _ = os.path.split(
os.path.abspath(django_cloud_deploy.tests.__file__))
config_path = os.path.join(dirname, 'integration', 'data',
'integration_test_config.yaml')
with ope... | 5,315,276 |
async def test_contextmanager_raise_generatorexit():
"""Test that shutdown via GeneratorExit is propagated"""
@a.contextmanager
async def no_op():
yield
with pytest.raises(GeneratorExit):
async with no_op():
raise GeneratorExit("used to tear down coroutines")
# during ... | 5,315,277 |
def test_double_to_single_signature():
"""
Test that the new object passes a signature test.
"""
assert (
is_double_callable(double_to_single_callable(double_application_function))
== False
) | 5,315,278 |
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... | 5,315,279 |
def start(sync_event_source, loop=None):
"""Create and start the WebSocket server."""
if not loop:
loop = asyncio.get_event_loop()
event_source = asyncio.Queue(loop=loop)
bridge = threading.Thread(target=_multiprocessing_to_asyncio,
args=(sync_event_source, event... | 5,315,280 |
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"
"""
pseudo_dict = data.dict(by_alias=True)
... | 5,315,281 |
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] | 5,315,282 |
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 ... | 5,315,283 |
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
... | 5,315,284 |
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... | 5,315,285 |
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 = [
"... | 5,315,286 |
def location_2d(x: Union[np.ndarray, float],
y: Union[np.ndarray, float],
color_guide: Union[np.array, List],
fig_title: str,
x_label: str,
y_label: str,
color_label: str,
dot_size: float = 16.,
... | 5,315,287 |
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]],
... | 5,315,288 |
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.
"""
logger.warning... | 5,315,289 |
def main(filepath):
"""Convert MELT output into TranspoScope input.
@param filepath: Path to the MELT output file
@type param: str
@return: None
@rtype : None
"""
file_name = filepath.split("/")[-1].split(".")[0]
file_handler = load_vcf(filepath)
_, header = parse_meta_info(fi... | 5,315,290 |
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(*[vals for vals in hy... | 5,315,291 |
def import_curves_data_csv_file():
"""
Import user curves data CSV file as a *Nuke* *ColorLookup* node.
Returns
-------
ColorLookup
ColorLookup node.
"""
file = nuke.getFilename('Choose ColorLookup Node Curves Data CSV File',
'*.csv')
if file is not ... | 5,315,292 |
def _ApplyContainerMods(kind, container, chgdesc, mods,
create_fn, modify_fn, remove_fn,
post_add_fn=None):
"""Applies descriptions in C{mods} to C{container}.
@type kind: string
@param kind: One-word item description
@type container: list
@param container: Con... | 5,315,293 |
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 to be cropped
:param b... | 5,315,294 |
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... | 5,315,295 |
def user():
"""Returns a user with name='mesh', token='token', trakt={'trakt': 'auth'}"""
return User('mesh', 'token', {'trakt': 'auth'}) | 5,315,296 |
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 output
and input as a JSON file, pool file is output a... | 5,315,297 |
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 | 5,315,298 |
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... | 5,315,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.