content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def bivariate_histogram(xsample, ysample, reference_value_mean=None,\
reference_value_covariance=None, bins=None, matplotlib_function='imshow',\
xlabel='', ylabel='', title='', fontsize=28, ax=None, show=False,\
contour_confidence_levels=0.95, reference_color='r', reference_alpha=1,\
minima=None, maxima... | 01e479b80dca6b87494b323f9fa76a8a4a08d4e1 | 3,612,600 |
def arrayToVec(array, arrType=carmcmcLib.vecD):
"""
Convert the input numpy array to a python wrapper of a C++ std::vector<double> object.
"""
vec = arrType()
vec.extend(array)
return vec | efdbe2ae33821ff6aadfd699aa535eacf962efe3 | 3,612,601 |
import six
def moma(model, reference=None, cache=None, reactions=None, *args, **kwargs):
"""
Minimization of Metabolic Adjustment[1]
Parameters
----------
model: cobra.Model
reference: FluxDistributionResult, dict
cache: ProblemCache
reactions: list
Returns
-------
FluxDi... | 87397e01b8ddba25c1d92d652aecb2c85d8239df | 3,612,602 |
def api_v2_url(path_str,
params=None,
base_route=settings.API_BASE_URL,
**kwargs):
"""
Convenience function for APIv2 usage: Concatenates parts of the absolute API url based on arguments provided
For example: given path_str = '/nodes/abcd3/contributors/' and par... | 71d7efeb9d6e6279776f3e28257428ee3c09b9f7 | 3,612,603 |
import json
def serialize_timingsession(session_pk, pk_offset=0):
"""Serialize all data associated with a timing session into JSON."""
session = TimingSession.objects.get(pk=session_pk)
data_to_dump = [
[session],
[session.coach],
[session.coach.user],
Split.objects.filter(... | 9de0ccf0a0eb2644fc7cf2289815f5e39d9a5416 | 3,612,604 |
def send_via_mail_to(request):
"""
send email to list of freinds
:param request:
in the square represented by :
west < longitude < east
north < latitude < south
"""
idAlert = int(request.POST['id'])
emails = request.POST['list']
text = request.POST['text']
lis... | 68e17f426ea3ba15f3e95cb9ce3daf1a65c7cbed | 3,612,605 |
import glob
import os
import time
def getdata():
"""Returns a numpy array containing the most recently written EDA spectrum.
Return None,None if the most recent file is older than MAXAGE seconds.
NOTE - this will only work when run on 'bigdas', where live spectrum data is written to /tmp every seco... | d443714397585c2982eb930fc394ff579fe58516 | 3,612,606 |
def get_tables_from_url(url, url_to_html='requests'):
"""Get's a list of pandas dataframes from tables scraped from a url.
Note that this will only work with static pages. If the html needs to be rendered dynamically,
you'll have to get your needed html otherwise (like with selenium).
>>> url = 'https:... | 767a99ca64ce840c04b993c48d9b861c73211da9 | 3,612,607 |
import random
import math
import tqdm
import time
def matrix_split(interaction_dataset, user_test_ratio=0.2, item_test_ratio=0.2, min_user_interactions=0,
seed=0, max_concurrent_threads=4, **kwds):
"""Dataset split method that uses a matrix split strategy. More specifically, item_test_ratio items... | d983e27c162835616c855dd54f7d9cf89708d458 | 3,612,608 |
import copy
def Loadexc(casefile_dyn):
""" Loads exciter data.
@param casefile_dyn: m-file or struct with dynamic data
@return: exciter parameter matrix
@see: U{http://www.esat.kuleuven.be/electa/teaching/matdyn/}
"""
# Load data
if isinstance(casefile_dyn, dict):
exc = casefile_... | f5fcfb34bd6b9a430aed208173ee633b61d957d8 | 3,612,609 |
def _num_requests_needed(num_repos, factor=2, wiggle_room=100):
"""
Helper function to estimate the minimum number of API requests needed
"""
return num_repos * factor + wiggle_room | 525af1e3aa5e1c0b35195fcd8e64cd32101bb6f2 | 3,612,610 |
import re
def linebreakshtml(value, autoescape=True):
"""
Replaces double line breaks in HTML to a paragraph break (``</p>``).
This tag ignores single line breaks.
"""
autoescape = autoescape and not isinstance(value, SafeData)
value = normalize_newlines(force_text(value))
if autoescape:
... | bdd38b299f297194d9e3ca3c31c20ba2203ed622 | 3,612,611 |
def season(date, hemisphere, isleapyear):
"""
date is a datetime object
hemisphere is either 'north' or 'south', dependent on long/lat.
https://stackoverflow.com/questions/16139306/determine-season-given-timestamp-in-python-using-datetime
"""
if isleapyear:
dd = date.day + 1
... | 318803e94426c046b27e3d50b1490961f26b90ed | 3,612,612 |
from typing import Generator
def find_files(base_path: str, annotation_path: str or None = None) -> Generator[str, Annotation, None]:
"""Get each file and its proper annotation object.
Parameters
----------
base_path : srt
Base path of input files.
annotation_path : str or None
Pa... | 8ee544a6ec876f395caa0be6dcc2de2ccb2fc541 | 3,612,613 |
def request_course_creator(request):
"""
User has requested course creation access.
"""
user_requested_access(request.user)
return render(request) | ad036a1852e39c7c626f4013c4d8b6e3958b1d2c | 3,612,614 |
def _generate_monthly_price_materialized_view_sql():
"""
Generate the SQL used to generate the materialized view used by the last point view
:return:
"""
return """
CREATE MATERIALIZED VIEW instancedata_monthly_price_mv
ENGINE = SummingMergeTree
PARTITION BY crawlMonth
... | 8cbe81bd07074accf6f621ab68d795282e0e844d | 3,612,615 |
def number_constructors():
"""A decorator for parametrized tests that test particular number operations.
"""
return pytest.mark.parametrize(
"newobj",
[
lambda: weakget(0),
lambda: pep505(0),
lambda: _weakget__nothing, # a singleton
],
ids... | 8b8c1534f1285f03b2219dba58ed9490236d87a3 | 3,612,616 |
import threading
def approve_paper(request):
"""API approve_paper"""
if not request.user.is_authenticated:
return JsonResponse({'status': 'false'}, status=401)
if request.method == 'POST':
id = request.POST['id']
comment = request.POST['comment']
paper = get_object_or_404(... | 0f5c48e747d4b5fea890de5586561da3f13e18ac | 3,612,617 |
def dopamine_eval(runner, patient0, seed=100):
"""Evaluate an agent."""
base_env = runner._environment.environment # pylint: disable=protected-access
initial_health_state = np.zeros_like(
base_env.initial_params.initial_health_state)
initial_health_state[patient0] = 1
base_env.set_initial_health_state... | b5d497923ff62e953bb6a6df717645b886b0138a | 3,612,618 |
import torch
def pad_data(data_list, fill=0):
"""
Pad tensors with fill-value such that list of variable shaped tensors can be stacked
"""
n_samples = len(data_list)
#first determine longest time series:
lengths = [x.shape[0] for x in data_list]
max_len = max(lengths)
output = fil... | d6d978d0247b7481f5eb33a23292addaa10ba792 | 3,612,619 |
import json
def market(request):
""" Consulta a API procurando por informações sobre o mercado """
conn.request("GET", "/market/v2/get-summary?region=BR", headers=headers)
res = conn.getresponse()
data = res.read()
summary = json.loads(data.decode("utf-8"))['marketSummaryAndSparkResponse']
ret... | 1bb8cbc8bd44811a8e0f50b328ec0a2b858a82d3 | 3,612,620 |
def setup_invalid_yaml(tmpdir):
"""Returns a list containing three Vector instances"""
test_config_data = """
test: 1
test2:
1
"""
default_dict = {'test': 'testing', 'test2': 'still testing'}
test_cfg = tmpdir.mkdir("sub").join('test_config.yml')
test_cfg.write(test_config_data)
... | 0f16cc6e8974b077996957b3f26f0d5f3c194ad3 | 3,612,621 |
import torch
def fuse_features(features1, features2, frame_batch_size=64, device='cuda'):
"""feature fusion"""
video_length = features1.shape[0]
frame_start = 0
frame_end = frame_start + frame_batch_size
features = np.empty(shape=[0, 4096], dtype=np.float32)
if video_length <= frame_batch_siz... | 539838c30cb9ac1e01af7f9b5d15df9cf4663275 | 3,612,622 |
def raHMS2deg(angle):
"""
EXAMPLE: Angle("10:42:44",unit=u.hourangle).deg
"""
return astropy.coordinates.Angle(angle,unit=u.hourangle).deg | f0b910131e8802c029f8f7a6758f4fe1184f24e0 | 3,612,623 |
import os
import uuid
import json
def generate(images, captions=dict(), outputdir='.', no_cache=False,
stage_width=1080, stage_height=680,
width=1200, height=800, thumbheight=50,
disable_keyboard_nav=0, image_margin=0,
toggleinfo=True, thumbnails=True,
... | d02c2cd002ae45d6155fda05d611fe3e08a7d8b0 | 3,612,624 |
import os
def rel(*x):
""""Simple path helper"""
abspath = os.path.abspath(main_file_location)
BASE_DIR = os.path.dirname(abspath)
return os.path.join(BASE_DIR, *x) | 72fd2ba6be7fc1d4a663a9aa765c903adeb8625e | 3,612,625 |
def same_padding_for_kernel(shape, corr, strides_up=None):
"""Determine correct amount of padding for `same` convolution.
To implement `'same'` convolutions, we first pad the image, and then perform a
`'valid'` convolution or correlation. Given the kernel shape, this function
determines the correct amount of p... | 8d956c75a2e0609a04ec56374a4cb9b3b367b90a | 3,612,626 |
import re
def dedeidentify(text):
"""
MIMIC-specific
:param text: The text to de-de-identify
:return:
"""
return re.sub(r"\[\*\*.*\*\*\]", xxxx, text).lower() | 033c04bb61ce26fa2e7af902cc4d3ffbb9c88004 | 3,612,627 |
def embed_net_siam1():
"""
This is a siamese type network to compare two patches.
"""
data1 = mx.sym.Variable("data1")
data2 = mx.sym.Variable("data2")
conv_weight = []
conv_bias = []
for i in range(3):
conv_weight.append(mx.sym.Variable('conv' + str(i) + '_weight'))
conv... | 0817dcead9060991d9fe0bf951b0cb4790823166 | 3,612,628 |
import os
def traced_graphql_wrapped(
func,
args,
kwargs,
span_kwargs=None,
span_callback=None,
ignore_exceptions=(),
):
"""
Wrapper for graphql.graphql function.
"""
# allow schemas their own tracer with fall-back to the global
schema = args[0]
tracer = getattr(schema,... | 030a11eb9dd56e87f4aa061de6ca0b1088ca9a01 | 3,612,629 |
def get_time_ms(frame, position):
"""Get time in ms and string based on the finishing position
:param frame: A frame from AsyncVideoCapture / cv2.VideoCapture
:type frame: numpy.ndarray
:param position: Position 1-4
:type position: int
:return: Time in milliseconds, time as string
:rtype: (... | ffd10436170823a2c3a4b08c0d2d262355a12bb7 | 3,612,630 |
def _extract_license_outliers(license_service_output):
"""Extract license outliers.
This helper function extracts license outliers from the given output of
license analysis REST service.
:param license_service_output: output of license analysis REST service
:return: list of license outlier package... | 101a916fec08a3a5db1a09a2817e82314ca19f6b | 3,612,631 |
def maxout(x, pool_size, axis=1):
"""Maxout activation function.
It accepts an input tensor ``x``, reshapes the ``axis`` dimension
(say the size being ``M * pool_size``) into two dimensions
``(M, pool_size)``, and takes maximum along the ``axis`` dimension.
Args:
x (:class:`~chainer.Variab... | 5e30761e4abefb5d823690c4c92c9a8666e2aded | 3,612,632 |
from tests.fpga_drivers import FpgaDriverBase
from ctypes import c_uint32
def test_fpga_drivers_base():
"""
Test accelize_drm.fpga_drivers.FpgaDriverBase.
"""
library = 'fpga_library.so'
fpga_slot_id = 5
base_address = 0x10
fpga_image = 'fpga_image'
class Fpga:
"""Fake FPGA""... | c7d6d59e00a1167ded304170a81b960ac17f5fb6 | 3,612,633 |
from typing import Set
def GetNumDistinctChromeVersions(db, build_config, start_date, end_date):
"""Get the number of distinct chrome versions.
This represents the number of successful chrome uprevs.
Args:
db: cidb.CIDBConnection object.
build_config: Name of build config of master builder.
start_... | 83a7fd123a3154990629406b2c3d5e2ccb3b1e6f | 3,612,634 |
def install_pip():
"""
Install pip using apt-get install.
"""
#we need to upgrade pip package using pip itself
return apt_get_install("python-pip") + pip_install("pip") | 16df3a5d123735f1d3b1ba85eb55849ddcbf1e26 | 3,612,635 |
import subprocess
def runProcess(exe, working_dir):
"""
Function that opens a command line and runs a command.
Captures the output and returns.
Input:
- exe: str,
string of the command to be run. ! REMEMBER TO ESCAPE CHARS!
- working_dir: str,
directory where the cmd sh... | 08d3ae0d81c9ce92c0c74a023ce289e2c0278f22 | 3,612,636 |
import sys
def get_os():
"""
Determines the type of operating system being used. Needed for when we are
loading & saving local files later
Parameters
------------
none
Returns
------------
os_type : str
Type of OS the script is running on
Ex: 'linux' is the scrip... | 6f7d133f8987e9314017a382affda3892ccd36c6 | 3,612,637 |
def center(map, object):
"""
Center an ee.Image or ee.Feature on the map.
Args:
map: The map to center the object on.
object: The ee.Image or ee.Feature to center.
Returns:
The provided map.
"""
coordinates = object.geometry().bounds().coordinates().getInfo()[0]
... | 60a2baa1c4f83b0e9b1221bcc474f109c35cbd7a | 3,612,638 |
from datetime import datetime
def login_user():
"""
Login user in api
:return: token
"""
print('Login')
auth = request.authorization
# print(request.authorization)
if not auth or not auth.username or not auth.password:
return make_response('could not verify', 401, {'WWW.Authent... | 3e371f9dde691a19ccb72b1f1255e0569034ac24 | 3,612,639 |
import warnings
def normalized_diff(b1, b2):
"""Take two numpy arrays and calculate the normalized difference.
Math will be calculated (b1-b2) / (b1+b2).
Parameters
----------
b1, b2 : arrays with the same shape
Math will be calculated (b1-b2) / (b1+b2).
Returns
----------
n_... | e905b76c7dced3b8194b98bf83339be6a6e16d46 | 3,612,640 |
from sys import path
def read_expected_result(test_name):
"""
:param test_name:
:return:
"""
data_file_path = path.join(
get_test_data_prefix(test_name),
"Result.xlsx"
)
return pd.read_excel(
data_file_path, sheet_name=None
) | 3dafe47d4e0ad86a89634e5c742870289d4365c1 | 3,612,641 |
import tkinter as tk
from tkinter import filedialog
def get_json_file_path():
"""Opens dialog box for user to choose where to save the measurements.
Uses default directory in case of failure.
Requires very hacky work-around of installing
tk and tcl in NX directories"""
try:
root = tk.Tk(... | ce234384a6d2c98693a7a52b0d22ec8716ad7a76 | 3,612,642 |
import shlex
def parse_config_string(config_string, issue_warnings=True):
"""
Parses a config string (comma-separated key=value components) into a dict.
"""
config_dict = {}
my_splitter = shlex.shlex(config_string, posix=True)
my_splitter.whitespace = ","
my_splitter.whitespace_split = Tru... | 1decd3b203b779099111e949b2757a3f52b8c25d | 3,612,643 |
import os
def dump_sections(path, bank_size=0x4000, initial_bank=0, last_bank=None, separator="\n\n"):
"""
Returns a str of assembly source code. The source code delineates each
SECTION and includes bytes from the file specified by baserom.
"""
if not last_bank:
last_bank = calculate_bank_... | 2d69d000375621a05eab60c3ae0ac264cecbdf3f | 3,612,644 |
def load_data_clf(ds_name):
"""
Load the data for classification by the specified dataset name.
Parameters
----------
ds_name : str
Returns
-------
data : DataFrame
"""
ds_load_func = None
if ds_name in DS_LOAD_FUNC_CLF.keys():
ds_load_func = DS_LOAD_FUNC_CLF[ds_na... | 159a3a7b347400416f17cedf0dc04037b133431c | 3,612,645 |
def parse_file_name(file_name):
"""
<Purpose>
Parses a file name to identify its module and its descriptor
<Arguments>
file_name: the name of the test file
<Exceptions>
InvalidTestFileError: if you provide a test file which does not follow the
naming convention of 'ut_<module>_<descriptor>... | 55698a5934b639ce0ddb40cb6eb2edf1614ec04f | 3,612,646 |
def _proto_builder_test_impl(ctx):
"""The implementation of the 'proto_builder_test' rule.
Tests the files generated by the 'proto_builder' rule. The test performs a
textual comparison of the generated source and header with the expected
source and header respectively.
Args:
ctx: The current... | 705ffebeb126ca04c7f4ea35aa82e81f44210b8f | 3,612,647 |
def _make_nxm_w (*args, **kw):
"""
Make a simple wildcarded NXM entry class
"""
t = _fix_types(kw.pop('type', _nxm_maskable_numeric_entry))
ok = False
for tt in t:
if _issubclass(tt, _nxm_maskable):
ok = True
break
if not ok:
t.insert(0, _nxm_maskable)
return _make_nxm(*args, type=t... | 5a4f3b020a3cc91b908f8a8892716865dd7decf9 | 3,612,648 |
def process_datasets(dataset_class, dataset_args, unc_model, device, test_fn=test_unc_model, N=1000, **forward_kwargs):
"""
calls test_fn(unc_model, dataset) for every dataset in datasets
"""
results = {}
for name in dataset_args:
print("Testing", name)
print(N)
dataset = dat... | 8a049e099715b5315524fea15f168964bb49f500 | 3,612,649 |
def accuracy_metric(actual, predicted, correct=0) -> float:
"""calculate accuracy of the dataset comparing the actual test label vs the predicted label"""
for i in range(len(actual)):
if actual[i] == predicted[i]:
correct += 1
return correct / len(actual) * 100.0 | d7f19ccd1da426e00043ee3887261c85d963b47d | 3,612,650 |
from typing import Any
import copy
def get_test_case(
data: pd.DataFrame,
model: Any,
key: str,
add: ARITHEMETIC_OPERATIONS = None,
multiply: ARITHEMETIC_OPERATIONS = None,
) -> SCORES:
"""
Helper method to create the different test cases that alter the keys in a
dictionary
"""
... | 6996c1ef020ae12c65eebbe9275ff0ad3d0c155f | 3,612,651 |
def realign_mol(mol,conf,coord_Map, alg_Map, mol_template, maxsteps): # RAUL: This function requires a clear separation between minimization and alignment.
"""
Minimizes and aligns the molecule provided freezing the atoms that match
the mol_template.
Parameters
----------
mol : rdkit.Chem.Mol... | 325d324693c5b0e064b56209ba2029a357b7fe91 | 3,612,652 |
def measure_shadow_work(simulation, n_steps):
"""Run the simulation for n_steps and return a vector of the shadow work accumulated
during integration.
* Check whether simulation.integrator has bookkeeping variables W_shad and/or heat.
* If only W_shad is available, measure shadow work as W_shad
* I... | c3ef18a0caf040f5d34316bf0d7b5b51b6a6cd43 | 3,612,653 |
def cumulative_cross_corr(I1, I2):
"""
doing normalized cross correlation on distance imagery
:param I1: NP.ARRAY (_,_)
binary array
:param I2: NP.ARRAY (_,_)
binary array
:return result: NP.ARRAY (_,_)
similarity surface
... | 082ee285ba75c72ff1d9b1551b2b882212bde291 | 3,612,654 |
def getGbdbTables(database, tableset):
""" Remove tables that aren't pointers to Gbdb files."""
sep = "','"
tablestr = sep.join(tableset)
tablestr = "'" + tablestr + "'"
hgsqlOut = qaUtils.callHgsql(database, "select table_name from information_schema.columns where\
... | 31c591104698eb50b8ecc63c08609ebf08dd9a10 | 3,612,655 |
def four_bar_plane_truss(num_samples: int = 100, distribution: str = "lhs") -> list:
"""Four bar plane truss problem.
As found in Multiobjective structural optimization using a microgenetic algorithm.
Parameters
----------
x : list or ndarray
Should have 4 elements
Returns
-------
... | 952d57cf9cbc89dca61046e7a06f6eee1a93a953 | 3,612,656 |
def parseFile (pomFile):
""" Parses a pom.xml file and returns a Maven object or None
"""
with open (pomFile, 'rb') as f:
return parseString (f.read())
return None | cd6baa8bfd141a0778dca5bd0cfe2b2d2b86a9ae | 3,612,657 |
def register_error_handlers(a=app):
"""Register error handlers."""
# @see https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-vii-error-handling
@a.errorhandler(500)
def handle_internal(error):
db.session.rollback()
flash(_('Error: %s') % error, 'error')
return rend... | 06b5f75dd422a16363e62ea5f8157d85051ebf74 | 3,612,658 |
def evaluations_to_columns(evaluation):
"""Convert the results of :meth:`metrics.ScoringMixIn.evaluate` to a pandas DataFrame-ready format
Parameters
----------
evaluation: dict of OrderedDicts
The result of consecutive calls to :meth:`metrics.ScoringMixIn.evaluate` for all given dataset types
... | 26c5f4b2a9830f7547f6b59d9653fea25345b43d | 3,612,659 |
import abc
import functools
def get_metric(name: str, **kwargs) -> abc.Callable:
"""Returns metric function for given metric name
Parameters
----------
name : str
Metric name
kwargs : any
Additional keyword-arguments for metric
Returns
-------
metric : callable
... | ddd94ad7d39538f7308dc5bdf6b57f238a6173b4 | 3,612,660 |
def resource_exists(env, resource):
"""Checks for resource existence without actually instantiating a model.
:return: `True` if the resource exists, `False` if it doesn't
and `None` in case no conclusion could be made
(i.e. when `IResourceManager.resource_exists` is not
... | 270d55de9b6fa29628ea996af16af2971a9487de | 3,612,661 |
def run_dqmc(p, unequal_time=True, callback=None, progress=False, *args, **kwargs):
"""Runs a DQMC simulation.
Parameters
----------
p : Parameters
The input parameters of the DQMC simulation.
unequal_time : bool
If `True`, unequal-time measurements will be performed.
callback :... | 661f725d21e819fc1c656fec8c8c395cc23f3c42 | 3,612,662 |
def merge(left: list, right: list) -> list:
"""Merges 2 sorted lists (left and right) in 1 single list, which is
returned at the end.
Time complexity: O(m), where m = len(left) + len(right)."""
mid = []
i = 0 # Used to index the left list.
j = 0 # Used to index the right list.
while i < ... | 9f6c501469e79a9f5ecfd8e23ee3384fc56c5a48 | 3,612,663 |
def replace(i_list: list, target: int,new_value: int)-> list:
"""
Replace all the target value with a new value
:param i_list: the list to be analyzed
:param value: the value to replace
:param target: the value to be replaced
:return: the new list
"""
return list(map(lambda value: new_va... | d0d2bc928c915d3456a25cc4ff341b23a66c4098 | 3,612,664 |
def single(request, id, template_name="microblogging/single.html"):
"""
A single tweet.
"""
tweet = get_object_or_404(Tweet, id=id)
return render_to_response(template_name, {
"tweet": tweet,
}, context_instance=RequestContext(request)) | 117ab58d3626740f91929f8c4e9dd2bfd9d07f21 | 3,612,665 |
def generate_responses(prompt, pipeline, seed=None, debug=False, **kwargs):
"""Generate responses using a text generation pipeline."""
if seed is not None:
set_seed(seed)
outputs = pipeline(prompt, **kwargs)
responses = list(map(lambda x: clean_text(x['generated_text'][len(prompt):]), outputs))... | 83af9e4a2412f5c5ff4cbfb927f53c1d607d1712 | 3,612,666 |
import warnings
def astropy_tabular_data(*args, **kwargs):
"""
Build a data set from a table. We restrict ourselves to tables
with 1D columns.
All arguments are passed to
astropy.table.Table.read(...).
"""
result = Data()
with warnings.catch_warnings():
warnings.simplefi... | bcaa8fe58be57ff93618ec0a89ec7070e39c49f9 | 3,612,667 |
def words_cmp(a, b):
"""
word比较器
:param a: (word, 词频)
:param b: (word, 词频)
:return: [-1|0|1]
"""
a_word, a_freq = a
b_word, b_freq = b
if a_freq != b_freq:
return b_freq - a_freq
elif a_word != b_word:
return -1 if a_word < b_word else 1
else:
return 0 | b758a5a685b81f5fbca5840529272727e5fcf5d7 | 3,612,668 |
def _load_data(args):
"""Load data from path."""
if args.data_format == 'CULANE':
return vega.dataset("AutoLaneDataset", dataset_format="CULane", data_path=args.data_path, mode="test",
batch_size=args.batch_size).loader
elif args.data_format == 'COCO':
return ... | 908cab2892fb0661e31cb65c2273ba811ef0427b | 3,612,669 |
def extract_u_nk(xvg, T):
"""Return reduced potentials `u_nk` from a Hamiltonian differences XVG file.
Parameters
----------
xvg : str
Path to XVG file to extract data from.
T : float
Temperature in Kelvin the simulations sampled.
Returns
-------
u_nk : DataFrame
... | 81f24762f0bd637ef46e0d7e1236aaa657853050 | 3,612,670 |
def group(query, fields=None, step=None):
"""Group results by `fields` and/or `step`."""
if fields is None:
fields = []
if isinstance(fields, string_types):
fields = [fields]
fields = ['"%s"' % f for f in fields]
if step:
fields.insert(0, 'time(%s)' % step)
return '%s GRO... | 819e14714bc3e376cca8c7610466d37c0d599511 | 3,612,671 |
def first_level_directory(path):
"""Return the first level directory of a path.
>>> first_level_directory('home/syt/work')
'home'
>>> first_level_directory('/home/syt/work')
'/'
>>> first_level_directory('work')
'work'
>>>
:type path: str
:param path: the path for which we want... | 3e151912f7ed43c8d3ec9593179ea3016ff1ce2c | 3,612,672 |
def get_plugin_option(name, options):
"""
Retrieve option name from options dict.
:param options:
:return:
"""
for o in options:
if o.get('name') == name:
return o['value'] | 38720ed9f0a42a543260d75dd043d4d9136b8fef | 3,612,673 |
def run_cc(hf):
"""
Run and return a restricted CCSD calculation on mol,
with HF molecular orbital coefficients in the RHF object hf.
"""
if type(hf) == SCF_TYPES['RHF']:
calc_cls = cc.CCSD
elif type(hf) == SCF_TYPES['UHF']:
calc_cls = cc.UCCSD
else:
raise NotImplemen... | c8a48215891f6c29c54efb6b45f8e8ee8906e97d | 3,612,674 |
def contains(
name,
value,
count_lt=None,
count_lte=None,
count_eq=None,
count_gte=None,
count_gt=None,
count_ne=None,
):
"""
Only succeed if the value in the given register location contains
the given value
USAGE:
.. code-block:: yaml
foo:
check.... | 2d4f6207c06db89461fb2e7854857a14b1e58e76 | 3,612,675 |
async def top_salty():
"""
### Returns top 10 saltiest user
- Takes `/top_salty`
### Response
`id` - userid
`username` - username
`saltiness` - saltiness
`salty_description` = salty description
"""
QUERY = "SELECT * FROM users ORDER BY saltiness limit 10"
pg_conn=db_conec... | 25521a15fd6aac0360de9230b9823b3baa92075d | 3,612,676 |
from datetime import datetime
def thai_strftime(
datetime: datetime.datetime, fmt: str, thaidigit: bool = False
) -> str:
"""
Convert :class:`datetime.datetime` into Thai date and time format.
The formatting directives are similar to :func:`datatime.strrftime`.
This function uses Thai names and ... | 4be7be1e0490c2f7e7b0daec079082bea02f2ccd | 3,612,677 |
def dot_product(t1, t2, keep_dims=False, name=None, reduction_dim=None):
"""Computes the dot product of t1 and t2.
Args:
t1: A rank 2 tensor.
t2: A tensor that is the same size as t1.
keep_dims: If true, reduction does not change the rank of the input.
name: Optional name for this op.
reduction... | 95080d6dfc2845d700c1f57a8501832482065c6d | 3,612,678 |
def assert_boolean(raw_val):
"""
Assert that the value is boolean.
:return The value if it is boolean, otherwise raise an exception
"""
return assert_type(raw_val, bool) | 3d261ac4495a8d911aa828bdf64cd7260cf742db | 3,612,679 |
def classic_vs_bayesian_normal(mu, sigma, num_points, prior):
""" Compute both classical and Bayesian inference processes over the range of
data sample sizes (num_points) for a normal distribution with parameters
mu,sigma for comparison.
Args:
mu (scalar): the mean parameter of the normal distribution
... | 45d461ae62ba6dacff5aa2836a7617c21e4c0a3a | 3,612,680 |
def get_canonical_synonym(key):
"""Returns canonical synonym for key, else just key.
"""
if key == 'SAMPLE':
return MELTED_SCHEMA_KEY__ES_LABEL
return key | 48e86fc48f4d9dd354b17bdf206d5089dd2ec8ab | 3,612,681 |
import torch
def get_batch_pipe(data, neox_args):
"""A modification of get_batch() to work with the latest batch instead of an iterator."""
# Items and their type.
keys = ["text"]
datatype = torch.int64
tokens, labels, loss_mask, attention_mask, position_ids = _get_batch(
neox_args, neox_... | 5f629153bc467cf7ec94e8b5cdc3de17e1debaa4 | 3,612,682 |
def compute_precision(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(k=maxk, dim=1, largest=True, sorted=True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
... | 6986f09ac6385ae1409f998648babd2006bed63d | 3,612,683 |
import torch
def get_landmark_model(output_size) -> torch.nn.Module:
"""Build the convolutional network model with Keras Functional API.
Args:
output_size: the number of output node, usually equals to the number of marks times 2 (in 2d space).
Returns:
a model
"""
model = torch.n... | 20e6796e1a035aa94076de2979bddc449d6ecb37 | 3,612,684 |
def isPerfectSquare(p: int) -> bool:
"""Checks if given number is a perfect square.
A perfect square is an integer that is a square of another integer.
Parameters:
p: int
number to check
Returns:
result: bool
True if number is a perfect square
F... | d9c725193a5100e06825944239fe3442bed17b92 | 3,612,685 |
def frequencies_for_cutoffs(col, cutoffs):
""" Sets cutoffs for the frequencies """
# Sets each frequency to 0 by default
freqs = [0] * len(cutoffs)
for el in col:
for i in range(len(cutoffs)):
if el <= cutoffs[i]:
freqs[i] += 1
break
return freqs | 9784a7a68450d90de79de71804eb08bc796506eb | 3,612,686 |
def find(user_id, session):
"""
Find all the history.
:param user_id: history user_id
:param session: session
:return: history data.
"""
result = []
fetch = session.query(KMHistory)
for history in fetch.filter_by(user_id=user_id).all():
result.append(history)
return resul... | b95aabeec4a017a8e2fa8d6ec115f087a7c979cd | 3,612,687 |
import socket
def fetch(url, data='', agent=None, referrer=None, charset=None, verbose=0,
cookiejar={}, type=None, method=None, accept_language=None):
"""Make an HTTP or HTTPS request.
If 'data' is given, do a POST; otherwise do a GET.
If 'agent', 'referrer' and/or 'accept_language' are given,... | e60eec53733ee7f705df33920ab564481125a0ac | 3,612,688 |
import json
def emolument_new_view(request):
"""
Add new emolument
"""
# Check authorization
if not Utils.has_permission(request, request.registry.settings['affaire_facture_edition']):
raise exc.HTTPForbidden()
params = request.params
data = json.loads(params['data'])
emolumen... | 0a48dc228ce8ecf87f1574a2fc99e8db946d092f | 3,612,689 |
def display(auth_context):
"""
View function for displaying the checkout page.
Parameters:
auth_context (dict): The authentication context of request.
See middlewares/auth.py for more information.
Output:
Rendered HTML page.
"""
products = []
# Pre... | 24ddd9b8b47a0a06d6d11d60f2854625e07eaff4 | 3,612,690 |
def golden_ratio(n):
"""returns the Golden Ratio to an accuracy of `n` decimal places
Examples
--------
>>> print(golden_ratio(20))
1.61803398874989484820
>>> print(golden_ratio(50))
1.61803398874989484820458683436563811772030917980576
"""
x = _sym.symbols('x')
gr = [sol for sol... | 35b95aea80e25d6ff024966c74e9df773ae40e26 | 3,612,691 |
from datetime import datetime
import aiohttp
import async_timeout
async def _is_new_version_available() -> bool:
"""Return `True` if a newer archive of the repo at http://github.com/zwave-js/node-zwave-js is available."""
file_updated_at = _load_db_from_file().get(UPDATED_AT)
if file_updated_at is None:
... | ae150ccbab9fd9f2976ad79498c4e03e7949356b | 3,612,692 |
def totalbp(file):
"""Count total number of sequenced base pairs"""
with open(file, 'r') as Infile:
loci = ''
Count = 0
Loci_count = 0
start = False
for line in Infile:
#count first locus
if Loci_count == 0:
... | 0b1f47c379bcb3cb33a6baa82907db4044b5e220 | 3,612,693 |
import mysensors.mysensors as mysensors
import socket
def setup(hass, config):
"""Setup the MySensors component."""
version = config[DOMAIN].get(CONF_VERSION)
persistence = config[DOMAIN].get(CONF_PERSISTENCE)
def setup_gateway(device, persistence_file, baud_rate, tcp_port, in_prefix,
... | 723e0a43f750987ec3707fda76c8ef0bca32966e | 3,612,694 |
def oppositeFunction(basef):
""" the opposite of a function """
if isinstance(basef, FitnessEvaluator):
if isinstance(basef, FunctionEnvironment):
''' added by JPQ '''
if isinstance(basef, MultiObjectiveFunction):
res = MultiObjectiveFunction()
else:
... | 7a15e025dc3cfc488a843a974db1d9368930b5a8 | 3,612,695 |
import os
def _state(base, kwargs):
"""Gets version and package_data. Writes MANIFEST.in.
Args:
base (dict): our base params
Returns:
dict: base updated
"""
state = {}
sha = '\n'
if not 'version' in kwargs:
state['version'], s = _version(base)
if s:
... | ada0a3bff4724e443248216d6d9cff8c076f89ed | 3,612,696 |
def cell(n):
"""Format a cell"""
return '{:3} {:5}'.format(
n, 'SPACE'
if n == 32 else 'DEL' if n == 127 else chr(n) if n >= 33 else 'NA') | a7696335b1962ab9b6fc661c3884f278e8cc38c9 | 3,612,697 |
def shape_arrays_for_pcolor_plotting(ps, indexing_list_indep_vars, ordered_params, dep_var_mgf):
""" """
X = ps.get_mgf_arr(ordered_params[0].name)[
tuple(indexing_list_indep_vars)]
Y = ps.get_mgf_arr(ordered_params[1].name)[
tuple(indexing_list_indep_vars)]
Z = None
if (np.shape(d... | 5fb92e455459d632690b3cb24dc62a4b837da7f1 | 3,612,698 |
def adoytoymd(year, doy, hour=0, min=0, sec=0):
"""adoytoymd(year, doy, hour, min, sec) -> string
Convert an array time with a day-of-year to a year-month-day time string. The
hour, minute and second parameters are optional. All input parameters must
be of type int."""
#
# validate input values
#
... | e3a8073c527d82a4123abdba97766295b6ad6241 | 3,612,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.