content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def zr_wr_dem(x):
"""
Real Name: b'Zr wr dem'
Original Eqn: b'( [(1,0)-(365,0.04)],(1,0),(2,0),(3,0),(4,0),(5,0),(6,0),(7,0),(8,0),(9,0),(10,0),(11,\\\\ 0),(12,0),(13,0),(14,0),(15,0),(16,0),(17,0),(18,0),(19,0),(20,0),(21,0),(22,0),(23\\\\ ,0),(24,0),(25,0),(26,0),(27,0),(28,0),(29,0),(30,0),(31,0),(32,0),... | 20a4fba212b0b950b75e2c048c063db2840ed949 | 3,607,467 |
def parse_json(data, collection):
""" Calls the appropriate json parser based on the collection,
returns whatever the parser returns, along with the query and
num_responses, which it gets from the json response. If there
are no results, it returns ([], query, 0)"""
# FIRST (only applies to reference... | 7a84729e7d907325a10d469ac720069a633426e5 | 3,607,471 |
def inner_func_float():
"""
Обертка для lambda (двухуровневая, float)
"""
return defaultdict(inner_lambda_float) | 76c8695cfa567dc198af343a75969d65236eab3c | 3,607,472 |
def _reachablerootspure(pfunc, minroot, roots, heads, includepath):
"""See revlog.reachableroots"""
if not roots:
return []
roots = set(roots)
visit = list(heads)
reachable = set()
seen = {}
# prefetch all the things! (because python is slow)
reached = reachable.add
dovisit =... | 08364dd59bab0136e41893d13328e6665269230a | 3,607,473 |
def Go_NoGo(loaded_file, i):
"""
:param loaded_file: file output from operant box
:param i: number of days analyzing
:return: data frame of all analysis extracted from file (one animal)
"""
(timecode, eventcode) = extract_info_from_file(loaded_file, 500)
(dippers, dippers_retrieved, retrieva... | 36d56142ffae3d6b42f18760418c6f069a045f27 | 3,607,474 |
def read_sfmlearn(ego_path, flip):
"""
Right-hand coordinate (following SfMLearn paper).
X: Pitch, Y: Yaw, Z: Roll
"""
ego_dict = {}
with open(ego_path, "r") as f:
for line in f:
strings = line.strip("\r\n").split(",")
key = strings[0]
vx, vy, vz, rx, ... | 38d708334f70c3a2abdf8bc28edd3700b9476498 | 3,607,475 |
def get_links(soup, artist):
"""Get the complete link for each song of the artist"""
links = f'links_{artist}'
links = []
for td in soup.find_all('td'):
if "tal" in td.get('class',[]):
links.append('https://www.lyrics.com'+td.find('a')['href'])
return links | 0587286e3bd15abdee0403745b5fc6d5af81ce5c | 3,607,476 |
def colorize_profit(profit):
"""
Colorize the profit depending on its value.
:param profit: Profit.
:return: console_colored, html_colored
"""
color = {
'html': {
profit <= -10: RED_HTML,
-10 < profit <= 0: YELLOW_HTML,
0 < profit < 10: GREEN_HTML,
... | 886823f7aed0fdd9279b487e2dd7f0dabcaa889a | 3,607,477 |
from typing import BinaryIO
def _read_ft_cfg(file: BinaryIO) -> Metadata:
"""
Constructs metadata from fastText config.
"""
cfg = list(_read_required_binary(file, "<12id"))
losses = ['HierarchicalSoftmax', 'NegativeSampling', 'Softmax']
cfg[6] = losses[cfg[6] - 1]
models = ['CBOW', 'SkipGr... | 8b63714ceb3dd96be5351ea55ba83f93faf1970b | 3,607,478 |
from typing import Callable
def named(name: str) -> Callable[[C], C]:
"""
Change the name of a function to the given name.
"""
def decorator(original):
# type: (C) -> C
original.__name__ = str(name)
original.__qualname__ = str(name)
return original
return decorato... | 44f755872f627f528964669508072a6f37defe91 | 3,607,479 |
def getQuarter(date):
"""Extracts the quarter from a date, ranging from 1-4.
Args:
date (Date): The date to use.
Returns:
int: An integer that is representative of the extracted value.
"""
return ((date.month - 1) // 3) + 1 | 26868a8dc6e4fd9e58daccf44b2357529dfdd1fd | 3,607,480 |
def dup_mul(f, g, K):
"""
Multiply dense polynomials in ``K[x]``.
**Examples**
>>> from sympy.polys.domains import ZZ
>>> from sympy.polys.densearith import dup_mul
>>> f = ZZ.map([1, -2])
>>> g = ZZ.map([1, 2])
>>> dup_mul(f, g, ZZ)
[1, 0, -4]
"""
if f == g:
ret... | f10628d9054b7dae1a303e841ec69ea5684f53c3 | 3,607,481 |
from typing import Type
def norm_param(arr_t):
"""
Returns a transformation that calculates the ``order``-norm
(1 output, 1 input, 1 param): ``output = abs(input) ** order``.
"""
if dtypes.is_complex(arr_t.dtype):
out_dtype = dtypes.real_for(arr_t.dtype)
else:
out_dtype = arr_t... | 376741b651f0d3efa572b3fd14baadc9bfb84cfc | 3,607,482 |
def _get_filenames_glob(variable, drs):
"""Return patterns that can be used to look for input files."""
path_template = _select_drs('input_file', drs, variable['project'])
filenames_glob = _replace_tags(path_template, variable)
return filenames_glob | 13441ed29b7516be09f6855dff10d0f2d19f794e | 3,607,483 |
def _LoadGclientFile(path):
"""Load a gclient file and return the solutions defined by the gclient file.
Args:
path: The gclient file to load.
Returns:
A list of solutions defined by the gclient file or an empty list if no
solutions exists.
"""
global_scope = {}
# Similar to depot_tools, we us... | 0142ad9b4c87eca35c8b1e5fae30c19c5d8d05a5 | 3,607,484 |
def find_closet_match(color, tile_colors):
"""在tile_colors中寻找与颜色color最接近的颜色,返回下标和差异值"""
diff = float('inf')
index = 0
for i, c in enumerate(tile_colors):
d = get_color_diff(color, c)
if d < diff:
diff = d
index = i
return index, diff | d68ead2b8d24114b2f29a77e97c90c93df5a1a64 | 3,607,485 |
from enum import Enum
from typing import Tuple
from typing import Callable
from typing import Any
def load_conf(
conf_type: Enum,
conf_data: Tuple[str, FileConfig] = CONFIGS_DATA,
load_func: Callable[[FileConfig], Any] = dispatcher
):
"""
Универсальный кэшируемый загрузчик конфигураций... | 8a575c85d375af24cde7b2812ea7d271e004d797 | 3,607,486 |
def LicenseFromPath(path):
"""Try to figure out the license for a given path.
Splits path and looks for known license dirs in segments.
Args:
path: A filesystem path, hopefully including a license dir.
Returns:
The name of the license, eg OFL, UFL, etc.
Raises:
ValueError: if 0 or >1 licenses ma... | 89f6fee5f0869640ae51f10fb5298930b6be8d9d | 3,607,487 |
def _get_dyson_purecool_device():
"""Return a valid device as provided by the Dyson web services."""
device = mock.Mock(spec=DysonPureCool)
device.serial = "XX-XXXXX-XX"
device.name = "Living room"
device.connect = mock.Mock(return_value=True)
device.auto_connect = mock.Mock(return_value=True)
... | d4af0ba642bea2fce2bdef222b1b7dfae94b59a0 | 3,607,488 |
def list_quicklinks():
"""
Returns a list of QuickLinks
:return: list<String> list of quick links
"""
quicklinks_list = []
with open(DEFAULT_FILE) as file:
for line in file:
quicklinks_list.append(line.strip())
return quicklinks_list | 5e3ab8d1840e53fd0218e347961b8217c34eafa6 | 3,607,489 |
import hashlib
def hash_seqs(sequences):
"""
Generates hexdigest of Sha1 hash for each sequence in a list of sequences.
This function is useful for generating sequence specific identifiers that allow for easier comparison of features
from multiple sequencing runs or sequence processing runs.
"""... | 35c3291a58ebc7e053250f7234faacd0356f7df5 | 3,607,490 |
def add_myst(original: str) -> str:
"""Change docs/conf.py to use MyST-Parser, enabling md files"""
# add myst_parser extension and its own extensions configuration
content = original.splitlines()
myst = '\n# Enable markdown\nextensions.append("myst_parser")\n'
myst_extensions = template("myst_exten... | 64d13a78b12ff856333a65e42de855bfc3eaf33e | 3,607,491 |
def get_paths(link, nb):
"""
Generate a list containing all URLs
Args:
link [str]: Base HTML link
nb [int]: Number of pages usingHTML link
Returns:
url [str]: [List containing all URLs]
"""
url = []
for si in range(2000, 2020):
for ti in range(1, nb+1):
... | 8fd0a947eeb5435f0df48dc928feb3a10786c2cc | 3,607,492 |
def heaviside(x, bias=0):
"""
Heaviside function Theta(x - bias)
returns 1 if x >= bias else 0
:param x:
:param bias:
:return:
"""
indicator = 1 if x >= bias else 0
return indicator | b325a862cbc2cac97b8e4808c6d77b54a0f1d643 | 3,607,493 |
def register(message_array, device, auto_mode):
"""
Message: register
"""
pwd = pwgen(10, no_symbols=True)
if (device.contributor.status == Contributor.UNKNOWN) or (device.contributor.status == Contributor.INACTIVE):
device.contributor.status = Contributor.ACTIVE
device.contribu... | c4776ad2fe1f953253b0ed6194e89c71f14dc0a8 | 3,607,494 |
def lsubstr(view, point, length=1):
""" Return the character(s) to the left of the point on the same line. """
col = view.rowcol(point)[1]
region = Region(point - min(length, col), point)
return view.substr(region) | 874511493cf71c508984404780751fc4f59c35c6 | 3,607,495 |
def biggest_differences_words(prunedTable):
""" Finds the words that are most different from their most frequent alternative across each semantic dimension
Parameters
----------
prunedTable : a data frame
The data frame representing arousal, valence, and dominance ratings for words and their mo... | 2b39a717fbdf7d823a381ff3320e2ac487f65ec3 | 3,607,496 |
def centos8(function):
"""Decorator to set the Linux distribution to CentOS 8"""
def wrapper(*args, **kwargs):
hpccm.config.g_linux_distro = linux_distro.CENTOS
hpccm.config.g_linux_version = StrictVersion('8.0')
return function(*args, **kwargs)
return wrapper | 4fbdc47e00bff3b8967cfa8ba9c422b4586915de | 3,607,497 |
def stats(state):
"""Return the statistics for given state.
Parameters
----------
state : RunningState
Returns
-------
Stats named tuple
"""
if not state.count:
return Stats(0, 0, 0, 0, 0, 0)
mean = state.sum / state.count
std = (float(state.sum2 - 2.0 * state.sum ... | 731dc9c40db2f459f0bf7419277e9bc4106c2578 | 3,607,498 |
import asyncio
import concurrent
async def get_async_multiprocess():
"""Multi Process"""
loop = asyncio.get_running_loop()
with concurrent.futures.ProcessPoolExecutor() as pool:
task1 = loop.run_in_executor(pool, syncFn1, 1)
task2 = loop.run_in_executor(pool, syncFn2, 2)
res1 = awa... | b1609c2582ff9022bccb15f7d16bb299a991f26a | 3,607,499 |
from typing import Union
from typing import Optional
import sympy
def exponentiate_fermion_operator(
fermion_generator: Union[FermionOperator, InteractionOperator],
transformation: str = "Jordan-Wigner",
number_of_qubits: Optional[int] = None,
) -> Circuit:
"""Create a circuit corresponding to the exp... | a6c4e8203da1d1864dc3ee37a5c7b807b3f33b62 | 3,607,500 |
def mock_stats(
url,
token=None,
version=None):
"""mock_stats
mock stats
:param url: IEX resource url
:param token: optional - string token for your user's
account
:param version: optional - version string
"""
val = {
'url': url,
'version': ... | ef3f5df8f881575131ad4b9fd7a8baed6b6b4840 | 3,607,501 |
def build_help_text(command_class):
"""Generate help text from a command class."""
command = command_class()
parser = command.create_parser({})
return parser.format_help() | 3fc8491e37db2f0b96144ad0b34723ceb71a51ca | 3,607,502 |
import io
def read_names(f):
"""Read names, specified one per line, from a file."""
return (line.strip() for line in io.open(f, 'r', encoding='utf-8')) | 98724005ef5c647aa31205bc8afd07da50ece002 | 3,607,503 |
import numpy
def Sens_m(poly, dist, **kws):
"""
Variance-based decomposition/Sobol' indices.
First order sensitivity indices.
Args:
poly (chaospy.poly.ndpoly):
Polynomial to find first order Sobol indices on.
dist (Dist):
The distributions of the input used in... | 9069d726ad4d34c9ee2653532bf13fc4d2c00450 | 3,607,505 |
import getpass
def user():
"""
Return user (string), taken from environment or prompt
"""
try:
nexpose_user = environ["NEXPOSE_USER"]
except KeyError:
nexpose_user = getpass.getpass(prompt="Nexpose user:")
return nexpose_user | 7d05176b2ec147955ddc32b9c5468d568d9cda48 | 3,607,506 |
import uuid
def convert_uuid_to_es_fmt(uuid_str):
"""Converts uuid to e-series compatible name format."""
uuid_base32 = encode_hex_to_base32(uuid.UUID(str(uuid_str)).hex)
return uuid_base32.strip('=') | b8279f6c783da840326662d99f8e54a4371c1464 | 3,607,507 |
def QT_FROM_RR(rr):
"""
Returns the interval of acceptable QT durations with the given RR
intervals. It applies a linear regression model with the coefficients
obtained from the referenced study.
"""
return Iv(m2s(220) + 0.1 * rr.start, m2s(240) + 0.25 * rr.end) | ddf43e19faec4b95e9fe0f0fee076cfe1de3c830 | 3,607,508 |
import time
def _Retry(func, *args, **kwargs):
"""Retries the function if an exception occurs.
Args:
func: The function to call and retry.
*args: Args to pass to the function.
**kwargs: Kwargs to pass to the function.
Returns:
Whatever the function returns.
"""
retries = _RETRIES
while T... | 0d42e649612e7398e14d9ce4f303ae770efebc1f | 3,607,510 |
def get_astroconda_list(flavor="dev"):
"""return the list of astroconda packages.
Parameters
----------
flavor: string
The sub type of astroconda distribution
"""
if flavor not in ["dev", "contrib"]:
raise ValueError("Only dev and contrib flavors currently exist")
astrocon... | 26be357733ee80fd84f539edc9a93195972f74c6 | 3,607,511 |
import requests
def _get_pypi_versions():
"""List releases available from PyPI."""
response = requests.get(
"https://pypi.org/pypi/faculty-cli/json", timeout=1
)
versions = response.json()["releases"].keys()
return [StrictVersion(v) for v in versions] | 68ed3cdd9aca74673560089686ad7d301b268d01 | 3,607,512 |
import time
def performance(fn):
"""计算性能的修饰器"""
@wraps(fn)
def measurePerformance(*args, **kwargs):
t1 = time.time()
result = fn(*args, **kwargs)
t2 = time.time()
print(f'{fn.__name__}: {t2 - t1: .5f}s')
return result
return measurePerformance | 03f64c9cf472613b35ce288ac1b260d7f055a46b | 3,607,513 |
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the Google Maps trackers."""
domain_data = hass.data[DOMAIN][config_entry.entry_id]
coordinator = domain_data[COORDINATOR]
tracked = set()
max_accuracy = config_entry.options.get(ATTR_GPS_ACCURACY)
@callback
def ... | 487b4b94ef0a9d478f589c357e0e2794c7709935 | 3,607,514 |
def update_fps(fps: int):
"""update_fps."""
logger.info("Updating fps")
logger.info(" fps: %s", fps)
return "ok" | 05a2fe397977c34f3e22e93354eb26b092c29239 | 3,607,515 |
import torch
def max_aggregation_fn(features, index, l):
"""
Arg: features: N x dim
index: N x 1, e.g. [0,0,0,1,1,...l,l]
l: lenght of keypoints
"""
index = index.unsqueeze(-1).expand(-1, features.shape[-1]) # N x 64
set_features = torch.zeros((l, features.shape[-1]), device=features.dev... | d75cb9574bbf3e80826b9d149529eee88949b7b5 | 3,607,516 |
from datetime import datetime
def pretty_date(time=False):
"""
Get a datetime object or a int() Epoch timestamp and return a
pretty string like 'an hour ago', 'Yesterday', '3 months ago',
'just now', etc
"""
now = datetime.utcnow()
diff = now - time
second_diff = diff.seconds
day_d... | f5b449430dae7cf86fa6edb0aae29e5bc7e3efea | 3,607,517 |
def has_data():
"""Check if the PhosphoSite data is available and can be loaded.
Returns
-------
bool
True if the data can be loaded, False otherwise.
"""
global _has_data
if _has_data is None:
try:
_get_phospho_site_dataset()
# If we succeeded withou... | 0097fc4fc07e06244970e3a04ec68e3f52739b17 | 3,607,518 |
def getValue(inpt):
"""reads in an input field and extracts the value of it
Args:
inpt ([type]): html input field
Returns:
str: value of that field
"""
r: str = None
if inpt:
r = inpt.get('value')
return r | 7023ceb6724999b8d892307ac4c9bb822df0bc82 | 3,607,519 |
def format_cols_2digit(df, skip_last_col=True):
"""Formats a dataframes columns so that numbers are always two-digits (padded with 0)
Parameters
----------
df : pandas DataFrame
Input DataFrame.
skip_last_col : bool
A special case, where the very last column contains text, rather th... | 5c9bc98ed6298f8f3d181432320cc69dc4c30ea2 | 3,607,520 |
def parse_probe_chunk(chunk):
"""Prase nmap probe / port strings
"""
result = {'name': '', 'payload': '', 'ports': []}
lines = chunk.splitlines()
for line in lines:
if line.startswith('Probe '):
name, payload = parse_probestr(line)
result['name'] = name
r... | 3767d6d6e8fc4e73d633f632e7a5928e298701e3 | 3,607,521 |
from typing import Optional
from typing import Sequence
import warnings
def build_job_submit_torque(
job_name: str,
script_name: str,
target_system: Optional[TARGET_SYSTEM] = "woody",
nodes: Optional[int] = 1,
ppn: Optional[int] = 4,
walltime: Optional[str] = "24:00:00",
args: Optional[Seq... | b8e0be01c26d0fe007af9a024c4df0d5c606822a | 3,607,522 |
def load_shader(shaderpath, shadername, vertex_format_list=None,
fragment_formatlist=None):
"""Funcion que carga un shader y retorna un objeto del tipo ShaderProgram"""
fragment = Shader(shaderpath + shadername + ".fsh", FRAGMENT, True,
fragment_formatlist)
vertex = Sha... | cad1c71f19e3e964cb642c0957223b78806fafe0 | 3,607,523 |
def pdfgen(mean, sdev, bins_list):
"""
A function to generate 3 probability density function data
Parameters:
mean1 (numpy.ndarray, required): The means of the datasets.
sdev1 (numpy.ndarray,1 required): The standard deviation of
the dataset
bins_list(numpy.ndarray, requi... | dde1d1559f46d95f27e0cc08d91d851fe1825167 | 3,607,524 |
def soup_from_restart_files(basename, skip_solvent=True):
"""
Reads a Soup from the restart files.
"""
for module in [amber, gromacs, namd]:
try:
top, crds, vels = module.get_restart_files(basename)
return module.soup_from_restart_files(
top, crds, vels, skip_solvent)
except util.F... | d859c29268dba5c58734737e987efea4d456f869 | 3,607,525 |
def ec_filter(query_list, hit_list, ec_number):
"""
"""
passed_query = query_list.copy()
for i, query in enumerate(query_list):
anno = hit_list[i]
anno_ec_number = anno.split("|")[0].replace(">EC:", "").split(".")
if len(anno_ec_number) < 3:
passed_query.pop(i)
... | b8b66f19f79dc60cd2d044f4bcfdd46d3a3908b7 | 3,607,526 |
def remove_noisy_channels(data, data_properties, hist_num_buckets=100, hist_max_diff=10):
"""
Removes noisy channels from data.
Parameters
----------
data : NumPy Array
SPM data supplied by the user
data_properties : dict
channel properties of the SPM data
... | 461aa8c069f3f4ef1af99dbc207835eadca5946f | 3,607,527 |
def get_relative_path(root, path):
"""
Return the relative path from root to path, which should be nested under root.
"""
precondition(path.startswith(root), '%s is not under %s' % (path, root))
return path[len(root) :] | 986f2f1a8dd69ae15b4ee41d3bef635d3889dffb | 3,607,528 |
import ast
def clean_data(s):
"""Cleans the main `mag_papers` table.
Args:
s (`sqlalchemy.orm.session.Session`): PostgreSQL connection.
Returns:
mag (pd.DataFrame)
"""
# Read tables
mag = pd.read_sql(s.query(Paper).statement, s.bind)
flag = pd.read_sql(s.query(CoreContro... | cc5b6cfccb1a97076dd31b70469b4f1437bc2011 | 3,607,529 |
def L2_norm(doc_vec):
"""
Renormalize document vector onto the hypersphere.
Args:
doc_vec (numpy array): Document vector
Returns:
doc_vec: Normalized document vector
"""
# Renormalize onto the hypersphere
doc_vec /= np.linalg.norm(doc_vec)
# Sanity check, L2 norm and ... | 994114e04cb8051e42d8525878c54dc182d0a415 | 3,607,531 |
import time
def wait_for_text_not_visible(
driver, text, selector, by=By.CSS_SELECTOR, timeout=settings.LARGE_TIMEOUT
):
"""
Searches for the text in the element of the given selector on the page.
Returns True if the text is not visible on the page within the timeout.
Raises an exception if the te... | 2eb69b48b106e532811cb76dc75d5cb699e6d553 | 3,607,533 |
def reverse_complement_no_loops(seq):
"""Return WC complement of a base without loops"""
# Initialize rev_seq to a lowercase seq
rev_seq = seq.lower()
# Substitute bases
rev_seq = rev_seq.replace('t','A')
rev_seq = rev_seq.replace('a','T')
rev_seq = rev_seq.replace('g','C')
rev_seq = rev... | 2a94d38827cbda95272776b0bea652af9d30b64d | 3,607,535 |
def edit_assignment_group(request_ctx, course_id, assignment_group_id, **request_kwargs):
"""
Modify an existing Assignment Group.
Accepts the same parameters as Assignment Group creation
:param request_ctx: The request context
:type request_ctx: :class:RequestContext
:param course_... | 635b07a5e230a446e6ce698c1b14ee4b0c87d085 | 3,607,536 |
import time
def RunInteractive(filter_text, modified_base, modified_client):
"""Runs interactive mode when presubmit is run as a standalone application.
This will run all files in the ontology as if they were new.
Args:
filter_text: command line arguments. The only available argument is
'match:<valu... | 3c0584d951d46827eebf124cfd23af508c616ebb | 3,607,537 |
from typing import Callable
def simplex_integral(
f: Callable, num_classes: int, boundary_offset=1e-10, coord_sum: float = 1, **kwargs
):
"""
Performs an integral over num_classes-1 dimensional simplex using scipy
:param f: function to integrate over the simplex. Should accept num_classes-1 variables... | 278cc82976178617784e980c30a853b136cb0689 | 3,607,538 |
from collections import OrderedDict
def update(data_df, cal_dict, param, bound, start, end):
"""Update calibration times for give parameter and boundary"""
if param not in cal_dict["parameters"]:
cal_dict["parameters"][param] = OrderedDict()
if bound not in cal_dict["parameters"][param]:
... | f8c63a528ad6533938f215179c17bd236eefeb67 | 3,607,539 |
import json
def addRemoteFriend():
"""
Processing POST method from local for adding friend on the server side
:return: Code 200 if ok
"""
method = request.method
if(method == "POST" and checkPassword(request, app.admin_password)):
j = json.loads(request.json)
username = j['user... | ef023de0ba4347b82ae0336915b2c9ec30acefd9 | 3,607,540 |
def manage_simple_models(request, operation, model):
"""
A unified handler function for all simple models
Parameters
----------
request :
operation : str
Currently supported operations: create, delete
model : str
Currently supported models:
Returns
-------
"""
... | 4737ae1d377bcd292beae56497609f13856d5076 | 3,607,541 |
import itertools
def euler131(lim=1000000):
"""Solution for problem 131."""
# m^3 = n^3 + p*n^2 = n*n*(n+p)
# 1) Proof that this is equivalent to n and (n+p) being perfect cube
# Let m = prod(pi^ei) be the prime decomposition of m
# n = prod(pi^fi) n
#... | 77036cb8d55a5ce14ba23ca5a6f90382672e5c1f | 3,607,542 |
def viaCombusta(obj):
""" Returns if an object is in the Via Combusta. """
return 195 < obj.lon < 225 | 531ab5b5725bf3ed6dc8c8ff99c3980b3533e558 | 3,607,543 |
from typing import Set
from typing import Callable
def route(
path_pattern: str,
http_methods: Set[str],
) -> Callable[..., Callable]:
"""
Register a decorated method so that it can be recognized as a route.
Args:
path_pattern: The end part of a URL pattern. E.g. `/targets` or
... | 2a24f717f7539afe90c1818f37cc4ceeb162ef04 | 3,607,544 |
def label_name(condition):
"""format label name
"""
label = condition.replace("_", " ").split(".")
label[0] = label[0].capitalize()
return " ".join(label) | 06ea2caf9bb881aa016ef3f74999fe376d30cb05 | 3,607,545 |
import numbers
def reshape(tensor, dims_list):
"""Reshape the given tensor by collapsing dimensions."""
shape = get_shape(tensor)
dims_prod = []
for dims in dims_list:
if isinstance(dims, numbers.Number):
dims_prod.append(shape[dims])
elif all([isinstance(shape[d], int) for... | fe228e50a7eb829129bb12434018eedaa51deb87 | 3,607,546 |
def lp(dic, data, pred="default", x1="default", xn="default", ord=8, mode='f',
append='after', bad_roots='auto', mirror=None, fix_mode='on',
method='tls'):
"""
Linear Prediction
Parameters
----------
dic : dict
Dictionary of NMRPipe parameters.
data : ndarray
Array... | ef5454d0fe7e9e53cd8a2da68399998f9208ceda | 3,607,547 |
def query(query_string, database=config.DEFAULT_DB):
"""
Execute a query given by param and return True/False and result.
result is a list of tuples with the query output info
"""
status = True
try:
conn = psycopg2.connect(user=config.USERNAME, \
password=config.PAS... | 269b3e38de5fe7b9c5697ffea2b48a85cfe4e596 | 3,607,548 |
def copresence(acc, w1, w2):
"""Results 1 if a pair of figures is on stage at the same time, and 0
otherwise."""
return int(acc + w1 + w2 > 0) | 3056b25df4a59bc421a3aec3d33e25db8ccb98bd | 3,607,549 |
def qratio(value_unit_1, value_unit_2, unit=None ):
"""
Return a quantity value for ``value_unit_1/value_unit_2``.
If the signature of the associated units are in simplified form,
signature information is retained in the quotient.
When ``unit`` is None, the reference unit is used.
Example ::
... | b60903481b8456a507356153344539ac8dfcc524 | 3,607,550 |
def key_line(cfgmap, key):
"""Get the line number of `key` in `cfgmap`."""
if not hasattr(cfgmap, "key2line"):
key2line = {}
for cfgkey in cfgmap:
key2line[cfgkey] = getattr(cfgkey, "line", -1)
cfgmap.key2line = key2line
return cfgmap.key2line.get(key, -1) | 94649a30f949e868610426642699e9ac43b644be | 3,607,551 |
from dit.utils import is_string_like
def log_func(b):
"""
Returns a base-`b` logarithm function.
Parameters
----------
b : positive float or 'e'
The base of the desired logarithm function.
Returns
-------
log : function
The base-`b` logarithm function. The returned fu... | 15083b0a5d51984647b42ff52799a22550148c08 | 3,607,552 |
def get_lad_list(lads, oa_points):
"""
Get a list of the local authority districts for which we have data for.
"""
oa_points = gpd.overlay(oa_points, lads, how='intersection')
lad_list = oa_points['name'].to_list()
return oa_points, lad_list | e7488b4b0f2a697e67d6708cbd0474dae091efa6 | 3,607,553 |
def _dict_from_labels(labels, separator='='):
"""Create a multidict from label string."""
return MultiDict(((label[0].strip(), label[1].strip()
if len(label) > 1 else None)
for label in (raw.split(separator, 1)
for raw in labels))) | a0614ca8867a8eeb211bfcd31e4c2cfc649515bb | 3,607,554 |
import logging
import torch
import operator
def build_hoi_train_loader(cfg, mapper=None):
"""
A data loader is created by the following steps:
1. Use the dataset names in config to query :class:`DatasetCatalog`, and obtain a list of dicts.
2. Start workers to work on the dicts. Each worker will:
... | 5234707be8d4e8f3eb2badbbae9fe3b9088179c5 | 3,607,555 |
def unf_rsb_Mccain_m3m3(rsp_m3m3, gamma_oil, psp_MPaa=0, tsp_K=0):
"""
Solution Gas-oil ratio at bubble point pressure calculation according to McCain (2002) correlation
taking into account the gas losses at separator and stock tank
ref1 "Reservoir oil bubblepoint pressures revisited; solution gas... | ab4296b7f22af15a8422a3cf0a23826b3ae9f7c7 | 3,607,556 |
def decode_token(request):
"""
Global function that ensures that will be used to decode the token
"""
token = request.headers.get('Authorization')
if token is None:
abort(401, message="No token provided")
try:
payload = jwt.decode(token, Config.SECRET_KEY)
except jwt.De... | 0ae42591c618cb4ba80024d41f0d45780be66d5e | 3,607,557 |
def gen_bool_parse(val):
"""Convert a string, as a human might type it, to a boolean. Unrecognized
values raise an exception.
"""
val = val.strip()
if not val:
return False
try:
return bool(int(val))
except:
pass
ch = val[0]
if ch in {'t', 'T', 'y', 'Y'}:
... | 3c1944c7633f329848569c6cb29af11e145dfa5c | 3,607,558 |
def baremetal_adapter(name, active, section):
"""Config adapter for "baremetal"."""
if not is_full_section(section):
return active
if name == 'MBEDTLS_NO_PLATFORM_ENTROPY':
return True
return include_in_full(name) and keep_in_baremetal(name) | 1db45112caa1031b51973c38ae3e2ef5e68927ac | 3,607,559 |
import glob
def _expand_glob_path(file_roots):
"""
Applies shell globbing to a set of directories and returns
the expanded paths
"""
unglobbed_path = []
for path in file_roots:
try:
if glob.has_magic(path):
unglobbed_path.extend(glob.glob(path))
... | f765e3063f098d2bf185df619783b428b192b37a | 3,607,562 |
def read_memory_stats(target_file):
"""Reads and parses memory stats."""
target_file.readline()
test_line = target_file.readline()
if "MEMORY" in test_line:
target_string = target_file.readline()
warnings = ""
if target_string.find("WARNING") != -1:
warnings = target_... | a1fafc3d5f5d307e01d2252404a8e4ab8f73cfbf | 3,607,563 |
def read_ply(ply_fn):
"""
Read ply file
:param ply_fn: str
:return:
vertices: N x 3, numpy.ndarray(float)
faces: M x 3, numpy.ndarray(int)
"""
vertices, faces, n_vertices, n_faces = [], [], 0, 0
header_end = False
with open(ply_fn, 'r') as fin_ply:
# Read header
line = fin_p... | 4e2edaed2c20971ea839b96787bf520e83af97b6 | 3,607,564 |
def crop(image: np.ndarray, x: float, y: float, w: float, h: float,
relative: bool = False, loc: Loc = Loc.UPPER_LEFT) -> np.ndarray:
"""Crop an image using an (x,y) point, width, and height.
Args:
image (np.ndarray): Image to be cropped.
x (float): x coordinate of the point (relative ... | 24c33fffde01396965bd9f73f653ba0e86bcbf84 | 3,607,565 |
def stiffnessMatrixFromPot(Epot,u_dof):
""" Return stiffness matrices from an experssion of potential energy and a list of DOF"""
n=len(u_dof)
Ke= zeros(n,n)
for i in range(n):
for j in range(n):
Ke[i,j] = Epot.diff(u_dof[j]).diff(u_dof[i])
return Ke | 40c80daeaa9b059f7648990b55c08d26734a6f86 | 3,607,566 |
def stations_level_over_threshold(stations, tol):
"""Returns a list of tuples, where each contains the name of a station at which the relative
water level is above tol and the relative water level at that station"""
flooded_stations = []
for station in stations:
relative_level = station.relati... | 5c8a7562415e4a3c05f509bc4d922c775368d202 | 3,607,567 |
import collections
def _build_nightly_dict(
registered_ds: FullNamesDict,
stable_version_ds: FullNamesDict,
) -> NightlyDict:
"""Computes the nightly dict from the registered and stable dict."""
nightly_ds = collections.defaultdict(
lambda: collections.defaultdict( # pylint: disable=g-long-lambda
... | 366ca503bfd62c021769ac8c4b366b9c30bb8eaf | 3,607,568 |
def process_results(sources_list):
"""Function that process the results list and transforms them into a list of objects
Args: sources_list: A list of dictionaries that contains news sources details
Returns:
sources_results: a list of news sources objects"""
sources_results = []
for source_item ... | ea3fcd616412a8b0b8c9b03ed36779f81dd3908a | 3,607,569 |
import torch
def get_box_info(boxes):
"""
input: [batch_size, (x1,y1,x2,y2)]
output: [batch_size, (x1,y1,x2,y2,cx,cy,w,h)]
"""
return torch.cat((boxes / float(IM_SCALE), center_size(boxes) / float(IM_SCALE)), 1) | b5a76f66b08390447b2c49fbfa3350ce5ee66aa7 | 3,607,571 |
def add_index_levels(to, source, fill=""):
"""Add levels to the "to" index so it has all levels in the "source" index. The possible levels are, in this order: "Name", "Site", "Peptide", "Database_ID"
Parameters:
to (pandas.Index or pandas.MultiIndex): The index to add levels to.
source (pandas.Index or... | 42a4f6b58759e106aa28ca4cea7002b25070cf3a | 3,607,572 |
def browser_images(request):
"""display image browser"""
images = []
for full_model_name in settings.image_models():
app_name, model_name = full_model_name.split('.')
model = get_model(app_name, model_name)
if model:
images.extend(model.objects.all())
return render(... | 10adc32b1a50d148310cdf50ac457cd89eead9fe | 3,607,573 |
def cov(X, p):
"""vector autocovariance up to order p
Parameters
----------
X : ndarray, shape (N, n)
The N time series of length n
Returns
-------
R : ndarray, shape (p + 1, N, N)
The autocovariance up to order p
"""
N, n = X.shape
R = np.zeros((p + 1, N, N))
... | a6f8d1fa310e7070653fed013af880a66071bcd0 | 3,607,574 |
import torch
def get_test_loader(transform=None):
"""
Args:
transform (transform): Albumentations transform
Returns:
testloader: DataLoader Object
"""
if transform:
testset = Cifar10SearchDataset(transform=transform, train=False)
else:
testset = Cifar10SearchDataset(train=False)
test... | 28d21160a82a7b1c48822b00875df7dad5f34fe8 | 3,607,575 |
def _is_container_terminated(client, resource_group_name, name, container_name):
"""Check if a container should be considered terminated. """
container_group, container = _find_container(client, resource_group_name, name, container_name)
# If a container group is terminated, assume the container is also te... | 42ceb828397a130fd5a53333faf8cee5875826c0 | 3,607,576 |
def getW(D, K, Mu = 0.5):
"""
Return affinity matrix
[1] Wang, Bo, et al. "Similarity network fusion for aggregating data types on a genomic scale."
Nature methods 11.3 (2014): 333-337.
:param D: Self-similarity matrix
:param K: Number of nearest neighbors
"""
#W(i, j) = exp(-Dij^2/... | 8b8c5bb81acaf9a428a22654677f9ad3ebb5486b | 3,607,577 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.