content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def sigmoid(t):
"""
apply the sigmoid function on t.
Output:
- 1/(1+exp(-t))
"""
return 1 / (1 + np.exp(-t)) | 63,600 |
def get_reservation(location: Optional[str] = None,
project: Optional[str] = None,
reservation_id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetReservationResult:
"""
Returns information about the reservation.
"... | 63,601 |
def checksession(request):
"""
@params:
request, django请求实例
@function:
判断是否已经登录
"""
if not settings.LOGIN_KEY in request.session:
raise http.ErrorResp(err_code.NO_LOGIN)
return err_code.OK | 63,602 |
def test_discard_timerange():
"""Schedule.discard(TimeRange) -> None"""
schedule = Schedule([
TimeRange(Time(1000), Time(2000))
])
schedule.discard(TimeRange(Time(1000), Time(1200)))
assert schedule == Schedule([
TimeRange(Time(1200), Time(2000))
])
schedule = Schedule([
... | 63,603 |
def try_dbfield(fn, field_class):
"""
Try ``fn`` with the DB ``field_class`` by walking its
MRO until a result is found.
ex::
_try_dbfield(field_dict.get, models.CharField)
"""
# walk the mro, as field_class could be a derived model field.
for cls in field_class.mro():
# sk... | 63,604 |
def _get_year_month_range(year, month, quantity):
"""Return several year/month pairs from a given start."""
yield year, month
for _ in range(quantity - 1):
year, month = _increment_year_month(year, month)
yield year, month | 63,605 |
def missing_tag_translations(request, tag_id):
"""Returns a JSON object hash of languages for which there are no
translations for this Tag."""
tag = get_object_or_404(Tag, id=tag_id)
data = {}
langs = [tag.site.default_language, ]
for lang in tag.site.alternate_language.all():
langs.appe... | 63,606 |
def from_yaml(file):
"""Load configuration from YAML file with include constructor.
To include another file use "!include filename".
Examples:
.. code-block::
# file: bar.yaml
- 3.6
- [1, 2, 3]
# file: foo.yaml
a: 1
b:
... | 63,607 |
def listResources(request):
""" Generates an HTML page listing all resources. """
resources = models.Resources.objects.all().order_by('resource_name')
#
return render(request, "list_resources.html",
{'resources' : resources}) | 63,608 |
def list_s3(bucket, prefix, ext):
"""Get listing of files on S3 with prefix and extension
"""
counter = 0
for key in _list_s3(bucket, prefix, ext):
counter += 1
if counter % 5000 == 0:
print(f'Found {counter} items so far', file=sys.stderr)
print(key) | 63,609 |
def ceil(x: float) -> int:
"""
Return the ceiling of ``x`` as a float, the smallest integer
value greater than or equal to ``x``.
"""
... | 63,610 |
def publish_as_gist_file(ctx, path, name="index"):
"""Publish a gist.
More information on gists at http://gist.github.com/.
"""
github_config = get_github_config(ctx, allow_anonymous=False)
user = github_config._github.get_user()
with open(path, "r") as fh:
content = fh.read()
conte... | 63,611 |
def parse(text: str):
"""Parse the DSL contained in text."""
if not text.strip():
return example_default()
has_index_collision = False
has_index_order_mismatch = False
info_queue, some_axis_maps = [], []
axis_values_rows_req_string: str = unsafe(text)
axis_values_rows_req = [row.st... | 63,612 |
def read_diff_file(data_path: str, otu_id: str, otu_version: Union[int, str]) -> dict:
"""
Read a history diff file from disk.
:param data_path: the application data path
:param otu_id: the change's OTU ID
:param otu_version: the change's OTU version
:return: the diff
"""
path = virtoo... | 63,613 |
def create_app(config):
"""Docstring for create_app method."""
app = Flask(__name__, instance_relative_config=True)
app.config.from_object(app_config[config])
jwt = JWTManager(app)
app.register_blueprint(version_2)
create_tables()
return app | 63,614 |
def importers():
"""List triple importers."""
for prefix, f in sorted(PREFIX_IMPORTERS.items()):
click.secho(f'prefix: {prefix} from {inspect.getmodule(f).__name__}')
for suffix, f in sorted(EXTENSION_IMPORTERS.items()):
click.secho(f'suffix: {suffix} from {inspect.getmodule(f).__name__}') | 63,615 |
def load(*args ,**kwargs):
"""
This function attempts to determine the base data type of a filename or
other set of arguments by calling
:meth:`yt.data_objects.api.Dataset._is_valid` until it finds a
match, at which point it returns an instance of the appropriate
:class:`yt.data_objects.api.Data... | 63,616 |
def generate_color_swatches(
output_folder='data/color_swatches',
output_csv='color_dataset.csv',
select_colors=['blue', 'green'],
swatch_size=(100, 100)
):
"""
Generate synthetic color swatches based on a mapping between complex color names, simple color names, and RGB values.
Parameters
... | 63,617 |
def get_index_of_tone_vowel(syllable):
"""
Returns the index of the vowel that should be marked with a tone accent in a given syllable.
The tone marks are assigned with the following priority:
- A and E first
- O is accented in OU
- otherwise, the *final* vowel
Returns -1 if no vowels fou... | 63,618 |
def IterateQueue(queue_head, element_ptr_type, element_field_name, backwards=False, unpack_ptr_fn=None):
""" Iterate over an Element Chain queue in kernel of type queue_head_t. (osfmk/kern/queue.h method 2)
params:
queue_head - value : Value object for queue_head.
element_ptr... | 63,619 |
def mediaGenerator(request):
"""Randomly picks an content file from the requested database.
`request`: selects prefered database
"""
folder = 'content/' + request
mediaPaths = glob(folder + '/*')
return random.choice(mediaPaths) | 63,620 |
def run_experiment(data: Dict):
""" Run CMAXENT with gapminder data.
"""
## Gapminder experiments with GDP, HDI, F, LE
# gapminder = ConditionalMAXENT(x=data["y"]+data["x"],
# moment_dict=data["moment_constraints"],
# probability_x... | 63,621 |
def returnMeans(means_particle, stds_particle, sizes_particle, ax, col='blue', particle_name=""):
"""
Helper for multiMeans(). Plots the energy bin means for individual particles in subplots.
:parameter means_particle: array containing the means of the energy bins for a particle.
:type means_particle: n... | 63,622 |
def filter_factory(global_conf, **local_conf):
"""Returns a WSGI filter app for use with paste.deploy."""
conf = global_conf.copy()
conf.update(local_conf)
def auth_filter(app):
return FederatedAuthentication(app, conf)
return auth_filter | 63,623 |
def contrast_luvoir_num(coro_floor, norm, design, matrix_dir, rms=1*u.nm):
"""
Compute the contrast for a random segmented mirror misalignment on the LUVOIR simulator.
:param coro_floor: float, coronagraph contrast floor
:param norm: float, normalization factor for PSFs: peak of unaberrated direct PSF
... | 63,624 |
def create(document_dir):
"""
creates an inverted index given an English text corpus
for movies. If the directory provided does not exist,
the program will print an error. If the filenames
in the test corpus do not match with the description,
the program will print an error and will skip the
... | 63,625 |
def get_drive_info(action, drive) -> any:
"""
This allows us to query specific information about our drives including
temperatures, smart assessments, and space available to use for plots.
It allows us to simply hand it a drive number (drive0, drive22, etc)
and will present us with the data back. Th... | 63,626 |
def pathlib_parts():
"""将路径根据路径分隔符分隔,得到一个元组"""
path = pathlib.WindowsPath(r"D:\lcoderfit\fuck")
part_list = path.parts
print(part_list)
"""
('D:\\', 'lcoderfit', 'fuck')
""" | 63,627 |
def filter_violations(violations: List[Violation],
exclude_categories: List[str],
exclude_severities: List[int]) -> List[Violation]:
"""
Filter violations according to rules specified by the user.
:param violations: all violations
:param exclude_categories: ca... | 63,628 |
def notary_info(request):
"""get notary details"""
name = request.POST.get('name')
if not name:
return format_return(13000)
msg_code, msg_data = interface.get_notary_info(name=name.strip(''))
return format_return(msg_code, data=msg_data) | 63,629 |
def reject_on_exception(func):
"""
Decorator on actor callback functions that handles exceptions by
sending it to caller as promise rejections. The function should have
an argument called ``callback``.
"""
arg_names = getargspec(func).args
callback_pos = None
if arg_names:
for id... | 63,630 |
def get_mock_discovery(host_list, invalid_interface=False, invalid_key=False):
"""Return a mock gateway info instance."""
gateway_discovery = Mock()
gateway_dict = {}
for host in host_list:
gateway = Mock()
gateway.ip_adress = host
gateway.port = TEST_PORT
gateway.sid =... | 63,631 |
def run():
"""
Runs ORIG and APP tests.
"""
# create test suite
ts = unittest.TestSuite()
ts.addTest(orig.suite)
ts.addTest(app.client.suite)
ts.addTest(app.server.suite)
# kill children if parent fails
os.setpgrp()
# run
runner = unittest.TextTestRunner(verbosity=2)
... | 63,632 |
def cache(path):
"""
Method for setting options during request session.
Example:
>>> from faux import requests
>>> requests.cache('/path/to/local/cache')
>>> requests.get('http://localhost')
"""
global CACHE
if not path:
raise AssertionError('Invalid path specifi... | 63,633 |
def partition(key, nr_partitions, params):
"""
Returns an integer in ``range(0, nr_partitions)``.
:param key: is a key object emitted by a task function
:param nr_partitions: the number of partitions
:param params: the object specified by the *params* parameter
""" | 63,634 |
def test_proxied_syntax_error():
"""The logcapture plugin formats errors by extracting and converting
the value to a string. Nose recreates a proxy exception lacking
filename and lineno attributes, crashing the shortcut formatting
"""
string_error = ''.join([
"invalid syntax (package.py, lin... | 63,635 |
def pytest_unconfigure(config: PyTestConfig):
"""
Configuration hook which calls the global teardown function.
"""
helpers.teardown()
Log.info("Pytest unconfiguration hook finished successfully")
# An explicit "kill" of current process to ensure clean exit in case of errors when stopping the co... | 63,636 |
def get_raw_text(xml_tree_element):
""" get raw text with xml encodings a string """
text = ET.tostring(xml_tree_element)
return text | 63,637 |
def rankingMinPath(matrix,seeds,levels):
"""
errado, analisar
"""
chosen = np.full(matrix.shape[0], np.inf)
height_vector = np.zeros(matrix.shape[0],dtype=int)
parent = np.full(matrix.shape[0], np.inf)
fila = []
for s in seeds:
fila.append(s)
height_vector[s] = 0
parent[s]=-1
chosen[s] = 0
print(fil... | 63,638 |
def register_run_config(name):
"""Registers a run configuration class."""
basecls = BaseConfig
registry = RUN_CONFIG_REGISTRY
reg_func = partial(_register, name=name, basecls=basecls, registry=registry)
return reg_func | 63,639 |
def batch_iter(data, batch_size, num_epochs, shuffle=True):
"""
Generates a batch iterator for a dataset
:param data:
:param batch_size:
:param num_epochs:
:param shuffle:
:return:
"""
data = np.array(data)
data_size = len(data)
num_batches_per_epoch = int((len(data) - 1) / b... | 63,640 |
def test_confluence_helper_deactivate_user():
"""Test ConfluenceHelper deactivate_user
"""
with requests_mock.mock() as mock_adapter:
helper = ConfluenceHelper(TEST_AUTH_USER, TEST_AUTH_PASS, TEST_SERVER, test_logger)
# First call should return 204
mock_adapter.post(DEFS.post_deacti... | 63,641 |
def statement_block(evaluator, ast, state):
"""Evaluates statement block "{ ... }"."""
state.new_local_scope()
for decl in ast["decls"]:
evaluator.eval_ast(decl, state)
for stmt in ast["stmts"]:
res, do_return = evaluator.eval_ast(stmt, state)
if do_return:
state.remo... | 63,642 |
def _create_query_dict(query_text):
"""
Create a dictionary with query key:value definitions
query_text is a comma delimited key:value sequence
"""
query_dict = dict()
if query_text:
for arg_value_str in query_text.split(','):
if ':' in arg_value_str:
... | 63,643 |
def nan_gaussian_filter(T, fwhm, mode="constant", cval=0, preserve_nan=True, **kwargs):
"""default parameters mimic
convolve(x,kernels.Gaussian2DKernel(fwhm),preserve_nan=True,boundary='fill',fill_value=np.nan)
fill_value = np.nan basically continues the interpolation beyond the boundary
"""
V = T.c... | 63,644 |
def _getVersionString(value):
"""Encodes string for version information string tables.
Arguments:
value - string to encode
Returns:
bytes - value encoded as utf-16le
"""
return value.encode("utf-16le") | 63,645 |
def crop_image(input_image, image_extent, bbox, output_image):
"""Crop an image by a bounding box.
bbox and image_extent format: (xmin, ymin, xmax, ymax)
:param input_image: Array containing the data or path to an image
:param image_extent: The geographic extent of the image
:param output_image: The imag... | 63,646 |
def test_itruediv_special_cases_two_args_less__equal_2(arg1, arg2):
"""
Special case test for `__itruediv__(self, other, /)`:
- If `x1_i` is less than `0` and `x2_i` is `-0`, the result is `+infinity`.
"""
res = asarray(arg1, copy=True)
itruediv(res, arg2)
mask = logical_and(less(arg... | 63,647 |
def _reload_feast():
"""After changing environment need to reload modules and rerun usage decorators"""
modules = (
"feast.infra.local",
"feast.infra.online_stores.sqlite",
"feast.feature_store",
)
for mod in modules:
if mod in sys.modules:
reload(sys.modules[... | 63,648 |
def h_n(n, z):
""" Spherical Hankel function of order n
Parameters
----------
n : numpy.array(M,N)
Order of the function
z : numpy.array(M,N)
Function argument
Returns
-------
yn(z) : numpy.array(M,N)
Function value
"... | 63,649 |
def get_org_projects_info(org_link):
"""Get organisation's projects information
:param org_link: Valid link to the organisation's info page of a specific year
:type org_link: str
:returns: A list of dictionaries of each project's title, descrition and link of project
:rtype: list
"""
respon... | 63,650 |
def get_shift_of_one_to_one_match(matches: List[List[bool]]) -> Optional[int]:
"""
Matches is an n x n matrix representing a directed bipartite graph.
Item i is connected to item j if matches[i][j] = True
We try to find a shift k such that each item i is matched to an item j + shift
usecase:
f... | 63,651 |
def parse_zebet(url=""):
"""
Retourne les cotes disponibles sur zebet
"""
if not url:
url = "https://www.zebet.fr/fr/competition/96-ligue_1_conforama"
if "/sport/" in url:
return parse_sport_zebet(url)
try:
soup = BeautifulSoup(urllib.request.urlopen(url), features="lxml"... | 63,652 |
def cambia_curso_publico(id_curso: Union[None, str, int] = None):
"""Cambia el estatus publico de un curso."""
CURSO = Curso.query.filter_by(codigo=id_curso).first()
if CURSO.publico:
CURSO.publico = False
else:
CURSO.publico = True
database.session.commit() | 63,653 |
def background(f):
"""
Call a function in a simple thread, to prevent blocking
Taken from the Jupyter Qtconsole project
"""
t = Thread(target=f)
t.start()
return t | 63,654 |
def calculate_entropy_batch_mixing(
adata: ad.AnnData,
use_rep: str = "delta",
batch_col: str = "batch_indices",
n_neighbors: int = 50,
n_pools: int = 50,
n_samples_per_pool: int = 100,
random_state: int = 0,
n_jobs: Union[None, int] = None,
calc_knn: bool = True
) -> float:
"""C... | 63,655 |
def get_leap_seconds(truncate=True):
"""
Gets a list of GPS times for when leap seconds occurred
Keyword arguments
-----------------
truncate: Reduce list of leap seconds to positive GPS times
Returns
-------
GPS time (seconds since 1980-01-06T00:00:00) of leap seconds
"""
leap... | 63,656 |
def serialize(obj: Any) -> str:
"""
Serializes object into a string JSON
DEPRECATED use json_encoder.to_json directly
:param obj: object to serialize
:return: JSON string
"""
return json.dumps(obj, cls=EnhancedJSONEncoder) | 63,657 |
def save_point_cloud(pcd, rgb, filename, binary=True):
"""Save an RGB point cloud as a PLY file.
:paras
@pcd: Nx3 matrix, the XYZ coordinates
@rgb: NX3 matrix, the rgb colors for each 3D point
"""
assert pcd.shape[0] == rgb.shape[0]
if rgb is None:
gray_concat = np.tile(np.arra... | 63,658 |
def block2dict(block: list, kind: str = None, sequence: int = -1) -> dict:
"""Takes a text block from a SerialEM .nav file and converts it into a
dictionary."""
patt_split = re.compile(r'\s?=\s?')
d = {}
for item in block:
key, value = re.split(patt_split, item)
try:
if... | 63,659 |
def plurality(l):
"""
Take the most common label from all labels with the same rev_id.
"""
s = l.groupby(l.index).apply(lambda x:x.value_counts().index[0])
s.name = 'y'
return s | 63,660 |
def trace_using(logger):
"""Decorator factory to trace callables.
Args:
logger: The logger to use for tracing
Returns:
The decorator, which takes a function and decorates it.
"""
def real_decorator(func):
"""Decorate a callable to report args, kwargs and return."""
... | 63,661 |
def test_parse_multiline_prompts() -> None:
"""It parses a string with two prompt characters.
This also checks for alternate prompt characters.
"""
types, tokens = tokenize("# first line\n~ second line")
assert len(tokens) == len(types) == 6
assert types == [Generic.Prompt, Text, Text, Generic... | 63,662 |
def lowpass_filter(data: FLOATS_TYPE,
sampling_freq_hz: float,
cutoff_freq_hz: float,
numtaps: int) -> FLOATS_TYPE:
"""
Apply a low-pass filter to the data.
Args:
data: time series of the data
sampling_freq_hz: sampling frequency :mat... | 63,663 |
def uncollect_if_test_explainer(**kwargs):
"""
This function is used to skip combinations of explainers
and classifiers that do not make sense. This is achieved
by using the hooks in conftest.py. Such functions should
be passed to the @pytest.mark.uncollect_if decorator as
the func argument. The... | 63,664 |
def cli(ctx, **kwargs):
"""Runs a Github Action Workflow.
ACTION : The action to execute from a workflow.
By default, Popper searches for a workflow in .github/main.workflow
or main.workflow and executes it if found.
$ popper run
When an action name is passed as argument, the specified ac... | 63,665 |
def trimAndStandardizeMates(target_seq_ID, bam_lines, references, reference_lengths, primer_seqs):
"""1) Trim reads upstream of primer sequence(s), relative to primer sequences(s)
2) Relabel reads <umi_5p>_<umi_3p>
"""
aux_info = None
reject_reason, mate1, mate2 = processBamLinesForTarget(target_... | 63,666 |
def ensure_traefik_credentials(path: pathlib.Path):
"""
Ensure we have persistent username / password creds for traefik.
We want this to be as stable as possible, and not change each
time this script is run. So we write it to a separate file with
a version string, and re-generate it only if that ve... | 63,667 |
def electric_field(relative_permittivity, relative_permeability, frequency, current, length, r, theta):
"""
Calculate the electric far field for the Hertzian dipole.
:param relative_permittivity: The relative permittivity.
:param relative_permeability: The relative permeability.
:param frequency: Th... | 63,668 |
def get_messages_per_week(msgs):
"""Gets lists of messages for each calendar week between the first and the last message.
Args:
msgs (list of Mymessage objects): Messages.
Returns:
A dictionary such as:
{
week (datetime.date): list of messages within this week
... | 63,669 |
def _handle_text_outputs(snippet: dict, results: str) -> dict:
"""
Parse the results string as a text blob into a single variable.
- name: system_info
path: /api/?type=op&cmd=<show><system><info></info></system></show>&key={{ api_key }}
output_type: text
outputs:
- name: system_in... | 63,670 |
def run_app(cls_or_app):
"""Entrance method used to start the App. It runs, or instantiates and runs
a :class:`MoreKivyApp` type instance.
"""
from kivy.core.window import Window
handler = _MoreKivyAppHandler()
ExceptionManager.add_handler(handler)
app = cls_or_app() if inspect.isclass(cls_... | 63,671 |
def delete_lambdas(cleaner):
"""
Deletes all lambda functions from the client. It will construct a list of resources, delete them, then wait for
each deletion.
:param cleaner: A Cleaner object from the main cleanup.py script
:return: None
"""
print('\n\nlooking for lambda functions starting ... | 63,672 |
def make_uuid():
"""generate uuids even on Python 2.4 which has no 'uuid'"""
return _uuids.pop(0) | 63,673 |
def _to_iso_format(traintime: datetime) -> str:
"""Return isoformatted utc time."""
return dt.as_utc(traintime).isoformat() | 63,674 |
def parse_timestamp(datetime_repr: str) -> datetime:
"""Construct a datetime object from a string."""
return datetime.strptime(datetime_repr, '%b %d %Y %I:%M%p') | 63,675 |
def proxy_request(request, **kwargs):
""" generic view to proxy a request.
Args:
destination: string, the proxied url
prefix: string, the prrefix behind we proxy the path
headers: dict, custom HTTP headers
no_redirect: boolean, False by default, do not redirect to "/"
... | 63,676 |
def process_subscription(subscription):
"""Process subscription tasks."""
cycle = cycle_manager.get(
filter_data={
"subscription_id": str(subscription["_id"]),
"active": True,
}
)
tasks = list(
filter(
lambda x: x["scheduled_date"].timestamp() ... | 63,677 |
async def test_clan(client: AsyncClient, mocker: MockerFixture):
"""This tests all function in the file, because link_clan() needs to be called first"""
mocker.patch("Backend.networking.http.NetworkBase._request", mock_request)
# =====================================================================
# ... | 63,678 |
def image_stabilisation_proj(
image: xpArray, axis: int = 0, projection_type: str = "max-min", **kwargs
) -> SequenceRegistrationModel:
"""
Computes a sequence stabilisation model for an image sequence indexed along a specified axis.
Instead of running a full nD registration, this uses projections inste... | 63,679 |
def _check_bgp4(aggregator, common_tags):
"""
Shared testing function for profiles supporting BGP4 metrics.
"""
tags = ['neighbor:244.12.239.177'] + common_tags
for metric in PEER_GAUGES:
aggregator.assert_metric('snmp.{}'.format(metric), metric_type=aggregator.GAUGE, tags=tags)
for met... | 63,680 |
def get_LOR_colors(LOR_list, min_max=(-2, 2)):
"""Use Log Odds Ratios list to create color map for allele columns
"""
cmap = cm.coolwarm
if min_max!=False:
norm = Normalize(vmin=min_max[0], vmax=min_max[1])
else:
bnd_Val = max(abs(min(LOR_list)), abs(max(LOR_list)))
print("mi... | 63,681 |
def test_ocean_assets_search(publisher_ocean_instance, metadata):
"""Tests that a created asset can be searched successfully."""
identifier = str(uuid.uuid1()).replace("-", "")
metadata_copy = metadata.copy()
metadata_copy["main"]["name"] = identifier
assert (
len(publisher_ocean_instance.as... | 63,682 |
def rules_typescript_dev_dependencies():
"""
Fetch dependencies needed for local development, but not needed by users.
These are in this file to keep version information in one place, and make the WORKSPACE
shorter.
"""
http_archive(
name = "io_bazel",
urls = ["https://github.co... | 63,683 |
def _shard(split: Split, shard_index: int, num_shards: int) -> Tuple[int, int]:
"""Returns [start, end) for the given shard index."""
assert shard_index < num_shards
arange = np.arange(split.num_examples)
shard_range = np.array_split(arange, num_shards)[shard_index]
start, end = shard_range[0], (sha... | 63,684 |
def refractive_index(h_gp):
"""average atmospheric refractive index"""
delta = 2.93e-4
rho = atmosphere(h_gp)
n = 1. + delta * (rho / RHO0)
return n | 63,685 |
def push_limits_within_a_row(nono, row):
"""
Function pushes all block origins and endings within given row as far
as possible.
"""
changed_origins, new_origins = push_block_origins(
nono.data.get_row_hints(row),
nono.limits.get_row_origins(row),
exh=True,
)
changed_e... | 63,686 |
def randvec(n):
"""
Given the number of vertices n returns a random 2^n x 1 basis vector
Parameters
----------
n : integer
Number of bits in string which represents the number of verticies
in graph.
Returns
-------
v : ndarray
A random 2^n x 1 basis vec... | 63,687 |
def assemble_result_str(ref_snp, alt_snp, flanking_5, flanking_3):
"""
(str, str, str, str) -> str
ref_snp : str
DESCRIPTION: 1 character (A, T, G or C), the reference SNP.
alt_snp : str
DESCRIPTION: 1 character (A, T, G or C), the variant SNP.
flanking_5 : str
DESCRIPTI... | 63,688 |
def encrypt_blob(raw_data, public_key) -> bytes:
"""Return RSA + AES encrypted byte data from raw data input.
:ivar raw_data: Bytes rsa + aes data.
:raw_data raw_data: bytes
:ivar public_key: urlsafe base64encoded rsa public key string value.
:public_key public_key: string"""
decrypted_bytes = b... | 63,689 |
def test_add_widget_classes_simple():
"""Test when field has no errors and not initially hidden"""
form = ExampleForm({"text": "some text here"})
field = form["text"]
result = add_widget_classes(field)
expected = '<input type="text" name="text" value="some text here" class="nhsuk-input" required id=... | 63,690 |
def get_api_data(session, url, date_time):
"""Get the JSON-formatted response from the AMM API for the desired
date-time.
"""
session = session or requests.Session()
return session.get(url, params={"dt": date_time.format("DD/MM/YYYY")}).json() | 63,691 |
def trackedcmd(ui, repo, remotepath=None, *pats, **opts):
"""show or change the current narrowspec
With no argument, shows the current narrowspec entries, one per line. Each
line will be prefixed with 'I' or 'X' for included or excluded patterns,
respectively.
The narrowspec is comprised of expres... | 63,692 |
def validate_cnpj(doc):
"""Basic function to validate the CNPJ number for serializer field
Args:
doc (str): The CNPJ number, accepts with or without characters
Raises:
ValidationError: CNPJ inválido!
Returns:
doc: The CNPJ number
"""
if not cnpj(doc):
raise Val... | 63,693 |
def api_information(auth_token, repo_name, issue_number):
"""Comments the api information on the pr"""
gradle.run('apiInformation', '--continue', check=False)
dir_suffix = 'build/apiinfo'
comment_string = ""
for filename in os.listdir(dir_suffix):
subproject = filename
formatted_output_lines = []
... | 63,694 |
def make_trefoil(size=100, noise=0.0, a=2, b=2, c=3, **kwargs):
"""Generate synthetic trefoil dataset.
Params
-----
:size = int (default = 1000)
- the number of data points to use
"""
# generate trefoil
phi = np.linspace(0, 2*np.pi, size)
x = np.sin(phi) + a*np.sin(a*phi)
y = n... | 63,695 |
def _makeOperator(operatorInput, expectedShape):
"""Takes a dense numpy array or a sparse matrix or
a function and makes an operator performing matrix * blockvector
products.
Examples
--------
>>> A = _makeOperator( arrayA, (n, n) )
>>> vectorB = A( vectorX )
"""
if operatorInput i... | 63,696 |
def search(state, goal_state):
"""Iterative deepening depth-first"""
depth = 0
def dls(node):
if node.is_goal(goal_state):
return node
if node.depth < depth:
node.expand()
for child in node.children:
result = dls(child)
if ... | 63,697 |
async def test_create_start_entry_adapter_fails(
event_loop: Any,
mocker: MockFixture,
new_start_entry: StartEntry,
start_entry_mock: dict,
) -> None:
"""Should raise IllegalValueException."""
mocker.patch(
"race_service.services.start_entries_service.create_id",
return_value=sta... | 63,698 |
def union(*windows):
"""Union windows and return the outermost extent they cover.
Parameters
----------
windows: list-like of window objects
((row_start, row_stop), (col_start, col_stop))
Returns
-------
((row_start, row_stop), (col_start, col_stop))
"""
from rasterio._io i... | 63,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.