content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def default_sv2_sciencemask():
"""Returns default mask of bits for science targets in SV1 survey.
"""
sciencemask = 0
sciencemask |= sv2_mask["LRG"].mask
sciencemask |= sv2_mask["ELG"].mask
sciencemask |= sv2_mask["QSO"].mask
sciencemask |= sv2_mask["BGS_ANY"].mask
sciencemask |= sv2_mas... | 33,700 |
def upsert(biomodelos, geoserver, models_info, models_folder):
"""Create or update the model file in Geoserver for an existing model
in BioModelos
MODELS_INFO \t csv file that maps the tax_id, model_id and model_file
for each model to upload
MODELS_FOLDER \t Path to folder that contains all the fi... | 33,701 |
def solver_softmax(K, R):
"""
K = the number of arms (domains)
R = the sequence of past rewards
"""
softmax = np.zeros(K, dtype=float)
for i, r in R.items():
softmax[i] = np.mean(r)
softmax = np.exp(softmax) / np.exp(softmax).sum()
si = np.random.choice(np.arange(0, K, 1), size... | 33,702 |
def mapview(request):
"""Map view."""
context = basecontext(request, 'map')
return render(request, 'map.html', context=context) | 33,703 |
def adapt_coastdat_weather_to_pvlib(weather, loc):
"""
Adapt the coastdat weather data sets to the needs of the pvlib.
Parameters
----------
weather : pandas.DataFrame
Coastdat2 weather data set.
loc : pvlib.location.Location
The coordinates of the weather data point.
Retur... | 33,704 |
def bprop_distribute(arr, shp, out, dout):
"""Backpropagator for primitive `distribute`."""
return (array_reduce(scalar_add, dout, shape(arr)),
zeros_like(shp)) | 33,705 |
def ids_to_non_bilu_label_mapping(labelset: LabelSet) -> BiluMappings:
"""Mapping from ids to BILU and non-BILU mapping. This is used to remove the BILU labels to regular labels"""
target_names = list(labelset["ids_to_label"].values())
wo_bilu = [bilu_label.split("-")[-1] for bilu_label in target_names]
... | 33,706 |
def generate_input_types():
"""
Define the different input types that are used in the factory
:return: list of items
"""
input_types = ["Angle_irons", "Tubes", "Channels", "Mig_wire", "Argon_gas", "Galvanised_sheets", "Budget_locks",
"Welding_rods", "Body_filler", "Grinding_discs"... | 33,707 |
def ase_tile(cell, tmat):
"""Create supercell from primitive cell and tiling matrix
Args:
cell (pyscf.Cell): cell object
tmat (np.array): 3x3 tiling matrix e.g. 2*np.eye(3)
Return:
pyscf.Cell: supercell
"""
try:
from qharv.inspect.axes_elem_pos import ase_tile as atile
except ImportError:
... | 33,708 |
def test_missing_access_fn() -> None:
"""
This test shows that the plugin needs an `access` provided or else it raises a type error.
"""
slot_filler = RuleBasedSlotFillerPlugin(rules=rules)
workflow = Workflow([slot_filler])
intent = Intent(name="intent", score=0.8)
body = "12th december"
... | 33,709 |
def in_order(root):
"""
In order traversal starts at the left node, then the root, then the right
node, recursively
"""
if root:
in_order(root.left)
print(root.value)
in_order(root.right) | 33,710 |
def timeout(timeout_sec, timeout_callback=None):
"""Decorator for timing out a function after 'timeout_sec' seconds.
To be used like, for a 7 seconds timeout:
@timeout(7, callback):
def foo():
...
Args:
timeout_sec: duration to wait for the function to return before timing out
... | 33,711 |
def p_anonymous_method_expression(p):
"""anonymous_method_expression : DELEGATE explicit_anonymous_function_signature_opt block
""" | 33,712 |
def parse_chat_logs(input_path, user, self):
"""
Get messages from a person, or between that person and yourself.
"self" does not necessarily have to be your name.
Args:
input_path (str): Path to chat log HTML file
user (str): Full name of person, as appears in Messenger app
se... | 33,713 |
def remove_undesired_text_from_xml(BLAST_xml_file):
""" Removes undesired text from malformed XML files delivered by NCBI server via biopython wrapper.
"""
undesired_text = "CREATE_VIEW\n"
BLAST_xml_file_orig = BLAST_xml_file[:-4] + "_orig.xml"
move(BLAST_xml_file, BLAST_xml_file_orig)
with open... | 33,714 |
def on_get(req, resp, schedule_id):
"""
Get schedule information. Detailed information on schedule parameters is provided in the
POST method for /api/v0/team/{team_name}/rosters/{roster_name}/schedules.
**Example request**:
.. sourcecode:: http
GET /api/v0/schedules/1234 HTTP/1.1
... | 33,715 |
def make_labels(dest_folder, zoom, country, classes, ml_type, bounding_box, sparse, **kwargs):
"""Create label data from OSM QA tiles for specified classes
Perform the following operations:
- If necessary, re-tile OSM QA Tiles to the specified zoom level
- Iterate over all tiles within the bounding box... | 33,716 |
def while_e():
""" Lower case Alphabet letter 'e' pattern using Python while loop"""
row = 0
while row<7:
col = 0
while col<6:
if col==0 and row>0 and row<6 or col>0 and col<5 and row%3==0 or col==5 and row in (1,2):
... | 33,717 |
def pressure_correction(pressure, rigidity):
"""
function to get pressure correction factors, given a pressure time series and rigidity value for the station
:param pressure: time series of pressure values over the time of the data observations
:param rigidity: cut-off rigidity of the station making... | 33,718 |
def get_file_size(file_name):
"""
:rtype numeric: the number of bytes in a file
"""
bytes = os.path.getsize(file_name)
return humanize_bytes(bytes) | 33,719 |
def test_cumulative_return():
"""
Test for the cumulative return calculation.
:return:
"""
data = pd.DataFrame({'date': ['2020-10-04 12:09:07', '2020-10-05 16:10:05',
'2020-10-06 12:01:00', '2020-10-07 17:00:00'],
'pnl': [100000, 90000, 7500... | 33,720 |
def get_project_path_info():
"""
获取项目路径
project_path 指整个git项目的目录
poseidon_path 指git项目中名字叫poseidon的目录
"""
_poseidon_path = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
_project_path = os.path.dirname(_poseidon_path)
return {"project_path": _project_path,
"poseid... | 33,721 |
def main(argv=sys.argv):
"""
Main method called by the eggsecutable.
:param argv:
:return:
"""
utils.vip_main(init_volttron_central, identity=VOLTTRON_CENTRAL,
version=__version__) | 33,722 |
def prepare_data(song: dict) -> dict:
"""
Prepares song dataa for database insertion to cut down on duplicates
:param song: Song data
:return: The song data
"""
song['artist'] = song['artist'].upper().strip()
song['title'] = song['title'].upper().strip()
return song | 33,723 |
def com(struct):
"""
Calculates center of mass of the system.
"""
geo_array = struct.get_geo_array()
element_list = struct.geometry['element']
mass = np.array([atomic_masses_iupac2016[atomic_numbers[x]]
for x in element_list]).reshape(-1)
total = np.sum(mass)
com = n... | 33,724 |
def distance_matrix(values, metric):
"""Generate a matrix of distances based on the `metric` calculation.
:param values: list of sequences, e.g. list of strings, list of tuples
:param metric: function (value, value) -> number between 0.0 and 1.0"""
matrix = []
progress = ProgressTracker(len(values))... | 33,725 |
def tic():
""" Python implementation of Matlab tic() function """
global __time_tic_toc
__time_tic_toc = time.time() | 33,726 |
def txt_write(lines: List[str], path: str, model: str = "w", encoding: str = "utf-8"):
"""
Write Line of list to file
Args:
lines: lines of list<str> which need save
path: path of save file, such as "txt"
model: type of write, such as "w", "a+"
encoding: type of encoding, suc... | 33,727 |
def _Pack(content, offset, format_string, values):
"""Pack values to the content at the offset.
Args:
content: String to be packed.
offset: Offset from the beginning of the file.
format_string: Format string of struct module.
values: Values to struct.pack.
Returns:
Updated content.
"""
si... | 33,728 |
def get_rotation_matrix(orientation):
"""
Get the rotation matrix for a rotation around the x axis of n radians
Args:
- (float) orientation in radian
Return:
- (np.array) rotation matrix for a rotation around the x axis
"""
rotation_matrix = np.array(
[[1, 0, 0],
... | 33,729 |
def logs_for_build(
build_id, session, wait=False, poll=10
): # noqa: C901 - suppress complexity warning for this method
"""Display the logs for a given build, optionally tailing them until the
build is complete.
Args:
build_id (str): The ID of the build to display the logs for.
wait (... | 33,730 |
def prepare_labels(label_type, org_xml_dir=ORG_XML_DIR, label_dir=LABEL_DIR):
""" Prepare the neural network output targets."""
if not os.path.exists(os.path.join(label_dir, "TEXT")):
os.makedirs(os.path.join(label_dir, "TEXT"))
if not os.path.exists(os.path.join(label_dir, "WORDLIST")):
os... | 33,731 |
def machinesize(humansize):
"""convert human-size string to machine-size"""
if humansize == UNKNOWN_SIZE:
return 0
try:
size_str, size_unit = humansize.split(" ")
except AttributeError:
return float(humansize)
unit_converter = {
'Byte': 0, 'Bytes': 0, 'kB': 1, 'MB': 2... | 33,732 |
def generate_erdos_renyi_netx(p, N):
""" Generate random Erdos Renyi graph """
g = networkx.erdos_renyi_graph(N, p)
W = networkx.adjacency_matrix(g).todense()
return g, torch.as_tensor(W, dtype=torch.float) | 33,733 |
def kmc_algorithm(process_list):
"""
:param rate_list: List with all the computed rates for all the neighbours for all the centers
:param process_list: List of elements dict(center, process, new molecule).
The indexes of each rate in rate_list have the same index that the associated process in
proce... | 33,734 |
def _update_changed_time(cnn: Connection) -> None:
"""Update task changed time."""
t: Table = PeriodicTasks.__table__
rv = cnn.execute(t.select(t.c.id == 1)).fetchone()
if not rv:
cnn.execute(t.insert().values(id=1, changed_at=datetime.now()))
else:
cnn.execute(
t.update... | 33,735 |
def __matlab_round(x: float = None) -> int:
"""Workaround to cope the rounding differences between MATLAB and python"""
if x - np.floor(x) < 0.5:
return int(np.floor(x))
else:
return int(np.ceil(x)) | 33,736 |
def db_remove(src_path, db, chat_id):
"""Removes a string entry from a database file and the given set variable.
If it does not already exist in the set, do not take any action.
"""
if chat_id in db:
with open(src_path, "r+") as f:
l = f.readlines()
f.seek(0)
... | 33,737 |
def rayleightest(circ_data, dim='time'):
"""Returns the p-value for the Rayleigh test of uniformity
This test is used to identify a non-uniform distribution, i.e. it is
designed for detecting an unimodal deviation from uniformity. More
precisely, it assumes the following hypotheses:
- H0 (null hyp... | 33,738 |
def load_cfg(cfg_file: Union[str, Path]) -> dict:
"""Load the PCC algs config file in YAML format with custom tag
!join.
Parameters
----------
cfg_file : `Union[str, Path]`
The YAML config file.
Returns
-------
`dict`
A dictionary object loaded from the YAML config fil... | 33,739 |
def generate(args):
"""Generates sample data for writing CBNs using the cli_main CLI utlity.
Args:
args: dict containing:
- log_type: string in the LOG_TYPE format
- start_date: optional string in the YYYY-MM-DD format The following
directory structure will be created (if it doesn't
exis... | 33,740 |
def test_api_exception():
"""Test API response Exception"""
with pytest.raises(BigoneAPIException):
with requests_mock.mock() as m:
json_obj = {
'errors': [{
'code': 20102,
'message': 'Unsupported currency ABC'
}]
... | 33,741 |
def pdist_triu(x, f=None):
"""Pairwise distance.
Arguments:
x: A set of points.
shape=(n,d)
f (optional): A kernel function that computes the similarity
or dissimilarity between two vectors. The function must
accept two matrices with shape=(m,d).
Returns... | 33,742 |
def simulate_in_dymola(heaPum, data, tableName, tableFileName):
""" Evaluate the heat pump performance from the model in Dymola.
:param heaPum: Heat pump model (object).
:param data: Reference performance data (object).
:param tableName: Name of the combiTimeTable.
:param tableFileName: Name of the... | 33,743 |
def get_model_defaults(cls):
"""
This function receives a model class and returns the default values
for the class in the form of a dict.
If the default value is a function, the function will be executed. This is meant for simple functions such as datetime and uuid.
Args:
cls: (obj) : A Mo... | 33,744 |
def mask_clip(mask_file, data_files, out_dir='.', pfb_outs=1, tif_outs=0) -> None:
"""clip a list of files using a full_dim_mask and a domain reference tif
Parameters
----------
mask_file : str
full_dim_mask file generated from shapefile to mask utility no_data,0's=bbox,1's=mask
data_files ... | 33,745 |
def add_response_headers(headers=None):
"""This decorator adds the headers passed in to the response"""
headers = headers or {}
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
resp = make_response(f(*args, **kwargs))
h = resp.headers
... | 33,746 |
def delete(path:pathlike) -> None:
"""Attempt to delete the canonical source file.
"""
protocol, fpath = _decompose(str(path))
if protocol == "file":
try:
pathlib.Path(fpath).unlink()
except Exception as e:
raise DeleteError(str(path), str(e))
elif protocol ==... | 33,747 |
def modules_in_pkg(pkg):
"""Return the list of modules in a python package (a module with a
__init__.py file.)
:return: a list of strings such as `['list', 'check']` that correspond to
the module names in the package.
"""
for _, module_name, _ in pkgutil.walk_packages(pkg.__path__):
... | 33,748 |
def restore(request: Request, project_id: int) -> JSONResponse: # pylint: disable=invalid-name,redefined-builtin
"""Restore project.
Args:
project_id {int}: project id
Returns:
starlette.responses.JSONResponse
"""
log_request(request, {
'project_id': project_id
})
... | 33,749 |
def _broadcast_arrays(x, y):
"""Broadcast arrays."""
# Cast inputs as numpy arrays
# with nonzero dimension
x = np.atleast_1d(x)
y = np.atleast_1d(y)
# Get shapes
xshape = list(x.shape)
yshape = list(y.shape)
# Get singltons that mimic shapes
xones = [1] * x.ndim
yones = [1... | 33,750 |
def Output(primitive_spec):
"""Mark a typespec as output."""
typespec = BuildTypespec(primitive_spec)
typespec.meta.sigdir = M.SignalDir.OUTPUT
return typespec | 33,751 |
def test__conformer_trunk():
""" tets dir_.conformer_trunk
"""
spc_trunk_ddir = dir_.conformer_trunk()
assert not spc_trunk_ddir.exists(PREFIX)
spc_trunk_ddir.create(PREFIX)
assert spc_trunk_ddir.exists(PREFIX) | 33,752 |
def cb_init_hook(optname, value):
"""exec arbitrary code to set sys.path for instance"""
exec(value) | 33,753 |
def save_predictions_df(predictions_df: np.ndarray,
directory: str,
last_observation_date: str,
forecast_horizon: int,
model_description: Optional[Dict[str, str]],
dataset_name: str,
... | 33,754 |
def partitionFromMask(mask):
""" Return the start and end address of the first substring without
wildcards """
for i in range(len(mask)):
if mask[i] == '*':
continue
for j in range(i+1, len(mask)):
if mask[j] == '*':
break
else:
if ... | 33,755 |
def test_invalid_method_in_check_parameters(method: str) -> None:
"""Test error in check_parameters when invalid method is selected."""
mapie = MapieRegressor(DummyRegressor(), method=method)
with pytest.raises(ValueError, match=r".*Invalid method.*"):
mapie.fit(X_boston, y_boston) | 33,756 |
def add_documents_to_index(documents, index, retries=DEFAULT_NUM_RETRIES):
"""Adds a document to an index.
Args:
- documents: a list of documents. Each document should be a dictionary.
Every key in the document is a field name, and the corresponding
value will be the field's value.
... | 33,757 |
def mask_to_bias(mask: Array, dtype: jnp.dtype) -> Array:
"""Converts a mask to a bias-like Array suitable for adding to other biases.
Arguments:
mask: <bool> array of arbitrary shape
dtype: jnp.dtype, desired dtype of the returned array
Returns:
bias: <bool> array of the same shape as the input, wi... | 33,758 |
def external_dependency(dirname, svnurl, revision):
"""Check out (if necessary) a given fixed revision of a svn url."""
dirpath = py.magic.autopath().dirpath().join(dirname)
revtag = dirpath.join('-svn-rev-')
if dirpath.check():
if not revtag.check() or int(revtag.read()) != revision:
... | 33,759 |
def optimize_clustering(
data,
algorithm_names: Union[Iterable, str] = variables_to_optimize.keys(),
algorithm_parameters: Optional[Dict[str, dict]] = None,
random_search: bool = True,
random_search_fraction: float = 0.5,
algorithm_param_weights: Optional[dict] = None,
algorithm_clus_kwargs:... | 33,760 |
def bashhub():
"""Bashhub command line client"""
pass | 33,761 |
def sql_fingerprint(query, hide_columns=True):
"""
Simplify a query, taking away exact values and fields selected.
Imperfect but better than super explicit, value-dependent queries.
"""
parsed_query = parse(query)[0]
sql_recursively_simplify(parsed_query, hide_columns=hide_columns)
return s... | 33,762 |
def contfrac(x, y):
"""
calculate continuated fraction of x/y
"""
while y:
a = x // y
yield a
x, y = y, x - a * y | 33,763 |
def get_account():
"""Return one account and cache account key for future reuse if needed"""
global _account_key
if _account_key:
return _account_key.get()
acc = Account.query().get()
_account_key = acc.key
return acc | 33,764 |
def test_determine_reference_type_recursive() -> None:
"""Should return recursive reference type."""
reference = "#/test"
assert determine_reference_type(reference) == RECURSIVE_REFERENCE | 33,765 |
def resetGTFAttributes(infile, genome, gene_ids, outfile):
"""set GTF attributes in :term:`gtf` formatted file so that they are
compatible with cufflinks.
This method runs cuffcompare with `infile` against itself to add
attributes such as p_id and tss_id.
Arguments
---------
infile : strin... | 33,766 |
def cli_args_exec(args):
"""
potcar args_exec
"""
if args.DEBUG:
print(__file__)
if args.test:
test(args.test_dir)
elif args.list:
get_avail_pot(args.pp_names, args.ptype, True)
else:
gen_potcar(args.pp_names, args.ptype, args.dirname, args.preview) | 33,767 |
def is_seq_of(
seq: Sequence, expected_type: type, seq_type: Optional[type] = None
) -> bool:
"""Check whether it is a sequence of some type.
Args:
seq (Sequence):
Sequence to be checked.
expected_type (type):
Expected type of sequence items.
seq_type (type, ... | 33,768 |
def mutate_single_residue(atomgroup, new_residue_name):
"""
Mutates the residue into new_residue_name. The only atoms retained are
the backbone and CB (unless the new residue is GLY). If the original
resname == new_residue_name the residue is left untouched.
"""
resnames = atomgroup.resnam... | 33,769 |
def test_initial_state():
"""Check the initial state of the class."""
c = StackOverflowCollector()
assert c is not None | 33,770 |
def future_bi_end_f30_base(s: [Dict, OrderedDict]):
"""期货30分钟笔结束"""
v = Factors.Other.value
for f_ in [Freq.F30.value, Freq.F5.value, Freq.F1.value]:
if f_ not in s['级别列表']:
warnings.warn(f"{f_} not in {s['级别列表']},默认返回 Other")
return v
# 开多仓因子
# ---------------------... | 33,771 |
def deleteFile(fileName):
"""
Delete a file
"""
os.remove(fileName) | 33,772 |
def convert_pre_to_021(cfg):
"""Convert config standard 0.20 into 0.21
Revision 0.20 is the original standard, which lacked a revision.
Variables moved from top level to inside item 'variables'.
Ocean Sites nomenclature moved to CF standard vocabulary:
- TEMP -> sea_water_temperature... | 33,773 |
def test_no_timeout_locate_ns_existing(nsproxy):
"""
Locating a NS that exists with no timeout should be OK.
"""
locate_ns(nsproxy.addr(), timeout=0.) | 33,774 |
def get_alerts_alarms_object():
""" helper function to get alert alarms
"""
result = []
# Get query filters, query SystemEvents using event_filters
event_filters, definition_filters = get_query_filters(request.args)
if event_filters is None: # alerts_alarms
alerts_alarms = db.session.q... | 33,775 |
def data_cubes_combine_by_pixel(filepath, gal_name):
"""
Grabs datacubes and combines them by pixel using addition, finding the mean
and the median.
Parameters
----------
filepath : list of str
the data cubes filepath strings to pass to glob.glob
gal_name : str
galaxy name/... | 33,776 |
def usdm_bypoint_service(
fmt: SupportedFormats,
):
"""Replaced above."""
return Response(handler(fmt), media_type=MEDIATYPES[fmt]) | 33,777 |
def read_geonames(filename):
"""
Parse geonames file to a pandas.DataFrame. File may be downloaded
from http://download.geonames.org/export/dump/; it should be unzipped
and in a "geonames table" format.
"""
import pandas as pd
return pd.read_csv(filename, **_GEONAMES_PANDAS_PARAMS) | 33,778 |
def create_property_map(cls, property_map=None):
""" Helper function for creating property maps """
_property_map = None
if property_map:
if callable(property_map):
_property_map = property_map(cls)
else:
_property_map = property_map.copy()
else:
_propert... | 33,779 |
def test_payload_with_address_invalid_chars(api_server_test_instance):
""" Addresses cannot have invalid characters in it. """
invalid_address = "0x61c808d82a3ac53231750dadc13c777b59310bdg" # g at the end is invalid
channel_data_obj = {
"partner_address": invalid_address,
"token_address": "... | 33,780 |
def readNetCDF(filename, varName='intensity'):
"""
Reads a netCDF file and returns the varName variable.
"""
import Scientific
import Scientific.IO
import Scientific.IO.NetCDF
ncfile = Scientific.IO.NetCDF.NetCDFFile(filename,"r")
var1 = ncfile.variables[varName]
data = sp.array(var... | 33,781 |
def show(ctx, name_only, cmds, under, fields, format, **kwargs):
"""Show the parameters of a command"""
cmds = cmds or sorted(config.parameters.readonly.keys())
if under:
cmds = [cmd for cmd in cmds if cmd.startswith(under)]
with TablePrinter(fields, format) as tp, Colorer(kwargs) as colorer:
... | 33,782 |
def make_count_set(conds, r):
"""
returns an r session with a new count data set loaded as cds
"""
#r.assign('conds', vectors.StrVector.factor(vectors.StrVector(conds)))
r.assign('conds', vectors.StrVector(conds))
r('''
require('DSS')
cds = newSeqCountSet(count_matrix, conds)
''')
... | 33,783 |
def RunCommand(cmd, timeout_time=None, retry_count=3, return_output=True,
stdin_input=None):
"""Spawn and retry a subprocess to run the given shell command.
Args:
cmd: shell command to run
timeout_time: time in seconds to wait for command to run before aborting.
retry_count: number of ti... | 33,784 |
def get_clusters_low_z(min_mass = 10**4, basepath='/lustre/scratch/mqezlou/TNG300-1/output'):
"""Script to write the position of z ~ 0 large mass halos on file """
halos = il.groupcat.loadHalos(basepath, 98, fields=['GroupMass', 'GroupPos','Group_R_Crit200'])
ind = np.where(halos['GroupMass'][:] > min_mas... | 33,785 |
def test_wait_for_db(mocker):
"""Test waiting for db"""
mocker.patch("time.sleep", return_value=True)
ec = mocker.patch(
"django.db.backends.base.base.BaseDatabaseWrapper.ensure_connection",
return_value=None,
)
ec.side_effect = [OperationalError] * 5 + [True]
call_command("wait_... | 33,786 |
def create_env(idf_revision):
"""
Create ESP32 environment on home directory.
"""
if not os.path.isdir(root_directory):
create_root_dir()
fullpath = os.path.join(root_directory, idf_revision)
if os.path.isdir(fullpath):
print('Environment %s is already exists' % idf_revision)
... | 33,787 |
def _serialize_key(key: rsa.RSAPrivateKeyWithSerialization) -> bytes:
"""Return the PEM bytes from an RSA private key"""
return key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption()... | 33,788 |
def test_decide_overwrite_var_full_path_resultdir():
"""options provided in cli get preference over the ones provided inside tests
"""
temp_dir = os.path.join(os.path.split(__file__)[0], "war_test3.xml")
resultdir = os.path.split(__file__)[0]
namespace = Namespace(datafile=None, random_tc_execution... | 33,789 |
def main():
""" Pass command line arguments to NCL script"""
config = conf.config(__doc__, sys.argv[1:])
t0 = time.time()
if config['out-dir']==None:
out_dir = '.'
else:
out_dir = config['out-dir']
# if ncl-code-dir not specified, expect it in ../ncl relat... | 33,790 |
def ldns_key_algo_supported(*args):
"""LDNS buffer."""
return _ldns.ldns_key_algo_supported(*args) | 33,791 |
def test_add_split():
"""Test add_split"""
# db init
EXAMPLE = get_dataset()
db = EXAMPLE(paths={'data': os.path.join('data', 'data'),
'meta': os.path.join('data', 'data')})
db.add('example_id', np.arange(len(db)), lazy=False)
# checks
db_split = copy.deepcopy(db)
... | 33,792 |
def read_k_bytes(sock, remaining=0):
"""
Read exactly `remaining` bytes from the socket.
Blocks until the required bytes are available and
return the data read as raw bytes. Call to this
function blocks until required bytes are available
in the socket.
Arguments
---------
sock : So... | 33,793 |
def total_minutes(data):
"""
Calcula a quantidade total de minutos com base nas palestras
submetidas.
"""
soma = 0
for item in data.keys():
soma += (item*len(data[item]))
return soma | 33,794 |
def test_repo_is_on_pypi_true():
"""Test 'repo_is_on_pypi'"""
assert common_funcs.repo_is_on_pypi({"name": "pytest"}) | 33,795 |
def grid_to_vector(grid, categories):
"""Transform a grid of active classes into a vector of labels.
In case several classes are active at time i, the label is
set to 'overlap'.
See :func:`ChildProject.metrics.segments_to_grid` for a description of grids.
:param grid: a NumPy array of shape ``(n,... | 33,796 |
def init_db():
"""Initialize database
"""
db = sqlite3.connect(app.config['DATABASE'])
db.row_factory = sqlite3.Row
with open('schema.sql', 'r') as f:
db.cursor().executescript(f.read())
db.commit() | 33,797 |
def standard_script_options(usage, description):
"""Create option parser pre-populated with standard observation script options.
Parameters
----------
usage, description : string
Usage and description strings to be used for script help
Returns
-------
parser : :class:`optparse.Opti... | 33,798 |
def connect():
""" Connect to the PostgreSQL database server """
conn = None
try:
# connect to the PostgreSQL server
print('Connecting to the PostgreSQL database...')
url = ""+sv+"."+ns+"."+"svc.cluster.local"
conn = psycopg2.connect(
host=url,
databas... | 33,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.