content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Callable
from typing import Iterable
from typing import List
def lmap(f: Callable, x: Iterable) -> List:
"""list(map(f, x))"""
return list(map(f, x)) | 51b09a3491769aafba653d4198fde94ee733d68f | 3,632,541 |
import ImportPathHelper as imports
from editor_python_test_tools.utils import Report
from editor_python_test_tools.utils import TestHelper as helper
import azlmbr.legacy.general as general
import azlmbr.bus
import azlmbr.physics as phys
import azlmbr.math as mathazon
def C4925577_Materials_MaterialAssignedToTerrain()... | 45b527c1b413c33be81fecf7babd4d11de513a8f | 3,632,542 |
def fallible_to_exec_result_or_raise(
fallible_result: FallibleExecuteProcessResult, description: ProductDescription
) -> ExecuteProcessResult:
"""Converts a FallibleExecuteProcessResult to a ExecuteProcessResult or raises an error."""
if fallible_result.exit_code == 0:
return ExecuteProcessResult(
fal... | 774cf9e89fd383a37992fff0b2e1b72ff96bddc8 | 3,632,543 |
def cumprod_np(a: np.ndarray, mod: int) -> np.ndarray:
"""Compute cumprod over modular not in place.
the parameter a must be one dimentional ndarray.
"""
n = a.size
assert a.ndim == 1
m = int(n**0.5) + 1
a = np.resize(a, (m, m))
for i in range(m - 1):
a[:, i + 1] = a[:, i + 1] *... | b5b1635000bf82b563c350341c8c56edbb0eb9fb | 3,632,544 |
def table_of_contents(df_documentation=''):
"""
Function::: table_of_contents
Description: brief description here (1 line)
Details: Full description with details here
Inputs
doc_csv_file: FILE csv file with documentation of functions
Outputs
tab_contents: STR Table of content... | fa5c26b729278bcc312a07fc6822ecf4837e2828 | 3,632,545 |
def mock_get_location_business_from_sam(client, duns_list):
""" Mock function for location_business data as we can't connect to the SAM service """
columns = ['awardee_or_recipient_uniqu'] + list(update_historical_duns.props_columns.keys())
results = pd.DataFrame(columns=columns)
duns_mappings = {
... | 61c9d0c0ee18a3840f7b2c0b70c504c388e83343 | 3,632,546 |
def repeat(N, fn):
"""repeat module N times
:param int N: repeat time
:param function fn: function to generate module
:return: repeated loss
:rtype: MultiSequential
"""
return MultiSequential(*[fn() for _ in range(N)]) | da20e6af56fd227d6eb2c6e083ac21d5c65e71e3 | 3,632,547 |
import numpy
def dense_to_one_hot(labels_dense, num_classes):
"""Convert class labels from scalars to one-hot vectors."""
num_labels = labels_dense.shape[0]
index_offset = numpy.arange(num_labels) * num_classes
labels_one_hot = numpy.zeros((num_labels, num_classes))
labels_one_hot.flat[index_offset + labels... | dc4c717a03624708be6b09b040acb5a901d1e8f0 | 3,632,548 |
from typing import Set
from typing import Mapping
def parse_input(data: str) -> (Set[str], Mapping[str, Mapping[str, int]]):
"""Extract the names and associated happines changes from data."""
names = set()
happiness_changes = {}
for line in data.splitlines():
match = INPUT.fullmatch(line)
... | 147cc6a19160b6e472249e59c5a8a41fb73f6cde | 3,632,549 |
def main(argv):
"""The program.
Returns an error code or None.
"""
try:
# Build an environment from the list of arguments.
env, writer = make_env_and_writer(argv)
try:
cmd = COMMANDS[env.options.command](env, writer)
cmd.execute()
finally:
... | 00063921703fea4ef21e8767ccdb1156f3c45911 | 3,632,550 |
import pandas
def merger(primary_path:str, secondary_path:str, desired_columns:list, shared_column="time"):
"""
--> Primary path is the global analysis file produced by analyzing NMR spectra
--> Secondary path is the raw-data file recorded by the DAQ.
--> Desired columns is a list of columns that you want to MIG... | 8db087622b691bb0b36505e038c8aa5ed5902121 | 3,632,551 |
import unicodedata
import re
def slugify_ref(value: Text, allow_unicode: bool = False) -> Text:
"""
Convert to ASCII if 'allow_unicode' is False. Convert spaces to hyphens.
Remove characters that aren't alphanumerics, underscores, or hyphens. Convert to lowercase.
Also strip leading and trailing whit... | 1ce3893436f1590e55679248290aadc486f0d717 | 3,632,552 |
import json
def user_search():
"""UserSearch"""
value = request.args.get('search')
cur = MY_SQL.connection.cursor()
cur.execute(
'''SELECT id, username FROM accounts.users WHERE
username LIKE '%%%s%%';''',
(value)
)
users = json.dumps(cur.fetchall())
return users | 774234ee4cb4bae2b77a0c469037c695660d250e | 3,632,553 |
def graphcut(img1, img2, mask):
"""
Inputs:
Mask:
The 80px area out of the boundary. 2 dims.
Pixels on the edge of Img1 are marked with 1 and same for Img2. Internal pixels are marked with 3.
Img1 & Img2:
Here Img1 means source img, aka. the input img. Img2 is... | a6d113e714191015f446cf1e687d925258dfb06f | 3,632,554 |
def lutForTBMap():
""" produce a look up table for a red-black-blue colormap"""
cmap=mpl.colors.LinearSegmentedColormap.from_list('my_colormap',
['blue','black','red'],
256)
#I'm not entirely sure what this lower is for. Its use... | 1017d2fc7c7279ac3baa1393286244586d0e30c8 | 3,632,555 |
import typing
import tqdm
def val_one_epoch(model: Module, dataloader: DataLoader, criterion,
device: str) -> typing.Tuple[typing.Union[np.ndarray, None],
dict]:
"""
Validate the given model for one epoch.
:param model: model to evaluate
... | d51a5fbb064d00de1a48d30927cb1695db0a3168 | 3,632,556 |
def multiply_something(num1, num2):
"""this function will multiply num1 and num2
>>> multiply_something(2, 6)
12
>>> multiply_something(-2, 6)
-12
"""
return(num1 * num2) | 1a726c04df146ab1fa7bfb13ff3b353400f2c4a8 | 3,632,557 |
def post_shift_dp(train_set, vali_set, test_set, logreg_model):
"""Post-shifts log. regression model for demographic parity using vali_set.
Returns the train, validation and test sets with the group attribute appended
as an additional feature, and the post-shifted linear model for the expanded
datasets.
Arg... | 03cfcf5060e6419398042ff08fbb991c34551726 | 3,632,558 |
def determine_acknowledgement(record, report, ignore_string):
"""Mark report for output unless ignored"""
if record[COMMENT_TEXT]:
comment = record[COMMENT_TEXT].lower()
else:
comment = ""
if ignore_string in comment:
report["should"] = False
return True
report["shou... | 8fd4d0d2623a0183953a21cb2029da0fadc95bff | 3,632,559 |
def estimate_infectious_rate_constant_vec(event_times,
follower,
t_start,
t_end,
kernel_integral,
count_events... | 207833e1b32885fe39a209bfef227665c8c59ad1 | 3,632,560 |
import urllib
import json
def cotacaoBRL():
"""
Retorna a última cotação do Bitcoin em BRL - Mercado Bitcoin via API BitValor
"""
with urllib.request.urlopen("https://api.bitvalor.com/v1/ticker.json") as url:
data = json.loads(url.read().decode())
last = data['ticker_24h']['exchanges... | a6c96aa8c8cff46ab4b410a81d1ef19ac912fcbb | 3,632,561 |
from typing import List
def adder(journal: Journal) -> List[JournalEntry]:
"""A task that requires previous phases to have recorded journal entres with tags 'x' and 'y', which it will sum.
Returns a new journal entry, titled 'x+y', containing the sum of the existing journal entries 'x' and 'y'
"""
x... | 03303cd74dffa0631dbb120280666701268871e7 | 3,632,562 |
def find(word,letter):
"""
find letter in word , return first occurence
"""
index=0
while index < len(word):
if word[index]==letter:
#print word,' ',word[index],' ',letter,' ',index,' waht'
return index
index = index + 1
return -1 | bdeb0f0993fb4f7904b4e9f5244ea9d7817fa15f | 3,632,563 |
def subsample_ind(n, k, seed=32):
"""
Return a list of indices to choose k out of n without replacement
"""
rand_state = np.random.get_state()
np.random.seed(seed)
ind = np.random.choice(n, k, replace=False)
np.random.set_state(rand_state)
return ind | 958ddcf3122bc8c8f9cab0539896bfc624d1901f | 3,632,564 |
def HA2(credentails, request):
"""Create HA2 md5 hash
If the qop directive's value is "auth" or is unspecified, then HA2:
HA2 = md5(A2) = MD5(method:digestURI)
If the qop directive's value is "auth-int" , then HA2 is
HA2 = md5(A2) = MD5(method:digestURI:MD5(entityBody))
"""
if crede... | 94f9a6b6e6371f1d7c1c6606577cbbced201facf | 3,632,565 |
from typing import Dict
from typing import Any
import hashlib
def name_to_scope(
template: str,
name: str,
*,
maxlen: int = None,
params: Dict[str, Any] = None,
) -> str:
"""Return scope by given template possibly shortened on name part.
"""
scope = template.format(name=name, **params)... | cd6759da406b6072565f693cdffe8eb16107c074 | 3,632,566 |
def bootstrap_idxs(n, rng: np.random.Generator = None):
"""
Generate a set of boostrap indexes of length n, returning the pair (in_bag, out_bag) containing the in-bag and
out-of-bag indexes as numpy arrays
"""
if rng is None or type(rng) is not np.random.Generator:
rng = np.random.default_rn... | 3d76cfea110c91a228bc8bc3ec5698c9a94676b8 | 3,632,567 |
def run(argv=None):
"""Main entry point; defines and runs the wordcount pipeline."""
parser = argparse.ArgumentParser()
parser.add_argument('--input',
dest='input',
default='$GTFS_BUCKET/at/20190429120000/at.zip',
help='Input file to p... | d4bacf3a16dc53e3e8b6213e6dbbb2be9a7df2b0 | 3,632,568 |
def check_skyscrapers(input_path: str):
"""
Main function to check the status of skyscraper game board.
Return True if the board status is compliant with the rules,
False otherwise.
>>> check_skyscrapers("check.txt")
True
"""
lst = read_input(input_path)
if check_columns(lst) and\
... | ff57e649bbd87563fe97e870e304259041f0582f | 3,632,569 |
from typing import Dict
from typing import Any
import importlib
def load_preprocessor(preproc_params: Dict[str, Any], device: str) -> Module:
"""Load preprocessor from module preprocessors.name"""
preproc = None
if preproc_params is not None:
preproc_module = importlib.import_module(
f... | a6ea8dc293c883f5bcd1841bd1d483b97d393dab | 3,632,570 |
def get_image_ground_truth(image_id, dataset):
"""Load and return ground truth data for an image (image, mask, bounding boxes).
Args:
image_id:
Image id.
Returns:
image:
[height, width, 3]
class_ids:
[instance_count] Integer class IDs
bbo... | 3894e5714ceb64c7b414f100e69ac5c3b2b36fb8 | 3,632,571 |
def nested_field_map(name: str) -> Mapper:
"""
Arguments
---------
name : str
Name of the property.
Returns
-------
Mapper
Field map.
See Also
--------
field_map
"""
return field_map(
name,
python_to_api=lambda x: [[x]],
api_to_... | 7af0a3e8df4f4bc8228a3473d75bbab527bf0eee | 3,632,573 |
def socket_state(realsock, waitfor="rw", timeout=0.0):
"""
<Purpose>
Checks if the given socket would block on a send() or recv().
In the case of a listening socket, read_will_block equates to
accept_will_block.
<Arguments>
realsock:
A real socket.socket() object to check for.
... | fc2fa9162d3228021c6738e0e2453cabae907899 | 3,632,574 |
def wrap_with_threadpool(obj, worker_threads=1):
"""
Wraps a class in an async executor so that it can be safely used in an event loop like asyncio.
"""
async_executor = ThreadPoolExecutor(worker_threads)
return AsyncWrapper(obj, executor=async_executor), async_executor | 744a428535aa70d7b130e12bb9c144aac3df4d96 | 3,632,575 |
import re
def file_read(lines):
""" Function for the file reading process
Strips file to get ONLY the text; No timestamps or sentence indexes added so returned string is only the
caption text.
"""
# new_text = ""
text_list = []
for line in lines:
if re.search('^[0-9]', line) is No... | 7d37bb79c6b1cdd43d7b813e03bf3d8b18f5a6ed | 3,632,576 |
def has_file_ext(view, ext):
"""Returns ``True`` if view has file extension ``ext``.
``ext`` may be specified with or without leading ``.``.
"""
if not view.file_name() or not ext.strip().replace('.', ''):
return False
if not ext.startswith('.'):
ext = '.' + ext
return view.fil... | 043edf03874d1ec20e08fcb5795fd205206f7194 | 3,632,578 |
def balanced_accuracy_score(y_true: np.array, y_score: np.array) -> float:
"""
Calculate the balanced accuracy for a ground-truth prediction vector pair.
Args:
y_true (array-like): An N x 1 array of ground truth values.
y_score (array-like): An N x 1 array of predicted values.
Returns:... | 4c7a17e5a5706b8b8cf65d15db51283d7873aca0 | 3,632,579 |
import re
def VOLTS(text):
""" Parse all voltages in tegrastats output
[VDD_name] X/Y
X = Current power consumption in milliwatts.
Y = Average power consumption in milliwatts.
"""
return {name: {'cur': int(cur), 'avg': int(avg)} for name, cur, avg in re.findall(VOLT_RE, text)} | f79934a037b2d995974e833c8b7b045e195637d4 | 3,632,580 |
from typing import Union
async def get_team_id(user_id: int) -> Union[int, None]:
"""Return the team id of a user based on their user id."""
data = await users.find_one(
{"user_id": user_id},
{"team_id": 1, "_id": 0},
)
if data:
team_id = data.get("team_id")
else:
... | e0905e65edc6ff84d35d25ec43eb98f3898295af | 3,632,581 |
def get_atom_types_selected(smi_file, database):
""" Determines the atom types present in an input SMILES file.
Args:
smi_file (str) : Full path/filename to SMILES file.
"""
# list of atom types to be selected
if database == "GDB-13":
atom_types = ['H', 'C', 'N', 'O', 'Cl']
p... | 26a92a44db7c4f187f21e6dfe8dd64694fabc29a | 3,632,583 |
def run_profile(times, schedule, msid, model_spec, init, pseudo=None):
""" Run a Xija model for a given time and state profile.
:param times: Array of time values, in seconds from '1997:365:23:58:56.816' (cxotime.CxoTime epoch)
:type times: np.ndarray
:param schedule: Dictionary of pitch, roll, etc. va... | 92ffe057738183d50aac40693d572a232354e621 | 3,632,584 |
def extract_optimized_structure(out_file, n_atoms, atom_labels):
"""
After waiting for the constrained optimization to finish, the
resulting structure from the constrained optimization is
extracted and saved as .xyz file ready for TS optimization.
"""
optimized_xyz_file = out_file[:-4]+".xyz"
... | 203dfd85987c29ec4f2479ca47be0d497a230480 | 3,632,585 |
def get_genes(exp_file, samples, threshold, max_only):
"""
Reads in and parses the .bed expression file.
File format expected to be:
Whose format is tab seperated columns with header line:
CHR START STOP GENE <sample 1> <sample 2> ... <sample n>
Args:
exp_file (str): Name... | 62b27eef9c863078c98dee0d09bada5e058909e2 | 3,632,586 |
def conv_name_to_c(name):
"""Convert a device-tree name to a C identifier
This uses multiple replace() calls instead of re.sub() since it is faster
(400ms for 1m calls versus 1000ms for the 're' version).
Args:
name: Name to convert
Return:
String containing the C version of this... | 150af670d8befea7374bbb5b13da9d6e0734863e | 3,632,587 |
from typing import Tuple
from typing import Optional
from typing import List
import io
from re import I
import textwrap
def generate(
symbol_table: intermediate.SymbolTable, namespace: csharp_common.NamespaceIdentifier
) -> Tuple[Optional[str], Optional[List[Error]]]:
"""
Generate the C# code of the visit... | 53e905a0ad37b5f6e47220439747a004db7f8203 | 3,632,588 |
def get_account_id(role_arn):
"""
Returns the account ID for a given role ARN.
"""
# The format of an IAM role ARN is
#
# arn:partition:service:region:account:resource
#
# Where:
#
# - 'arn' is a literal string
# - 'service' is always 'iam' for IAM resources
# - 'regi... | 623eb66eefd59b9416deb478c527062ae4454df7 | 3,632,589 |
def retrieve_context_topology_node_total_potential_capacity_total_potential_capacity(uuid, node_uuid): # noqa: E501
"""Retrieve total-potential-capacity
Retrieve operation of resource: total-potential-capacity # noqa: E501
:param uuid: ID of uuid
:type uuid: str
:param node_uuid: ID of node_uuid
... | 5a4cdee9e14783598ad622fd7faacc5c11b2ed70 | 3,632,590 |
def GHP_Op_max(Q_max_GHP_W, tsup_K, tground_K):
"""
For the operation of a Geothermal heat pump (GSHP) at maximum capacity supplying DHN.
:type tsup_K : float
:param tsup_K: supply temperature to the DHN (hot)
:type tground_K : float
:param tground_K: ground temperature
:type nProbes: float... | 3025a70d8d32030cb098b2087e0d9e0eef16b315 | 3,632,591 |
def attention_lm_decoder(decoder_input,
decoder_self_attention_bias,
hparams,
name="decoder"):
"""A stack of attention_lm layers.
Args:
decoder_input: a Tensor
decoder_self_attention_bias: bias Tensor for self-attention
(see c... | 90ff631cdf8898dfde86e965ad70c317936f0b1c | 3,632,592 |
from typing import Any
def list_to_dict(data: list, value: Any = {}) -> dict:
"""Convert list to a dictionary.
Parameters
----------
data: list
Data type to convert
value: typing.Any
Default value for the dict keys
Returns
-------
dictionary : dict
Dictionary ... | 1e73bb6ca98b5e2d9b1e0f8d4cb19fc044a9ce63 | 3,632,593 |
def Routing_Meta():
"""Routing_Meta() -> MetaObject"""
return _DataModel.Routing_Meta() | f5fc17eb8dc8e428e03ec6fe37cb9dec2c32f355 | 3,632,594 |
def get_tag_name(tag):
"""
Extract the name portion of a tag URI.
Parameters
----------
tag : str
Returns
-------
str
"""
return tag[tag.rfind("/") + 1:tag.rfind("-")] | e24f0ae84ed096ec71f860291d1e476c75bf8370 | 3,632,595 |
import requests
def create_user(token, user_name, maps_to_id):
"""
Creates the user account in Keycloak
"""
users_url = '{keycloak}/auth/admin/realms/{realm}/users'.format(
keycloak=KEYCLOAK['SERVICE_ACCOUNT_KEYCLOAK_API_BASE'],
realm=KEYCLOAK['SERVICE_ACCOUNT_REALM'])
headers = {... | e7a4b9cce99343156dc3933d7726cbc8ff5a1597 | 3,632,596 |
def view_profile(request, username=None):
"""view a user's profile
"""
message = "You must select a user or be logged in to view a profile."
if not username:
if not request.user:
messages.info(request, message)
return redirect("collections")
user = request.user
... | 5ab171f5d1f414100b8c8e36b652511b3df37a9b | 3,632,598 |
import torch
def bf_shannon_entropy(w: 'Tensor[N, N]') -> 'Tensor[1]':
"""
Compute the Shannon entropy of w.
Warning: this method is very inefficient.
It should only be used on small examples, e.g., for testing purposes.
"""
Z = torch.zeros(1).double().to(device)
H = torch.zeros(1).double(... | b606c97cd43ead270b82d73bf9af2a0aed2b9a08 | 3,632,599 |
def extract_y(x, coefficients, degree):
"""
:param x: a matrix containing in each row the first 'degree' powers of a random number in the interval [-3, 2]
:param coefficients: vector of coefficients w_star' (in ascending order: from x**0 to x**n)
:return y : value of y that satisfy the polynomial given ... | 424b94b99bfcbe12e230e18ba0ecc7f7296da164 | 3,632,600 |
def model_scattered_light(data, errs, mask,
verbose=True,
deg=[5,5], sigma=3.0, maxiter=10):
"""
Fit a 2D legendre polynomial to data (only using data in the mask).
Iteratively sigma-clip outlier points.
"""
scatlight = data.copy()
scatlighterr... | 28cd9638a40db6734fe00a00bbbb76b588eb0619 | 3,632,601 |
def Convert_Data_To_GrayScale(data):
"""
This function converts an image data set in grayscale
input:
data: input data set
return: a numpy array of grayscale images
"""
return np.sum(data/3, axis=3, keepdims=True) | dc814b209e7a22981e5395cd3fead16b0d7c222c | 3,632,602 |
def jittered_center_crop(frames,
box_extract,
box_gt,
search_area_factor,
output_sz,
scale_type='original',
border_type='replicate'):
""" For each frame in frames, ex... | 477c847fe6b9d5a8baa5775c8220c267d69c22ab | 3,632,603 |
def np_sample_kumaraswamy(a, b, size):
"""
Numpy function to sample k ~ Kumaraswamy(a, b)
Args:
a: shape parameter 1
b: shape parameter 2
size: Return shape of np array
"""
assert a>0 and b>0, "Parameters can not be zero"
U = np.random.uniform(size=size)
K = (1 - (1 - U)**(1... | f1011f4a590066290f7c8ea10585432b49375987 | 3,632,604 |
import re
def find_meta(meta, file, error=True):
"""
Extract __meta__ value from METAFILE.
file may contain:
__meta__ = 'value'
__meta__ = '''value lines '''
"""
try:
text = read(file)
except Exception as err:
raise RuntimeError("Failed to read file") from err
... | 844f6000d591d145f3e267a73bf7a8ebf67c60a3 | 3,632,605 |
def get_training_input(filenames, params):
""" Get input for training stage
:param filenames: A list contains [source_filename, target_filename]
:param params: Hyper-parameters
:returns: A dictionary of pair <Key, Tensor>
"""
with tf.device("/cpu:0"):
src_dataset = tf.data.TextLineDat... | 25e2a92cce6b9dcbc89187d873ba580bd8ed3da0 | 3,632,606 |
def cbar(ni, nj, resources, commcost):
""" Average communication cost """
n = len(resources)
if n == 1:
return 0
npairs = n * (n - 1)
return 1. * sum(commcost(ni, nj, a1, a2) for a1 in resources.values() for a2 in resources.values()
if a1 != a2) / npairs | b215de30bcb019e2299edbb61591b7a1c129c58b | 3,632,607 |
import re
def get_electrostatic_potentials(outcar, atoms):
""" Retrieve the electrostatic averaged potentials from the OUTCAR file
:param outcar: content of the OUTCAR file (list of strings)
:param atoms: number of atoms of each atomic species (list of integers)
:return: dictionary with the electrosta... | 5846dc5b33d68ba19fced68fa0a6ffd76653ebb8 | 3,632,608 |
import logging
def get_metrics_delta(metric_name, label_suffix, labels, before_metrics, after_metrics):
"""Calculate the difference between 2 samples"""
s1 = find_sample_by_labels(metric_name, label_suffix, labels, before_metrics)
s2 = find_sample_by_labels(metric_name, label_suffix, labels, after_metrics... | e2baf39507bfaf281731241257796275e7284c32 | 3,632,609 |
def convert_region_type(region_type):
"""
Convert the integer region_type to the corresponding RegionType enum object.
"""
return int_to_region_type[region_type] | 2f16634c188e172a0a5a2d84db38782e7131d86f | 3,632,610 |
import scipy
def fit_to_data(x: np.ndarray, y: np.ndarray) -> np.ndarray:
"""
Fit @a func to data in @a x and @a y
Create an initial estimate for parameters, because timestamps are very big
"""
p0 = np.array([1.0, x[0] - 100, 0.0])
popt, _ = scipy.optimize.curve_fit(f=weight, xdata=x, ydata=y... | c9bba5795c5590cce87c4d04d8ccddfb0ce7d57f | 3,632,612 |
def new_url(fiscal_year, dept_str=DEPARTMENTS_DICT['1700']):
"""
modify the URL
https://www.fpds.gov/ddps/FY07-V1.4/1700-DEPARTMENTOFTHENAVY/1700-DEPARTMENTOFTHENAVY-DEPTOctober2006-Archive.zip
to be correct for the `fiscal_year` given.
"""
assert type(fiscal_year) is str, "fiscal year must be s... | 7d12bd1e060abcd3b382ee9eb094c193e5d3a04e | 3,632,613 |
def normalize_units(data):
"""Normalize units in datasets and their exchanges"""
for obj in data:
obj['unit'] = normalize_units_function(obj.get('unit', ''))
# for param in ds.get('parameters', {}).values():
# if 'unit' in param:
# param['unit'] = normalize_units_function(param['... | eea6cbdc7e8ad9852c0f6ab03a8f9d2789568164 | 3,632,614 |
def xvalBooklets(dfResp, dfObsResp, configObsList, configRespList):
"""
Cross-validates records for a booklet using data from a ready-made data frames. Returns a data frame containing
extracted responses from the response data table and the reconstructed responses from the observable
data, for selected ... | 29ca12be17a9b5b660ab44256deaf85f678b86d0 | 3,632,615 |
def imap_any(conditions):
"""
Generate an IMAP query expression that will match any of the expressions in
`conditions`.
In IMAP, both operands used by the OR operator appear after the OR, and
chaining ORs can create very verbose, hard to parse queries e.g. "OR OR OR
X-GM-THRID 111 X-GM-THRID 22... | de4ef1680cd2c8370d82640ff95186ed3ea81202 | 3,632,616 |
def format_sources(sources):
"""
Make a comma separated string of news source labels.
"""
formatted_sources = ""
for source in sources:
formatted_sources += source["value"] + ','
return formatted_sources | f9f86f11e4dfe9ecd3fbbd5e14d3ca750a4e1a5a | 3,632,617 |
def update_dict_to_latex(update_dict, order):
"""Returns update dictionary and order as latex string."""
ret_val = "\\begin{eqnarray*}\n"
get_line = lambda obj: wrap_long_latex_line(latex_print(obj) + "\\\\\n")
for v in reversed(order):
ret_val += latex_print(v) + " &=& "
if isinstance(u... | 4498216b5a6a224a7609d739670348e7dafa0843 | 3,632,618 |
def setup_base_empty_grade_helper(user: User, unit: models.Unit) -> models.Grade:
"""
Helper method to setup an empty grade before sending a request to the grading
view.
"""
grade = models.Grade(user=user, unit=unit)
grade.status = "sent"
grade.score = None
grade.notebook = None
gra... | 1c80a04c0de4859c050c8e09c5c8f31166898c64 | 3,632,619 |
def register_project(fn: tp.Callable = None):
"""Register new project.
Parameters
----------
call
This function will get invoked upon finding the project_path.
the function name will be used to search in $PROJECT_PATHS
"""
def _wrapper():
path = _start_proj_shell(fn.__n... | 8b379434c2cefa444d2fbb3168bf66295c6e8cac | 3,632,620 |
import re
def tag_word_in_sentence(sentence, tag_word):
"""
Use regex to wrap every derived form of a given ``tag_word`` in ``sentence`` in an html-tag.
Args:
sentence: String containing of multiple words.
tag_word: Word that should be wrapped.
Returns:
: Sentence with replacements... | 84567341d24b34cf7effca7cb1798d9c4b01533d | 3,632,622 |
def get_content_type(response: 'Response') -> str:
"""Get content type from ``response``.
Args:
response (:class:`requests.Response`): Response object.
Returns:
The content type from ``response``.
Note:
If the ``Content-Type`` header is not defined in ``response``,
the... | 34398cca048c6eb261e2481884f4496a03749c16 | 3,632,623 |
def _get_file_url_from_dropbox(dropbox_url, filename):
"""Dropbox now supports modifying the shareable url with a simple
param that will allow the tool to start downloading immediately.
"""
return dropbox_url + '?dl=1' | fe0256ae747826dbbe5ac3c3a4afa42e0584699a | 3,632,624 |
def launch_coef_scores(args):
"""
Wrapper to compute the standardized scores of the regression coefficients, used when computing the number of
features in the reduced parameter set.
@param args: Tuple containing the instance of SupervisedPCABase, feature matrix and response array.
@return: The stan... | 02423ef564b55dfcc37bddadcc813edffba05795 | 3,632,625 |
from typing import Any
def update(
configuration: dict, client: Any, issue: Any, issue_fields: dict, transition: str = None
) -> dict:
"""Updates a Jira issue."""
data = {"resource_id": issue.key, "link": f"{configuration.browser_url}/browse/{issue.key}"}
if issue_fields:
issue.update(fields=... | 13342f693e6fdce753d10856a5ff325d6ec84d9b | 3,632,626 |
def resolve_wishlist_from_user(user: "User") -> Wishlist:
"""Return wishlist of the logged in user."""
wishlist, _ = Wishlist.objects.get_or_create(user=user)
return wishlist | 2b21487bc5ee6c8da0cce7212e1065e2abb85004 | 3,632,627 |
def register_dat_matrix(file_path):
"""
Parse the registration matrix from the given file.
Parse the registration matrix from the given file in register.dat file format. See https://surfer.nmr.mgh.harvard.edu/fswiki/RegisterDat for the file format. The matrix encodes an affine transformation that can be ap... | 379c8d5b39ac448ef63412975afde50bf9f7359e | 3,632,628 |
import warnings
import math
def lnprob(theta, phi_total_data, f_blue_data, err, corr_mat_inv):
"""
Calculates log probability for emcee
Parameters
----------
theta: array
Array of parameter values
phi: array
Array of y-axis values of mass function
err: numpy.arra... | 97a884ce0af245982b806f360d16606d3eed966f | 3,632,629 |
def get_car_coordinates(list_points, x_points_traj, y_points_traj):
"""
input:
list_points - car config = phi(last point), length, width, l_base
x_points_traj, x_points_traj - current shifted position(center of back axis)
return:
car_coordinates - list(list)
len(car_coordinates) = 4
"""
list_point... | 0e1449ff39828db49ad3e5497d901ffeef135110 | 3,632,630 |
def create_module(module_name):
"""Function for create a new empty virtual module and register it"""
module = module_cls(module_name)
setattr(module, '__spec__', spec_cls(name=module_name, loader=VirtualModuleLoader))
registry[module_name] = module
return module | 9b08c7899513a4f181577b11385dc77d4e347d09 | 3,632,631 |
def _days_in_month(month_0: int, year: int) -> int:
""" Returns days in a month (0-indexed). Hope I got this right. """
if month_0 != 1:
return DAYS_IN_MONTH[month_0]
if (year % 4) == 0 and ((year % 100) != 0 or (year % 400) == 0):
return DAYS_IN_MONTH[month_0] + 1
return DAYS_IN_MONTH[... | b234491372def8c1f2da30039e8b41551d14eb84 | 3,632,632 |
def create_otfeature( featureName = "calt",
featureCode = "# empty feature code",
targetFont = None,
codeSig = "DEFAULT-CODE-SIGNATURE" ):
"""
Creates or updates an OpenType feature in the font.
Returns a status message in form of a string.
"""
... | 4e212dfaf161b3cd7c7ab5c4ffb187a73c979e67 | 3,632,633 |
def wilson_ci(num_hits, num_total, confidence=0.95):
""" Convenience wrapper for general_wilson """
z = st.norm.ppf((1+confidence)/2)
p = num_hits / num_total
return general_wilson(p, num_total, z=z) | 30706ff0848cc8c292b182ed946af71093b07e73 | 3,632,634 |
def convert_to_noun(word, from_pos):
""" Transform words given from/to POS tags """
if word.lower() in ['most', 'more'] and from_pos == 'a':
word = 'many'
synsets = wn.synsets(word, pos=from_pos)
# Word not found
if not synsets:
return []
result = derivational_conversion(word... | 02b7aba4e386297ed34d004aa55cab481c22f81f | 3,632,635 |
import itertools
def get_slug(obj, title, group):
"""
used to get unique slugs
:param obj: Model Object
:param title: Title to create slug from
:param group: Model Class
:return: Model object with unique slug
"""
if obj.pk is None:
obj.slug = slug_orig = slugify(title)
for x in itertools.count(1):
if n... | 014ac32090d70c5acda6f7f46804b88e730c54bd | 3,632,636 |
def create_link(url):
"""Create an html link for the given url"""
return (f'<a href = "{url}" target="_blank">{url}</a>') | 77a5375369be2be140a69a4521c50a92cee2d5ed | 3,632,637 |
def cummean(x):
"""Return a same-length array, containing the cumulative mean."""
return x.expanding().mean() | b5a35c56cb78e0588dd5be64a75384c4cd81ccb5 | 3,632,638 |
def validity_range_contains_range(
overall_range: DateRange,
contained_range: DateRange,
) -> bool:
"""
If the contained_range has both an upper and lower bound, check they are
both within the overall_range.
If either end is unbounded in the contained range,it must also be unbounded
in the ... | 255f0782a8b6461692a255380fdfc9079e5ca33a | 3,632,639 |
def find_reference_section_no_title_via_dots(docbody):
"""This function would generally be used when it was not possible to locate
the start of a document's reference section by means of its title.
Instead, this function will look for reference lines that have numeric
markers of the format 1., ... | 546533051b9ca8df1266ea278dd34134c1a234c9 | 3,632,640 |
def get_syntax_errors(graph):
"""List the syntax errors encountered during compilation of a BEL script.
Uses SyntaxError as a stand-in for :exc:`pybel.parser.exc.BelSyntaxError`
:param pybel.BELGraph graph: A BEL graph
:return: A list of 4-tuples of line number, line text, exception, and annotations p... | a0f3493b88b081de3613397c997d71dabdae78be | 3,632,641 |
def generate_S_tau(t):
"""
Generates the S_tau matrix for a template
Args:
t (np.array): the template vector
Returns:
np.array: the S_tau matrix
"""
t_binning = unique_binning(t)
return generate_S_from_binning(t_binning) | b438f9ddd0c36de3abb32553e21b7495f163b1a9 | 3,632,642 |
def create_neural_network(input_, output_, reservoir_, spectral_, sparsity_, noise_, input_scale, random_, silent_):
"""Create an Echo State Network.
:rtype: pyESN.ESN
:param input_: number of input units to use in ESN
:param output_: number of output units to use in ESN
:param reservoir_: number of... | 25b2048e1d3790e6386df0cfa6bdcfee4fc73db4 | 3,632,643 |
def validate_measure_for_asset_changes(asset_type: str, measure: str) -> str:
"""
Validates the range argument for asset changes command
:param asset_type: asset type argument passed by the user
:param measure: measure argument passed by the user
:return: measure if valid else raise ValueError
"... | 0bac72d07fd65cbcc589b2e6d5ea0faed13ee69a | 3,632,644 |
def create_incident(**kwargs):
"""
Creates an incident
"""
incidents = cachet.Incidents(endpoint=ENDPOINT, api_token=API_TOKEN)
if 'component_id' in kwargs:
return incidents.post(name=kwargs['name'],
message=kwargs['message'],
statu... | a19312816556a06f892da8ac9c8c6bb344ed3ce8 | 3,632,645 |
def harvey_two(frequency, tau_1, sigma_1, tau_2, sigma_2, white_noise, ab=False):
"""
Two Harvey model
Parameters
----------
frequency : numpy.ndarray
the frequency array
tau_1 : float
timescale of the first harvey component
sigma_1 : float
amplitude of the first har... | bc5860984c7bf357f18f6f7ec8e2ce592f6841cd | 3,632,646 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.