content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def image_model_saver(image_model, model_type, output_directory, training_dict, labels1, labels2, preds, results1, results2):
"""
Saves Keras image model and other outputs
image_model: Image model to be saved
model_type (string): Name of model
output_directory: Directory to folder to save... | 19,100 |
def predicted_orders(
daily_order_summary: pd.DataFrame, order_forecast_model: Tuple[float, float]
) -> pd.DataFrame:
"""Predicted orders for the next 30 days based on the fit paramters"""
a, b = order_forecast_model
start_date = daily_order_summary.order_date.max()
future_dates = pd.date_range(star... | 19,101 |
def _try_command_line(command_line):
"""Returns the output of a command line or an empty string on error."""
_logging.debug("Running command line: %s" % command_line)
try:
return subprocess.check_output(command_line, stderr=subprocess.STDOUT)
except Exception as e:
_print_process_error(command_line, e)
... | 19,102 |
def eval_loop(model, ldr, device):
"""Runs the evaluation loop on the input data `ldr`.
Args:
model (torch.nn.Module): model to be evaluated
ldr (torch.utils.data.DataLoader): evaluation data loader
device (torch.device): device inference will be run on
Returns:
list: l... | 19,103 |
def get_total_frts():
"""
Get total number of FRTs for a single state.
Arguments:
Returns:
{JSON} -- Returns headers of the columns and data in list
"""
query = """
SELECT
place.state AS state
, COUNT(DISTINCT frt.id) AS state_total
FROM
... | 19,104 |
def test_from_transform():
"""Initialize from inverse of q0 via transform matrix"""
q = Quat(q0.transform.transpose())
assert np.allclose(q.q[0], -0.26853582)
assert np.allclose(q.q[1], 0.14487813)
assert np.allclose(q.q[2], -0.12767944)
assert np.allclose(q.q[3], 0.94371436)
q = Quat(q0.tr... | 19,105 |
def newton_sqrt(n: float, a: float) -> float:
"""Approximate sqrt(n) starting from a, using the Newton-Raphson method."""
r = within(0.00001, repeat_f(next_sqrt_approx(n), a))
return next(r) | 19,106 |
def prismatic(xyz, rpy, axis, qi):
"""Returns the dual quaternion for a prismatic joint.
"""
# Joint origin rotation from RPY ZYX convention
roll, pitch, yaw = rpy[0], rpy[1], rpy[2]
# Origin rotation from RPY ZYX convention
cr = cs.cos(roll/2.0)
sr = cs.sin(roll/2.0)
cp = cs.cos(pitch/2... | 19,107 |
def markov_chain(bot_id, previous_posts):
"""
Caches are triplets of consecutive words from the source
Beginning=True means the triplet was the beinning of a messaeg
Starts with a random choice from the beginning caches
Then makes random choices from the all_caches set, constructing a markov chain
... | 19,108 |
def SurfaceNet_fn_trainVal(N_viewPairs4inference, default_lr, input_cube_size, D_viewPairFeature, \
num_hidden_units, CHANNEL_MEAN, return_train_fn=True, return_val_fn=True, with_weight=True):
"""
This function only defines the train_fn and the val_fn while training process.
There are 2 trainin... | 19,109 |
def test_bandpass_image():
"""Cube class: testing bandpass_image"""
shape = (7, 2, 2)
# Create a rectangular shaped bandpass response whose ends are half
# way into pixels.
wavelengths = np.array([1.0, 2.0, 3.0, 4.0, 5.0])
sensitivities = np.array([1.0, 1.0, 1.0, 1.0, 1.0])
# Specify a r... | 19,110 |
def _assign_data_radial(root, sweep="sweep_1"):
"""Assign from CfRadial1 data structure.
Parameters
----------
root : xarray.Dataset
Dataset of CfRadial1 file
sweep : str, optional
Sweep name to extract, default to first sweep. If None, all sweeps are
extracted into a list.
... | 19,111 |
def get_memory_usage():
"""This method returns the percentage of total memory used in this machine"""
stats = get_memstats()
mfree = float(stats['buffers']+stats['cached']+stats['free'])
return 1-(mfree/stats['total']) | 19,112 |
def gamma0(R, reg=1e-13, symmetrize=True):
"""Integrals over the edges of a triangle called gamma_0 (line charge potentials).
**NOTE: MAY NOT BE VERY PRECISE FOR POINTS DIRECTLY AT TRIANGLE
EDGES.**
Parameters
----------
R : (N, 3, 3) array of points (Neval, Nverts, xyz)
Returns
-----... | 19,113 |
def is_even(x):
""" True if obj is even. """
return (x % 2) == 0 | 19,114 |
def get_http_proxy():
"""
Get http_proxy and https_proxy from environment variables.
Username and password is not supported now.
"""
host = conf.get_httpproxy_host()
port = conf.get_httpproxy_port()
return host, port | 19,115 |
def get_parser_udf(
structural=True, # structural information
blacklist=["style", "script"], # ignore tag types, default: style, script
flatten=["span", "br"], # flatten tag types, default: span, br
language="en",
lingual=True, # lingual information
lingual_parser=None,
strip=True,
r... | 19,116 |
def img_preprocess2(image, target_shape,bboxes=None, correct_box=False):
"""
RGB转换 -> resize(resize不改变原图的高宽比) -> normalize
并可以选择是否校正bbox
:param image_org: 要处理的图像
:param target_shape: 对图像处理后,期望得到的图像shape,存储格式为(h, w)
:return: 处理之后的图像,shape为target_shape
"""
h_target, w_target = target_shap... | 19,117 |
def pivot_timeseries(df, var_name, timezone=None):
"""
Pivot timeseries DataFrame and shift UTC by given timezone offset
Parameters
----------
df : pandas.DataFrame
Timeseries DataFrame to be pivoted with year, month, hour columns
var_name : str
Name for new column describing da... | 19,118 |
def _preprocess_stored_query(query_text, config):
"""Inject some default code into each stored query."""
ws_id_text = " LET ws_ids = @ws_ids " if 'ws_ids' in query_text else ""
return '\n'.join([
config.get('query_prefix', ''),
ws_id_text,
query_text
]) | 19,119 |
def handler_request_exception(response: Response):
"""
Args:
response (Response):
"""
status_code = response.status_code
data = response.json()
if "details" in data and len(data.get("details")) > 0:
data = data.get("details")[0]
kwargs = {
"error_code": data.get("err... | 19,120 |
def n_real_inputs():
"""This gives the number of 'real' inputs. This is determined by trimming away inputs that
have no connection to the logic. This is done by the ABC alias 'trm', which changes the current
circuit. In some applications we do not want to change the circuit, but just to know how may inputs
... | 19,121 |
def get_stats_for_dictionary_file(dictionary_path):
"""Calculate size of manual and recommended sections of given dictionary."""
if not dictionary_path or not os.path.exists(dictionary_path):
return 0, 0
dictionary_content = utils.read_data_from_file(
dictionary_path, eval_data=False)
dictionaries = ... | 19,122 |
def log_speed(speed_logs, message):
"""Measures and logs the duration of a context.
Parameters
----------
speed_logs : list of str
Text logs regarding processing speed.
message : str
A log message, which will be processed using ``string.format()``
with the duration of a cont... | 19,123 |
def delete_bucket_tagging(Bucket=None):
"""
Deletes the tags from the bucket.
To use this operation, you must have permission to perform the s3:PutBucketTagging action. By default, the bucket owner has this permission and can grant this permission to others.
The following operations are related to Delet... | 19,124 |
def mlrPredict(W, data):
"""
mlrObjFunction predicts the label of data given the data and parameter W
of Logistic Regression
Input:
W: the matrix of weight of size (D + 1) x 10. Each column is the weight
vector of a Logistic Regression classifier.
X: the data matrix of size... | 19,125 |
def create_app():
"""Create Flask application."""
app = Flask(__name__, instance_relative_config=False)
from .error_pages import add_error_pages
app = add_error_pages(app)
app.config.from_object("config")
with app.app_context():
from .global_variables import init_global
init_g... | 19,126 |
def process_integration(request, case_id):
"""Method to process case."""
try:
case = OVCBasicCRS.objects.get(case_id=case_id, is_void=False)
county_code = int(case.county)
const_code = int(case.constituency)
county_id, const_id = 0, 0
crs_id = str(case_id).replace('-', ''... | 19,127 |
def get_aabb(pts):
"""axis-aligned minimum bounding box"""
x, y = np.floor(pts.min(axis=0)).astype(int)
w, h = np.ceil(pts.ptp(axis=0)).astype(int)
return x, y, w, h | 19,128 |
def _solve(f, *symbols, **flags):
"""Return a checked solution for f in terms of one or more of the
symbols. A list should be returned except for the case when a linear
undetermined-coefficients equation is encountered (in which case
a dictionary is returned).
If no method is implemented to solve t... | 19,129 |
def get_object_ratio(obj):
"""Calculate the ratio of the object's size in comparison to the whole image
:param obj: the binarized object image
:type obj: numpy.ndarray
:returns: float -- the ratio
"""
return numpy.count_nonzero(obj) / float(obj.size) | 19,130 |
def get_region(ds, region):
""" Return a region from a provided DataArray or Dataset
Parameters
----------
region_mask: xarray DataArray or list
Boolean mask of the region to keep
"""
return ds.where(region, drop=True) | 19,131 |
def read_borehole_file(path, fix_df=True):
"""Returns the df with the depths for each borehole in one single row instead
instead being each chunck a new row"""
df = pd.read_table(path,
skiprows=41,
header=None,
sep='\t',
... | 19,132 |
def cpl_parse(path):
""" Parse DCP CPL """
cpl = generic_parse(
path, "CompositionPlaylist",
("Reel", "ExtensionMetadata", "PropertyList"))
if cpl:
cpl_node = cpl['Info']['CompositionPlaylist']
cpl_dcnc_parse(cpl_node)
cpl_reels_parse(cpl_node)
return cpl | 19,133 |
def notfound():
"""Serve 404 template."""
return make_response(render_template('404.html'), 404) | 19,134 |
def read_network(file: str) -> Tuple[int, int, List[int]]:
"""
Read a Boolean network from a text file:
Line 1: number of state variables
Line 2: number of control inputs
Line 3: transition matrix of the network (linear representation of a logical matrix)
:param file: a text file
... | 19,135 |
def copy(srcpath, destpath, pattern=None, pred=_def_copy_pred):
"""
Copies all files in the source path to the specified destination path. The
source path can be a file, in which case that file will be copied as long as
it matches the specified pattern.
If the source path is a directory, all di... | 19,136 |
def bundle_products_list(request,id):
"""
This view Renders Bundle Product list Page """
bundle = get_object_or_404(Bundle, bundle_id=id)
bundleProd = BundleProducts.objects.filter(bundle=id)
stocks = Stock.objects.all()
context = {
"title": "Bundle Products List",
"bundle": b... | 19,137 |
def rot_x(theta):
"""
Rotation matrix around X axis
:param theta: Rotation angle in radians, right-handed
:return: Rotation matrix in form of (3,3) 2D numpy array
"""
return rot_axis(0,theta) | 19,138 |
def SetupPushNotification(request, callback, customData = None, extraHeaders = None):
"""
Sets the Amazon Resource Name (ARN) for iOS and Android push notifications. Documentation on the exact restrictions can
be found at: http://docs.aws.amazon.com/sns/latest/api/API_CreatePlatformApplication.html. Current... | 19,139 |
def ValidateEntryPointNameOrRaise(entry_point):
"""Checks if a entry point name provided by user is valid.
Args:
entry_point: Entry point name provided by user.
Returns:
Entry point name.
Raises:
ArgumentTypeError: If the entry point name provided by user is not valid.
"""
return _ValidateArgum... | 19,140 |
def save_volfile(array, filename, affine=None):
"""
Saves an array to nii, nii.gz, or npz format.
Parameters:
array: The array to save.
filename: Filename to save to.
affine: Affine vox-to-ras matrix. Saves LIA matrix if None (default).
"""
if filename.endswith(('.nii', '.ni... | 19,141 |
def park2_4_z(z, x):
""" Computes the Parkd function. """
y1 = x[0][0]
y2 = x[0][1]
chooser = x[1]
y3 = (x[2] - 103.0) / 91.0
y4 = x[3] + 10.0
x = [y1, y2, y3, y4]
if chooser == 'rabbit':
ret = sub_park_1(x)
elif chooser == 'dog':
ret = sub_park_2(x)
elif chooser == 'gerbil':
ret = sub_p... | 19,142 |
def get_string_coords(line):
"""return a list of string positions (tuple (start, end)) in the line
"""
result = []
for match in re.finditer(STRING_RGX, line):
result.append( (match.start(), match.end()) )
return result | 19,143 |
def array_from_pixbuf(p):
"""Convert from GdkPixbuf to numpy array"
Args:
p (GdkPixbuf): The GdkPixbuf provided from some window handle
Returns:
ndarray: The numpy array arranged for the pixels in height, width, RGBA order
"""
w,h,c,r=(p.get_width(), p.get_height(), p.get_n_channel... | 19,144 |
def entropy(x,k=3,base=2):
""" The classic K-L k-nearest neighbor continuous entropy estimator
x should be a list of vectors, e.g. x = [[1.3],[3.7],[5.1],[2.4]]
if x is a one-dimensional scalar and we have four samples
"""
assert k <= len(x)-1, "Set k smaller than num. samples - 1"
d = len(x[0])
N... | 19,145 |
def respond_to_command(slack_client, branch, thread_ts):
"""Take action on command."""
logging.debug("Responding to command: Deploy Branch-%s", branch)
is_production = False
if branch == 'develop':
message = "Development deployment started"
post_to_channel(slack_client, message, thread_t... | 19,146 |
def build_bazel_rules_nodejs(**kwargs):
"""Rule node.js
"""
name = "build_bazel_rules_nodejs"
ref = get_ref(name, "d334fd8e2274fb939cf447106dced97472534e80", kwargs)
sha256 = get_sha256(name, "5c69bae6545c5c335c834d4a7d04b888607993027513282a5139dbbea7166571", kwargs)
github_archive(name, "bazelb... | 19,147 |
def write_file(graph, filename, mode=None):
""" write file
Arguments:
----------
graph {pydotplus.graphviz.Dot} -- graph
filename {str} -- file name
Keyword Arguments:
------------------
mode {str} -- type of function (default: None}
Raises:
-------
Excepti... | 19,148 |
def s3upload_start(
request: HttpRequest,
workflow: Optional[Workflow] = None,
) -> HttpResponse:
"""Upload the S3 data as first step.
The four step process will populate the following dictionary with name
upload_data (divided by steps in which they are set
STEP 1:
initial_column_names: L... | 19,149 |
def search_explorations(query, limit, sort=None, cursor=None):
"""Searches through the available explorations.
args:
- query_string: the query string to search for.
- sort: a string indicating how to sort results. This should be a string
of space separated values. Each value should start ... | 19,150 |
def find_resourceadapters():
"""
Finds all resource adapter classes.
:return List[ResourceAdapter]: a list of all resource adapter classes
"""
subclasses = []
def look_for_subclass(module_name):
module = __import__(module_name)
d = module.__dict__
for m in module_name... | 19,151 |
def print_scale(skill, points):
"""Return TeX lines for a skill scale."""
lines = ['\\cvskill{']
lines[0] += skill
lines[0] += '}{'
lines[0] += str(points)
lines[0] += '}\n'
return lines | 19,152 |
def test_add_op_scalar():
"""
Program:
fn (x, y) {
return x + y;
}
"""
x = relay.var('x', shape=())
y = relay.var('y', shape=())
func = relay.Function([x, y], add(x, y))
x_data = np.array(10.0, dtype='float32')
y_data = np.array(1.0, dtype='float32')
check... | 19,153 |
def getsize(file: Union[TextIO, BinaryIO]) -> int:
"""
Overview:
Get the size of the given ``file`` stream.
:param file: File which size need to access.
:return: File's size.
Examples::
>>> import io
>>> from hbutils.file import getsize
>>>
>>> with io.Bytes... | 19,154 |
def print_(fh, *args):
"""Implementation of perl $fh->print method"""
global OS_ERROR, TRACEBACK, AUTODIE
try:
print(*args, end='', file=fh)
return True
except Exception as _e:
OS_ERROR = str(_e)
if TRACEBACK:
cluck(f"print failed: {OS_ERROR}",skip=2)... | 19,155 |
def _expm_multiply_interval(A, B, start=None, stop=None,
num=None, endpoint=None, balance=False, status_only=False):
"""
Compute the action of the matrix exponential at multiple time points.
Parameters
----------
A : transposable linear operator
The operator whose exponential is of ... | 19,156 |
def subprocess(mocker):
""" Mock the subprocess and make sure it returns a value """
def with_return_value(value: int = 0, stdout: str = ""):
mock = mocker.patch(
"subprocess.run", return_value=CompletedProcess(None, returncode=0)
)
mock.returncode.return_value = value
... | 19,157 |
def ljust(string, width):
"""
A version of ljust that considers the terminal width (see
get_terminal_width)
"""
width -= get_terminal_width(string)
return string + " " * width | 19,158 |
def device_sort (device_set):
"""Sort a set of devices by self_id. Can't be used with PendingDevices!"""
return sorted(device_set, key = operator.attrgetter ('self_id')) | 19,159 |
def _ontology_value(curie):
"""Get the id component of the curie, 0000001 from CL:0000001 for example."""
return curie.split(":")[1] | 19,160 |
def get_current_joblist(JobDir):
""" -function to return current, sorted, joblist in /JobDir """
if os.path.exists(JobDir):
jobdirlist = os.walk(JobDir).next()[1]
jobdirlist.sort()
return jobdirlist | 19,161 |
def save_keys(profile, access_token):
"""
Save keys to ~/.weibowarc
"""
filename = default_config_filename()
save_config(filename, profile, access_token)
print("Keys saved to", filename) | 19,162 |
def readpacket( timeout=1000, hexdump=False ):
"""Reads a HP format packet (length, data, checksum) from device.
Handles error recovery and ACKing.
Returns data or prints hexdump if told so.
"""
data = protocol.readpacket()
if hexdump == True:
print hpstr.tohexstr( data )
else:
... | 19,163 |
def df_down_next_empty_pos(df, pos):
"""
Given a position `pos` at `(c, r)`, reads down column `c` from row `r` to find the next
empty cell.
Returns the position of that cell if found, or `None` otherwise.
"""
return df_down_next_matching_pos(df, pos, pd.isna) | 19,164 |
def day(stats):
"""
Returns a random day action function based on your decided day action
:return: Function tht will give a random day action
"""
# Later versions should read in numbers/booleans to determine this first statement
input("As the sun rises it marks a new day. What will you do?")
... | 19,165 |
def optimise_f2_thresholds(y, p, verbose=False, resolution=100):
"""Optimize individual thresholds one by one. Code from anokas.
Inputs
------
y: numpy array, true labels
p: numpy array, predicted labels
"""
n_labels = y.shape[1]
def mf(x):
p2 = np.zeros_like(p)
for i in... | 19,166 |
def ipv6_generator():
"""A generator for keys (type ipv6) that will skip some keys and repeat
most, just for the sake of a good spread of keys. Completely random
offsets are generated.
"""
min_ = randint(1,100)
max_ = randint(min_, 100000)
cur = min_
off = randrange(4294967296)
whi... | 19,167 |
def holding_vars():
""" input
This is experimental, used to indicate unbound (free) variables in
a sum or list comprehensive.
This is inspired by Harrison's {a | b | c} set comprehension notation.
>>> pstream(holding_vars(),', holding x,y,z')
Etok(holding_vars,', holding x , y , z')
... | 19,168 |
def select_with_several_genes(accessions, name, pattern,
description_items=None,
attribute='gene',
max_items=3):
"""
This will select the best description for databases where more than one
gene (or other attribute) map... | 19,169 |
def list_messages_matching_query(service, user_id, query=''):
"""List all Messages of the user's mailbox matching the query.
Args:
service: Authorized Gmail API service instance.
user_id: User's email address. The special value "me"
can be used to indicate the authenticated user.
query:... | 19,170 |
def write_to_string(input_otio, **profile_data):
"""
:param input_otio: Timeline, Track or Clip
:param profile_data: Properties passed to the profile tag describing
the format, frame rate, colorspace and so on. If a passed Timeline has
`global_start_time` set, the frame rate will be set automatical... | 19,171 |
def parse_IS(reply: bytes, device: str):
"""Parses the reply to the shutter IS command."""
match = re.search(b"\x00\x07IS=([0-1])([0-1])[0-1]{6}\r$", reply)
if match is None:
return False
if match.groups() == (b"1", b"0"):
if device in ["shutter", "hartmann_right"]:
return ... | 19,172 |
def quatXYZWFromRotMat(rot_mat):
"""Convert quaternion from rotation matrix"""
quatWXYZ = quaternions.mat2quat(rot_mat)
quatXYZW = quatToXYZW(quatWXYZ, 'wxyz')
return quatXYZW | 19,173 |
def schema_is_current(db_connection: sqlite3.Connection) -> bool:
"""
Given an existing database, checks to see whether the schema version in the existing
database matches the schema version for this version of Gab Tidy Data.
"""
db = db_connection.cursor()
db.execute(
"""
selec... | 19,174 |
def xattr_writes_supported(path):
"""
Returns True if the we can write a file to the supplied
path and subsequently write a xattr to that file.
"""
try:
import xattr
except ImportError:
return False
def set_xattr(path, key, value):
xattr.setxattr(path, "user.%s" % ke... | 19,175 |
def end(pstats_file):
"""Ends yappi profiling session, saves the profilinf info to a CProfile pstats file, and pretty-prints it to the console."""
yappi.stop()
func_stats = yappi.get_func_stats()
if func_stats:
_rows = []
for _stat in func_stats._as_dict:
if '/Spardaqus/' in ... | 19,176 |
def _lovasz_softmax(probabilities, targets, classes="present", per_image=False, ignore=None):
"""The multiclass Lovasz-Softmax loss.
Args:
probabilities: [B, C, H, W]
class probabilities at each prediction (between 0 and 1).
Interpreted as binary (sigmoid) output
wit... | 19,177 |
def encodeDERTRequest(negoTypes = [], authInfo = None, pubKeyAuth = None):
"""
@summary: create TSRequest from list of Type
@param negoTypes: {list(Type)}
@param authInfo: {str} authentication info TSCredentials encrypted with authentication protocol
@param pubKeyAuth: {str} public key encrypted wit... | 19,178 |
def p_cmdexpr_dbinspect(p):
"""cmdexpr : DBINSPECT
| DBINSPECT arglist
| DBINSPECT MACRO""" | 19,179 |
def remove_collection(browse_layer):
""" Remove Sx-Cat collection. """
collection_name = browse_layer.browse_type
logger.info("Removing Sx-Cat collection '%s'.", collection_name)
return_code = _sxcat_command(["remove", collection_name])
if return_code != 0:
logger.warning(
"Fai... | 19,180 |
def _crossCorrelations(queue, n_atoms, array, variances, indices):
"""Calculate covariance-matrix for a subset of modes."""
n_modes = len(indices)
arvar = (array[:, indices] * variances[indices]).T.reshape((n_modes,
n_atoms, 3))
array = ar... | 19,181 |
def describe_config_rule_evaluation_status(ConfigRuleNames=None, NextToken=None, Limit=None):
"""
Returns status information for each of your AWS managed Config rules. The status includes information such as the last time AWS Config invoked the rule, the last time AWS Config failed to invoke the rule, and the r... | 19,182 |
def generate_s3_strings(path):
"""Generates s3 bucket name, s3 key and s3 path with an endpoint from a path
with path (string): s3://BUCKETNAME/KEY
x --> path.find(start) returns index 0 + len(start) returns 5 --> 0 + 5 = 5
Y --> path[len(start):] = BUCKENAME/KEY --> .find(end) looking for f... | 19,183 |
def hierholzer(network: Network, source=0):
""" Hierholzer's algorithm for finding an Euler cycle
Args:
network (Network): network object
source(int): node where starts (and ends) the path
Raises:
NotEulerianNetwork: if exists at least one node with odd degree
NotNetworkNod... | 19,184 |
def RemoveChromeBrowserObjectFiles(chromeos_root, board):
"""Remove any object files from all the posible locations."""
out_dir = os.path.join(
GetChrootPath(chromeos_root),
'var/cache/chromeos-chrome/chrome-src/src/out_%s' % board)
if os.path.exists(out_dir):
shutil.rmtree(out_dir)
logger.Get... | 19,185 |
def fit1d(xdata,zdata,degree=1,reject=0,ydata=None,plot=None,plot2d=False,xr=None,yr=None,zr=None,xt=None,yt=None,zt=None,pfit=None,log=False,colorbar=False,size=5) :
"""
Do a 1D polynomial fit to data set and plot if requested
Args:
xdata : independent variable
zdata : dependent variable to be f... | 19,186 |
def nucleus_sampling(data, p, replace=0, ascending=False, above=True):
"""
:param tensor data: Input data
:param float p: Probability for filtering (or be replaced)
:param float replace: Default value is 0. If value is provided, input data will be replaced by this value
if data match criteria.
... | 19,187 |
def mark_ready_for_l10n_revision(request, document_slug, revision_id):
"""Mark a revision as ready for l10n."""
revision = get_object_or_404(Revision, pk=revision_id,
document__slug=document_slug)
if not revision.document.allows(request.user, 'mark_ready_for_l10n'):
... | 19,188 |
def test_get_weather_observed(bear_lake_observed, manchester_vermont_observed):
"""Tests the get_weather_observed() function.
"""
# Weather observed - Bear Lake, RMNP, Colorado
# Test object type
assert isinstance(bear_lake_observed, gpd.geodataframe.GeoDataFrame)
# Test precip amount
asser... | 19,189 |
def is_all_maxed_out(bad_cube_counts, bad_cube_maximums):
"""Determines whether all the cubes of each type are at their maximum
amounts."""
for cube_type in CUBE_TYPES:
if bad_cube_counts[cube_type] < bad_cube_maximums[cube_type]:
return False
return True | 19,190 |
def get_local_vars(*args):
"""
get_local_vars(prov, ea, out) -> bool
"""
return _ida_dbg.get_local_vars(*args) | 19,191 |
def items(chatlog_path, out_path, to, realm):
"""
Parse chatlog items into LOKI format.
"""
chatlog_path = Path(chatlog_path).absolute()
out_path = Path(out_path).absolute()
click.echo(f"Parsing: {chatlog_path.as_posix()}")
click.echo(f"Writing items into {out_path.as_posix()}")
with op... | 19,192 |
def gcc():
"""
getCurrentCurve
Get the last curve that was added to the last plot plot
:return: The last curve
:rtype: pg.PlotDataItem
"""
plotWin = gcf()
try:
return plotWin.plotWidget.plotItem.dataItems[-1]
except IndexError:
return None | 19,193 |
def test_structure_roundtrip_precision(new_workdir):
"""Testing structure roundtrip precision ase->aiida->cp2k->aiida->ase..."""
import ase.build
import numpy as np
from aiida.engine import run
from aiida.plugins import CalculationFactory
from aiida.orm import Dict, StructureData
computer... | 19,194 |
async def more_lights(hass, lights):
"""Provide lights 'light.light_3' and 'light.light_4'."""
await make_lights(hass, ['light_3', 'light_4'], area_name="area_2") | 19,195 |
def nfs_setup(cluster: str, headers_inc: str):
"""Demonstrates NFS Setup using REST APIs."""
print("Demonstrates NFS Setup using REST APIs.")
print("=======================================")
print()
show_svm(cluster, headers_inc)
print()
svm_name = input(
"Choose the SVM on which you... | 19,196 |
def searchDevice(search):
"""
Method that searches the ExtraHop system for a device that
matches the specified search criteria
Parameters:
search (dict): The device search criteria
Returns:
dict: The metadata of the device that matches the criteria
"""
url =... | 19,197 |
def regularmeshH8(nelx, nely, nelz, lx, ly, lz):
""" Creates a regular H8 mesh.
Args:
nelx (:obj:`int`): Number of elements on the X-axis.
nely (:obj:`int`): Number of elements on the Y-axis.
nelz (:obj:`int`): Number of elements on the Z-axis.
lx (:obj:`float`): X-axis length.
... | 19,198 |
def test_run_component_compile_command_instance(tmp_path, capsys, instance_aware):
"""
Run the component compile command for a component with a postprocessing
filter
"""
component_name = "test-component"
instance_name = "test-instance"
_prepare_component(tmp_path, component_name)
if inst... | 19,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.