content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def random_string(length=-1, charset=string.ascii_letters):
"""
Returns a random string of "length" characters.
If no length is specified, resulting string is in between 6 and 15 characters.
A character set can be specified, defaulting to just alpha letters.
"""
if length == -1: length = random.... | 58,500 |
def save_textfile(text, path, mode='w'):
"""Saves text in file path with mode 'w'-write or 'a'-append"""
logger.debug('save file %s' % path)
f=open(path, mode)
f.write(text)
f.close() | 58,501 |
def rho_NFW(r, rs, rhos):
"""
The density profile [GeV/cm**3] of an NFW halo.
Parameters
----------
r : the distance from the center [kpc]
rs : the NFW r_s parameter [kpc]
rhos : the NFW rho_s parameter [GeV/cm**3]
"""
res = rhos/(r/rs)/(1.+r/rs)**2
return res | 58,502 |
def markVisibilityOfSignals(ctx, ctxName, signals, interfaceSignals):
"""
* check if all signals are driven by something
* mark signals with hidden = False if they are connecting statements
or if they are external interface
"""
for sig in signals:
driver_cnt = len(sig.drivers)
... | 58,503 |
def get_jasper(version,
use_dw=False,
use_dr=False,
bn_eps=1e-3,
vocabulary=None,
model_name=None,
pretrained=False,
root=os.path.join("~", ".tensorflow", "models"),
**kwargs):
"""
Create Jasp... | 58,504 |
def _load_local_auth():
"""Returns a LocalAuthParameters tuple from LUCI_CONTEXT.
Returns:
LocalAuthParameters for connecting to a local auth server.
Raises:
BadLuciContextParameters if file is missing or not valid.
"""
data = luci_context.read('local_auth')
if data is None:
raise BadLuciConte... | 58,505 |
def start_to_process_pending_gazettes():
"""
Setup objects necessary to extract text from the gazettes and call the
tasks function to extract the text
"""
enable_debug_if_necessary()
database = create_database_interface()
storage = create_storage_interface()
index = create_index_interfac... | 58,506 |
def ifequal(parser, token):
"""
Output the contents of the block if the two arguments equal each other.
Examples::
{% ifequal user.id comment.user_id %}
...
{% endifequal %}
{% ifnotequal user.id comment.user_id %}
...
{% else %}
...
... | 58,507 |
def ssim(x: np.ndarray, y: np.ndarray) -> float:
"""Calculate the structural similarity metric (SSIM) between images.
Note:
This function requires skimage.
"""
from skimage.metrics import structural_similarity
assert x.dtype == y.dtype
return structural_similarity(x, y, channel_axis=2... | 58,508 |
def get_config_data(request):
"""
Sends form configuration data to the frontend.
This allows clientside validation to mirror serverside validation.
"""
return JsonResponse({
"nameMaxLength": settings.CONTACTFORM_NAME_MAX_LENGTH,
"organizationMaxLength": settings.CONTACTFORM_ORGANIZA... | 58,509 |
def read(fileObj, securityTrader=None, _flowType=None):
"""
读取 excel 文件,并返回
:param fileObj: 已经打开的 file 文件实例,限制 file 实例是为了可以不依赖磁盘文件,直接使用内存
:param securityTrader: 对应的券商
:param _flowType:
:return:
"""
flowing = Flowing.open(fileObj, securityTrader)
return flowing | 58,510 |
def get_saml_assertion(response):
"""Parses a requests.Response object that contains a SAML assertion.
Returns an base64 encoded SAML Assertion if one is found"""
# Decode the requests.Response object and extract the SAML assertion
soup = BeautifulSoup(response.text, "html.parser")
# Look for the SAM... | 58,511 |
def test_gt_cmd(vim_bot):
"""Test gt, gT command."""
_, editor_stack, editor, vim, qtbot = vim_bot
assert 0 == editor_stack.get_stack_index()
cmd_line = vim.get_focus_widget()
qtbot.keyClicks(cmd_line, 'gt')
assert 1 == editor_stack.get_stack_index()
cmd_line = vim.get_focus_widget()
... | 58,512 |
def delete_data_source(
name: Optional[str] = None,
data_source_id: Optional[str] = None,
account_id: Optional[str] = None,
boto3_session: Optional[boto3.Session] = None,
) -> None:
"""Delete a data source.
Note
----
You must pass a not None ``name`` or ``data_source_id`` argument.
... | 58,513 |
def register_for_init_call(m):
"""
Decorator that tags a method to be called at the end of processing cmds.
NOTE: This decorator MUST BE the outermost decorator used on a method
decorated with multiple decorators! The custom user attributes
of a method aren't preserved in python 2.7 even... | 58,514 |
def breakup_names(df):
"""Breakup full name into surname, title, first name"""
df[['surname','given_name']] = df['Name'].str.split(",", expand= True)
df[['title', 'first_name']] = df['given_name'].str.split(n=1, expand= True)
df = df.drop(columns=['Name', 'given_name'])
return df | 58,515 |
def get_arguments_info(parser):
"""
Read help message into variable by putting the stdout output from
parser.print_help() into a custom sdtout.
Parameters
==========
parser [argparse.ArgumentParser]
Returns
=======
arguments_info [dict]: arguments_info[variable_name] =
... | 58,516 |
def main():
"""This is a sample entry point, but you should generally not call it.
Instead, subclass Hub in a separate file and write a similar main function
there."""
arguments = docopt(__doc__)
inbound = parse_host_and_port(arguments["--inbound"])
outbound = parse_host_and_port(arguments["--o... | 58,517 |
def parse_args(argv):
"""Returns a tuple of (opts, args) for arguments."""
parser = make_parser()
args = parser.parse_args(argv[1:])
sdk = args.sdk
# Use APPENGINEPY_SDK_VERSION if set.
if not sdk and (sdk_version_key in os.environ):
sdk = (os.environ[sdk_version_key],)
return args... | 58,518 |
def cat(dir, file_name=None, input=None):
""" act like unix 'cat' - put string into file (or echo data out """
ret_val = None
# step 1: figure out the file path
if dir:
if file_name:
file_path = os.path.join(dir, file_name)
else:
file_path = dir
# step 2... | 58,519 |
def get_state_change_with_balance_proof(
storage: sqlite.SQLiteStorage,
chain_id: typing.ChainID,
token_network_identifier: typing.TokenNetworkID,
channel_identifier: typing.ChannelID,
balance_hash: typing.BalanceHash,
sender: typing.Address,
) -> sqlite.StateChangeRecord... | 58,520 |
def main():
"""
Training.
"""
# Initialize model and optimizer
model = tiny_detector(n_classes=n_classes)
criterion = MultiBoxLoss(priors_cxcy=model.priors_cxcy)
optimizer = torch.optim.SGD(params=model.parameters(),
lr=lr, momentum=momentum, weight_decay=weig... | 58,521 |
def best_down_collapse(X,kX,dimq,signal):
"""Returns the down-collapse V which minimize the topological reconstructione error ||s-phi*_Vpsi*_V(s)|^2
"""
s=np.array(signal)**2
Bq=kX[dimq]
BT=Bq.copy()
C=BT.tolil()
ind=C.rows
possible_min_WQ=[]
possible_min_value=[]
for Q in ran... | 58,522 |
def evaluate_lambda_t(t, phi_start, linear, phase0):
"""
Evaluates firing rate(t, x) = tuning_curve(x) * theta_modulation(t, x) at given time points
:param t: sample time points
:param phi_start: starting point of the place field (in rad)
:param linear: flag for circular vs. linear track -> slightly... | 58,523 |
def _mapc(ctx, input_files, resource_info):
"""Creates actions that compile a Core Data mapping model files.
Each file should be contained inside a .xcmappingmodel directory.
Args:
ctx: The Skylark context.
input_files: An iterable of files in all mapping models that should be
compil... | 58,524 |
def image_content_type(outfile: Path) -> str:
""" Derives a content type from an image file's suffix """
return f"image/{outfile.suffix[1:]}" | 58,525 |
def test_dct2_simple():
"""Tests the 1D version of the dct2."""
time_domain = [1, 1, 1, 1]
expected = scipy.fftpack.dct(time_domain)
actual = dct2(time_domain)
numpy.testing.assert_array_almost_equal(actual, expected) | 58,526 |
def make_contribution_subsystems_plots(model_fn, random_samples_fn, sep = "\t", key = "pathway", absolute_values = False):
"""
Used for data QC. Plots histogram to see which reactions that have the largest contribution to each pathway
"""
model = cobra.io.read_sbml_model(model_fn)
df = get_random_sa... | 58,527 |
def play_again() -> str:
"""Ask the user if he wants to play another turn"""
yes_or_no = input('Play again? [y/n]: ')
while yes_or_no not in ['y', 'n']:
yes_or_no = input('Please insert "y" or "n": ')
return yes_or_no | 58,528 |
def create_session (user, is_trusted):
"""
Perform user authentication User.password and role activations.
This method must be called once per user prior to calling other methods within this module.
The successful result is Session that contains target user's RBAC User.roles.
This API will...
... | 58,529 |
def ansi_wrap(value: str, width: int = 80, left_pad: int = 6) -> str:
"""Wrap characers relative to their cell width."""
decoded_text = decode_ansi(value)
wrapped_text = "\n".join(_wrap_ansi(decoded_text, width=width, left_pad=left_pad))
return wrapped_text | 58,530 |
def hashcolumns(dframe, columns, maxval):
""" Hash each value of multiple dataframe columns. """
columnvals = list(zip(*(dframe[col] for col in columns)))
return list(hashval(v, maxval) for v in columnvals) | 58,531 |
def random_triangles(n=3):
""" Draw n triangles which can overlap """
coords = []
for i in range(n*3):
coords.append([random.random()*5, random.random()*5,random.random()*5])
coords = np.array(coords)
faces = []
for i in range(n):
faces.append([i*3, i*3+1, i*3+2])
faces = ... | 58,532 |
def get_config():
"""Get the default hyperparameter configuration."""
config = ml_collections.ConfigDict()
config.problem = "classification"
config.env_model = "MLP"
config.agent = "KalmanFilter"
config.seed = 0
config.nsteps = 20
config.ntrials = 20
config.train_batch_size = 1
... | 58,533 |
def online_providers(provider: str = None):
"""
Check if the provider can be reached, or any provider if none is specified.
Parameters
----------
provider : str, optional
Only try to yield the specified provider.
Yields
------
provider
Provider instances
"""
for... | 58,534 |
def extras_require() -> t.Dict[str, t.List[str]]:
"""
Parse requirements in requirements/extras directory
"""
extra_requirements = {}
for extra in extras:
extra_requirements[extra] = parse_requirement(
os.path.join("extras", extra + ".txt")
)
extra_requirements["all"... | 58,535 |
def make_vbox(model_dict: dict) -> widgets.VBox:
"""
:param model_dict:
:return:
"""
labels = []
for k in model_dict:
if type(model_dict[k]) is not dict:
string = str(model_dict[k])
labels.append(make_setting_hbox(k, string))
else:
mini_labels... | 58,536 |
def UserTypingFilter(cli):
"""Determine if the input field is empty."""
return (cli.current_buffer.document.text and
cli.current_buffer.document.text != cli.config.context) | 58,537 |
def setSipStackTimers(stack,props):
"""SET timer values on the SIP Stack object of a server
Arg props should be a dictionary.
For example, { 'timerT4': '3333' }"""
m = "setSipStackTimers:"
sop(m,"Entry. %s,%s" % (stack,props))
# Get the Timers owned by the SIP Stack
timers = getObjectsOfTyp... | 58,538 |
def create_myst_config(
settings: frontend.Values,
excluded: Sequence[str],
config_cls=MdParserConfig,
prefix: str = "myst_",
):
"""Create a configuration instance from the given settings."""
values = {}
for attribute in config_cls.get_fields():
if attribute.name in excluded:
... | 58,539 |
def test_shst_deformation():
"""Test of shearing and stretching deformation calculation for basic case."""
a = np.arange(3)
u = np.c_[a, a, a] * units('m/s')
with pytest.warns(MetpyDeprecationWarning):
sh, st = shearing_stretching_deformation(u, u, 1 * units.meter, 1 * units.meter,
... | 58,540 |
def updatePrimesFount(p: tuple, nBits: int):
"""
Update prime number's fount (or create one with one element if not exist) and add given tuple if not present in stocked ones.
"""
name = f"{str(nBits)}_bits"
if not isFileHere(name + ".txt", c.DIRECTORY_FOUNT):
print("\nData not existing, cre... | 58,541 |
def cube_K(shape, rms, data, peaks=[0, 1, 2, 3], origin=(0, 0),
header=None, writeto=None, **kwargs):
"""
Construct a fits HDU with ln(K) values for all xy positions in a
cube of a given shape. Optionally, writes a fits file.
Additional keyword args are passed to lnK_xy function.
"""
... | 58,542 |
def scale_image(image, new_width=600):
"""
scales the image to new_width while maintaining aspect ratio
"""
new_w = new_width
(old_w, old_h) = image.size
aspect_ratio = float(old_h)/float(old_w)
new_h = int(aspect_ratio * new_w)
new_dim = (new_w, new_h)
image = image.resize(new_dim)
... | 58,543 |
def get_container_metadata(item):
"""Extract desired metadata from Docker container object."""
if type(item) is str:
return item
tags = getattr(item, 'tags', None)
if tags is not None:
return tags[0]
else:
return str(item) | 58,544 |
def presentation_defaults():
"""For importing into presentation.
Typical figure is 11" wide and 7" tall. No scaling should be necessary.
Typically presentation figures have more whitespace and fewer panels
than manuscript figures.
Actually I think the font size should not be below 18, unle... | 58,545 |
def init(params={}):
"""
Initialize PyGemstones and it internal modules.
After initialize it set pygemstones.system.settings.initialized as true
Arguments:
params : dict
Returns:
None
"""
if s.initialized:
return
colorama.init()
s.initialized = True | 58,546 |
def leaky_relu(alpha=0.1, name='LeakyReLU', collect=False):
"""Modified version of ReLU, introducing a nonzero gradient for negative input.
Args:
alpha: `int`, the multiplier.
name: operation name.
collect: whether to collect this metric under the metric collection.
"""
def _le... | 58,547 |
def show_sample_attributes(request):
"""
show the user-defined sample attribute home page
"""
ctxd = {}
ctx = RequestContext(request, ctxd)
return render_to_response(
"rundb/sample/sampleattributes.html", context_instance=ctx, mimetype="text/html"
) | 58,548 |
def make_identity_dict(rng):
""" make_identity_dict(rng) -> dict
Return a dictionary where elements of the rng sequence are
mapped to themselves.
"""
zwróć {i:i dla i w rng} | 58,549 |
def get_pks(constraints):
"""Get primary key(s) given constraint list"""
pks = {}
if constraints:
for name, constraint in constraints.items():
if constraint['type'] == PRIMARY and len(constraint['columns']) == 1:
column = constraint['columns'][0]
pks[colu... | 58,550 |
def _invoke_function(function_name, json_args, json_kwargs):
"""Invokes callback with given function_name.
This function is meant to be used by frontend when proxying
data from secure iframe into kernel. For example:
_invoke_function(fn_name, "'''" + JSON.stringify(data) + "'''")
Note the trip... | 58,551 |
def set_object_metadata(data_file, metadata):
"""
Sets the swift metadata to the specified data_file
:param data_file: full path of the data file
"""
fd = open_data_file(data_file)
write_metadata(fd, metadata, md_key=SWIFT_METADATA_KEY)
close_data_file(fd) | 58,552 |
def test_molecule_center_calculation_of_benzene():
"""Tests molecule center for benzene"""
benzene = Molecule(read=benzene_xyz)
benzene_com = benzene.get_center() # Center of mass
benzene_cog = benzene.get_center(mass=False) # Geometric center
assert np.allclose(get_molecule_center(b... | 58,553 |
def main():
"""The main program is written here"""
args = get_args() # assign the get_args() function to args variable
dob = (2020 - args.age) # get the user's date of birth
age_group = str() # create a variable that will hold the user's age group
year = 'years' # define a year string
... | 58,554 |
def single_particle_first2p_zbt_metafit(fitfn, exp_list, **kwargs):
"""Fit to zero body terms for all available normal-ordering schemes,
taking only the first 2 points from each
"""
return single_particle_metafit_int(
fitfn, exp_list,
dpath_sources=DPATH_FILES_INT, dpath_plots=DPATH_PLOT... | 58,555 |
def interact_GxG(pheno,snps1,snps2=None,K=None,covs=None):
"""
Epistasis test between two sets of SNPs
Args:
pheno: [N x 1] SP.array of 1 phenotype for N individuals
snps1: [N x S1] SP.array of S1 SNPs for N individuals
snps2: [N x S2] SP.array of S2 SNPs for N individuals
... | 58,556 |
def _get_clone_readiness(media, dtype):
"""
Checks the given media for clones and determines their readiness for archiving.
"""
if dtype == "image":
return _get_single_clone_readiness(media, "image")
if dtype == "video":
return _get_single_clone_readiness(media, "archival")
if dt... | 58,557 |
def bot_is_public():
"""Don't use this elsewhere."""
async def bot_public(ctx: SalamanderContext) -> bool:
assert isinstance(ctx.cog, Meta), "safe enough" # nosec
cog: Meta = ctx.cog
info = await cog.cached_info.get_app_info()
return info.bot_public or await ctx.bot.is_owner(ct... | 58,558 |
def objmap_streamfunc_uvh(xd, yd, ud, vd, hd, xm, ym, l, SNR, fcor, g=9.81, return_err=False):
"""Map velocity and height observations to non-divergent geostrophic stream function.
The Coriolis parameter fcor and gravity (or reduced gravity) g should be specified."""
xd = np.asarray(xd).ravel()
yd = np.... | 58,559 |
def visualize_game_round_count():
"""
Prints round count of a game.
:return: html code
"""
return html.Span('Rounds: {0}'.format(len(pre.round_names)), style={'padding': '5px', 'fontSize': '16px'}) | 58,560 |
def test_agraph_constructor_bad_input():
"""AGraph constructor does not support edge lists."""
with pytest.raises(TypeError, match="Unrecognized input"):
pgv.AGraph([(0, 1), (1, 2)]) | 58,561 |
def get_window_icon(hwnd):
"""Return QPixmap."""
#hicon = win32gui.GetClassLong(hwnd, win32con.GCL_HICON)
hicon = get_hicon(hwnd)
if not valid_handle(hicon):
return None
try:
return make_qicon(hicon)
except:
return None
#info = win32gui.GetIconInfo(hicon)
#try:
... | 58,562 |
def ec_entity(response):
"""
Return URL or File entity in Demisto format for use in entry
context depending on data in 'response' (the report)
Parameters
----------
response : dict
Object returned by ANYRUN API call in 'get_report' function.
Returns
-------
dict
Fil... | 58,563 |
def generate_map(df: pd.DataFrame):
""""
Generates the map for the dashboard
Parameters
----------
df : pandas dataframe
The dataframe that contains the data to plot.
Returns
-------
chart : html of altair Chart
The generated map converted to html
"""
world_map ... | 58,564 |
def mapped_route_add(request):
"""
Страница конструктора, которая позволит задавать последовательность остановок,
Далее, открыть карту и построить промежуточные маршруты,
Подтвердить и исходранить маршрут в БД.
:param request:
:return: Template of constructor
"""
template_name = 'admin_... | 58,565 |
def test_set(tmpdir):
"""
Verify setting works as expected.
"""
m = meta.GenericBuildMeta(_create_test_files(tmpdir), '1.2.3')
m.set('test', 'changed')
m.write()
assert m.get('test') == 'changed'
m.set(['a', 'b'], 'z')
m.write()
assert m.get(['a', 'b']) == 'z'
assert m['a']['... | 58,566 |
def percentage(sub, all):
"""Calculate percent relation between "sub" and "all".
Args:
sub (int): Some value.
all (int): Maximum value.
Returns:
int: (sum * 100) / all
"""
return int((sub * 100) / all) | 58,567 |
def symbolicTz(z = 0):
"""
Translation on «z» axis. Returns Dual Quaternion in matrix form
"""
return Matrix([[1],
[0],
[0],
[0],
[0],
[0],
[0],
[0.5 * z]]) | 58,568 |
def get_branch_all(git_dir):
""" Return all branch names).
"""
try:
output = git('-C', git_dir, 'branch', '--all')
except ErrorReturnCode as e:
return failed_util_call_results(e)
else:
return succeeded_util_call_results(output) | 58,569 |
def _databases(is_refresh: bool, current_path: str, session: ObjectExplorerSession, match_params: dict) -> List[NodeInfo]:
"""Function to generate a list of databases"""
_default_node_generator(is_refresh, current_path, session, match_params)
is_system = 'systemdatabase' in current_path
return [_get_nod... | 58,570 |
def get_run_runtime(dataset_id, vm_id, run_id):
""" loads a runtime file (runtime.txt) and parses the string to return time, runtime_info"""
run_dir = (RUNS_DIR_PATH / dataset_id / vm_id / run_id)
if not (run_dir / "runtime.txt").exists():
return None
runtime = open(run_dir / "runtime.txt", 'r'... | 58,571 |
def metrics(bb1, bb2):
"""Computes metrics between two boxes"""
i1, j1, w1, h1 = to_tlwh(bb1)
i2, j2, w2, h2 = to_tlwh(bb2)
top = max(i1, i2)
bottom = min(i1 + h1, i2 + h2)
left = max(j1, j2)
right = min(j1 + w1, j2 + w2)
overlap_height = bottom - top
overlap_width = right - left
... | 58,572 |
def main():
"""Main function for getting connection to database and running test"""
args, _ = AGP_RDS_GENERATE.parse_known_args()
connection = get_connection_dict(args)
db = DB_DICT[args.run_option](connection)
db.run_test(args.source) | 58,573 |
def web_tokenizer(sentence):
"""
The web tokenizer works like the :func:`word_tokenizer`, but does not split URIs or
e-mail addresses. It also un-escapes all escape sequences (except in URIs or email addresses).
"""
return [token for i, span in enumerate(web_tokenizer.split(sentence))
fo... | 58,574 |
def _check_directory_files_permission(block_id, block_dict, extra_args=None):
"""
Check all files permission inside a directory
"""
path = runner_utils.get_param_for_module(block_id, block_dict, 'path')
permission = runner_utils.get_param_for_module(block_id, block_dict, 'permission')
blacklist... | 58,575 |
def async_parse_date_datetime(
value: str, entity_id: str, device_class: SensorDeviceClass | str | None
) -> datetime | date | None:
"""Parse datetime string to a data or datetime."""
if device_class == SensorDeviceClass.TIMESTAMP:
if (parsed_timestamp := dt_util.parse_datetime(value)) is None:
... | 58,576 |
def region_of_interest(img, vertices):
"""
Applies an image mask.
Only keeps the region of the image defined by the polygon
formed from `vertices`. The rest of the image is set to black.
"""
#defining a blank mask to start with
mask = np.zeros_like(img)
#defining a 3 channel... | 58,577 |
async def app_factory() -> web.Application:
"""Created to launch app from gunicorn (see docker/boot.sh)"""
app_settings = ApplicationSettings()
assert app_settings.SC_BUILD_TARGET # nosec
log.info("Application settings: %s", app_settings.json(indent=2, sort_keys=True))
app, _ = _setup_app_from_se... | 58,578 |
def test_ieee8021x_wep40(dev, apdev):
"""IEEE 802.1X connection using dynamic WEP40"""
skip_with_fips(dev[0])
params = hostapd.radius_params()
params["ssid"] = "ieee8021x-wep"
params["ieee8021x"] = "1"
params["wep_key_len_broadcast"] = "5"
params["wep_key_len_unicast"] = "5"
hapd = hosta... | 58,579 |
def makeone(pb, params, where, compdir=None):
"""
Crée une donnée pour l'apprentissage du problème "Le jardinier et les
taupes" :
1. Génère une instance du problème dans la version du module `pb`,
pour les paramètres `params`.
2. Résout cette instance.
3. Sauvegarde la gri... | 58,580 |
def _collapse_to_cwl_record(samples, want_attrs):
"""Convert nested samples from batches into a CWL record, based on input keys.
"""
input_keys = sorted(list(set().union(*[d["cwl_keys"] for d in samples])), key=lambda x: (-len(x), tuple(x)))
out = {}
for key in input_keys:
if key in want_att... | 58,581 |
def extract_Card():
"""
读取流量业务,并存为数据库
:return: 返回知识表 dict list
"""
conn = sqlite3.connect("CMCC_NewDB.db")
cur = conn.cursor()
# create table
exec_create_command = "CREATE TABLE Card("
for slot in Card_DB_slots:
if slot in ["功能费"]:
exec_create_command +... | 58,582 |
def open_old_stds(name, type, dbif=None):
"""This function opens an existing space time dataset and return the
created and initialized object of the specified type.
This function will call exit() or raise a
grass.pygrass.messages.FatalError in case the type is wrong,
or the space time d... | 58,583 |
def describe_response(
status: typing.Union[int, HTTPStatus],
description: str = "",
*,
content: typing.Union[typing.Type[BaseModel], type, dict] = None,
headers: dict = None,
links: dict = None,
) -> typing.Callable[[T], T]:
"""
describe a response in HTTP view function
https://git... | 58,584 |
def report_exception(f):
""" Minimal decorator for reporting exceptions that occur within a
function. Does not support generators."""
@wraps(f)
def wrapped_f(*args, **kwargs):
try:
return f(*args, **kwargs)
except:
sentry_sdk.capture_exception()
raise
... | 58,585 |
def default_cleanup() -> None:
"""Default function to clean up the session"""
pass | 58,586 |
def from_manifest(
manifest_path: str,
data_cache_name: str = "task_data",
logger: logging.Logger = logging.getLogger(__name__),
) -> Environment:
"""Load an environment object from a schema definition on disk."""
env = Environment()
# load the manifest
if not env.load_manifest_with_cache(... | 58,587 |
def write_notebook_output(notebook, output_dir, notebook_name):
"""Extract output from notebook cells and write to files in output_dir.
This also modifies 'notebook' in-place, adding metadata to each cell that
maps output mime-types to the filenames the output was saved under.
"""
resources = dict(... | 58,588 |
def thread_worker(
function: Optional[Callable] = None,
start_thread: Optional[bool] = None,
connect: Optional[Dict[str, Union[Callable, Sequence[Callable]]]] = None,
progress: Optional[Union[bool, Dict[str, Union[int, bool, str]]]] = None,
worker_class: Union[
Type[FunctionWorker], Type[Gen... | 58,589 |
def uncorr_noise_deprojection_bias(f1, map_var):
"""
Computes the bias associated to contaminant removal in the presence of uncorrelated inhomogeneous noise to the auto-pseudo-Cl of a given field f1.
:param NmtField f1: fields to correlate
:param map_cls_guess: array containing a HEALPix map correspond... | 58,590 |
def _log_err_to_es(msg, err=None):
"""Log an indexing error in an elasticsearch index."""
# The key is a hash of the message data body
# The index document is the error string plus the message data itself
_id = hashlib.blake2b(json.dumps(msg).encode('utf-8')).hexdigest()
es_indexer._write_to_elastic... | 58,591 |
def convert_expression(lst_tkn:list):
"""
Parameters:
-----------
* lst_tkn [list]: list containing the raw tokens.
Return:
-------
* lst_res [list]: NPI tokens list obtained by shunting-yeard algorithm.
"""
lst_tkn = natural_conversion(lst_tkn)
lst_res = shunting_yard_al... | 58,592 |
def share(files, dbpool):
"""Sets the share value of the files to 1 in the database
:param files: list of absolute file paths
:param dbool: twisted.enterprise.adbapi.ConnectionPool object
"""
for f in files:
yield dbpool.runQuery('update indexer set share=1 where filename=?', (f,))
defer... | 58,593 |
def main():
"""Runs compare_versions (see utilities.compare_versions) on a Stringdb
object
This runs the compare_versions function on a Stringdb object to find the
version information of the source and determine if a fetch is needed. The
version information is also printed.
Returns:
di... | 58,594 |
def value(colors: list):
"""
Each resistor has a resistance value.
Manufacturers print color-coded bands onto
the resistors to denote their resistance values.
Each band acts as a digit of a number.
The program will take two colors as input,
and output the correct number.
:param colors:
... | 58,595 |
def intersect_curve_surface(curve, surface, itol=None):
"""
Find the intersection points of a curve and a surface.
:param curve: Curve to intersect.
:type curve: :class:`.BezierCurve` or :class:`.NurbsCurve`
:param surface: Surface to intersect.
:type surface: :class:`.BezierSurface` or :class:... | 58,596 |
def get_test_batch(data, batch_size=100, stim_history=30, min_window=10):
"""Get a batch of training data."""
stim = data['stimulus']
resp = data['responses']
ei_mag = data['ei_magnitude']
stim_batch = np.zeros((batch_size, stim.shape[1],
stim.shape[2], stim_history))
resp_batch =... | 58,597 |
def rgb_to_hex(r, g, b):
"""
Generate a html hex color string from r,g,b values
:params r,g,b: (0,1) range floats
:return: a html compatible hex color string
"""
assert is_valid_rgb(r, g, b), "Error, r,g,b must be (0,1) range floats"
R,G,B = rgb_to_RGB(r,g,b)
return "#{:02x}{:02x}{:... | 58,598 |
def load_transforms(name):
"""Load data transformations.
Note:
- Gaussian Blur is defined at the bottom of this file.
"""
_name = name.lower()
if _name == "cifar_sup":
normalize = transforms.Normalize([0.4914, 0.4822, 0.4465], [0.2023, 0.1994, 0.2010])
aug_transform... | 58,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.