content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def sample_targets_and_primes(targets, primes, n_rounds,
already_sampled_targets=None, already_sampled_primes=None):
"""
Sample targets `targets` and primes `primes` for `n_rounds` number of rounds. Omit already sampled targets
or primes which can be passed as sets `already_sam... | 21,100 |
def test_recurse():
"""
Test to recurse through a subdirectory on the master
and copy said subdirectory over to the specified path.
"""
name = "/opt/code/flask"
source = "salt://code/flask"
user = "salt"
group = "saltstack"
if salt.utils.platform.is_windows():
name = name.rep... | 21,101 |
def getsign(num):
"""input the raw num string, return a tuple (sign_num, num_abs).
"""
sign_num = ''
if num.startswith('±'):
sign_num = plus_minus
num_abs = num.lstrip('±+-')
if not islegal(num_abs):
return sign_num, ''
else:
try:
temp = float(... | 21,102 |
def _convert_actions_to_commands(
subvol: Subvol,
build_appliance: Subvol,
action_to_names_or_rpms: Mapping[RpmAction, Union[str, _LocalRpm]],
) -> Mapping[YumDnfCommand, Union[str, _LocalRpm]]:
"""
Go through the list of RPMs to install and change the action to
downgrade if it is a local RPM wi... | 21,103 |
def fit_DBscan (image_X,
eps,
eps_grain_boundary,
min_sample,
min_sample_grain_boundary,
filter_boundary,
remove_large_clusters,
remove_small_clusters,
binarize_bdr_coord,
... | 21,104 |
def get_today_timestring():
"""Docen."""
return pd.Timestamp.today().strftime('%Y-%m-%d') | 21,105 |
def load_json(filepath):
"""
Load a json file
:param filepath: path to json file
"""
fp = Path(filepath)
if not fp.exists():
raise ValueError("Unrecognized file path: {}".format(filepath))
with open(filepath) as f:
data = json.load(f)
return data | 21,106 |
def handle(req):
"""handle a request to the function
Args:
req (str): request body
"""
r = requests.get("http://api.open-notify.org/astros.json")
result = r.json()
index = random.randint(0, len(result["people"]) - 1)
name = result["people"][index]["name"]
return "{} is in space"... | 21,107 |
def get_file_hashsum(file_name: str):
"""Generate a SHA-256 hashsum of the given file."""
hash_sha256 = hashlib.sha256()
with open(file_name, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_sha256.update(chunk)
return hash_sha256.hexdigest() | 21,108 |
def predict_ch3(net, test_iter, n=6):
"""预测标签(定义见第3章)。"""
for X, y in test_iter:
break
trues = d2l.get_fashion_mnist_labels(y)
preds = d2l.get_fashion_mnist_labels(d2l.argmax(net(X), axis=1))
titles = [true + '\n' + pred for true, pred in zip(trues, preds)]
d2l.show_images(d2l.reshape(X[... | 21,109 |
def getReviews(appid, savePath):
"""
This function returns a list of user reviews from Steamworks website, convert the
reviews into Pandas dataframe, then export to .csv file to the savePath
"""
# Detailed reference for parameters setting, please visit:
# https://partner.steamgames.com/doc/s... | 21,110 |
def generate_primes(n):
"""Generates a list of prime numbers up to `n`
"""
global PRIMES
k = PRIMES[-1] + 2
while k <= n:
primes_so_far = PRIMES[:]
divisible = False
for p in primes_so_far:
if k % p == 0:
divisible = True
break
... | 21,111 |
def Convex(loss, L2_reg):
"""
loss: src_number loss
[loss_1, loss_2, ... loss_src_number]
"""
src_number = len(loss)
lam = cp.Variable(src_number)
prob = cp.Problem(
cp.Minimize(lam @ loss + L2_reg * cp.norm(lam, 2)), [cp.sum(lam) == 1, lam >= 0]
)
# prob.solve()
prob.so... | 21,112 |
def state(new_state):
"""State decorator.
Specify True (turn on) or False (turn off).
"""
def decorator(function):
"""Decorator function."""
# pylint: disable=no-member,protected-access
def wrapper(self, **kwargs):
"""Wrap a group state change."""
from li... | 21,113 |
def rotTransMatrixNOAD(axis, s, c, t):
"""
build a rotate * translate matrix - MUCH faster for derivatives
since we know there are a ton of zeros and can act accordingly
:param axis: x y or z as a character
:param s: sin of theta
:param c: cos of theta
:param t: translation (a 3 tuple)
:... | 21,114 |
def angular_diameter_distance(z, cosmo=None):
""" Angular diameter distance in Mpc at a given redshift.
This gives the proper (sometimes called 'physical') transverse
distance corresponding to an angle of 1 radian for an object at
redshift `z`.
Parameters
----------
z : array_like
In... | 21,115 |
def main(stdin):
"""
Take sorted standard in from Hadoop and return lines.
Value is just a place holder.
"""
for line_num in stdin:
# Remove trailing newlines.
line_num = line_num.rstrip()
# Omit empty lines.
try:
(line, num) = line_num.rsplit('\t', 1)
... | 21,116 |
def _ignore_module_import_frames(file_name, name, line_number, line):
"""
Ignores import frames of extension loading.
Parameters
----------
file_name : `str`
The frame's respective file's name.
name : `str`
The frame's respective function's name.
line_number : `int`
... | 21,117 |
def test_i(name, expectation, limit_name, limit_value, result):
""" Check for behaviour of I under different pipeline configurations.
name
Name of I, defines its output.
expectation
Test is expected to raise an error when names requires calculaion of total iterations (e.g. for 'm')
... | 21,118 |
def get_tf_tensor_data(tensor):
"""Get data from tensor."""
assert isinstance(tensor, tensor_pb2.TensorProto)
is_raw = False
if tensor.tensor_content:
data = tensor.tensor_content
is_raw = True
elif tensor.float_val:
data = tensor.float_val
elif tensor.dcomplex_val:
... | 21,119 |
def _createPhraseMatchList(tree1, tree2, matchList, doEquivNodes=False):
"""
Create the list of linked phrases between tree1 and tree2
"""
phraseListTxt1 = tree1.getPhrases()
phraseListHi1 = tree2.getPhrases()
if PRINT_DEBUG or PRINT_DEBUG_SPLIT:
print "\nPhrase 1 nodes:"
pr... | 21,120 |
def coth(x):
"""
Return the hyperbolic cotangent of x.
"""
return 1.0/tanh(x) | 21,121 |
def rmtree_fixed(path):
"""Like :func:`shutil.rmtree` but doesn't choke on annoying permissions.
If a directory with -w or -x is encountered, it gets fixed and deletion
continues.
"""
if path.is_link():
raise OSError("Cannot call rmtree on a symbolic link")
uid = os.getuid()
st = p... | 21,122 |
def param_is_numeric(p):
"""
Test whether any parameter is numeric; functionally, determines if any
parameter is convertible to a float.
:param p: An input parameter
:return:
"""
try:
float(p)
return True
except ValueError:
return False | 21,123 |
def convert_graph_to_angular_abstract_graph(graph: Graph, simple_graph=True, return_tripel_edges=False) -> Graph:
"""Converts a graph into an abstract angular graph
Can be used to calculate a path tsp
Arguments:
graph {Graph} -- Graph to be converted
simple_graph {bool} -- Indicates if ... | 21,124 |
def login_to_site(url, username, password, user_tag, pass_tag):
"""
:param url:
:param username:
:param password:
:param user_tag:
:param pass_tag:
:return: :raise:
"""
browser = mechanize.Browser(factory=mechanize.RobustFactory())
browser.set_handle_robots(False)
browser.se... | 21,125 |
async def test_db(
service: Service = Depends(Service)
) -> HTTPSuccess:
"""Test the API to determine if the database is connected."""
if service.test().__class__ is not None:
return { "message": "Database connected." }
else:
return {"message": "Database not connected." } | 21,126 |
def main(ctx):
"""Show ids of accounts defined in `my_accounts` config var.
The format is suitable for BITSHARESD_TRACK_ACCOUNTS= env variable to use in docker-compose.yml for running docker
image bitshares/bitshares-core:latest
"""
if not ctx.config['my_accounts']:
ctx.log.critical('You n... | 21,127 |
def model_fit_predict():
"""
Training example was implemented according to machine-learning-mastery forum
The function takes data from the dictionary returned from splitWindows.create_windows function
https://machinelearningmastery.com/stateful-stateless-lstm-time-series-forecasting-python/
:return:... | 21,128 |
def mp_variant_annotations(df_mp, df_split_cols='', df_sampleid='all',
drop_hom_ref=True, n_cores=1):
"""
Multiprocessing variant annotations
see variantAnnotations.process_variant_annotations for description of annotations
This function coordinates the annotation of varian... | 21,129 |
async def wiki(wiki_q):
""" For .wiki command, fetch content from Wikipedia. """
match = wiki_q.pattern_match.group(1)
try:
summary(match)
except DisambiguationError as error:
await wiki_q.edit(f"Disambiguated page found.\n\n{error}")
return
except PageError as pageerror:
... | 21,130 |
def find_attachments(pattern, cursor):
"""Return a list of attachments that match the specified pattern.
Args:
pattern: The path to the attachment, as a SQLite pattern (to be
passed to a LIKE clause).
cursor: The Cursor object through which the SQLite queries are
sent to... | 21,131 |
def generate_symmetric_matrix(n_unique_action: int, random_state: int) -> np.ndarray:
"""Generate symmetric matrix
Parameters
-----------
n_unique_action: int (>= len_list)
Number of actions.
random_state: int
Controls the random seed in sampling elements of matrix.
Returns
... | 21,132 |
def sanitizer_update(instrument_name: str | None):
"""Update sanitizers with new data"""
from .service.sanitize import update_tablesanitizer
if instrument_name:
items = (instrument_name,)
else:
listing = app.get_local_source_listing(
defaults.source_dir,
defaults.... | 21,133 |
def model_fields_map(model, fields=None, exclude=None, prefix='', prefixm='', attname=True, rename=None):
"""
На основании переданной модели, возвращает список tuple, содержащих путь в орм к этому полю,
и с каким именем оно должно войти в результат.
Обрабатываются только обычные поля, m2m и generic сюда... | 21,134 |
def test_setext_headings_extra_90x():
"""
Test case extra 90: SetExt heading with full image with backslash in label
"""
# Arrange
source_markdown = """a![foo\\#bar][bar]a
---
[bar]: /url 'title'"""
expected_tokens = [
"[setext(2,1):-:3::(1,1)]",
"[text(1,1):a:]",
"[im... | 21,135 |
def scaffold_to_smiles(mols: Union[List[str], List[Chem.Mol]],
use_indices: bool = False) -> Dict[str, Union[Set[str], Set[int]]]:
""" Computes the scaffold for each SMILES and returns a mapping from scaffolds to sets of smiles (or indices).
Parameters
----------
mols: A list of ... | 21,136 |
def encontrar_passwords():
"""
Probar todas las combinaciones de 6 letras, hasheando cada una para ver si
coinciden con los hashes guardados en los /etc/shadow
Para el tema de equipos, basicamente fui probando con copiar y pegar
contenido en texto de distintas paginas de wikipedia en el archivo
... | 21,137 |
def save(fileref, data=None, metadata=None, compression_level=None, order='C'):
"""saves the data/metadata to a file represented by `fileref`."""
if isinstance(fileref, (str, bytes, _PathLike)):
fileref = check_suffix(fileref)
with open(fileref, 'wb') as dest:
save(dest, data=data, m... | 21,138 |
def queue_merlin_study(study, adapter):
"""
Launch a chain of tasks based off of a MerlinStudy.
"""
samples = study.samples
sample_labels = study.sample_labels
egraph = study.dag
LOG.info("Calculating task groupings from DAG.")
groups_of_chains = egraph.group_tasks("_source")
# magi... | 21,139 |
def sphere_mass(density,radius):
"""Usage: Find the mass of a sphere using density and radius"""
return density*((4/3)*(math.pi)*radius**3) | 21,140 |
def generate_stats_table(buildings_clust_df):
"""
Generate statistical analysis table of building types in the area
Args:
buildings_clust_df: building footprints dataframe after performed building blocks assignment (HDBSCAN)
Return:
stat_table: statistical analysis results ... | 21,141 |
def make_multisat(nucsat_tuples):
"""Creates a rst.sty Latex string representation of a multi-satellite RST subtree
(i.e. merge a set of nucleus-satellite relations that share the same nucleus
into one subtree).
"""
nucsat_tuples = [tup for tup in nucsat_tuples] # unpack the iterable, so we can che... | 21,142 |
def plot_to_image(figure):
"""Converts the matplotlib figure to a PNG image."""
# The function is adapted from
# github.com/tensorflow/tensorboard/blob/master/docs/image_summaries.ipynb
# Save the plot to a PNG in memory.
buf = io.BytesIO()
plt.savefig(buf, format="png")
# Closing the figure prevents it ... | 21,143 |
def create_connection(db_config: Box = None) -> None:
"""Register a database connection
Args:
db_config: Yapconf-generated configuration object
Returns:
None
"""
global motor_db
motor_conn = MotorClient(
host=db_config.connection.host,
port=db_config.connection... | 21,144 |
async def getDiscordTwitchAlerts(cls:"PhaazebotDiscord", guild_id:str, alert_id:int=None, limit:int=0, offset:int=0) -> list:
"""
Get server discord alerts, if alert_id = None, get all
else only get one associated with the alert_id
Returns a list of DiscordTwitchAlert().
"""
sql:str = """
SELECT
`discord... | 21,145 |
def is_visible_dir(file_info):
"""Checks to see if the file is a visible directory.
@param file_info: The file to check
@type file_info: a gnomevfs.FileInfo
"""
return is_dir(file_info) and not is_hidden(file_info) | 21,146 |
def add_model_components(m, d, scenario_directory, subproblem, stage):
"""
:param m:
:param d:
:return:
"""
# Import needed availability type modules
required_availability_modules = get_required_subtype_modules_from_projects_file(
scenario_directory=scenario_directory,
subpr... | 21,147 |
def read_file(item):
"""Read file in key path into key image
"""
item['image'] = tf.read_file(item['path'])
return item | 21,148 |
def make_joint(withdraw, old_password, new_password):
"""Return a password-protected withdraw function that has joint access to
the balance of withdraw.
>>> w = make_withdraw(100, 'hax0r')
>>> w(25, 'hax0r')
75
>>> make_joint(w, 'my', 'secret')
'Incorrect password'
>>> j = make_joint(w,... | 21,149 |
def should_parse(config, file):
"""Check if file extension is in list of supported file types (can be configured from cli)"""
return file.suffix and file.suffix.lower() in config.filetypes | 21,150 |
def gui_main():
"""Главное окно программы"""
layout_range = 20
layout_distance = 20
sg.theme(GUI_THEME) # Применение темы интерфейса
layout_main_window = [
[sg.Text('Производитель принтера:',
size=(20, 1),
pad=((0, 0), (10, layout_range))),
sg.D... | 21,151 |
def _get_pipeline_per_subband(subband_name: str):
"""
Constructs a pipeline to extract the specified subband related features.
Output:
sklearn.pipeline.Pipeline object containing all steps to calculate time-domain feature on the specified subband.
"""
freq_range = FREQ_BANDS_RANGE[subband_n... | 21,152 |
def add_default_area(apps, schema_editor):
"""Use a dummy area for progress with no areas
"""
Area = apps.get_model('goals', 'Area')
Progress = apps.get_model('goals', 'Progress')
prgs = Progress.objects.filter(area=None)
if len(prgs):
area = Area.objects.first()
for progress in ... | 21,153 |
def get_credentials_interactively() -> Credentials:
""" Gets credentials for the bl interactively
"""
return ("placeholder-user", "placeholder-pass") | 21,154 |
def reynolds(find="Re", printEqs=True, **kwargs):
"""
Reynolds Number = Inertia / Viscosity
"""
eq = list()
eq.append("Eq(Re, rho * U * L / mu)")
return solveEqs(eq, find=find, printEq=printEqs, **kwargs) | 21,155 |
def data_app():
""" Data Processer and Visualizer """
st.title("Data Cake")
st.subheader("A to Z Data Analysis")
file = ['./dataset/Ac1',[0,1]]
def file_selector():
filename = st.file_uploader("Upload Excel File", type=['xls','xlsx'])
if filename is not None:
sheetname... | 21,156 |
def merge_clusters_for_nodes(nodes_to_merge: List[NNCFNode], clusterization: Clusterization):
"""
Merges clusters to which nodes from nodes_to_merge belongs.
:param nodes_to_merge: All nodes are clusters for which should be merged.
:param clusterization: Clusterization of nodes to work with.
"""
... | 21,157 |
def derivative(x, y, order=1):
"""Returns the derivative of y-coordinates as a function of x-coodinates.
Args:
x (list or array): 1D array x-coordinates.
y (list or array): 1D array y-coordinates.
order (number, optional): derivative order.
Returns:
... | 21,158 |
def get_ff_parameters(wc_params, molecule=None, components=None):
"""Get the parameters for ff_builder."""
ff_params = {
'ff_framework': wc_params['ff_framework'],
'ff_molecules': {},
'shifted': wc_params['ff_shifted'],
'tail_corrections': wc_params['ff_tail_corrections'],
... | 21,159 |
def healpix_header_odict(nside,nest=False,ordering='RING',coord=None, partial=True):
"""Mimic the healpy header keywords."""
hdr = odict([])
hdr['PIXTYPE']=odict([('name','PIXTYPE'),
('value','HEALPIX'),
('comment','HEALPIX pixelisation')])
ordering =... | 21,160 |
def hello():
"""Test endpoint"""
return {'hello': 'world'} | 21,161 |
def get_config_data(func_name: str, config_file_name: str = "config.json")\
-> tuple[str, str, str, str] | str | tuple[str, str]:
"""Extracts the data pertaining to the covid_news_handling module from the
provided config file.
A try except is used to get the encoding style to be used, and to check ... | 21,162 |
def test_get_sorted_filenames():
"""
Checking sorted filenames returned by util function
"""
with TempDirectory() as tempdir:
tempdir.write((tempdir.path + "/a.txt"), (bytes(1)))
tempdir.write((tempdir.path + "/b.txt"), (bytes(1)))
tempdir.write((tempdir.path + "/c.txt"), (bytes(... | 21,163 |
def compare_gaussian_classifiers():
"""
Fit both Gaussian Naive Bayes and LDA classifiers on both
gaussians1 and gaussians2 datasets
"""
for f in ["gaussian1.npy", "gaussian2.npy"]:
# Load dataset
X, y = load_dataset(f"../datasets/{f}")
# Fit models and predict over training ... | 21,164 |
def permute_channels(n_channels, keep_nbr_order=True):
"""Permute the order of neighbor channels
Args:
n_channels: the total number of channels
keep_nbr_order: whether to keep the relative order of neighbors
if true, only do random rotation and flip
if false, random perm... | 21,165 |
def checkHdf5CorrelationNan(frags_dict, fragList, atmList, jsonfile):
"""Check cor energies are not error. Cor energies that were not calculated are 0.0 and nan if error."""
with open('correlation-nan.txt', 'w') as w:
for key, dict_ in frags_dict.items():
if np.isnan(dict_['os']):
... | 21,166 |
def test_merging_recipes():
"""Test recipes can be merged and merging results in a valid minimal DAG."""
A, B = generate_recipes()
# Merging empty recipes returns original recipe
C = A.merge(None)
assert A == C
C = workflows.recipe.Recipe().merge(A)
assert A == C
C = A.merge(workflows... | 21,167 |
def from_file(file,typcls):
"""Parse an instance of the given typeclass from the given file."""
s = Stream(file)
return s.read_value(typcls._ep_typedesc) | 21,168 |
def test_supersmoother_multiband(N=100, period=1):
"""Test that results are the same with/without filter labels"""
t, y, dy = _generate_data(N, period)
periods = np.linspace(period / 2, period * 2, 100)
model = SuperSmoother()
P_singleband = model.fit(t, y, dy).score(periods)
filts = np.ones(N... | 21,169 |
def read_test_ids():
"""
Read sample submission file, list and return all test image ids.
"""
df_test = pd.read_csv(SAMPLE_SUBMISSION_PATH)
ids_test = df_test['img'].map(lambda s: s.split('.')[0])
return ids_test | 21,170 |
def chuseok(year=None):
"""
:parm year: int
:return: Thanksgiving Day of Korea
"""
year = year if year else _year
return LunarDate(year, 8, 15).toSolarDate() | 21,171 |
def _run():
"""Makes event-attribution schematics for 2019 tornado-prediction paper.
This is effectively the main method.
"""
file_system_utils.mkdir_recursive_if_necessary(
directory_name=OUTPUT_DIR_NAME)
# Interpolation with merger.
figure_object, axes_object = _plot_interp_two_time... | 21,172 |
def plot_order(generation_idx, obs, out_path=None):
"""Plot generation coordinate list. A star on the curve
denotes the pixel generated last. obs is a three-tuple of input image dimensions,
(input-channels-unused, num_rows, num_cols)"""
plt.figure(figsize=(3, 3))
plt.hlines(np.arange(-1, obs[1])+0.5... | 21,173 |
def distribute(iterable, layout: ModelLayout):
"""
Of each group of layout.n_replicas successive items from the iterable, pick the one with index
`layout.replica_idx`.
Makes sure that the underlying iterator is advanced at the same pace no matter what replica_idx is.
"""
it = iter(iterable)
... | 21,174 |
def DELETE(request):
"""Delete a user's authorization level over a simulation."""
# Make sure required parameters are there
try:
request.check_required_parameters(
path={
'simulationId': 'int',
'userId': 'int'
}
)
except exceptio... | 21,175 |
def process_query(data):
"""
Concat query, question, and narrative then 'preprocess'
:data: a dataframe with queries in rows; query, question, and narrative in columns
:return: 2d list of tokens (rows: queries, columns: tokens)
"""
lst_index = []
lst_words = []
for index, r... | 21,176 |
def test_ssl_cert_search_command_success(mocker_http_request, client):
"""
When "ssl-cert-search" command executes successfully then context output and response should match.
"""
from PassiveTotal_v2 import ssl_cert_search_command
# Fetching expected raw response from file
with open('test_d... | 21,177 |
def parameter_parser():
"""
A method to parse up command line parameters.
The default hyperparameters give a high performance model without grid search.
"""
parser = argparse.ArgumentParser(description="Run SimGNN.")
parser.add_argument("--dataset",
nargs="?",
... | 21,178 |
def nb_view_patches(Yr, A, C, S, b, f, d1, d2, YrA=None, image_neurons=None, thr=0.99, denoised_color=None, cmap='jet'):
"""
Interactive plotting utility for ipython notebook
Args:
Yr: np.ndarray
movie
A,C,b,f: np.ndarrays
outputs of matrix factorization algorithm
... | 21,179 |
def menu():
"""Manda el Menú \n
Opciones:
1: Añadir a un donante
2: Añadir a un donatario
3: Revisar la lista de donantes
4: Revisar la lista de donatarios
5: Realizar una transfusion
6: Estadisticas
7: Salir
Returns:
opc(num):Opcion del menu "... | 21,180 |
def get_engine(hass, config):
"""Set up Pico speech component."""
if shutil.which("pico2wave") is None:
_LOGGER.error("'pico2wave' was not found")
return False
return PicoProvider(config[CONF_LANG]) | 21,181 |
def test_optional_fields(data, fld):
"""Verify that the FN028 item is created without error if an optional field is omitted
Arguments:
- `data`:
"""
data[fld] = None
item = FN028(**data)
assert item.project_id == data["project_id"] | 21,182 |
def test_robot_maps(robot):
"""
Test robot maps.
Test robot maps
"""
assert(robot.maps() == [{
'active_pmapv_details': {
'active_pmapv': {
'child_seg_xfer_seq_err': 0,
'create_time': 1570282549,
'creator': 'user',
'... | 21,183 |
def load_cp() -> Tuple[List[str], List[List[float]]]:
"""
Loads cloud point data; target values given in Celsius
Returns:
Tuple[List[str], List[List[float]]]: (smiles strings, target values);
target values have shape (n_samples, 1)
"""
return _load_set('cp') | 21,184 |
async def test_browse_media_single_source_no_identifier(
hass: HomeAssistant, dms_device_mock: Mock, device_source_mock: None
) -> None:
"""Test browse_media without a source_id, with a single device registered."""
# Fast bail-out, mock will be checked after
dms_device_mock.async_browse_metadata.side_ef... | 21,185 |
def walk_up(directory_path):
"""
Implementation by Michele Pasin
https://gist.github.com/zdavkeos/1098474#gistcomment-2943865
Mimic os.walk, but walk 'up' instead of down the directory tree.
"""
directory_path = path.realpath(directory_path)
# get files in current dir
try:
nam... | 21,186 |
def look_up(f, *args, **kwargs):
"""
:param f:
:type f:
:param args:
:type args:
:param kwargs:
:type kwargs:
:return:
:rtype:"""
ag_hash = hash(args) + make_hash(kwargs)
if f in global_table:
if ag_hash in global_table[f]:
return global_table[f][ag_hash]... | 21,187 |
def getenv(key, default=None):
"""Get an environment variable, return None if it doesn't exist.
The optional second argument can specify an alternate default.
"""
return environ.get(key, default) | 21,188 |
def test_list_nmtokens_min_length_nistxml_sv_iv_list_nmtokens_min_length_1_4(mode, save_output, output_format):
"""
Type list/NMTOKENS is restricted by facet minLength with value 5.
"""
assert_bindings(
schema="nistData/list/NMTOKENS/Schema+Instance/NISTSchema-SV-IV-list-NMTOKENS-minLength-1.xsd... | 21,189 |
def read_tag(request, tid, *args, **kwargs):
"""read_tag(tid) returns ..."""
s = api.read_tag(request, tid, *args, **kwargs)
return render_to_response('read/tag.html', s) | 21,190 |
def ber_img(original_img_bin, decoded_img_bin):
"""Compute Bit-Error-Rate (BER) by comparing 2 binary images."""
if not original_img_bin.shape == decoded_img_bin.shape:
raise ValueError('Original and decoded images\' shapes don\'t match !')
height, width, k = original_img_bin.shape
errors_bits... | 21,191 |
def get_fractal_patterns_WtoE_NtoS(fractal_portrait, width, height):
""" get all fractal patterns from fractal portrait, from West to East, from North to South """
fractal_patterns = []
for x in range(width):
# single fractal pattern
f_p = get_fractal_patterns_zero_amounts()
for y in... | 21,192 |
def test_process_entry_array_user(jobs):
"""Providing a user shorts the checks for existing jobs."""
jobs.process_entry(
{
"AllocCPUS": "1",
"Elapsed": "00:00:00",
"JobID": "14729857_[737-999]",
"JobIDRaw": "14729857",
"MaxRSS": "",
... | 21,193 |
def rating(date=None):
"""P2peye comprehensive rating and display results.
from https://www.p2peye.com
Args:
date: if None, download latest data, if like '201812', that download month data.
Returns:
DataFrame
"""
start = time.time()
if date is None:
date = s... | 21,194 |
def crop_image(src, box, expand=0):
"""Read sensor data and crop a bounding box
Args:
src: a rasterio opened path
box: geopandas geometry polygon object
expand: add padding in percent to the edge of the crop
Returns:
masked_image: a crop of sensor data at specified bounds
... | 21,195 |
def add_msgpack_support(cls, ext, add_cls_methods=True):
"""Adds serialization support,
Enables packing and unpacking with msgpack with 'pack.packb' and
'pack.unpackb' methods.
If add_method then enables equality, reading and writing for the classs.
Specificly, adds methods:
bytes <- obj... | 21,196 |
def main():
"""Run the models with each preprocessor using multiple_experiments."""
for preproc in preprocs:
for model in spaces:
multiple_experiments(model, 'full', spaces[model], 5, preproc) | 21,197 |
def test_plot_glass_brain(testdata_3d, tmpdir): # noqa:F811
"""Smoke tests for plot_glass_brain with colorbar and negative values."""
img = testdata_3d['img']
plot_glass_brain(img, colorbar=True, resampling_interpolation='nearest')
# test plot_glass_brain with negative values
plot_glass_brain(img, ... | 21,198 |
def parse_conf():
"""(Dictionary) Function that parses the config file and/or environment variables and returns dictionary."""
# Following tuple holds the configfile/env var versions of each config
ALL_CONFIGS = (
# Name of the variable in code, Path to config in the config file(section + value), n... | 21,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.