content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_manifest_backfill_broken_tag(clear_rows, initialized_db):
"""
Tests backfilling a broken tag.
"""
# Delete existing tag manifest so we can reuse the tag.
TagManifestLabel.delete().execute()
TagManifest.delete().execute()
# Create a tag with an image referenced missing parent images... | 5,317,900 |
def format_meta(metadictionary):
"""returns a string showing metadata"""
returntext = EMPTYCHAR
returntext += 'SIZE' + BLANK + COLON + BLANK + str(metadictionary['size'])+EOL
returntext += 'USER' + BLANK + COLON + BLANK + str(metadictionary['user'])+EOL
returntext += 'DATE' + BLANK + COLO... | 5,317,901 |
def test_masters_have_user_locations_string(ufo_module):
"""Test that stringified Axis Locations are converted.
Some versions of Glyph store a string instead of an int.
"""
font = to_glyphs([ufo_module.Font(), ufo_module.Font()])
font.customParameters["Axes"] = [{"Tag": "opsz", "Name": "Optical"}]
... | 5,317,902 |
def test_action_only_on_leaf():
"""Test actions that must be on leaf node"""
for operation in (
Action.Operation.APPROVE,
Action.Operation.DENY,
Action.Operation.ERROR,
):
request = RequestFactory(state=Request.State.NOTIFIED)
request.create_child()
with pytes... | 5,317,903 |
def create_update_comment(token, org, repo_name, pr_number, comment_body):
"""Creates or updates existing comment on a PR"""
# auth with GH token
gh = Github(token)
# ref to repo
github_repo = gh.get_repo(f'{org}/{repo_name}')
# get current user id of token owner
current_bot_user = gh.get_us... | 5,317,904 |
def look_in_directory(directory, file_to_find):
"""
Loop through the current directory for the file, if the current item
is a directory, it recusively looks through that folder
"""
# Loop over all the items in the directory
for f in os.listdir(directory):
# Uncomment the line below t... | 5,317,905 |
def accumulating_income():
"""
Real Name: Accumulating Income
Original Eqn: Income
Units: Month/Month
Limits: (None, None)
Type: component
Subs: None
"""
return income() | 5,317,906 |
def createConfig(namespace=None, updateEnv=None, updateEnvMap=None, updateEnvHelp=None, updateEnvDefaults=None,
updateProperties=None, config=Config, initFromEnv=True, **settings):
"""Creates a base configuration class."""
namespace = sys.modules[namespace] if isinstance(namespace, str) else namespace
... | 5,317,907 |
def fake_map_matrix_T_without_enemy(map, mySide):
"""
伪造一个没有敌方坦克的地图类型矩阵
WARNING:
首先检查是不是对方 tank ,因为可能遇到对方已经死亡或者两方坦克重合
这种时候如果己方坦克恰好在这个位置,就会被删掉,assert 不通过
"""
map_ = map
oppSide = 1 - mySide
cMatrixMap = map_.matrix_T.copy()
for oppTank in map_.tanks[oppSide]:
if (... | 5,317,908 |
def YumUninstall(vm):
"""Uninstalls the memtier package on the VM."""
_Uninstall(vm) | 5,317,909 |
def dict_factory(cursor, row):
"""
Factory function to convert a sqlite3 result row in a dictionary
:param cursor: cursor object
:param row: a row object
:return: dictionary representation of the row object
"""
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row... | 5,317,910 |
def ndcgREval(data, gt, gf):
"""
Compute NDCG@R, where R is the number of relevant documents
"""
ideal = generate_ideal(gt,gf)
dcgScore = dcg(data[:(gt)])
norm = dcg(ideal[:(gt)][:len(data)])
if(norm == 0): print('norm=0 in ndcgREval')
return dcgScore / norm | 5,317,911 |
def create_modifiers(y_position):
"""Create all creatable modifiers"""
def create():
for mod in rt.modifier.classes:
try:
created = mod()
print(created)
box = create_box()
rt.addModifier(box, created)
yield box
... | 5,317,912 |
def queue_busy_workers(queue: str) -> List[str]:
"""
This function counts the number of busy workers for a given queue.
"""
return [
worker.name
for worker in rq.Worker.all(queue=queue)
if worker.state == "busy"
] | 5,317,913 |
def coste(theta, X, Y):
"""
cost function
computes J(theta) for a given dataset
"""
m = np.shape(X)[0]
H = sigmoid((np.dot(X,theta)))
J = -1/m * ( np.log(H).transpose().dot(Y)
+ np.log(1-H).transpose().dot(1-Y))
return J | 5,317,914 |
def test_simhash_table():
"""Tests the HashCounter."""
# pylint: disable=too-many-locals,unused-variable
num_hash_buckets = 4
debug = True
class HashFn(object):
"""A mock hash function. Big-endian."""
codes = None
buckets = None
@staticmethod
def _i2b(i):
... | 5,317,915 |
def replace_php_define(text, define, value):
"""
Replaces a named constaint (define) in PHP code.
Args:
text (str) : The PHP code to process.
define (str) : Name of the named constant to modify.
value (int,str) : Value to set the 'define' to.
Returns:
The mo... | 5,317,916 |
def setup_logging(name: str, level=logging.DEBUG, json_logging=True) -> Logger:
"""
Sets up root logger.
"""
if json_logging:
setup_json_logging(level)
else:
setup_plain_logging(level)
# disable useless logging from flask
logging.getLogger('werkzeug').setLevel(logging.WARNIN... | 5,317,917 |
def data_method(func):
"""
Decorate object methods by tagging them as data methods.
The generated data class will have the decorated methods in them.
.. code:: python
>>> from objetto.applications import Application
>>> from objetto.objects import Object, attribute, data_method
... | 5,317,918 |
def replace_bn(module, name):
"""
Recursively put desired batch norm in nn.module module.
set module = net to start code.
"""
# go through all attributes of module nn.module (e.g. network or layer) and put batch norms if present
for attr_str in dir(module):
target_attr = getattr(module,... | 5,317,919 |
def test_tensor2pretty_response(y_tensor):
"""
test that the mapping back from tensor to pandas works
"""
# run mapping
pandas_out = tensor2pretty_response(train_Y_sample=y_tensor)
# compare
for i in range(y_tensor.size()[0]):
assert y_tensor[i,0].item() == pandas_out["Response"].i... | 5,317,920 |
def get_frontend_names():
"""Return the names of all supported frontends
Returns
-------
list : list of str
A list of frontend names as strings
"""
return [frontend.name() for frontend in ALL_FRONTENDS] | 5,317,921 |
async def update_listener(hass: HomeAssistant, entry: ConfigEntry):
"""Update when config_entry options update."""
if entry.options[CONF_UPDATE_INTERVAL]:
coordinator = hass.data[DOMAIN][entry.entry_id]["coordinator"]
new_update_interval = timedelta(seconds=entry.options[CONF_UPDATE_INTERVAL])
... | 5,317,922 |
def test_st_e080_st_e080_v(mode, save_output, output_format):
"""
TEST :Syntax Checking for simpleType Declaration : Union with Fixed
Value (33)
"""
assert_bindings(
schema="msData/simpleType/stE080.xsd",
instance="msData/simpleType/stE080.xml",
class_name="Root",
ver... | 5,317,923 |
def get_spec_file_path(step_class):
"""
Given a STep (sub)class, divine and return the full path to the
corresponding spec file. Use the fact that by convention, the spec file is
in the same directory as the `step_class` source file. It has the name of
the Step (sub)class and extension .spec.
... | 5,317,924 |
def test_launch_with_missing_oauth_nonce_key():
"""
Does the launch request work with a missing oauth_nonce key?
"""
oauth_consumer_key = 'my_consumer_key'
oauth_consumer_secret = 'my_shared_secret'
launch_url = 'http://jupyterhub/hub/lti/launch'
headers = {'Content-Type': 'application/x-www... | 5,317,925 |
def setUpModule():
"""Вызывается один раз перед всеми классами, которые есть в файле."""
print('> setUpModule') | 5,317,926 |
def getColourPlotData(g, r, i, z, y):
"""Collect the colour info from input filter data for plotting"""
from gkutils.commonutils import getColour, getColourStats
import json
colourPlotLimits = {}
coloursJSON = []
grColour = []
riColour = []
izColour = []
colourPlotLabels = [{'label... | 5,317,927 |
def show(*args, **kwargs):
"""Wrapper for make_figure()"""
return make_figure(*args, **kwargs) | 5,317,928 |
def set_title(node, title):
"""Sets the title of a link or image node. Returns 1 on success, 0 on failure.
Args:
node (cmark_node): The node to set the title attribute on
title (string): Title as string
Returns:
int: 0 on failure, 1 on success
"""
title=to_c_string(... | 5,317,929 |
def get_image(filename, convert_rgb=True):
"""Returns numpy array of an image"""
image = Image.open(filename)
# sometime image data is gray.
if convert_rgb:
image = image.convert("RGB")
else:
image = image.convert("L")
image = np.array(image)
return image | 5,317,930 |
def find_order_to_apply_confirmation(domain, location):
"""
Tries to find the EmergencyOrder that the receipt confirmation applies to.
:param domain: the domain to search
:param location: the SQLLocation that the confirmation is coming from
:return: the EmergencyOrder that the confirmation should ap... | 5,317,931 |
def tiny(tmpdir):
"""Create a tiny fake brain."""
# This is a minimal version of what we need for our viz-with-timeviewer
# support currently
subject = 'test'
subject_dir = tmpdir.mkdir(subject)
surf_dir = subject_dir.mkdir('surf')
rng = np.random.RandomState(0)
rr = rng.randn(4, 3)
... | 5,317,932 |
def find_exp_parameters(cfg, logger):
""" Extracts experimental parameters. """
hemi, space = cfg['hemi'], cfg['space']
space_idf = f'hemi-{hemi}*.func.gii' if 'fs' in space else 'desc-preproc_bold.nii.gz'
# Use all possible participants if not provided
if cfg['subject'] is None:
cfg['subj... | 5,317,933 |
def create_universe(code, infilepath_or_buffer=None, sids=None, from_universes=None,
exclude_delisted=False, append=False, replace=False):
"""
Create a universe of securities.
Parameters
----------
code : str, required
the code to assign to the universe (lowercase alphan... | 5,317,934 |
def onroot_vc(t, y, solver):
"""
onroot function to reset the solver back at the start, but keep the current
velocity as long as the time is less than a given amount
"""
if t > 28: # we have found 4 interruption points, so we stop
return 1
solver.reinit_IC(t, [Y0, y[1]])
return 0 | 5,317,935 |
def test_attributes_callable():
"""Verify attributes can take a callable"""
ATTRS = lambda tag, name, val: name == 'title'
TAGS = ['a']
text = u'<a href="/foo" title="blah">example</a>'
assert (
bleach.clean(text, tags=TAGS, attributes=ATTRS) ==
u'<a title="blah">example</a>'
) | 5,317,936 |
def _only_one_selected(*args):
"""Test if only one item is True."""
return sum(args) == 1 | 5,317,937 |
async def team_join(event: Event, app: SirBot) -> None:
"""
Handler for when the Slack workspace has a new member join.
After 30 seconds sends the new user a greeting, some resource links, and
notifies the community channel of the new member.
"""
slack_api = app.plugins["slack"].api
user_id... | 5,317,938 |
def get_org_files(rcfile):
"""Get a list of org files from a 'vimrc' file."""
with open(rcfile, 'r') as vimrc:
data = vimrc.read()
orgfiles = re.search(r'org_agenda_files\s=.*?\[.*?\]', data, re.DOTALL).group()
orgfiles = orgfiles.split('[')[1].split(', ')
orgfiles = [slugify(x) for x in org... | 5,317,939 |
def transform_and_crop_coordinate(coordinate, transform=None, offset=None, theta=None, inverse=True, name=None):
""" Transforms a single coordinate then applies a crop offset.
You probably don't need to use this, just call random_projection_transform()
and then transform_and_crop_image().
Please not... | 5,317,940 |
def parse_direct_to_payload(
logger: OchronaLogger, direct: str, config: OchronaConfig
) -> Dict[str, Any]:
"""
Parses direct input string as PEP-508 compliant file and outputs a JSON payload.
:param logger: A configured `OchronaLogger` instance
:param direct: input string
:param config: An inst... | 5,317,941 |
def build_uncertainty_calibrator(
calibration_method: str,
uncertainty_method: str,
regression_calibrator_metric: str,
interval_percentile: int,
calibration_data: MoleculeDataset,
calibration_data_loader: MoleculeDataLoader,
models: Iterator[MoleculeModel],
scalers: Iterator[StandardScal... | 5,317,942 |
def generate_new_diversity_plots(otu_table_fs, gg_f, mapping_f,
mapping_category='Sample_Type',
min_num_samples=11,
category_values_to_exclude=None,
verbose=False):
"""Will exclude 'NA... | 5,317,943 |
def tile_data3d(data,(lentZ,lentY,lentX)):
"""
Tile sparky data into 1D numpy array
Parameters:
* data Three-dimensional data array
* lentZ Z (w1) dimention tile size
* lentY Y (w2) dimention tile size
* lentX X (w3) dimention tile size
Returns 1D numpy array of floats
... | 5,317,944 |
def format_sv(sv):
"""
Post-processing to format SVs for export
:param sv: parsed SV
:return: none
"""
sv[TRANSCRIPTS_FIELD] = [{'gene_id': gene} for gene in sv[GENES_FIELD]]
sv['transcriptConsequenceTerms'] = [sv[CALL_FIELD]]
if sv[SF_FIELD]:
sv['sn'] = int(sv[SC_FIELD] / sv[SF... | 5,317,945 |
def run_webserver(*args, **kwargs):
"""Runs webserver in command line, adds routes."""
from openpype.modules import ModulesManager
manager = ModulesManager()
webserver_module = manager.modules_by_name["webserver"]
host = kwargs.get("host") or "localhost"
port = kwargs.get("port") or 8079
se... | 5,317,946 |
def do_lock(
project: Project,
strategy: str = "all",
tracked_names: Optional[Iterable[str]] = None,
requirements: Optional[Dict[str, Dict[str, Requirement]]] = None,
) -> Dict[str, Candidate]:
"""Performs the locking process and update lockfile.
:param project: the project instance
:param ... | 5,317,947 |
def sparse_to_vector(vector: scipy.sparse.spmatrix):
"""
Converts one dimensional sparse matrix to a vector array to allow more features.
:param vector: Vector as a sparse matrix (x,1) or (1,x).
:return: Vector as an one dimensional array (x,).
"""
return np.ravel(vector.toarray()) | 5,317,948 |
def uncentered_operator(X, func, center=None, fill=None, **kwargs):
"""Only apply the operator on a centered patch
In some cases, for example symmetry, an operator might not make
sense outside of a centered box. This operator only updates
the portion of `X` inside the centered region.
Parameters
... | 5,317,949 |
def validate(config):
"""Validate the configuration
"""
schema = anyconfig.loads(json_config_schema(), ac_parser="json")
result, message = anyconfig.validate(config, schema)
if not result:
raise SystemExit(message) | 5,317,950 |
def _get_range_and_pstring(variable, mean_cube, tropopause=False):
"""Get range for color bar and print string."""
if variable == "Air Temperature":
print_var = "Temperature [K]"
set_range = np.linspace(180, 230, 21)
elif variable == "Geopotential Height":
print_var = "Geopotential H... | 5,317,951 |
def main():
"""
Walk CODE directory to locate PyLauncher.json files. Once located,
import data and generate menu items and CMD objects to execute
commands when selected.
"""
selections = []
for root, _dirs, files in os.walk(CODE):
# If JSON file is found, read data
if 'PyL... | 5,317,952 |
def merge_storage(df, cons, prod, stor):
"""Merge positve storage in consumption and negative part in the production
"""
_df = df.copy()
assert not _df.isnull().values.any(), 'Include NaN values'
_df[prod] = _df[prod] - _df[stor].clip(upper=0)
_df[cons] = _df[cons] + _df[stor].clip(lower=0)
... | 5,317,953 |
def install_jvm_runtime(jvm_version: str, minecraft_directory: Union[str, os.PathLike], callback: Dict[str, Callable] = None):
"""
Installs the given jvm runtime. callback is the same dict as in the install module.
"""
if callback is None:
callback = {}
manifest_data = requests.get(_JVM_MANI... | 5,317,954 |
def send_help_message(update: Update, context: CallbackContext) -> None:
""" Sends a help message to the chat. """
try:
_, _, chat = get_message_meta(update)
with open(HELP_PATH, "r") as help_file:
context.bot.send_message(chat_id=chat.id, text=help_file.read(),
... | 5,317,955 |
def load_page_data(img_dir: str, current_obj: Mapping[T, T]) -> Mapping[T, T]:
"""
Iterate through the img directory, and retrieve the page level data
"""
page_data = []
for f in glob.glob(f'{img_tmp}/*'):
page_obj = {}
page_num = int(os.basename(f))
img = Image.open(f)
... | 5,317,956 |
def wraps(wrapped,
assigned = WRAPPER_ASSIGNMENTS,
updated = WRAPPER_UPDATES):
"""Decorator factory to apply update_wrapper() to a wrapper function
Returns a decorator that invokes update_wrapper() przy the decorated
function jako the wrapper argument oraz the arguments to wraps()... | 5,317,957 |
def numeric_date(dt=None):
"""
Convert datetime object to the numeric date.
The numeric date format is YYYY.F, where F is the fraction of the year passed
Parameters
----------
dt: datetime.datetime, None
date of to be converted. if None, assume today
"""
from calendar import ... | 5,317,958 |
def specific_clean_cell_lst():
"""Clean a list of cells - column cells"""
# List of strings
col_cells = request.json["cells"]
col_type = request.json["coltype"]
clean_cells = fix_specific(col_cells, col_type)
return clean_cells | 5,317,959 |
def compress_sym(sym_expanded, make_symmetric=True):
"""Compress symmetric matrix to a vector.
Similar to scipy.spatial.squareform, but also contains the
diagonal.
Parameters
----------
sym_expanded : nd-array, shape (size, size)
Input matrix to compress.
make_symmetric : bool (de... | 5,317,960 |
def append_result(gsutil, path, build, version, passed):
"""Download a json list and append metadata about this build to it."""
# TODO(fejta): delete the clone of this logic in upload-to-gcs.sh
# (this is update_job_result_cache)
end = time.time() + 300 # try for up to five minutes
... | 5,317,961 |
def get_cc_biz_id_by_app(fta_application_id):
"""
通过fta_application_id获取cc_id
"""
app = session.query(AlarmApplication).filter_by(
app_id=fta_application_id,
is_deleted=False,
is_enabled=True).first()
if app:
return app.cc_biz_id
else:
return None | 5,317,962 |
def get_csv_filename(folder="zips"):
"""
Returns the Path of the csv-file stored in zips-folder
"""
csvs = [f for f in Path(folder).iterdir() if f.suffix == ".csv"]
if len(csvs) >= 1:
return csvs[0]
else:
logger.error(f"CSV-file missing")
raise FileNotFoundError("CSV-file... | 5,317,963 |
def generate_random_id(start: str = ""):
"""
Generates a random alphabetic id.
"""
result = "".join(random.SystemRandom().choices(string.ascii_lowercase, k=16))
if start:
result = "-".join([start, result])
return result | 5,317,964 |
def add_supplementary_xml(element: etree, config: dict) -> etree:
"""Add arbitrary xml from configuration object to xml
Args:
element (etree): original xml document
config (dict): standard ReadAlong-Studio configuration
Returns:
etree: xml with supplemental markup
"""
if "x... | 5,317,965 |
def get_client_names(worksheet) -> list:
"""Get list of client names from Excel worksheet."""
num_rows = worksheet.max_row
names = []
for i in range(2, num_rows+1):
cell_obj = worksheet.cell(row=i, column=1)
if cell_obj.value not in names:
names.append(cell_obj.value)
r... | 5,317,966 |
def as_json(dictionary):
"""
Object hook used in order to create the right object reading a JSON.
:param dictionary: Dict, Dictionary to analyze.
:return: The right object represented in the JSON.
"""
if "first_name" in dictionary:
return User(**dictionary)
elif "update_id" in dictio... | 5,317,967 |
def coefficient_map(cv: xr.DataArray) -> xr.DataArray:
"""
Return the coefficient map
:param cv: cost volume
:type cv: xarray.Dataset, with the data variables cost_volume 3D xarray.DataArray (row, col, disp)
:return: the coefficient map
:rtype : 2D DataArray (row, col)
"""
row = cv.coor... | 5,317,968 |
def transpose(a, axes=None):
"""
Reverse or permute the axes of an array; returns the modified array.
For an array a with two axes, transpose(a) gives the matrix transpose.
Parameters
----------
a : array_like
Input array.
axes : tuple or list of ints, optional
If specified... | 5,317,969 |
def post_token():
"""
<url>/notifications/api/PushToken
Get Device Tokens for notifications
"""
token = request.json.get('token')
deviceId = request.json.get('deviceId')
user = User.query.filter_by(token=token).first()
device = DevicesNotificationHandlers.query.filter_by(user_id=user.i... | 5,317,970 |
def run_module():
"""Run module for processing NCHS mortality data."""
params = read_params()
export_start_date = params["export_start_date"]
if export_start_date == "latest": # Find the previous Saturday
export_start_date = date.today() - timedelta(
days=date.today().weekday() +... | 5,317,971 |
def get_timestamp() -> str:
"""
Получение текущей временной метки
"""
return datetime.datetime.now(pytz.utc).strftime('%Y.%m.%d %H:%M:%S %z').strip() | 5,317,972 |
def as_anno(class_id, x_center, y_center, w, h, Win, Hin):
"""
Construct an BramBox annotation using the basic YOLO box format
"""
from brambox.boxes.annotations import Annotation
anno = Annotation()
anno.class_id = class_id
anno.x_top_left = (x_center - w / 2) * Win
anno.y_top_left = (y... | 5,317,973 |
def parse_testcase_xml(testcase):
"""
Flatten fields of interest from a TestCase XML element into a dict,
where anything not found is None
"""
# We need to emit only Unicode things, but we may get str or Unicode
# depending on if the parser thinks we have UTF-8 or ASCII data in a field.
... | 5,317,974 |
def build_coco_results(dataset, image_ids, rois, class_ids, scores):
"""Arrange results to match COCO specs in http://cocodataset.org/#format
rois: [num_instance, (y1, x1, y2, x2, class_id)] in image coordinates.
image_ids: [num_instances]
class_ids: [num_instances]
scores: (optional) confidence sc... | 5,317,975 |
def get_instance_ip(compute_url, instance_id, token):
""" Retrieve the IPs of the running instance """
url = "%s/servers/%s/ips" % (compute_url, instance_id)
headers = {"X-Auth-Token": "%s" % token, "Content-type": "application/json"}
curl = requests.get(url=url, headers=headers)
if curl.status_c... | 5,317,976 |
def _domain_map(z, satu, mapType=0):
"""domain color the array `z`, with the mapping
type `mapType`, using saturation `s`. Currently
there is only one domain coloring type
"""
h = _hue(z)
s = satu*_np.ones_like(h, _np.float)
v = _absolute_map(_np.absolute(z))
hsv_map = _np.dstack((h, s, ... | 5,317,977 |
def provider(provided_dependency_name: _Name = None,
**named_dependencies: _Name) -> Callable[[_ProviderMethod], _ProviderMethod]:
"""
Method decorator for instance provider methods in a module class. The provider method can take
parameters representing dependencies, just like the "@inject()" d... | 5,317,978 |
def _num_to_words(num):
"""
Turkish converter
Params:
num(int/long): number to be converted
Returns:
wordString
"""
units = ['', u'bir', u'iki', u'üç', u'dört', u'beş', u'altı', u'yedi', u'sekiz', u'dokuz']
teens = ['', u'onbir', u'oniki', u'onüç', u'ondört', u'onbeş', u'on... | 5,317,979 |
def get_vehicle_txn(session, vehicle_id):
"""
For when you just want a single vehicle.
Arguments:
session {.Session} -- The active session for the database connection.
vehicle_id {String} -- The vehicle's `id` column.
Returns:
{dict} or {None} -- Contains vehicle information fo... | 5,317,980 |
def celery_haystack_update_index(apps=None, **kwargs):
"""
A celery task class to be used to call the update_index management
command from Celery.
"""
defaults = {
'batchsize': settings.CELERY_HAYSTACK_COMMAND_BATCH_SIZE,
'age': settings.CELERY_HAYSTACK_COMMAND_AGE,
'remove':... | 5,317,981 |
def slugify(value):
"""
Slugify a string (even if it contains non-ASCII chars)
"""
# Re-map some strings to avoid important characters being stripped. Eg
# remap 'c++' to 'cpp' otherwise it will become 'c'.
for k, v in settings.OSCAR_SLUG_MAP.items():
value = value.replace(k, v)
# ... | 5,317,982 |
def _read_stdin():
"""
handles piped in data
"""
try:
Stream(sys.stdin.buffer).decode()
except:
try:
stuff = sys.stdin.buffer.read()
cue = Cue(stuff)
cue.decode()
cue.show()
except:
pass | 5,317,983 |
def set_group_active_status(user, group_id, status):
"""
This sets the group active status to True or False
:param user: User who wants to set this group status flag
:param group_id: id of the group for which the active status to be set
:param status: True or False
:return:
"""
group = g... | 5,317,984 |
def song(karaoke=False):
"""
Listen to the Gammapy song.
Make sure you listen on good headphones or speakers. You'll be not disappointed!
Parameters
----------
karaoke : bool
Print lyrics to sing along.
"""
import webbrowser
import sys
webbrowser.open('http://gammapy.o... | 5,317,985 |
def upper(value: str): # Only one argument.
"""Converts a string into all uppercase"""
return value.upper() | 5,317,986 |
def _create_sorted_hash_list(data: Dict, hash_function: str) -> List[Dict]:
"""Create a sorted sha256 hash list."""
out = []
for obj in data:
hash = _create_json_hash(obj, hash_function=hash_function)
out.append(hash)
out.sort()
return out | 5,317,987 |
def disease_function_subset(ipa, network_dir, printing=False):
"""
Returns a disease subset of functions. A function is considered a
disease if its lowercase name is the same as its class and its name is
not a function category. Build must be run first
"""
disease_names = set()
for function ... | 5,317,988 |
def map_tensor(x, func):
"""
Apply function @func to torch.Tensor objects in a nested dictionary or
list or tuple.
Args:
x (dict or list or tuple): a possibly nested dictionary or list or tuple
func (function): function to apply to each tensor
Returns:
y (dict or list or tu... | 5,317,989 |
def get_keyname_to_fingerprint():
"""Get a map of pub key filename to fingerprint"""
trusted_keys_dir = get_trusted_keys_dir()
filepath = os.path.join(trusted_keys_dir, _KEYNAME_TO_FINGERPRINT_FILE)
with open(filepath, "r") as fi:
keyname_to_fingerprint = json.load(fi)
for keyname, fingerpri... | 5,317,990 |
def xor(a,b):
""" XOR two strings of same length"""
assert len(a) == len(b)
x = []
for i in range(len(a)):
x.append( chr(ord(a[i])^ord(b[i])))
return ''.join(x) | 5,317,991 |
def _add_bls_key_to_validator():
"""
Assumes past staking epoch by definition of adding keys to existing validator
"""
_verify_account_balance(0.1 * len(node_config["public-bls-keys"])) # Heuristic amount for balance
chain_val_info = get_validator_information()
bls_keys = set(x.replace('0x', ''... | 5,317,992 |
def wmts2twmsbox_scale(scale_denominator, col, row):
"""
Returns TWMS equivalent bounding box based on TILECOL and TILEROW.
Arguments:
scale_denominator -- WMTS scale denominator value from getCapabilities.
col -- WMTS TILECOL value.
row -- WMTS TILEROW value.
"""
print ... | 5,317,993 |
def get_hash(x, length=16):
"""Return hash of x."""
return hashlib.sha224(yaml.dump(dict(key=x)).encode()).hexdigest()[:length] | 5,317,994 |
def make_unhealthy():
"""Sets the server to simulate an 'unhealthy' status."""
global _is_healthy
_is_healthy = False
template = render_template('index.html',
hostname=gethostname(),
zone=_get_zone(),
template=... | 5,317,995 |
def filtreDonner(liste) :
"""
Fonction qui va filtrer les donner.
Cette fonction va filtrer les donners inutiles mot trop frequent ...
param : liste[string] -> liste chaine de caractere a filtrer
return : liste[string] -> liste chaine de caractere filtrer.
"""
return liste | 5,317,996 |
def convert_to_recordio_files(data_frame, dir_name, records_per_shard):
"""
Convert a pandas DataFrame to recordio files.
Args:
data_frame: A pandas DataFrame to convert_to_recordio_files.
dir_name: A directory to put the generated recordio files.
records_per_shard: The record number... | 5,317,997 |
async def _(bot: Bot, event: GroupMessageEvent, state: T_State = State()):
"""
/sp+ 增加本群词条
"""
msg = str(state['_prefix']['command_arg'])
sp_write = await approve.write(str(event.group_id), msg)
gid = str(event.group_id)
status = await check_func_status("requests", str(gid))
if status:
... | 5,317,998 |
def get_include():
"""
Return the directory that contains the dpctl *.h header files.
Extension modules that need to be compiled against dpctl should use
this function to locate the appropriate include directory.
"""
import os.path
return os.path.join(os.path.dirname(__file__), "include") | 5,317,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.