content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def resolve_ident(name: str, env) -> str:
"""Finds the variable, list, procedure or sprite with specified name in
env."""
for var in env["sprite"]["variables"]:
if var["name"] == name:
return "var", var["id"]
for lst in env["sprite"]["lists"]:
if lst["name"] == name:
... | 99a3a6cb8af259b80ca5b22c368d9c8e452977f2 | 51,100 |
import json
def bbox_to_geojson(bbox=None):
"""
:param bbox: A list [xmin, ymin, xmax, ymax]
:returns: A geojson of the bbox.
"""
bbox = Polygon.from_bbox(bbox)
geometry = json.loads(GEOSGeometry(bbox, srid=4326).geojson)
return {"type": "Feature", "geometry": geometry} | e607690a0ba87778bdf41925d1caa8ec197fd1ad | 51,101 |
def countDirectlyConnected(port: LPort, result: dict) -> int:
"""
Count how many ports are directly connected to other nodes
:return: cumulative sum of port counts
"""
inEdges = port.incomingEdges
outEdges = port.outgoingEdges
if port.connectedAsParent or (port.children and not all(p.conne... | b4dd2f1deec222336f4498df34b9252eea25324b | 51,102 |
def unmarshal(data_in):
"""Takes in binary data and maps builds the appropriate frame type,
returning a frame object.
:param bytes data_in: Raw byte stream data
:rtype: tuple of bytes consumed, channel, and a frame object
:raises: specification.FrameError
"""
# Look to see if it's a proto... | f5a4f7096453c696ec3eb6e7cd7925fc3719b5f4 | 51,103 |
def ip_interface(address):
"""Take an IP string/int and return an object of the correct type.
Args:
address: A string, integer, or a tuple of strings or integers
representing the IP interface as an IP address and optional
network prefix.
Returns:
An IPv4Interface or... | 92509799cb5617b54de04b0560b3e1fbf68f6b54 | 51,104 |
def wrap_reclassify_by_pons(row, fasta, chr_prefixed, pons):
"""Wrap 'relassify_by_panel_of_non_somatic' so that this function is
only applied to instances predicted 'somatic'
Args: see 'relassify_by_panel_of_non_somatic'
Returns: see 'relassify_by_panel_of_non_somatic'
"""
if row["predicted_cl... | 9b8cb6dd13aa2463a1cb433ffd11bc0018e3f910 | 51,105 |
import gzip
def read_rapsearch_aln(rpfile, linestocount, verbose=False):
"""
Read the rapsearch file and just return the query lines
:param rpfile: rapsearch file to read
:param linestocount: how many query lines to count
:param verbose: more output
:return: a query line
"""
if rp... | 5b53ef5ac8b73933aa673fa5670d3c50e4fa610e | 51,106 |
import numpy
def acosine(a,b,weights):
"""Distance between two points based on the pearson correlation coefficient.
By treating each data point as half of a list of ordered pairs it is
possible to caluclate the pearson correlation coefficent for the list.
Since the pearson correlation coefficen... | 19ffa98cb12c1d4e8026e0763c76062d2c4b19c8 | 51,107 |
def conv_3x3(inputs, downsample=False):
"""
conv_3x3
"""
return conv_base(inputs, (3, 3), downsample=downsample) | 8b5aab7497d15faba0ad085e6f1d4834b5902c2d | 51,108 |
def column(matrix, i):
"""
Returning all the values in a specific columns
Parameters:
X: the input matrix
i: the column
Return value: an array with desired column
"""
return [row[i] for row in matrix] | 2a88c40d11e7fe7f28970acd4d995a8428126a4d | 51,109 |
def cubicinout(x):
"""Return the value at x of the 'cubic in out' easing function between 0 and 1."""
if x < 0.5:
return 4 * x**3
else:
return 1/2 * ((2*x - 2)**3 + 2) | 505f0c5b8dc7b9499450474dbb1991eec068b553 | 51,110 |
def get_sparse_graph(graph):
"""
Returns a sparse adjacency matrix in CSR format
:param graph: undirected NetworkX graph
:return: Scipy sparse adjacency matrix
"""
return nx.to_scipy_sparse_matrix(graph, format='csr', dtype=np.float, nodelist=graph.nodes) | d8b6a13d133ec37ba68482c73146e5b37a85316b | 51,111 |
def run_tap_query(stcs, start_time=None, end_time=None, mission=None,
service='http://vao.stsci.edu/CAOMTAP/TapService.aspx', maxrec=100, verbose=False):
"""
Handler for TAP service.
Parameters
----------
stcs : str
Polygon to search for
start_time : float
MJD ... | d2a0ba8d0385e23e9f8ab061654368e66bebab48 | 51,112 |
from typing import Optional
def make_door_state(door_status: Optional[Door.Status]) -> State:
"""makes a simple state with a door"""
grid = Grid.from_shape((2, 1))
if door_status:
grid[0, 0] = Door(door_status, Color.RED)
agent = Agent(Position(1, 0), Orientation.N)
return State(grid, ag... | 340794c1ecd2bb5bed19af9a472285ed0a6008f3 | 51,113 |
def remove_duplicates(string: str) -> str:
"""
Remove duplicate characters in a string
:param string:
:return:
"""
without_duplicates = ""
for letter in string:
if letter not in without_duplicates:
without_duplicates += letter
return without_duplicates | 2caafc6b38cf2b920324bd976acb3caf90660c25 | 51,114 |
def interferometer(U):
"""Interferometer.
Args:
U (array): unitary matrix
Returns:
array: symplectic transformation matrix
"""
X = U.real
Y = U.imag
S = np.vstack([np.hstack([X, -Y]), np.hstack([Y, X])])
return S | f45ddb1e4ae0d9f8b118a9b6b0cecc655e4ed581 | 51,115 |
def make_tfd_dataframe(tfd_data_flat):
"""
This is just a quick function to make a nice DataFrame from the data. It makes it easy to manage.
Syntax: tfd_data_df = make_tfd_dataframe(tfd_data_flat)
Inputs:
tfd_data_flat - Dictionary containing information about the file and channel along wit... | 3c6d464dbbc4dfd2b713d58c36ecf258c7fcd90c | 51,116 |
def process_medians(helst, shelst, authlst):
"""
>>> medians_he = [12, 130, 0, 12, 314, 18, 15, 12, 123]
>>> medians_she = [123, 52, 12, 345, 0, 13, 214, 12, 23]
>>> books = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
>>> process_medians(helst=medians_he, shelst=medians_she, authlst=books)
{'... | 8262cd306b09d7ea201360a3c5abb6eef6dac966 | 51,117 |
def recalib(spec, figfilename, title, ref_spec, linelist, ref_calib,
aperture_koffset=(1, 0), pixel_koffset=(1, None),
xorder=None, yorder=None, maxiter=None, clipping=None, window_size=None,
q_threshold=None, direction=None, fit_filter=None
):
"""Re-calibrate the wavelength of an in... | 5f1c099551ea7d53fce222ea3aed852d33d1353f | 51,118 |
def encode_payload_values(payload_dict):
"""This function URL-encoded any string-formatted payload values.
.. versionadded:: 3.2.0
:param payload_dict: The JSON payload for an API call in dictionary format
:type payload_dict: dict
:returns: The JSON payload with URL-encoded string values
"""
... | 1f76d252e1206d0596d21a7f29733827865f0717 | 51,119 |
import math
def sequential_clustering(singleton_list, num_clusters):
"""
Take a data table and create a list of clusters
by partitioning the table into clusters based on its ordering
Note that method may return num_clusters or num_clusters + 1 final clusters
"""
cluster_list = []
... | 5239dae52107ba60ae3053d0b90b139d8bffa9e7 | 51,120 |
def _extract_fits(obj, hdu=0, unit=None, hdu_uncertainty=_HDU_UNCERT,
hdu_mask=_HDU_MASK, unit_key=_UNIT_KEY):
"""Extract data and meta from FITS files and HDUs."""
if isinstance(obj, (str, bytes, PathLike)):
hdul = fits.open(obj)
elif isinstance(obj, imhdus):
hdul = fits.H... | a1b8d63191585e2d5c8fa708d303da435479a57d | 51,121 |
def normalize_point_cloud(inputs):
"""
input: pc [N, P, 3]
output: pc, centroid, furthest_distance
"""
#print("shape",input.shape)
C = inputs.shape[-1]
pc = inputs[:,:,:3]
if C > 3:
nor = inputs[:,:,3:]
centroid = np.mean(pc, axis=1, keepdims=True)
pc = inputs[:,:,:3] - ... | 02be80ca8287af82140cdf9f68a0d48c70441d76 | 51,122 |
import click
def info(country_name):
"""Brief information about a country."""
country = return_country(country_data, country_name)
currency = return_country(currency_data, country_name)
calling_code = return_country(country_calling_code, country_name)
if currency is None and country is None and ... | c5c8e41c9c79f60592f8e35c3cebdfe220881b8a | 51,123 |
def aCoulomb(r, t=0, charge=-1):
"""
Coulomb acceleration calculation.
Input: r, t --Spatiotemporal coordinates.
charge --Coulomb charge. (Default: -1)
Output: aCoulomb --Acceleration vector.
"""
return(r*charge/blas.dznrm2(r)**3) | 00f5db2dd6dcd42d4704096583399cedc498e6f6 | 51,124 |
def get_finite(arr):
"""
Select only finite elements of an array.
"""
return arr[np.isfinite(arr)] | 09016626ec77c1e8b3cb2255b0ecac366c7f9a2d | 51,125 |
import argparse
def parse_args():
"""
Parses command line args
Returns:
The argparse namespace
"""
parser = argparse.ArgumentParser(description="Copies packer artifacts from the packer manifest output to terraform input variables.")
parser.add_argument('--enterprise', dest='enterprise... | 2b0dddb18edc3dfdf527ff31168f428dfb30dd03 | 51,126 |
def get_x_from_index(index: int) -> int:
"""Compute the x-coordinate with the provided x index.
This method compute the x coordinate associated with the
given x index. The returned value has the same dimension as
the constants provided in _constants.py.
Parameters:
index (int): The circuit... | eca24874f91098900de34d29351c27341dab4204 | 51,127 |
import awkward1.highlevel
import numbers
import numpy
from typing import Iterable
def to_numpy(array, allow_missing=True):
"""
Converts `array` (many types supported, including all Awkward Arrays and
Records) into a NumPy array, if possible.
If the data are numerical and regular (nested lists have eq... | 52a0e0425bcded9b6dd5afe7be543a844728de7f | 51,128 |
import glob
import os
def csvLayerNames(layer_path):
"""
Get names of layers stored as csv files.
"""
layer_names = glob.glob(os.path.join(layer_path, "*.csv"))
xx = [os.path.basename(i) for i in layer_names]
return xx | 682bf78f5d0a93f55277acf022d98d8c414a1161 | 51,129 |
import sys
def module_property(func):
"""Decorator to turn module functions into proerties.
Function names must be prefixed with an underscore"""
module = sys.modules[func.__module__]
def base_getattr(name):
raise AttributeError(
f"module '{module.__name__}' has no attribute '{nam... | 919e83e8c4027b6d541d1348bba2c1c4c3436952 | 51,130 |
def coeff_generator(style, func):
"""Make a Coefficient"""
if func == "f":
base = f
else:
base = g
if style == "func":
return coefficient(base, args=args)
if style == "array":
return coefficient(base(tlist, **args), tlist=tlist)
if style == "arraylog":
re... | 6aec6c0a1044e711390649002410d5dadc8d36f7 | 51,131 |
def load_imagenet_meta(meta_path):
"""It reads ImageNEt metadata from ILSVRC 2012 dev tool file
Args:
meta_path: path to ImageNet metadata file
Returns:
wnids: list of ImageNet labels(as strings)
words: list of words(a... | c96ec911c7fdadfa975a774a77177decb090dcd3 | 51,132 |
def _static_folder_path(static_url, static_folder, static_asset, prefix=''):
"""
Returns a path to a file based on the static folder, and not on the
filesystem holding the file.
Returns a path relative to static_url for static_asset
"""
# first get the asset path relative to the static folder... | 2b160faadd8ef8c9f436452542810de9a6701b34 | 51,133 |
def get_df_by_month(df, month):
"""Return ."""
cols = get_column_by_month(df, month)
basic = ['uid', 'age', 'sex', 'active_date', 'limit']
dates_col = [ACTIVE_MONTH, ACTIVE_YEAR, ACTIVE_DOW]
# this get sum of loans of 8,9,10,11
cols_12_cum = get_column_by_month(df, '12')
cols_12_cum.remove('... | b3f74dd934038932b991fd850c9d80eb397100f7 | 51,134 |
def mock_protocol_engine(decoy: Decoy) -> ProtocolEngine:
"""Get a mock EngineStore interface."""
return decoy.mock(cls=ProtocolEngine) | 83ff94a15d104551bcbfa5b98ed3f10de79519cd | 51,135 |
def wrap_render_to_string(f):
""" decorator for django.template.loader.render_to_string """
@wraps(f)
def wrapper(template_name, context=None, request=None, *args, **kwargs):
if request is not None and has_variant(request):
template_name = get_templates(template_name, get_variant(reques... | 8ea8801755f7a6d6486f952c13d75cbebad032da | 51,136 |
import json
def dumps(dict_):
"""
Converts dictionaries to indented JSON for readability.
Args:
dict_ (dict): The dictionary to be JSON encoded.
Returns:
str: JSON encoded dictionary.
"""
string = json.dumps(dict_, indent=4, sort_keys=True)
return string | c2f3eabe0b473def6233476018d8c3a3918beb70 | 51,137 |
def camel_case_to_snake_case(name):
"""
HelloWorld -> hello_world
"""
s1 = _FIRST_CAP_RE.sub(r'\1_\2', name)
return _ALL_CAP_RE.sub(r'\1_\2', s1).lower() | 2cf136866815cc63f5335d2fe1d68586b1ece88e | 51,138 |
def num_nets_provisioned(context, project_id):
"""Returns number of networks for a given tennat.
:param project_id: globally unique neutron tenant identifier
"""
return context.session.query(db_models.AristaProvisionedNets). \
filter_by(project_id=project_id).count() | 8d848fe77c76370318142d020fe5a551a6a0f6b2 | 51,139 |
def csundir_vect(time_in):
"""
Calculate the direction of the sun.
Parameters
----------
time_in: list of float
Time array.
Returns
-------
gst: list of float
Greenwich mean sideral time (radians).
slong: list of float
Longitude along ecliptic (radians).
... | 8a0973af076690922f6be55e552a61cb10ee75d2 | 51,140 |
import os
def get_parsable_list(path: str, name: str) -> list:
"""
Generate a list of parsable files.
Args:
path (str): a path to expected Bactopia results
name (str): the name of sample to test
Returns:
list: information about the status of parsable files
"""
parsabl... | 9adbeaf32b3034747f13144a8ab504d13a9e4868 | 51,141 |
def process_image(img,skip_dilate=False):
"""Uses a blurring function, adaptive thresholding and dilation to expose the main features of an image."""
# Gaussian blur with a kernal size (height, width) of 9.
# Note that kernal sizes must be positive and odd and the kernel must be square.
proc = cv2.Gaus... | a83996f96d4c473cdbd9dfe3fab7a16da7fe6c15 | 51,142 |
from datetime import datetime
def sample_game(**params):
"""Create and return a sample game"""
defaults = {
'igdb_id': 1,
'name': 'Mass Effect',
'summary': 'best game ever',
'rating': 90,
'first_release_date': datetime.datetime.fromtimestamp(1317945600)
}
defaul... | bfb4ef5e0fb93b9ab49d921e7509b2681bff3ac1 | 51,143 |
def minkowski_distance(dataset=None, x=None, y=None, p_value=None):
"""generalization of the euclidean and manhattan distances.
:param dataset: two object dataset with numeric attributes
:param x: list of first object's numeric attributes
:param y: list of second object's numeric attributes
:return:... | 4cc9ec7efbc16ad1cfde9f39135a42168e996f3c | 51,144 |
def most_symmetric_integer_factorization(N):
"""
Calculates the "most symmetric" integer factorization of N. This is the closest two integer factors of N. If N is
a square number, the integer factorization is "symmetric" and (sqrt(N), sqrt(N)) is the most "symmetric"
factorization.
Args:
N:... | bd633302c4ba9baf97e3da2abd27b5eb915ba240 | 51,145 |
import inspect
def alias_version(func):
"""Wrapper function to support aliasing of SPICE body names or codes.
"""
if hasattr(func, 'alias'):
return func.alias
if not hasattr(func, 'ALIAS_ARGS'):
alias_args = {}
for k in range(len(func.ARGNAMES)):
sig = func.SIGNAT... | 2d98fee83368ccb1e8aa1e020b8179477b275654 | 51,146 |
from typing import List
def count_nucleotides(lines: List[str]) -> str:
"""
:param lines: A line, in a list representing DNA sequence
:return: Four numbers separated by spaces - respective number of A, C, G and T nucleotides in input
"""
# only one sequence is expected
dna_sequence, = lines
... | d6d7e2a9c229ba1e006f39b05f54d12523cf088c | 51,147 |
def parsedir(directory, parsed, files, blocked, exts=('.torrent',),
return_metainfo=False, errfunc=_errfunc):
"""Parse bencoded files in a directory structure.
Parameters
str - path of directory
{str: {str: *}}
- dictionary, keyed by sha hash of encoded info dic... | 7674f5e0280d151062d36a305f85ec97535184b7 | 51,148 |
def CreateModelPart(meshes):
"""Creates a ModelPart given meshes as input"""
logger.debug('Calling "CreateModelPart"')
model_part = ModelPart()
geometries_io.GeometriesIO.AddMeshes(model_part, meshes)
return model_part | 73cb262fa9fdbdd4d35436009bc383414d6e23d6 | 51,149 |
def jpeg_linqual(quality):
"""
See int jpeg_quality_scaling(int quality)
in libjpeg-turbo source (file ijg/jcparam.c).
Convert quality rating to percentage scaling factor
used to scale the quantization table.
"""
quality = max(quality, 1)
quality = min(quality, 100)
if quality < 50:
... | a35157416fd4d95dddfe6cf8408a99e6247703ba | 51,150 |
def pytest_funcarg__content(request):
"""
The content for the test document as string.
By default, the content is taken from the argument of the ``with_content``
marker. If no such marker exists, the content is build from the id
returned by the ``issue_id`` funcargby prepending a dash before the i... | e357042566ce22557ba5c8f83b14f56cb8025dca | 51,151 |
def dict_to_ul(s):
"""
Helper to convert recursively dict elements to an html unsorted list
"""
app.logger.debug("Flattening %s" % s)
result = '<ul style="padding-left:2em">'
result = dict_to_li(s, result)
app.logger.debug("Result of flattening: %s" % result)
return str(result) | 00737490bc6c40810bbfc470d088d5be1bb93e51 | 51,152 |
def get_stationary_distribution(scc, reactions, epsilon = 1e-5):
""" Calculate the stationary distribution of complexes in a SCC.
Returns:
dict: Mapping of complexes to stationary distribution (flt).
"""
log.debug(f"Calculating stationary distribution for scc: {[x.name for x in scc]}")
scc... | 0e762615d9ba5de3e8c0d3a6f59068929b9ca567 | 51,153 |
import os
from sys import path
def findParentName(parentCollection, parentCollectionName):
"""
Recursive function to find the containing parent collections of a
collection or resource.
"""
if os.path.split(parentCollection)[1] == os.path.split(path)[1]:
# print (os.path.split(parentCollecti... | 269458d8bfaf2780b2e13fcc93c3cf89f7da1cfe | 51,154 |
def _apply_weighting(F, loss, weight=None, sample_weight=None):
"""Apply weighting to loss.
Parameters
----------
loss : Symbol
The loss to be weighted.
weight : float or None
Global scalar weight for loss.
sample_weight : Symbol or None
Per sample weighting. Must be bro... | e7d73368c1194f98c44861137d23231c565a415a | 51,155 |
def split_s3_path(s3_path):
"""
Splits the complete s3 path to a bucket name and a key name,
this is useful in cases where and api requires two seperate entries (bucket and key)
Arguments:
s3_path {string} -- An S3 uri path
Returns:
bucket {string} - The bucket name
key {... | 81efc5fc125c62d4dcde577b3424029acb4a536f | 51,156 |
def build_reference_wcs(inputs, sciname='sci'):
"""Create the reference WCS based on all the inputs for a field"""
# start by creating a composite field-of-view for all inputs
wcslist = []
for img in inputs:
nsci = countExtn(img)
for num in range(nsci):
extname = (sciname, nu... | 63d792275898bc2d6b4d8187d7f7d799ae22dc33 | 51,157 |
import unittest
import sys
import os
def main():
"""
process main for unit tests
This method will prepare the test suite, load listed test classes and
perform a run.
"""
loader = unittest.TestLoader()
suite = unittest.TestSuite()
# toggle verbose mode (if provided)
if '-v' in sy... | a1895e3e6fdca97237666c50d724e85c86c5eef3 | 51,158 |
import logging
import io
import sys
import types
def _RunMethod(dev, args, extra):
"""Runs a method registered via :func:`MakeSubparser`.
.. image:: _static/adb.common_cli._RunMethod.CALLER_GRAPH.svg
Parameters
----------
dev : TODO
TODO
args : TODO
TODO
extra : TODO
... | 3b1c3636d7bb6b49bc6274288512adab2cbeb671 | 51,159 |
def get_q_rq_H(region, R_type):
"""単位面積当たりの必要暖房能力
Args:
region(int): 省エネルギー地域区分
R_type(string): 居室の形式
Returns:
float: 単位面積当たりの必要暖房能力
"""
if R_type == '主たる居室':
return get_table_m_2()[0][region - 1]
elif R_type == 'その他の居室':
return get_table_m_2()[1][region - 1]... | ac3196e6583d2bfc24555c66f0b575971937bab9 | 51,160 |
import zipfile
def createZip(zip_name, src):
"""
parameter:- zip file name , folder path
This will create zip file
"""
zipf = zipfile.ZipFile(zip_name, 'w', zipfile.ZIP_DEFLATED)
for file in src:
zipf.write(file)
zipf.close()
print("--------zip file created --------")
... | 325f8a6b63f4a8c2d46b8d07bfc3b3e938d50836 | 51,161 |
def dash(*txts):
"""Join non-empty txts by a dash."""
return " -- ".join([t for t in txts if t != ""]) | 53566f49991f8d7930a63f7d2d22c125d9d25073 | 51,162 |
def quarter(month):
"""
:int month: Any month, as an int.
:return: The quarter of the year during which that month occurs (1-4)
"""
return int(ceil(float(month) / 3)) | 76d4e58e3b68870d9fc2f9697580fdef6624cc13 | 51,163 |
import asyncio
import functools
def call_later(delay, fn, *args, **kwargs) -> asyncio.Handle:
"""
Call a function after a delay (in seconds).
"""
loop = asyncio.get_event_loop()
callback = functools.partial(fn, *args, **kwargs)
handle = loop.call_later(delay, callback)
return handle | 86d157ed0f5f8dc7f806af9871a71057dc36222c | 51,164 |
from typing import Tuple
def build_blacklist_status(blacklist_status: str) -> Tuple[str, str, str]:
"""Build the blacklist_status
@type blacklist_status: str
@param blacklist_status: The blacklist status from command line
@returns Tuple[str, str, str]: The builded blacklist status
"""
blackli... | 10f0c3a77169a0e9b9136d454e6d17efdd4760f6 | 51,165 |
import spwd
import grp
def isuser(username, domain, password=None):
"""Check if user exists and if he is a member of the group 'domain'."""
try:
spwd.getspnam(username)
return username in grp.getgrnam(domain)[3]
except KeyError:
return False
except PermissionError:
prin... | 70e920c0fe3212c3e2588bc429c745fe134653e7 | 51,166 |
import os
import subprocess
def _run_cmd(cmd, working_dir, timelimit):
"""
Run a compilation command in the sandbox.
:param cmd: The command to run.
:param working_dir: The directory to run the command in.
:param timelimit: The number of seconds the command is allowed to run.
:return: The valu... | d103b00adbc6092be859fee9d0ab52474ce05679 | 51,167 |
from typing import Match
def CheckCStyleCast(filename, clean_lines, linenum, cast_type, pattern, error):
"""Checks for a C-style cast by looking for the pattern.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to... | f02e9ea980b2d68e2e03207209d14ab5e2f3f236 | 51,168 |
def dataclassAsDict(obj) -> dict:
"""
Return dataclass values as ``dict``.
This is a non-recursive variant of ``dataclasses.asdict``.
"""
if not is_dataclass(obj):
raise TypeError(f'Object {obj} is not a dataclass')
return {field.name: getattr(obj, field.name) for field in fields(obj)} | 0b026e4442f7ce06ef4afec026c6d5cef40d3180 | 51,169 |
async def server_error(request, exc):
"""
Return an HTTP 500 page.
"""
response = "Server error"
return PlainTextResponse(response) | 4bff48761e456261b95f825f5d38317918390e0d | 51,170 |
def _check_substituted_domains(patchset, search_regex):
"""Returns True if the patchset contains substituted domains; False otherwise"""
for patchedfile in patchset:
for hunk in patchedfile:
if not search_regex.search(str(hunk)) is None:
return True
return False | e3fdeaa1ede7f041bb6080d4647c8d969b41f73d | 51,171 |
def build(
requirements, # type: Iterable[InstallRequirement]
wheel_cache, # type: WheelCache
build_options, # type: List[str]
global_options, # type: List[str]
):
# type: (...) -> BuildResult
"""Build wheels.
:return: The list of InstallRequirement that succeeded to build and
t... | 7f174ec0b7aa6ea2ee73c192d68c33353bb37e3e | 51,172 |
import logging
import sys
def error_logger(log_path, name):
"""
formatting error log
:param log_path: error log path
:param name: log name
:return: Logger
"""
logger = logging.getLogger(name)
logger.setLevel(logging.INFO)
# Terminal output INFO log
console_handler = logging.St... | b27097f22ab76dba1ac6d2981cf6b9fbdad3e431 | 51,173 |
import os
def filter_enzyme_kinase(stmts_in, **kwargs):
"""Filter Phosphorylations to ones where the enzyme is a known kinase.
Parameters
----------
stmts_in : list[indra.statements.Statement]
A list of statements to filter.
save : Optional[str]
The name of a pickle file to save t... | 8136f1b00b6080a7549274edfe95370bee381446 | 51,174 |
import re
def prepareReposToJson(json_repos):
"""
Convert information about repo to proper format
:param json_repos:
:return: dictionary
"""
columns = ["created_on", "description", "fork_policy", "full_name", "has_issues", "has_wiki", "is_private",
"language", "links", "mainbran... | 40eaa03779b0161f78250a174e19b77041d511e8 | 51,175 |
def notifications(context):
"""
This renders the actual box where popup notifications get displayed on screen
"""
return render_to_string('notifications/display.html', {}, context) | 88a48f14f6557c75951ae5d514807f35d39f12e9 | 51,176 |
import os
def _get_default_settings(variable, config_user, derive=False):
"""Get default preprocessor settings."""
settings = {}
# Set up downloading using synda if requested.
if config_user['synda_download']:
# TODO: make this respect drs or download to preproc dir?
download_folder =... | 8a089c592924821bff974a3fc0ffe617c675d3f7 | 51,177 |
def browserid_authenticate(request, assertion):
"""
Verify a BrowserID login attempt. If the BrowserID assertion is
good, but no account exists on flightdeck, create one.
"""
backend = browserid_auth.BrowserIDBackend()
result = backend.verify(assertion, settings.SITE_URL)
if not result:
... | c4c30679f12fdeafea1975a6b523a05bb902d40c | 51,178 |
import pyrf
import vtool_ibeis as vt
from os.path import exists
def compute_forgroundness(fpath1, kpts1, species='zebra_plains'):
"""
hack in foregroundness
"""
# hack for getting a model (not entirely ibeis independent)
trees_path = ut.get_app_resource_dir('ibeis', 'detectmodels', 'rf', species)
... | 874f694a487009a9e7ada5cd4094384ce94d7cd1 | 51,179 |
from typing import Optional
def draw_self_loop(
point: np.array,
ax: Optional[plt.Axes] = None,
padding: float = 1.5,
width: float = 0.3,
plot_size: int = 10,
linewidth: float = 0.2,
color: str = "pink",
) -> plt.Axes:
"""Draw a loop from `point` to itself
!Important! By "center" ... | 4f33d750d3228b16302cea8819bf102051345fa9 | 51,180 |
def verify_arguments(target, method_name, args, kwargs):
"""Verifies that the provided arguments match the signature of the provided method.
:param Target target: A ``Target`` object containing the object with the method to double.
:param str method_name: The name of the method to double.
:param tuple ... | f9975e11d21834664ce31e0d0b0d924b271c6db4 | 51,181 |
from rptk import RptkAPI
from rptk.query import BaseQuery
import os
import json
import importlib
def mock_query_classes(monkeypatch):
"""Monkeypatch query classes for testing."""
class _MockQuery(BaseQuery):
def query(self, *objects):
objects = super(self.__class__, self).query(*objects)
... | fae4d604d7d8910e8e06ac3371ea19b4bdc2f008 | 51,182 |
def _get_routine_reference(self, routine_id):
"""Constructs a RoutineReference.
Args:
routine_id (str): the ID of the routine.
Returns:
google.cloud.bigquery.routine.RoutineReference:
A RoutineReference for a routine in this dataset.
"""
return RoutineReference.from_api... | 740b26d21676289f55688ee834017b62ad8324b6 | 51,183 |
def file(file_path: str) -> File:
"""
Returns a File object for a specified file path.
:param file_path:
:return File: a ReadableFile or ConvertibleFile object.
"""
if not is_found(file_path):
raise FileNotFoundError(file_path)
elif check_ext(file_path, Extensions.HISTOGRAM) and is... | f17dd501b92bd7cc3e40d64aaebd92c943a19826 | 51,184 |
from re import T
def get_bias_offset(nnet):
"""
returns the offset to balance the polynomial parameters possible by the bias
terms of the network.
"""
offset = 0
L = len(nnet.trainable_layers)
for l in range(L-1):
layer = nnet.trainable_layers[l]
if layer.b is not None:
... | 79b44c65c7a8b533a4c474977edc8eb6e63b0b9e | 51,185 |
def export_liaison(request):
"""导出所有联系人信息"""
response = HttpResponse(content_type='application/ms-excel')
response['Content-Disposition'] = 'attachment; filename="liaison.xls"'
# 创建一个workbook,设置编码
wb = xlwt.Workbook(encoding='utf-8')
# 创建一个worksheet,对应excel中的sheet,表名称
ws = wb.add_sheet('liai... | f66b2a0e412bbfac8c201523c77554f3a2c4e31a | 51,186 |
def get_percentage(df, filename=None, dropna=True):
"""
Normalise results to be plotted
"""
if len(df.columns) > 1 and len(df.index) > 1:
by_row, by_col = True, False
else:
by_row, by_col = True, True
if dropna is True:
# get nan Percentage
# 'Percentage NaN'
... | 9488848f41b693695ab9c21cf59d9aa4057efb04 | 51,187 |
def third_octaves(p, fs, density=False,
frequencies=NOMINAL_THIRD_OCTAVE_CENTER_FREQUENCIES,
ref=REFERENCE_PRESSURE):
"""Calculate level per 1/3-octave in frequency domain using the FFT.
:param x: Instantaneous signal :math:`x(t)`.
:param fs: Sample frequency.
:param... | 3d6abc7d30181300205fc7d4aa0cb429cf032a9a | 51,188 |
import torch
def convert_to_one_hot(
targets: torch.Tensor,
num_class: int,
label_smooth: float = 0.0,
) -> torch.Tensor:
"""
This function converts target class indices to one-hot vectors, given the number of classes.
Args:
targets (torch.Tensor): Index labels to be converted.
... | 344d527e9d799c03e710c07ea9229e0a0f34599c | 51,189 |
def temperature(
fire_time,
fire_temperature,
beam_rho,
beam_cross_section_area,
protection_k,
protection_rho,
protection_c,
protection_thickness,
protection_protected_perimeter,
terminate_when_cooling=False,
terminate_max_temperatu... | 284e5b21983804fd0fdf7b14d2e6e249d35795e6 | 51,190 |
def flow_schema(dps):
"""Return schema used in config flow."""
return {
vol.Optional(CONF_FAN_SPEED_CONTROL): vol.In(dps),
vol.Optional(CONF_FAN_OSCILLATING_CONTROL): vol.In(dps),
vol.Optional(CONF_FAN_DIRECTION): vol.In(dps),
vol.Optional(CONF_FAN_DIRECTION_FWD, default="forward... | 94513cd2fe1302f022fb214231a18630c6e2accc | 51,191 |
from typing import Tuple
import torch
def fast_rcnn_inference_single_image(
boxes,
scores,
image_shape: Tuple[int, int],
score_thresh: float,
nms_thresh: float,
topk_per_image: int,
aps_thresh: float,
):
"""
Single-image inference. Return bounding-box detection results by threshold... | 17d2893d6fdfb7d1e03759352cba46508f2b2f5c | 51,192 |
import re
import yaml
import os
def parse_config(data, tag='!ENV'):
"""
https://medium.com/swlh/python-yaml-configuration-with-environment-variables-parsing-77930f4273ac
Load a yaml configuration file and resolve any environment variables
The environment variables must have !ENV before them and be in... | 0699698ac3017e8b932775643dfa8cf6c77f9755 | 51,193 |
def StrSubstr(start_idx, count, initial_string):
"""
Create a concrete version of the substring
:param start_idx : starting index of the substring
:param end_idx : last index of the substring
:param initial_string
:return : a concrete version of the substring
"""
new_value = initial_str... | 88b0c077ec38fec1d0a5baa247114f472944c424 | 51,194 |
def delete_segment(seq, start, end):
"""Return the sequence with deleted segment from ``start`` to ``end``."""
return seq[:start] + seq[end:] | 1eba39d373ac2ab28ea1ea414f708a508bdf48d2 | 51,195 |
def placeNodesInLevels(nodes, edge_function):
"""Given a node "N" and an edge function, divide nodes into a sequence of groups
so that nodes never flow into their own group or an ealier group. Throw
if this has a cycle
"""
all_nodes = findAllNodes(nodes, edge_function)
reverse_edges = {c: set()... | e61b90bcc3bf384254a444f0da6c53c301cd3ae3 | 51,196 |
from typing import List
def voronoi_coloring(
points: List[complex],
centers: List[complex],
colors: List[Color]) -> Frame:
"""Convert the list of complex points to color output frame.
Args:
points (List[complex]): Input "image".
centers (List[complex]): Region centers... | 5a5376f8f033583caf5f58ae62f121854ebdb377 | 51,197 |
def get_directions(i0, i1, i2, i3):
""" get list of directions in a certain sequence """
return [directions_list[i0], directions_list[i1], directions_list[i2], directions_list[i3]] | e28cc069071807df3d892fc2f0e2b0d7ecbe8e4f | 51,198 |
def press_valve_route(action):
"""Route for press valve
Arguments:
action {string} -- Define the state change for the LOX and FUEL
Returns:
string -- Returns the valve controllers message
"""
if ser.is_open == True:
if action == 'FUEL-PRESS-OPEN':
ser.write(b'O1\n')
message = ser... | 5307fdb775e982f61af73b521ae04642067077cd | 51,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.