content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def _get_vco(verts_orig, loop):
"""
Get vertex original coordinate from loop
"""
for vo in verts_orig:
if vo["vidx"] == loop.vert.index and vo["moved"] is False:
return vo["vco"]
return loop.vert.co | e8a0f829ca4a294b87f2e7087eb78194274ceacd | 646,413 |
def _block_len_in_section(block, section):
"""Return the length of a block in a section [start, end]."""
len_start = max(block.start, section.start)
len_end = min(block.end, section.end)
return len_end - len_start + 1 | 2cdb004d6d4ed70dd267d9fe9f37753bb5e7d95c | 646,414 |
def transformSynapseCoordinates(bboxCoordinates):
"""
Downsample bounding box coordinates
Parameters
-----------
bboxCoordinates : dict - boundingbox object created by get_anno_boundingbox()
Returns
-----------
bboxCoordinates : dict
"""
xoffset = 0 # 7096.0*3.0/100.0
yoff... | 270940688b9767380cdff3fa4f2dc49f336a2744 | 646,415 |
def spell_number(s):
""" Function to convert number to word """
n = int(s)
if n > 2 and n <= 10:
if n == 3:
return 'Third'
elif n == 4:
return 'Fourth'
elif n == 5:
return 'Fifth'
elif n == 6:
return 'Sixth'
elif n == 7... | 2c41dbe8728938cf88613cac9d25b0cca34d395c | 646,416 |
def _get_discovery_for_dmaap(get_component_spec_func, name, version):
"""Get all config keys that are for dmaap streams
Returns:
--------
Tuple of message router config keys list, data router config keys list
"""
spec = get_component_spec_func(name, version)
all_streams = spec["streams"].g... | bb2c78c59ab817391129583b1485c96c71c23c8c | 646,417 |
def shift_era5_time_coordinate(cube, shift=30):
"""Shift instantaneous variables (default = 30 minutes forward in time).
After this shift, as an example:
time format [1990, 1, 1, 11, 30, 0] will be [1990, 1, 1, 12, 0, 0].
For aggregated variables, already time format is [1990, 1, 1, 12, 0, 0].
"""
... | 9bc3efdb69c8591cc275f26218084df8680b7290 | 646,418 |
import hashlib
import os
import binascii
def hash_password(pwd: str) -> str:
"""Hashes password using salted password hashing (SHA512 & PBKDF_HMAC2)
Args:
pwd: Password to be hashed
Returns:
str: Hashed password
"""
salt = hashlib.sha256(os.urandom(60)).hexdigest().encode("ascii"... | 648a779f825bd3ce4b2eed4c245b80e618cd2d2a | 646,419 |
def wrap(command: bytes):
"""
Wrap the given command into the padding bytes \x02 and \x03
:param command: bytes
:return: padded command: bytes
"""
start = b"\x02"
stop = b"\x03"
return start + command + stop | bc31e05edecde7a95042e52c3ac9f7fd15957356 | 646,421 |
from typing import Any
import yaml
from functools import reduce
def get_config_value(keys: str) -> Any:
"""Retrieves a configuration value from the Pavo configuration file.
Args:
keys (str): The string of (nested) dictionary values.
Note:
You can find nested keys by introducing '.' in yo... | 2b760613e463b38ec0aceba8aa57c5c678f5208c | 646,422 |
import random
def get_exponential_backoff_interval(
factor,
retries,
maximum,
full_jitter=False
):
"""Calculate the exponential backoff wait time."""
# Will be zero if factor equals 0
countdown = min(maximum, factor * (2 ** retries))
# Full jitter according to
# https://www.awsarch... | c3b26aeed4267218a0698a431239f57dcbfbcf45 | 646,423 |
def split_namespace(tag):
"""returns a tuple of (namespace,name) removing any fragment id
from namespace"""
if tag[:1] == "{":
namespace, name = tag[1:].split("}", 1)
return namespace.split("#")[0], name
else:
return (None, tag) | e144cc7e693bbe2abdac26d567dbe706f40759ff | 646,424 |
def findNextOpr(txt):
"""
>>> findNextOpr(' 3* 4 - 5')
3
>>> findNextOpr('8 4 - 5')
6
>>> findNextOpr('89 4 5')
-1
"""
# decide whether the data type is correct
if not isinstance(txt, str) or len(txt) <= 0:
return "error: findNextOpr"
# use for ... | 021a9dbe59009df97939b09c4b2e0033b8fcfabd | 646,425 |
import re
import os
def dpkg_query(cmd_output):
"""
This method parse the output from the package managerand return
a dictionary with the information of the packages. This is used
when the packages are in deb format.
"""
verregex = re.compile(r' \([=<>]* [^ )]*\)')
output = dict()
pkg ... | b9617e6024c9f1f88f347a7247ec5be4cd2969a1 | 646,426 |
import re
def replace_unescaped_utf_8_chars(input_text):
"""
Unescapes characters like "ä" with their equivalents,
e.g. "ö". Only necessary to support Python 2.7+.
"""
pattern = re.compile(r"�(\w{2});�(\w{2});")
def replace(match):
byte_array = bytearray(map(lam... | c5cc78e62e01dcda4343261e840ab38aff375660 | 646,427 |
def make_dnp(pid: int, gid: int, team: int) -> list:
"""Player was labeled DNP (Did Not Play)
:param pid: (int) Player ID
:param gid: (int) Game ID
:param team: (int) Team ID
:return: (lst) Player Stats
"""
player_stat = []
player_stat.append(pid) # Player ID
player_stat.app... | 4ec4fa14747e361b3728c8fa472387426298db4f | 646,428 |
import json
def yaml_to_json(yml_object):
"""
Re-create RIPE json format from yaml
"""
construct = {
"objects": {
"object": [{"source": {"id": "RIPE"}, "attributes": {"attribute": []}}]
}
}
for i in yml_object:
construct["objects"]["object"][0]["attributes"... | 826fb375296eb425da5ff18c16bbf930a6ad4d96 | 646,429 |
from pathlib import Path
import os
import random
def main():
"""use pathlib for Python >= 3.4"""
directory = Path("main_dir", "sub_dir")
file = "example.json"
print(Path(directory, file))
# >>> "main_dir/sub_dir/example.json"
"""use os for Python < 3.4"""
directory = os.path.join("mai... | 70c5cbdd4cfeb0eb7ad1ba8658d9893c9cdd2b0a | 646,431 |
import os
def running_on_ci() -> bool:
"""Return True if running on CI machine."""
return os.environ.get("ARVIZ_CI_MACHINE") is not None | 35db37969011937d733c0793addc441651e77647 | 646,432 |
import os
def gettestdata():
"""Return a dict of the test file data."""
testdatadir = os.path.dirname(os.path.realpath(__file__))
with open(f"{testdatadir}/testdata") as testdatafile:
lines = testdatafile.readlines()
# Remove blank lines and those starting with '#'.
lines = [line for lin... | d3c7839c1cc7f1af43d96e24fa343805476ddae2 | 646,433 |
from typing import List
def get_substr_index(ls_string: List[str], substring: str) -> int:
"""
Parameters
----------
ls_string : list of strings to find the substring in
substring : the substring
Returns
-------
int of index of the first substr match in the list, -1 if the substr does... | 0e25f99e824829234dcf11259e2b8fc4ae3866d3 | 646,434 |
import heapq
def find_k_largest_numbers(nums: list[int], k: int) -> list[int]:
"""
Complexity:
Time: O(nlogk)
Space O(k)
Args:
nums: array of numbers for which to find the largest k elements
k: num largest elements to find
Returns: the k largest elements in `nums`
... | 291923a5ea9be157e599666922d6c8c69530b394 | 646,435 |
def valid_age(person, i, min_age):
"""Verify age requirement of person in given iteration."""
return person["birth"] <= (i - min_age) and person["death"] >= i | 691083b293c4537ee1dcbf65448104c366dfd575 | 646,436 |
def narrow(checked, DASHRlut):
"""Returns dictionary mapping selected DASHRs to local drives.
:param checked: array of integer pins
:param DASHRlut: dictionary mapping of all locally detected DASHRs
:returns: dictionary mapping only user-selected DASHRs
"""
for_harvest = {}
for pin in check... | d34d579a687c77c4c33d1b4fa064002e4e9e51f7 | 646,437 |
import os
def _normalize_path(path):
"""Normalize a path by ensuring it is a string.
If the resulting string contains path separators, an exception is raised.
"""
parent, file_name = os.path.split(path)
if parent:
raise ValueError("{!r} must be only a file name".format(path))
else:
... | 5a14e82cbaf0f5e074ad08c99d139bdcb810804c | 646,438 |
def read_random_points(path='random_points/random_points_random_triangles.txt'):
"""Function to read files with random points"""
points = []
with open(path, "r") as f:
while True:
split_line = f.readline().split("\t")
# if end of file is reached
if len(split_line... | 176bc921c6dd95d692bd91de899ce20044c63d3a | 646,439 |
import tempfile
def translatePath(path):
"""
Returns the translated path.
path : string or unicode - Path to format
*Note, Only useful if you are coding for both Linux and the Xbox.
e.g. Converts 'special://masterprofile/script_data' -> '/home/user/XBMC/UserData/script... | f3836cf1e3fb9e7d93441eee1ed0635bbee4c16e | 646,440 |
def factorial_pythonic(number: int) -> int:
"""Factorial with reduce function (pythonic approach).
Examples:
>>> assert factorial_pythonic(0) == 1
>>> assert factorial_pythonic(1) == 1
>>> assert factorial_pythonic(2) == 2
>>> assert factorial_pythonic(3) == 6
"""
return... | b5b9aa022f454b0f371d9108691f91b17d50588a | 646,441 |
import re
def camelcase_to_snakecase(_str: str) -> str:
"""camelcase_to_snakecase.
Transform a camelcase string to snakecase
Args:
_str (str): String to apply transformation.
Returns:
str: Transformed string
"""
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', _str)
return re.sub... | bdad95ef8e16c0197cf764656bbf739a5dafa165 | 646,442 |
def CreateNoteMap(layout):
"""Returns a MIDI note to [KeyMap] dictionary from the given Layout
message.
"""
note_map = {}
for km in layout.keymaps:
for note in km.notes:
if note not in note_map:
note_map[note] = []
note_map[note].append(km)
return ... | 2ba06ad733c78a0794d8ce9c7e56e70dd55fc842 | 646,443 |
def assign(domino_set):
"""Assigns 7 domino pieces to each player and returns each players set of tiles and the list of remaining tiles"""
player_hand = []
computer_hand = []
for _ in range(7):
player_hand += [domino_set.pop()]
computer_hand += [domino_set.pop()]
return player_hand,... | 61bdfaaf5ecc8a0fa6caee6a84b8257702da11d6 | 646,444 |
import sys
def read_job_params(job_file, require=[]):
"""Read job parameters from text table."""
job = {}
if job_file is not None:
for line in open(job_file):
if line.strip():
param, val = line.split()
# require a decimal for floats
try:
if val.find('e') != -1:
... | 35b288771d23f1e91296e1d2bd4ae1477871b2d5 | 646,445 |
def is_core(g, node, args):
"""Inline graphs that are marked as part of the core."""
return g.has_flags('core') | df4c3a9d82310f38987c871d8bf600a60043ca06 | 646,446 |
import torch
def evolution_op(t_step, energy):
"""Compute the unitary time-evolution operator for the given energy.
Parameters
----------
energy :
time_step :
"""
if isinstance(energy, list):
ev_op = [torch.exp(-1.0j * eng * t_step) for eng in energy]
else:
ev_op = to... | c3ae1fa3e3c506392d9f82e18aa9e82d617db704 | 646,447 |
import numpy
def sphere(x):
"""
The Sphere function.
Parameters
----------
x : array_like
1-D array of points at which the Sphere function is to be computed.
Returns
-------
float
The value of the Sphere function.
"""
return numpy.square(x).sum() | 89becf0b9c261cbe3076d9d41754fe4d34b3a842 | 646,448 |
import os
def read_label_as_dict(file, ext='.txt'):
"""
Reads a label file in text format as a dictionary
:param file: Name of the label file
:param ext: Name of the file extension. Defaulted to text
:return: A dictionary of the label
"""
label_content = {}
if os.path.isfile(file):
... | e17dcbc236ad77bb499a323b289c332d2ad7eba1 | 646,449 |
import re
def non_whitespaces():
"""\\S: All except whitespaces."""
return "the secret of a healthy life is {}".format(
re.sub(r'\S+', '***', "fish & chips")) | 93ca1e6cc14a170e5ba2c3eb54963c8d09874326 | 646,450 |
import os
import glob
def get_single_model_path(checkpoints_dir: str):
"""Lightning's hack to load last epoch model if available.
Args:
checkpoints_dir: directory with the image checkpoints
Returns:
Path to a single checkpoint to be loaded
"""
last_path = os.path.join(checkpoint... | d0ac4f635af6685f47029e005e4a7b5d886fdd1d | 646,451 |
def dE_swap(ij, c, W, AL):
"""
Energy differential after swapping cells i and j.
Depends only on i, j, and their neighbors
"""
new_c = c.at[ij].set(c[ij[::-1]])
E_local = -W[ c[ij, None], c[AL[ij]]].sum()
E_local_swap = -W[new_c[ij, None], new_c[AL[ij]]].sum()
return E_... | 6312651523dbe936dcc7a5129455cac9fdfa594a | 646,452 |
def sender_receiver_features(x, send_edges, recv_edges, batched=False):
"""
batched: used in dynamicvars settings
"""
if batched:
x_j = x[send_edges]
x_i = x[recv_edges]
else:
x_j = x[:, send_edges]
x_i = x[:, recv_edges]
return x_j, x_i | 44487b7f42796daf3078f51dfe7673c2716d92c9 | 646,454 |
import re
def strip_replies(payload):
"""
Gets rid of any previous emails that were appended to the end of the email we're currently looking at
Creates a list of common indicators email services use to denote a reply has started, then checks for those
in the email and deletes anything after them.
... | 02b075ee78c87f9d04c6a628d237cadca392945a | 646,456 |
def trim_tensor(tensor, start_index, length):
"""trim a tensor, given by the max length"""
return tensor[start_index:start_index+length, :] | 0374ab6657f661e15f084a9beb15ca926cff1b5c | 646,458 |
def add_doc(docstring):
"""
A decorator for adding docstring. Taken shamelessly from stackexchange.
"""
def document(func):
func.__doc__ = docstring
return func
return document | 5a84230b353734711f4f1dfb3f0d03eee146a07f | 646,459 |
import requests
def service_fetch_probes(service, proto):
"""Fetches all service probes from the given protocol"""
if service == 'pingdom':
url = 'https://my.pingdom.com/probes/' + proto
elif service == 'uptimerobot':
url = 'https://uptimerobot.com/inc/files/ips/' + proto + '.txt'
elif... | 67381e0fe9a6913e82bcaf01127ac9f85fa7a303 | 646,460 |
def order_slaves_on_gtid(slaves):
"""Function: order_slaves_on_gtid
Description: Take a Slave array and sort them on their GTID positions,
with the top(first) slave being the best Slave.
Arguments:
(input) slaves -> Slave instance array.
(output) slave_list -> List of slaves in ... | 07fdc77dea153dd02efa0bdd0cb7b71a5c223835 | 646,461 |
import sys
def regionParse(string):
"""
Parses region:start_position-end_position, returns a tuple
>>> regionParse('chr4:200000-200100')
('chr4', 200000, 200100)
"""
start = string[string.find(':') + 1:string.find('-')]
end = string[string.find('-') + 1:]
start = start.replace(',', '')... | fe1ba9c024991a6bc15675fddae7d15faa7b8a1b | 646,462 |
import json
def loadTheme(themename, path="data/themes.json"):
""" Loads the theme needed for the application to be styled """
global THEMES
THEMES = json.load(open(path, "r")) # Load all themes
try:
return THEMES[themename] # Return theme
except KeyError: # If theme doesn't exist
... | ee4bfa83817882973064cc5dce851b6a689aabd1 | 646,463 |
def clean_sheet_value(value):
"""
Takes a spreadsheet cell value and returns a cleaned version
Args:
value (str): A raw spreadsheet cell value
Returns:
str or None: A string with whitespace stripped, or None if the resulting value was an empty string
"""
stripped = value.strip(... | ff6b2da6f0ce3d718e71b43794e0a224e7f7b072 | 646,464 |
def my_formatter_1f(x,p):
"""Format tick marks to have 1 significant figure."""
return "%.1f" % (x) | ff89e72a071c609e6a363dc8fa4ba648c1d05031 | 646,465 |
def list_of(type_):
"""Generates a "list of" callable for the specified type. The callable
attempts to convert all elements in the passed value to the specifed
``type_``, raising ``ValueError`` on error."""
def __init__(self, values):
list.__init__(self, map(type_, values))
def append(self,... | 1c939cee03521349ca882d52abf92a592d0f187d | 646,466 |
import torch
def normalize_lab(lab_img):
"""
Normalizes the LAB image to lie in range 0-1
Args:
lab_img : torch.Tensor img in lab space
Returns:
lab_img : torch.Tensor Normalized lab_img
"""
mean = torch.zeros(lab_img.size())
stds = torch.zeros(lab_img.size())
m... | 392e3fef49a71a3a2f77884c58135466f81e8762 | 646,467 |
def api_status():
"""API health check endpoint for monitoring and alerting."""
return {'Status': 'OK'} | 548791945e312d06a0a1b76ef07ad571be240b2a | 646,468 |
def vertex_egonet(G, v):
""" Computes the number of edges in the ego network of the vertex v. """
ego_network = G.induced_subgraph(G.neighborhood(v))
ego_edges = ego_network.ecount()
return ego_edges | c865e9bd85ffe7b4fc899eb4d1b8885684a2e809 | 646,469 |
def scurve(start,end,n,s):
"""Return an S-Curve with a constant velocity section from start to end with
n points. The start and end S-curves each have s points"""
ys,ye = start,end
s1 = [ (ye-ys)*(x*x-s*s)/(2*s*float(n-1))+ys for x in range(0,s) ]
cv = [ (ye-ys)*(x-s)/float(n-1)+ys for x in range(s,s+n) ]
s2 = [ ... | a16ba1143cdeff9a8392a2c993b88918dff82350 | 646,470 |
import sys
def getProcNameFromCfg(filename):
"""it searches for the line containing the string consumerName, usually
found as a property of the process, and returns the set value found.
eg.
matches line:
process = cms.Process ("ECALDQM")
returns:
ECALDQM
"""
try:
f = open(filename)
except:
sys.stder... | 053d1556eaca1d392b9528e1cfbbd6ec311d4fa6 | 646,472 |
import string
import random
def gen_nonce(k=8, chars=string.ascii_letters + string.digits):
""" 生成一段加密用的字符串
字符串可以被用于密码、兑换码等等
"""
return ''.join(random.choices(chars, k=k)) | b582596f41b3305865883460a3b56220d787f97c | 646,474 |
def sort_files(files):
"""Sort a list of file names.
Parameters
----------
files : list of str
List of file names, to sort.
Returns
-------
list of str
Sorted list of files.
"""
return sorted(files) | 390684ba6292a2d1f898dcb512e429efaad39806 | 646,475 |
from datetime import datetime
def convert_datastore_datetime(field):
"""
return datetime in different ways, depending on whether the lib returns
a str, int, or datetime.datetime
"""
dt = ''
if type(field) == datetime:
dt = field
elif type(field) == int:
dt = datetime.utcfro... | dd2e8c34fac34519ac0199a9dd69b29dcf9f8005 | 646,476 |
def fetch_sequence(chrom, start, end, strand, genome):
""" Given a BED region, fetch its sequence. If it is on the minus strand,
then reverse-complement the sequence. """
seq = genome.sequence({'chr': chrom, 'start': start, 'stop': end,
'strand': strand}, one_based=False)
re... | a522168302c64941b22e0c1602d1a641910dd98a | 646,477 |
def process_event(dom, _cal):
"""
Extract useful details from a DOM element into a dict
"""
strings = list(dom.strings)
if len(strings) > 1: # has time
return dict(time=strings[0], event=strings[1])
return dict(event=strings[0]) | 586d0d17cd0dd477130d4ca5299c7c2ebeba1406 | 646,478 |
def filter_function_ortho(x):
"""Filter words based on punctuation and length."""
a = not set(x['orthography']).intersection({' ', "'", '.', '/', ',', '-'})
return (a and len(x['orthography']) >= 3) | 754a270603d5eca2aef5c968028e15154b8ca285 | 646,479 |
def convert_to_99_percent_confidence(margin_of_error):
"""
Converts a margin of error from the U.S. Census Bureau to the 99% confidence level.
Args:
margin_or_error (float): A margin of error at the bureau's standard 90% confidence level
Returns:
The adjusted margin of error (float).
... | 8bb872c84bdda9a6943c9402f61a18df3e84e889 | 646,480 |
def get_value(obj, attr):
"""
Returns the value of an attribute. First it tries to return the unicode value.
"""
if hasattr(obj, attr):
try:
value = getattr(obj, attr).__unicode__()
return {'id': getattr(obj, attr).id, 'value': value}
except:
value = ... | 5e328647dbbb46b7b91ab76961084cd42d426fb4 | 646,481 |
def awk(s: str, n: int, d: str = ' ') -> str:
"""Act like awk and select the nth element
Args:
s: string to split up
n: the element to select
d: the delimiter between elements
Returns:
"""
split = s.strip().split(d)
if len(split) >= n:
# awk is 1-indexed
... | 2ba2cd0f6734384d699e4c2860a50c665d930549 | 646,482 |
import csv
def ReadFile(f, tsv=False):
"""Read the CSV file, returning the column names and rows."""
if tsv:
c = csv.reader(f, delimiter='\t', doublequote=False,
quoting=csv.QUOTE_NONE)
else:
c = csv.reader(f)
# The first row of the CSV is assumed to be a header. The rest are dat... | 64cbfa3521487abeb1400be479ea64640cc5cb86 | 646,483 |
def _DegreeDict(tris):
"""Return a dictionary mapping vertices in tris to the number of triangles
that they are touch."""
ans = dict()
for t in tris:
for v in t:
if v in ans:
ans[v] = ans[v] + 1
else:
ans[v] = 1
return ans | 0626c2019aa2d4f46f5267ed8e19f7d69fe1fc48 | 646,484 |
import os
def list_abs_path_of_files(dirname):
"""Function to list absolute paths of files of desired directory"""
# This function can be called elsewhere by importing parent module.
# In such case, we need to chdir to required dir to list files.
# Otherwise, os.listdir() would get the list of files, ... | c15663d7529399bca9faedec19d9c187d2dad6da | 646,485 |
def escape_path(path):
"""
Adds " if the path contains whitespaces
Parameters
----------
path: str
A path to a file.
Returns
-------
an escaped path
"""
if ' ' in path and not (path.startswith('"') and path.endswith('"')):
return '"' + path + '"'
... | 6f3122532fa2590d43e9ad537d07f005d05c54fa | 646,486 |
import json
def get_json_value(value):
""" Get value as JSON. If value is not in JSON format return the given value """
try:
return json.loads(value)
except ValueError:
return value | 672f8d79aef23ee8f639ce87860029d54bf78ca3 | 646,487 |
import os
def password(name):
"""Choose a weakly random password from name, consistent across calls."""
return name + str(os.getpid()) | 64c69091bd2ebee0547f343fb9574500f4c7dc5c | 646,489 |
import sqlite3
def get_columns(cxn, table):
"""Get a list of columns from a table"""
sql = f'PRAGMA table_info({table});'
cxn.row_factory = sqlite3.Row
columns = [r[1] for r in cxn.execute(sql)]
return columns | b3b33d52d644409cda497e1a71c873d6470fa93c | 646,490 |
def is_overlap(x, y):
"""Whether the token x is contained within any span in the sequence y."""
if "NUM" in [c.pos_ for c in x]:
return False
return any([x.text in yy for yy in y]) | 58ad1071792f8cc28bcf7677e80607ddacc80d28 | 646,491 |
import base64
import zlib
import json
def json_zip2str(json_data):
"""
Return a string of compressed JSON data, suitable for transmission
back to a client.
"""
return base64.b64encode(
zlib.compress(
json.dumps(json_data).encode('utf-8')
)
).decode('ascii') | 9906fb484f849cc75c623055616ec941b71c2f55 | 646,493 |
import time
def time_in_seconds_str():
"""return time in seconds since midnight local time"""
t = time.localtime()
return str(t.tm_hour * 3600 + t.tm_min * 60 + t.tm_sec) | 6420fe93b453088411712e499bc6a683c4d79147 | 646,494 |
def find_row(table, row):
"""
Return row index with row header in table
or -1 if row is not in table
"""
for idx in range(len(table)):
if table[idx][0] == row:
return idx
return -1 | 64f7cab3a9f7d9829a40c993185d5ccc9689d1c8 | 646,495 |
def map_severity(meta_severity):
""" Map scanner severity to Carrier severity """
severity_map = {
"INFO": "Info",
"WARNING": "Medium",
"ERROR": "High",
}
return severity_map.get(meta_severity, "Info") | a7126a332820db07e0deed52194def3c0a11fe12 | 646,496 |
def get_zip_perms(zipinfo):
"""Get file/dir permissions from zipinfo
Args:
zipinfo (zipfile.Zipinfo): information about one component file of a
zip-file
Returns:
int: file permissions for file in octal
"""
# Windows zip files with no permissions seem to sensibly default ... | 7321b95dee6aedcf5771b19eabc09977fd9333ed | 646,497 |
def imap(imap, vmin=None, vmax=None, cmap='YlGnBu_r', length_unit='cm'):
"""
Convenience base function to plot any IntensityMap2D instance
Parameters
----------
ratemap : IntensityMap2D
Intensity map to plot
cmap : Colormap or registered colormap name, optional
Colormap to use f... | fbc19e21f7740bb2965f99398090eb24929b4e52 | 646,498 |
from typing import OrderedDict
def history_treeview():
""" Define Data Dictionary treeview columns for history table. Snippet:
("column", "row_id"), ("heading", "Row ID"), ("sql_table", "History"),
("column", "music_id"), ("heading", "Music ID"), ("sql_table", "History"),
("column", "user... | 1ff4dbecdd0d410e1eba0b60b3cbfa1639f84aab | 646,499 |
def array(x):
"""
Construct an array of size x (not a bitarray)
Args:
x (int): size of the array
Returns:
array: array of size x
"""
assert isinstance(x, int)
assert x < 4096, "Array too large"
return [None] * x | 2ebd491a04d68ac9370f506bdbe2f9f1c5ef0b0c | 646,500 |
def create_message_id(node) -> str:
"""Create message id from beautiful soup node.
>>> node = NavigableString(value="test")
>>> create_message_id(node)
'test'
"""
return " ".join(
word_not_blank
for word in node.string.split("\n")
if (word_not_blank := word.strip())
... | 61ff3abcac6ca0948d01557112b7559bb338f6cc | 646,501 |
def weighted_average(values):
"""Calculates an weighted average
Args:
values (Iterable): The values to find the average as an iterable of
``(value, weight)`` pairs
Returns:
The weighted average of the inputs
Example:
>>> weighted_average([(1, 2), (2, 3)])
1... | 5f6e08bb90d2325e346b62519272c562d174fa06 | 646,503 |
import sys
def startup(page, param_string):
""" Handles startup of script, flags, etc.
:page: String. URL before querystring.
:param_string: String. URL querystring.
:returns: String. Page ready for sqli manipulation.
"""
params = {i.split('=')[0]:i.split('=')[1] f... | 07cfe126f01f089397a84a0d6e867e712be1321f | 646,504 |
def set_staff_object(context, object):
"""
Assign an object to be the "main object" of this page.
Example::
{% set_staff_object page %}
"""
request = context["request"]
request.staff_object = object
return "" | ac2b6d3642f1fbe9b707dcbee0f27edb1bdcd72f | 646,505 |
import numpy
def linear_basis(v, b):
"""
#; (c) Kenneth A. Goldberg http://goldberg.lbl.gov KAGoldberg(at)lbl.gov
#; Lawrence Berkeley National Laboratory
#; 8/03/09
#; IDL files: linear_basis1.pro
#
#; When the linear polynomial basis functions, b[i].a, are already calculated,
#; us... | 775474bb71d5fc34c0cd2449d6bba1d59e787af5 | 646,506 |
import os
def get_labels_from_dir(dir_path):
"""Return classification class labels (= first subdirectories names)"""
labels_list = []
for (root, directories, filenames) in os.walk(dir_path):
directories.sort()
labels_list += directories
# Break to only keep the top directory
... | 1de160108ba3bd0c6f710f132b17c7400f9618c1 | 646,507 |
import json
def create_token(client, username, password, client_id):
"""Creates a new token given a username, password and client id."""
rv = client.post('/v1/oauth/token', follow_redirects=True, data={
'grant_type': 'password',
'client_id': client_id,
'username': username,
'pa... | 5ee1b67bc01679f6f6cd0335e47681d5620cfb40 | 646,508 |
import math
def standard_deviation(times):
"""
Calculates the standard deviation of a list of numbers.
"""
mean = sum(times) / len(times)
# Sum the squares of the differences from the mean.
result = 0
for time in times:
result += (time - mean) ** 2
return math.sqrt(result / len(times)) | 6e46feb09ffc6bf0a3ecc960adfeec9c95269754 | 646,509 |
def find_codon_diff(protein, mutated_protein):
"""
Function to find the effect the SNP had on the protein.
First compares the length of the proteins to see if the SNP caused a premature
stop codon, otherwise, returns the new codon.
"""
if len(protein) == len(mutated_protein):
for i in ra... | 7b691e8be1e8f8f75629bf07f72d51a68ed0a92c | 646,510 |
import copy
def get_value_from_str_dotted_key(d, dotted_key):
"""Get value from python dict via dotted notation.
:param d: dictionary
:param dotted_key:
:return: str
"""
keys = dotted_key.split('.')
temp = copy.deepcopy(d)
try:
for key in keys:
temp = temp[key]
... | 33a97ae9ea842f5cace8baf71dba039770e69af2 | 646,511 |
from typing import OrderedDict
def parse_headers(text):
"""Parse a string of headers (copied from Firefox) into a dict used in requests."""
return OrderedDict(line.split(': ') for line in text.splitlines() if line) | 474501f99f464a7b7af6e326a83f32e3ca96a8a2 | 646,512 |
import functools
import operator
def sum(xs):
"""
sum :: Num a => [a] -> a
The sum function computes the sum of a finite list of numbers.
"""
return functools.reduce(operator.add, xs, 0) | e38e26546da7ee4a438d9b2ede60362f73a8bc8f | 646,513 |
def compose_key(instance):
"""Given an instance, returns a key
:arg instance: The model instance to generate a key for
:returns: A string representing that specific instance
.. Note::
This uses the id attribute of the model instance.
That's good enough for my needs, but we might need ... | 728696720af1d94adf69e664d2da1ab9d248a563 | 646,515 |
def Xor(a, b):
"""Return a ^ b as a byte string where a and b are byte strings."""
# pad shorter byte string with zeros to make length equal
return bytes(bytearray([x ^ y for (x, y) in zip(bytearray(a), bytearray(b))])) | a487939866939a7f759034432486a95ab9c01675 | 646,516 |
import re
def parse_bind_address(address, default=('localhost', 8080)):
"""
>>> parse_bind_address('80')
('localhost', 80)
>>> parse_bind_address('0.0.0.0')
('0.0.0.0', 8080)
>>> parse_bind_address('0.0.0.0:8081')
('0.0.0.0', 8081)
"""
if ':' in address:
host, port = addres... | 5e4275e361bec09a517a2b8c78c77f7e285c5054 | 646,517 |
def get_points_ranges(points):
"""Get minimum and maximum coordinate values of points."""
ranges = []
for coord in (0, 1):
cur_coordinate = []
for func in (min, max):
cur_coordinate.append(func(
points, key=lambda point: point['position'][coord]
)['pos... | b250fb5c649fef706f3a29eebfb5f4650d6afca2 | 646,518 |
def to_identifier(key):
"""Converts given key to identifier, interpretable by TaskJuggler as a task-identifier
Args:
key (str): Key to be converted
Returns:
str: Valid task-identifier based on given key
"""
return key.replace('-', '_') | 3ebd320a40761ca85a8d564e27754621a5c9c1e6 | 646,519 |
def compute_kmp_fail(P):
"""Utility that computes and returns KMP 'fail' list."""
m = len(P)
fail = [0] * m # by default, presume overlap of 0 everywhere
j = 1
k = 0
while j < m:
if P[j] == P[k]: # k + 1 characters match thus far
fail[j] = k + 1... | ebf7008d05b46f49e0aaecd236c74406b2963677 | 646,520 |
def mapping_facebook_user_info_to_sso_user_info(
cognito_id, cognito_email, facebook_user_info
):
"""
Map the Facebook ID token info to the user info.
"""
sso_user_info = dict()
sso_user_info["cognito_id"] = cognito_id
sso_user_info["cognito_email"] = cognito_email
sso_user_info["federat... | 4e241c1b9c94770a24bb1ac2a93bc7c7eb1571f3 | 646,521 |
def gf_reversed_table() -> dict[int, int]:
"""Table - Inverse Galois Field.
Returns:
dict[int, int]: Dictionary of the form {argument: value}
"""
table = {
1: 0, 2: 1, 3: 25, 4: 2, 5: 50, 6: 26, 7: 198, 8: 3, 9: 223, 10: 51,
11: 238, 12: 27, 13: 104, 14: 199, 15: 75, 16: 4, 17: ... | 4e5b2b7104f25c042c9b2cb50ebe2b6a67adefa1 | 646,522 |
def _parse_text(res, path):
"""Parsing text from response by path.
"""
value = None
node = res.find(path)
if node is not None:
value = node.text
value = value.strip()
return value | d4cfa89412c968a2c1a1737bfc2051dc2e621712 | 646,523 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.