content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def traffic(config, task):
"""Main function of Bulkdozer, performs the Bulkdozer job"""
global clean_run
if config.verbose:
print('traffic')
try:
setup(config, task)
logger.clear()
logger.log('Bulkdozer traffic job starting')
logger.flush()
init_daos(config, task)
assets(config, t... | 9,200 |
def test_complex_expression():
"""Ensures that add works correctly."""
complex_expression = _MathExpression() * 2 + 1
assert complex_expression(1) == 3 | 9,201 |
def parse_urdf_file(package_name, work_name):
""" Convert urdf file (xml) to python dict.
Using the urdfpy package for now.
Using the xml package from the standard library could be
easier to understand. We can change this in the future
if it becomes a mess.
"""
rospack = rospkg.RosPack()
... | 9,202 |
def _get_mgmtif_mo_dn(handle):
"""
Internal method to get the mgmt_if dn based on the type of platform
"""
if handle.platform == IMC_PLATFORM.TYPE_CLASSIC:
return("sys/rack-unit-1/mgmt/if-1")
elif handle.platform == IMC_PLATFORM.TYPE_MODULAR:
return("sys/chassis-1/if-1")
else:
... | 9,203 |
def measure_cv_performance(gene_by_latent_train, data_test):
"""
Measure NMF model performance on held out data. Performance is evaluated based on the model's ability
to reconstuct held out samples.
\hat{u} := arg min_{u} || x - uV^T || s.t. u >= 0
\hat{x} := \hat{u} V^T
error = || x - \hat{x} ||
... | 9,204 |
def _eject_vmedia(task, managers, boot_device=None):
"""Eject virtual CDs and DVDs
:param task: A task from TaskManager.
:param managers: A list of System managers.
:param boot_device: sushy boot device e.g. `VIRTUAL_MEDIA_CD`,
`VIRTUAL_MEDIA_DVD` or `VIRTUAL_MEDIA_FLOPPY` or `None` to
... | 9,205 |
def sectionize(parts, first_is_heading=False):
"""Join parts of the text after splitting into sections with headings.
This function assumes that a text was splitted at section headings,
so every two list elements after the first one is a heading-section pair.
This assumption is used to join sections wi... | 9,206 |
def set_runner(runner):
"""
Set the global runner instance
:param runner: the runner instance to set as the global runner
"""
global RUNNER
RUNNER = runner | 9,207 |
def byte_compare(stream_a, stream_b):
"""Byte compare two files (early out on first difference).
Returns:
(bool, int): offset of first mismatch or 0 if equal
"""
bufsize = 16 * 1024
equal = True
ofs = 0
while True:
b1 = stream_a.read(bufsize)
b2 = stream_b.read(bufsi... | 9,208 |
def update_variable(_outvars, _values):
"""Update the variable to the new value in the variable table."""
pass | 9,209 |
def get_resize_augmentation(image_size, keep_ratio=False, box_transforms=False):
"""
Resize an image, support multi-scaling
:param image_size: shape of image to resize
:param keep_ratio: whether to keep image ratio
:param box_transforms: whether to augment boxes
:return: albumentation Compose
... | 9,210 |
def calc_theta_from_q(q, E):
"""
=======================================================================
>> @DATE: 02/06/2020 SS 1.0 original
>> @AUTHOR: Saransh Singh Lawrence Livermore national Lab
>> @DETAIL: converts q to theta given an energy
>> @param q scattering parameter = 4 * pi ... | 9,211 |
def test_block_quotes_229fx():
"""
Test case 229f: variation of 229 with different spacing
"""
# Arrange
source_markdown = """> ```
> 2
>> ```
"""
expected_tokens = [
"[block-quote(1,1)::> \n> \n>\n]",
"[fcode-block(1,3):`:3::::::]",
"[text(2,3):2\n\a>\a>\a ```:]",
... | 9,212 |
def extract_question(metric):
"""Extracts the name and question from the given metric"""
with open(metric) as f:
data = f.readlines()
data = [x.strip() for x in data]
# filter out empty strings
data = list(filter(None, data))
# data[0] = '# Technical Fork'
metric_name = data[0].sp... | 9,213 |
def get_side(node, vowels, matcher, r):
"""Get side to which char should be added. r means round (or repeat).
Return 0 or plus int to add char to right,
minus int to left,
None if char node should be avoided.
"""
# check if node has both char neighbours
if node.next is None:
if node... | 9,214 |
def serve_build():
"""needed for building assets"""
serve("build") | 9,215 |
def gap_perform_pruning(model_path, pruned_save_path=None, mode='gap', slim_ratio=0.5,
mask_len=False, full_save=False, full_save_path=None, var_scope='',
ver=1):
""" Interface for GAP pruning step (step2).
Args:
model_path: path to the saved checkpoint,
... | 9,216 |
def html_wrap(ptext, owrapper, attribute=''):
"""
Wrap text with html tags.
Input:
ptext -- text to be wrapped
owrapper -- tag to wrap ptext with
attribute -- if set, attribute to add to ptext
If owrapper ends with a newline, then the newline will appear after the
bracket c... | 9,217 |
def start_vsfm(port=None, vsfm_binary_path=default_path):
"""
Starts VSFM, binds it to a socket, opens the socket interface, sets up a logger and waits.
:param port: Port number to open, defaults to a random one
:param vsfm_binary_path: the path to VSFM.exe, defaults from the vsfm_data file
:return:... | 9,218 |
def names(namespace):
"""Return extension names without loading the extensions."""
if _PLUGINS:
return _PLUGINS[namespace].keys()
else:
return _pkg_resources_names(namespace) | 9,219 |
def create_tech_storage(connector, technology_list):
"""
This function writes the ``StorageDuration`` table.
"""
cursor = connector.cursor()
storage_techs = [tech for tech in technology_list if tech.storage_tech]
table_command = """CREATE TABLE "StorageDuration" (
"regions... | 9,220 |
def toggle_device_setting(daq, device):
"""
Toggle a setting on the device: If it's enabled, disable the setting, and
vice versa.
"""
path = "/%s/sigouts/0/on" % device
is_enabled = daq.getInt(path)
print(f"Toggling setting '{path}'.")
daq.setInt(path, not is_enabled)
daq.sync() | 9,221 |
def cfq_lstm_attention_multi():
"""LSTM+attention hyperparameters tuned for CFQ."""
hparams = common_hparams.basic_params1()
hparams.daisy_chain_variables = False
hparams.batch_size = 1024
hparams.hidden_size = 128
hparams.num_hidden_layers = 2
hparams.initializer = 'uniform_unit_scaling'
hparams.initia... | 9,222 |
def create_modeling_tables(spi_historical, spi_fixtures, fd_historical, fd_fixtures, names_mapping):
"""Create tables for machine learning modeling."""
# Rename teams
for col in ['team1', 'team2']:
spi_historical = pd.merge(spi_historical, names_mapping, left_on=col, right_on='left_team', how='left... | 9,223 |
def restart_supervisord():
"""Reload supervisorctl conf to run celery and celerybeat"""
sudo('supervisorctl reload', pty=True) | 9,224 |
def daily_selection():
"""
Select a random piece of material from what is available. A piece is defined
by a newline; every line is a new piece of content.
"""
logger.log("Selecting today's material")
with open(settings.CONTENT, "r") as file:
content = file.readlines()
lines = len(co... | 9,225 |
def pin_output(pin, state):
"""
Wrapper function used to debug pin states.
"""
GPIO.output(pin, state)
log('debug', 'pin ', pin, ', state ', state) | 9,226 |
def cli():
"""
Easy and effective tooling for FIX Repository data.
FIX2dict greatly simplifies working with FIX Repository data by
leveraging open and combat-proven web technologies. The ultimate
goal is to provide users with a consistent, authoritative and
high-quality FIX reference in an acce... | 9,227 |
def center_image(image):
""" Центрирование якорной точки изображения. """
image.anchor_x = image.width // 2
image.anchor_y = image.height // 2 | 9,228 |
def write_stored_taxa(stored_taxa: Dict):
"""Write taxon view history to file, along with stats on most frequently viewed taxa
Args:
Complete taxon history (including previously stored history)
"""
# Do a recount/resort before writing
stored_taxa["frequent"] = OrderedDict(Counter(stored_tax... | 9,229 |
def get_browser_version():
"""
obtain the firefox browser version, this is necessary because zeus can only handle certain versions.
"""
logger.info(set_color(
"attempting to get firefox browser version"
))
try:
firefox_version_command = shlex.split("firefox --version")
ou... | 9,230 |
def feature_evaluation(X: pd.DataFrame, y: pd.Series, output_path: str = ".") -> NoReturn:
"""
Create scatter plot between each feature and the response.
- Plot title specifies feature name
- Plot title specifies Pearson Correlation between feature and response
- Plot saved under given f... | 9,231 |
def is_checkpointing() -> bool:
"""Whether the current forward propagation is under checkpointing.
Returns:
bool: :data:`True` if it's under checkpointing.
"""
return thread_local.is_checkpointing | 9,232 |
def create_tile_assets_profile(iam, profile_name, locations):
"""
Creates a profile (and corresponding role) with read and write access to
the tile assets bucket.
"""
profile = iam.create_instance_profile(
InstanceProfileName=profile_name,
Path='/',
)
iam.create_role(
... | 9,233 |
def cli(dir):
"""
Sets up the project environment.
This is called by default after `whisk create` and should be run manually after cloning an existing project.
See :func:`whisk.setup.setup` for the full list of steps that are performed.
"""
whisk.setup.setup(dir) | 9,234 |
def noise_filter(rgb_array, coef=8, read_noise=2, shot_noise=246):
""" Apply bilateral noise filter to RGB image"""
h, w, _ = rgb_array.shape
luma_img = rgb_array[:, :, 0] + rgb_array[:, :, 1] + rgb_array[:, :, 2]
average = scipy.ndimage.filters.uniform_filter(luma_img, 5, mode='mirror')
sigma_map =... | 9,235 |
def test_flux_custom_units_correct(specviz_gui, qtbot):
"""
Accept valid custom units
"""
ucd = get_ucd(specviz_gui)
qtbot.addWidget(ucd)
ucd.ui.comboBox_units.setCurrentIndex(0)
assert ucd.ui.comboBox_units.currentText() == ucd.data_unit_equivalencies_titles[0]
ucd.ui.comboBox_units.s... | 9,236 |
def logout():
"""
Logout of AVA Cloud.
"""
try:
r = requests.get(url + '/logout')
r.raise_for_status()
except requests.exceptions.HTTPError as e:
if r.status_code == 400:
click.echo('Error: Bad credentials', err=True)
elif r.status_code == 401:
... | 9,237 |
def drop_entity(p_json: json):
"""
Удаляет сущность
:param p_json: json с указанием id сущности, которую нужно удалить
"""
try:
l_model=Model(p_json=p_json)
l_model.drop_entity()
return _JsonOutput(p_json_object=None, p_message="Entity has dropped successfully").body
exc... | 9,238 |
def get_ssl_vpn_client_certs(ids: Optional[Sequence[str]] = None,
name_regex: Optional[str] = None,
output_file: Optional[str] = None,
ssl_vpn_server_id: Optional[str] = None,
opts: Optional[pulumi.Invoke... | 9,239 |
def quantile(h: Distogram, value: float) -> Optional[float]:
""" Returns a quantile of the distribution
Args:
h: A Distogram object.
value: The quantile to compute. Must be between 0 and 1
Returns:
An estimation of the quantile. Returns None if the Distogram
object contains... | 9,240 |
def convert_to_py(path):
"""从ipynb文档中提取代码内容"""
content = []
cells = get_notebook_cells(path)
for cell in cells:
if cell["cell_type"] == "code":
if content:
content += ["\n"]
for i in cell["source"]:
if i.strip().startswith("!") or ... | 9,241 |
def arachni_del_vuln(request):
"""
The function Delete the Arachni Vulnerability.
:param request:
:return:
"""
if request.method == 'POST':
vuln_id = request.POST.get("del_vuln", )
un_scanid = request.POST.get("scan_id", )
scan_item = str(vuln_id)
value = scan_it... | 9,242 |
def pipe(*args, encoding="utf-8", print_output=False, raise_exception=False):
"""Every arg should be a subprocess command string which will be run and piped to
any subsequent args in a linear process chain. Each arg will be split into command
words based on whitespace so whitespace embedded within words is... | 9,243 |
def construct_imports(variables, imports):
"""Construct the list of imports by expanding all command line arguments."""
result = {}
for i in imports:
kv = i.split('=', 1)
if len(kv) != 2:
print 'Invalid value for --imports: %s. See --help.' % i
sys.exit(1)
result[kv[0]] = expand_template(k... | 9,244 |
def is_regex(param):
"""
判断参数是否是合法正则表达式字符串
:param param: {String} 参数
:return: {Boolean} 是否是合法正则表达式
"""
try:
re.compile(param)
return True
except re.error:
return False | 9,245 |
def NetCDF_SHP_lat_lon(name_of_nc, box_values, name_of_lat_var, name_of_lon_var, correct_360):
"""
@ author: Shervan Gharari
@ Github: https://github.com/ShervanGharari/candex
@ author's email id: sh.gharari@gmail.com
@license: Apache2
Th... | 9,246 |
def format_issues(
input_issues: list,
developer_ids: list,
start_date: datetime.datetime,
end_date: datetime.datetime,
end_date_buffer: int = 0,
) -> list:
"""extract and formats key fields into an output list
Args:
input_issues: issues (tuples) from GitHub
developer_ids: GitHu... | 9,247 |
def train_transforms(image_size, train_img_scale=(0.35, 1),
normalize: bool = True,
mean=torch.tensor([0.485, 0.456, 0.406]),
std=torch.tensor([0.229, 0.224, 0.225])):
"""Transforms for train augmentation with Kornia."""
transforms = [
Acci... | 9,248 |
def test_tmatrix_spheroid_is_sphere(material, atol):
"""tmatrix of spheroid with aspect ratio 1 is equal to tmatrix of sphere"""
sphere = miepy.sphere([0,0,0], radius, material)
spheroid = miepy.spheroid([0,0,0], radius, radius, material, tmatrix_lmax=4)
T1 = sphere.compute_tmatrix(lmax, wavelength, ... | 9,249 |
def get_spans_bio(tags,id2label=None):
"""Gets entities from sequence.
Args:
tags (list): sequence of labels.
Returns:
list: list of (chunk_type, chunk_start, chunk_end).
Example:
>>> tags = ['B-PER', 'I-PER', 'O', 'B-LOC']
>>> get_spans_bio(tags)
# outpu... | 9,250 |
def tag_stamp(b_tag_after_update, repo_path_in_section, repo, branch='', commit=''):
"""
Tag with time stamp after clone or pull
"""
if b_tag_after_update:
# store current path
cwd = os.getcwd()
# move to the repository path
os.chdir(repo_path_in_section)
# get ... | 9,251 |
def min_count1(lst):
"""
Get minimal value of list, version 1
:param lst: Numbers list
:return: Minimal value and its count on the list
"""
if len(lst) == 0:
return []
count = 0
min_value = lst[0]
for num in lst:
if num == min_value:
count += 1
el... | 9,252 |
def setJournal(filename = None):
"""
Method of open / close a journal file that records prompts and commands typed to a text file.
param filename string the name of the journal file, if None will close any current open journal file.
:param filename: the name of the journal file, (defaults to None which... | 9,253 |
def create_build_from_docker_image(
image_name,
install_package,
namespace,
source_image="quay.io/ocsci/fedora",
source_image_label="latest",
):
"""
Allows to create a build config using a Dockerfile specified as an
argument, eg.::
$ oc new-build -D $'FROM centos:7\\nRUN yum ins... | 9,254 |
def waymo_data_prep(root_path,
info_prefix,
version,
out_dir,
workers,
max_sweeps=5):
"""Prepare the info file for waymo dataset.
Args:
root_path (str): Path of dataset root.
info_prefix (str): T... | 9,255 |
def exactly_one_topping(ketchup, mustard, onion):
"""Return whether the customer wants exactly one of the three available toppings
on their hot dog.
"""
return True if int(ketchup) + int(mustard) + int(onion) == 1 else False | 9,256 |
def strip_line_endings(data: list) -> list:
"""Removes line endings(\n). Removes item if only contains \n."""
return [i.rstrip("\n") for i in data if i != "\n"] | 9,257 |
def calculate_afqt_scores(df):
"""This function calculates the AFQT scores. See information at
https://www.nlsinfo.org/content/cohorts/nlsy79/topical-guide/education/aptitude-achievement-intelligence-scores
for more details. In addition, we adjust the Numerical Operations score along the lines
des... | 9,258 |
def test_qubitop_to_paulisum():
"""
Conversion of QubitOperator; accuracy test
"""
hop_term = FermionOperator(((2, 1), (0, 0)))
term = hop_term + hermitian_conjugated(hop_term)
pauli_term = jordan_wigner(term)
forest_term = qubitop_to_pyquilpauli(pauli_term)
ground_truth = PauliTerm("X... | 9,259 |
def weighting_system_z():
"""Z-weighting filter represented as polynomial transfer function.
:returns: Tuple of `num` and `den`.
Z-weighting is 0.0 dB for all frequencies and therefore corresponds to a
multiplication of 1.
"""
numerator = [1]
denomenator = [1]
return nume... | 9,260 |
def shutdown():
"""
Shuts down the API (since there is no legit way to kill the thread)
Pulled from https://stackoverflow.com/questions/15562446/how-to-stop-flask-application-without-using-ctrl-c
"""
func = request.environ.get('werkzeug.server.shutdown')
if func is None:
raise RuntimeEr... | 9,261 |
def add_glitch(psr, epoch, amp):
"""
Like pulsar term BWM event, but now differently parameterized: just an
amplitude (not log-amp) parameter, and an epoch. [source: piccard]
:param psr: pulsar object
:param epoch: TOA time (MJD) the burst hits the earth
:param amp: amplitude of the glitch
... | 9,262 |
def on_post_request():
"""This function triggers on every POST request to chosen endpoint"""
data_sent = request.data.decode('utf-8')
return Response(return_animal_noise(data_sent), mimetype='text/plain') | 9,263 |
def settings(comid=None, community=None):
"""Modify a community."""
pending_records = \
len(CommunityRecordsCollection(community).filter({'status': 'P'}))
return render_template(
'invenio_communities/settings.html',
community=community,
comid=comid,
pending_records=pe... | 9,264 |
def product_of_basins():
"""Return the product of the sizes of the three largest basins."""
max_x = len(values[0]) - 1
max_y = len(values) - 1
def heightmap(x, y):
"""Return the height value in (xth column, yth row)."""
return values[y][x]
def is_lowpoint(x, y):
"""Return T... | 9,265 |
def test_io_forward():
"""Test IO for forward solutions
"""
fwd = mne.read_forward_solution(fname)
fwd = mne.read_forward_solution(fname, force_fixed=True)
leadfield = fwd['sol']['data'] | 9,266 |
def close_consumer(consumer):
"""Close consumer"""
consumer.close() | 9,267 |
def singularity26(function):
"""Decorator to set the global singularity version"""
def wrapper(*args, **kwargs):
hpccm.config.g_ctype = container_type.SINGULARITY
hpccm.config.g_singularity_version = StrictVersion('2.6')
return function(*args, **kwargs)
return wrapper | 9,268 |
def testScanUpdate_always_updatesExistingScan(mocker, db_engine_path):
"""Test Agent save implementation."""
mocker.patch.object(models, 'ENGINE_URL', db_engine_path)
models.Database().create_db_tables()
models.Scan.create('test')
database = models.Database()
database.session.commit()
asser... | 9,269 |
def denormalize(series, last_value):
"""Denormalize the values for a given series.
This uses the last value available (i.e. the last
closing price of the week before our prediction)
as a reference for scaling the predicted results.
"""
result = last_value * (series + 1)
return result | 9,270 |
def tfidf(
s: pd.Series, max_features=None, min_df=1, max_df=1.0, return_feature_names=False
) -> pd.Series.sparse:
"""
Represent a text-based Pandas Series using TF-IDF.
*Term Frequency - Inverse Document Frequency (TF-IDF)* is a formula to
calculate the _relative importance_ of the words in a doc... | 9,271 |
def decorator(fn: AsyncFn, *, expire: int, maxsize: int) -> AsyncFn:
"""Cache decorator."""
cache = LRUCache(maxsize=maxsize)
@wraps(fn)
async def wrapper(*args: Tuple[Any, ...], **kwds: Dict[str, Any]) -> Any:
"""Wrap the original async `fn`.
Cached results will be returned if cache h... | 9,272 |
def _write_incon(
f, labels, primary_variables, porosities, permeabilities, phase_compositions, eos
):
"""Write INCON block."""
from ._helpers import _write_incon as writer
# Write INCON block
if permeabilities is not None:
permeabilities = (
permeabilities[:, None] if permeabil... | 9,273 |
def cleanQrc(uiFile):
"""
Looks for included resources files in provided .ui file
If it doesn't find any, it returns the original file else:
Adds all search paths to Qt
Converts all paths
turns this> :/images/C:/Users/mindd/Desktop/CircleOfFifths.jpg
... | 9,274 |
def reindex(src_index, dst_index, type_list, chunk_size=None, time=None):
"""Reindex a set of indexes internally within ElasticSearch. All of the
documents under the types that live in "type_list" under the index
"src_index" will be copied into the documents under the same types
in the index "d... | 9,275 |
def pad(data, paddings, mode="CONSTANT", name=None, constant_value=0):
""" PlaidML Pad """
# TODO: use / implement other padding method when required
# CONSTANT -> SpatialPadding ? | Doesn't support first and last axis +
# no support for constant_value
# SYMMETRIC -> Requires implement ?... | 9,276 |
def taxon_id(_):
"""
Always returns 10090, the mouse taxon id.
"""
return 10090 | 9,277 |
def rthread_if(data, *forms):
"""
Similar to rthread, but each form must be a tuple with (test, fn, ...args)
and only pass the argument to fn if the boolean test is True.
If test is callable, the current value to the callable to decide if fn must
be executed or not.
Like rthread, Arguments are... | 9,278 |
def cell_edit(sender, app_data):
"""Click-handler. Function to enable editing in a table cell.
The function shows a status update to the user including tag and content of the clicked cell.
To achieve editing, the label within the table cell is removed and a text input widget is
placed at the same posit... | 9,279 |
def decompose_matrices(Ks):
"""
Apply Cholesky decomposition to each matrix in the given list
:param Ks: a list of matrices
"""
Ls = []
for i, K_d in enumerate(Ks):
Ls.append(np.linalg.cholesky(K_d))
return Ls | 9,280 |
async def plugin_remove_cmd(client, message):
"""remove an installed plugin.
alemiBot plugins are git repos, cloned into the `plugins` folder as git submodules.
This will call `git submodule deinit -f`, then remove the related folder in `.git/modules` and last remove \
plugin folder and all its content.
If flag `... | 9,281 |
def ndcg_score(y_pre, y_true, k=20):
"""
get NDCG@k
:param y_pre: numpy (batch_size,x)
:param y_true: y_truth: list[batch_size][ground_truth_num]
:param k: k
:return: NDCG@k
"""
dcg = dcg_score(y_pre, y_true, k)
idcg = dcg_score(y_true, y_true, k)
return dcg / idcg | 9,282 |
def test_instantiate_8():
"""Test value stored as int"""
a = FixedPoint(0.1, 'Q0.4')
assert a.value == 1 | 9,283 |
def get_discount_weights(
discount_factor: float, traj_len: int, num_trajs: int = 1
) -> Optional[npt.NDArray[np.float32]]:
"""
Return the trajectory discount weight array if applicable
:param discount_factor: the discount factor by which the displacements corresponding to the k^th timestep will
be ... | 9,284 |
def touch_to_square(touch_x, touch_y, num_rows, num_cols):
""" Given a touch x and y, convert it to a coordinate on the square. """
x = clamp(maprange((PAD_Y_RANGE_MAX, PAD_Y_RANGE_MIN),
(0, num_rows),
touch_y) + random.randrange(-1, 2),
0, num_rows - ... | 9,285 |
def is_valid_scheme(url):
"""Judge whether url is valid scheme."""
return urlparse(url).scheme in ["ftp", "gopher", "http", "https"] | 9,286 |
def test_binom_conf_badinput4():
"""Sterne.
With current implementation, Sterne can only be used with two-sided CI
"""
pytest.raises(ValueError, binom_conf_interval,
10, 3, 0.95, 'upper', None, 'sterne') | 9,287 |
def test_one_library(logger):
"""
Runs a test using one solution from the library as a quick litmus
test for code health.
"""
solution = "\/ [TCP:dataofs:5]-drop-|"
censor = "censor2"
test_type = "echo"
fitness = common.run_test(logger, solution, censor, test_type, log_on_fail=True)
... | 9,288 |
def height_to_transmission(height, material, energy, rho=0, photo_only=False,
source='nist'):
"""
Calculates the resulting x-ray transmission of an object based on the given
height (thickness) and for a given material and energy.
Parameters
==========
height: grating... | 9,289 |
def assignModelClusters(keyframe_model, colors):
""" Map each colorspace segment to the closest color in the input.
Parameters
----------
keyframe_model : FrameScorer
colors : numpy array of int, shape (num_colors, 3)
"""
hsv_mean_img = keyframe_model.hsv_means.copy().reshape(1, keyframe_m... | 9,290 |
def internal_path_exists(path):
"""
Validates that url path is registered and can properly be resolved
in a django configuration.
"""
try:
resolve(path)
except Http404:
raise ValidationError("'{0}' is not a valid url.".format(path)) | 9,291 |
def sort_according_to_ref_list(fixturenames, param_names):
"""
Sorts items in the first list, according to their position in the second.
Items that are not in the second list stay in the same position, the others are just swapped.
A new list is returned.
:param fixturenames:
:param param_names:... | 9,292 |
def calc_ef_from_bases(x,*args):
"""
Calculate energies and forces of every samples using bases data.
"""
global _hl1,_ergs,_frcs,_wgt1,_wgt2,_wgt3,_aml,_bml
#.....initialize variables
if _nl == 1:
_wgt1,_wgt2= vars2wgts(x)
elif _nl == 2:
_wgt1,_wgt2,_wgt3= vars2wgts(x)
... | 9,293 |
def test_wheel_no_compiles_pyc(
script: PipTestEnvironment, shared_data: TestData, tmpdir: Path
) -> None:
"""
Test installing from wheel with --compile on
"""
shutil.copy(shared_data.packages / "simple.dist-0.1-py2.py3-none-any.whl", tmpdir)
script.pip(
"install",
"--no-compile"... | 9,294 |
def HIadj_post_anthesis(
NewCond_DelayedCDs,
NewCond_sCor1,
NewCond_sCor2,
NewCond_DAP,
NewCond_Fpre,
NewCond_CC,
NewCond_fpost_upp,
NewCond_fpost_dwn,
... | 9,295 |
def packify(fmt=u'8', fields=[0x00], size=None, reverse=False):
"""
Packs fields sequence of bit fields into bytearray of size bytes using fmt string.
Each white space separated field of fmt is the length of the associated bit field
If not provided size is the least integer number of bytes that hold the... | 9,296 |
def SetScore(objects: object) -> None:
"""Updates the score count and the render values."""
eaten = 0
for item in objects.items.keys():
if item.startswith("chip"):
eaten += objects.items[item]["eaten"]
objects.score_font = objects.font.render(f'Score: {eaten}', False, (0, 0, 0))
... | 9,297 |
def price(bot, update, args):
"""Receive a stock code and return the price.
Parameters:
*args: Accept only one str argument containing the stock code (e.g. 'PETR3')
Examples:
/price BBAS3
This would return the current price for BBAS3 stock"""
stock_code = str(args[0])
stock... | 9,298 |
def fix_conf_params(conf_obj, section_name):
"""from a ConfigParser object, return a dictionary of all parameters
for a given section in the expected format.
Because ConfigParser defaults to values under [DEFAULT] if present, these
values should always appear unless the file is really bad.
:param c... | 9,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.