content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def pproc_Kirchhoff_2d(size, shape: nparray, points: nparray,
solution: nparray, D: nparray, S: nparray,
loads: nparray):
"""
JIT-compiled function that calculates post-processing quantities
at selected ponts for multiple left- and right-hand sides.
... | 67,300 |
def update_release_version(pep440=False):
"""Release versions are stored in a file called VERSION.
This method updates the version stored in the file.
This function should be called when creating new releases.
It is called by setup.py when building a package.
pep440: bool
When True... | 67,301 |
def streaming_line_input_type_check(line: str) -> None:
"""Ensure each line is a string. Raises `TypeError` if not."""
if not isinstance(line, str):
raise TypeError("Input line must be a 'str' object.") | 67,302 |
def test_check_tensor():
"""Test that check_tensor works for a variety of inputs."""
X = np.zeros((3, 4, 5))
assert_equal(check_tensor([1, 2]).shape, (2, ))
assert_raises(ValueError, check_tensor, X, dtype=np.float, n_dim=1)
assert_equal(check_tensor(X, dtype=np.float, n_dim=6).shape,
... | 67,303 |
def make_interrupt(name, irq, description):
"""make an interrupt"""
i = interrupt()
i.name = name
i.irq = irq
i.description = description
return i | 67,304 |
def stacked_bar(tag, title, datalist):
"""
data list should be a list of dictionary formatted as follows
{"name": "A"
"data": {
"R1_mapped": 50,
"R2_mapped": 50,
"R1_unmapped": 50,
"R2_unmapped": 50,
}
}
"""
dataitems = ""
for item in datalist:
... | 67,305 |
def version(api, verify_version=False):
"""Obtain a dictionary of versions for the Podman components."""
response = api.request("GET", "/_ping")
response.read()
if response.getcode() == HTTPStatus.OK:
return response.headers
# TODO: verify api.base and header[Api-Version] compatible
retu... | 67,306 |
async def restart(hub, ctx, name, resource_group, **kwargs):
"""
.. versionadded:: 1.0.0
Restart a virtual machine.
:param name: The name of the virtual machine to restart.
:param resource_group: The resource group name assigned to the
virtual machine.
CLI Example:
.. code-block... | 67,307 |
def mk_models_NO1(activation, mid_units, dropout_rate,dropout_rate_2,X_train,LEARNING_RATE):
"""
RGB画像を対象に分類を行います
入力サイズは基本(image_num,64,64,3)
畳み込みは2回
"""
filter_num=get_filter_num()
labels=get_labels()
model = Sequential()
model.add(Conv2D(32, (3, 3), padding='same',i... | 67,308 |
def find_job(context, job_id, state=None):
"""Check the job ID existence.
Check if job with given ID is returned from the service and optionally if
the job status has expected value.
"""
jsondata = context.response.json()
jobs = jsondata['jobs']
job_id = get_unique_job_id(context, job_id)
... | 67,309 |
def test_list_sample_types(mock_csv_path):
"""
Arrange/Act: Run the `list-sample-types` command.
Assert: The output includes 'Rock outcrop / float' in output".
"""
path = str(mock_csv_path)
runner: CliRunner = CliRunner()
result: Result = runner.invoke(
cli.cli, ["list-sample-types",... | 67,310 |
def cli(ctx, workflow_id, label):
"""Get a list of workflow input IDs that match the given label. If no input matches the given label, an empty list is returned.
Output:
list of workflow inputs matching the label query
"""
return ctx.gi.workflows.get_workflow_inputs(workflow_id, label) | 67,311 |
def cvCalcAffineFlowPyrLK(*args):
"""
cvCalcAffineFlowPyrLK(CvArr prev, CvArr curr, CvArr prev_pyr, CvArr curr_pyr,
CvPoint2D32f prev_features, CvPoint2D32f curr_features,
float matrices, int count, CvSize win_size,
int level, char status, float track_error,
CvTermCriteria crit... | 67,312 |
def _remove(path, soft=True):
"""Remove the file. If `soft`, then no error will be raised if the
file does not exist.
In contrast to beets' util.remove, this uses lexists such that it can
actually remove symlink links.
"""
path = syspath(path)
if soft and not os.path.lexists(path):
r... | 67,313 |
def get_artifacts_store_name():
"""Get the artifacts store name"""
return os.getenv(POLYAXON_KEYS_ARTIFACTS_STORE_NAME) | 67,314 |
def build_sgpr(
data: Dataset,
search_space: SearchSpace,
kernel_priors: bool = True,
likelihood_variance: Optional[float] = None,
trainable_likelihood: bool = False,
num_inducing_points: Optional[int] = None,
trainable_inducing_points: bool = False,
) -> SGPR:
"""
Build a :class:`~g... | 67,315 |
def cb_config(data, option, value):
"""Script option changed, update our copy."""
option_name = option.split(".")[-1]
if option_name in vimode_settings:
vimode_settings[option_name] = value
if option_name == 'user_mappings':
load_user_mappings()
if "_color" in option_name:
lo... | 67,316 |
def phasedivergent(repo, subset, x):
"""Mutable changesets marked as successors of public changesets.
Only non-public and non-obsolete changesets can be `phasedivergent`.
(EXPERIMENTAL)
"""
# i18n: "phasedivergent" is a keyword
getargs(x, 0, 0, _(b"phasedivergent takes no arguments"))
phase... | 67,317 |
def microtargetBuilder(localBuildlist, localCompiler, localCParams, localLParams, threadNumber):
"""Builds specified range of microtargets in separate thread"""
for target in localBuildlist:
targetObjName = hashlib.md5(target.encode('utf-8')).hexdigest()
targetObjPath = "fastbuild/" + targetObjN... | 67,318 |
def plot_diagnostic(fileout, plot_dir, project_info, model):
"""
;; Arguments
;; fileout: dir
;; directory to save the plot
;;
;; Description
;; Plot diagnostic and save .png plot
;;
"""
import projects
E = ESMValProject(project_info)
verbosity = E.get_ver... | 67,319 |
def find_on_screen(file):
"""
:param file: image
:return: the x and y coordinate and width and height dimensions of the image on the screen
"""
return gui.locateOnScreen(file) | 67,320 |
def _get_rpg_files(path_to_files, level):
"""Returns list of RPG files for one day sorted by filename."""
files = os.listdir(path_to_files)
files = [f"{path_to_files}{file}" for file in files
if file.endswith(str(level))]
files.sort()
return files | 67,321 |
def proccess_drm1_drm2(op2file, op4file=None, dosort=True):
"""
Process op2/op4 file2 output from DRM1/DRM2 DMAPs to form data
recovery matrices.
Parameters
----------
op2file : string
Either the basename of the .op2 and .op4 files, or the full
name of the .op2 file
op4file ... | 67,322 |
def ugrnn_transform(state: tf.Tensor,
inputs: tf.Tensor,
W_gates: tf.Tensor,
b_gates: tf.Tensor):
"""
Performs a standard UGRNN transformation.
"""
# Compute the linear transformation for the gates
stacked = tf.concat([inputs, state], axis=... | 67,323 |
def f(xx, uu, uref, t, p):
""" Right hand side of the vectorfield defining the system dynamics
:param xx: state
:param uu: input
:param uuref: reference input (not used)
:param t: time (not used)
:param pp: additionial free parameters (not used)
:return: ... | 67,324 |
def overview_data(vv, state = None,p = 0.25):
"""
Fetches, filters, and cleans Voteview
NOMINATE data and returns as JSON string
Args
- p: sample proportion
"""
if state != None:
p = 1.0
vv = filter_state(vv, state)
vv = filter_cols(vv,COLS)
vv = add_part... | 67,325 |
def test_has_oms_multiple(get_testdict):
"""Test on a bunch of different structures"""
for key, value in get_testdict.items():
omsdetector = MOFChecker.from_cif(key)
assert omsdetector.has_oms == value | 67,326 |
def return_prediction(model, sample):
"""Return a prediction for heart classification
Arguments:
model {model.h5} -- Pre-trained model to predict the heart classification
sample {array} -- Sample of the ECG reading of dimension (1,186,1)
Returns:
string -- Returns the predictions
... | 67,327 |
def import_submodules(package, recursive=True):
"""
Import all submodules of a module, recursively, including subpackages
:param package: package (name or actual module)
:type package: str | module
:rtype: dict[str, types.ModuleType]
"""
if isinstance(package, str):
package = import... | 67,328 |
def include(obj_name):
"""
Includes the object with the given name. The requirement is satisfied when the respective object is exported.
Parameters
----------
obj_name : `str`
The object name to include when exported.
Returns
-------
placeholder : `value` / `NotImplemen... | 67,329 |
def test_keep_alive_server_timeout():
"""If the client keep-alive timeout is longer than the server
keep-alive timeout, the client will either a 'Connection reset' error
_or_ a new connection. Depending on how the event-loop handles the
broken server connection."""
loop = asyncio.new_event_loop()
... | 67,330 |
def shownamespaces(context, mapping):
"""Dict of lists. Names attached to this changeset per
namespace."""
repo = context.resource(mapping, b'repo')
ctx = context.resource(mapping, b'ctx')
namespaces = util.sortdict()
def makensmapfn(ns):
# 'name' for iterating over namespaces, templat... | 67,331 |
def _update_doc(opt: Callable[["TwistOptions", str], None], **kwargs: str) -> None:
"""
Update the docstring of a method that implements an option.
The string is dedented and the given keyword arguments are substituted.
"""
opt.__doc__ = dedent(opt.__doc__ or "").format(**kwargs) | 67,332 |
def GetFlagValue(index):
"""Returns the flag value for the given index value (0...n-1)."""
return bundle_firmware.gbb_flag_properties.values()[index] | 67,333 |
def get_translation(nmt_outputs, sent_id, tgt_eos, subword_option):
"""Given batch decoding outputs, select a sentence and turn to text."""
if tgt_eos: tgt_eos = tgt_eos.encode("utf-8")
# Select a sentence
output = nmt_outputs[sent_id, :].tolist()
# If there is an eos symbol in outputs, cut them at tha... | 67,334 |
def test_apply_dq_plane_replace_flags(niriprim):
"""Replace only given flags."""
# First check with no_data, which is not present in the mask so pixel
# should not be changed
data_orig = niriprim.streams['main'][0][0].data.copy()
ad = niriprim.applyDQPlane(replace_flags=DQ.no_data, replace_value=0)... | 67,335 |
def lstmcell_grad_h(input, hx, cx, w_ih, w_hh, b_ih, b_hh, dh, dc, target="cce"):
"""
Computes dh w.r.t. dw, db, dcx, dhx, dx.
Args:
input: akg.tvm.Tensor of type float16, float32.
hx: akg.tvm.Tensor for hidden variable from previous cell.
cx: akg.tvm.Tensor for state variable... | 67,336 |
def test_averageklpe():
"""Check AverageKLPE"""
score_train_true = - np.array([(np.sqrt(2) + np.sqrt(10)) / 2,
(np.sqrt(2) + 2) / 2,
(2 + np.sqrt(10)) / 2])
pred_train_true = np.array([1, 1, 0])
score_test_true = - np.array([(1 + np.... | 67,337 |
def start_httptools_ui(port):
"""Start Server UI."""
subprocess.Popen(['httptools',
'-m', 'server', '-p', str(port)])
time.sleep(3) | 67,338 |
def delete_certificate(CertificateArn=None):
"""
Deletes a certificate and its associated private key. If this action succeeds, the certificate no longer appears in the list that can be displayed by calling the ListCertificates action or be retrieved by calling the GetCertificate action. The certificate will ... | 67,339 |
def get_mod_whitelist():
"""Return dict of modifications that are relevant for the data."""
mod_whitelist = {}
for members in antibody_map.values():
for gene_name, phos_sites in members.items():
for residue, position in phos_sites:
if gene_name not in mod_whitelist:
... | 67,340 |
def urldecode(str):
"""
>>> print(urldecode("%E4%BD%A0%E5%A5%BD"))
你好
"""
return unquote(str) | 67,341 |
def status_command(args):
"""Show repositories that have local changes"""
viewdir = find_enclosing_view_checked()
filename = os.path.join(viewdir, viewfile.DEFAULT_FILENAME)
with open(filename, 'r') as f:
view = viewfile.parse(f, filename)
had_change = False
for entry in view.entries:
... | 67,342 |
async def test_async_discover_hosts():
"""Verify discover hosts does not throw."""
discover_hosts = discovery.DiscoverHosts()
with patch.object(discovery, "MAX_ADDRESSES", 16):
hosts = await discover_hosts.async_discover()
assert isinstance(hosts, list) | 67,343 |
def distance_uv(uv1, uv2):
""" [cmds] UV 2 点間の距離を返す
Args:
p1 (list[float, float]): cmds の UV コンポーネント文字列
p2 (list[float, float]): cmds の UV コンポーネント文字列
Returns:
float: 二次元座標の距離
"""
uvCoord1 = cmds.polyEditUV(uv1, query=True)
uvCoord2 = cmds.polyEditUV(uv2, quer... | 67,344 |
def main(budget=budget,
max_runs=max_runs,
current_batch=current_batch,
number_of_batches=number_of_batches):
"""Initialize suite and observer, then benchmark solver by calling
``batch_loop(SOLVER, suite, observer, budget,...``
"""
suite = Suite(suite_name, suite_instance, sui... | 67,345 |
def apply(log: Union[EventLog, pd.DataFrame], parameters: Optional[Dict[Any, Any]] = None) -> List[
Tuple[Tuple[str, str], int, Dict[str, Any]]]:
"""
Provided an event log / dataframe, returns
a list having as elements the activity-resources with the batches that are detected, divided in:
- Simultan... | 67,346 |
def check_trading_day(df_indices, date):
"""
The function return the next trading day.
Parameters:
df_indices: List of trading days in the whole dataset
date: The prediction day
Returns:
date: The next trading day
"""
while (True):
if (date in df_indices):
... | 67,347 |
def store_standards(imgID_list, side='blue', trace=None,
arc=None, splot='no', redo='no', resize='yes',
crval=None, cdelt=None, extract=True, telluric_cal_id=None):
"""Extract spectra for spectroscopic standard stars and determine
corrections needed for fluxing.
Wraps iraf.standard and... | 67,348 |
def test_ur_reg_instantiation_fancy(testdir):
"""Make sure a fancy unrodded region can be instantiated"""
inp = dassh.DASSH_Input(
os.path.join(testdir, 'test_inputs', 'input_ur_conv_factor.txt'),
empty4c=True)
mat = {'coolant': dassh.Material('sodium'),
'duct': dassh.Material('ht... | 67,349 |
def masked_greater(x: numpy.ma.core.MaskedArray, value: float):
"""
usage.scipy: 1
"""
... | 67,350 |
def coPrime(x):
"""
Finds a random co-prime of given number
"""
n = x * 2 + 100000 # Upper limit for range of random integers
y = random.randint(x * 2, n)
if (fractions.gcd(x, y) != 1):
return coPrime(x)
else:
return y | 67,351 |
def plot_chat_content_usage_group(content_usage, normalize=True):
"""
Plots what type of content is sent in the group
:param content_usage: The content sent
:param normalize: If to show in normalized format or in numbers
"""
fig = plt.figure(1, (8, 6))
ax = fig.add_subplot(1, 1, 1)
use... | 67,352 |
def create_task_id(prefix):
""" Create random task-id """
return "{prefix}-{id}".format(prefix=prefix, id=random_hex(6)) | 67,353 |
def AddResourceArgs(parser):
"""Add resource args of images for 'packages diff' command."""
concept_parsers.ConceptParser(
[
resource_args.CreateImageResourcePresentationSpec(
'Name of the disk image as the diff base.', 'base'
),
resource_args.CreateImageResourcePre... | 67,354 |
def do_train(task_type, dataset=None, network=None, load_checkpoint_path="", save_checkpoint_path="", epoch_num=1):
""" do train """
if load_checkpoint_path == "":
raise ValueError("Pretrain model missed, finetune task must load pretrain model!")
steps_per_epoch = dataset.get_dataset_size()
# op... | 67,355 |
def assert_valid_slice(slice_, shape=None):
"""
:param slice_:
:param shape:
:return:
"""
if shape is None:
shape = (9999999, 9999999)
for i, s in enumerate(slice_):
assert s.start is not None and (s.start >= 0) and (s.start <= shape[i]), \
"{} (0 row 1 col) start... | 67,356 |
def feh_calc(theta, V, EW, power):
"""Calculate the metallicity for a given magnitude and EW."""
a, b, c, d, e = theta
# Wdash = reduced_ew(theta, V, EW)
FeH = a + b*V + c*EW + d*EW**power + e*V*EW
# FeH = d + f*np.power(Wdash, 1) + g*np.power(Wdash, 2)
return FeH | 67,357 |
def metadata_parser(f):
"""
Parses a metadata file into dictionary.
The metadata file is expected to have the following format:
id;name;dtype
where:
- id denotes packet id (unsigned char or 1 byte uint)
- name is the data channel name (str)
- dtype is expected datatype (str)
:param f: A file object with th... | 67,358 |
def _GetValueAndSource(sim, control, name, sources):
"""Returns value of specified telemetry 'name' and 'source'.
Arguments:
sim: Simulator telemetry dictionary.
control: Controller telemetry dictionary.
name: [string] Telemetry variable e.g. 'airspeed' or 'alpha'.
sources: [list of strings] The li... | 67,359 |
def _clean_sub_graphs(G_, min_length=80, max_nodes_to_skip=100,
weight='length', verbose=True,
super_verbose=False):
"""
Remove subgraphs with a max path length less than min_length,
if the subgraph has more than max_noxes_to_skip, don't check length
(this ... | 67,360 |
def transform(*args):
"""
Transform XML document(s) using XSLT.
`*args` contain string commands and/or options in the following format:
[<options>] <xsl-file> {-p|-s <name>=<value>} [<xml-file>...]
where
<xsl-file> - main XSLT stylesheet for transformation
<xml-file> - input... | 67,361 |
def decode(secret: Union[str, bytes], token: Union[str, bytes]) -> Mapping:
"""Decode JWT."""
if isinstance(secret, str):
secret = secret.encode()
if isinstance(token, str):
token = token.encode()
try:
signing_input, signature_segment = token.rsplit(b'.', 1)
payload_segm... | 67,362 |
def bencode(data, f=None):
"""
Writes a serializable data piece to f
The order of tests is nonarbitrary,
as strings and mappings are iterable.
If f is None, it writes to a byte buffer
and returns a bytestring
"""
if f is None:
f = BytesIO()
_bencode_to_file(data, f)
return f.getvalue()
else:
_bencode... | 67,363 |
def save_raster ( output_name, raster_data, dataset, driver="GTiff" ):
"""
A function to save a 1-band raster using GDAL to the file indicated
by ``output_name``. It requires a GDAL-accesible dataset to collect
the projection and geotransform.
"""
# Open the reference dataset
g_input = gdal... | 67,364 |
def onboard(do_declaration, as3_declaration, trusted_sources,
post_onboard_enabled, post_onboard_commands, phone_home_url,
phone_home_url_verify_tls, phone_home_cli):
"""Implements the onboarding business logic"""
do_enabled = True
if do_declaration:
try:
tmos_on... | 67,365 |
def test_CIO_officers_query(caplog):
"""Test querying for officers with an option for register_view.
Currently including this option yields a 400 error.
"""
officers = list(get_company_officers(ACCESS_COMPANY_ID))
assert officers == [] | 67,366 |
def Mean0(a):
"""
Replacing np.mean(a, axis = 0) for 2D arrays
Parameters
----------
a : 2D numpy array, floats
Returns
-------
average : 1D numpy array, floats
Averages over the columns of a.
"""
average = np.zeros(a.shape[1])
for col in range(... | 67,367 |
def download_burst():
"""Returns an html table with the burst retrieved from the DB.
"""
images_path = "server/data/bursts"
burst_id = int(request.args.get('burstId'))
burst_format = request.args.get('format')
burst = DB.get_burst(burst_id)
files = int(burst['duration'] / burst['interval'])
... | 67,368 |
async def delete_order(request: web.Request, order_id) -> web.Response:
"""Delete purchase order by ID
For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
:param order_id: ID of the order that needs to be deleted
:type order_id: str
... | 67,369 |
def fio_json_output_with_error(fio_json_output):
"""
Example of fio --output-format=json output, with io_u error. Based on
actual test run.
"""
err_line = (
"fio: io_u error on file /mnt/target/simple-write.0.0: "
"No space left on device: write offset=90280222720, buflen=4096"
)... | 67,370 |
def test_pedido_set_allowed_methods(method, allowed, adminClient, list_url):
"""Testa os métodos permitidos da view de conjunto dos pedidos"""
res = getattr(adminClient, method)(list_url)
assert (res.status_code != status.HTTP_405_METHOD_NOT_ALLOWED) == allowed | 67,371 |
def supprimeExtension(str):
"""
Fonction qui supprime l'extension de notre str
param : str : string -> chaine de caractere qu'on souhaite supprimer l'extension.
return string : chaine de caractere sans extenstion
"""
#appliquer cette fonction avant supprimePonctuation
return "".join... | 67,372 |
def has_equal_properties(obj, property_dict):
"""
Returns True if the given object has the properties indicated by the keys of the given dict, and the values
of those properties match the values of the dict
"""
for field, value in property_dict.items():
try:
if getattr(obj, field... | 67,373 |
def write_fits_gz(table, path):
"""Write BinTableHDU to fits.gz in a reproducible way.
Writing to `.fits.gz` with Astropy directly never gave
reproducible files, probably because in the background
some date string was inserted in the zip file.
So this helper function first write to `.fits` and the... | 67,374 |
def outerproduct(tensor1: BlockSparseTensor,
tensor2: BlockSparseTensor) -> BlockSparseTensor:
"""
Compute the outer product of two `BlockSparseTensor`.
The first `tensor1.ndim` indices of the resulting tensor are the
indices of `tensor1`, the last `tensor2.ndim` indices are those
of `tensor... | 67,375 |
def niriss_header(ra=53.1592277508136, dec=-27.782056346146, pa_aper=128.589,
filter='F150W', grism='GR150R'):
"""Make JWST/NIRISS image header
Parameters
----------
ra, dec : float, float
Coordinates of the center of the image
pa_aper : float
Position angle of th... | 67,376 |
def validate_twilio_request(f):
"""Validates that incoming requests genuinely originated from Twilio"""
# Adapted from https://www.twilio.com/docs/usage/tutorials/how-to-secure-your-flask-app-by-validating-incoming-twilio-requests?code-sample=code-custom-decorator-for-flask-apps-to-validate-twilio-requests-3&c... | 67,377 |
def get_path_components(path):
"""
http://stackoverflow.com/questions/3167154/how-to-split-a-dos-path-into-its-components-in-python
"""
folders = []
while True:
path, folder = os.path.split(path)
if folder != "":
folders.append(folder)
else:
if path !=... | 67,378 |
def assert_allclose(
actual: numpy.ndarray,
desired: numpy.ndarray,
rtol: float,
err_msg: Literal["solver eigen"],
):
"""
usage.sklearn: 1
"""
... | 67,379 |
def processJSONForms (forms,outstream):
"""Takes a JSON list, and an output stream. Generates the annotation from the JSON list
and writes it to the output stream."""
assert(type(forms) == list)
# print("%d forms" % len(forms))
for form in forms:
assert(type(form) == dict)
... | 67,380 |
def train(model, training_data, validation_data, optimizer, scheduler, pred_loss_func, opt):
""" Start training. """
valid_event_losses = [] # validation log-likelihood
valid_pred_losses = [] # validation event type prediction accuracy
valid_rmse = [] # validation event time prediction RMSE
best... | 67,381 |
def is_api(auth_entry):
"""Returns whether the auth entry point is via an API call."""
return (auth_entry == AUTH_ENTRY_LOGIN_API) or (auth_entry == AUTH_ENTRY_REGISTER_API) | 67,382 |
def calcROC(output, LTE):
"""Uses shogun functions to calculate the area under the ROC curve"""
pm = PerformanceMeasures(Labels(numpy.array(LTE)), Labels(numpy.array(output)))
auROC = pm.get_auROC()
return auROC | 67,383 |
def test_serialization_negative():
"""Test serialization when performative is not recognized."""
tx_msg = RegisterMessage(
performative=RegisterMessage.Performative.REGISTER, info={},
)
with patch.object(RegisterMessage.Performative, "__eq__", return_value=False):
with pytest.raises(
... | 67,384 |
def _GetCoveredBuilders(trybot_config):
"""Returns a dict mapping masters to lists of builders covered in config."""
covered_builders = {}
for master, builders in trybot_config.iteritems():
covered_builders[master] = builders.keys()
return covered_builders | 67,385 |
def _load_vocabulary(filename):
"""Loads a vocabulary file.
Args:
filename: Path to text file containing newline-separated words.
Returns:
vocab: A dictionary mapping word to word id.
"""
tf.logging.info("Reading vocabulary from %s", filename)
vocab = collections.OrderedDict()
with tf.gfile.GFil... | 67,386 |
def get_all_names():
"""
Return a dictionary of all names, indexed by index.
"""
keys = get_singleton(create=False)
if keys is None:
return {}
entries = keys.attr('entries')
result = {}
for entry in entries:
idx = entry.index()
result[idx] = entry.attr('name... | 67,387 |
def format_power(power):
"""
Converts a value for a power (which may be floating point or a
`fractions.Fraction` object), into a string either looking like
an integer or a fraction.
"""
if not isinstance(power, Fraction):
if power % 1.0 != 0.0:
frac = Fraction.from_float(powe... | 67,388 |
def test_both_lightsheets_nonadmin_request(test_client,test_login_nonadmin,test_delete_request_db_contents):
""" Submits a new request as 'lightserv-test' (a nonadmin) that can be used for various tests.
This request has raw data on bucket in the correct folder with both left and right lightsheets
that can be used f... | 67,389 |
def _aggregate_neighbors(estimator, neigh_Y, neigh_weights):
"""Aggregate the nearest neighbors rankings according to the weights."""
aggregate = estimator._rank_algorithm.aggregate
neigh_data = zip(neigh_Y, neigh_weights)
Y = [aggregate(Y, sample_weight) for Y, sample_weight in neigh_data]
return... | 67,390 |
def float_scalar(size=DEF_MATRIX, rep=DEF_REP):
"""
Returns the execution time of performing the sum of a random number to
each element of a random real matrix.
Parameters
----------
size : int
The dimension of the square matrix that will be used in the
... | 67,391 |
def get_upload_source_metadata(instance, bag):
"""
Get all FTS metadata files in the bag. If they are valid then get their contents, otherwise
rename the invalid metadata file.
Parameters
----------
instance: BaseResource class instance
Class we want to add the attributes to
bag: Ba... | 67,392 |
def project(opts):
"""Update user options with the options of an existing PyScaffold project
Params:
opts (dict): options of the project
Returns:
dict: options with updated values
Raises:
:class:`~.PyScaffoldTooOld`: when PyScaffold is to old to update from
:class:`~.N... | 67,393 |
def main(file_, bfile, dataset, coding, chip_name, assembly, create_samples):
"""Read sample names from map/ped files and updata smarter database (insert
a record if necessary and define a smarter id for each sample)
"""
logger.info(f"{Path(__file__).name} started")
# find assembly configuration
... | 67,394 |
def xr_ds_ex(decode_times=True, nyrs=3, var_const=True):
"""return an example xarray.Dataset object, useful for testing functions"""
# set up values for Dataset, 4 yrs of analytic monthly values
days_1yr = np.array([31.0, 28.0, 31.0, 30.0, 31.0, 30.0, 31.0, 31.0, 30.0, 31.0, 30.0, 31.0])
time_edges = n... | 67,395 |
def evaluate(gold, pred):
"""
Produce CoNLL 2005 SRL evaluation results for a provided sentences given as lists of tags, with the first list being a
list of targets. For example, [['-', 'love', '-'], ['(A0*)', '(V*)', '(A1*)']].
:param gold: gold labels
:param pred: predicted labels
:return: SRL... | 67,396 |
def posix_times(space):
""" posix_times - Get process times """
utime, stime, cu_time, cs_time, rtime = os.times()
rdct_w = OrderedDict()
rdct_w['ticks'] = space.newint(int(rtime))
rdct_w['utime'] = space.newint(int(utime))
rdct_w['stime'] = space.newint(int(stime))
rdct_w['cutime'] = space.... | 67,397 |
def gzip_file() -> None:
"""
gzips FILENAME
"""
with open(FILENAME, 'rb') as f_in, \
gzip.open(f'{FILENAME}.gz', 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
# confirm gzipped file exists
if DEBUG_MODE:
logging.info("Confirming gzipped file exists: %s",
... | 67,398 |
def setup_platform(opp, config, add_entities, discovery_info=None):
"""Set up the Pushbullet Sensor platform."""
try:
pushbullet = PushBullet(config.get(CONF_API_KEY))
except InvalidKeyError:
_LOGGER.error("Wrong API key for Pushbullet supplied")
return False
pbprovider = PushB... | 67,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.