content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
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
#
... | 5,290,400 |
def file_selector():
"""Function enables the user to select the txt files that they have downloaded.
returns:
"""
layout = [[sg.Text("Choose a file: "),sg.Input(key="-IN2-" ,change_submits=True), sg.FileBrowse(key="-IN-")],
[sg.Button("Submit")]]
window = sg.Window("File... | 5,290,401 |
def connect_cursor(USERPATH):
"""Connect a cursor to database.
Input: Path to authorized user "secrets.yaml" file that is
expected to include connection parameters
Output: Database cursor object
Future consideration:
enable user to input latest year of available data instead
of hard... | 5,290,402 |
def avoid_other_snakes(my_head: Dict[str, int], snakes: List[dict], possible_moves: List[str]) -> List[str]:
"""
my_head: Dictionary of x/y coordinates of the Battlesnake head.
e.g. {"x": 0, "y": 0}
snakes: List of dictionaries containing information about enemy Battlesnakes.
possible_moves:... | 5,290,403 |
def calculateJitterPercent(data):
"""
calculate jitter in percent
"""
return calculateJitterRatio(data) / 10.0 | 5,290,404 |
def create_sim_openmm(model, anchor, output_filename, state_prefix=None):
"""
Take all relevant model and anchor information and generate
the necessary OpenMM objects to run the simulation.
Parameters
----------
model : Model()
The Model which contains the anchor and all settings fo... | 5,290,405 |
def process_tenant(aci_session, tenant, override=False, fetch_endpoints=False):
"""
:param aci_session: ACI session
:param tenant: Cisco Tenant Object
:param override: Purge existing configurations for this Tenant in BAM
:param fetch_endpoints: Boolean - Import endpoints
:return:
"""
if... | 5,290,406 |
def get_supported_formats(request):
"""Return a dictionary of possible conversions between image formats.
CSRF protection is not required on GET request."""
if request.method == "GET":
return JsonResponse(data=SUPPORTED_FORMATS)
else:
return HttpResponse(content="Use GET method", status=... | 5,290,407 |
def main():
"""
Take the first CLI argument and describe the corresponding word
"""
# handle the --version switch
if '--version' in sys.argv:
print('duden ' + __version__)
sys.exit(0)
# parse normal arguments
args = parse_args()
# search all words matching the string
... | 5,290,408 |
def expunge(file, dry_run, table, output, flag, verbose, model, **kwargs):
"""Expunge (NaN flagged values) FILE and save to OUTPUT.
"""
from .commands.expunge import expunge_command
expunge_command(file, output, flagcol=flag, dry_run=dry_run, verbose=verbose, model=model, table=table, **kwargs) | 5,290,409 |
def check_check(rgx, *tests):
"""
Enables fast testing whether a regex works as designed.
:param rgx: regex to test
:param tests: input characters
:return:
"""
for test in tests:
print(test, rgx.check(test)) | 5,290,410 |
def test_mech_suspend_fails(mock_locate, mock_load_mechfile,
mock_vmrun_suspend, mechfile_two_entries):
"""Test 'mech suspend' powered on."""
mock_load_mechfile.return_value = mechfile_two_entries
runner = CliRunner()
result = runner.invoke(cli, ['suspend', 'first'])
mock... | 5,290,411 |
async def websocket_unbind_devices(hass, connection, msg):
"""Remove a direct binding between devices."""
zha_gateway = hass.data[DATA_ZHA][DATA_ZHA_GATEWAY]
source_ieee = msg[ATTR_SOURCE_IEEE]
target_ieee = msg[ATTR_TARGET_IEEE]
await async_binding_operation(
zha_gateway, source_ieee, targe... | 5,290,412 |
def tf_cache_template(function, scope=None, *args, **kwargs):
"""
A decorator for class methods that define TensorFlow operations.
The function is first wrapped in a variable_scope() that allows
us to specify a initializer, regularizer etc.
The result is then wrapped in a make_template() so that
... | 5,290,413 |
def nms(dets, thresh, soft_nms=False):
"""Dispatch to either CPU or GPU NMS implementations."""
if dets.shape[0] == 0:
return []
elif soft_nms:
return cpu_soft_nms(dets, thresh, method = 1)
else:
return cpu_nms(dets, thresh) | 5,290,414 |
def mean_expression(df, annotation, stage_regex=r".*", normal=False):
"""Return the mean expression values of the subset of samples.
Parameters
----------
df: pandas.DataFrame
Each row is a gene and each column is a sample.
annotation: pandas.DataFrame
A data frame w... | 5,290,415 |
def get_contract_stat():
"""
获取合同金额
:return: 合同数、总计金额
"""
mongo_db.connect_db('ext_system')
contracts = do_search('contract_t', {})
_count = len(contracts)
_total = 0.
for _r in contracts:
if (len(_r[u'金额']) > 0) and ((_r[u'金额'].replace('.', '')).isdigit()):
_tota... | 5,290,416 |
def get_posts_url_from_page(page_url):
"""
获取指定页面中所有文章的URL
:param page_url
:return:
"""
try:
response = yield httpclient.AsyncHTTPClient().fetch(page_url, headers=headers)
soup = BeautifulSoup(response.body, 'html.parser')
posts_tag = soup.find_all('div', class_="post flo... | 5,290,417 |
def split_env_items(env_string: str) -> List[str]:
"""Splits space-separated variable assignments into a list of individual assignments.
>>> split_env_items('VAR=abc')
['VAR=abc']
>>> split_env_items('VAR="a string" THING=3')
['VAR="a string"', 'THING=3']
>>> split_env_items('VAR="a string" THI... | 5,290,418 |
def tree2diagram(tree, dom=Ty()):
"""
Takes a depccg.Tree in JSON format,
returns a :class:`discopy.biclosed.Diagram`.
"""
if 'word' in tree:
return Word(tree['word'], cat2ty(tree['cat']), dom=dom)
children = list(map(tree2diagram, tree['children']))
dom = Ty().tensor(*[child.cod for... | 5,290,419 |
def test_sun():
"""Test sun fake"""
_ = sun_fake(
batch_size=4,
seq_length_5=13,
) | 5,290,420 |
def intersection_over_box(chips, boxes):
"""
intersection area over box area
:param chips: C
:param boxes: B
:return: iob, CxB
"""
M = chips.shape[0]
N = boxes.shape[0]
if M * N == 0:
return np.zeros([M, N], dtype='float32')
box_area = bbox_area(boxes) # B
inter_... | 5,290,421 |
def get_past_seasons(num_seasons):
"""
Go back num_seasons from the current one
"""
season = CURRENT_SEASON
seasons = []
for i in range(num_seasons):
season = get_previous_season(season)
seasons.append(season)
return seasons | 5,290,422 |
def LineGroupInstanceAdd(data,fileName, seperator="^\\s*$"):
"""
add some extra data to an instance list.
"""
data.add(LineGroupIterator(FileReader(File(fileName)),
Pattern.compile(seperator),
1)) | 5,290,423 |
def magma_sgesv(n, nhrs, A, lda, ipiv, B, ldb):
"""
Solve system of linear equations.
"""
info = c_int_type()
status = _libmagma.magma_sgesv(n, nhrs, int(A), lda,
int(ipiv), int(B),
ldb, ctypes.byref(info))
magmaCheckStatus(... | 5,290,424 |
def signup(request):
"""
A method to add another user to the known users
:param request:
:return:
"""
# logger.debug("signup")
if request.method == 'POST':
# logger.debug("signup, method POST")
form = SignUpForm(request.POST)
if form.is_valid():
# logger.d... | 5,290,425 |
def _CollectGpuSamples(
vm: virtual_machine.BaseVirtualMachine) -> List[sample.Sample]:
"""Run CUDA memcpy on the cluster.
Args:
vm: The virtual machine to run the benchmark.
Returns:
A list of sample.Sample objects.
"""
if not nvidia_driver.CheckNvidiaSmiExists(vm):
return []
global_metad... | 5,290,426 |
def remove_host(config, sync_name, name):
""" remove sync """
sync = get_sync(config, name)
sync['hosts'].remove(get_host(config, sync_name, name))
return True | 5,290,427 |
def slow_function():
"""
模拟思考过程
:return: 结果
"""
time.sleep(3)
return 43 | 5,290,428 |
def full_jitter(value):
"""Jitter the value across the full range (0 to value).
This corresponds to the "Full Jitter" algorithm specified in the
AWS blog's post on the performance of various jitter algorithms.
(http://www.awsarchitectureblog.com/2015/03/backoff.html)
Args:
value: The unadu... | 5,290,429 |
def get_lldp_neighbors(device):
"""Get current LLDP neighbor information.
Return a two-level dictionary with the LLDP neighbor information..
The first-level key is the local port (aka interface) name.
The second-level keys are 'system' for the remote system name
and 'port' for the remote port ID. O... | 5,290,430 |
def _get_temporal_concepts(world: owlready2.World) -> set:
"""
Fetches all classes, data and object properties that are used within the definition (equivalence or subclass) of
some temporal criticality phenomenon. Also regards SWRL rules.
:param world: World to get temporal concepts in.
:return: A s... | 5,290,431 |
def _pathcontains_filter(files, pathcontains):
"""Filtre par chemin"""
filtered_files = []
for file in files:
if pathcontains in file:
filtered_files.append(file)
return filtered_files | 5,290,432 |
def test_dev_requirements_sorted():
"""
Check that dev-requirements.in is sorted (within sections).
"""
with open(os.path.join(REPO_DIR, 'dev-requirements.in'), 'r') as f:
lines = f.readlines()
def is_comment_or_empty(line):
return not line.strip() or line.lstrip().startswith('#')
... | 5,290,433 |
def dprime(y_true, y_pred, pmarg: float = 0.01, outputs: List[str] = ['dprime', 'bias', 'accuracy']) -> tuple:
"""
Calculate D-Prime for binary data.
70% for both classes is d=1.0488.
Highest possible is 6.93, but effectively 4.65 for 99%
http://www.birmingham.ac.uk/Documents/college-les/psych/visi... | 5,290,434 |
def main():
"""Main function. Set up widgets, calculate, plot."""
st.set_page_config(layout='wide')
# Set up sidebar input widgets
with st.sidebar:
P_des, n_des, p, r, n_max = params()
complementary, inclusive, out_txt = range_cond()
# Proportions of output screen
left_col... | 5,290,435 |
def function_to_be_decorated():
"""This is documentation for function_to_be_decorated."""
return True | 5,290,436 |
def read_file_utf8(data_file, mode='more'):
"""
读文件, 原文件和数据文件
:return: 单行或数组
"""
try:
with open(data_file, 'r', encoding='utf8') as f:
if mode == 'one':
output = f.read()
return output
elif mode == 'more':
output = f.rea... | 5,290,437 |
def cli(config_file):
"""Main entry point.
Args:
config_file (str): File path to the kube-config file.
"""
try:
config.load_kube_config(config_file=config_file)
except Exception as e:
logger.error(
"Kubernetes configuration not set. `deploy` and `destroy` comman... | 5,290,438 |
async def load_fake_data(quantity: Optional[int] = 0) -> Dict[str, Any]:
"""loading fake data
Returns:
redirect to root path /
"""
await API_functools.insert_default_data(quantity=quantity)
return RedirectResponse(url="/") | 5,290,439 |
def test_eap_teap_tls_cs_sha1(dev, apdev):
"""EAP-TEAP with TLS cipher suite that uses SHA-1"""
run_eap_teap_tls_cs(dev, apdev, "AES128-SHA") | 5,290,440 |
def sync_send(msg: SMSMessage, secret: str) -> str:
"""Synchronously send an SMSMessage, using the requests library.
Returns:
The response from the server.
Raises:
SMSSendError if sending failed.
"""
headers = {"X-Profile-Secret": secret}
data = msg.as_dict()
r = requests.... | 5,290,441 |
def _divisor_gen(n):
"""Generate divisors of n"""
# Refactoring of "What is the best way to get all the divisors of a number"
# at http://stackoverflow.com/a/171784.
if n == 1:
yield 1
return
primes, multiplicities = split(prime_factorization(n))
# Since factors are prime, each p... | 5,290,442 |
def play_turn(algod_client, player, addr_adversary,
addr_game_table, game_table_lsig,
addr_sink, sink_lsig,
addr_adversary_bet_escrow, adversary_bet_escrow_lsig,
asa_turn_id, asa_pieces_id,
asa_pieces_max_remove, asa_pieces_amount, asa_pieces_total):... | 5,290,443 |
def expmap(u, x0):
"""
This function maps a vector u lying on the tangent space of x0 into the manifold.
Parameters
----------
:param u: vector in the tangent space
:param x0: basis point of the tangent space
Returns
-------
:return: point on the manifold
"""
if np.ndim(x0)... | 5,290,444 |
def zip_py(module_dir='fncore'):
"""Zips python module for submission to Spark"""
root_dir = os.path.abspath(os.path.join(module_dir, os.pardir))
base_dir = os.path.relpath(module_dir, root_dir)
temp_dir = tempfile.gettempdir()
zippath = os.path.join(temp_dir, 'fn_pyspark_module_' + base_dir)
... | 5,290,445 |
def get_abertura_context(document: Dict, max_size: int = 4000) -> str:
"""Returns the abertura content of the document_text.
"""
document_text = document['text']
max_size = update_max_size(document, max_size=max_size)
context = document_text[:max_size]
return context | 5,290,446 |
def page(cursor=None, limit=None, user=None):
"""# Retrieve paged Webhooks
Receive a list of up to 100 Webhook objects previously created in the Stark Bank API and the cursor to the next page.
Use this function instead of query if you want to manually page your requests.
## Parameters (optional):
- ... | 5,290,447 |
def integer_at_least(actual_value, expected_value):
"""Assert that actual_value is an integer of at least expected_value."""
result = isinstance(actual_value, int)
if result:
result = actual_value >= expected_value
if result:
return result
else:
raise AssertionError(
... | 5,290,448 |
def test_write_modality_agnostic_files(tmp_path):
"""Test function `write_modality_agnostic_files`."""
import os
from clinica.iotools.bids_utils import write_modality_agnostic_files
assert len(os.listdir(tmp_path)) == 0
write_modality_agnostic_files("ADNI", tmp_path)
files = os.listdir(tmp_pat... | 5,290,449 |
def save_to_table(out_dir, name, dryrun, **kwargs):
"""Save keys to .csv files."""
# Check for file
if not os.path.isdir(out_dir):
os.makedirs(out_dir)
fname = os.path.join(out_dir, f'table_{name}.csv')
fieldnames = list(kwargs.keys())
# Read or write header
try:
with open(f... | 5,290,450 |
def test_calendar__CalendarDisplaySettings__1():
"""It fulfills the `ICalendarDisplaySettings` interface."""
assert verifyObject(ICalendarDisplaySettings, CalendarDisplaySettings()) | 5,290,451 |
def calculate_his3p_small_wh_coefficients():
"""
Calculate the Walsh-Hadamard coefficients of the His3p(small) fitness functions.
"""
return _calculate_wh_coefficients_complete('his3p_small') | 5,290,452 |
def eq(a, b, n):
"""Euler's quadratic formula"""
## : coefficient: a, b int
## : n int | n >= 0
rst = n**2 + a*n + b
return rst | 5,290,453 |
def test_sdss_compressed(compress, tmp_path):
"""Test automatic recognition of supported compression formats.
"""
ext = {'gzip': '.gz', 'bzip2': '.bz2', 'xz': '.xz'}
if compress == 'bzip2' and not HAS_BZ2:
pytest.xfail("Python installation has no bzip2 support")
if compress == 'xz' and not H... | 5,290,454 |
def generate_lattice(ltype, volume, minvec=tol_m, minangle=pi/6, max_ratio=10.0, maxattempts = 100, **kwargs):
"""
Generates a lattice (3x3 matrix) according to the space group symmetry and
number of atoms. If the spacegroup has centering, we will transform to
conventional cell setting. If the generated... | 5,290,455 |
def is_unqdn(cfg, name):
"""
Returns True if name has enough elements to
be a unqdn (hostname.realm.site_id)
False otherwise
"""
parts = name.split(".")
if len(parts) >= 3:
return True
else:
return False | 5,290,456 |
def logMessage(*args: Any, level: int = INFO, loggername: str = None, sep=" "):
"""
Logs messages to logging log. Gui widgets can be subscribed to the log with:
logging.getLogger().addHandler(callable)
Parameters
----------
args : tuple[str]
Similar to python 3's print()... | 5,290,457 |
def get_proj(geom, proj_list=None):
"""Determine best projection for input geometry
"""
out_srs = None
if proj_list is None:
proj_list = gen_proj_list()
#Go through user-defined projeciton list
for projbox in proj_list:
if projbox.geom.Intersects(geom):
out_srs = proj... | 5,290,458 |
def format_vertex(body: Json) -> Json:
"""Format vertex data.
:param body: Input body.
:type body: dict
:return: Formatted body.
:rtype: dict
"""
vertex: Json = body["vertex"]
if "_oldRev" in vertex:
vertex["_old_rev"] = vertex.pop("_oldRev")
if "new" in body or "old" in bo... | 5,290,459 |
def get_tag_list(frmt):
"""
Gets a list of tags from the XML conversion output of a specific document.
:param frmt: format/extension of the input document (document must be present in the tests/in folder)
:return: list of element tags
"""
oxobj = OxGaWrap(f'tests/in/test.{frmt}')
tree = oxob... | 5,290,460 |
def get_window(window, Nx, fftbins=True):
"""Compute a window function.
This is a wrapper for `scipy.signal.get_window` that additionally
supports callable or pre-computed windows.
Parameters
----------
window : string, tuple, number, callable, or list-like
The window specification:
... | 5,290,461 |
def test_offense_records_by_jurisdiction(batch, jurisdiction):
"""Offense records helper function should allow filtering by jurisdiction."""
ciprs_record = CIPRSRecordFactory(jurisdiction=jurisdiction, batch=batch)
offense = OffenseFactory(
disposition_method=constants.DISMISSED_DISPOSITION_METHODS[... | 5,290,462 |
def haversine(pt, lat2=42.355589, lon2=-71.060175):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
lon1 = pt[0]
lat1 = pt[1]
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])... | 5,290,463 |
def download_using_ftp(username: str,
password: str,
public_address: str,
remote_file: str,
log: logging.Logger,
download_path: str = videos) -> Tuple:
"""Download/fetch/transfer file using OpenSSH... | 5,290,464 |
def check_ip(ip):
"""Checks whether given IP address is valid or not.
Implements only basic checking."""
if ip is not None:
iplst = ip.split('.')
if len(iplst) != 4:
return False
for num in iplst:
if int(num) > 255 or int(num) < 0:
ret... | 5,290,465 |
def adcp_earth_vertical(w):
"""
Description:
Wrapper function to compute the Upward Velocity Profile (VELPROF-VLU)
from Earth coordinate transformed velocity profiles as defined in the
Data Product Specification for Velocity Profile and Echo Intensity -
DCN 1341-00750.
... | 5,290,466 |
def to_comma_type(numpy_type):
"""
convert a single numpy type to comma type
numpy arrays are unrolled and converted to a prefixed comma type
>>> from comma.csv.format import *
>>> to_comma_type('f8')
'd'
>>> to_comma_type('S12')
's[12]'
>>> to_comma_type('3u4')
'3ui'
>>> t... | 5,290,467 |
def generate_hists(yaml_config, output='out.root', systematics='ALL', numpy=False):
"""
Generate histograms based on a single YAML file.
This is essentially a wrapper around the functions
- generate_data_hists
- generate_mc_hists
steered by the config file
Parameters
----------
yaml... | 5,290,468 |
def is_valid_medialive_channel_arn(mlive_channel_arn):
"""Determine if the ARN provided is a valid / complete MediaLive Channel ARN"""
if mlive_channel_arn.startswith("arn:aws:medialive:") and "channel" in mlive_channel_arn:
return True
else:
return False | 5,290,469 |
def Faculty4(request):
"""
Returns the render for the sdg graph
"""
data = dataFrameSDG().drop(columns = "Misc")
data2 = data.T
data3 = data2.reset_index(level = 0)
data4=data3.rename(columns=data3.iloc[0]).drop(data3.index[0])
figure = px.bar(data4, x = "Faculty", y = FacultyIndex["... | 5,290,470 |
def est_vega(S, K, r, sigma, T):
""" Define a function to calculate the vega
which is also the derivative of option with respect to sigma
"""
d = (np.log(S/K) + (r + 0.5 * sigma* sigma)* T) / (sigma * np.sqrt(T))
vega = S * np.sqrt(T) * norm.pdf(d)
return vega | 5,290,471 |
def generate_a_pair() -> Tuple[int, int]:
"""
Generate private ephemeral a and public key A.
Returns:
Tuple (private a (int), public A (int))
"""
prime = _get_srp_prime()
generator = _get_srp_generator()
a = _to_int(_generate_random_bytes(32)) # RFC-5054 reccomends 256 bits
A... | 5,290,472 |
def perform_data_filtering_q3(data):
"""
Takes the original DataFrame.
Returns the altered DataFrame necessary for Q3.
"""
df = data
angina_presence = df['cp'] <= 2
df['cp'] = np.where(angina_presence, 1, 0)
return df | 5,290,473 |
def reload_config(test_run: RunnerEnvironment) -> dict:
"""Load configuration of test as JSON-object."""
return load(open(test_run.test_env.config_file, 'r')) | 5,290,474 |
def generate_random_particle(_id, input_size, neurons):
"""Function to generate random particle to init PSO algorithm"""
position = []
speed = []
n_neurons = sum(neurons)
n_weights = input_size * neurons[0]
for i in range(len(neurons) - 1):
n_weights = n_weights + neurons[i]*neurons[i+1]... | 5,290,475 |
def print_enclosed_text(text):
"""Print some text, enclosed by horizontal lines."""
print('-' * 80)
print(text)
print('-' * 80)
print() | 5,290,476 |
def model_fn(model,
features,
mode,
hparams,
problem_names,
train_steps=100000,
worker_id=0,
worker_replicas=1,
eval_run_autoregressive=False,
decode_hparams=None):
"""Builds the model for all modes.
... | 5,290,477 |
def convert_tf_to_crowdsourcing_format(images, detections):
"""
Args:
images: dictionary {image_id : image info} (images from Steve's code)
detections: detection output from multibox
Returns:
dict : a dictionary mapping image_ids to bounding box annotations
"""
image_annotation... | 5,290,478 |
def smtp_send(receiver):
"""Function to perform the last action of sending email"""
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
server.login(sender_email, password)
server.sendmail(sender_email, receiver, message.as_string()) | 5,290,479 |
def horn_schunk_flow(img0,img2,lambada,max_iter,epsilon):
"""
:param img0: first frame
:param img2: second frame
:param lambada: hyper parameter
:param max_iter: threshold for iterations
:param epsilon: decay rate
:return: flow and gradient
"""
decay=10000
i=0
## averaging k... | 5,290,480 |
def true_pred_hist(
y_true: NumArray,
y_pred: NumArray,
y_std: NumArray,
ax: Axes = None,
cmap: str = "hot",
bins: int = 50,
log: bool = True,
truth_color: str = "blue",
**kwargs: Any,
) -> Axes:
"""Plot a histogram of model predictions with bars colored by the mean uncertainty o... | 5,290,481 |
def read_typetree(
nodes: List[Union[dict, TypeTreeNode]], reader: EndianBinaryReader
) -> dict:
"""Reads the typetree of the object contained in the reader via the node list.
Parameters
----------
nodes : list
List of nodes/nodes
reader : EndianBinaryReader
... | 5,290,482 |
def read_bip32_keys_gap_size(db: sqlite3.Connection, account_id: int,
masterkey_id: int, prefix_bytes: bytes) -> int:
"""
Identify the trailing BIP32 gap (of unused keys) at the end of a derivation sequence.
For now we create keys in a BIP32 sequence sequentially with no gaps, so we can take the
... | 5,290,483 |
def convert_bool_to_0_or_1(
params: Optional[Dict[str, Any]]
) -> Optional[Dict[str, Any]]:
"""Converts all bool values in dict to "0" or "1".
Slack APIs safely accept "0"/"1" as boolean values.
Using True/False (bool in Python) doesn't work with aiohttp.
This method converts only the bool values i... | 5,290,484 |
def calc_kin_temp(vel, nums, masses, kB):
"""
Calculates the kinetic energy and temperature.
Parameters
----------
kB: float
Boltzmann constant in chosen units.
masses: numpy.ndarray
Mass of each species.
nums: numpy.ndarray
Number of particles of each species.
... | 5,290,485 |
def test_values():
""" Check a Matching can have its `values` accessed. """
matching = Matching()
assert list(matching.values()) == []
matching = Matching(dictionary)
assert list(matching.values()) == reviewers | 5,290,486 |
def calc_P_remain(
P_avail: pd.DataFrame,
P_req: pd.Series,
gidx: wio.GearMultiIndexer,
):
"""Return `p_avail - p_req` for all gears > g2 in `gwot`. """
c = wio.pstep_factory.get().cycle
## Drop pandas axis or else substraction would fail with:
# ValueError: cannot join with no overla... | 5,290,487 |
def prefix_path(path,src_list):
"""
prefix the path to every file in the src_list
"""
return [os.path.join(path,e) for e in src_list] | 5,290,488 |
def load_user(user_id: str) -> User:
"""Return the current JWT user."""
return user_domain_logic.get_user(user_id) | 5,290,489 |
def _process_exp(client, job_id="test", worker_id=None, bonus_mode="random", clear_session=True, url_kwargs=None):
"""
:param client: (flask.testclient)
:param job_id: (str)
:param worker_id: (str)
:param bonus_mode: (str: random|full|none)
:param clear_session: (bool)
"""
exp_value = in... | 5,290,490 |
def get_argparser():
"""
Returns an argument parser for this script
"""
parser = ArgumentParser(description='Predict using a U-Time model.')
parser.add_argument("--folder_regex", type=str, required=False,
help='Regex pattern matching files to predict on. '
... | 5,290,491 |
def remove_empty_routes(operator: Callable[..., Solution]):
"""
Wrapper function that removes empty routes from the returned solution
instance. These routes may come into existence because all customers have
been removed by e.g. a destroy operator.
"""
@wraps(operator)
def decorator(*args, *... | 5,290,492 |
def _get_zipname(platform):
"""Determine zipfile name for platform.
Parameters
----------
platform : str
Platform that will run the executables. Valid values include mac,
linux, win32 and win64. If platform is None, then routine will
download the latest asset from the github r... | 5,290,493 |
def AddBond():
"""Template written as an example for OTHER people to write their own"""
from Pmv.picker import AtomPicker
p = AtomPicker(self, numberOfObjects=2, gui=0)
p.go(modal=1)
atoms = p.getObjects()
assert atoms[0].top == atoms[1].top
from MolKit.molecule import Bond
Bond(atoms[0]... | 5,290,494 |
def interleaved_gate_fidelity_bounds(irb_decay: float, rb_decay: float, dim: int,
unitarity: Optional[float] = None):
"""
Use observed rb_decay to place a bound on fidelity of a particular gate with given interleaved
rb decay.
Optionally, use unitarity measurement r... | 5,290,495 |
def session_factory_from_settings(settings):
"""
Convenience method to construct a ``MongoSessionFactory`` from Paste config
settings. Only settings prefixed with "mongo.sessions" will be inspected
and, if needed, coerced to their appropriate types (for example, casting
the ``timeout`` value as an `... | 5,290,496 |
def f_stock():
"""
Real Name: b'F Stock'
Original Eqn: b'INTEG ( F Acquisition Rate-F Shipment Rate, 400)'
Units: b'SKU'
Limits: (None, None)
Type: component
b''
"""
return integ_f_stock() | 5,290,497 |
def deep_ensemble_predict(x,
models,
training_setting,
uncertainty_type='entropy'):
"""Deep Ensembles uncertainty estimator.
Args:
x: `numpy.ndarray`, datapoints from input space, with shape [B, H, W, 3],
where B the batch size... | 5,290,498 |
def tsPredFig(df, item, predictDays):
"""
This function is to predict the community demand using Prophet Time Series Algorithms.
Args:
df (dataframe) : dataset
item (str) : product type that was selected
predictDays(int): days for prediction
Returns:
forecast : da... | 5,290,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.