content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def error_handler(fun):
"""
Assert异常装饰器,用来方便的进行断言式接口开发
"""
def wrapper_fun(*args, **kwargs):
try:
return fun(*args, **kwargs)
except AssertionError as e:
return e.args[0]
except Exception as e:
return create_resp(code=8000, data=[], message=str... | 74,700 |
def notfound(e):
"""404 template"""
return render_template('404.html'), 404 | 74,701 |
def read_pipes():
# type: () -> str
""" Call to read_pipes.
:return: The command read from the pipe
"""
o = _COMPSs.read_pipes() # noqa
return o | 74,702 |
def require_json():
"""Ensure JSON Content-Type for requests with a body (POST, PATCH)."""
if request.method not in BODY_METHODS:
return
try:
view = current_app.view_functions.get(request.endpoint)
if view not in json_exempt_views and not request.is_json:
abort(400, {'me... | 74,703 |
async def get_relic_info(relic_name):
"""
Gets relic information and caches it, if not already cached.
Also helps mantain a parts list.
"""
logger.info("Fetching relic info for %s." % relic_name)
relic_infos = utils.get_json('relic_info')
if relic_name in relic_infos:
return relic... | 74,704 |
def manchester_vermont_observed(
awhere_api_key,
awhere_api_secret,
manchester_vermont_longitude,
manchester_vermont_latitude,
):
"""Fixture that returns a geodataframe for the observed weather
for Manchester, Vermont.
"""
# Define kwargs for Manchester, Vermont
vt_kwargs = {
... | 74,705 |
def get_rv_xmatch(ra, dec, G_mag=None, dr2_sourceid=None):
"""
Given a single RA, dec, and optionally Gaia G mag, and DR2 sourceid, xmatch
against spectroscopic catalogs to try and mine out an RV and error.
Returns tuple of:
(rv, rv_err, provenance)
Presumably all RVs returned are helio... | 74,706 |
def increment_name(mjd, lastname=None, suffixlength=4):
""" Use mjd to create unique name for event.
"""
dt = time.Time(mjd, format='mjd', scale='utc').to_datetime()
if lastname is None: # generate new name for this yymmdd
suffix = string.ascii_lowercase[0]*suffixlength
else:
yymmd... | 74,707 |
def get_fields_for_annotation(prepare_params):
""" Collecting field names to annotate them
:param prepare_params: structure with filters and ordering
:return: list of field names
"""
from tasks.models import Task
result = []
# collect fields from ordering
if prepare_params.ordering:
... | 74,708 |
def topic_meta(topic, precinctNum):
"""
Return meta data about each precinct's election result
output:
{
"percentTurnout": num,
"registeredVoters": num,
"totalVotes": num
},
"""
if precinctNum != 'all':
return j... | 74,709 |
def sync_cluster_type_to_service_config():
"""
从存储同步存储集群到资源服务类型配置
:return:
"""
# 从存储获取全量存储场景,添加不存在的service_type
scenarios = StorekitHelper.get_scenarios()
storage_service_type_list = resource_service_config.filter_list(active=1, resource_type="storage")
if scenarios:
for storage_... | 74,710 |
def check_for_previewimage(czi):
"""Check if the CZI contains an image from a prescan camera
:param czi: CZI imagefile object
:type metadata: CziFile object
:return: has_attimage - Boolean if CZI image contains prescan image
:rtype: bool
"""
att = []
# loop over the attachments
fo... | 74,711 |
def check_spec(spec: Union[str, Iterable[str]]) -> bool:
"""Checks the spec against the hard constraints.
Internally, Draco checks against the definitions, constraints, helpers,
and hard constraints.
:param spec: The specification to check
"""
if not isinstance(spec, str):
spec = "\n".... | 74,712 |
def export_progress_report(driver: CompassWebDriver,
cycle: str,
download_path: str = ".\\") -> None:
"""Export progress report data.
Data is saved as "[download_path]/[cycle].csv"
Args:
driver: An instance of CompassWebDriver
cycle... | 74,713 |
def num_associated_keyword(keyword, input_rel, relation, quantified=False, keyword2=None):
"""
Finds the number of associated elements for a given keyword.
Optionally a second keyword can be passed, in which case the number of elements that are associated with BOTH
keywords is returned.
:param keyw... | 74,714 |
def get_closest_multiple_of_16(num):
"""
Compute the nearest multiple of 16. Needed because pulse enabled devices require
durations which are multiples of 16 samples.
"""
return int(num) - (int(num) % 16) | 74,715 |
def _convert_line_to_task(line: str) -> Task:
"""
Convert a line record to a task instance.
Args:
line A record line from the storage file
Return
A task instance
"""
id, message, time, project, category, links, started_at, finished_at = line.strip().split(sep)
return ... | 74,716 |
def scene_equal(a, b):
"""
Do a simple check on two scenes and assert
that they have the same geometry.
Parameters
------------
a : trimesh.Scene
Object to be compared
b : trimesh.Scene
Object to be compared
"""
# should have the same number of geometries
assert len(... | 74,717 |
def test_delete_event_form_as_admin(permission_test_util):
"""An admin should be able to delete an event form."""
member, event, _, expected_update_delete_status_code = permission_test_util
form = EventFormFactory(event=event)
client = get_api_client(user=member)
url = _get_form_detail_url(form)
... | 74,718 |
def TransformListFactory(name: str, transforms: tp.Sequence[Transform]):
"""Create a new TransformationList subclss with the given name that performs
the specified transforms."""
return TransformListMetaclass(name, (TransformationList,), {},
transforms=transforms) | 74,719 |
def max_subarray(arr: List[int]) -> Tuple[int, int]:
"""
:time: O(n)
:space: O(n)
"""
max_val = max(x for x in arr)
if max_val < 0:
return max_val, max_val
max_subsequence_sum = sum(x for x in arr if x > 0)
max_subarray_sum = 0
current_sum = 0
for x in arr:
curr... | 74,720 |
def receive_redcap_det(*, session):
"""
Receive REDCap data entry triggers.
"""
document = request.form.to_dict()
LOG.debug(f"Received REDCap data entry trigger")
datastore.store_redcap_det(session, json.dumps(document))
return "", 204 | 74,721 |
async def ws(websocket):
"""$ wsdump.py ws://0.0.0.0:8000/ws"""
await websocket.accept(subprotocol=None)
cid = websocket.client.port
try:
while True:
t = await websocket.receive_text()
if t == 'close':
break
... | 74,722 |
def testnull():
"""Test case that do nothing"""
pass | 74,723 |
def distribute_statistics(immutability, source_path, packaging_path, parms, user, group):
"""
Determines if the distribution method is set to local or remote
and calls the correct distribution method.
Args:
immutability (bool): If True, change the file attributes for immutability.
sourc... | 74,724 |
def AND_columns_with_NANFLAGs(
df: pd.DataFrame, nan_val: int = 1, NANFLAG=-1
) -> pd.Series:
"""see :func:`apply_bool_op_on_columns_with_NANFLAGs()`"""
return apply_bool_op_on_columns_with_NANFLAGs(
df, pd.Series.__and__, nan_val, NANFLAG
) | 74,725 |
def split_container(path):
"""Split path container & path
>>> split_container('/bigdata/path/to/file')
['bigdata', 'path/to/file']
"""
path = str(path) # Might be pathlib.Path
if not path:
raise ValueError('empty path')
if path == '/':
return '', ''
if path[0] == '/':
... | 74,726 |
def load_data_dict(data_config):
"""
Load mapping information (dictionary) between raw data files to table names in the
database.
Parameters
----------
data_config : str
Path of the config file that stores data dictionaries in yaml.
This file should contains two dictionaries, on... | 74,727 |
def test_get_host_pairs_command_success(mocker_http_request, client):
"""
When "pt-get-host-pairs" command executes successfully then context output and response should match.
"""
from PassiveTotal_v2 import get_host_pairs_command
# Fetch the expected response from file
with open('test_data... | 74,728 |
async def _run_clang_tidy(
options: Any, line_filters: List[Dict[str, Any]], files: Iterable[str]
) -> CommandResult:
"""Executes the actual clang-tidy command in the shell."""
base = [options.clang_tidy_exe]
# Apply common options
base += ["-p", options.compile_commands_dir]
if not options.co... | 74,729 |
def run(self, service, mqttConnectArgs, app, appRunOptions={}, noMQTT=False, noHTTP=False):
"""Lifecycle for all the threads"""
service.client.loop_start()
if not noMQTT:
service.client.connect(*mqttConnectArgs)
exitEvent = threading.Event()
timerThread = threading.Thread(target=service.time... | 74,730 |
def alias_tuples_from_dict(aliases_dict):
"""
Convert from aliases dict we use in items, to a list of alias tuples.
The providers need the tuples list, which look like this:
[(doi, 10.123), (doi, 10.345), (pmid, 1234567)]
"""
alias_tuples = []
for ns, ids in aliases_dict.iteritems():
... | 74,731 |
async def response_to_dict(response: aiohttp.ClientResponse) -> CensusData:
"""Convert a response received from the server to a dictionary.
In some cases - mostly error states - the API will return JSON data
without providing the appropriate ``Content-Type`` entity header,
which breaks :meth:`aiohttp.C... | 74,732 |
def partial_trace(
density_matrix: np.ndarray,
targets: Optional[List[int]] = None,
) -> np.ndarray:
"""Returns the reduced density matrix for the target qubits.
If no target qubits are supplied, this method returns the trace of the density matrix.
Args:
density_matrix (np.ndarray): The de... | 74,733 |
def write_trace(movement_trace, results):
"""
Writes movement trace of the particles in a file for visualization
"""
main_dir = os.path.dirname(__file__)
rel_path = "vis/data/pso_data1.js"
abs_file_path = os.path.join(main_dir, rel_path)
f = open(abs_file_path, 'wb')
data = "var data = "+str(movement_trace)+";"... | 74,734 |
def lazy_pinyin(hans, style=Style.NORMAL, errors='default'):
"""不包含多音字的拼音列表.
与 gupinyin.pinyin 的区别是返回的拼音是个字符串,
并且每个字只包含一个读音.
:param hans: 汉字
:type hans: unicode or list
:param style: 指定拼音风格,默认是 gupinyin.Style.NORMAL 风格。
更多拼音风格详见 gupinyin.Style。
:param errors: 指定如何处理没有拼音的字符,... | 74,735 |
def energy_degeneracy(N, m):
"""Calculate the number of Dicke states with same energy.
The use of the `Decimals` class allows to explore N > 1000,
unlike the built-in function `scipy.special.binom`
Parameters
----------
N: int
The number of two-level systems.
m: float
Tota... | 74,736 |
def sigmoid(x):
"""Implementation of the sigmoid (logistic) function.
:param x: Function parameter.
:type x: int or float
"""
return 1 / (1 + np.exp(-x)) | 74,737 |
def test_applytorows_with_df_generation():
"""Testing ApplyToRows pipeline stages."""
df = _num_df()
cbf_stage = ApplyToRows(_sum_and_diff)
res_df = cbf_stage(df)
assert 'sum' in res_df.columns
assert 'diff' in res_df.columns
assert res_df['sum'][1] == 3
assert res_df['sum'][2] == 6
... | 74,738 |
def run_tasks(header, tasks):
"""Run a group of tasks with a header, footer and success/failure messages.
Args:
header: A message to print in the header bar before the tasks are run.
tasks: A list of tuples containing a task title, a task, and a weight.
If the tuple only contains tw... | 74,739 |
def list_entities() -> (str, int):
"""
Точка входа для запроса на получение записи пользователя по id. Пример запроса:
curl http://localhost:80/users
:return: если база не пуста, то возвращает json с данными пользователей и код 200,
иначе возвращает код 404
Формат возвращаемого... | 74,740 |
def map_intervals(ref_itv, other_itv, gap_chars={"-", "."}):
"""
Map intervals of representative sequences on its aligned version
Report contracted intervals that need to backpropagate in the other alignments at this level
"""
# extend contracted intervals
contracted = other_itv.length < ref_itv... | 74,741 |
def convert_ros2_time_to_float(time_tuple):
"""
Converts time from tuple (ROS2) format to floating point number
"""
return float(time_tuple[0] + time_tuple[1]/TIME_CONVERSION_CONST_) | 74,742 |
def p_expr_method(p):
"""
expr : method_decl SEMICOLON
| method_decl LEFT_BRACE skip_body RIGHT_BRACE
""" | 74,743 |
def csv_render(domain):
"""Render and return the csv-formatted report."""
headers = ('Domain', 'Type', 'Tweak', 'IP', 'Error')
csv_filename = 'dnstwister_report_{}.csv'.format(domain.to_ascii())
def local_resolve_candidate(candidate):
domain = Domain(candidate['domain-name'])
ip_addr, e... | 74,744 |
def crawl(path):
"""Crawl the path for possible Git directories.
Args:
path (str): Original path to crawl.
"""
main_dir = pathlib.Path(path)
if not main_dir.is_dir():
main_dir = main_dir.parent
main_dir = main_dir.resolve()
LOG.info('Finding directories in %s', main_dir)
... | 74,745 |
def center(x, y, width, height):
"""
info: gets the center x, y
:param x: int
:param y: int
:param width: int: 0 - inf
:param height: int: 0 - inf
:return: (int, int)
"""
return _get_center(x, width), _get_center(y, height) | 74,746 |
def get_prettyhandles_image(rankings):
"""return PIL image for rankings"""
SMOKE_WHITE = (250, 250, 250)
BLACK = (0, 0, 0)
img = Image.new("RGB", (900, 450), color=SMOKE_WHITE)
font = ImageFont.truetype("tle/assets/fonts/Cousine-Regular.ttf", size=30)
draw = ImageDraw.Draw(img)
x = 20
y... | 74,747 |
def extract_cnn_features(net, mean, img, layer, blob = None):
""" Extracts image features from a CNN using Caffe.
net - caffe.Net instance
mean - A numpy array with the mean values for each channel.
Channels must be in BGR order and the scale of values is assumed to be [0,255].
... | 74,748 |
def get_or_create_sc(type="sparkContext", name="CerebralCortex-Kernal", enable_spark_ui=False):
"""
get or create spark context
Args:
type (str): type (sparkContext, SparkSessionBuilder, sparkSession, sqlContext). (default="sparkContext")
name (str): spark app name (default="CerebralCortex-... | 74,749 |
def welchs_test_arrays(x1, x2):
"""
A spearate implementation that automatically calculates means, variances and the number of samples from the input lists of values.
Not currently used in the code because the number of samples is calculated earlier, when the estimators were combined.
It is kept as a s... | 74,750 |
def extrapolate_nsigma(ref_mag, SNR, nsigma=5):
"""
Fit a parabola to log10(SNR) vs ref_mag and
extrapolate/interpolate to find the n-sigma magnitude limit.
"""
log10_SNR = np.log10(SNR)
index = np.where(log10_SNR == log10_SNR)
pars = np.polyfit(log10_SNR[index], ref_mag[index], 2)
mag =... | 74,751 |
def main(cmdl):
""" Run the script. """
args = _parse_cmdl(cmdl)
global _LOGGER
_LOGGER = logmuse.logger_via_cli(args, make_root=True)
_LOGGER.debug("Creating counter")
counter = ReadCounter(args.readsfile, cores=args.cores,
outfile=args.outfile, action="CountReads", ... | 74,752 |
def extract_valid_voxels(gdf: gpd.GeoDataFrame):
"""
Given a GeoDataFrame gdf containing data from one source team,
with columns "dst_ip", "geometry",
process the Shapely objects contained in
"geometry" and store only the voxels that have not been invalidated
over their relevant time frames.
... | 74,753 |
def apply_holms_test(imbalanced_experiment, control_oversampler=None):
"""Use the Holm's method to adjust the p-values of a paired difference
t-test for every combination of classifiers and metrics using a control
oversampler.
Parameters
----------
imbalanced_experiment : object of :class:`rlea... | 74,754 |
def alternate_screen():
"""Use the `alternate screen buffer`_.
.. _alternate screen buffer: https://invisible-island.net/xterm/ctlseqs/
ctlseqs.html#h2-The-Alternate-Screen-Buffer
This function is a context manager for use in ``with`` statements.
It switches to the alternate screen buffer when ... | 74,755 |
def read_gmt(filepath,
gene_sets=(),
drop_description=True,
save_clean=False,
collapse=False):
"""
Read GMT.
:param filepath: str; filepath to a .gmt compress
:param gene_sets: iterable: list of gene set names to keep
:param drop_description: bool;... | 74,756 |
def parse(url: str, out_path: str, out_format: str):
"""
gets link and returns the response
"""
response = requests.get(url)
assert response.status_code == 200, f'bad status code: {response.status_code}'
response_html = Selector(response.text)
links_to_films = response_html.xpath('//td[@cl... | 74,757 |
def test_DPS_write_fn(tmpdir):
"""
1. max line 65536
"""
from nebula_website.views.db_stat import DPS_write_fn
def count_line(fn):
c = 0
with open(fn, 'r') as f:
for _ in f:
c += 1
return c
# 写入65534 + 1 行
# 实际也有 65535行
valid_count = 65... | 74,758 |
def get_email_from_token(token, salt, secret, max_age=86400):
"""
Read an email from a timestamped token.
Raises an exception if the token is more than 24 hours old or invalid
"""
ts = URLSafeTimedSerializer(secret)
email = ts.loads(token, salt=salt, max_age=max_age)
return email | 74,759 |
def template_match(source_image, template_image, region_center, option=0):
""" template match
@param source_image: np.array(input source image)
@param template_image: np.array(input template image)
@param region_center: list(if not None, it means source_image is
part of origin target image, ot... | 74,760 |
def months_in_prison(popu):
"""Return array of months in prison for each person in population."""
return np.array([person["months_in_prison"] for person in popu.values()]) | 74,761 |
def spending_over_time_test_data():
"""
Generate minimum test data for 'spending_over_time' integration tests.
Use some calculations inside of a loop to get a larger data sample.
"""
for i in range(30):
# Define some values that are calculated and used multiple times
transaction_id =... | 74,762 |
def main():
"""main
"""
# Training settings
parser = argparse.ArgumentParser(description='Graph Dataset')
parser.add_argument(
'--epochs',
type=int,
default=100,
help='number of epochs to train (default: 100)')
parser.add_argument(
'--dataset',
typ... | 74,763 |
def print_inplace(msg):
"""Clears out the previous line and prints a new one."""
term_width = get_terminal_size().columns
spacing = term_width - terminal_width(msg)
# On windows we need one less space or we overflow the line for some reason.
if is_win32:
spacing -= 1
sys.stderr.write("... | 74,764 |
def centre_window(window):
""" Centre the window 'window' """
window.update_idletasks()
# Screen
sw = window.winfo_screenwidth()
sh = window.winfo_screenheight()
# Window
ww = window.winfo_width()
wh = window.winfo_height()
window.geometry('%dx%d%+d%+d' % (ww, wh, (sw - ww)/2, (w... | 74,765 |
def elementary(deriv_func):
"""Decorator to create an elementary operation
This takes as an argument a function that calculates the derivative of the function
the user is calculating. When the decorated function is called, `@elementary` also calls
`deriv_func` and stores both the value and derivative i... | 74,766 |
def VerifyHWID(database, encoded_string,
probed_results, device_info, vpd, rma_mode,
current_phase=None, allow_mismatched_components=False):
"""Verifies the given encoded HWID v3 string against the probed BOM object.
A HWID context is built with the encoded HWID string and the project... | 74,767 |
def _singularize_copa_examples(dataset):
"""Converts COPA multi-choice examples to batch of single-answer examples."""
indexes = []
premises = []
questions = []
choices = []
labels = []
for example in dataset:
for choice in ["choice1", "choice2"]:
indexes.append(example["idx"])
premises.a... | 74,768 |
def test_skewt_shade_cape_cin(test_profile):
"""Test shading CAPE and CIN on a SkewT plot."""
p, t, tp = test_profile
with matplotlib.rc_context({'axes.autolimit_mode': 'data'}):
fig = plt.figure(figsize=(9, 9))
skew = SkewT(fig, aspect='auto')
skew.plot(p, t, 'r')
skew.plot... | 74,769 |
def configure_code_run(batch):
"""
This function tells stroopwafel what program to run, along with its arguments.
IN:
batch(dict): This is a dictionary which stores some information about one of the runs. It has an number key which stores the unique id of the run
It also has a subprocess... | 74,770 |
def get_client() -> RabbitmqClient:
"""Returns a RabbitmqClient instance."""
# Replace the parameters with proper values for host, port, login and password
# Change the value of exchange if needed.
#
# For any parameter that is not given here, the client tries to use a value from an environment vari... | 74,771 |
def get_animal_ids(id=None):
"""
Return the distinct animal ids
:param id : id of the specific dataset
"""
if id is None:
return jsonify({})
animal_ids = db.session.query(Movement_data.animal_id).filter_by(dataset_id=id).distinct(Movement_data.animal_id)
result = []... | 74,772 |
def find_actors(hg, edge):
"""Returns set of all coreferences to actors found in the edge."""
actors = set()
if is_actor(hg, edge):
actors.add(main_coref(hg, edge))
if not edge.is_atom():
for item in edge:
actors |= find_actors(hg, item)
return actors | 74,773 |
def rate_project(request, project_id):
"""
rate_project view function to process the user input rating information
based on usability,content and design and return an average
rating which will be stored in the database
"""
current_user=request.user
# get project to be rated from the DB
... | 74,774 |
def load_era5(
var, lat, lon, time,
reduce_func=None,
resample="1D",
):
"""
Download and return an ERA5 variable for a defined time window.
Parameters
----------
var : string
Name of the ERA5 climate variable to download, e.g "air_temperature_at_2_metres"
lat: tuple or list... | 74,775 |
def test_docker_service(host):
"""Check docker service"""
s = host.service("docker")
assert s.is_running
assert s.is_enabled | 74,776 |
def stack_to_queue(stack):
"""
Convert queue to a stack
"""
input_stack = copy.deepcopy(stack)
output_queue = ArrayQueue()
while True:
try:
output_queue.add(input_stack.pop())
except KeyError:
break
return output_queue | 74,777 |
def sigma(S,T,P=0. | units.dbar):
""" Density anomaly """
_S=S.value_in(units.psu)
_T=T.value_in(units.Celsius)
_P=P.value_in(units.dbar)
return _seawater.sigma(_S,_T,_P) | units.kg/units.m**3 | 74,778 |
def notify(apprise_client, title, submission_id):
"""Send apprise notification."""
apprise_client.notify(
title=title,
body="https://www.reddit.com/" + submission_id,
) | 74,779 |
def get_dir_list_recurse(basepath, itempath="", parent=None):
"""Walk directory tree for get_dir_list."""
total = []
if not basepath.endswith("/"):
basepath = basepath + "/"
if itempath and not itempath.endswith("/"):
itempath = itempath + "/"
items = os.listdir(basepath + itempath)
... | 74,780 |
def laplacian_positional_encoding(g, pos_enc_dim):
"""
Graph positional encoding v/ Laplacian eigenvectors
"""
# Laplacian
A = g.adjacency_matrix_scipy(return_edge_ids=False).astype(float)
N = sp.diags(dgl.backend.asnumpy(g.in_degrees()).clip(1) ** -0.5, dtype=float)
L = sp.eye(g.number_... | 74,781 |
def create_2d_gaussian(dim, sigma):
"""
Source: https://github.com/vsvinayak/mnist-helper/blob/master/mnist_helpers.py
This function creates a 2d gaussian kernel with the standard deviation
denoted by sigma
:param dim: integer denoting a side (1-d) of gaussian kernel
:type dim: int
:param s... | 74,782 |
def get_embedding(path):
"""
Get the dataset of ingredients as a dictionary.
:return: a dictionary representing the embedding
"""
embedding_io = io.BytesIO(pkgutil.get_data(__name__, path))
return np.load(embedding_io, allow_pickle=True).item() | 74,783 |
def test_last_block_not_recent_read_timeout(
mock_time_range, mock_monero_rpc, caplog
):
"""Raises a requests.exceptions.ReadTimeout"""
mock_monero_rpc.side_effect = ReadTimeout(
"Request timed out when reading response."
)
mock_time_range.return_value = (True, 12, "minutes")
response ... | 74,784 |
def get_challenges_for_user_id(database, user_id, ctf_channel_id):
"""
Fetch a list of all challenges a user is working on for a given CTF.
Return a list of matching Challenge objects.
This should technically only return 0 or 1 challenge, as a user
can only work on 1 challenge at a time.
"""
... | 74,785 |
def pytest_runtest_setup():
"""
This is run when setting up the tests.
"""
# We don't want to allow access to sockets, to make sure we're not making calls to some website
disable_socket() | 74,786 |
def allowed_file(filename):
""" allowed formats to be uploaded for mcdss """
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS | 74,787 |
def parse_sph_header( fh ):
"""Read the file-format header for an sph file
The SPH header-file is exactly 1024 bytes at the head of the file,
there is a simple textual format which AFAIK is always ASCII, but
we allow here for latin1 encoding. The format has a type declaration
for each field a... | 74,788 |
def update_graphite():
"""
Handles the connection with graphite and the update of the lists to be committed. Data is send periodically
(depending on UPDATE_DELAY).
:return: None
:rtype: None
"""
global graphite_list
# Open socket with graphite
sock = socket.socket()
sock.conne... | 74,789 |
def cli():
"""great_expectations command-line interface"""
pass | 74,790 |
def add_records(datalinks_records_list):
"""
upserts records into db
:param datalinks_records_list:
:return: success boolean, plus a status text for retuning error message, if any, to the calling program
"""
rows = []
for i in range(len(datalinks_records_list.datalinks_records)):
fo... | 74,791 |
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:
... | 74,792 |
def set_time_of_last_rdd(time_of_last_rdd_processed):
"""
Sets the time at which the last RDD was processed.
Returns:
Nothing. Set() method.
"""
global TIME_OF_LAST_RDD
TIME_OF_LAST_RDD = time_of_last_rdd_processed | 74,793 |
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} | 74,794 |
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... | 74,795 |
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... | 74,796 |
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... | 74,797 |
def build_gallery(config):
"""Updates and generates everything: scans the image dirs, updates the metadata in the project path and generates
the site in destination, creating image variants where needed
config: the yaml file containing the various paths for the project to be used
"""
core.update_ev... | 74,798 |
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... | 74,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.