content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def create_partial_image_rdd_decoder(key_type):
"""Creates a partial, tuple decoder function.
Args:
value_type (str): The type of the value in the tuple.
Returns:
A partial :meth:`~geopyspark.protobufregistry.ProtoBufRegistry.image_rdd_decoder`
function that requires ``proto_bytes`... | 2df5c506cf8603e9e4acbb4ccb77f8f5d830fe82 | 3,654,000 |
import json
def to_json(simple_object):
"""
Serializes the ``simple_object`` to JSON using the EnhancedJSONEncoder above.
"""
return json.dumps(simple_object, cls=EnhancedJSONEncoder) | c9f8c9474210661a7b63924a72442014c831e170 | 3,654,001 |
def bootstrap_metadata():
""" Provides cluster metadata which includes security modes
"""
return _metadata_helper('bootstrap-config.json') | ec2294606446a9b78a603826fca6f447ed2d9bb9 | 3,654,002 |
def unique_slug(*, title: str, new_slug: str = None) -> str:
"""Create unique slug.
Args:
title: The text where the slug will be generate.
new_slug: Custom slug to hard code.
Returns:
The created slug or hard code slug
"""
if new_slug is None:
slug = slugify(title)... | b4e119502edf144f8393b38a47e3fbeb25335aff | 3,654,003 |
import math
def dcg(r, k=None):
"""The Burges et al. (2005) version of DCG.
This is what everyone uses (except trec_eval)
:param r: results
:param k: cut-off
:return: sum (2^ y_i - 1) / log (i +2)
"""
result = sum([(pow(2, rel) - 1) / math.log(rank + 2, 2) for rank, rel in enumerate(r[:k]... | d93c500ba55411807570c8efebdeaa49ce7fe288 | 3,654,004 |
async def detect_objects(computervision_client, image_url):
"""Detect objects from a remote image"""
detect_objects_results_local = \
computervision_client.detect_objects(image_url)
return detect_objects_results_local.objects | 9adb2a3b2c08f99187159ad6a22047bbf3d4c30a | 3,654,005 |
def rgb(r=None, g=None, b=None, smooth=True, force=True):
"""
Set RGB values with PWM signal
:param r: red value 0-1000
:param g: green value 0-1000
:param b: blue value 0-1000
:param smooth: runs colors change with smooth effect
:param force: clean fade generators and set color
:retu... | 5d5455a785a719e5252c3333e45c06352e8769ed | 3,654,006 |
from .core.configs import get_configs
from .core.configs import set_configs
from .core.configs import del_configs
def handle_config(args, configs):
"""Handle `view` subcommand
:param args: parsed arguments
:type args: `argparse.Namespace`
:param configs: configurations object
:type configs: `... | 60fb9b289e99369a9f83bdf675a793fe85191257 | 3,654,007 |
from typing import Dict
from typing import List
def filter_safe_actions(
action_shield: Dict[int, Dict[ActionData, int]], energy: int, bel_supp_state: int
) -> List[ActionData]:
"""Utility function to filter actions according to required energy for them with given action shield.
Parameters
----------... | e62b24233792d4decca1bd853b6344a8541882be | 3,654,008 |
def get_routes_by_tunnel(compute, project, region, tunnel, restore, debug):
""" Filters all routes to a specific project, region and tunnel."""
match = '%s/regions/%s/vpnTunnels/%s' % (project, region, tunnel)
routes_all = list_routes(compute, project, debug)
routes = []
for route in routes_all:
if route.... | 97500f97b75a225cf08329a12d841e0c92fe3c66 | 3,654,009 |
def fcard(card):
"""Create format string for card display"""
return f"{card[0]} {card[1]}" | ca3866011b418bf35e1b076afd7134926a9382f9 | 3,654,010 |
def resetChapterProgress(chapterProgressDict, chapter, initRepeatLevel):
"""This method resets chapter progress and sets initial level for repeat routine.
Args:
chapterProgressDict (dict): Chapter progress data.
chapter (int): Number of the chapter.
initRepeatLevel (int): Initial level ... | e02d6e97f556a2c080c2bc273255aacedf7bb086 | 3,654,011 |
def aStarSearch(problem, heuristic=nullHeuristic):
"""Search the node that has the lowest combined cost and heuristic first."""
"*** YOUR CODE HERE ***"
priorityqueue = util.PriorityQueue()
priorityqueue.push( (problem.getStartState(), [], 0), heuristic(problem.getStartState(), problem) )
checkedsta... | 0d84de971424d82020b48e35443bfe92cc2665d0 | 3,654,012 |
def gen_flag(p1=0.5, **_args):
"""
Generates a flag.
:param p1: probability of flag = 1
:param _args:
:return: flag
"""
return 1 if np.random.normal(0, 100) <= p1 * 100 else 0 | 0accef3f2fd03c4918b52db2f6c72d405243af87 | 3,654,013 |
from typing import OrderedDict
import re
def load_migrations(path):
"""
Given a path, load all migrations in that path.
:param path: path to look for migrations in
:type path: pathlib.Path or str
"""
migrations = OrderedDict()
r = re.compile(r'^[0-9]+\_.+\.py$')
filtered = filter(
... | 5bd761e6a9ffab4aa08a473e8d2c667e7fb87813 | 3,654,014 |
def filterkey(e, key, ns=False):
"""
Gibt eine Liste aus der Liste C{e} mit dem Attribut C{key} zurück.
B{Beispiel 1}: Herauslesen der SRS aus einer Liste, die C{dict}'s enthält.
>>> e = [{'SRS':'12345', 'Name':'WGS-1'}, {'SRS':'54321', 'Name':'WGS-2'}]
>>> key = "SRS"
>>> filterkey(e, key)
... | f56967e9623622d2dffdb9fe6f128893df9ad798 | 3,654,015 |
def get_runtime_preinstalls(internal_storage, runtime):
"""
Download runtime information from storage at deserialize
"""
if runtime in default_preinstalls.modules:
logger.debug("Using serialize/default_preinstalls")
runtime_meta = default_preinstalls.modules[runtime]
preinstalls ... | 3e9eda4f116f0f5baf38a2fea827c575e814deaa | 3,654,016 |
import os
def update_graph(slider_value):
"""
Update the graph depending on which value of the slider is selected
Parameters
----------
slider_value: the current slider value, None when starting the app
Returns
-------
dcc.Graph object holding the new Plotly Figure as given by the pl... | 4a7e8939c1a86239a08f2fa460f7bf407fa5a686 | 3,654,017 |
def on_coordinator(f):
"""A decorator that, when applied to a function, makes a spawn of that function happen on the coordinator."""
f.on_coordinator = True
return f | d9c97c47255d165c67a4eb67a18cc85c3c9b9386 | 3,654,018 |
def redirect_subfeed(match):
"""
URL migration: my site used to have per-category/subcategory RSS feeds
as /category/path/rss.php. Many of the categories have Path-Aliases
in their respective .cat files, but some of the old subcategories no
longer apply, so now I just bulk-redirect all unaccounted-f... | 101509cbf75ce9be5307edd265988cca662a7880 | 3,654,019 |
from typing import List
from typing import Tuple
import random
def _train_test_split_dataframe_strafified(df:pd.DataFrame, split_cols:List[str], test_ratio:float=0.2, verbose:int=0, **kwargs) -> Tuple[pd.DataFrame, pd.DataFrame]:
"""
ref. the function `train_test_split_dataframe`
"""
df_inspection = d... | 82c4f2a1da3d7e7a4a854c037ab209dffe01f5b2 | 3,654,020 |
def index():
"""
This route will render a template.
If a query string comes into the URL, it will return a parsed
dictionary of the query string keys & values, using request.args
"""
args = None
if request.args:
args = request.args
return render_template("public/index.ht... | ae76de55fb9263264d87447fc2fe173ad62e3245 | 3,654,021 |
from typing import Type
from typing import List
def multi_from_dict(cls: Type[T_FromDict], data: dict, key: str) -> List[T_FromDict]:
"""
Converts {"foo": [{"bar": ...}, {"bar": ...}]} into list of objects using the cls.from_dict method.
"""
return [cls.from_dict(raw) for raw in data.get(key, [])] | 44b9aa28d93f24cc76cddf3cba9fbcbcde937d3d | 3,654,022 |
import inspect
def infer_signature(func, class_name=''):
"""Decorator that infers the signature of a function."""
# infer_method_signature should be idempotent
if hasattr(func, '__is_inferring_sig'):
return func
assert func.__module__ != infer_method_signature.__module__
try:
fu... | e1ab5d9850b4a3026ecd563324026c9cd1675d31 | 3,654,023 |
def field_wrapper(col):
"""Helper function to dynamically create list display method
for :class:`ViewProfilerAdmin` to control value formating
and sort order.
:type col: :data:`settings.ReportColumnFormat`
:rtype: function
"""
def field_format(obj):
return col.format.format(getattr(... | 0a41b5462a6905af5d1f0cc8b9f2bdd00206e6bd | 3,654,024 |
def is_isotropic(value):
""" Determine whether all elements of a value are equal """
if hasattr(value, '__iter__'):
return np.all(value[1:] == value[:-1])
else:
return True | 9c99855d53cf129931c9a9cb51fc491d2fe0df21 | 3,654,025 |
def grouper(iterable, n, fillvalue=None):
"""Iterate over a given iterable in n-size groups."""
args = [iter(iterable)] * n
return zip_longest(*args, fillvalue=fillvalue) | 26adffa4a3c748defe3732d5b94358dda20d095c | 3,654,026 |
def format_gro_coord(resid, resname, aname, seqno, xyz):
""" Print a line in accordance with .gro file format, with six decimal points of precision
Nine decimal points of precision are necessary to get forces below 1e-3 kJ/mol/nm.
@param[in] resid The number of the residue that the atom belongs to
@pa... | ceeeeeafe4f7484fa17ee4ebd79363209c8f7391 | 3,654,027 |
def return_as_list(ignore_nulls: bool = False):
"""
Enables you to write a list-returning functions using a decorator. Example:
>>> def make_a_list(lst):
>>> output = []
>>> for item in lst:
>>> output.append(item)
>>> return output
Is equivalent to:
>>> @retur... | 5f5f089e5664ffbbd5d78a71bf984909e677bcc5 | 3,654,028 |
def get_pingback_url(target_url):
"""
Grabs an page, and reads the pingback url for it.
"""
logger.debug("get_pingback_url called...")
logger.debug("grabbing " + str(target_url))
html = urlopen(target_url).read()
logger.info( "Got %d bytes" % len(html))
soup = bs(html, 'html.parser')
... | cfca2962cf7fee480bae1c0654358dec70906fdd | 3,654,029 |
def assemble_insert_msg_content(row, column, digit):
"""Assemble a digit insertion message."""
return str(row) + CONTENT_SEPARATOR + str(column) + CONTENT_SEPARATOR + str(digit) | 5c4a40aedf4569a8f12793356c2cbedecf32d839 | 3,654,030 |
from typing import Union
def get_difference_of_means(uni_ts: Union[pd.Series, np.ndarray]) -> np.float64:
"""
:return: The absolute difference between the means of the first and the second halves of a
given univariate time series.
"""
mid = int(len(uni_ts) / 2)
return np.abs(get_mean(... | 5e7e709afffde843f3f1be7941c620d4f248e8b4 | 3,654,031 |
def user_collection():
"""
用户的收藏页面
1. 获取参数
- 当前页
2. 返回数据
- 当前页
- 总页数
- 每页的数据
:return:
"""
user = g.user
if not user:
return "请先登录"
# 获取当前页
page = request.args.get('p', 1)
page_show = constants.USER_COLLECTION_MAX_NEWS
# 校验参数
t... | d5ad3a3121dfc169952cad514b3fa930662dd2af | 3,654,032 |
def activity(*, domain, name, version):
"""Decorator that registers a function to `ACTIVITY_FUNCTIONS`
"""
def function_wrapper(func):
identifier = '{}:{}:{}'.format(name, version, domain)
ACTIVITY_FUNCTIONS[identifier] = func
return function_wrapper | 1529c19b8d1d5be02c45e87a446abf62aafc143a | 3,654,033 |
def OEDParser(soup, key):
""" The parser of Oxford Learner's Dictionary. """
rep = DicResult(key)
rep.defs = parseDefs(soup)
rep.examples = parseExample(soup)
return rep | 21b4670047e06f1251e70e09aed5da4dba0449ec | 3,654,034 |
def X_SIDE_GAP_THREE_METHODS(data):
"""
Upside/Downside Gap Three Methods
:param pd.DataFrame data: pandas DataFrame with open, high, low, close data
:return pd.Series: with indicator data calculation results
"""
fn = Function('CDLXSIDEGAP3METHODS')
return fn(data) | 87d3ca966d13756c3cd2bf15647a4d696f1e1f02 | 3,654,035 |
def fix_legacy_database_uri(uri):
""" Fixes legacy Database uris, like postgres:// which is provided by Heroku but no longer supported by SqlAlchemy """
if uri.startswith('postgres://'):
uri = uri.replace('postgres://', 'postgresql://', 1)
return uri | aa3aa20110b7575abf77534d08a35dccb04b731d | 3,654,036 |
def create_need():
"""
Créé le besoin en db
:return:
"""
student = Student.query.filter_by(id_user=session['uid']).first()
title = request.form.get('title')
description = request.form.get('description')
speaker_id = request.form.get('speaker_id')
estimated_tokens = int(request.form.... | d8af541668818e1ed40382b4ed457ac819ab3ce6 | 3,654,037 |
def insert_rolling_mean_columns(data, column_list, window):
"""This function selects the columns of a dataframe
according to a provided list of strings, re-scales its
values and inserts a new column in the dataframe with the
rolling mean of each variable in the column list and the
provided window le... | fd37ca307aaa0d755cd59aa69320003d02cb677a | 3,654,038 |
def get_url_names():
""" Получение ссылок на контент
Returns:
Здесь - список файлов формата *.str
"""
files = ['srts/Iron Man02x26.srt', 'srts/Iron1and8.srt']
return files | 4ee8fdd5ab9efc04eda4bfe1205e073064030520 | 3,654,039 |
from datetime import datetime
def unix_utc_now() -> int:
"""
Return the number of seconds passed from January 1, 1970 UTC.
"""
delta = datetime.utcnow() - datetime(1970, 1, 1)
return int(delta.total_seconds()) | b9768b60cf6f49a7cccedd88482d7a2b21cf05a2 | 3,654,040 |
from typing import Set
def _preload_specific_vars(env_keys: Set[str]) -> Store:
"""Preloads env vars from environ in the given set."""
specified = {}
for env_name, env_value in environ.items():
if env_name not in env_keys:
# Skip vars that have not been requested.
continue... | 6eb6c09f56235b024f15749d8ec65e8801991b43 | 3,654,041 |
import re
def _format_workflow_id(id):
"""
Add workflow prefix to and quote a tool ID.
Args:
id (str): ...
"""
id = urlparse.unquote(id)
if not re.search('^#workflow', id):
return urlparse.quote_plus('#workflow/{}'.format(id))
else:
return urlparse.quote_plus(id) | ea6b6f83ef430128c8a876c9758ce3d70b1bef63 | 3,654,042 |
def calc_log_sum(Vals, sigma):
"""
Returns the optimal value given the choice specific value functions Vals.
Parameters
----------
Vals : [numpy.array]
A numpy.array that holds choice specific values at common grid points.
sigma : float
A number that controls the variance of the ... | 18f71725ea4ced0ea5243fb201f25ae636547947 | 3,654,043 |
def comment_create(request, post_pk):
"""記事へのコメント作成"""
post = get_object_or_404(Post, pk=post_pk)
form = CommentForm(request.POST or None)
if request.method == 'POST':
comment = form.save(commit=False)
comment.post = post
comment.save()
return redirect('blog:post_detail'... | fe6357cfcff1a522064ad9f49b030cf63a02b575 | 3,654,044 |
import torch
def tensor_from_var_2d_list(target, padding=0.0, max_len=None, requires_grad=True):
"""Convert a variable 2 level nested list to a tensor.
e.g. target = [[1, 2, 3], [4, 5, 6, 7, 8]]
"""
max_len_calc = max([len(batch) for batch in target])
if max_len == None:
max_len = max_len_... | 2aa5fcc5b2be683c64026126da55330937cd8242 | 3,654,045 |
from web3.middleware import geth_poa_middleware
def make_w3(gateway_config=None):
"""
Create a Web3 instance configured and ready-to-use gateway to the blockchain.
:param gateway_config: Blockchain gateway configuration.
:type gateway_config: dict
:return: Configured Web3 instance.
:rtype: :... | 85119161c7842319718e7075192b277f810b4328 | 3,654,046 |
def _log2_ratio_to_absolute(log2_ratio, ref_copies, expect_copies, purity=None):
"""Transform a log2 ratio to absolute linear scale (for an impure sample).
Does not round to an integer absolute value here.
Math::
log2_ratio = log2(ncopies / ploidy)
2^log2_ratio = ncopies / ploidy
... | 939a9e4ccb0a1fe9c8c2e6f369bb23c556f04a14 | 3,654,047 |
def fixt():
"""
Create an Exchange object that will be re-used during testing.
"""
mesh = df.UnitCubeMesh(10, 10, 10)
S3 = df.VectorFunctionSpace(mesh, "DG", 0)
Ms = 1
A = 1
m = df.Function(S3)
exch = ExchangeDG(A)
exch.setup(S3, m, Ms)
return {"exch": exch, "m": m, "A": A, ... | 4e46550f1ef9e821e459612b82c0410b7459b09b | 3,654,048 |
def touch_emulator(ev, x, y):
"""
This emulates a touch-screen device, like a tablet or smartphone.
"""
if ev.type == pygame.MOUSEBUTTONDOWN:
if ev.button != 1:
return None, x, y
elif ev.type == pygame.MOUSEBUTTONUP:
if ev.button != 1:
return None, x, y
... | 826b17c7bc9089acebdf3e1ea64fa0613e13e8ea | 3,654,049 |
import sys
def check_python_version() -> bool:
"""Check minimum Python version is being used.
Returns:
True if version is OK.
"""
if sys.version_info.major == 3 and sys.version_info.minor >= 6:
return True
logger.error(
"Aborting... Python version 3.6 or greater is required... | 3ca8296e72a380f86744460ec88cccae1fd58be4 | 3,654,050 |
def invert_dict(d):
"""
Invert dictionary by switching keys and values.
Parameters
----------
d : dict
python dictionary
Returns
-------
dict
Inverted python dictionary
"""
return dict((v, k) for k, v in d.items()) | c70bfdb5ffa96cf07b1a4627aa484e3d5d0f4fea | 3,654,051 |
def atom_present_in_geom(geom, b, tol=DEFAULT_SYM_TOL):
"""Function used by set_full_point_group() to scan a given geometry
and determine if an atom is present at a given location.
"""
for i in range(len(geom)):
a = [geom[i][0], geom[i][1], geom[i][2]]
if distance(b, a) < tol:
... | ad4afd6ca3d419b69ef502d64e3e66635485d340 | 3,654,052 |
import locale
def atof(value):
"""
locale.atof() on unicode string fails in some environments, like Czech.
"""
if isinstance(value, unicode):
value = value.encode("utf-8")
return locale.atof(value) | b0b2d2ea70c5e631ad2a1d25eb5c55d06cbdac1e | 3,654,053 |
def r_group_list(mol, core_mol):
"""
This takes a mol and the common core and finds all the R-groups by
replacing the atoms in the ligand (which make up the common core) with
nothing.
This fragments the ligand and from those fragments we are able to
determine what our R-groups are. for any comm... | 16df0f54a5bf374bd1e77d3443baa42aab2dd231 | 3,654,054 |
def set_execution_target(backend_id='simulator'):
"""
Used to run jobs on a real hardware
:param backend_id: device name. List of available devices depends on the provider
example usage.
set_execution_target(backend_id='arn:aws:braket:::device/quantum-simulator/amazon/sv1')
"""
global dev... | 2efb44723a804e39d998ddc3e7a7c3bdaa0440db | 3,654,055 |
def segregate(str):
"""3.1 Basic code point segregation"""
base = bytearray()
extended = set()
for c in str:
if ord(c) < 128:
base.append(ord(c))
else:
extended.add(c)
extended = sorted(extended)
return bytes(base), extended | e274393735bf4f1d51a75c73351848cbfdd5f81f | 3,654,056 |
def count_tetrasomic_indivs(lis) -> dict:
""" Count number of times that a chromosome is tetrasomic (present in four copies)
:returns counts_of_tetrasomic_chromosomes"""
counts_of_tetrasomic_chromosomes = {k: 0 for k in chr_range}
for kary_group in lis:
for index, chr_type in enumerate(chr_rang... | 598cd10bdbaeea061be0e259de756beba9d248b7 | 3,654,057 |
def make_image_grid(images: np.ndarray, nrow: int = 1) -> np.ndarray:
"""Concatenate multiple images into a single image.
Args:
images (np.array):
Images can be:
- A 4D mini-batch image of shape [B, C, H, W].
- A 3D RGB image of shape [C, H, W].
... | 1b367392c275a44e5c23ce19c96f5727015285f5 | 3,654,058 |
def drive_time_shapes(drive_time):
"""Simplify JSON response into a dictionary of point lists."""
isochrones = {}
try:
for shape in drive_time['response']['isoline']:
uid = str(int(shape['range'] / 60)) + ' minutes'
points = shape['component'][0]['shape']
point... | f8f5074d5326ba598c083fdcc228bdfb69f427a5 | 3,654,059 |
def compute_transformation_sequence_case_1(cumprod, local_shape, ind,
sharded_leg_pos, pgrid):
"""
Helper function for `pravel`, see `pravel` for more details.
"""
ops = []
ndev = np.prod(pgrid)
if ndev % cumprod[ind - 1] != 0:
raise ValueError("reshaping not p... | 0f88967a2fcc132af753a2c5dfbf2a9b8087877a | 3,654,060 |
def fix_join_words(text: str) -> str:
"""
Replace all join ``urdu`` words with separate words
Args:
text (str): raw ``urdu`` text
Returns:
str: returns a ``str`` object containing normalized text.
"""
for key, value in WORDS_SPACE.items():
text = text.replace(key, value... | a13040b420db5b0daf27f3a2f6a1e93a9188c312 | 3,654,061 |
def degree_of_appropriateness(attr_list,data_list,summarizers,summarizer_type,t3,letter_map_list,alpha_sizes,age,activity_level,flag=None,goals=None):
"""
Inputs:
- data: the database
- summarizer: the conclusive phrase of the summary
- summarizer_type: the type of summarizer
- t3: the degree o... | 60e34efcd3ca45471acc53202d243f6e55813179 | 3,654,062 |
import statistics
def constitutive_exp_normalization_raw(gene_db,constitutive_gene_db,array_raw_group_values,exon_db,y,avg_const_exp_db):
"""normalize expression for raw expression data (only for non-baseline data)"""
#avg_true_const_exp_db[affygene] = [avg_const_exp]
temp_avg_const_exp_db={}
for... | 38d5d39cb6a5532b84f08ddd0fbb27335e45897b | 3,654,063 |
def parse_rummager_topics(results):
"""
Parse topics from rummager results
"""
pages = []
for result in results:
pages.append(
Topic(
name=result['title'],
base_path=result['slug'],
document_type=DocumentType[result['format']]
... | d88355014c4a74e1ca7ca2ca1389850cba550612 | 3,654,064 |
def format_last_online(last_online):
"""
Return the upper limit in seconds that a profile may have been
online. If last_online is an int, return that int. Otherwise if
last_online is a str, convert the string into an int.
Returns
----------
int
"""
if isinstance(last_online, str):
... | 335ed9a37062964b785c75246c9f23f678b4a90e | 3,654,065 |
from datetime import datetime
import pkg_resources
import requests
import json
def get_currency_cross_historical_data(currency_cross, from_date, to_date, as_json=False, order='ascending', interval='Daily'):
"""
This function retrieves recent historical data from the introduced `currency_cross` from Investing
... | 6a01f89b128842497e76d0a3497b204ac6641080 | 3,654,066 |
def load_target(target_name, base_dir, cloud=False):
"""load_target load target from local or cloud
Parameters
----------
target_name : str
target name
base_dir : str
project base directory
cloud : bool, optional
load from GCS, by default False
Returns
-------
... | 2ea76be87afdf524b45f26e9f8271ec973e0951a | 3,654,067 |
def gradient(pixmap, ca, cb, eff, ncols):
""" Returns a gradient width the start and end colors.
eff should be Gradient.Vertical or Gradient.Horizontal
"""
x=0
y=0
rca = ca.red()
rDiff = cb.red() - rca
gca = ca.green()
gDiff = cb.green() - gca
bca = ca.blue()... | 63406959617a7192c35e05b8efc81dcedfa7d54a | 3,654,068 |
def option_to_text(option):
"""Converts, for example, 'no_override' to 'no override'."""
return option.replace('_', ' ') | 4b7febe0c4500aa23c368f83bbb18902057dc378 | 3,654,069 |
def login(email, password):
"""
:desc: Logs a user in.
:param: email - Email of the user - required
password - Password of the user - required
:return: `dict`
"""
if email == '' or password == '':
return {'success': False, 'message': 'Email/Password field left blank.'}
... | 3ea350984d2c4206d66136e283b4784e08606352 | 3,654,070 |
def _cons8_89(m8, L88, L89, d_gap, k, Cp, h_gap):
"""dz constrant for edge gap sc touching edge, corner gap sc"""
term1 = 2 * h_gap * L88 / m8 / Cp # conv to inner/outer ducts
term2 = k * d_gap / m8 / Cp / L88 # cond to adj bypass edge
term3 = k * d_gap / m8 / Cp / L89 # cond to adj bypass corner
... | b6e8b6331be394e9a10659029143997b097fae86 | 3,654,071 |
def categories_split(df):
""" Separate the categories in their own columns. """
ohe_categories = pd.DataFrame(df.categories.str.split(';').apply(
lambda x: {e.split('-')[0]: int(e.split('-')[1]) for e in x}).tolist())
return df.join(ohe_categories).drop('categories', axis=1) | 93e6b1dc384162b63fbf5775d168c0e693829f97 | 3,654,072 |
def build_received_request(qparams, variant_id=None, individual_id=None, biosample_id=None):
""""Fills the `receivedRequest` part with the request data"""
request = {
'meta': {
'requestedSchemas' : build_requested_schemas(qparams),
'apiVersion' : qparams.apiVersion,
},
... | bfb0131f3ead563ffd1840119b6f7297a466d4dc | 3,654,073 |
def is_router_bgp_configured_with_four_octet(
device, neighbor_address, vrf, max_time=35, check_interval=10
):
""" Verifies that router bgp has been enabled with four
octet capability and is in the established state
Args:
device('obj'): device to check
vrf('vrf'): vrf to... | 870600a1a5c68d5a4080d8a18966ddc107ae8a72 | 3,654,074 |
import os
import pickle
def validate(i):
"""
Input: {
model_name - model name:
earth
lm
nnet
... | 733de640d864d1484753e459eb3c352201546dd4 | 3,654,075 |
import six
def cluster_absent(
name='localhost',
quiet=None):
"""
Machine is not running as a cluster node
quiet:
execute the command in quiet mode (no output)
"""
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if ... | f19c4c18cd0812ee2f4426a458cfb49e4faba5e0 | 3,654,076 |
def link_symbols_in_code_blocks(path, blocks, symbols):
"""Link symbols appearing a sequence of blocks."""
return [link_symbols_in_code_block(path, block, symbols)
for block in blocks] | 4185e9a1c9b0c8ff2748e80390763b089e9f8831 | 3,654,077 |
def cem_model_factory(
env, network=mlp, network_params={},
input_shape=None,
min_std=1e-6, init_std=1.0, adaptive_std=False,
model_file_path=None, name='cem'):
"""
Model for gradient method
"""
def build_graph(model, network=network,
input_shape=inpu... | e9327a4f3711e19e71cc16658d6e93acba29da47 | 3,654,078 |
def get_job(job_id: UUID) -> Job:
"""
Get job by ID.
Args:
job_id (UUID): ID of the job to be returned.
Returns:
Job
"""
return JobRepository.get_one_by_id(model_id=job_id) | 53e70843ce18e77b17e79bac83ba0225d6087e23 | 3,654,079 |
import os
def set_job_dirs():
"""Sets job directories based on env variables set by Vertex AI."""
model_dir = os.getenv('AIP_MODEL_DIR', LOCAL_MODEL_DIR)
if model_dir[0:5] == 'gs://':
model_dir = model_dir.replace('gs://', '/gcs/')
checkpoint_dir = os.getenv('AIP_CHECKPOINT_DIR', LOCAL_CH... | 93d9a648c7cc89cb5bc316e0e798e8f09ea3c8b9 | 3,654,080 |
import pytz
def localize_datetime(input_df, timezone=DEFAULT_TIMEZONE,
tms_gmt_col=DEFAULT_TMS_GMT_COL):
"""
Convert datetime column from UTC to another timezone.
"""
tmz = pytz.timezone(timezone)
df = input_df.copy()
return (df.set_index(tms_gmt_col)
.tz_lo... | 0d6f8638199f0ccfcf61e025b38dbe84d9eab8ff | 3,654,081 |
import contextlib
import socket
def get_available_port() -> int:
"""Finds and returns an available port on the system."""
with contextlib.closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
sock.bind(('', 0))
_, port = sock.getsockname()
return int(port) | c86de127fb237662052b8ce010e99d271836e1ef | 3,654,082 |
def prettyprint_float(val, digits):
"""Print a floating-point value in a nice way."""
format_string = "%." + f"{digits:d}" + "f"
return (format_string % val).rstrip("0").rstrip(".") | ba62671d9cb8061744fbf1e070e76c31d0ba185d | 3,654,083 |
from typing import Any
from typing import Dict
def year_page(archive_id: str, year: int) -> Any:
"""
Get year page for archive.
Parameters
----------
archive : str
Must be an arXiv archive identifier.
year: int
Must be a two or four digit year.
Returns
-------
dict
... | 9bd609718d782d3cca185929ebacebd0e353bb10 | 3,654,084 |
import scipy
def vert_polyFit2(data, z, bin0, step=1, deg=2):
"""
Trying to use the vertical polynomial fit to clean up the data
not reallly sure about what im doing though
"""
data = np.squeeze(data)
z = np.squeeze(z)
dz = np.nanmean(np.gradient(np.squeeze(z)))
bin1 = int(np.ceil(bi... | ceeeac26b9eba625164a055deb96741c6d99702e | 3,654,085 |
def is_downloadable(url):
"""
Does the url contain a downloadable resource
"""
h = requests.head(url, allow_redirects=True)
header = h.headers
content_type = header.get('content-type')
print content_type
if 'text' in content_type.lower():
return False
if 'html' in content_typ... | 74ccff9d967a3763c852a23d8775970ac9ff9e10 | 3,654,086 |
def dataframe_is_one_query_target_pair(dataframe):
"""
make sure there is only one query sequence and reference sequence in the
given dataframe. Used to check that we aren't aggregating % identity
numbers across bin alignment pairs.
:param dataframe:
:return:
"""
num_query_bins = len(d... | 8a8aba9f4b2eaaca6971bf5c158d043a033d0ec8 | 3,654,087 |
def update_api_key(
self,
name: str,
permission: str,
expiration: int,
active: bool,
key: str = None,
description: str = None,
ip_list: str = None,
) -> bool:
"""Update existing API key on Orchestrator
.. list-table::
:header-rows: 1
* - Swagger Section
... | 9e37062475c3b83ab86c51355442cf6de0df1c34 | 3,654,088 |
def cleanGender(x):
"""
This is a helper funciton that will help cleanup the gender variable.
"""
if x in ['female', 'mostly_female']:
return 'female'
if x in ['male', 'mostly_male']:
return 'male'
if x in ['couple'] :
return 'couple'
else:
return 'unknownGe... | 23d71f2307aa829312f4a1d2a002ae2b55556050 | 3,654,089 |
def get_servers():
"""
Retrieve all the discord servers in the database
:return: List of servers
"""
session = Session()
servers = session.query(Server).all()
return servers | 3953867d18c2e282ee11190a3ee1303126b2394e | 3,654,090 |
def wait_till_postgres_responsive(url):
"""Check if something responds to ``url`` """
engine = sa.create_engine(url)
conn = engine.connect()
conn.close()
return True | 645c98799fa7d0347fc52850b7f3813fec74968c | 3,654,091 |
def get_string_display(attr1, attr2, helper1, helper2, attribute_mode):
"""
get the attribute mode for string
attribute mode can be:
'base', 'full', 'partial', 'masked'
Note that some attribute does not have partial mode, in this case, partial mode will return masked mode
Remeber to call has_par... | fa61332f82310ece349309f378126a4b3179483f | 3,654,092 |
import re
def is_doi(identifier: str) -> bool:
"""Validates if identifier is a valid DOI
Args:
identifier (str): potential doi string
Returns:
bool: true if identifier is a valid DOI
"""
doi_patterns = [
r"(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?![\"&\'])\S)+)",
r"(10.... | 5c0bfe0527adbf53e89d302ee05feb80d285db64 | 3,654,093 |
def meshgrid_flatten(*X):
"""
Functionally same as numpy.meshgrid() with different output
format. Function np.meshgrid() takes n 1d ndarrays of size
N_1,...,N_n, and returns X_1,...,X_n n-dimensional arrays of shape
(N_1, N_2,... N_n). This returns instead a 2d array of shape
(N_1*...*N_n, n).... | a7136a7a4dadb6449fd5079c78f15b13da3721dd | 3,654,094 |
from typing import Union
import copy
def transform_scale(
features,
factor: float,
origin: Union[str, list] = "centroid",
mutate: bool = False,
):
"""
Scale a GeoJSON from a given
point by a factor of scaling
(ex: factor=2 would make the GeoJSON 200% larger).
If a FeatureCollection... | bacc6a365dbed0531d4516a736dd9ca2937b8cad | 3,654,095 |
import importlib
def create_agent(opt):
"""Create an agent from the options model, model_params and model_file.
The input is either of the form "parlai.agents.ir_baseline.agents/IrBaselineAgent"
(i.e. the path followed by the class name) or else just 'IrBaseline' which
assumes the path above, and a cl... | 6f5793ee0af7ed677f47c27ba5b94ad6f80ea957 | 3,654,096 |
def check_version(actver, version, cmp_op):
"""
Check version string of an active module against a required version.
If dev/prerelease tags result in TypeError for string-number comparison,
it is assumed that the dependency is satisfied.
Users on dev branches are responsible for keeping their own p... | 4d2cf92c412659044ad226aeeadb9145ceb75241 | 3,654,097 |
def dfa_intersection(dfa_1: dict, dfa_2: dict) -> dict:
""" Returns a DFA accepting the intersection of the DFAs in
input.
Let :math:`A_1 = (Σ, S_1 , s_{01} , ρ_1 , F_1 )` and
:math:`A_2 = (Σ, S_2 , s_{02} , ρ_2 , F_2 )` be two DFAs.
Then there is a DFA :math:`A_∧` that runs simultaneously both
... | ea69f3cda2bd28f5b70d1724ffdd628daf1beffa | 3,654,098 |
def change_status(request, page_id):
"""
Switch the status of a page.
"""
perm = PagePermission(request.user).check('change', method='POST')
if perm and request.method == 'POST':
page = Page.objects.get(pk=page_id)
page.status = int(request.POST['status'])
page.invalidate()
... | b65775d91c69cf4ac4d5a59d128581011986f1e7 | 3,654,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.