content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def RemoveContacts(client, obj_store, user_id, device_id, request):
"""Remove contacts."""
request['user_id'] = user_id
yield gen.Task(Operation.CreateAndExecute,
client,
user_id,
device_id,
'RemoveContactsOperation.Execute',
req... | 5,332,600 |
def test_get_meta_strings_wrong_type():
"""A call to Dataset.get_meta_strings is made with the wrong type
"""
d = Dataset("test_dataset")
with pytest.raises(TypeError):
d.get_meta_strings(42) | 5,332,601 |
def get_freesurfer_matrix_ras2vox():
"""
Get standard matrix to convert RAS coordinate to voxel index for Freesurfer conformed space volumes.
Get matrix to convert RAS coordinate to voxel index for Freesurfer conformed space volumes. See the documentation for get_freesurfer_matrix_vox2ras for background in... | 5,332,602 |
def parse_create_table(string):
"""Parse the create table sql query and return metadata
Args:
string(sql): SQL string from a SQL Statement
Returns:
table_data(dict): table_data dictionary for instantiating a table
"""
# Parse the base table definitions
table_data = to_dict(get_... | 5,332,603 |
def handle_volumes(region, config):
"""Try to attach volumes"""
volumes = config.get("volumes", {})
# attach ESB volumes first
if "ebs" in volumes:
handle_ebs_volumes(region, volumes.get("ebs"))
# then take care of any RAID definitions
if "raid" in volumes:
handle_raid_volumes(... | 5,332,604 |
def retrieve_context_connection_connection_by_id(uuid): # noqa: E501
"""Retrieve connection by ID
Retrieve operation of resource: connection # noqa: E501
:param uuid: ID of uuid
:type uuid: str
:rtype: Connection
"""
return 'do some magic!' | 5,332,605 |
def read_filenames(path):
"""
Read all file names from `path` and match them against FILENAME_REGEX.
Arguments:
- path: path to the directory containing CSV data files.
Returns:
- list of tuples of every filename and regex match to the CSV filename
format in the specified dir... | 5,332,606 |
def _sp_sleep_for(t: int) -> str:
"""Return the subprocess cmd for sleeping for `t` seconds."""
return 'python -c "import time; time.sleep({})"'.format(t) | 5,332,607 |
def verify_show_environment(dut, verify_str_list):
"""
To get show environment.
Author: Prudvi Mangadu (prudvi.mangadu@broadcom.com)
"""
command = "show environment"
output = utils.remove_last_line_from_string(st.show(dut, command, skip_tmpl=True))
result = True
for item in verify_str_li... | 5,332,608 |
def database():
"""In memory blank test database from the declarative model."""
engine = create_engine("sqlite:///:memory:", future=True)
session_maker = sessionmaker(
autocommit=False,
autoflush=False,
bind=engine,
future=True,
)
Base.metadata.create_all(engine) # c... | 5,332,609 |
def profile_time(trace_name,
name,
enabled=True,
stream=None,
end_stream=None):
"""Print time spent by CPU and GPU.
Useful as a temporary context manager to find sweet spots of code
suitable for async implementation.
From: https://github.co... | 5,332,610 |
def plot() -> None:
"""Open the interactive plotting window."""
if figure.data.z2n.size == 0:
click.secho("The periodogram was not calculated yet.", fg='yellow')
else:
figure.plot_figure()
plt() | 5,332,611 |
def get_labelset_keys():
"""get labelset keys
Given DATA_CFG, return slideviewer labelsets
Args:
none
Returns:
list: a list of labelset names
"""
cfg = ConfigSet()
label_config = cfg.get_value(path=const.DATA_CFG+'::LABEL_SETS')
labelsets = [cfg.get_value(... | 5,332,612 |
def gen_mf_html(pypeit_file, qa_path):
""" Generate the HTML for a MasterFrame set
Args:
pypeit_file (str):
Name of the PypeIt file, no path
qa_path (str):
Path to the QA folder
"""
# TODO: Can this instead just use the pypeit file?
# Read calib file
cali... | 5,332,613 |
def create_instrument_level_pattern(instrument_symbols: List[str]) -> str:
"""Creates a regular expression pattern to target all the instrument symbols in a list.
The function creates a regular expression pattern to target, within a specific DC
message, the portion of the message containing the complete in... | 5,332,614 |
def localtime(nist_lookup=0,
localtime=DateTime.localtime,utctime=utctime):
""" Returns the current local time as DateTime instance.
Same notes as for utctime().
"""
return localtime(utctime(nist_lookup).gmticks()) | 5,332,615 |
def device_now():
"""Return datetime object constructed from 'now' on device."""
cmd = "adb shell date '+%Y:%m:%d:%H:%M:%S'"
lines = u.docmdlines(cmd)
line = lines.pop(0)
if line is None:
u.error("unable to interpret output from '%s'" % cmd)
d = line.split(":")
try:
dt = datetime(int(d[0]), int(d[... | 5,332,616 |
def copy_safe_request(request):
"""
Copy selected attributes from a request object into a new fake request object. This is needed in places where
thread safe pickling of the useful request data is needed.
"""
meta = {
k: request.META[k]
for k in HTTP_REQUEST_META_SAFE_COPY
if... | 5,332,617 |
def sha256(firmware_filename, firmware_size=None):
"""Returns the sha256 hash of the firmware"""
hasher = hashlib.sha256()
# If firmware size is supplied, then we want a sha256 of the firmware with its header
if firmware_size is not None:
hasher.update(b"\x00" + firmware_size.to_bytes(4, "little... | 5,332,618 |
async def async_unload_entry(hass, entry):
"""Unload a config entry."""
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
if unload_ok:
hass.data[DOMAIN][entry.entry_id].stop()
return unload_ok | 5,332,619 |
def is_serial_increased(old, new):
""" Return true if serial number was increased using RFC 1982 logic. """
old, new = (int(n) for n in [old, new])
diff = (new - old) % 2**32
return 0 < diff < (2**31 - 1) | 5,332,620 |
def generate_docs():
"""
info: generates_docs for salt community
:return:
"""
path = '/'.join(os.path.dirname(os.path.realpath(__file__)).split('\\'))
os.system('salt-call --local --file-root={0} state.sls generate_docs'.format(path)) | 5,332,621 |
def svn_relpath_skip_ancestor(parent_relpath, child_relpath):
"""svn_relpath_skip_ancestor(char const * parent_relpath, char const * child_relpath) -> char const *"""
return _core.svn_relpath_skip_ancestor(parent_relpath, child_relpath) | 5,332,622 |
def rnn_model(input_dim, units, activation, output_dim=29):
""" Build a recurrent network for speech
"""
# Main acoustic input
input_data = Input(name='the_input', shape=(None, input_dim))
# Add recurrent layer
simp_rnn = GRU(units, activation=activation,
return_sequences=True, implement... | 5,332,623 |
def _pad_statistic(arr, pad_width, stat_length, stat_op):
"""
pads the array with values calculated along the given axis, used in mode: "maximum",
"minimum", "mean"
"""
ndim = arr.ndim
shape = arr.shape
if stat_length is None:
stat_length = _make_stat_length(shape)
else:
... | 5,332,624 |
def register_do(mysql, json):
"""
helper function that registers data objects into MySQL DB
@param mysql: a mysql object for MySQL database
@param json: metadata that contains information for data source and device
"""
cnx = mysql.connect()
cursor = cnx.cursor()
dataSource = json... | 5,332,625 |
def reraise_wrapped_error(error: Exception):
"""Wraps failures with better error messages.
Args:
error: The exception. We must be inside a raise.
Raises:
ImportError: Typically if there is a version mismatch.
"""
if 'undefined symbol' in str(error).lower():
six.reraise(ImportError,
... | 5,332,626 |
def split_amount(amount, splits, places=2):
"""Return list of ``splits`` amounts where sum of items equals ``amount``.
>>> from decimal import Decimal
>>> split_amount(Decimal('12'), 1)
Decimal('12.00')
>>> split_amount(Decimal('12'), 2)
[Decimal('6.00'), Decimal('6.00')]
Amounts have a ma... | 5,332,627 |
def shift_compare_date(df, date_field, smaller_eq_than_days=1, compare_with_next=False):
""" ATENTION: This Dataframe need to be sorted!!!
"""
from datetime import timedelta
if compare_with_next:
s = (
(df[date_field].shift(-1) - df[date_field]
) <= timedelta(days=small... | 5,332,628 |
def format_alleles(variant):
"""Gets a string representation of the variant's alleles.
Args:
variant: nucleus.genomics.v1.Variant.
Returns:
A string ref_bases/alt1,alt2 etc.
"""
return '{}/{}'.format(variant.reference_bases, ','.join(
variant.alternate_bases)) | 5,332,629 |
def _validate_inputs(input_list, input_names, method_name):
"""
This method will validate the inputs of other methods.
input_list is a list of the inputs passed to a method.
input_name is a list of the variable names associated with
input_list
method_name is the name of the method whose input... | 5,332,630 |
def install(app=None, timeout=0.02, engine=None):
"""
Creates a :class:`~PySide.QtCore.QTimer` instance that will be triggered
continuously to call :func:`Engine.poll() <pants.engine.Engine.poll>`,
ensuring that Pants remains responsive.
========= ======== ============
Argument Default De... | 5,332,631 |
def server_base_url(environ):
"""
Using information in tiddlyweb.config, construct
the base URL of the server, sans the trailing /.
"""
return '%s%s' % (server_host_url(environ), _server_prefix(environ)) | 5,332,632 |
def calc_ctrlg_ratio(rpl: sc2reader.resources.Replay,
pid: int) -> dict[str, float]:
"""Calculates the ratio between `ControlGroupEvents` and the union of
the `CommandEvents`, `SelectionEvents` and `ControlGroupCommand` sets
to quantify the players' level of awareness and use of this ... | 5,332,633 |
def data_exists(date, hour=None):
"""
Checks if there is a directory with daily data files for given date and hour(s)
Parameters
----------
date: str
Expected date format is yyyy/mm/dd
hour: int or array-like, default None
Specific hour(s) to check, has to be in the range of 0... | 5,332,634 |
def plot_single_roccurve(signals, bkgs, cut_function, cut_values, ax=None):
"""
Main routine for plotting a single roccurve
"""
# Get a default ax if none is given
if ax is None:
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(8,8))
ax = fig.gca()
# Plot the bas... | 5,332,635 |
def clear_screen(screen: pg.Surface, color=BACKGROUND) -> None:
"""Clears screen i.e. draws a rectangle that
covers the whole <screen> of color <BACKGROUND>"""
pg.draw.rect(screen, color, (0, 0, WIDTH, HEIGHT)) | 5,332,636 |
def draw_normal_surface(pcd, scale, estimation_params=None):
"""Draw and return a mesh of arrows of normal vectors for each point
in the given cloud
Parameters
----------
pcd : o3d.geometry.PointCloud
Input point cloud
scale : float
Scale of the default arrow which is 1 meter... | 5,332,637 |
def test_where_with_kwargs(CTX):
"""
Tests that subclasses of a class can be stored in the same collection.
:return:
"""
expected_dict = {
'Washington D.C.': {
'cityName': 'Washington D.C.',
'country': 'USA',
'capital': True,
'obj_type': "Muni... | 5,332,638 |
def texture_from_clusters(clusters):
""" Compute the GLCM texture properties from image clusters.
:param clusters: clusters of pixels representing sections of the image
:returns: DataFrame -- of texture features for every cluster.
"""
thetas = np.arange(0, np.pi, np.pi/8)
props = ['contrast', ... | 5,332,639 |
def parse_dict(input_data):
"""Return a rules dict of the format:
{
'light red': [(1, 'bright white'), (2, 'muted yellow')],
'dark orange': [(3, bright white), (4, muted yellow)],
'faded blue': [(0, 'bags')]
}
"""
bags = dict()
for line in input_data.split('\n'):
outer, ... | 5,332,640 |
def write_table_header(op2_file, fascii, table_name):
"""
Writes the beginning of an op2 table
Parameters
----------
op2_file : file
the op2 file object
table_name : str
the table name to write
"""
table0 = [
4, 2, 4,
8, table_name.encode('ascii'), 8,
... | 5,332,641 |
def extract_vars(samples_file_name,n_burnin,v_names,debug,stride=1):
"""From a file with samples in ascii format, with
the first line containing the label for each column, extract
the columns with the labels in v_names and return them
in a numpy array. Remove n_burnin samples from the top.
Only read... | 5,332,642 |
def distance_without_normalise(bin_image):
"""
Takes a binary image and returns a distance transform version of it.
"""
res = np.zeros_like(bin_image)
for j in range(1, bin_image.max() + 1):
one_cell = np.zeros_like(bin_image)
one_cell[bin_image == j] = 1
one_cell = distance_... | 5,332,643 |
def classify_sentiment(rows_per_file: int, senti4sd_pool_root: str,
inpath: str, outpath: str):
"""Classify sentiment in the inpath file using any classificationTask.sh
scripts found in the directory tree starting from senti4sd_pool_root.
Result is placed at outpath.
The input fi... | 5,332,644 |
def list_inventory():
""" Returns all of the Inventory """
app.logger.info('Request for inventory list')
inventory = []
category = request.args.get('category')
name = request.args.get('name')
condition = request.args.get('condition')
count = request.args.get('count')
available = request.... | 5,332,645 |
def parse_args():
"""Parse command line arguments"""
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input-dir', help="Directory which contains the input data", required=True)
parser.add_argument('-o', '--output-dir', help="Directory which will hold the output data", required=True)
p... | 5,332,646 |
def is_instance_method(obj):
"""Checks if an object is a bound method on an instance."""
if not isinstance(obj, MethodType):
return False # Not a method
elif obj.__self__ is None:
return False # Method is not bound
elif (
issubclass(obj.__self__.__class__, type)
or hasa... | 5,332,647 |
def _clean_empty_and_duplicate_authors_from_grobid_parse(authors: List[Dict]) -> List[Dict]:
"""
Within affiliation, `location` is a dict with fields <settlement>, <region>, <country>, <postCode>, etc.
Too much hassle, so just take the first one that's not empty.
"""
# stripping empties
clean_au... | 5,332,648 |
def save_weights(weights):
""" Saves the weights after the processing of video. """
if os.path.exists(WEIGHTS_DIR):
os.remove(WEIGHTS_DIR)
try:
os.stat('weights')
except:
os.mkdir('weights')
np.save(WEIGHTS_DIR, weights)
print("Weights saved successfully!") | 5,332,649 |
def get_distutils_display_options():
""" Returns a set of all the distutils display options in their long and
short forms. These are the setup.py arguments such as --name or --version
which print the project's metadata and then exit.
Returns
-------
opts : set
The long and short form d... | 5,332,650 |
def get_followers(api, user_id):
"""Returns list of followers"""
followers = []
next_max_id = ''
while next_max_id is not None:
_ = api.getUserFollowers(user_id, maxid=next_max_id)
followers.extend(api.LastJson.get('users', []))
next_max_id = api.LastJson.get('next_max_id', '')
... | 5,332,651 |
def inference(model_path, json_path, q='question', ref='reference answer', stud='student answers',
result_path='results.json'):
"""
Generate feedback to student answers and save to file
:param model_path: string / path to model
:param json_path: string / path to json file with data
:pa... | 5,332,652 |
def main(dataset='all'):
"""
Parameters
----------
dataset : string
Either 'all' or a path to a yaml symbol file.
"""
cfg = utils.get_database_configuration()
mysql = cfg['mysql_online']
connection = pymysql.connect(host=mysql['host'],
user=mysql[... | 5,332,653 |
def plot_graph_embedding(y_emb, labels, adj, line_alpha=0.2, s=7, title=""):
"""
Plots the visualization of graph-structured data
Args:
y_emb (np.array): low dimensional map of data points, matrix of size n x 2
labels (np.array): underlying class labels, matrix of size n x 1
adj (sci... | 5,332,654 |
def map(v, ds, de, ts, te):
"""\
Map the value v, in range [ds, de] to
the corresponding value in range [ts, te]
"""
d1 = de - ds
d2 = te - ts
v2 = v - ds
r = v2 / d1
return ts + d2 * r | 5,332,655 |
def get_Q_body(hs_type, Theta_SW_hs):
"""温水暖房用熱源機の筐体放熱損失 (2)
Args:
hs_type(str): 温水暖房用熱源機の種類
Theta_SW_hs(ndarray): 温水暖房用熱源機の往き温水温度
Returns:
ndarray: 温水暖房用熱源機の筐体放熱損失
"""
if hs_type in ['石油従来型暖房機', '石油従来型温水暖房機', '石油従来型給湯温水暖房機', '不明']:
# (2a)
return [234 * 3600 * 10... | 5,332,656 |
def softmax(inputs):
"""
Calculate the softmax for the give inputs (array)
:param inputs:
:return:
"""
return np.exp(inputs) / float(sum(np.exp(inputs))) | 5,332,657 |
def get_config_list(ranking, ckpt_path2is_3class):
"""Assemble a model list for a specific task based on the ranking.
In addition to bundling information about the ckpt_path and whether to
model_uncertainty, the config_list also lists the value of the metric to
aid debugging.
Args:
ranking... | 5,332,658 |
def _get_turn_angle(start_angle, target_angle):
"""
Difference in angle in the range -180 to +180 (where negative is counter clockwise)
Parameters
----------
start_angle, target_angle : float
Returns
-------
float
difference in angle.
"""
return _map_to_pm180(target_ang... | 5,332,659 |
def load(fname):
"""Load symbol from a JSON file.
You can also use pickle to do the job if you only work on python.
The advantage of load/save is the file is language agnostic.
This means the file saved using save can be loaded by other language binding of mxnet.
You also get the benefit being able... | 5,332,660 |
def filter_pairs(pairs):
"""returns pairs of with filter_pair()==True"""
return [pair for pair in pairs if filter_pair(pair)] | 5,332,661 |
def step_impl(context):
"""
:type context: behave.runner.Context
"""
assert context.is_compliant is True
logger.info("The car is compliant") | 5,332,662 |
def merge(list_geo, npts=5):
"""
merge a list of cad_geometries and update internal/external faces and connectivities
Args:
list_geo: a list of cad_geometries
Returns:
a cad_geometries
"""
geo_f = list_geo[0]
for geo in list_geo[1:]:
geo_f = geo_f.merge(geo, npts=np... | 5,332,663 |
async def test_internal_sketch_name(
command,
context,
node_before,
sketch_name,
gateway,
message_schema,
):
"""Test internal sketch name command."""
with context:
async for msg in gateway.listen():
assert message_schema.dump(msg) == command
break
for... | 5,332,664 |
def save_upstream(client, stage, data):
"""
Put a bunch of param values into AWS
"""
prefix = f"/jobbergate-api/{stage}"
for k, v in data.items():
client.put_parameter(
Name=f"{prefix}/{k}",
Value=v,
Type="String",
Overwrite=True,
)
... | 5,332,665 |
def imshow(image: Imagelike, module: str = None, **kwargs) -> None:
"""Show the given image.
FIXME[todo]:
Showing an image can be done in different ways:
- blocking=True: the execution of the main program is blocked.
The display will run an event loop to guarantee a responsive
GUI behaviour... | 5,332,666 |
def update(frame_number):
"""Creating stopping condition for the animation to reach stopping stage
The animation will carry on and update each frame as the agents move,
eat and interact with other agents in the environment. The animation
will stop running when the random state of 0.1 is reach... | 5,332,667 |
def terminate_processes_matching_cmd_line(match_strings,
kill=False,
exclude_strings=None):
"""Terminates processes matching particular command line (case sensitive)."""
if exclude_strings is None:
# By default, do not terminate... | 5,332,668 |
def test_atomic_language_max_length_4_nistxml_sv_iv_atomic_language_max_length_5_1(mode, save_output, output_format):
"""
Type atomic/language is restricted by facet maxLength with value 11.
"""
assert_bindings(
schema="nistData/atomic/language/Schema+Instance/NISTSchema-SV-IV-atomic-language-ma... | 5,332,669 |
def download_data():
"""Download data"""
if not PATH.exists():
command = ["download_chandra_obsid", f"{OBS_ID}"]
execute_command(command=command)
else:
log.info(f"Skipping download, {PATH} already exists.") | 5,332,670 |
def prepare_commonvoice(
corpus_dir: Pathlike,
output_dir: Pathlike,
languages: Union[str, Sequence[str]] = "auto",
splits: Union[str, Sequence[str]] = COMMONVOICE_DEFAULT_SPLITS,
num_jobs: int = 1,
) -> Dict[str, Dict[str, Dict[str, Union[RecordingSet, SupervisionSet]]]]:
"""
Returns the ma... | 5,332,671 |
def rmv_cmd(trgt):
"""Remove target with force"""
result = run_command(["rm", "-rf", trgt])
if result.returncode != 0:
raise Exception("Removing {} before testing failed!".
format(os.path.dirname(os.path.realpath(__file__))
+ trgt)) | 5,332,672 |
def plot_array_trans(pdata,a,copy=False):
"""
Warning!!!
----------
Latest Information: 22/05/2012 this is deprecated and plot_array_transg is used instead.
Purpose:
--------
Transform array according to speficication in list a. return a copy if copy is True.
Example:
--------
... | 5,332,673 |
def heartbeat_handler():
"""
Triggers SPM heartbeat and fires power on event when booting.
"""
try:
# Check if not in state on
if context["state"] != "on":
# Get current status
res = conn.status()
old_state = context["state"]
new_state ... | 5,332,674 |
def process_generate_api_token_data(post_data):
"""
This expects the post_data to contain an array called ``user_to_form``.
Each item in this array is of the form:
.. code-block:: python
'<UserID>.<form_prefix>' (i.e. '1.form-0')
Each form then may add two form data key-value pairs:
... | 5,332,675 |
def dummyfunc1():
"""
Returns
-------
Nothing!
Examples
--------
Nada
"""
pass | 5,332,676 |
def add_vcolor(hemis, mesh=None, name='color'):
"""Seems like `hemis` is color you wish to apply to currently selected mesh."""
from bpy import context as C
from bpy import data as D
if mesh is None:
mesh = C.scene.objects.active.data
elif isinstance(mesh, str):
mesh = D.meshes[mesh]... | 5,332,677 |
def gridSeach(model, parameters, features, response, train, test):
"""
This function performs a grid search over the parameter space.
It is simplistic and only allows certain range of values. If there
is a parameter in the models that needs to be a list it has to be modified.
"""
import i... | 5,332,678 |
def cvt_lambdef(node: pytree.Base, ctx: Ctx) -> ast_cooked.Base:
"""lambdef: 'lambda' [varargslist] ':' test"""
assert ctx.is_REF, [node]
name = xcast(ast_cooked.NameBindsNode, cvt(node.children[0], ctx.to_BINDING()))
ctx_func = new_ctx_from(ctx)
if len(node.children) == 4:
parameters = xcas... | 5,332,679 |
def tan(x) -> None:
"""
传入弧度值,计算正切。 示例:计算tan60°
- math.tan(math.radians(60))
1.732051"""
... | 5,332,680 |
def ischapter_name(text_str):
"""判断是否是章节名"""
if re.match(r'^第(.{1,9})([章节回卷集部篇])(\s*)(.*)', text_str):
return True
else:
return False | 5,332,681 |
def calc_mean_onbit_density(bitsets, number_of_bits):
"""Calculate the mean density of bits that are on in bitsets collection.
Args:
bitsets (list[pyroaring.BitMap]): List of fingerprints
number_of_bits: Number of bits for all fingerprints
Returns:
float: Mean on bit density
"... | 5,332,682 |
def logger_client():
"""Authentification and service delivery from gmail API
"""
creds = None
# The file token.pickle stores the user's access and refresh tokens,
# and is created automatically when the authorization flow
# completes for the first time.
if os.path.exists('token.pickle'):
... | 5,332,683 |
def get_parameters(path: str) -> List[Dict[str, Any]]:
"""
Retrieve parameters from AWS SSM Parameter Store. Decrypts any encrypted parameters.
Relies on the appropriate environment variables to authenticate against AWS:
https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-envvars.html
""... | 5,332,684 |
def normalizeUrl(url):
"""
ParseResult(scheme='https', netloc='www.tWitch.tv', path='/ludwig/clip/MoldyNiceMarjoramCharlieBitMe-6EbApxzSGbjacptE', params='', query='a=b&c=d', fragment='')
Wish I could convert clips like this:
https://www.twitch.tv/ludwig/clip/MoldyNiceMarjoramCharlieBitMe-6EbApxzSG... | 5,332,685 |
def _getPVGIS(lat, lon):
"""
This function uses the non-interactive version of PVGIS to extract a
tmy dataset to be used to predict VRE yields for future periods.
------ inputs ------
Latitude, in decimal degrees, south is negative.
Longitude, in decimal degrees, west is negative.
... | 5,332,686 |
def get_metric_key_samples(metricDict, metricNames, keyVal="means"):
"""
Returns a dictionary of samples for the given metric name, but only extracts
the samples for the given key
Args:
metricDict (dict): Dictionary of sampled metrics
metricNames (list): Names of the keys of the metric ... | 5,332,687 |
def apply_nonbonded(nodes, scaling=1.0, suffix=""):
""" Nonbonded in nodes. """
# TODO: should this be 9-6 or 12-6?
return {
"u%s"
% suffix: scaling
* esp.mm.nonbonded.lj_9_6(
x=nodes.data["x"],
sigma=nodes.data["sigma%s" % suffix],
epsilon=nodes.d... | 5,332,688 |
def swapi_films(episode):
"""
Gets the films listed in the api.
:param episode:
:return: response json
"""
response = requests.get(SWAPI_API + 'films/' + str(episode))
return response | 5,332,689 |
def prepare_qualifications(request, bids=[], lotId=None):
""" creates Qualification for each Bid
"""
new_qualifications = []
tender = request.validated["tender"]
if not bids:
bids = tender.bids
if tender.lots:
active_lots = [lot.id for lot in tender.lots if lot.status == "active"... | 5,332,690 |
def int_format(x):
"""
Format an integer:
- upcast to a (u)int64
- determine buffer size
- use snprintf
"""
x = upcast(x)
buf = flypy.runtime.obj.core.newbuffer(flypy.types.char, ndigits(x) + 1)
formatting.sprintf(buf, getformat(x), x)
return flypy.types.String(buf) | 5,332,691 |
def _resolve_atomtypes(topology_graph, typemap):
"""Determine the final atomtypes from the white- and blacklists."""
atoms = {
atom_idx: data for atom_idx, data in topology_graph.atoms(data=True)
}
for atom_id, atom in typemap.items():
atomtype = [
rule_name for rule_name in ... | 5,332,692 |
def main():
""" Main method """
window = Spiral()
window.setup()
arcade.run() | 5,332,693 |
def pyccparser2cbmc(srcfile, libs):
"""
Transforms the result of a parsed file from pycparser to a valid cbmc
input.
"""
fd = open(srcfile, "r")
src = fd.read()
fd.close()
# Replace the definition of __VERIFIER_error with the one for CBMC
if "extern void __VERIFIER_error();" in src:
# print "__VERIFIER_err... | 5,332,694 |
def check_finished(worker, exec_id):
"""
:param worker:
:param exec_id:
:return:
"""
result = worker.status(exec_id)
status = dill.loads(base64.b64decode(result.data))
if status["status"] == "FAILED":
raise Exception("Remote job execution failed")
elif status["status"] == "... | 5,332,695 |
def execute_runs():
"""
Execute multiple runs in series using multiple cores.
:return: Nothing.
"""
# Initialise empty list of results.
results = []
# Initialise pool of workers.
pool = Pool(processes=params['CORES'])
for run in range(params['RUNS']):
# Execute a single e... | 5,332,696 |
def round_filters(filters, global_params):
""" Calculate and round number of filters based on depth multiplier. """
multiplier = global_params.width_coefficient
if not multiplier:
return filters
divisor = global_params.depth_divisor
min_depth = global_params.min_depth
filters *= multipli... | 5,332,697 |
def print_results(is_cat):
"""
Print whether cat is in image
Args:
is_cat:
Returns:
"""
if is_cat:
print("Image contains cat!")
else:
print("Unfortunately, image does not contain cat") | 5,332,698 |
def handle_input():
"""Handles the input"""
# Global variables that might be changed
global bypass_ticks
global running
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pyga... | 5,332,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.