content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def DataframetolaTexTable(DF, alignment=None, fname=None,shade=False):
"""
Args:
df: pandas dataframe
alignment: python list of allignment of columns; default is ['c',..]; use ['c', 'p{4in}', 'c', 'c'] for wrapping
fname: path to save latex table
Returns:
object:
Returns... | 55,500 |
def is_report_metrics_switch_on():
"""
Whether bagua report switch is on or not.
"""
return int(os.environ.get("BAGUA_REPORT_METRICS", 0)) == 1 | 55,501 |
def restart_vm():
"""Restart the VM."""
compute_client = connect()
async_vm_restart = compute_client.virtual_machines.restart(
os.environ.get('GROUP_NAME'),
os.environ.get('ZEDE_NAME')
)
async_vm_restart.wait()
print(async_vm_restart.result()) | 55,502 |
def getinstructorData(courseIds):
"""
Gets and instructor object for the course id's given.
"""
instructorDict = {}
instructor = CourseInstructor.select().where(CourseInstructor.course << courseIds)
for i in instructor:
instructorDict.setdefault(i.course.id, []).append(i.user.fi... | 55,503 |
def convert_farenheit_to_celcius(temp):
"""Convert the temperature from Farenheit to Celcius scale.
:param float temp: The temperature in degrees Farenheit.
:returns: The temperature in degrees Celcius.
:rtype: float
"""
return (temp - 32) * 5 / 9 | 55,504 |
def test_unit_vector_N():
"""Test if the unit vector to a plane is calculated correctly"""
u_BC = [0.34040355, 0.62192853, 0.27011169]
u_AB = [0.28276792, 0.34232697, 0.02370306]
u_N = qmmmrebind.parameterize.unit_vector_N(u_BC, u_AB)
assert u_N[0] == -0.6516162898107304 | 55,505 |
def update_special_casings(uc, lc, tc, special_casing):
"""Update case conversion tables with special case conversion rules."""
for x in special_casing.data:
c1 = long(x[0], 16)
if x[4] != '':
# conditions
continue
lower = parse_unicode_sequence(x[1])
t... | 55,506 |
def creates_app():
"""Create the application
Returns:
[sanic.Sanic]: the main application
"""
LOGGER.info("Create application %s", app_version.RELEASE)
app = sanic.Sanic(__name__)
app.static('/static', './static')
errors.add_exceptions_handlers(app)
app.blueprint(version.bp)
... | 55,507 |
def test_multiple_observation_sequences_diff_dims_with_single():
"""Multiple observation sequences with different dimensionality and allow_single=True"""
X = [np.arange(8).reshape(-1, 2), np.arange(12).reshape(-1, 3)]
with pytest.raises(ValueError) as e:
val.is_observation_sequences(X, allow_single=... | 55,508 |
def parse_args():
"""Parse arguments and return them
"""
parser = argparse.ArgumentParser(
description='fpb is a fuel plugin builder which '
'helps you create plugin for Fuel')
# TODO(vsharshov): we should move to subcommands instead of
# exclusive group, because in this case we cou... | 55,509 |
def test_main_single_instance_no_tags_stop(ec2_instance):
"""
GIVEN Single instance without assigned tag.
WHEN main() is called.
THEN The stop action has been performed on given instance.
"""
ec2_instance.start()
main(aws_region='eu-west-1', ec2_action='stop', ec2_no_tags=True)
assert ec... | 55,510 |
def get_frequent_item(data):
"""
对于给定的字符串列表,找出其中出现次数最多的字符
参数
----
data: list[str],字符串列表
返回
----
re: list[str],出现次数最多的字符串
"""
_hash = word_count(data)
max_num = max(_hash.values())
return list(filter(lambda x: _hash[x] == max_num, _hash)) | 55,511 |
def upgrade():
"""Change default pool_slots to 1 and make pool_slots not nullable"""
with op.batch_alter_table("task_instance", schema=None) as batch_op:
batch_op.alter_column("pool_slots", existing_type=sa.Integer, nullable=False, server_default='1') | 55,512 |
def pzz_unpack(path, dir_path):
""" BMS script: https://zenhax.com/viewtopic.php?f=9&t=8724&p=39437#p39437
"""
with open(path, "rb") as f:
file_count = f.read(4)
file_count, = unpack("<I", file_count)
size = f.read(file_count * 4)
size = unpack("<{}I".format(file_count), size... | 55,513 |
def generate(save_path: str, n: int = 4) -> None:
"""Saves all possible combinations of `n` length amino acid sequence.
TODO: Add var that allows you to remove the certain variants. Useful
if we want to generate a dataset that doesn't include variants from
the training dataset.
Params:
-------... | 55,514 |
def float_coords_(coords):
"""\
"""
return [float_recur(coord) for coord in coords] | 55,515 |
def getLastSystemMessage(sensorId,sessionId):
"""
getLastSystemMessage - get last system message (metadata only) for the sensor.
URL Path:
- sensorId: The sensor ID for which the configuration is desired.
- sessionId: The session ID for the session.
HTTP Return Codes:
- 200 OK... | 55,516 |
def save_fasttext_bin_to_vec(model, output_path):
"""Converts FastText binary format to word2vec format"""
words = model.get_words()
with open(output_path, 'w+') as vecFile:
vecFile.write((str(len(words)) + " " + str(model.get_dimension())) + "\n")
for w in words:
v = model.get_w... | 55,517 |
def assemble(filepath):
"""Converts human-readable LLVM assembly to binary LLVM bitcode.
Args:
filepath: The path to the file to assemble. If the name ends with ".bc", the
file is assumed to be in bitcode format already.
Returns:
The path to the assembled file.
"""
if not filepath.endswith('.b... | 55,518 |
def invt_sample_z(log_density, size=1, rng=None, **log_cdf_kwargs):
"""
Inverse transform sampling to generate "true" z values for simulation:
"""
if rng is None:
rng = np.random.default_rng()
zgrid, log_cdf = get_log_cdf(log_density, **log_cdf_kwargs)
cdf = np.exp(log_cdf)
interp_... | 55,519 |
def fsort(l, signed=True, reverse=False):
"""Sort a sequence of strings with one or more floating point number fields
in using the floating point value(s) (and intervening strings are treated
as normally done). Note that + and - preceding a number are included in the
floating point value unless `signed=... | 55,520 |
def detailed_resolver(report=MAIN_REPORT, priority_key=by_priority):
""" Group by category, provide all the non-muted activated feedback """
pass | 55,521 |
def adaptive_chunked_choosers_and_alts(choosers, alternatives, chunk_size, trace_label, chunk_tag=None):
"""
generator to iterate over choosers and alternatives in chunk_size chunks
like chunked_choosers, but also chunks alternatives
for use with sampled alternatives which will have different alternati... | 55,522 |
def svg_draw_board(nodes, nets, w, h, svg_name="netList.svg", txt="HI", H=50, W=50, spacing_x=5, spacing_y=5):
"""
:type nets: list
:param nets:
:type nodes: list
"""
w2 = float(W) / 2
h2 = float(H) / 2
svg_doc = svgwrite.Drawing(filename=svg_name, size=((W + spacing_y) * w +... | 55,523 |
def food_parse(db, query):
"""
returns a jsonable dict for the autocomplete js library we are using
for a text field used to select a food item
:param db:
:param query:
:return:
"""
parts = re.split("\s+", query)
parts = [lemmer.lemmatize(part) for part in parts]
db_query = ' '.... | 55,524 |
def read_gpop_hdf5(
path: Union[Path, str], interior_path: str, dof: Optional[int] = None
) -> Union[
Tuple[numpy.ndarray, Dict[int, numpy.ndarray], Dict[int, numpy.ndarray]],
Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray],
]:
"""Read the one-body densities from a HDF5 file.
Args:
path ... | 55,525 |
def invite(request):
"""
Simple view to send invitations to friends via mail. Making the invitation
system as a view, guarantees that no invitation will be monitored or saved
to the hard disk.
"""
if request.method == "POST":
mail_addr = request.POST['email_addr']
raw_addr_list ... | 55,526 |
def build_wheel(wheel_directory, config_settings=None, metadata_directory=None):
"""Builds a wheel, places it in wheel_directory"""
poetry = Poetry.create(".")
return unicode(
WheelBuilder.make_in(
poetry, SystemEnv(Path(sys.prefix)), NullIO(), Path(wheel_directory)
)
) | 55,527 |
def entrypoint():
"""
Run entrypoint when `__name__` is `"__main__"`
"""
if __name__ == "__main__":
main() | 55,528 |
def cells():
"""Cells
From in 'Image manipulation and processing using Numpy and Scipy' section
2.6.6 Measuring object properties
<http://www.tp.umu.se/~nylen/fnm/pylect/advanced/image_processing/index.html>
No known copyright restrictions, released into the public domain.
"""
np.random.s... | 55,529 |
def jsonify_arg_input(arg):
"""Jsonify user input (in AssemblyPipeline `append` and `insert` methods)
into a standard step json."""
if isinstance(arg, RunnableArgument):
return arg.to_json()
# If a function object or name of a function is provided, we assume it
# does not have to be run (fun... | 55,530 |
def plot(data=[], files=[], plot_params=plot_parameters(),
combine=False, display=False, output_dir='.', echo_dart=None):
"""
A function to plot JSON data
Args:
- data (list):
- list of "plot_data" objects
- should contain their own plot_parameters object
- ... | 55,531 |
def geodetic_to_ellipsoidal(lat: u.deg, lon: u.deg, height: u.m, ell):
"""Convert from geodetic to ellipsoidal-harmonic coordinates.
Parameters
----------
lat : ~astropy.units.Quantity
Geodetic latitude.
lon : ~astropy.units.Quantity
Geodetic longitude.
height : ~astropy.units.Q... | 55,532 |
def enc_backbuffer(backbuffer):
"""Helper function for RLE compression, encodes a string of uncompressable data."""
compdata = []
if len(backbuffer) == 0:
return compdata
while len(backbuffer) > 128:
compdata.append(127)
compdata.extend(backbuffer[0:128])
backbuffer = bac... | 55,533 |
def fourier_features(index, freq, order):
"""
`Reference`_: https://www.kaggle.com/ryanholbrook/seasonality
Example:
>>> # Compute Fourier features to the 4th order (8 new features) for a
>>> # series y with daily observations and annual seasonality:
>>> # fourier_features(y, freq=365.25,... | 55,534 |
def read_range(read):
"""Creates a Range proto from the alignment of Read.
Args:
read: nucleus.genomics.v1.Read. The read to calculate the range for.
Returns:
A nucleus.genomics.v1.Range for read.
"""
start = read.alignment.position.position
end = start + cigar.alignment_length(read.alignment.ciga... | 55,535 |
def _get_label_members(X, labels, cluster):
"""
Helper function to get samples of a specified cluster.
Args:
X (np.ndarray): ndarray with dimensions [n_samples, n_features]
data to check validity of clustering
labels (np.array): clustering assignments for data X
cluster ... | 55,536 |
def test_day(dataset_path: Path, universe_limit):
"""Test case for verifying the results of day 21."""
game = load_dataset(ROOT_PATH.joinpath(dataset_path))
log.info(
"Loaded day 21 dataset %s with player 1 at %d " "and player 2 at %d.",
dataset_path.name,
game.position1,
gam... | 55,537 |
def create_balcony(bm, faces, prop):
"""Generate balcony geometry
"""
for f in faces:
if not valid_ngon(f):
popup_message("Balcony creation not supported for non-rectangular n-gon!", "Ngon Error")
return False
f.select = False
normal = f.normal.copy()
... | 55,538 |
def output_path(inid=None, ftype='data', format='json', site_dir='_site',
must_work=False):
"""Convert an ID into a data, edge, headline, json, or metadata path
Args:
inid: str. Indicator ID with no extensions of paths, eg '1-1-1'.
Can also be "all" for all data. If it is N... | 55,539 |
def film_availability_keys():
"""
FilmAvailability definition
Optional keys: "id"
"""
return ["service", "displayName", "country", "url"] | 55,540 |
def align_protein():
"""
Takes the unaligned proteins in ./data/download and align them using the
hmm profile.
"""
file = [file for file in os.listdir("./data/download/") if ".hmm" in file][0]
cmd = ("hmmalign "
"./data/download/%s "
"./data/download/all_protein "
... | 55,541 |
def get_label(scores):
""" Compute labels using score values.
Args:
scores: Score values for each detection.
Returns: Label for each detection.
"""
return tf.math.argmax(scores, axis=1) | 55,542 |
def store_orgname(n:tuple):
"""
sequence idをキーにorgname(とtaxonomy id)を保存する
保存先はとりあえずsqlite
:param t:
:return:
"""
conn = sqlite3.connect(target_db)
cur = conn.cursor()
# 一致するsequence id(sid)が登録されていなければ新たにdbにデータを保存する
cur.execute('INSERT INTO {} VALUES {}'.format(tbl, n))
conn.c... | 55,543 |
def create_bucket(s3_client, bucket_name = 'arxiv-etl'):
"""Creates an S3 bucket if one does not already exists
Args:
s3_client (boto3 client object): A boto3 S3 client
bucket_name (str, optional): The bucket name to create. Defaults to 'arxiv-etl'.
"""
# Retrieve the list of existing b... | 55,544 |
def cm_step_summary(abf):
"""
Return a message displaying average stats
formatted like 'Cm = 34.56 +/- 3.21 pF'
"""
Ihs, Rms, Ras, Cms = cm_step_valuesBySweep(abf)
out = ""
out += "Ih = %.02f +/- %.02f pA\n" % (np.mean(Ihs), np.std(Ihs))
out += "Rm = %.02f +/- %.02f pA\n" % (np.mean(Rms)... | 55,545 |
def check_arg_input_file(input_file: str) -> bool:
"""Return True of the input_file exists, raise an error otherwise.
:param input_file: the input file
:param input_format: the expected format of the input file
"""
path_input_file = Path(input_file)
if not path_input_file.is_file():
rai... | 55,546 |
def test_missing_header(stolen_list_importer, logger, db_conn):
"""Test Depot ID 96588/2.
Verify that the Stolen List data is not imported if a header column is missing.
"""
expect_failure(stolen_list_importer, exc_message='cannot find the column headers - , 642222222222222, imei, '
... | 55,547 |
def ner_rebulid():
"""
将原有数据转化为标记数据
"""
new_train=Tjson(file_path="data/train.json")
new_dev=Tjson(file_path="data/dev.json")
files=["data/o/train.json","data/o/dev.json"]
data=[]
for file in files:
for line in Tjson(file_path=file).load():
# print("line",line['label... | 55,548 |
def V_tank_Reflux(Reflux_mass, tau, rho_Reflux_20, dzeta_reserve):
"""
Calculates the tank for waste.
Parameters
----------
Reflux_mass : float
The mass flowrate of Reflux, [kg/s]
tau : float
The time, [s]
rho_Reflux_20 : float
The destiny of waste for 20 degrees celc... | 55,549 |
def locate_ob():
"""Try use pkgconfig to locate Open Babel, otherwise guess default location."""
# Warn if the (major, minor) version of the installed OB doesn't match these python bindings
if not is_package_installed("openbabel"):
raise RuntimeError("Error: Openbabel is not installed.")
py_ver... | 55,550 |
def vprint(*args, **kwargs):
""" Helper function that prints when verbose has been enabled. """
if verbose:
print(*args, file=sys.stdout, **kwargs) | 55,551 |
def angular_travel(angle_array):
"""
Takes in an array of angular change and returns the angles travelled. This is sensitive to changes in
direction, The angles travelled are returned as an array of stepwise values
"""
travelled = [0]
for a, angle in enumerate(angle_array):
travelled.app... | 55,552 |
def check_output_dir(output_dir):
"""
Checks the output directory for files generated in previous runs, these can be skipped later by detect_trs()
Checking is done quite naively, only looking for files ending in '.pickle' (so no support for .pcl, .pkl ...)
Parameters:
output_dir (str): Directory t... | 55,553 |
def IR_50(cfg):
"""Constructs a ir-50 model.
"""
input_size = cfg.INPUT.SIZE_TRAIN
model = Backbone(input_size, 50,cfg.MODEL.BACKBONE.BACKBONE_OUT_CHANNELS, 'ir')
return model | 55,554 |
def notice_changes(notice_file):
""" List changes in a given notice file """
# Read the notice file
notice_file = find_file(notice_file, is_notice=True)
with open(notice_file, 'r') as f:
notice_string = f.read()
parser = etree.XMLParser(huge_tree=True)
notice_xml = etree.fromstring(notic... | 55,555 |
def writeNetfile2(G, fname):
"""
write net file from G (networkx)
Parameters
----------
G: a neteworkx object
Returns
-------
file
"""
nZones = ''
nNodes = str(len(G.nodes()))
nLinks = str(len(G.edges()))
header = "<NUMBER OF ZONES> " + nZones + "\n<NUMBER OF NODES> " + nNodes + "\n<FIRS... | 55,556 |
def attention_aggregator(embedding_lists, weights, embed_dim=0) -> torch.Tensor:
"""
Returns a weighted sum of embeddings
:param embedding_lists: list of n tensors of shape (l, K) embedding tensors (l can vary)
:param weights: list of n tensors of shape (l,) weights (l can vary, but matc... | 55,557 |
def _calculate_application_risk(module):
"""
Function to calculate Software risk due to application type. This
function uses a similar approach as RL-TR-92-52 for baseline fault
density estimates. The baseline application is Process Control
software. Every other application is ranked relative to ... | 55,558 |
def test():
""" Eventually this could become a convenience command for calling the
other test commands quickly with just test -x.
"""
return test_all() | 55,559 |
def run_vpcflow_cleanup():
"""Function to run the vpcflow_cleanup function"""
vpcflow_cleanup()
logging.info("This is the end of the script. Please feel free to validate that logging resources have been cleaned up.") | 55,560 |
def callback():
"""
Step 3: Retrieving an access token.
The user has been redirected back from the provider to your registered
callback URL. With this redirection comes an authorization code included
in the redirect URL. We will use that to obtain an access token.
"""
global REDIRECT_URI
... | 55,561 |
def export_file(isamAppliance, file_path, filename, check_mode=False, force=False):
"""
Downloading a file from the file application log files area
"""
import os.path
if force is True or (os.path.exists(filename) is False):
if check_mode is False: # No point downloading a file if in check_... | 55,562 |
def main(debug, log_path, output_path):
""" LogProcessor helps parses log file and process two CSV files."""
click.echo("Begin")
if debug:
LOGGER.setLevel(logging.DEBUG)
else:
LOGGER.setLevel(logging.INFO)
log_processor = LogProcessor(log_path, output_path)
log_processor.log_rea... | 55,563 |
def parse_mid_list(mid_list, transit_duration):
"""
TODO: make sure tdb iso is precise
output will be saved in csv
"""
t12 = ["ingress"]
tmid = ["midtransit"]
t34 = ["egress"]
for mid in mid_list:
ing = mid - dt.timedelta(days=transit_duration / 2)
egr = mid + dt.timedel... | 55,564 |
def get_args():
"""
desc: get cli arguments
returns:
args: dictionary of cli arguments
"""
parser = argparse.ArgumentParser(description="this script is used for downloading datasets for training this implementation of the Hierarchical Attention Networks")
parser.add_argument("dataset", choices=["imdb"]... | 55,565 |
def check(ctx, project_dir):
"""Checks if the created model is valid."""
project_dir = os.path.abspath(project_dir)
try:
runners.load(project_dir)
except Exception as ex:
raise click.ClickException(str(ex))
click.echo("Everything is OK!") | 55,566 |
def split_model_by_material_id(bdf_filename, bdf_filename_base,
encoding=None, size=8, is_double=False):
"""
Splits a model based on the material ID
Parameters
----------
bdf_filename : str
the filename to read (e.g. fem.bdf)
bdf_filename_base : str
... | 55,567 |
def save_dict_to_hdf5(dic, group, filename):
""" Save a dictionary to a HDF5 file
"""
with h5.File(filename, 'a') as h5file:
if group not in h5file.keys():
save_dict_contents_to_group(h5file, group, dic)
else:
print(group + ' already saved in ' + filename) | 55,568 |
def RK(A,b,k=100, random_state=None):
"""
Function that runs k iterations of randomized Kaczmarz iterations (with uniform sampling).
Parameters
----------
A : NumPy array
The measurement matrix (size m x n).
b : NumPy array
The measurement vector (size m x 1).
k : int_, opti... | 55,569 |
def wait_for_instatiation(platform_adapter, service_platform, service_uuid, period=5, timeout=None):
"""
Method for waiting for SP to instantiate the service, in case PA has not callback
:param service_platform:
:param service_uuid:
:return:
"""
_LOG.debug(f'Wait until service {service_uuid}... | 55,570 |
def run_k_means(reduced_text: str, k: int, dataframe: pd.DataFrame)->None:
""" create dataframe column for k means cluster """
kmeans = KMeans(n_clusters=k, random_state=42)
y_pred = kmeans.fit_predict(reduced_text)
dataframe['y_pred'] = y_pred
return y_pred | 55,571 |
def split_blank_line(
lines: List[str], line_offset: int = 0
) -> Tuple[List[str], List[str]]:
"""Split leading blank line from lines if one exists
Args:
lines: The lines to evaluate.
line_offset (optional): The offset into the overall document we are at. This is
used for report... | 55,572 |
def score_students(model_file, students_filepath):
"""Prints the estimated score for each student in the data file
Arguments:
Takes the parameter file name for the mirt json parameter
file of interest.
Is interactive at the command line with options to enter
various questions a... | 55,573 |
def get_page_list_by_page(base_url: str, api_token: str, page_path: str, limit:Union[int, None]=None) -> dict:
"""
get page list under the specified page path
"""
req_url = '{}{}'.format(base_url, '/_api/pages.list')
limit = 1e10 if limit is None else limit
queries = {
'access_token': f'... | 55,574 |
def erode_edges(mask, erosion_width):
"""Erode edge of objects to prevent them from touching
Args:
mask: uniquely labeled instance mask
erosion_width: integer value for pixel width to erode edges
Returns:
mask where each instance has had the edges eroded
"""
if erosion_widt... | 55,575 |
def load_keel_file(path):
"""Load a keel dataset format.
Parameters
----------
path : str
The filepath of the keel dataset format.
Returns
-------
keel_dataset: KeelDataset
The keel dataset format loaded.
"""
handle = open(path)
try:
line =... | 55,576 |
def get_annotations(directory):
""" Returns rel path for all anvil files in a directory"""
return (
os.path.join(directory, f)
for f in os.listdir(directory)
if f.endswith(".anvil")
) | 55,577 |
def test_h2oconnectionconf():
"""Test H2OConnectionConf functionality."""
# Verify construction of config from dictionary
conf1 = { 'ip' : '1.1.1.1', 'port' : 80 }
cconf1 = H2OConnectionConf(conf1)
assert cconf1.ip == '1.1.1.1'
assert cconf1.port == 80
assert cconf1.url == 'http://1.1.1.1:8... | 55,578 |
def searchsorted2d(a, b):
"""
Searches a sorted 2D array along the second axis. Basically performs a vectorized digitize. Solution provided here:
https://stackoverflow.com/questions/40588403/vectorized-searchsorted-numpy.
:param a: The array to take the elements from
:type a: torch.Tensor
:param... | 55,579 |
def bytesToBits(numBytes):
"""
Converts number of bytes to bits.
:param numBytes: The n number of bytes to convert.
:returns: Number of bits.
"""
return numBytes * 8 | 55,580 |
def rankhist(X_f, X_o, X_min=None, normalize=True):
"""Compute a rank histogram counts and optionally normalize the histogram.
Parameters
----------
X_f: array-like
Array of shape (k,m,n,...) containing the values from an ensemble
forecast of k members with shape (m,n,...).
X_o: arr... | 55,581 |
async def update_node_config(node: Node, path: Path) -> None:
"""
Update the node config with information about columns.
"""
with open(path, encoding="utf-8") as input_:
original = yaml.safe_load(input_)
updated = node.to_yaml()
# preserve column attributes entered by the user
if "c... | 55,582 |
def build_data_sampler(config, dataset):
"""Returns a data sampler object of :class:`colossalai.nn.data.sampler.BaseSampler`
constructed from `config`.
Args:
config (dict or :class:`colossalai.context.Config`): A python dict or
a :class:`colossalai.context.Config` object containing info... | 55,583 |
def create_directory(update: Update, context: CallbackContext) -> None:
"""Create a new directory in the current directory when the command /rm is issued"""
global current_dir
global board_id
chat_id = update.message.chat_id
new_dir_name = ' '.join(update.message.text.split(' ')[1:])
clear_hist... | 55,584 |
def to_kwargs(triangles):
"""
Convert a list of triangles to the kwargs for the Trimesh constructor.
Parameters
---------
triangles: (n,3,3) float, triangles in space
Returns
---------
kwargs: dict, with keys:
'vertices' : (n,3) float
'faces' : ... | 55,585 |
def get_model_field(model, name):
"""
Gets a field from a Django model.
:param model: A Django model, this should be the class itself.
:param name: A Django model's field.
:return: The field from the model, a subclass of django.db.models.Model
"""
return model._meta.get_field(name) | 55,586 |
def get_clean_sample_mask(log_mah_fit, logmp_sample, it_min, lim=0.01, z_cut=3):
"""Calculate mask to remove halos with outlier MAH behavior.
Parameters
----------
log_mah_fit : ndarray of shape (n_halos, n_times)
logmp_sample : float
it_min : int
Index of the minimum time used to def... | 55,587 |
def _get_answer_files(request):
"""
Gets the path to where the hashed and raw answers are saved.
"""
answer_file = f"{request.cls.__name__}_{request.cls.answer_version}.yaml"
raw_answer_file = f"{request.cls.__name__}_{request.cls.answer_version}.h5"
# Add the local-dir aspect of the path. If th... | 55,588 |
def inert_masses(m_1, H, z_m, E_1):
"""First stage inert masses.
Arguments:
m_1 (scalar): First stage wet mass [units: kilogram].
H (scalar): Fraction of the recovery vehicle dry mass which is added recovery
hardware [units: dimensionless].
z_m (scalar): Fraction of baseline... | 55,589 |
def _grid_mapping(pollon, pollat, mapping_name=None):
"""creates a grid mapping DataArray object"""
if mapping_name is None:
mapping_name = cf.DEFAULT_MAPPING_NCVAR
da = xr.DataArray(np.zeros((), dtype=np.int32))
attrs = cf.mapping.copy()
attrs["grid_north_pole_longitude"] = pollon
attrs... | 55,590 |
def retrieve_employees(page=1):
"""
Handle requests to the /employees/<int:page> route - @roles_required(xxx)
Retrieve all employee from the DB ordered by the First Name with the pagination support
Filter employees based on specified start date and end date
"""
employees_per_page = 7
employ... | 55,591 |
def worker_pool_unresponsive(worker_pool):
"""
Send out a notification that the given ``worker_pool`` is unresponsive.
"""
logger.error('WorkerPool is unresponsive: {0}'.format(
worker_pool.log_name()))
t = get_template('job_runner/email/worker_pool_unresponsive.txt')
c = Context({
... | 55,592 |
def plot_metric_comparison_by_label(metric1: str,
metric2: str,
from_csv: bool = False,
db: cosem_db.MongoCosemDB = None,
training_version: str = "v0003.2",
... | 55,593 |
def __virtual__():
"""
Confine this module to yum based systems
"""
if __opts__.get("yum_provider") == "yumpkg_api":
return (False, "Module yumpkg: yumpkg_api provider not available")
try:
os_grain = __grains__["os"].lower()
os_family = __grains__["os_family"].lower()
exc... | 55,594 |
def get_update_message(new_version, info_url):
"""Return a string suitable for notifying users about the status
of their update check. NEW_VERSION and INFO_URL generally come
directly from a call to update_check()."""
if new_version is None:
return (f'You are running the latest version ({__ver... | 55,595 |
def str_url_encode(text):
"""
Encode package before send to Telegram API.
:param text: string.
:return: string.
"""
return quote(text) | 55,596 |
def _select_single_channel(state):
"""Select the audioPackFormat path, audioChannelFormat and audioTrackUID
for single channels within the pack.
"""
for audioChannelFormat, track_spec in state.channel_allocation:
yield evolve(state,
audioPackFormat_path=_get_pack_format_path... | 55,597 |
def block(func: AnyCallable, *args: Any, **kwargs: Any) -> Any:
"""
Run a function in a blocking manner, whether the function is async or blocking.
Args:
func - the function (async or blocking) to run
args - the args to run the function with
kwargs - the kwargs to run the function w... | 55,598 |
def input(msg="", default="", title="Lackey Input", hidden=False):
""" Creates an input dialog with the specified message and default text.
If `hidden`, creates a password dialog instead. Returns the entered value. """
root = tk.Tk()
input_text = tk.StringVar()
input_text.set(default)
PopupInpu... | 55,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.