content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import List
def load_actions(action_file: str) -> List[str]:
"""
Load unique actions from an action file
"""
return load_uniq_lines(action_file) | a5ffe3ccac462bc8277da6174a5eb81071a6fb84 | 30,500 |
def get_formula(name, sbml_model, params, assignment_rules, replacements):
"""
get a string representation for a function definition with parameters already replaced
@param name: function name
@type name: str
@param sbml_model: libsbml model
@type sbml_model: libsbml.model
@param params: par... | eb7b521d8349f0bbb156faf10faa57a84ebe3034 | 30,501 |
def ConvertFile(filename_in, filename_out, loglevel='INFO'):
"""
Converts an ANSYS input file to a python pyansys script.
Parameters
----------
filename_in : str
Filename of the ansys input file to read in.
filename_out : str
Filename of the python script to write a translation... | b044b565193ca0d78edd77706cdeb1711d95f063 | 30,502 |
from typing import Optional
def get_metadata_saml(idp_id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetMetadataSamlResult:
"""
Use this data source to retrieve SAML IdP metadata from Okta.
## Example Usage
```python
import pulumi
imp... | 5b4e1fdf72d7e11d7f4eee878e88e174b452cfa5 | 30,503 |
from typing import Dict
def _average_latency(row: Dict):
"""
Calculate average latency for Performance Analyzer single test
"""
avg_sum_fields = [
"Client Send",
"Network+Server Send/Recv",
"Server Queue",
"Server Compute",
"Server Compute Input",
"Serve... | f321cb4d55af605298225f2f0146a9a71ee7895b | 30,504 |
from typing import Dict
from typing import Any
import json
import re
def load_dict_from_string(string: str) -> Dict[str, Any]:
"""Convert string to JSON string, convert to a dictionary, and return."""
logger.debug('Loading Dictionary from string: "{}"'.format(string))
json_string = jsonify_string(string)... | cf1282fe0e8cbf636222ed26f6ac2dc62488eebf | 30,505 |
def _(expr, assumptions):
"""
Integer**Integer -> !Prime
"""
if expr.is_number:
return _PrimePredicate_number(expr, assumptions)
if ask(Q.integer(expr.exp), assumptions) and \
ask(Q.integer(expr.base), assumptions):
return False | da1b018ef6fdb6987666806ce34ee784d03cff9b | 30,506 |
import tqdm
import torch
def train(model, trainLoader, optimizer, loss_function, device, trainParams):
"""
Function to train the model for one iteration. (Generally, one iteration = one epoch, but here it is one step).
It also computes the training loss, CER and WER. The CTC decode scheme is always 'gree... | f2726ad6f63997abd670c5f4614b1cef1e35dec7 | 30,507 |
def reorder(A, B):
"""Change coefficient order from y**2 xy x**2 to x**2 xy y**2 in both A and B.
Parameters
----------
A : array
polynomial coefficients
B : array
polynomial coefficients
Returns
-------
A2, B2: numpy arrays
coefficients with changed order
... | 6a4740a0423bc3a804e66b0cda4a444a7f58072e | 30,508 |
import functools
import collections
def collate_revs(old, new, key=lambda x: x, merge=lambda old, new: new):
"""
Given revision sets old and new, each containing a series
of revisions of some set of objects, collate them based on
these rules:
- all items from each set are yielded in stable order
... | 06f37d895fd906513aa3b85fb2ff48e0f2f2b625 | 30,509 |
from typing import Tuple
from typing import List
def load_conversation(
filename: str,
dictionary: corpora.Dictionary,
with_symbol: bool=True
) -> (Tuple[List[int], List[int]]):
"""対話コーパスをロードする。
Args:
filename (str): コーパスファイル
コーパスファイルの一行は
何 が 好き です か ?,Python ... | fb7aec9ea228fe528d6744564c1a2b298a33575c | 30,510 |
def close_incons_reduction(incons: list):
"""
Two step:
0. under the same backends pair
1. the same input, choose largest.(done before)
* 2. different inputs with small distance. Do not update(not used)
"""
def is_duplicate(t: tuple, li: list):
"""unique inconsistency"""
for... | 5fd581471ff361d2351b2dd8285d606399667e21 | 30,511 |
def mf2tojf2(mf2):
"""I'm going to have to recurse here"""
jf2={}
items = mf2.get("items",[])
jf2=flattenProperties(items,isOuter=True)
#print jf2
return jf2 | 399fa35f592bb6ec042003ed2884f94078ac01fd | 30,512 |
def import_all(filename):
""" Imports file contents from user with parameters from nueral net and later calculations
currently not robust to missing or incorrect arguments from file
currently does not convert values to int; done in later functions
inputs: filename - name of input file, curre... | ab5b2fecb6cadd2754d52cc9333d110955ca10c7 | 30,513 |
from typing import Union
from pathlib import Path
from typing import Dict
from typing import Tuple
from typing import Any
def fill_database(path: Union[str, Path], settings: SettingsConfig,
inputs: MeasurementInputs, alchemy: Alchemy,
parent_location_id: int, sex_id: int, child_pri... | 39836b397a7cf384bf3ca493914f9d024baf9f6f | 30,514 |
def ydhms2dt(year,doy,hh,mm,ss):
"""
ydhms2dt Take a year, day-of-year, etc and convert it into a date time object
Usage: dto = ydhms2dt(year,day,hh,mm,ss)
Input: year - 4 digit integer
doy - 3 digit, or less integer, (1 <= doy <= 366)
hh - 2 digit, or less int, (0 <= hh <... | 3d8fd1a6086f3dd35c80c2d862e820b7aecc5e5b | 30,515 |
def create_test_db(verbosity=1, autoclobber=False):
"""
Creates a test database, prompting the user for confirmation if the
database already exists. Returns the name of the test database created.
"""
# If the database backend wants to create the test DB itself, let it
creation_module = get_creat... | 87659029e01399f6d46780dbd3e2809bc809b70c | 30,516 |
import _ctypes
def key_import(data, key_type=KEY_TYPE.SYMMETRIC, password=b''):
"""Imports a key or key generation parameters."""
key = _ctypes.c_void_p()
_lib.yaca_key_import(key_type.value, _ctypes.c_char_p(password),
data, len(data), _ctypes.byref(key))
return Key(key) | 9cbe8dfcab3e854b096a5628c6be52d6873e8ca1 | 30,517 |
def test_training_arguments_timestamp(monkeypatch, grim_config):
"""Test TrainingWrapperArguments correctly applies a timestamp."""
def mock_return():
return '2019-06-29_17-13-41'
monkeypatch.setattr(grimagents.common, "get_timestamp", mock_return)
grim_config['--timestamp'] = True
argume... | 391b2fdbf716bfdc22f8449a3692679d6018f200 | 30,518 |
def to_vsizip(zipfn, relpth):
""" Create path from zip file """
return "/vsizip/{}/{}".format(zipfn, relpth) | 6f5baf380bd7ab8a4ea92111efbc0f660b10f6f8 | 30,519 |
import sys
def readMashDBParams(dbPrefix, kmers, sketch_sizes, mash_exec = 'mash'):
"""Get kmers lengths and sketch sizes from existing database
Calls :func:`~getKmersFromReferenceDatabase` and :func:`~getSketchSize`
Uses passed values if db missing
Args:
dbPrefix (str)
Prefix fo... | 6cdf5f0b337c123412ee6f3c437ca671ed463e02 | 30,520 |
import fastr
def crossval(config, label_data, image_features,
param_grid=None, use_fastr=False,
fastr_plugin=None, tempsave=False,
fixedsplits=None, ensemble={'Use': False}, outputfolder=None,
modus='singlelabel'):
"""
Constructs multiple individual classifi... | 90d543973861152f2e89acc6e444b3e1a9c465f5 | 30,521 |
def flw3i8e(ex, ey, ez, ep, D, eq=None):
"""
Compute element stiffness (conductivity)
matrix for 8 node isoparametric field element.
Parameters:
ex = [x1,x2,x3,...,x8]
ey = [y1,y2,y3,...,y8] element coordinates
ez = [z1,z2,z3,...,z8]
ep = [ir] ... | 90377f5ba6205e0f3bf1bc4f1fa0b84a4c69eec9 | 30,522 |
def cidr_to_netmask(value):
"""
Converts a CIDR prefix-length to a network mask.
Examples:
>>> "{{ '24'|cidr_to_netmask }}" -> "255.255.255.0"
"""
return str(netaddr.IPNetwork("1.1.1.1/{}".format(value)).netmask) | 232f4fb65be712bfb040d75ada40ed0450d84e2d | 30,523 |
def rgb_to_name(rgb_triplet: IntTuple, spec: str = CSS3) -> str:
"""
Convert a 3-tuple of integers, suitable for use in an ``rgb()``
color triplet, to its corresponding normalized color name, if any
such name exists.
The optional keyword argument ``spec`` determines which
specification's list o... | fdce9304c4d16d348fe37a920ae7cf44f3c3f56b | 30,524 |
def get_rr_Lix(N, Fmat, psd, x):
"""
Given a rank-reduced decomposition of the Cholesky factor L, calculate
L^{-1}x where x is some vector. This way, we don't have to built L, which
saves memory and computational time.
@param N: Vector with the elements of the diagonal matrix N
@param Fma... | 3658342296f18f3afdedf2cc790e1d0062e6c49d | 30,525 |
def ParameterSet_Create(*args):
"""
Create() -> ParameterSet
ParameterSet_Create(std::string const & publicID) -> ParameterSet
"""
return _DataModel.ParameterSet_Create(*args) | c6d6ef68505119b1b146d2be267a416341e09271 | 30,526 |
def generate_html_from_cli_args(cli_dict_for_command):
"""
Turn the dict into an html representation of the cli args and options.
:param cli_dict_for_command:
:return str:
"""
# def arg_md(opt, long_opt, default, help):
# return f"*) {opt}, {long_opt}, {help}\n"
text = ""
# ev... | 15c3b6f98141ab989cbe229a2b30778d5c664c9a | 30,527 |
def conical_sigma_Mach_walldeflection(Mach, deflection, gamma=defg._gamma):
"""computes shock angle sigma from upstream Mach number and wall deflection
Args:
Mach: param deflection:
gamma: Default value = defg._gamma)
deflection:
Returns:
"""
def local_def(sig):
"""inte... | 97fc3ac999f4a598860dcf25b4fd537bfcaf9326 | 30,528 |
def get_hashrate_info(results, miner, algo):
"""
Get Hashrate Information for a particular Miner and Algo
Returns:
dict
"""
# do the lookup
hashrate_info = results.get_hashrate_info(miner, algo)
if hashrate_info is None:
logger.warning("Model/Algo combination does not ex... | e94d0d7345a54181a9d5547afd1209419a92b497 | 30,529 |
import hashlib
def verify_verification_code(doctype, document_name, verification_code):
"""This method verfies the user verification code by fetching the originally sent code by the system from cache.
Args:
doctype (str): Name of the DocType.
document_name (str): Name of the document of the D... | 4013d2c2ff3eb318c16af8d43ca8b50af53379ea | 30,530 |
def orient1(ppos, apos, bpos):
"""
ORIENT1 return orientation of PP wrt. the line [PA, PB].
"""
#---------------------------------------------- calc. det(S)
smat = np.empty(
(2, 2, ppos.shape[0]), dtype=ppos.dtype)
smat[0, 0, :] = \
apos[:, 0] - ppos[:, 0]
smat[0, 1, :] = \
... | 705a27bde14c31262471b5d6a3621a695d8c091d | 30,531 |
def get_storm_data(storm_path):
""" Obtain raster grid of the storm with rasterio
Arguments:
*storm_path* (string) -- path to location of storm
"""
with rio.open(storm_path) as src:
# Read as numpy array
array = src.read(1)
array = np.array(array,dtype='flo... | 6db69cbd6970da467021a186f3062beaa6ed7387 | 30,532 |
import functools
def wrap_with_spectral_norm(module_class,
sn_kwargs=None,
pow_iter_collection=None):
"""Returns a constructor for the inner class with spectral normalization.
This function accepts a Sonnet AbstractModule class as argument (the class,
*no... | 5c849f2ee4dd8cd818ff7bebfb0564857bbb18de | 30,533 |
def ask_daemon_sync(view, ask_type, ask_kwargs, location=None):
"""Jedi sync request shortcut.
:type view: sublime.View
:type ask_type: str
:type ask_kwargs: dict or None
:type location: type of (int, int) or None
"""
daemon = _get_daemon(view)
return daemon.request(
ask_type,
... | 665a302445c4661d3e5610914bde688cd4512968 | 30,534 |
import logging
import time
def _etl_epacems(etl_params, datapkg_dir, pudl_settings, ds_kwargs):
"""Extract, transform and load CSVs for EPA CEMS.
Args:
etl_params (dict): ETL parameters required by this data source.
datapkg_dir (path-like): The location of the directory for this
p... | 5e9b951205c8e5d50d8b07f5b7661fcbc4595a80 | 30,535 |
def GetNvccOptions(argv):
"""Collect the -nvcc_options values from argv.
Args:
argv: A list of strings, possibly the argv passed to main().
Returns:
1. The string that can be passed directly to nvcc.
2. The leftover options.
"""
parser = ArgumentParser()
parser.add_argument('-nvcc_options', n... | bb143edb6099eb6182fe7b79e53422321cb3e03d | 30,536 |
import json
def show_node(request, name='', path='', revision=''):
"""
View for show_node page, which provides context for show_node.html
Shows description for yang modules.
:param request: Array with arguments from webpage data submition.
:param module: Takes first argument from url if request do... | 20e3a87be8f2d85632fe26cc86a3cc7742d2de33 | 30,537 |
def compute_F1(TP, TN, FP, FN):
"""
Return the F1 score
"""
numer = 2 * TP
denom = 2 * TP + FN + FP
F1 = numer/denom
Acc = 100. * (TP + TN) / (TP + TN + FP + FN)
return F1, Acc | 6f012246337534af37ff233ad78d9645907739e3 | 30,538 |
def name_full_data():
"""Full name data."""
return {
"name": "Doe, John",
"given_name": "John",
"family_name": "Doe",
"identifiers": [
{
"identifier": "0000-0001-8135-3489",
"scheme": "orcid"
}, {
"identifier... | ac590635dbe33e68dc88acd890d16dd3137befb2 | 30,539 |
def platypus(in_file, data):
"""Filter Platypus calls, removing Q20 filter and replacing with depth and quality based filter.
Platypus uses its own VCF nomenclature: TC == DP, FR == AF
Platypus gVCF output appears to have an 0/1 index problem so the reference block
regions are 1 base outside regions o... | 00979a3de36b051882e42e2231cac69a67dfec20 | 30,540 |
def delete(i):
"""
Input: { See 'rm' function }
Output: { See 'rm' function }
"""
return rm(i) | 048742483608b7530ee217a60c96f4c4f6ec6fb0 | 30,541 |
import logging
def _get_remote_image_id(s3_object) -> str:
"""
Get the image id of the docker cache which is represented by the S3 object
:param s3_object: S3 object
:return: Image id as string or None if object does not exist
"""
try:
if S3_METADATA_IMAGE_ID_KEY in s3_object.metadata:... | 07b73824c1f03ae24f584ef38ab0a2c37f3d436e | 30,542 |
def test_circuit_str(default_compilation_configuration):
"""Test function for `__str__` method of `Circuit`"""
def f(x):
return x + 42
x = hnp.EncryptedScalar(hnp.UnsignedInteger(3))
inputset = range(2 ** 3)
circuit = hnp.compile_numpy_function(f, {"x": x}, inputset, default_compilation_c... | abf2955b7cd440124eb2e2acf685aa84d69a3e4a | 30,543 |
def add_game():
"""Adds game to database"""
check_admin()
add_game = True
form = GameForm()
# Checks if form is valid
if form.validate_on_submit():
game = Game(name=form.name.data)
try:
db.session.add(game)
db.session.commit()
flash('Game suc... | 9134516408a1931a41a901b4523713871f580da0 | 30,544 |
def requires_moderation(page):
"""Returns True if page requires moderation
"""
return bool(page.get_moderator_queryset().count()) | 8f1cfa852cbeccfae6157e94b7ddf61d9597936e | 30,545 |
from typing import Optional
def _get_node_info(
node: NodeObject,
current_path: str,
node_type: str,
label: Optional[str] = None,
is_leaf: bool = True
) -> NodeInfo:
"""
Utility method for generating a NodeInfo from a NodeObject
:param node: NodeObject to convert in... | d0084dc757dd9501dc2853a1445524cbde9a0756 | 30,546 |
def get_peers():
"""Retrieve PeerIds and SSIDs for peers that are ready for OOB transfer"""
query = 'SELECT Ssid, PeerId from EphemeralState WHERE PeerState=1'
data = exec_query(query, db_path_peer)
return data | 9ab81631cf1f779b3a80b246e0a6144e46599a64 | 30,547 |
from bs4 import BeautifulSoup
def get_html_text(html):
"""
Return the raw text of an ad
"""
if html:
doc = BeautifulSoup(html, "html.parser")
return doc.get_text(" ")
return "" | 14353f368078ea6b1673d1066b0a529cc3e257d9 | 30,548 |
def valid_parentheses(string):
"""
Takes a string of parentheses, and determines if the order of the parentheses is valid.
:param string: a string of parentheses and characters.
:return: true if the string is valid, and false if it's invalid.
"""
stack = []
for x in string:
if x == "... | e8438404c461b7a113bbbab6417190dcd1056871 | 30,549 |
import os
import ctypes
def find_microbit():
"""
Returns a path on the filesystem that represents the plugged in BBC
micro:bit that is to be flashed. If no micro:bit is found, it returns
None.
Works on Linux, OSX and Windows. Will raise a NotImplementedError
exception if run on any other oper... | 967460400a32b0e18ec7f5193712b108f903113d | 30,550 |
def in_2core_graph_slow(cats: ArrayLike) -> BoolArray:
"""
Parameters
----------
cats: {DataFrame, ndarray}
Array containing the category codes of pandas categoricals
(nobs, ncats)
Returns
-------
retain : ndarray
Boolean array that marks non-singleton entries as Tru... | 46fc377643849b68d9071c9e592c1bba68a23a83 | 30,551 |
def has_form_encoded_header(header_lines):
"""Return if list includes form encoded header"""
for line in header_lines:
if ":" in line:
(header, value) = line.split(":", 1)
if header.lower() == "content-type" \
and "x-www-form-urlencoded" in value:
... | e4fe797e4884161d0d935853444634443e6e25bb | 30,552 |
from pathlib import Path
def get_best_checkpoint_path(path: Path) -> Path:
"""
Given a path and checkpoint, formats a path based on the checkpoint file name format.
:param path to checkpoint folder
"""
return path / LAST_CHECKPOINT_FILE_NAME_WITH_SUFFIX | b0637dd0fac5df3b7645cceec62f23fc3d48d4eb | 30,553 |
def storage_charge_rule(model, technology, timepoint):
"""
Storage cannot charge at a higher rate than implied by its total installed power capacity.
Charge and discharge rate limits are currently the same.
"""
return model.Charge[technology, timepoint] + model.Provide_Power[technology, timepoint] <... | 9f437d11f1eb1ce894381de10b719c9c08271396 | 30,554 |
def blck_void(preprocessor: Preprocessor, args: str, contents: str) -> str:
"""The void block, processes commands inside it but prints nothing"""
if args.strip() != "":
preprocessor.send_warning("extra-arguments", "the void block takes no arguments")
preprocessor.context.update(preprocessor.current_position.end, "... | 841be11c1f8f7b9d4c3552cdafe0aaa590b8fb9d | 30,555 |
import typing
def resize_image(image: np.ndarray,
width: typing.Optional[int] = None,
height: typing.Optional[int] = None,
interpolation=cv2.INTER_AREA):
"""
Resize image using given width or/and height value(s).
If both values are passed, aspect ratio is... | ee8bf8424bb23a941a7858a97d1b4ff6b5187d38 | 30,556 |
def attr(*args, **kwargs):
"""Decorator that adds attributes to classes or functions
for use with unit tests runner.
"""
def wrapped(element):
for name in args:
setattr(element, name, True)
for name, value in kwargs.items():
setattr(element, name, value)
r... | 77d20af87cef526441aded99bd6e24e21e5f81f9 | 30,557 |
def convert_units(table_name, value, value_unit, targets):
"""
Converts a given value in a unit to a set of target units.
@param table_name Name of table units are contained in
@param value Value to convert
@param value_unit Unit value is currently in
@param targets List of units to convert to
... | b8cdbeafa78ec71450e69cec6913e805bd26fa8a | 30,558 |
import os
def find_vital_library_path(use_cache=True):
"""
Discover the path to a VITAL C interface library based on the directory
structure this file is in, and then to system directories in the
LD_LIBRARY_PATH.
:param use_cache: Store and use the cached path, preventing redundant
search... | c124666e62be6bc9ea687fc812c2879342b437a2 | 30,559 |
def hex2binary(hex_num):
""" converts from hexadecimal to binary """
hex1 = h[hex_num[0]]
hex2 = h[hex_num[1]]
return str(hex1) + str(hex2) | 78d2a804d5f02c985d943e6242bc66143905df2f | 30,560 |
def nn(value: int) -> int:
"""Casts value to closest non negative value"""
return 0 if value < 0 else value | 08672feaefa99881a110e3fc629d4a9256f630af | 30,561 |
def resolve_vcf_counts_data(vcf_data, maf_data, matched_normal_sample_id, tumor_sample_data_col):
""" Resolves VCF allele counts data. """
vcf_alleles = [vcf_data["REF"]]
vcf_alleles.extend(vcf_data["ALT"].split(","))
tumor_sample_format_data = vcf_data["MAPPED_TUMOR_FORMAT_DATA"]
normal_sample_for... | 5e10d54038a84bc93a4d6b09ae5368e61ae3312f | 30,562 |
def example_profile_metadata_target():
"""Generates an example profile metadata document.
>>> root = example_profile_metadata_target()
>>> print_tree(root)
<?xml version='1.0' encoding='UTF-8'?>
<Profile xmlns="http://soap.sforce.com/2006/04/metadata">
<classAccesses>
<apexClass>ARTra... | 6e43847aec021e188c001ad59e297ecdfc31d202 | 30,563 |
def separate(expr, deep=False):
"""Rewrite or separate a power of product to a product of powers
but without any expanding, ie. rewriting products to summations.
>>> from sympy import *
>>> x, y, z = symbols('x', 'y', 'z')
>>> separate((x*y)**2)
x**2*y**2
>>> separate((x... | ae30943f0073508d85212f97d4298f63e16fcc05 | 30,564 |
import os
def get_sub_dirs(path: str):
"""Get sub-directories contained in a specified directory
Args:
path (str): path to directory
Returns:
str: lists of absolute paths
str: list of dir names
"""
try:
dirs = os.walk(path).next()[1]
except AttributeError:
... | f9f58521622020b7c164e7b3ba5096b92fc28848 | 30,565 |
def app_base(request):
"""
This should render the required HTML to start the Angular application. It is the only entry point for
the pyramid UI via Angular
:param request: A pyramid request object, default for a view
:return: A dictionary of variables to be rendered into the template
"""
de... | 3a097e920b33248b436e2eea00e05b5708b35779 | 30,566 |
from typing import List
import re
def check_lists(document: Document, args: Args) -> List[Issue]:
"""Check that markdown lists items:
- Are preceded by a blank line.
- Are not left empty.
- End with a period if they're a list of sentences.
- End without a period if they're a list of items."""
... | e224206b0683239fe957dd78795b8f2de69d4149 | 30,567 |
def transform_one(mt, vardp_outlier=100_000) -> Table:
"""transforms a gvcf into a form suitable for combining
The input to this should be some result of either :func:`.import_vcf` or
:func:`.import_vcfs` with `array_elements_required=False`.
There is a strong assumption that this function will be cal... | 7961d5ea3d0b0e58332552c9c3c72692f34868db | 30,568 |
def volume_rebalance(volume: str) -> Result:
"""
# This function doesn't do anything yet. It is a place holder because
# volume_rebalance is a long running command and I haven't decided how to
# poll for completion yet
# Usage: volume rebalance <VOLNAME> fix-layout start | start
# [force]|stop|... | 03df7752b45d90f84720be12f32703c1109d71c2 | 30,569 |
import json
def get_droplet_ip():
"""get droplet ip from cache."""
cached_droplet_info_file = 'droplet_info.json'
with open(cached_droplet_info_file, 'r') as info_f:
droplet_info = json.load(info_f)
return droplet_info['networks']['v4'][0]['ip_address'] | 21d0bfbbe6aebd7e88cc6465d49b221da271753a | 30,570 |
def country_converter(text_input, abbreviations_okay=True):
"""
Function that detects a country name in a given word.
:param text_input: Any string.
:param abbreviations_okay: means it's okay to check the list for abbreviations, like MX or GB.
:return:
"""
# Set default values
country_... | 19bdd3be63ee2a1165d8fc121203694da9732fea | 30,571 |
def lat_long_to_idx(gt, lon, lat):
"""
Take a geotransform and calculate the array indexes for the given lat,long.
:param gt: GDAL geotransform (e.g. gdal.Open(x).GetGeoTransform()).
:type gt: GDAL Geotransform tuple.
:param lon: Longitude.
:type lon: float
:param la... | 3fafcc4750daa02beaedb330ab6273eab6abcd56 | 30,572 |
def bugs_mapper(bugs, package):
"""
Update package bug tracker and support email and return package.
https://docs.npmjs.com/files/package.json#bugs
The url to your project's issue tracker and / or the email address to
which issues should be reported.
{ "url" : "https://github.com/owner/project/i... | 81f037ecb314dde5d7643da8e021662ac74daa7f | 30,573 |
def BSMlambda(delta: float, S: float, V: float) -> float:
"""Not really a greek, but rather an expression of leverage.
Arguments
---------
delta : float
BSM delta of the option
V : float
Spot price of the option
S : float
Spot price of the underlying
Returns... | ea9bf546a7cf46b3c2be01e722409663b05248e1 | 30,574 |
import pwd
def uid_to_name(uid):
"""
Find the username associated with a user ID.
:param uid: The user ID (an integer).
:returns: The username (a string) or :data:`None` if :func:`pwd.getpwuid()`
fails to locate a user for the given ID.
"""
try:
return pwd.getpwuid(uid).... | f9054e4959a385d34c18d88704d376fb4b718e47 | 30,575 |
def fit_poly(data, error_func, degree = 3):
""" Fit a polynomial to given data, using supplied error function.
Parameters
----------
data: 2D array where each row is a point (X0, Y)
error_func: function that computes the error between a polynomial and observed data
degree: polynomial degree
... | 007693c1e01edc69cee27dd1da0836087d8a2d11 | 30,576 |
def find_skyrmion_center_2d(fun, point_up=False):
"""
Find the centre the skyrmion, suppose only one skyrmion
and only works for 2d mesh.
`fun` accept a dolfin function.
`point_up` : the core of skyrmion, points up or points down.
"""
V = fun.function_space()
mesh = V.mesh()
c... | 030c704681a48cdeca1f880f08fe9fb039572640 | 30,577 |
import time
def test(num_games, opponent, silent):
""" Test running a number of games """
def autoplayer_creator(state):
""" Create a normal autoplayer instance """
return AutoPlayer(state)
def minimax_creator(state):
""" Create a minimax autoplayer instance """
return Au... | c7560e2d298039b5f201b57779e14b4a38054160 | 30,578 |
import webbrowser
def pseudo_beaker(UserId: str, SessionId: str, replay=True, scope=True, browser=None, OrgId: str=None, is_staging: bool=True) -> dict:
"""
Mimic the Beaker admin tool in opening up one or both of session replay and
Scope tools for a given User Id and Session Id.
Option to specify a ... | 6cf905762b76d90a4d32459d9259b452ffc89240 | 30,579 |
def table_parse(table):
"""
"""
data = []
rows = table.find_all('tr')
for row in rows:
cols = row.find_all('td')
cols = [ele.text.strip() for ele in cols]
data.append([ele for ele in cols if ele])
return data | 528008ada0ad7d594554ed5d577472a126df0cd1 | 30,580 |
import pandas
import numpy
def scan_mv_preprocessing_fill_pivot_nan(df):
"""
Value imputation.
Impute missing data in pivot table.
Parameters
----------
df : dataframe
Pivot table data with potentially missing values.
Returns
-------
df : dataframe
Pivot table da... | e88d1b2b0a3d4fc27afe29a10512116323046cef | 30,581 |
def image_show(request,item_container):
""" zeigt die Beschreibung der Datei an """
app_name = 'image'
vars = get_item_vars_show(request, item_container, app_name)
file_path = DOWNLOAD_PATH + item_container.container.path
file_name = file_path + item_container.item.name
width, height = get_image_size(file_n... | b68286bedd92aba7991e8994bf76d84bfe5d4c2e | 30,582 |
import logging
import collections
import functools
def train_and_eval():
"""Train and evaluate StackOver NWP task."""
logging.info('Show FLAGS for debugging:')
for f in HPARAM_FLAGS:
logging.info('%s=%s', f, FLAGS[f].value)
hparam_dict = collections.OrderedDict([
(name, FLAGS[name].value) for name ... | 30eb088295ae8bc9ef5cd67fc042802f91c85627 | 30,583 |
def common_kwargs(cfg, bin_count, pointing):
"""Creates a prepfold-friendly dictionary of common arguments to pass to prepfold"""
name = generate_prep_name(cfg, bin_count, pointing)
prep_kwargs = {}
if cfg["run_ops"]["mask"]:
prep_kwargs["-mask"] = cfg["run_ops"]["mask"]
prep_kwargs["-o"] = ... | c6a1f2ceb475e8f0d2b3e905d8109f79d77d3b79 | 30,584 |
def quatMultiply(q1,q2):
"""Returns a quaternion that is a composition of two quaternions
Parameters
----------
q1: 1 x 4 numpy array
representing a quaternion
q2: 1 x 4 numpy array
representing a quatnernion
Returns
-------
qM: 1 x 4 numpy array
rep... | 2c32f0390d01b36258c9bcabc290a47dca592ded | 30,585 |
def expandingPrediction(input_list, multiple=5):
"""
:param input_list:
:param multiple:
:return:
"""
expanded_list = []
for prediction in input_list:
for i in range(multiple):
expanded_list.append(prediction)
return expanded_list | 9a502adb15160e656bd727748eb5dae73858d7f8 | 30,586 |
def pages_siblings_menu(context, page, url='/'):
"""Get the parent page of the given page and render a nested list of its
child pages. Good for rendering a secondary menu.
:param page: the page where to start the menu from.
:param url: not used anymore.
"""
lang = context.get('lang', pages_sett... | 723249cd73ec95b947f279a99e88afe2ec51868d | 30,587 |
def aes(img, mask=None, canny_edges=None, canny_sigma=2):
"""Calculate the Average Edge Strength
Reference:
Aksoy, M., Forman, C., Straka, M., Çukur, T., Hornegger, J., & Bammer, R. (2012).
Hybrid prospective and retrospective head motion correction to mitigate cross-calibration errors.
Magnetic ... | 52cdcf45609e7ee35eb7d05a2529d4330b6509b4 | 30,588 |
def projection(basis, vectors):
"""
The vectors live in a k dimensional space S and the columns of the basis are vectors of the same
space spanning a subspace of S. Gives a representation of the projection of vector into the space
spanned by basis in term of the basis.
:param basis: an n-by-k array... | 107a1db030d0af7af346128fea10e5f7657b1a6a | 30,589 |
import json
import os
def _build_execution_context(worker_index, ports):
"""
Create execution context for the model.
:param worker_index: The index of this worker in a distributed setting.
:param ports: A list of port numbers that will be used in setting up the servers.
:return: The generated exec... | c036656637bae0ec543fe31445305bb32e3572a6 | 30,590 |
import numpy
def grab(sequence, random = numpy.random):
"""
Return a randomly-selected element from the sequence.
"""
return sequence[random.randint(len(sequence))] | 1760dc08b5971647f55248bd1b1f04d700dac38e | 30,591 |
def csl_url_args_retriever():
"""Returns the style and locale passed as URL args for CSL export."""
style = resource_requestctx.args.get("style")
locale = resource_requestctx.args.get("locale")
return style, locale | 96f87dd927f998b9599663432a95c2330b15b2d0 | 30,592 |
import glob
import os
def list_available_filter():
"""
List all available filter responses
Returns
-------
filter_dict : dict
Dictionary of filter names containing lists of available instruments
"""
filter_list = glob(FILTER_DIR + '*_*.dat')
filter_dict = {}
for filter_fi... | 01037a742cb0ce4b4f3918ce060d94e07c7e74db | 30,593 |
import random
def select_parents(population, m):
"""Select randomly parents for the new population from sorted by
fitness function existing population."""
fitness_population = sorted(
population,
key=lambda child: fitness_function(child, m),
reverse=True)
# ordered_population =... | 3f0a2de28da7355ce34f692f7bb0722896903c51 | 30,594 |
def rsqrt(x: Tensor):
"""Computes reciprocal of square root of x element-wise.
Args:
x: input tensor
Returns:
output tensor
Examples:
>>> x = tf.constant([2., 0., -2.])
>>> rsqrt(x)
<Tensor: shape=(3,), dtype=float32,
numpy=array([0.707, inf, nan], dtype=f... | 39b4574311eb74ccef18ddb936d1d92fbb0c1fd9 | 30,595 |
def averageObjPeg(objpegpts, planet, catalog=None, sceneid='NO_POL'):
"""
Average peg points.
"""
logger.info('Combining individual peg points: %s' % sceneid)
peg = stdproc.orbit.pegManipulator.averagePeg([gp.getPeg() for gp in objpegpts], planet)
pegheights = [gp.getAverageHeight() for gp in ob... | 92e41d33d3aa21ee6036e3f1a6550d81d793129e | 30,596 |
def _bytes_chr_py2(i):
"""
Returns a byte string of length 1 whose ordinal value is i in Python 2.
Do not call directly, use bytes_chr instead.
"""
return chr(i) | de524d1ec303cc297d7981570ef30aa9ae6840ed | 30,597 |
from typing import Any
def convert(parser: Any) -> c2gtypes.ParserRep:
"""Convert getopt to a dict.
Args:
parser (Any): docopt parser
Returns:
c2gtypes.ParserRep: dictionary representing parser object
"""
return {"parser_description": "", "widgets": extract(parser)} | cf6e53bd514bdb114c3bc5d3b7429c6a8f17881d | 30,598 |
def redirect_vurlkey(request, vurlkey, *args, **kwargs):
"""redirect_vurlkey(vurlkey) looks up the Vurl with base58-encoded index VURLKEY and issues a redirect to the target URL"""
v = Vurl.get_with_vurlkey(vurlkey.encode('utf-8'))
return v.http_response() | 99e4be6b43a8b983f9c8efdb60ccf2873ce3caf2 | 30,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.