content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_proto_messages(protocol: str) -> list:
""" Get messages of a protocol. """
db = MetaDB()
rows = db.get_all_meta()
db.close_conn()
messages = set(row[1] for row in rows if row[0] == protocol)
return messages | 28,300 |
def TokenAMarkdownReference(href, reference, title=None):
"""
[link text][1]
[1]: <https://example.com> "Title"
<a href="https://example.com" title="Title">link text</a>
"""
title = ' "%s"' % title if title else ""
data = "[%s]: %s%s" % (reference, href, title)
token = {
"type"... | 28,301 |
def inverse_document_frequency(word_occurrence, num_texts):
"""Takes in a word (string) and texts (list of lists and calculates the
number of texts over number of texts where the word occurs"""
try:
IDF = float(num_texts) / float(word_occurrence)
return math.log(IDF)
except ZeroDivisionE... | 28,302 |
def bip32_mprv_from_seed(seed: octets, version: octets) -> bytes:
"""derive the master extended private key from the seed"""
if isinstance(version, str): # hex string
version = bytes.fromhex(version)
assert version in PRIVATE, "wrong version, master key must be private"
# serialization data
... | 28,303 |
def cmd_ml_load_model(current_board : board.Board, flags, player_dict):
""" cmd loadmodel <filename> : load a machine learning model from file into MLPlayer """
if "default" not in flags:
error_message("Incorrectly formatted arguments")
return
model_name = flags["default"]
try:
p... | 28,304 |
def filterCombineCount(input, output):
"""extract count column only"""
df = pd.read_csv(input[0])
df =df.filter(like='Counts', axis=1)
df = df.set_index("Counts")
df.to_csv(output, index=True, sep='\t')
return | 28,305 |
def create_menu_node(context: WxRenderingContext) -> WxNode:
"""Creates node from xml node using namespace as module and tag name as class name"""
inst_type = get_type(context.xml_node)
args = get_attr_args(context.xml_node, 'init', context.node_globals)
inst = inst_type(**args)
return WxNode(inst, ... | 28,306 |
def show_loading(screen):
"""Show loading screen, renders independently on rest of the game"""
text = gfx.Text(screen, CFG().font_main, 16, (255, 255, 255))
screen.fill((0,0,0))
rect = screen.get_rect()
text.write('now loading...', rect.centerx, rect.centery, (255,255,255), origin='center')
pyga... | 28,307 |
def attach_calibration_pattern(ax, **calibration_pattern_kwargs):
"""Attach a calibration pattern to axes.
This function uses calibration_pattern to generate a figure.
Args:
calibration_pattern_kwargs: kwargs, optional
Parameters to be given to the calibration_pattern function.
... | 28,308 |
def alignplot(align_data, en_tokens = None, es_tokens = None, annot = False):
"""
plot the align data with tokens in both language
:params: annot: whether give annot on each element in the matrix
:params: align_data: attention matrix, array-like
:params: en_tokens: english tokens (list, array)
:... | 28,309 |
def GetModuleObjectAndName(globals_dict):
"""Returns the module that defines a global environment, and its name.
Args:
globals_dict: A dictionary that should correspond to an environment
providing the values of the globals.
Returns:
_ModuleObjectAndName - pair of module object & module name.
R... | 28,310 |
def to_datetime(timestamp: str) -> datetime.datetime:
"""Converts a timestamp string in ISO format into a datatime object.
Parameters
----------
timstamp : string
Timestamp in ISO format
Returns
-------
datetime.datetime
Datetime object
"""
# Assumes a string in ISO... | 28,311 |
def paint_box(stdscr, width, start_y, start_x, heading, fieldsets):
"""Paint a number of (text) fields in a box on the screen."""
indent = 2
padding = width - (len(heading) + 1)
full_heading = " " + heading
if padding > 0:
for x in range(padding):
full_heading += " "
stdscr.a... | 28,312 |
def test_pwd_removal_preserve_reserved_word(regexes, config_line):
"""Test that reserved words are preserved even if they appear in password lines."""
pwd_lookup = {}
assert config_line == replace_matching_item(regexes, config_line, pwd_lookup) | 28,313 |
def print_packages(ctx, param, value):
"""
Print the list of supported package manifests and datafile formats
"""
if not value or ctx.resilient_parsing:
return
from packagedcode import PACKAGE_DATAFILE_HANDLERS
for cls in sorted(
PACKAGE_DATAFILE_HANDLERS, key=lambda pc: (pc.de... | 28,314 |
async def handle_arg(
ctx: SlashContext,
key: str,
value: Any,
type_: Union[Callable, commands.Converter]
) -> Any:
"""
Handle an argument and deal with typing.Optional modifiers
Parameters
----------
ctx : SlashContext
The context of the argument
key : str
The a... | 28,315 |
def parse_command_arguments():
"""Returns parsed command arguments"""
parser = argparse.ArgumentParser(description="svg-to-swift converter")
parser.add_argument("--input_file", required=True, help="SVG file to convert.")
parser.add_argument("--output_file", default="svg.swift", help="File to save in swi... | 28,316 |
def get_module_source_path(modname, basename=None):
"""Return module *modname* source path
If *basename* is specified, return *modname.basename* path where
*modname* is a package containing the module *basename*
*basename* is a filename (not a module name), so it must include the
file extension: .p... | 28,317 |
def drop_useless_columns(data):
"""Drop the columns containing duplicate or useless columns."""
data = data.drop(
labels=[
# we stay in a given city
"agency_id",
"agency_name",
"agency_short_name",
# we stay on a given transportation network
... | 28,318 |
def arg_to_timestamp(arg: Any, arg_name: str, required: bool = False) -> Optional[int]:
"""Converts an XSOAR argument to a timestamp (seconds from epoch)
This function is used to quickly validate an argument provided to XSOAR
via ``demisto.args()`` into an ``int`` containing a timestamp (seconds
since ... | 28,319 |
def expfloats (floats):
"""Manipulates floats so that their tiles are logarithmic sizes
large to small"""
return [math.exp(i) for i in floats] | 28,320 |
def typeChecker(obj, *types, error=True):
"""
Check type(s) of an object.
The first type correlates to the first layer of obj and so on.
Each type can be a (tuple that holds) type, string or literal object such as `None`.
:param obj: Generic obj, iterable or not
:param types: lists or tuples if... | 28,321 |
def post_profile_identifier_chunks_token(identifier, token):
"""
Updates a public chunk.
"""
chunk = models.Chunk.get_by_token(identifier, token)
if not chunk:
raise errors.ResourceNotFound('That chunk does not exist')
stream_entity = chunk.key.parent().get()
others = filter(lambda p... | 28,322 |
def assert_res_props(res, exp_props, ignore_values=None, prop_names=None):
"""
Check the properties of a resource object.
"""
res_props = dict(res.properties)
# checked_prop_names = set()
for prop_name in exp_props:
if prop_names is not None and prop_name not in prop_names:
... | 28,323 |
def get_latest_checkpoint(checkpoint_dir: str) -> int:
"""Find the episode ID of the latest checkpoint, if any."""
glob = osp.join(checkpoint_dir, 'checkpoint_*.pkl')
def extract_episode(x):
return int(x[x.rfind('checkpoint_') + 11:-4])
try:
checkpoint_files = tf.io.gfile.glob(glob)
except tf.errors.... | 28,324 |
def lazy(f):
"""A decorator to simply yield the result of a function"""
@wraps(f)
def lazyfunc(*args):
yield f(*args)
return lazyfunc | 28,325 |
def build_source_test_raw_sql(test_namespace, source, table, test_type,
test_args):
"""Build the raw SQL from a source test definition.
:param test_namespace: The test's namespace, if one exists
:param source: The source under test.
:param table: The table under test
:... | 28,326 |
def get_random_word(used_words: List[int]) -> Tuple[Optional[str], List[int]]:
"""Select a random word from a list and pass on a list of used words.
Args:
used_words (list): A list of the indexes of every already used word.
Returns:
Tuple[Optional[str], list]: The random word that is selec... | 28,327 |
def _generate_image_and_label_batch(image, label, min_queue_examples,
batch_size, height, shuffle, channels_last=True):
"""Construct a queued batch of images and labels.
Args:
image: 3-D Tensor of [height, width, 3] of type.float32.
label: 1-D Tensor of type.int32
... | 28,328 |
def test_create_user(api_client, user_data):
"""Test user creation."""
response = api_client.post("/v1/users/", user_data)
assert response.status_code == status.HTTP_201_CREATED
assert User.objects.filter(username=user_data["username"]).exists() | 28,329 |
def update_attributes(cloudnet_variables: dict, attributes: dict) -> None:
"""Overrides existing CloudnetArray-attributes.
Overrides existing attributes using hard-coded values.
New attributes are added.
Args:
cloudnet_variables: CloudnetArray instances.
attributes: Product-specific at... | 28,330 |
def riskscoreci(x1, n1, x2, n2, alpha=0.05, correction=True):
"""Compute CI for the ratio of two binomial rates.
Implements the non-iterative method of Nam (1995).
It has better properties than Wald/Katz intervals,
especially with small samples and rare events.
Translated from R-package '... | 28,331 |
def blend(a, b, alpha=0.5):
"""
Alpha blend two images.
Parameters
----------
a, b : numpy.ndarray
Images to blend.
alpha : float
Blending factor.
Returns
-------
result : numpy.ndarray
Blended image.
"""
a = skimage.img_as_float(a)
b = skimage.... | 28,332 |
def GetWsdlMethod(ns, wsdlName):
""" Get wsdl method from ns, wsdlName """
with _lazyLock:
method = _wsdlMethodMap[(ns, wsdlName)]
if isinstance(method, ManagedMethod):
# The type corresponding to the method is loaded,
# just return the method object
return method
elif... | 28,333 |
def displayBoard(board):
"""Displays the board on the screen."""
tensDigitsLine = ' ' # Indentation for the number labels.
for i in range(1, 6):
tensDigitsLine += (' ' * 9) + str(i)
# Print the numbers across the top of the board.
print(tensDigitsLine)
print(' ' + ('0123456789' * 6... | 28,334 |
def plot_feature_wise(indicators, plot=False, show=True, ax=None, nf_max=40):
"""Plot the statistics feature-wise."""
n_mv_fw = indicators['feature-wise']
n_rows = indicators['global'].at[0, 'n_rows']
if show:
with pd.option_context('display.max_rows', None):
print(
... | 28,335 |
def normalize(string: str) -> str:
"""
Normalize a text string.
:param string: input string
:return: normalized string
"""
string = string.replace("\xef\xbb\xbf", "") # remove UTF-8 BOM
string = string.replace("\ufeff", "") # remove UTF-16 BOM... | 28,336 |
def get_images(image_dir: str, image_url: str = DEFAULT_IMAGE_URL):
"""Gets image.
Args:
image (str): Image filename
image_url (str): Image url
Returns:
str: Output image filename
"""
images = list_images(image_dir)
if not images and image_url is not None:
print... | 28,337 |
def generate_key(length=128):
"""Generate a suitable client secret"""
rand = SystemRandom()
return "".join(
rand.choice(string.ascii_letters + string.digits + string.punctuation)
for x in range(length)
) | 28,338 |
def export(mv_file, idx_file, dst_path, start=0, end=0, max_workers=5):
"""
:param mv_file: mv所在目录
:param idx_file: idx所在目录
:param dst_path: 结果存放目录
:param start:
:param end:
:param max_workers:
:return:
"""
mv_op = resolvemv_ope(mv_file, idx_file) # 实例化对象
nums = mv_op.getFr... | 28,339 |
def correlateFFT(FFTdata_i, FFTdata_j, out):
"""given two FFT data arrays, upsample, correlate, and inverse fourier transform."""
#### upsample, and multiply A*conj(B), using as little memory as possible
in_len = FFTdata_i.shape[0]
out_len = out.shape[0]
A = 0
B = (in_len + 1) ... | 28,340 |
def do_service_list(cc, args):
"""List Services."""
try:
service = cc.smc_service.list()
except exc.Forbidden:
raise exc.CommandError("Not authorized. The requested action "
"requires 'admin' level")
else:
fields = ['id', 'name', 'node_name', 'state... | 28,341 |
def upload_tosca_template(file): # noqa: E501
"""upload a tosca template description file
upload and validate a tosca template description file # noqa: E501
:param file: tosca Template description
:type file: werkzeug.datastructures.FileStorage
:rtype: str
"""
res = tosca_template_servic... | 28,342 |
def extract_data(mask, dra, ddc, dra_err, ddc_err, ra_rad, dc_rad, ra_dc_cor=None):
"""Get a clean sample based on mask
Parameters
----------
mask : array of boolean
mask for extract data
dra/ddc : array of float
R.A.(*cos(Dec.))/Dec. differences
dra_err/ddc_err : array of float... | 28,343 |
def holes_filler(arr_segm_with_holes, holes_label=-1, labels_sequence=(), verbose=1):
"""
Given a segmentation with holes (holes are specified by a special labels called holes_label)
the holes are filled with the closest labels around.
It applies multi_lab_segmentation_dilate_1_above_selected_label unti... | 28,344 |
def isAbsolute(uri : str) -> bool:
""" Check whether a URI is Absolute. """
return uri is not None and uri.startswith('//') | 28,345 |
def token_converter(tokens: Iterable[str]) -> Iterable[str]:
"""Convert tokens."""
def convert(token: str) -> str:
return token.lower().replace("-", "_")
return map(convert, tokens) | 28,346 |
def update_instance(instance, validated_data):
"""Update all the instance's fields specified in the validated_data"""
for key, value in validated_data.items():
setattr(instance, key, value)
return instance.save() | 28,347 |
def pupilresponse_nnls(tx, sy, event_onsets, fs, npar=10.1, tmax=930):
"""
Estimate single-event pupil responses based on canonical PRF (`pupil_kernel()`)
using non-negative least-squares (NNLS).
Parameters
-----------
tx : np.ndarray
time-vector in milliseconds
... | 28,348 |
def _eval_expression(
expression,
params,
x,
ind_var="x",
aux_params=None,
domain=DEFAULT_DOMAIN,
rng=DEFAULT_RANGE,
):
"""Evaluate the expression at x.
Parameters
----------
expression : string
The expression that defines the calibration function.
params : array... | 28,349 |
def too_few_peaks_or_valleys(
peak_indices: NDArray[int],
valley_indices: NDArray[int],
min_number_peaks: int = MIN_NUMBER_PEAKS,
min_number_valleys: int = MIN_NUMBER_VALLEYS,
) -> None:
"""Raise an error if there are too few peaks or valleys detected.
Args:
peak_indices: NDArray
... | 28,350 |
def negative_frequency(P_m):
"""get the negative probability"""
sample_num = []
sample_prob = []
for key, value in P_m.items():
sample_num.append(key)
sample_prob.append(value)
return sample_num, np.array(sample_prob)/sum(sample_prob) | 28,351 |
def _ShellQuote(command_part):
"""Escape a part of a command to enable copy/pasting it into a shell.
"""
return pipes.quote(command_part) | 28,352 |
def evaluate_coco(model, dataset, coco, eval_type="bbox", limit=0, image_ids=None):
"""Runs official COCO evaluation.
dataset: A Dataset object with valiadtion data
eval_type: "bbox" or "segm" for bounding box or segmentation evaluation
limit: if not 0, it's the number of images to use for evaluation
... | 28,353 |
def LogLEVEL(val):
"""
Return a sane loglevel given some value.
"""
if isinstance(val, (float, int)):
return int(val)
if isinstance(val, basestring):
return getattr(logging, val.upper())
return val | 28,354 |
def decoMakerApiCallChangePosToOptArg(argPos, argName):
""" creates a decorator, which change the positional argument ARGPOS into
an optional argument ARGNAME.
argPos=1 is the first positional arg
"""
# for understanding, what we are doing here please read
# # see http://sta... | 28,355 |
def wrangle_address_dist_matrix(ba_rel, ba_asso):
""" Get all buffer level derived variables based on "AH, Relatives and Associates" file
Note: we have some participants that list relatives but no associates (or vice versa), so we have to fill NA values
Keyword Arguments:
- ba_ba_comparison:
... | 28,356 |
def circlePoints(x, r, cx, cy):
"""Ther dunction returns the y coordinate of a
circonference's point
:x: x's coordinate value.
:r: length of the radius.
:cx: x coordinate of the center.
:cy: y coordinate of the center."""
return math.sqrt(math.pow(r,2) - math.pow(x-cx, 2)) + cy | 28,357 |
def aaa():
"""AAA command line"""
pass | 28,358 |
def get_thread_info():
"""
Returns a pair of:
- map of LWP -> thread ID
- map of blocked threads LWP -> potential mutex type
"""
# LWP -> thread ID
lwp_to_thread_id = {}
# LWP -> potential mutex type it is blocked on
blocked_threads = {}
output = gdb.execute("info threads", fro... | 28,359 |
def _maybe_convert_labels(y_true):
"""Converts binary labels into -1/1."""
are_zeros = math_ops.equal(y_true, 0)
are_ones = math_ops.equal(y_true, 1)
is_binary = math_ops.reduce_all(math_ops.logical_or(are_zeros, are_ones))
def _convert_binary_labels():
# Convert the binary labels to -1 or 1.
return ... | 28,360 |
def test_currency_deepcopy():
"""test_currency_deepcopy."""
new_currency = currency.__deepcopy__()
assert new_currency == currency
assert new_currency is not currency
assert new_currency.numeric_code == '978'
assert new_currency.alpha_code == 'EUR'
assert new_currency.decimal_places == 2
... | 28,361 |
def trim_listing(obj):
"""Remove 'listing' field from Directory objects that are keep references.
When Directory objects represent Keep references, it is redundant and
potentially very expensive to pass fully enumerated Directory objects
between instances of cwl-runner (e.g. a submitting a job, or usin... | 28,362 |
def create_plot(feature="bar"):
"""provided random generated plots"""
if feature == "bar":
N = 40
x = np.linspace(0, 1, N)
y = np.random.randn(N)
df = pd.DataFrame({'x': x, 'y': y}) # creating a sample dataframe
data = [
go.Bar(
x=df['x'], # ... | 28,363 |
def get_gram_matrix(tensor):
"""
Returns a Gram matrix of dimension (distinct_filer_count, distinct_filter_count) where G[i,j] is the
inner product between the vectorised feature map i and j in layer l
"""
G = torch.mm(tensor, tensor.t())
return G | 28,364 |
def calc_stat_moments(ds, dim_aggregator='time', time_constraint=None):
"""Calculates the first two statistical moments and
the coefficient of variation in the specified dimension.
Parameters:
-----------
ds : xr.Dataset
dim_aggregator : str
coordinate to calculate the stati... | 28,365 |
def validate_case_matches_checkpoint(do_lower_case, init_checkpoint):
"""Checks whether the casing config is consistent with the checkpoint name."""
# The casing has to be passed in by the user and there is no explicit check
# as to whether it matches the checkpoint. The casing information probably
# s... | 28,366 |
def test_refreshes_token_with_valid_refresh_token_cookie(
app: Flask, client: FlaskClient
) -> None:
"""Assert that the GifSync API will respond with an auth token and the auth token's
max age when POST /auth/refresh is requested with a cookie named "refresh_token"
containing a valid refresh token.
... | 28,367 |
def move_cursor_left() -> "None":
"""Move back a character, or up a line."""
get_app().current_buffer.cursor_position -= 1 | 28,368 |
def submit_ride_request():
"""
submit a ride request with the following required fields:
- netId (string) - netId of requester
- date (date object) - date of travel
- time (time object) - time of travel
- origin (string) - chosen from dropdown of origins
- destination (st... | 28,369 |
def update_youtube_dl():
"""This block for updating youtube-dl module in the freezed application folder in windows"""
current_directory = config.current_directory
# check if the application runs from a windows cx_freeze executable
# if run from source code, we will update system installed package and e... | 28,370 |
def _heatmap(data,
row_ticks=None,
col_ticks=None,
row_labels=None,
col_labels=None,
ax=None,
cbar_kw={},
cbarlabel="",
**kwargs):
"""Create a heatmap from a numpy array and two lists of labels.
(Code from `... | 28,371 |
def clustermap(gene_values, out_pdf, color=None, table=False):
""" Generate a clustered heatmap using seaborn. """
if table:
np.save(out_pdf[:-4], gene_values)
plt.figure()
g = sns.clustermap(
gene_values,
metric='euclidean',
cmap=color,
xticklabels=False,
yticklabels=False)
... | 28,372 |
def test_similarityAccuracyAggregate(mongoURI):
"""
Tests for basic accuracy against a brute-force constructed Python 'database'
at thresholds 0.2, 0.4, 0.6, 0.8, and 1. This test is relatively long and
will modify your local MongoDB instance.
"""
db_python = utils.setupPythonDB('data/test_data/... | 28,373 |
def html_colour_to_rgba(html_colour: str) -> ():
"""Convers HTML colout to its RGB values"""
html_colour = html_colour.strip()
if html_colour[0] == '#':
html_colour = html_colour[1:]
return tuple([int(x, 16) for x in (html_colour[:2], html_colour[2:4], html_colour[4:], '0')]) | 28,374 |
def index(request):
"""Displays form."""
data = {"menu": "index", "max_characters": settings.PASTE["max_characters"]}
if request.method == "POST":
paste = Paste(slug=random_id(Paste))
if request.FILES:
for language_name, any_file in request.FILES.items():
break
... | 28,375 |
def setup(bot):
"""Setup."""
check_folder()
check_file()
n = RoyaleRant(bot)
bot.add_cog(n) | 28,376 |
def lambda_handler(event, context):
"""
Assesses instance reservations and produces a report on them
"""
import json
event_settings = copy(LAMBDA_DEFAULTS)
event_settings.update(event)
# Set the local timezone for datetime formatting if the parameter was
# passed to the Lambda function... | 28,377 |
def trafficking_service():
"""Connect to Google's DFA Reporting service with oauth2 using the discovery service."""
return google_service(DDM_TRAFFICKING_SCOPE) | 28,378 |
def question_freq(freq_range):
"""Page for individual question's word frequency."""
# drop columns with all na
questions = st.multiselect(
label="Select specific questions below:",
options=selected_nan_df.columns[2:],
)
plots_range = st.sidebar.slider(
"Select the number of ... | 28,379 |
def launch_testing(model_epoch, input_type=0):
"""Function that launches a model over the test dataset"""
testset = MSCOCO(IMAGES_FOLDER_TEST, ANNOTATION_FILE_TEST,input_type=input_type)
#Load the training model
checkpoint = torch.load(os.path.join(MAIN_FOLDER, model_epoch))
net = Model(input_type=... | 28,380 |
def cd(path):
"""
A Fabric-inspired cd context that temporarily changes directory for
performing some tasks, and returns to the original working directory
afterwards. E.g.,
with cd("/my/path/"):
do_something()
Args:
path: Path to cd to.
"""
cwd = os.getcwd()
... | 28,381 |
def deduplicate(s, ch):
"""
From http://stackoverflow.com/q/42216559/610569
s = 'this is an irritating string with random spacing .'
deduplicate(s)
'this is an irritating string with random spacing .'
"""
return ch.join([substring for substring in s.strip().split(ch) if su... | 28,382 |
def optimize(mod):
"""Optimize all the functions in a module.
Modules are the only mutable piece of Relay. We write an
optimization pass over the module which destructively updates each
function while optimizing.
"""
return pass_set(mod) | 28,383 |
def sum_series(n):
"""Calculate sum of n+(n-2)+(n-4)..."""
return n if n < 2 else n + sum_series(n - 2) | 28,384 |
def get_preconditioner():
"""Compute the preconditioner M"""
diags_x = zeros((3, nx))
diags_x[0,:] = 1/hx/hx
diags_x[1,:] = -2/hx/hx
diags_x[2,:] = 1/hx/hx
Lx = spdiags(diags_x, [-1,0,1], nx, nx)
diags_y = zeros((3, ny))
diags_y[0,:] = 1/hy/hy
diags_y[1,:] = -2/hy/hy
... | 28,385 |
def compute_noise_ceiling(y, scoring=roc_auc_score, K=None, soft=True, return_pred=False, doubles_only=False):
""" Computes the noise ceiling for data with repetitions.
Parameters
----------
y : pd.Series
Series with numeric values and index corresponding to stim ID.
K : int
Number ... | 28,386 |
def main(clear_cache, debug, zwift_user, zwift_pass, tplvars, output_file, rider_list, template):
"""
Output some sort of rider list with data downloaded from ZwiftPower
\b
Arguments:
- RIDERLIST: Source of riders. Supported sources:
- team:13264
- riders:514482,399078
- rac... | 28,387 |
def maskw(m, edge, xray_image, imax, jmax, maxr, roundR, listcounter):
"""
Takes in a bunch of parameters for masking the image
Parameters
----------
Stuff ;
Returns
-------
highper, lowper, totalper, old_files, iMask, StatsA
"""
# old_files=np.zeros((imax,jmax))
# highpe... | 28,388 |
def check_shadow_dirs(processes, cwd):
"""
Assures that tmp0, tmp1 etc. exist
"""
nonExistingDirs = []
for iprocess in range(processes):
tmpDir = cwd + os.sep + 'tmp' + str(iprocess)
if not os.path.exists(tmpDir):
nonExistingDirs.append(tmpDir)
if len(nonExistingDirs)... | 28,389 |
def check_regularizer(layer_config, class_name='L1L2', l1=None, l2=None):
"""
Check if the kernel L1 and/or L2 regularizer coefficients are (about) the
same as the one that one expects. The regularizer coefficients are in
general not exactly the same as the chosen one (because of Keras), but it
shou... | 28,390 |
def get_all_contained_items(item, stoptest=None):
"""
Recursively retrieve all items contained in another item
:param text_game_maker.game_objects.items.Item item: item to retrieve items\
from
:param stoptest: callback to call on each sub-item to test whether\
recursion should continue.... | 28,391 |
def get_br_el_sub_name_list(year, dep, sem_num, br_dict, el_dict, dep_dict, content = ''):
""" Return list of name of breadth and elective subjects for this batch
Called by get_br_el_sub_name_list_helper for every roll number in the dep.
"""
grade_list = ['EX', 'A', 'B', 'C', 'D', 'P', 'F', 'X']
... | 28,392 |
def validate_context_for_visiting_vertex_field(location, context):
"""Ensure that the current context allows for visiting a vertex field."""
if is_in_fold_innermost_scope_scope(context):
raise GraphQLCompilationError(u'Traversing inside a @fold block after output is '
... | 28,393 |
def make_from_file(fn : str, robotModel : RobotModel, *args,**kwargs) -> RobotInterfaceBase:
"""Create a RobotInterfaceBase from a Python file or module containing the
``make()`` function.
args and kwargs will be passed to ``make``.
Example::
iface = make_from_file('klampt.control.simrobotcont... | 28,394 |
def page_id_url(context, reverse_id, lang=None):
"""
Show the url of a page with a reverse id in the right language
This is mostly used if you want to have a static link in a template to a page
"""
request = context.get('request', False)
if not request:
return {'content':''}
if lang ... | 28,395 |
def test_calculate_spend_cost_basis1_buy_used_by_2_sells_taxable(accountant):
""" Make sure that when 1 buy is used by 2 sells bought cost is correct
Regression test for taxable part of:
https://github.com/rotki/rotki/issues/223
"""
asset = A_BTC
cost_basis = accountant.pots[0].cost_basis
a... | 28,396 |
def convert(string):
""" the convert() function takes simple-formatted string and returns a 'lingtree description string' suitable for pasting into the SIL LingTree program directly
the string should contain multiple lines, one line per 'node relationship'. E.G. :
S = NP VP
NP = \L Juan
Juan = \G John
VP =... | 28,397 |
def Hij_to_cijkl(H):
"""Convert a Hooke's matrix to the corresponding rigidity tensor
Parameters
----------
H: 6x6 iterable or dict
The Hooke's matrix to be converted. If not already a np.ndarray, an iterable must
be castable to one.
Returns
-------
c: 3x3x3x3 np.ndarray
... | 28,398 |
def get_cymon_feed_size(jwt, feed_id):
"""Determine the number of results a feed will return (max: 1000).
Params:
- jwt: (type: string) JWT token.
- feed_id: (type: string) Cymon feed ID.
Returns:
- total: (type: int) feed size.
"""
try:
today = datetime.utcnow()
thresh... | 28,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.