content
stringlengths 39
9.28k
| sha1
stringlengths 40
40
| id
int64 8
710k
|
---|---|---|
import torch
def zeros(shape):
"""Create zeros like shape."""
return torch.zeros(shape)
|
a71105b8a009ee297105770670a9f363fe0e2019
| 460,523 |
def oriented(square, desired):
""" Return True if the given square is oriented as desired.
"""
success = True
neighbors = square.neighbors
for side,id_ in desired.items():
if id_ is None:
success &= (side not in neighbors)
else:
success &= (side in neighbors and neighbors[side] == id_)
if not success:
return success
return success
|
0734c5feed757b238ca748a88965e013b0d390aa
| 454,405 |
def _normalize_percent_rgb(value):
"""
Normalize ``value`` for use in a percentage ``rgb()`` triplet, as
follows:
* If ``value`` is less than 0%, convert to 0%.
* If ``value`` is greater than 100%, convert to 100%.
Examples:
>>> _normalize_percent_rgb('0%')
'0%'
>>> _normalize_percent_rgb('100%')
'100%'
>>> _normalize_percent_rgb('62%')
'62%'
>>> _normalize_percent_rgb('-5%')
'0%'
>>> _normalize_percent_rgb('250%')
'100%'
>>> _normalize_percent_rgb('85.49%')
'85.49%'
"""
percent = value.split('%')[0]
percent = float(percent) if '.' in percent else int(percent)
if 0 <= percent <= 100:
return '%s%%' % percent
if percent < 0:
return '0%'
if percent > 100:
return '100%'
|
910da5cf9d270ef46e4ace3e53fd082763743191
| 282,124 |
def calculate_occlusion(ray, obj, light, objects):
"""
Calculate if there is an object between the light and object
Args:
ray: A ray starting in the hit point with direction to the light
obj: The object where the hit point is
light: A source of light to calculate if it's occluded
objects: The objects in the scene
Returns:
bool: If there is an occlusion or not
"""
# Check for occlusion
# 1. Shoot ray from point to light
# 2. Check collision with other objects
# 3. If there is one between the hit point and the light, there is occlusion
light_distance = light.get_distance(ray.pr)
for other_obj in objects:
if other_obj == obj:
continue
shadow_t = ray.intersect(other_obj)
if 0 < shadow_t <= light_distance:
return True
return False
|
c15acf785f8baf72da64307380cd36d7de6b6ef8
| 694,713 |
import tempfile
import zipfile
def decompress(zip_file, dir=None):
"""Decompress Zip file
Decompress any zip file. For example, TOSCA CSAR
inputs:
zip_file: file in zip format
dir: directory to decompress zip. If not provided an unique temporary
directory will be generated and used.
return:
dir: absolute path to the decopressed directory
"""
if not dir:
dir = tempfile.NamedTemporaryFile().name
with zipfile.ZipFile(zip_file, "r") as zf:
zf.extractall(dir)
return dir
|
4a860d6b8a104d8325bd4fa83db6aa9b05a49f76
| 382,180 |
def build_index(interactors):
""" Build the index (P x D) -> N for all interactors of the current protein.
"""
index = dict() # P x D -> N
sorted_interactors = sorted(list(interactors))
for p, d in sorted_interactors:
index[(p, d)] = sorted_interactors.index((p, d))
return index
|
44856b3dd98cb751d7da43f0952fe6a15e530886
| 375,006 |
import urllib3
import certifi
def post_json(ctx, path, json):
"""
Make a POST request with a JSON payload to be sent to a NuvIoT endpoint.
Parameters
----------
ctx:
Context Object that defines how this method should call the server to include authentication.
path:
Path used to make the request, the auth and server information will be used from the ctx object.
json:
JSON object to be posted
Returns
-------
Will return any JSON returned from the server, if the response code is not a success code an exception will be raised.
"""
if ctx.auth_type == 'user':
headers={'Authorization': 'Bearer ' + ctx.auth_token, 'Content-Type':'application/json'}
else:
headers={'Authorization': 'APIKey ' + ctx.client_id + ':' + ctx.client_token, 'Content-Type':'application/json'}
url = ctx.url + path
encoded_data = json.encode('utf-8')
http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=certifi.where())
r = http.request('POST', url,
headers=headers,
preload_content=False,
body=encoded_data)
responseJSON = ''
responseStatus = r.status
for chunk in r.stream(32):
responseJSON += chunk.decode("utf-8")
r.release_conn()
if responseStatus > 299:
print('Failed http call, response code: ' + str(responseStatus))
print('Url: ' + url)
print('Headers: ' + str(headers))
print(responseJSON)
print('--------------------------------------------------------------------------------')
print()
raise Exception("Could not post JSON to %s" % url)
return responseJSON
|
a6c1f49ce04d4f129d5fc8d180c2e460bbc825ac
| 585,558 |
import re
def extract_energies(pdb_file):
""" Extract energies from the header of the PDB file, according to HADDOCK formatting """
vdw = .0
elec = .0
desolv = .0
air = .0
bsa = .0
vdw_elec_air_regex = r"\s(\-?\d*\.?\d{1,}|0\b)" # Known error: 8.754077E-02 is matched as 8.754077 which is
# not relevant for the I/O benchmark but should be taken into account
desolv_regex = r"(\-?\d*\.?\d*)$"
bsa_regex = r"(\-?\d*\.?\d*)$"
f = open(pdb_file, 'r')
for line in f:
if 'REMARK energies' in line:
# print(line)
total, bonds, angles, improper, dihe, vdw, elec, air, cdih, coup, rdcs, vean, dani, xpcs, rg = re.findall(
vdw_elec_air_regex, line)
vdw = float(vdw)
elec = float(elec)
air = float(elec)
if 'REMARK Desolvation' in line:
# print(line)
desolv = float(re.findall(desolv_regex, line)[0])
if 'REMARK buried surface area' in line:
# print(line)
bsa = float(re.findall(bsa_regex, line)[0])
break
f.close()
return vdw, elec, desolv, air, bsa
|
326aa323de92ef834365eb8b61eef3dc7b8fa97d
| 344,606 |
def camelify(s):
"""Helper function to convert a snake_case name to camelCase."""
start_index = len(s) - len(s.lstrip("_"))
end_index = len(s.rstrip("_"))
sub_strings = s[start_index:end_index].split("_")
return (s[:start_index]
+ sub_strings[0]
+ "".join([w[0].upper() + w[1:] for w in sub_strings[1:]])
+ s[end_index:])
|
84bed77f217b8af55b0bd2cca0d354f372ba9e3d
| 552,514 |
import cProfile
def profiler_setup(config):
"""
Set up profiler based on config
"""
if not config["profile"]:
return
profiler = cProfile.Profile()
profiler.enable()
return profiler
|
bc67268533a87482a2735dbc57cfc7af64655605
| 387,040 |
def normalize(lst, maxval=1.):
"""
Normalizes a list of values with a specified value.
**Parameters**
lst: *list*
List of values to be normalized
maxval: *float*, optional
The maximum value that the list will have after normalization.
**Returns**
normalized list: *list*
A list of values normalized to the specified value.
"""
listmax = max(lst)
for ind, val in enumerate(lst):
lst[ind] = float(val) / float(listmax) * maxval
return lst
|
9ae34b5b7a81d55de88c942806f0440040873165
| 27,682 |
from typing import Any
def get_cls_name(obj: Any, package_name: bool = True) -> str:
"""
Get name of class from object
Args:
obj (Any): any object
package_name (bool): append package origin at the beginning
Returns:
str: name of class
"""
cls_name = str(obj.__class__)
# remove class prefix
cls_name = cls_name.split('\'')[1]
# split modules
cls_split = cls_name.split('.')
if len(cls_split) > 1:
cls_name = cls_split[0] + '.' + cls_split[-1] if package_name else cls_split[-1]
else:
cls_name = cls_split[0]
return cls_name
|
6eb9a5b8b2ac4b33b988a90ba5f1988633179295
| 44,624 |
def id_number_checksum(gd):
"""
Calculates a Swedish ID number checksum, using the Luhn algorithm
"""
n = s = 0
for c in (gd['year'] + gd['month'] + gd['day'] + gd['serial']):
# Letter? It's an interimspersonnummer and we substitute the letter
# with 1.
if c.isalpha():
c = 1
tmp = ((n % 2) and 1 or 2) * int(c)
if tmp > 9:
tmp = sum([int(i) for i in str(tmp)])
s += tmp
n += 1
if (s % 10) == 0:
return 0
return (((s // 10) + 1) * 10) - s
|
bbf0a9fa7f6ed2c2bfc414173fd2ac9e9c1d8835
| 706,841 |
def case_sorting_key(e):
"""Sorting key for test case identifier."""
return tuple(map(lambda n: int(n), e[0].split('.')))
|
c6bb059b516b2fd2118caf117277d05fa1d44dfa
| 267,573 |
def get_active_intfs(host_ans):
"""
@Summary: Get the active interfaces of a DUT
@param host_ans: Ansible host instance of this DUT
@return: Return the list of active interfaces
"""
int_status = host_ans.show_interface(command="status")['ansible_facts']['int_status']
active_intfs = []
for intf in int_status:
if int_status[intf]['admin_state'] == 'up' and \
int_status[intf]['oper_state'] == 'up':
active_intfs.append(intf)
return active_intfs
|
b5131862f6f8944dc908b1c1e245efaccce37bb1
| 220,292 |
def count_matches(a: str, b: str) -> int:
"""Returns the number of locations where the two strings are equal."""
assert len(a) == len(b)
return sum(int(i == j) for i, j in zip(a, b))
|
9c901f8c8303f58989db466f0a728bac3f93eb67
| 610,859 |
def is_integer(s):
"""True if s in an integer."""
try:
c = float(s)
return int(c) == c
except (ValueError, TypeError):
return False
|
d24cc5f51fc44dd7fb19b9f1fdc430760ba66181
| 299,550 |
def binary_search(val, array):
"""
>>> binary_search(1, [1, 2, 3])
(0, 1)
>>> binary_search(1.5, [1, 2, 3])
(1, 2)
>>> binary_search(8, [1, 2, 3])
(None, None)
>>> binary_search(3, [1, 2, 4])
(2, 4)
"""
# Trivial cases - out of array range.
if len(array) == 0:
return None, None
if val > array[-1]:
return None, None
if val <= array[0]:
return 0, array[0]
low = 0
high = len(array) - 1
while high - low >= 2:
mid = (high + low) // 2
if array[mid] >= val:
high = mid
else:
low = mid + 1
if low == high:
return low, array[low]
if val > array[low]:
return high, array[high]
else:
return low, array[low]
|
7e77f29945b3f4f579461d11acd334f288daa601
| 132,115 |
def report_writer(md):
"""
Reads meta data into function and makes txt message report.
----------
md : dict
Contains meta data from experiment file
Returns
-------
message : string
The text output for the report
"""
s_name = md["sample_meta_data"]["sample_name"]
s_date = md["sample_meta_data"]["sample_date"]
s_surface = md["sample_meta_data"]["sample_surface_area"]
imp_mode = md["experiment_meta_data"]["impedance_mode"]
meas_volt = md["experiment_meta_data"]["measurement_voltage"]
vs = md["experiment_meta_data"]["vs"]
pert_v = md["experiment_meta_data"]["pertubation_voltage"]
sf = md["experiment_meta_data"]["starting_frequency"]
ef = md["experiment_meta_data"]["ending_frequency"]
ppi = md["experiment_meta_data"]["points_per_interval"]
ig = md["experiment_meta_data"]["interval_group"]
spacing = md["experiment_meta_data"]["spacing"]
intro_line = "Report for "+str(s_name)+" experiment conducted on "+str(s_date)+".\n\n"
imp_line = "A "+str(imp_mode)+" measurement was made with a "+str(pert_v)+"mV pertubation voltage at "+str(meas_volt)+"V vs. "+str(vs)+".\n\n"
range_line = "Experiment conducted from "+str(sf)+"Hz to "+str(ef)+"Hz with "+str(ppi)+ " points "+str(ig)+" using "+str(spacing)+" spacing.\n\n"
surface_line = "Sample has a surface area of "+str(s_surface)+"cm^2."
message = intro_line+imp_line+range_line+surface_line
return message
|
16d67de3ca6f858aeea1f1a652ab4946a6c60cc0
| 61,436 |
def list_contains_only_integers(lst):
"""Returns True if the input list contains only str representations of digits.
Args:
lst: A list.
Elements must be strings, and if any element is not a string representation of
a digit, the function returns False.
"""
if not isinstance(lst, list):
raise TypeError(f"The given input {lst} is not a list")
for elm in lst:
if not isinstance(elm, str):
raise TypeError(f"Element {elm} is not a string")
if not elm.isdigit():
return False
return True
|
06ac2b8b9867c651d501b5e3fee4e6452b77f5a0
| 219,237 |
def select_categorical_gmeta_fields(metabase_cur, column_id):
"""
Select Gmeta fields related to categorical columns.
Note that the return value is different from other column types.
Args:
metabase_cur
column_id
Return:
(Query result object fetched from psycopg2's DictCursor):
Like a list of dictionaries with column names as keys. An empty
list is returned if no record to fetch.
"""
metabase_cur.execute(
"""
SELECT code, frequency
FROM metabase.code_frequency
WHERE column_id = %(column_id)s
ORDER BY frequency DESC
LIMIT 20 -- Top-k
""",
{
'column_id': column_id,
},
)
return metabase_cur.fetchall()
|
30fb4247bdbbdcd50e56065efec429a7a4a3a37e
| 407,928 |
import torch
def kl_prox_softmin(ecost, a, b, eps, rho, rho2):
"""Prepares functions which perform updates of the Sikhorn algorithm
in exponential scale.
Parameters
----------
ecost: torch.Tensor of size [Batch, size_X, size_Y]
Exponential of the cost. Kernel of Sinkhorn operator.
a: torch.Tensor of size [Batch, size_X]
Input measure of the first mm-space.
b: torch.Tensor of size [Batch, size_Y]
Input measure of the second mm-space.
eps: float
Strength of entropic regularization.
rho: float
Strength of penalty on the first marginal of pi.
rho2: float
Strength of penalty on the first marginal of pi. If set to None it is
equal to rho.
Returns
----------
s_x: callable function
Map outputing updates of potential from Y to X.
s_y: callable function
Map outputing updates of potential from X to Y.
"""
tau = 1.0 / (1.0 + eps / rho)
tau2 = 1.0 / (1.0 + eps / rho2)
def s_y(v):
return torch.einsum("ij,j->i", ecost, b * v) ** (-tau2)
def s_x(u):
return torch.einsum("ij,i->j", ecost, a * u) ** (-tau)
return s_x, s_y
|
3572de47292e22cb64654d84c4845590a1000eab
| 474,497 |
def median_imputation(df):
"""Impute the missing numeric values with the median of that column after grouping by label"""
imputed_df = df.copy()
# get the numeric columns in the input df ("Label" and "struct_ordered" are excluded)
numeric_cols = imputed_df.drop(columns=["Label", "struct_ordered"]).select_dtypes(include="number").columns
# iterate over all the selected numeric columns and impute by median within each label group
for numeric_col in numeric_cols:
imputed_df[numeric_col] = imputed_df.groupby("Label")[numeric_col].apply(lambda x: x.fillna(x.median()))
return imputed_df
|
1870b3e2b2204626983ac9ca2f0766d66251f9fb
| 491,975 |
def copy_or_set_(dest, source):
"""
A workaround to respect strides of :code:`dest` when copying :code:`source`
(https://github.com/geoopt/geoopt/issues/70)
Parameters
----------
dest : torch.Tensor
Destination tensor where to store new data
source : torch.Tensor
Source data to put in the new tensor
Returns
-------
dest
torch.Tensor, modified inplace
"""
if dest.stride() != source.stride():
return dest.copy_(source)
else:
return dest.set_(source)
|
d30b1e98da0ab2ef134173ad39a3e6e66e08c903
| 524,799 |
def get_shape(x, unknown_dim_size=1):
"""
Extract shape from onnxruntime input.
Replace unknown dimension by default with 1.
Parameters
----------
x: onnxruntime.capi.onnxruntime_pybind11_state.NodeArg
unknown_dim_size: int
Default: 1
"""
shape = x.shape
# replace unknown dimensions by default with 1
shape = [i if isinstance(i, int) else unknown_dim_size for i in shape]
return shape
|
1c719191922a46b948fb567273e3a5152769e190
| 8,539 |
import hashlib
def sha256_hash(b: bytes) -> bytes:
"""
sha256_hash hashes the given bytes with SHA256
Args:
b (bytes): bytes to hash
Returns:
bytes: The hash result
"""
return hashlib.sha256(b).digest()
|
110367c664552fc068f1a1e0839fed0ae061d22f
| 256,139 |
def transform_dict(img):
"""
Take a raster data source and return a dictionary with geotranform values
and keys that make sense.
Parameters
----------
img : gdal.datasource
The image datasource from which the GeoTransform will be retrieved.
Returns
-------
dict
A dict with the geotransform values labeled.
"""
geotrans = img.GetGeoTransform()
ret_dict = {
'originX': geotrans[0],
'pixWidth': geotrans[1],
'rotation1': geotrans[2],
'originY': geotrans[3],
'rotation2': geotrans[4],
'pixHeight': geotrans[5],
}
return ret_dict
|
8817028adfce28ae7f7ae787d4256d52fee095bc
| 15,933 |
def query_registry(model, registry):
"""Performs a lookup on a content type registry.
Args:
model: a Django model class
registry: a python dictionary like
```
{
"my_app_label": True,
"my_other_model": {
"my_model": True,
},
}
```
The type of `<value>` is specific to each
registry. A return value of `None` signals
that nothing is registered for that `model`.
"""
app_label = model._meta.app_label
model = model.__name__.lower()
if app_label not in registry:
return None
if not isinstance(registry[app_label], dict):
return registry[app_label]
# subset specified
if model not in registry[app_label]:
return None
return registry[app_label][model]
|
7c410c5baa8d20792ee7f49423da000fee34d001
| 669,370 |
def binary_search_recursive(lst, key, start=0, end=None):
"""
Performs binary search with recursion for the given key in iterable.
Parameters
----------
lst : python iterable in which you want to search key
key : value you want to search
start : starting index
end : ending index
Returns
-------
index (int): key's index if found else -1
"""
if not end:
end = len(lst)
if not (start <= end):
return -1
mid = (start+end)//2
if lst[mid] == key:
return mid
elif lst[mid] < key:
return binary_search_recursive(lst, key, mid + 1, end)
else:
return binary_search_recursive(lst, key, start, mid-1)
|
70f464151c3357786308f2a0ea16e77c25382700
| 284,998 |
from typing import Any
from pathlib import Path
from typing import Tuple
def lookup_path(context: Any, sub_paths: Path) -> Tuple[bool, Any]:
"""Lookup attributs in a context like dictionary.
Arguments:
context (Any): a dictionnary like structure with in and [] methods
(support __contains__ or (__iter__ and __getitem__)).
sub_paths (Path): a path (single string or an ordered tuple of string)
Returns:
(Tuple[bool, Any]): (True, attribut value ) or (False, None) if path not found
Exceptions:
(RuntimeError): if context did not compliant
"""
if not context:
return (False, None)
if not (hasattr(context, "__contains__") or (hasattr(context, "__iter__") and hasattr(context, "__getitem__"))):
raise RuntimeError('Context must be dictionnary like')
if isinstance(sub_paths, Tuple):
if sub_paths:
# len > 0
current = context
i = 0
while i < len(sub_paths):
p = sub_paths[i]
if not current or p not in current:
return (False, None)
i += 1
current = current[p]
return (True, current)
return (False, None)
# simple string
match = sub_paths in context
return (match, context[sub_paths] if match else None)
|
fd21a1f993d9596ff15420a6faa022b832b25b66
| 433,999 |
def indexPosition2D(i, j, N, M):
"""This function is a generic function which determines if for a grid
of data NxM with index i going 0->N-1 and j going 0->M-1, it
determines if i,j is on the interior, on an edge or on a corner
The funtion return four values:
type: this is 0 for interior, 1 for on an edge and 2 for on a corner
edge: this is the edge number if type==1
node: this is the node number if type==2
index: this is the value index along the edge of interest --
only defined for edges"""
if i > 0 and i < N - 1 and j > 0 and j < M - 1: # Interior
return 0, None, None, None
elif i > 0 and i < N - 1 and j == 0: # Edge 0
return 1, 0, None, i
elif i > 0 and i < N - 1 and j == M - 1: # Edge 1
return 1, 1, None, i
elif i == 0 and j > 0 and j < M - 1: # Edge 2
return 1, 2, None, j
elif i == N - 1 and j > 0 and j < M - 1: # Edge 3
return 1, 3, None, j
elif i == 0 and j == 0: # Node 0
return 2, None, 0, None
elif i == N - 1 and j == 0: # Node 1
return 2, None, 1, None
elif i == 0 and j == M - 1: # Node 2
return 2, None, 2, None
elif i == N - 1 and j == M - 1: # Node 3
return 2, None, 3, None
|
3197313b6211e40e8b3bbde6e7eb18bdf15ee814
| 461,579 |
def GetErrorOutput(error, new_error=False):
"""Get a output line for an error in regular format."""
line = ''
if error.token:
line = 'Line %d, ' % error.token.line_number
code = 'E:%04d' % error.code
error_message = error.message
if new_error:
error_message = 'New Error ' + error_message
return '%s%s: %s' % (line, code, error.message)
|
4661c74fcef9f13c0aad3d74e827d9eea20f86ef
| 12,861 |
def rev_comp(seq: str) -> str:
"""
Generates the reverse complement of a sequence.
"""
comp = {
"A": "T",
"C": "G",
"G": "C",
"T": "A",
"B": "N",
"N": "N",
"R": "N",
"M": "N",
"Y": "N",
"S": "N",
"W": "N",
"K": "N",
"a": "t",
"c": "g",
"g": "c",
"t": "a",
"n": "n",
" ": "",
}
rev_seq = "".join(comp.get(base, base) for base in reversed(seq))
return rev_seq
|
cb6b95d2d3f15910ff3ad793d99bb56de898026e
| 11,619 |
from typing import Optional
def get_shelf_audience_code(location_code: str) -> Optional[str]:
"""
Parses audience code from given normalized location_code
"""
try:
audn = location_code[2].strip()
if audn:
return audn
else:
return None
except IndexError:
return None
|
5aa9c32a186f1f8a111f8a50fbf2c05ea0fd6705
| 344,232 |
def are_relatively_prime(a, b):
"""Return ``True`` if ``a`` and ``b`` are two relatively prime numbers.
Two numbers are relatively prime if they share no common factors,
i.e. there is no integer (except 1) that divides both.
"""
for n in range(2, min(a, b) + 1):
if a % n == b % n == 0:
return False
return True
|
f3f98b43a27f6da219e0c68f9da55df0a2774bde
| 616,781 |
def boolean(entry, option_key="True/False", **kwargs):
"""
Simplest check in computer logic, right? This will take user input to flick the switch on or off
Args:
entry (str): A value such as True, On, Enabled, Disabled, False, 0, or 1.
option_key (str): What kind of Boolean we are setting. What Option is this for?
Returns:
Boolean
"""
error = f"Must enter 0 (false) or 1 (true) for {option_key}. Also accepts True, False, On, Off, Yes, No, Enabled, and Disabled"
if not isinstance(entry, str):
raise ValueError(error)
entry = entry.upper()
if entry in ("1", "TRUE", "ON", "ENABLED", "ENABLE", "YES"):
return True
if entry in ("0", "FALSE", "OFF", "DISABLED", "DISABLE", "NO"):
return False
raise ValueError(error)
|
d62b36d08651d02719b5866b7798c36efd2a018f
| 3,297 |
def primary_private_ip(ip_configs):
""" This function extracts primary, private ipaddress """
return [ip['properties']['privateIPAddress']
for ip in ip_configs if ip['properties']['primary']][0]
|
281f25eecda0c477308d93376587875942b19993
| 516,169 |
def isInteger(n, epsilon=1e-6):
"""
Returns True if n is integer within error epsilon
"""
return (n - int(n)) < epsilon
|
8ef0960cffadc063317830dca77d1177569ad178
| 34,840 |
import pickle
def save_pickle(value, filename):
"""
Save value to pickle file
:param value: Value to save
:param filename: Filename to save value as
"""
with open(filename, 'wb') as f:
return pickle.dump(value, f)
|
70e8fbbf2420586127c2d0704243a227fe2c5d58
| 536,373 |
from typing import List
from typing import Any
def flatten(x: List[Any]) -> List[Any]:
"""Returns flattened list.
Args:
x (list): Nested Python list.
Returns:
list: Flattened Python list.
"""
return [i for sl in x for i in sl]
|
d9b24e63d75849bcf5f1538bbb3dcb44c4a64a5c
| 177,843 |
def uri_leaf(uri):
"""
Get the "leaf" - fragment id or last segment - of a URI. Useful e.g. for
getting a term from a "namespace like" URI. Examples:
>>> uri_leaf('http://example.org/ns/things#item')
'item'
>>> uri_leaf('http://example.org/ns/stuff/item')
'item'
>>> uri_leaf('http://example.org/ns/stuff/')
''
"""
return uri.rsplit('/', 1)[-1].rsplit('#', 1)[-1]
|
abbcc83543c5f20a93a59a94cc6c7e164ed70deb
| 169,223 |
def get_file_date_part(now, hour) -> str:
""" Construct the part of the filename that contains the model run date
"""
if now.hour < hour:
# if now (e.g. 10h00) is less than model run (e.g. 12), it means we have to look for yesterdays
# model run.
day = now.day - 1
else:
day = now.day
date = '{year}{month:02d}{day:02d}'.format(
year=now.year, month=now.month, day=day)
return date
|
42c2beddccba755f66061364463f8ad759d3c020
| 12,851 |
import zlib
def inflate(data):
"""Returns uncompressed data."""
return zlib.decompress(data, -zlib.MAX_WBITS)
|
144ba727f93a79abec7880a2781ea9971a69d825
| 374,636 |
def merge_dict_of_lists(d1: dict, d2: dict) -> dict:
"""Merge two dicts of lists.
Parameters
----------
d1 : dict
The first dict to merge.
d2 : dict
The second dict to merge.
Returns
-------
dict
The merged dict.
"""
ret = {k: list(v) for k, v in d1.items()}
for k, _ in d1.items():
if k in d2.keys():
ret[k] += d2[k]
else:
ret[k] = d2[k]
return ret
|
51c9c495c087c2d7fa1676800ab8223d1881308f
| 407,665 |
def calulate_loss_of_life(List_V, t):
""" For list of V values, calculate loss of life in hours
t = Time Interval (min)
"""
L = 0
for V in List_V:
L += (V * t) # Sum loss of life in minutes for each interval
LoL = L / 60 # Calculate loss of life in hours
return LoL
|
ee2499af737cca764aad0a2f13794a925a172b9e
| 10,849 |
import random
def encode_string(value):
"""
Encode a string into it's equivalent html entity.
The tag will randomly choose to represent the character as a hex digit or
decimal digit.
"""
e_string = ""
for a in value:
e_type = random.randint(0, 1)
if e_type:
en = "&#x%x;" % ord(a)
else:
en = "&#%d;" % ord(a)
e_string += en
return e_string
|
76af82e3495c605a5ddaf3df9bdd352749856c07
| 641,657 |
def mouse_within_existing_lines(self, mouse_y):
"""
Returns True if the given Y-coordinate is within the height of the text-editor's existing lines.
Returns False if the coordinate is below existing lines or outside of the editor.
"""
return self.editor_offset_Y < mouse_y < self.editor_offset_Y + (self.lineHeight * self.maxLines)
|
f0446b9607119d2ad439cc1933ab1723a0381ec0
| 477,852 |
import math
def euclidian(p1, p2):
"""Return euclidian distance between 2 points."""
return math.sqrt((p2[0] - p1[0])**2 + (p2[1] - p1[1])**2)
|
82c326077e8a90ed067e7d6cd2d5aabfd9745499
| 50,546 |
def curvature_from_fit(fit, y):
"""Compute curvature radius
Args:
fit (numpy.ndarray[3]<float>): polynomial regression fit coefficients
y (float): point where curvature will be evaluated
Returns:
float: curvature radius
"""
if len(fit) != 3:
raise AssertionError(f"expected fit coefficients to be of shape (3,), but received {fit.shape}")
f_prime = 2 * fit[0] * y + fit[1]
f_second = 2 * fit[0]
return (1 + (f_prime ** 2)) ** 1.5 / abs(f_second)
|
e4122c06e7e91da03aef0cafd21399a049004e1d
| 496,389 |
def _rect(x: float,
y: float,
boxwidth: float,
boxheight: float,
fill: str = 'white',
strokewidth: float = 1):
"""Draw an SVG <rect> rectangle."""
return f'<rect x="{x}" y="{y}" width="{boxwidth}" height="{boxheight}" ' \
f'stroke="black" fill="{fill}" stroke-width="{strokewidth}" />'
|
ce0b88a946dc1f1d65a3ffe5fa81920be06a294b
| 607,055 |
def is_within_region(readpos, contiglength, readlength, regionlength):
"""Checks if a read is within the given region."""
return readpos - readlength <= regionlength \
or readpos >= contiglength - regionlength
|
934ce7f066de80beb5d0f65bbe6eb6707fdfb39c
| 117,361 |
def load_stop_words(filename):
"""Load a set of stop words from a file.
One word each line."""
# you are using CPython, don't you?
# http://stackoverflow.com/a/11027437/1240620
stopwords = {w.strip() for w in open(filename)}
return stopwords
|
e23ec9a1d20396a0694bdd366a283bfbafb66f2b
| 646,221 |
def to_unicode(obj):
"""Convert object to unicode"""
if isinstance(obj, bytes):
return obj.decode('utf-8', 'ignore')
return str(obj)
|
e54c02e04109b8a99a7eb4e357e95ead89166137
| 8,536 |
def onlyunix(f):
"""
Decorator that indicates that the command cannot be run on windows
"""
f._onlyunix = True
return f
|
935bfe9f5fbb4b2341f79b3d7a7736e8664549cc
| 408,338 |
def after_space(s):
"""
Returns a copy of s after the first space
Parameter s: the string to slice
Precondition: s is a string with at least one space
"""
return s[s.find(' ') + 1:]
|
d16fe547b562a7089a0babf9578e7a06f7a1f69e
| 671,077 |
def get_bytes(encoded: bytearray, idx: int, length: int) -> tuple:
"""
Returns the bytes with given length, and next to be read index
:param encoded: bytearray
:param idx: index to start read from
:param length: length to be read
:return: tuple of bytes read and next index
"""
return encoded[idx:idx + length], idx + length
|
08fc9023b93680306e9d1703790fb86b092060be
| 532,893 |
def strip_suffix(text, suffix):
"""
Cut a set of the last characters from a provided string
:param text: Base string to cut
:param suffix: String to remove if found at the end of text
:return: text without the provided suffix
"""
if text is not None and text.endswith(suffix):
return text[:len(text) - len(suffix)]
else:
return text
|
883ccee3bd3c48b80839d8ad4838a77720c28faf
| 88,568 |
def format_human_readable_time(seconds):
""" format the number of seconds given as a human readable value """
if seconds < 60:
return "%.0f seconds" % seconds
if seconds < 60 * 60:
minutes = seconds / 60
return "%.0f minutes" % minutes
hour = seconds / 60 / 60
return "%.0f hours" % hour
|
fefde7d1b3e7bb8ba0c3db5a949a0d728d6790a1
| 415,297 |
def compute_node_degrees(ugraph):
"""
Returns a dictionary of degree number for
all nodes in the undirected graph
"""
node_deg = {}
# iterate over all dictionary keys to find size of
# adjacency list for each node
for node in ugraph:
node_deg[node] = len(ugraph[node])
return node_deg
|
a6d2f2df91b8536eca7814d54376f8b7855c2e7b
| 44,379 |
import yaml
def parse_config_file(config_file) -> dict:
"""Read config.yaml file with params.
Returns
-------
dict
Dict of config
"""
with open(config_file, 'r') as stream:
try:
CONFIG = yaml.safe_load(stream)
except yaml.YAMLError as exc:
print(exc)
exit(1)
return CONFIG
|
8f1fb9bcda94ef5c21edbf5e5bf95b327efd8c96
| 8,673 |
def listify(argument) -> list:
"""
Turn `argument` into a list, if it is not already one.
"""
if argument is None:
return []
if type(argument) is tuple:
argument = list(argument)
elif not type(argument) is list:
argument = [argument]
return argument
|
c0ec40c9b487028fa38d3023752107a12b7f18d0
| 456,467 |
def bytesToStr(s):
"""Force to unicode if bytes"""
if type(s) == bytes:
return s.decode('utf-8')
else:
return s
|
876e72d3b82c988edc92dce26969230cb04f17a8
| 207,022 |
def roots_linear(f):
"""Returns a list of roots of a linear polynomial."""
return [-f.coeff(0)/f.coeff(1)]
|
6fbd70139c0c90d8c9e4dc5f42cce64908716f4d
| 373,716 |
def _join_memory_tool_options(options):
"""Joins a dict holding memory tool options into a string that can be set in
the environment."""
return ':'.join(
'%s=%s' % (key, str(value)) for key, value in sorted(options.items()))
|
20f61a8ed622de2bbe12d14936669196c8a6be26
| 340,893 |
import re
def strip_hive_comments(hive_query):
"""Strip the comments in a Hive query."""
regex = r'--.*'
flags = re.MULTILINE | re.IGNORECASE
return re.sub(regex, '', hive_query, flags)
|
09bb1172d3753f2fdc5d0100120b77f09ea3066f
| 365,188 |
import torch
def reference_loss_func(loss_sum_or_avg: torch.Tensor, num_measurements: torch.Tensor, take_avg_loss: bool):
"""
Returns average loss for data from``loss_sum_or_avg``. This function sums all losses from ``loss_sum_or_avg`` and
divides the sum by the sum of ``num_measurements`` elements.
If ``take_avg_loss`` is ``True`` then ``loss_sum_or_avg[i]`` elements are mean values of ``num_measurements[i]``
losses. In that case before computing sum of losses each element of ``loss_sum_or_avg`` is multiplied by
corresponding element of ``num_measurements``.
If ``num_measurements`` sum is zero then the function returns NaN tensor.
The function is used for testing ``nemo.collections.common.metrics.GlobalAverageLossMetric`` class.
Args:
loss_sum_or_avg: a one dimensional float ``torch.Tensor``. Sums or mean values of loss.
num_measurements: a one dimensional integer ``torch.Tensor``. Number of values on which sums of means in
``loss_sum_or_avg`` are calculated.
take_avg_loss: if ``True`` then ``loss_sum_or_avg`` contains mean losses else ``loss_sum_or_avg`` contains
sums of losses.
"""
loss_sum_or_avg = loss_sum_or_avg.clone().detach()
if take_avg_loss:
loss_sum_or_avg *= num_measurements
nm_sum = num_measurements.sum()
if nm_sum.eq(0):
return torch.tensor(float("nan"))
return loss_sum_or_avg.sum() / nm_sum
|
11771a75f53d03ff767591a8a4884a3f61f4406a
| 437,967 |
def compute_number_of_clusters(
eigenvalues, max_clusters=None, stop_eigenvalue=1e-2):
"""Compute number of clusters using EigenGap principle.
Args:
eigenvalues: sorted eigenvalues of the affinity matrix
max_clusters: max number of clusters allowed
stop_eigenvalue: we do not look at eigen values smaller than this
Returns:
number of clusters as an integer
"""
max_delta = 0
max_delta_index = 0
range_end = len(eigenvalues)
if max_clusters and max_clusters + 1 < range_end:
range_end = max_clusters + 1
for i in range(1, range_end):
if eigenvalues[i - 1] < stop_eigenvalue:
break
delta = eigenvalues[i - 1] / eigenvalues[i]
if delta > max_delta:
max_delta = delta
max_delta_index = i
return max_delta_index
|
2d58a05c54ad0f178bba33ddfbc0c82cdb4fcfc3
| 454,822 |
def calculateSphereInertia(mass, r):
"""Returns upper diagonal of inertia tensor of a sphere as tuple.
Args:
mass(float): The spheres mass.
r(float): The spheres radius.
Returns:
: tuple(6)
"""
i = 0.4 * mass * r ** 2
ixx = i
ixy = 0
ixz = 0
iyy = i
iyz = 0
izz = i
return ixx, ixy, ixz, iyy, iyz, izz
|
324ddd5e9175971fbc45bf269118ce1a673718f6
| 410,115 |
def consolidate_grades(grade_decimals, n_expect=None):
"""
Consolidate several grade_decimals into one.
Arguments:
grade_decimals (list): A list of floats between 0 and 1
n_expect (int): expected number of answers, defaults to length of grade_decimals
Returns:
float, either:
average of grade_decimals padded to length n_extra if
necessary, and subtracting 1/n_extra for each extra, or
zero
whichever is larger.
Usage:
>>> consolidate_grades([1, 0, 0.5], 4)
0.375
>>> consolidate_grades([1, 0.5, 0], 2)
0.25
>>> consolidate_grades([1, 0.5, 0, 0, 0], 2)
0
"""
if n_expect is None:
n_expect = len(grade_decimals)
n_extra = len(grade_decimals) - n_expect
if n_extra > 0:
grade_decimals += [-1] * n_extra
elif n_extra < 0:
grade_decimals += [0] * abs(n_extra)
avg = sum(grade_decimals)/n_expect
return max(0, avg)
|
2125a562d90dad50d56b077f7c4573870b77437c
| 266,677 |
import yaml
def load_vasp_summary( filename ):
"""
Reads a `vasp_summary.yaml` format YAML file and returns
a dictionary of dictionaries. Each YAML document in the file
corresponds to one sub-dictionary, with the corresponding
top-level key given by the `title` value.
Example:
The file::
---
title: foo
data: foo_data
---
title: bar
data: bar_data
is converted to the dictionary::
{ 'foo': { 'title': 'foo', 'data': 'foo_data' },
'bar': { 'title': 'bar', 'data': 'bar_data' } }
Args:
filename (str): File path for the `vasp_summary.yaml` file.
Returns:
(dict(dict,dict,...)): A dictionary of separate YAML documents,
each as dictionaries.a
"""
with open( filename, 'r' ) as stream:
docs = yaml.load_all( stream, Loader=yaml.SafeLoader )
data = { d['title']: d for d in docs }
return data
|
236396afb16af6d30c5c39033e7efb122f25607b
| 536,956 |
def function_maker(func):
"""Wraps a function to return [params, f(params)]"""
def f(params):
try:
r = func(**params)
except Exception as e:
r = e
return [params, r]
return f
|
ba1add09c09b924db27500f04c0c3938e3940e93
| 623,489 |
import re
def _make_regex(pem_type):
"""
Dynamically generate a regex to match pem_type
"""
return re.compile(
r"\s*(?P<pem_header>-----BEGIN {0}-----)\s+"
r"(?:(?P<proc_type>Proc-Type: 4,ENCRYPTED)\s*)?"
r"(?:(?P<dek_info>DEK-Info: (?:DES-[3A-Z\-]+,[0-9A-F]{{16}}|[0-9A-Z\-]+,[0-9A-F]{{32}}))\s*)?"
r"(?P<pem_body>.+?)\s+(?P<pem_footer>"
r"-----END {0}-----)\s*".format(pem_type),
re.DOTALL,
)
|
1c1345520e37bb6c7ab75ae5856177c745f9f0fd
| 177,306 |
def program(msg):
"""Returns the program value of a program change message."""
return msg[1]
|
24cc307630dfe783a9b9157623d636b873c944bc
| 463,037 |
def to_payload(aliases):
"""
Boxes a list of aliases into a JSON payload object expected
by the server.
"""
return {"aliases": [{"value": alias} for alias in aliases]}
|
1950d4eac9fb6c9e211a7faafdea615a01179223
| 360,156 |
def compose(outer_function, inner_function):
"""
Utility function that returns the composition of two functions.
Args:
outer_function (function): A function that can take as input the output of
`inner_function`.
inner_function (function): Any function.
Returns:
function: The composition of `outer_function` with `inner_function`.
"""
return lambda *args, **kwargs: outer_function(inner_function(*args, **kwargs))
|
75243aed676f106c7dba575f9cedf2c72c8059d3
| 199,691 |
from typing import Any
def flag(argument: Any) -> bool:
"""
Check for a valid flag option (no argument) and return :py:obj:`True`.
Used in the ``option_spec`` of directives.
.. seealso::
:class:`docutils.parsers.rst.directives.flag`, which returns :py:obj:`None` instead of :py:obj:`True`.
:raises: :exc:`ValueError` if an argument is given.
"""
if argument and argument.strip():
raise ValueError(f"No argument is allowed; {argument!r} supplied")
else:
return True
|
7aeb0b0ddf5b98cafebf868adbc95204518513db
| 665,503 |
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 + '"'
else:
return path
|
6f3122532fa2590d43e9ad537d07f005d05c54fa
| 646,486 |
import random
def make_n_length_integer(n1, n2, allow_negative=False):
"""Function that generates an integer with specified number of digits.
Parameters
----------
n1 : int
Lower boundary for the number of digits
n2 : int
Upper boundary for the number of digits
allow_negative : boolean
Specifies if resulting integer can be negative. Default: False
Returns
-------
int
"""
range_start = 10**(n1-1)
range_end = (10**n2)-1
multiplier = random.choice((1, -1)) if allow_negative else 1
return random.randint(range_start, range_end) * multiplier
|
b277900036f30cefd5b2b5251320daa2fb4be139
| 504,328 |
def _ofc(id):
"""OFC ID converter."""
return "ofc-%s" % id
|
c31e2fb102c0238c943629de98cffeeac127cf29
| 628,111 |
def sieve_eratosthenes(range_to):
"""
A Very efficient way to generate all prime numbers upto a number.
Space complexity: O(n)
Time complexity: O(n * log(logn))
n = the number upto which prime numbers are to be generated.
"""
range_to=int(range_to)
# creating a boolean list first
prime = [True for i in range(range_to + 1)]
p = 2
while (p * p <= range_to):
# If prime[p] is not changed, then it is a prime
if (prime[p] == True):
# Update all multiples of p
for i in range(p * 2, range_to + 1, p):
prime[i] = False
p += 1
# return the list of primes
return [p for p in range(2, range_to + 1) if prime[p]]
|
b3f127295f988de6e0021d4137fc4e36290a5717
| 401,181 |
def _filter_features(
example,
feature_whitelist):
"""Remove features that are not whitelisted.
Args:
example: Input example.
feature_whitelist: A list of feature names to whitelist.
Returns:
An example containing only the whitelisted features of the input example.
"""
return {
feature_name: example[feature_name]
for feature_name in feature_whitelist
if feature_name in example
}
|
26f4afd9297f1b678761646494ebb83d4724ca01
| 70,379 |
def make_urls_list(ids_list):
"""
Appends each video id to the base url and insert them into a list
:param list ids_list: youtube video id list
:return list: list of urls
"""
base_url = 'https://www.youtube.com/watch?v='
urls_list = [base_url + _id
for _id in ids_list
if _id is not None]
return urls_list
|
8e682a2f8e5c2b815f112435b50b4925f2ed146b
| 203,879 |
def biggest_indices(items, n):
"""Return list of indices of n biggest elements in items"""
with_indices = [(x, i) for i, x in enumerate(items)]
ordered = sorted(with_indices)
return [i for x, i in ordered[-n:]]
|
fc1faf2720f605cceb007925aa1d54dca2f793de
| 435,682 |
import re
def format_author_name(author_name):
"""Format the author name (string) as N Benabderrazik. If there are
multiple first names it would be: A B FamilyName where A and B are
the first letters of the respective first names.
"""
# Keep only strings before an opening parenthesis (e.g. discard (Montpellier))
author_name = re.sub(r"\(.*$", "", author_name)
# Keep only word characters
author_name = re.findall(r"[\w']+", author_name)
# Turn the first names to initials and keep the family name as is
author_name = [author_name[i][0] if i < len(author_name)-1 else author_name[i]
for i in range(len(author_name))]
return " ".join(author_name)
|
040128f4249f261a73bcbb59c8c34bd6dff201db
| 302,893 |
def get_weights(model):
"""
Return weights of Keras model as a list of tuples (w, b), where w is a numpy array of weights and b is a numpy array
of biases for a layer. The order of the list is the same as the layers in the model.
:param model: Keras model
:return: List of layer weights (w, b)
"""
weights = model.get_weights()
assert len(weights) % 2 == 0
return list(zip(weights[0::2], weights[1::2]))
|
dcd18a9ffaa9afbb40b0df96cc98d1f9795d2431
| 224,385 |
def monthly_soil_heat_flux(t_month_prev, t_month_next):
"""
Estimates the monthly soil heat flux (Gmonth) [MJ m-2 day-1]
assuming a grass crop from the mean
air temperature of the previous month and the next month based on FAO
equation (43). If the air temperature of the next month is not known use
function monthly_soil_heat_flux2(). The resluting heat flux can be
converted to equivalent evaporation [mm day-1] using the equiv_evap()
function.
Arguments:
t_month_prev - mean air temperature of previous month [deg C]
t_month2_next - mean air temperature of next month [deg C]
"""
# Raise exceptions
if (t_month_prev < -95.0 or t_month_prev > 60.0):
raise ValueError, 't_month_prev=%g is not in range -95 to +60' % t_month_prev
elif (t_month_next < -95.0 or t_month_next > 60.0):
raise ValueError, 't_month_next=%g is not in range -95 to +60' % t_month_next
soil_heat_flux = 0.07 * (t_month_next - t_month_prev)
return soil_heat_flux
|
fa2e19f5f9839f4c75fcfee15c10b5227e2e1d6b
| 238,263 |
def get_number_base(bitstring, base):
"""Transfer bitstring to a number in base `base`."""
nr = 0
for place, bit in enumerate(bitstring[::-1]):
nr += base**place * int(bit)
return nr
|
1a54f84dd67b245009831258b7e50a28924e7f5b
| 637,916 |
import re
def install_package_family(pkg):
"""
:param: pkg ie asr900rsp2-universal.03.13.03.S.154-3.S3-ext.bin
:return: device_type of the installed image ie asr900
"""
img_dev = None
m = re.search(r'(asr\d+)\w*', pkg)
if m:
img_dev = m.group(1)
return img_dev
|
b344d51ae426e167dbd2397ab93cbf8707b01496
| 708,790 |
def expectationFromObservationDF1(observation):
"""Returns the expectation values for observation values, assuming a table
of two columns and two rows represented in a value list observations.
That is, the first two values are assumed to be row 1, the second two
values are assumed to be row 2.
A table like:
-----------------------------------
| | class | not class |
|-----------------------------------|
| token | 34 | 4567 |
| not token | 16356 | 34985737 |
-----------------------------------
is mapped on a list like this, i.e. observations is
( 34, 4567, 16356, 34985737 )
the returned corresponding expected values would be:
(2.15417057091995, 4598.84582942908, 16387.84582942908, 34985705.15417057)
"""
if len(observation) == 4:
rowtotal1 = sum(observation[:2])
rowtotal2 = sum(observation[2:])
columntotal1 = sum(observation[::2])
columntotal2 = sum(observation[1::2])
total = sum(observation)
return ( (rowtotal1 * columntotal1) / total,
(rowtotal1 * columntotal2) / total,
(rowtotal2 * columntotal1) / total,
(rowtotal2 * columntotal2) / total )
return None
|
c8f62376eb70762f5e2def6b26a56e3677cedca8
| 137,690 |
import torch
def h_inverse(x, epsilon=1.0):
"""Inverse if the above h-function, described in the paper [1].
If x > 0.0:
h-1(x) = [2eps * x + (2eps + 1) - sqrt(4eps x + (2eps + 1)^2)] /
(2 * eps^2)
If x < 0.0:
h-1(x) = [2eps * x + (2eps + 1) + sqrt(-4eps x + (2eps + 1)^2)] /
(2 * eps^2)
"""
two_epsilon = epsilon * 2
if_x_pos = (
two_epsilon * x
+ (two_epsilon + 1.0)
- torch.sqrt(4.0 * epsilon * x + (two_epsilon + 1.0) ** 2)
) / (2.0 * epsilon ** 2)
if_x_neg = (
two_epsilon * x
- (two_epsilon + 1.0)
+ torch.sqrt(-4.0 * epsilon * x + (two_epsilon + 1.0) ** 2)
) / (2.0 * epsilon ** 2)
return torch.where(x < 0.0, if_x_neg, if_x_pos)
|
3fdf30e5b02550eadefd63e60d72794424a29202
| 270,061 |
def parse_header(line):
"""Parse output of tcpdump of pcap file, extract:
time
date
ethernet_type
protocol
source ip
source port (if it exists)
destination ip
destination port (if it exists)
length of the data
resolved addresses (if they exist, for dns traffic only)
"""
ret_dict = {}
h = line.split()
date = h[0]
time = h[1]
ret_dict['raw_header'] = line
ret_dict['date'] = date
ret_dict['time'] = time
ret_dict['ethernet_type'] = h[2]
if h[2] == 'IP6':
"""
Conditional formatting based on ethernet type.
IPv4 format: 0.0.0.0.port
IPv6 format (one of many): 0:0:0:0:0:0.port
"""
ret_dict['src_port'] = h[3].split('.')[-1]
ret_dict['src_ip'] = h[3].split('.')[0]
ret_dict['dest_port'] = h[5].split('.')[-1].split(':')[0]
ret_dict['dest_ip'] = h[5].split('.')[0]
else:
if len(h[3].split('.')) > 4:
ret_dict['src_port'] = h[3].split('.')[-1]
ret_dict['src_ip'] = '.'.join(h[3].split('.')[:-1])
else:
ret_dict['src_ip'] = h[3]
if len(h[5].split('.')) > 4:
ret_dict['dest_port'] = h[5].split('.')[-1].split(':')[0]
ret_dict['dest_ip'] = '.'.join(h[5].split('.')[:-1])
else:
ret_dict['dest_ip'] = h[5].split(':')[0]
ret_dict['protocol'] = h[6]
try:
"""
If the packet is a DNS request or response, parse it
correctly for length and if response from DNS server then
parse the addresses resolved, add to list, and enter in return
directory. 'A' if for resolved IPv4, 'AAAA' for IPv6
"""
if ret_dict['src_port'] == '53' or ret_dict['dst_port'] == '53':
ret_dict['length'] = int(h[-1][1:-1])
if ret_dict['src_port'] == '53':
resolved_addrs = []
if ' A ' in line:
for addr in line.split(' A ')[1:]:
clean_addr = addr.replace(',', '').split()[0]
resolved_addrs.append(clean_addr)
if ' AAAA ' in line:
for addr in line.split(' AAAA ')[1:]:
clean_addr = addr.replace(',', '').split()[0]
resolved_addrs.append(clean_addr)
if resolved_addrs:
ret_dict['dns_resolved'] = resolved_addrs
except:
try:
ret_dict['length'] = int(line.split(' length ')[1].split(':')[0])
except:
ret_dict['length'] = 0
return ret_dict
|
3f2e84048f0e150e780752bec2bdb8897241275a
| 565,473 |
def calculate_IoU(geom, match):
"""Calculate intersection-over-union scores for a pair of boxes"""
intersection = geom.intersection(match).area
union = geom.union(match).area
iou = intersection/float(union)
return iou
|
92480c5cc7c1e3e99b6339a950256524a017ba3a
| 664,252 |
def number_of_lines(filename=""):
"""Returns the number of lines of a text file.
Keyword Arguments:
filename {str} -- file name (default: {""})
Returns:
Int -- number of lines of a text file.
"""
with open(filename, mode="r", encoding="utf-8") as file:
return len(file.readlines())
|
63ffab8fa133356354052591e8b29101ad267ad9
| 684,676 |
def parse_data_url(data_url):
"""
Parses a data URL and returns its components.
Data URLs are defined as follows::
dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
mediatype := [ type "/" subtype ] *( ";" parameter )
data := *urlchar
parameter := attribute "=" value
This specific implementation is limited to data urls of the following
format::
dataurl := "data:" type "/" subtype ";base64" "," data
Here an example::
'data:image/jpg;base64,/9j/4SXNRXhpZg...AUAFFABRQB//Z'
References:
- http://tools.ietf.org/html/rfc2397
- http://www.askapache.com/online-tools/base64-image-converter/
:param str data_url: A data URL.
:return: Components of the data URL,
e.g. ('image', 'png', 'base64', '/9j/4S')
:rtype: tuple (datatype, subtype, encoding, data)
:raises: ValueError if data URL doesn't follow spec.
"""
if not data_url.startswith('data:'):
raise ValueError("Not a data URL: " + data_url[:40])
try:
header, data = data_url.split(',')
header = header.replace('data:', '')
mediatype, encoding = header.rsplit(';', 1)
datatype, subtype = mediatype.split('/')
except BaseException:
raise ValueError("Data URL not in correct format: " + data_url[:40])
return datatype, subtype, encoding, data
|
ebffe86b339ee7e00717842fea16ae33922becb1
| 216,918 |
def _wildcards(word, symbol="_"):
"""Return list of wildcards associated with word."""
res = []
for i in range(len(word)):
res.append(word[:i] + symbol + word[i + 1 :]) # O(L) space
return res
|
b12a7c530f7e937c1358bd2809e064419118f928
| 547,455 |
def getBuildStepVersion(step):
"""Return the unpickled builder's persistenceVersion.
The version reported in buildstep.persistenceVersion is what the currently
loaded version of buildbot expects a step to be (instead of what is pickled).
This returns what has been pickled.
"""
return getattr(step,
'buildbot.status.builder.BuildStepStatus.persistenceVersion')
|
b2f9920a22108cc8c83fd657f81ed58779320f9f
| 510,801 |
import re
def is_doi(doi: str) -> bool:
"""
check whether a string is a valid DOI
:param doi: the string to be checked
:return: True if a valid DOI, False otherwise
"""
if type(doi) is not str:
raise TypeError("The method only takes str as its input")
# prefix suffix separated by /, so split and expect two elements
parts = doi.split('/')
if len(parts) != 2:
return False
# the number after "10." starts from 1000, so \d{4,}
pattern = re.compile(r"^(doi:)?10\.(\d{4,})(\.\d+)?$")
# group(1) could be None
m = re.search(pattern, parts[0])
if m:
return True
else:
return False
|
70962bc4df333cb8c861eb37b58b049086a2d57d
| 387,349 |
def bounding_box_to_annotations(bbx):
"""Converts :any:`bob.ip.facedetect.BoundingBox` to dictionary annotations.
Parameters
----------
bbx : :any:`bob.ip.facedetect.BoundingBox`
The given bounding box.
Returns
-------
dict
A dictionary with topleft and bottomright keys.
"""
landmarks = {
'topleft': bbx.topleft,
'bottomright': bbx.bottomright,
}
return landmarks
|
41b984e7824035ebda551712b5777c2aa4269de6
| 123,298 |
def mean(data):
"""
Get mean value of all list elements.
"""
return sum(data)/len(data)
|
32884e9f1a29b2a37422ec1da04d0c59b6b67d3c
| 38,651 |
from pathlib import Path
import shutil
def pwhich(command: str) -> Path:
"""Path to given command.
shutil.which only returns a string.
:returns: Path to command
:rtype: pathlib.Path
"""
path_str = shutil.which(command)
assert path_str, f"{command} not found"
return Path(path_str)
|
a926850cab35bace6c2187933438c44001d01eeb
| 643,347 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.