content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import numpy
def pack_sequence(sequence: numpy.ndarray) -> numpy.ndarray:
"""
Pack a sequence of signed integers to its binary 8-bit representation using numpy.
:param sequence: the integer sequence to pack (in the form of a numpy array, ndarray)
:return: the sequence packed in 8-bit integer in the f... | 96492c4fca50781f0f5468be36eefe14e21ac32e | 649,470 |
from typing import Iterable
def prep_sequence(value: str) -> Iterable[str]:
"""Split a sequence string into its component items.
Flex `notes` attribute is semicolon-delimited; other sequences use commas.
Empty string input interpreted as null data; returns empty list.
"""
sep = ";" if ";" in val... | b529f54f1c8ca820c5590106badb75b47c4cdbaa | 649,471 |
from typing import List
def remove_failed_ida_output(lines: List[str]) -> List[str]:
"""
Args:
lines: log output from IDA
Returns:
the log output but with failed IDA output removed
"""
result = []
ida_output = []
for line in lines:
if line:
ida_output.... | 407b15ea9cda17681e48fbd5df749e13f5f548a0 | 649,472 |
def getKeyOrderAndColNames(params, visibility):
"""Retrieve key order and col names
"""
key_order = ["key"] + params.get('%s_field_keys' % visibility)
col_names = ["Key"] + params.get('%s_field_names' % visibility)
ignore = params.get('%s_field_ignore' % visibility, [])
for field in ignore:
if field n... | d0f3883ebfb352890657b757d2cf6f68d9b064ab | 649,473 |
def get_expression(text, begin, separator):
"""Find the end of a expression or statement
An expression or statement ends at a new-line or at the separator,
unless the new-line or separator is encountered inside a string-literal or
inside matching bracket pairs.
@param text The total text being pars... | e7f04d67121f0d26732149654132b6e65fbb0b96 | 649,474 |
import json
def json_for(data):
"""
Serialize data to JSON.
"""
return json.dumps(data, indent=4, sort_keys=True) | 7c7f6446d656da3a5c46a982d3be55b1510d1334 | 649,475 |
def sign(x: float):
"""Sign function.
Parameters
----------
x
"""
return -1 if x < 0 else (1 if x > 0 else 0) | 37bf78bf2987b40b2ad976d6e77b5e0d7e0125bc | 649,476 |
import os
def _make_pipe_pair():
"""
Make two pipes, and return tuples of the read and write pairs.
:returns: Read/write pairs for the two pipes.
"""
r1, w1 = os.pipe()
r2, w2 = os.pipe()
return (r1, w2), (r2, w1) | 8437627e65c9b36e11000b5bbfa26d9d5c30d8d0 | 649,477 |
def create_fifo_queue(
env,
queue_name,
content_based_deduplication=False,
message_retention_period=None,
visibility_timeout=None,
redrive_policy=None,
):
"""
Create a new FIFO queue. Note that queue name has to end with ".fifo"
- "content_based_deduplication" turns on automatic con... | be5bf39b6c1fa3ff46e9dae552580ec9ff65c0c5 | 649,478 |
def add(lh_arg, rh_arg, neg=False):
"""Helper function to sum arguments.
Negates rh_arg if neg is True.
"""
if rh_arg is not None and neg:
rh_arg = -rh_arg
if lh_arg is None and rh_arg is None:
return None
elif lh_arg is None:
return rh_arg
elif rh_arg is None:
... | 4818f0ed98f0c0cd59f95c391ae4ac750a3fa00f | 649,479 |
def luhn(card):
""" Credit Card Validator with Mod 10, or Luhn algorithm
refering to it's creator 'Hans Peter Luhn' """
# return sum(map(int, str(card)[1::2]+str(card)[0::2]*2))%10==0
card=str(card).replace(' ','')
return (sum(map(int, str(card)[1::2])) + \
sum(sum(map(int, str(i*2))) fo... | e3d9673f31bc8b831caa895eaf4f4aa09c477430 | 649,480 |
import csv
def load_map_data(file):
"""
:param file:
:return:
"""
environment_bounds = []
with open(file, 'r', encoding='utf8') as fin:
reader = csv.reader(fin, skipinitialspace=True, delimiter=',')
raw_bounds = next(reader)
while raw_bounds:
x_coordinate... | 3d3533a953ec8ed002012a36a60ee9b2d95a2686 | 649,481 |
def compute_avg_img(restyle):
""" Compuate the average image that is used
to append to the input image. The code snippet
is copied from coach_restyle_psp.py
Args:
restyle: the trained restyle encoder
and stylgan decoder
"""
restyle.latent_avg = restyle.decoder.mean_laten... | 35fb281aac5d83745ba1f044cad9eb82abc10b00 | 649,482 |
def get_category_id(class_id):
"""
:param: class id which corresponding coco.names
:return: category id is used in instances_val2014.json
"""
if class_id >= 0 and class_id <= 10:
class_id = class_id + 1
elif class_id >= 11 and class_id <= 23:
class_id = class_id + 2
elif clas... | ba2e656b815c32925d63a74f25859a995516365c | 649,485 |
def popget(d, key, default=None):
"""
Get the key from the dict, returning the default if not found.
Parameters
----------
d : dict
Dictionary to get key from.
key : object
Key to get from the dictionary.
default : object
Default to return if key is not found in dict... | df430a146f83186102ac5c87133faf190ff2af8a | 649,486 |
def get_grad_norm(model, norm_type=2):
"""Get the norm of the model weight gradients"""
norm = 0
for p in model.parameters():
norm += p.grad.data.norm(norm_type).item() ** norm_type
return norm ** (1. / norm_type) | 06638876ff408e86d25f944e603c7437fb7e5890 | 649,487 |
def is_even(x):
"""
takes an integer input
outputs true if int is even
else outputs false
"""
return x%2==0 | dfb2882b7c1af7cddf767c1a45622043e36da773 | 649,488 |
import math
def vehicle_to_bbox(linear_velocity, angular_velocity, transform, angle, dt):
"""
Transform vehicle to a bbox, knowing velocity and position
"""
vehicle_width = 1.7
vehicle_length = 4.4
abs_vel = math.sqrt(pow(linear_velocity.x,2) + pow(linear_velocity.y,2))
x_dt = transform.l... | f92193feb962ab4e6751e64ba026e1c6e2953275 | 649,489 |
import os
import subprocess
def rasterize_opts(shp_in, fpath, fname, out_tif_val, pix_res, ext, outter_vals):
"""
:param shp_in: shapefile to be rasterised
:param fpath: output filepath
:param fname: output fileanme
:param out_tif_val: value to burn into new raster
:param pix_res: output pixel... | f44b04e3c8cb61b43629ca728befaca386509e3c | 649,490 |
def get_ui_confirmation(message: str):
"""
Get user confirmation to a message
:param message: Message displayed to the user
:type message: ``str``
:return: User answer: (True: yes False: no)
:rtype: :``bool``
"""
print(message + " y/n")
while 1:
answer = input()
if ... | c49a6aaf724c784c874c029316263cabd5a0176f | 649,491 |
def extract_lexicon(spacy, parsed_data):
"""
extracts the lexicon from the parsed data.
Keyword arguments:
spacy -- Spacy model to use.
parsed_data -- the parsed text to extract lexicon from.
Returns:
list - a list of the lexicon inside parsed_data.
"""
lexicon = []
for token i... | 47e595479b46b53c2e266dd024768e864d85ba7e | 649,492 |
import yaml
from typing import OrderedDict
def obj_to_yaml(root, outf=None, encoding="UTF-8", process_string=None):
"""
Output an XML plain object to yaml.
Output an object to yaml with some specific
management for OrderedDict, Strings and Tuples.
The specific treatment for these objects are
... | d56eb984b2c70d8dda1b1f14083dbba3ecdaa6b7 | 649,493 |
import subprocess
from datetime import datetime
def get_alignment_start_times(mp4_file, mp4Box_exe = 'bin/MP4Box'):
"""
Captures chapter timestamps from mp4 file
to be used for aligning subtitle times
"""
result = subprocess.run([mp4Box_exe, '-dump-chap-ogg', mp4_file, '-out', '/dev/stdout'],
... | bcd14eb91cd66db788ce8fce46d7e2922aad4f79 | 649,494 |
def gen_l_hpu(i_headers):
"""
# Treat columns as if it is a batch of natural language utterance with batch-size = # of columns * # of batch_size
i_headers = [(17, 18), (19, 21), (22, 23), (24, 25), (26, 29), (30, 34)])
"""
l_hpu = []
for i_header in i_headers:
for index_pair in i_header... | c60f24adc28a627c6989f70ffe30917b8e29e61c | 649,495 |
import os
import logging
def create_directory(path, yyyy_mm_dd, identifier=""):
"""create string for new directory name based on timestamp and optional identifier"""
path = path + "/" + yyyy_mm_dd
try:
new_directory = os.mkdir(path)
logging.info(path + " directory created.")
except Fil... | 665581fc16483885c9abc2cfc49bd5b3ab39f184 | 649,497 |
def getClosestUpstream(locus, genes):
"""
:param locus: BedTool object with only one position defined
:param genes: BedTool object with all the gene annotations in bedformat
:return: tuple of strings (gene_name(s),dist,strand)
"""
theclosest = locus.closest(genes, io=True, fu=True, D="a", d=Tru... | b5e73483b3a7f459907071ec465dfb4badec4143 | 649,498 |
def find_api_id(api_gateway_client, api_name):
"""
:param api_gateway_client: the client to use
:param api_name: the API to find
:return: the API ID of a unique API name; raises an error if there none or too many APIs with that name
"""
# Do use a paginator if you have a large number of APIs wit... | dd70caa6304e98d27f3f34cc6fec9b234d77cf1f | 649,500 |
async def index():
""" returns index page """
return "see /docs for the api" | a50afb3d6d0f64fd38d5f9f227b2356e5fe753b3 | 649,501 |
import sys
import os
import string
import glob
import re
def findLibrary(name):
"""Look for a library in the system.
Emulate the algorithm used by dlopen.
`name`must include the prefix, e.g. ``libpython2.4.so``
"""
assert sys.platform == 'linux2', "Current implementation for Linux only"
lib... | c2d51d7fecef52edf1f7659255b1d1b6a5a687df | 649,502 |
import random
def randomCityCoordinate(cityNum):
"""
随机产生城市坐标
:param cityNum: 城市数量 int
:return: 指定数量的城市坐标 list
"""
coordinate = []
while len(coordinate) < cityNum:
temp = (random.randint(0, cityNum * 2), random.randint(0, cityNum * 2))
if(coordinate.count(temp) == 0):
coordinate.append(tem... | 5e7bf35b01694669683deea47b7e1064298bef20 | 649,503 |
def error_logger(error_log, msg):
"""Logs errors and their arguments on a list and also prints them to the console"""
error_log.append(msg + '\r\n')
print(msg)
return None | 3496596c944daedbde1845fa2f03926282c2ced3 | 649,504 |
from random import choice
import logging
def complex_state_generator_bravo(last_state=''):
"""Pick a state."""
states = ['ALPHA', 'BRAVO', 'BRAVO', 'DONE']
if last_state:
states.remove(last_state) # Slightly lower chances of previous state.
state = choice(states)
logging.info('Generati... | 84635cd72413f01efaaa3c84d2815cf75afee171 | 649,505 |
from functools import reduce
import operator
def sum_seq(seq, fn=None):
"""Sum the elements seq[i], or fn(seq[i]) if fn is given.
Ex: sum_seq([1, 2, 3]) ==> 6; sum_seq(range(8), lambda x: 2**x) ==> 255"""
if fn:
seq = map(fn, seq)
return reduce(operator.add, seq, 0) | 86de138315e39577d61f2e68a9f0b5808f09eff3 | 649,508 |
def get_container_metrics(dcos_api_session, node: str, container_id: str):
"""Return container_id's metrics from the metrics API on node.
Retries on error or non-200 status for up to 30 seconds.
"""
response = dcos_api_session.metrics.get('/containers/' + container_id, node=node)
assert response.s... | 59cb8aa21f276b09b2cde7d520d1526067dcf0f3 | 649,510 |
from typing import List
def is_hat_shaped(learning_rates: List[float]):
"""
Check if the list of learning rates is "hat" shaped, i.e.,
increases then decreases
"""
# sufficient conditions:
# has both an increasing and decreasing segment
# decrease segment occurs after increasing segmen... | 5da66f5a367ccc75c82972d89dc5a92e875c409d | 649,511 |
def extractNodeParent(node, parentrefs):
"""Return a tuple of the most likely (parent, parentReference). The
parentReference is removed form the inverse references list of the node.
"""
for ref in node.inverseReferences:
if ref.referenceType in parentrefs:
node.inverseReferences.rem... | 69a12b02f2506588351fed0d3a7b45970d499a1b | 649,512 |
def isdivisor(number: int, divisor: int) -> bool:
"""
判断一个数是否为约数
:param number: 被求数
:param divisor: 约数
"""
return (number % divisor) == 0 | 61afc336ba5d2b2fdaa6df9a833bdd12dca65564 | 649,513 |
from unittest.mock import Mock
def mock_hass():
"""Hass mock with minimum amount of data set to make it work with auth."""
hass = Mock()
hass.config.skip_pip = True
return hass | cd29106cb2f34b2355fb3c15f309877a04b8ffb8 | 649,514 |
def is_subclass(obj, superclass):
"""Safely check if obj is a subclass of superclass."""
try:
return issubclass(obj, superclass)
except Exception:
return False | 4812f0e245546446256d0d2e9a305167e87da08d | 649,515 |
def test_ccall_method(x):
"""
>>> test_ccall_method(Overidable())
0
>>> Overidable().meth()
0
>>> class Foo(Overidable):
... def meth(self):
... return 1
>>> test_ccall_method(Foo())
1
>>> Foo().meth()
1
"""
return x.meth() | cf1ca39e74f534fb7200f0b40917255a780b8c32 | 649,516 |
def is_contributor(user):
"""Return whether the user is in the 'Registered as contributor' group."""
return (
user.is_authenticated and user.groups.filter(name="Registered as contributor").count() > 0
) | 843aebd7aeb924188136e00ac14b710305b1cfb8 | 649,517 |
import re
def get_rate(string: str) -> str:
"""Parse sting for pay rate
string: string representations of pay test_parse_rate_string
raises: ValueError:If cannot find numeric pay rate
"""
currency_regex = r'\d+(\.\d+)?'
match = re.search(currency_regex, string.replace(',', ''))
if not ma... | 967eb48b0ee19a25686e8a7d7f0857eded4c1cd8 | 649,518 |
def find_count_to_turn_out_to_all_zero_or_all_one(string):
"""
:param string: 0과 1을 포함하는 문자열
:return: 모든 1 또는 모든 0이 되기 위한 최소 변환 횟수
"""
count_to_zeros = 0
count_to_ones = 0
if string[0] == '0':
count_to_ones += 1
else:
count_to_zeros += 1
for i in range(len(string) ... | db5b64d87aaadc55cda902fbb2dee24206b59e9b | 649,519 |
def drop_shadow(p):
"""右下に影が落ちるような座標"""
return p, (p[0]+1, p[1]), (p[0], p[1]+1), (p[0]+1, p[1]+1) | 6fce3e876a5b1fa4c1bb27d8b38ae125b7f87f81 | 649,520 |
def extract_initials(*forenames):
"""Return a list of initials for each name in the given forenames.
"""
initials = []
# To handle varargs
for forename in forenames:
# Allow polymorphism: forenames can be str or sequence of str
try:
names = forename.split()
except... | eb28b5ff9d363621e460111094d051780d40838a | 649,522 |
from typing import List
def join(row: List[List[str]]) -> List[str]:
"""Join together a row of puzzle pieces into a complete list of lines"""
res = []
for i in range(len(row[0])):
res.append('│')
for piece in row:
res[i] += piece[i]
return res | bfc5f701ed9f0ed611a92998c423870a00c60b4e | 649,523 |
def post_match(view, name, style, first, second, center, bfr, threshold):
"""Ensure that backticks that do not contribute inside the inline or block regions are not highlighted."""
if first is not None and second is not None:
diff = first.size() - second.size()
if diff > 0:
first = ... | 01d68d923c92a3faa22bfb121e71587ce5941ee1 | 649,525 |
def inv_to_dict(inventory):
"""Convert an inventory to a simple cost->number dict."""
return {pos.units.currency: pos.units.number for pos in inventory} | ef9395f477bcb66f7c062dd02b4e704bf0928282 | 649,526 |
def format_as_vars_file_param(pathname):
"""Accepts a pathname and returns a string formatted as a valid terraform var-file include argument"""
return "-var-file={pn}".format(pn=pathname) | 844f06ad1ea8617ed2c51fd45224cc71b510a203 | 649,527 |
import getpass
def get_source_config():
"""
Get details of the source database (Oracle)
"""
print('\n------------------------------------------')
print('Enter source database settings:')
print('------------------------------------------')
config = {}
config['username'] = input('- User... | 507c0d68f4da0dedef604415d78b904d2ed1dc96 | 649,529 |
def calc_score(n_true_positives, n_truth, n_pred):
"""
# Args
detect_boxes : list of box-arrays
true_boxes : list of box-arrays
"""
precision = n_true_positives / max(n_pred, 1e-5)
recall = n_true_positives / max(n_truth, 1e-5)
if precision + recall == 0:
fscore = 0
e... | 1e6fdf883e4c21ce21f395083f64c7ba79c44057 | 649,530 |
def word_capitalize(word: str) -> str:
"""Capitalize the first letter of every word within a sentence."""
return ' '.join(map(str.capitalize, word.split())) | 2b693cd12413bb8aea8f705b8a4744f5eabedd58 | 649,531 |
import requests
def get_table_data(endpoint_url, endpoint_params, api_keys, **context):
"""
gets data at endpoint
"""
table_data = []
for i, k in enumerate(api_keys):
api_key = k['apikey']
school_name = k['school']
payload = {'apikey':api_key}
payload.update(endpo... | e59cdfe146054191a030613c3d829046ee12f4df | 649,532 |
def make_line(move):
"""(str) -> str
Determines the line between two dots specified in the string <move>
The <move> parameter is one of '01', '12', '03' etc. representing a line
connecting the dots in the pattern;
0---1---2
| | |
3---4---5
| | |
6---7---8
... | 20319fc50e90fdb20df90bf24bf10398119eb75d | 649,533 |
def user_dict(user_l):
""" list(dict) -> dict """
id_user = {}
for u in user_l:
id_user[u['custID']] = u
return id_user | cbe805d6df20ae136111787fba52e527a316b0e7 | 649,534 |
def driver_function(prices,n):
"""The driver holds the lookup dictionary and makes the original function call to rodcut function.
"""
dict = {}
def rodcut(prices,n):
"""
Note:
this function was found in C++ on: https://www.techiedelight.com/rot-cutting/
In... | b36ffce50a6dadc21fbd5315ef353f2105fbaccb | 649,536 |
def get_entity_name(battle, entity):
"""
Determine the identifying string name of the given entity in the battle.
Arguments
---------
battle : Battle
The Battle instance representing the battle.
entity : CombatEntity, Player
The entity to determine the name of.
... | 3056608646f8dba3e0ea3310316b79397f5e6574 | 649,537 |
def get_redirect_url(request, path=None):
"""Get redirect url for cas"""
scheme = request.scheme
host = request.get_host()
if path:
url = "{}://{}{}".format(scheme, host, path)
else:
url = "{}://{}".format(scheme, host)
return url | b5f81ae466a92f1cccbf5b67476d84ff97fb70f8 | 649,538 |
import uuid
def get_random_id() -> str:
"""
Generate a random ID string. The random ID will start with the '_'
character.
"""
# It is very important that these random IDs NOT start with a number.
random_id = '_' + uuid.uuid4().hex
return random_id | ad60f4618bdb13ea30f9b5fffef51d793c84973f | 649,540 |
import numpy
def concatenate_transforms(*args):
"""Merge multiple transformation matrices into one."""
M = numpy.identity(4, dtype=numpy.float64)
for i in args:
M = numpy.dot(M, i)
return M | f62214326a314d9d079b94ec82839042825f3801 | 649,541 |
def allowed_xml_tag_fragments():
"""
tuples of whitelisted tag startswith values for matching tags found in inline text
prior to being converted to HTML
values can be a complete tag for exact matching just the first few characters of a tag
such as the case would be for mml: or table td tags
"""
... | c1319c02d067e00869a4f4db3e082931f83e3655 | 649,543 |
def config_section_data():
"""Produce the default configuration section for app.config,
when called by `resilient-circuits config [-c|-u]`
"""
config_data = u"""[fn_docker]
# A comma separated list of approved images that can be used. May not be blank.
docker_approved_images=volatility,nsrl,amass
# ... | fbf4b5170d9d8aa52a7157cf44e61bf76d455f05 | 649,545 |
def set_user_password(client, profile, user, password="N0t-permanent!"):
""" Sets the specified user's password """
try:
response = client.admin_set_user_password(
UserPoolId=profile["user_pool_id"],
Username=user.email,
Password=password,
Permanent=False,... | 95645a25341f92400af87faf5f81b59652817966 | 649,546 |
def encode_date(o):
""" Encodes a Python datetime.date object as an ECMA-262 compliant
date string."""
return o.isoformat() | df3fcd5ae1e66a7ac59ad3f9c9ed96743279892b | 649,547 |
import os
def _dir_or_none(path):
"""Returns None if path does not exist."""
if os.path.isdir(path):
return path
return None | ede889ca2ee934b35bfaba05beb2ea45662b0e1e | 649,548 |
import functools
def elect_if_no_active_ep(func):
"""if there is no active endpoint, we will elect one before function"""
@functools.wraps(func)
def _wrapped(self, *args, **kwargs):
if not self.active:
self.elect()
return func(self, *args, **kwargs)
return _wrapped | 7113501b9664038581a27abd1b2add1a16e404ec | 649,549 |
def format_discord_link(link: str, guild_id: int):
"""
Format a discord link to a channel or message
"""
link = link.lstrip("<").rstrip(">").rstrip("/")
for prefix in (
f"https://discord.com/channels/{guild_id}/",
f"https://www.discord.com/channels/{guild_id}/",
):
if li... | 5f4a37d90b8f9adcb2483174e1e3ed271dd0ed44 | 649,550 |
from datetime import date, timedelta
from urllib.request import urlopen
from bs4 import BeautifulSoup
def current_rate(ccy_rq_id):
"""
Функция возвращает кортеж из двух элементов: курс валюты и разница с предыдущим курсом.
ccy_rq_id с значением "R01235" -- это USD
:type ccy_rq_id: str
"""
#... | 47835e5891f1446025f80165661fbda85f52a041 | 649,551 |
def get_species(df):
"""Return species of top hit from input DataFrame
of Mash results."""
try:
species = df.sort_values("Mash-distance").loc[0, "species"]
return species
except KeyError:
print("Can't find the species in the input mash_dict!") | 0df34487353d8461f80ba43b0b2f132e03c7bbff | 649,552 |
def locus_tag(ncrna):
"""
Get the locus tag of the gene, if present.
"""
return ncrna.get("gene", {}).get("locusTag", None) | 76e39c3904e3d2621d253f8f59cd0e8640f18ef7 | 649,553 |
def triangle_area(base, height):
"""Returns the area of a triangle"""
base = float(base)
height = float(height)
if (base < 0.0 or height < 0.0):
raise ValueError('Negative numbers are not allowed')
return base * height / 2.0 | cdcbd9cb01044dea0bbfbb028d5a4ccad96ea78f | 649,554 |
import math
def printXYZDegrees(self):
"""Print X, Y, and Z components in degrees."""
return ("[%f, %f, %f]" % (math.degrees(self.x), math.degrees(self.y), math.degrees(self.z))) | 8f48563c13e170a18b1c9a9e6385a842e307d177 | 649,555 |
def substitui_x_por_branco(gray):
"""
Localiza todas as posições em que há um X 3x3 na imagem de entrada e pinta estas posições com tom de cinza 127.
Na saída deve ficar um quadrado cinza onde havia X
"""
res = gray.copy()
return res | 3e67c9ef91a142dd680b47eaa673ff725a456110 | 649,556 |
def level_0():
"""Compute the calculation 2^38."""
return 2 ** 38 | 09be69c8e88f7b23765ad6204820185b5c2ba3f6 | 649,557 |
import itertools
def fast_filter(msgs):
"""
Grabs an arbitrary subset of 100 messages from the stream.
Convenient for fast testing.
"""
return itertools.islice(msgs, 100, 1100, 10) | b996f0f9e7dfbc437e29407ad4a1eab7afedb79d | 649,558 |
def float_general_format():
"""Float general format representation. Default float format."""
return "({0:.2g}, {1:.2g}) or ({0:.2g}, {1:.2G})".format(1/3, 10**-9/3) | 4e2d9bce08c4d366ce71d6d8038d5106635dcee3 | 649,561 |
def suspend_ha(fw_conn):
"""Suspend HA
Args:
fw_conn (PanDevice): A panos object for device
Returns:
results (Element): XML results from firewall
"""
command = ('<request><high-availability><state><suspend>'
'</suspend></state></high-availability></request>')
res... | 85b0cae258b29be6cebe83133233d27da0f77e0e | 649,562 |
def api_info():
"""Entry point into backend API."""
return "This is the Metador backend. If you see this, then you are authenticated." | 470297e465c90dbf2c81a264c06414423dfbb3ff | 649,563 |
import argparse
def get_params():
"""Returns the command line arguments."""
parser = argparse.ArgumentParser(description="""
This script takes an input of a gff file (usually generated by Prokka) with a
##FASTA section containing the sequence data, rotates the sequences to their
repli... | 9884fd77c94a67d8a1ef2371660bd6e5b7a904ca | 649,564 |
def array_to_text(arr, n):
"""Convert f1 results into readable text"""
txt = list(arr) # transform array to list
if n == 3:
txt = ["%.3f" % item for item in txt] # format decimals
else:
txt = ["%.0f" % item for item in txt]
return ' | '.join(e for e in txt) | 44385e2195edb61fd54c4c503e8079aa1c08daa1 | 649,565 |
import os
def get_iids_from_cvg_stat(cvg, nodenames, fullpath):
"""parse cvg st output into iid file"""
d = {}
outpath = os.path.dirname(fullpath)
taxon = os.path.dirname(os.path.dirname(fullpath)).replace('-', '_')
if '/assembly' in taxon:
taxon = os.path.dirname(taxon)
outfile_name =... | d32398d1d82f9d6ba6eeb3323f55c41cf68c1cda | 649,568 |
import os
def deconvolution_is_complete(psfs, output_prefix, im_name):
"""Check for saved deconvolution results
"""
estimate_filenames = [os.path.join(output_prefix, im_name + '_' + name +
'_estimate_history.tif')
for name in sorted(psfs.keys())]
ft_... | 01e4e262d7f8076588c1e1c1ecd6b2fc26a1348c | 649,569 |
def round_half_integer(x):
""" Rounds number to nearest floating point half integer.
Args:
x (number): quantity to be rounded
Returns:
float: number rounded to (generally exact) integer or half integer
"""
return round(2*float(x))/2 | e7f148ddd47a719b46d489c9839f3b39beffaa87 | 649,570 |
from typing import Dict
from typing import List
import sys
def unpack_meta_scraper_config(config_options: Dict) -> List:
"""Unpack meta scraper configuration."""
if config_options is False:
print("\nMissing, empty or wrongly named config file. \
Program will terminate.")
sys.exit()... | 5c58f75c7062107c01311603bdcdcd2d04692c90 | 649,571 |
def get_dimensions(response):
"""
Extract asked dimensions from api response
@list_dimensions : list of dict
"""
return response['reports'][0]['columnHeader']['dimensions'] | 6e41731276247d70c9c5b2d9ae59d427a066c2f3 | 649,572 |
def RPCCall(method):
"""Enables the method to be Umpire RPC function.
Args:
method: an unbound derived UmpireRPC class method.
Example:
class Foo(UmpireRPC):
def NonRPCFunction():
pass
@RPCCall
def RPCFunction(parameter, ...):
pass
"""
method.is_rpc_method = True
... | 5796aa3ac09c219b3dd922758b3c67879e93298e | 649,573 |
def path_from_schedule(jobs, start):
""" The evaluation is based on building the travel path.
For example in the network A,B,C with 4 trips as:
1 (A,B), 2 (A,C), 3 (B,A), 4 (C,A)
which have the travel path: [A,B,A,C,B,A,C,A]
The shortest path for these jobs is: [A,C,A,B,A] which uses the order:... | 11a9a8063dc17f8368214fd4c4dcb281eece1ff3 | 649,574 |
def _temp_analyze_files(tmpdir):
"""Generate temporary analyze file pair."""
orig_img = tmpdir.join("orig.img")
orig_hdr = tmpdir.join("orig.hdr")
orig_img.open('w+').close()
orig_hdr.open('w+').close()
return str(orig_img), str(orig_hdr) | bf834d958342a29998273197e3df9142c9a6b505 | 649,575 |
def is_all_upper(s):
"""Returns True if the whole of the string s is upper case."""
return sum(c.isupper() for c in s) == len(s) | 05b44185f9a40cdb2a54acd25a2e66845188f852 | 649,576 |
import hashlib
def hash_password_hashlib(password: str) -> str:
"""encrypt user password using hashlib
Args:
password (str): user password
Returns:
str: password encrypted
"""
return hashlib.md5(password.encode('utf-8')).hexdigest() | 3fdbdc98a5aba5eaa447be48590a8a8bed7d4c64 | 649,577 |
def sorted_dict(item, key=None, reverse=False):
"""Return a new sorted dictionary from the `item`."""
if not isinstance(item, dict):
return item
return {k: sorted_dict(v) if isinstance(v, dict) else v for k, v in sorted(item.items(), key=key, reverse=reverse)} | 169486dc9e72fd88b5325f1e8212895f44174969 | 649,578 |
def replace_spaces(s):
"""Creates a new copy to replace spaces."""
c = '%20'
t = ''
for ch in s:
if ch == ' ':
t += c
else:
t += ch
return t | 231340f59aaf066ca076441ea7d2df8aea1488bf | 649,579 |
def approx_eq(x, y, tolerance=1e-15):
"""Whether x is within tolerance of y."""
return abs(x - y) < tolerance | 8351d9b29a303df488ef2b569727fa3d8a1f0865 | 649,580 |
import typing
def transform_any_str_list(data: typing.Any) -> typing.List[str]:
"""
Helper function for transforming any type to an list of strings split by "\n"
:param data: the data to transform
:return: the transformed data
"""
if type(data) == str:
return data.split("\n")
if ty... | 9b38e6d451dc2a7e0959469e85c43591469c9cb9 | 649,581 |
import os
def findpeakpath(folder, proteiname):
"""
given a folder of bigwigs and a protein name, finds the right bigwig
"""
res = None
for val in os.listdir(folder):
if str(proteiname) in val:
if res:
raise ValueError('more than 1 bigwig file found')
res= val
if res:
return res
raise ValueError(... | 018c5d803fd1e0ab959a02e37a48ffc28398516a | 649,582 |
def node2feature(node_idx, data_shape):
"""Convert node index from CNN activation vector into 3 features including
index of channel, row and column position of the filter.
Return a tuple of (channel index, row index, column index).
"""
#data_size = {'conv1': [96, 55, 55],
# 'conv2': ... | 03e7418da417ca47f604e924d2ef59136fe34c7c | 649,583 |
def authority_and_code(valid_authority):
"""
Returns authority for httpbin and return code it should return
For the testing of connection reuse is just one valid authority sufficient.
"""
return valid_authority, 200 | 5d27483e6befef5599720533a961e204a4dff059 | 649,584 |
import itertools
def feature_engineering(df, cat_cols):
"""
This function is used for feature engineering
:param df: the pandas dataframe with train/test data
:param cat_cols: list of categorical columns
:return: dataframe with new features
"""
# this will create all 2-combinations of valu... | acb8729d29b2edf272471c0d63046960f0fffc01 | 649,586 |
def parabola_1D(xdata, a, b, c):
"""
Calculates a parabola of the form: a*(x-b)**2 + c
"""
return a*(xdata-b)**2 + c | 4b0615269136b908651b3c55486935ec283a1ba2 | 649,587 |
def remove_file_extension(file_name):
"""e.g.: remove_file_extension("hi.jpg") == "hi"
It does not mutate file_name (str is immutable anyway)
:param file_name: <str>
:return: it returns the file_name without the extension
"""
return file_name[:file_name.rindex('.')] | b16329451959063b23c92f6bafa46ccdaf0ac3b8 | 649,588 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.