content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import random
def get_random_string(length):
"""Gets a random string of specified length."""
sample_letters = 'abcdefghijklmnopqrstuvwxyz1234567890'
return ''.join([random.choice(sample_letters) for _ in range(length)]) | 14d67fcaea60b7b1ed3a80260623db0ac60876cd | 121,444 |
from datetime import datetime
def _from_yahoo_datetime(datetimestr: str) -> datetime:
""" From format `YYYY.MM.DD(d)HH:MM
Parameters
----------
datetimestr : str
String of datetime on a Yahoo Auction page.
Returns
-------
datetime
"""
year: int = int(datetimestr[:4])
month: int = int(datetimestr[5:7])
day: int = int(datetimestr[8:10])
hour: int = int(datetimestr[13:15])
min: int = int(datetimestr[16:18])
return datetime(year, month, day, hour, min) | 98efc06488a58ec87080a6931e21e8a7e99304e5 | 121,451 |
from datetime import datetime
def get_datetime_now_formatted() -> str:
""" Gets a string of the current date and time
in format: Jul 11 2019: 1:28 PM"""
return datetime.now().strftime("%b %d %Y, %-I:%M %p") | 363e406805e2ed098aad7518cce3daf72fefff09 | 121,455 |
def toBaseUnits(q):
""" Return magnitude of quantity `q` converted to base units
* * Used for polygons * *
Args:
q (:class:`qcobj.qconfigobj.Q_`): instance
Returns:
magnitude of q in base units
"""
return q.to_base_units().magnitude | df0a33bedd1c15c6f76f51b5989a078483107460 | 121,461 |
import re
def get_message_list(path):
"""get list of messages from a code file"""
messages = []
with open(path, 'r') as sourcefile:
txt = sourcefile.read()
messages += re.findall('_\("([^"]*)".*\)', txt)
messages += re.findall("_\('([^']*)'.*\)", txt)
messages += re.findall('_\("{3}([^"]*)"{3}.*\)', txt, re.S)
return messages | 0f04a0a07e53ec506dc9cfd3e10556bb57fcc77f | 121,465 |
from typing import Any
def keep_each_tree_predicate(
y: Any, raw_predictions: Any, previous_loss: float, current_loss: float
) -> bool:
"""This predicate will always return True.
This implies that every new tree will be used in the ensemble."""
return True | 78b6c3c3867c36361eab4c2d5a136ef5aaf62b68 | 121,467 |
import math
def format_duration(total_seconds):
"""Formats duration (in seconds) as human readable value e.g. 1h 30min"""
if not total_seconds:
return ""
rv = []
if total_hours := math.floor(total_seconds / 3600):
rv.append(f"{total_hours}h")
if total_minutes := round((total_seconds % 3600) / 60):
rv.append(f"{total_minutes}min")
return " ".join(rv) if rv else "<1min" | f78c5a4cf198534eaa12dbb131c675a54535cf4f | 121,468 |
from pathlib import Path
import json
from typing import List
def is_asciicast(file_path: Path) -> bool:
"""
is_asciicasts checks whether or not a file is an Asciinema recording
by looking at the contents of the file's first line. In an asciicast
v2 file, the first line should contain certain keys like "width",
"height" and others.
See: https://github.com/asciinema/asciinema/blob/develop/doc/asciicast-v2.md
Args:
file_path (Path): A path towards the file that will be checked.
Returns:
bool: Whether or not the file is an asciicast v2 file.
"""
with open(file_path, "r") as stream:
try:
first_line: str = stream.readline()
except Exception as err:
return False
try:
parsed: dict = json.loads(first_line)
except Exception as err:
return False
all_keys = parsed.keys()
want: List[str] = ["version", "width", "height", "timestamp", "env"]
for item in want:
if item not in all_keys:
return False
if parsed["version"] != 2:
return False
return True | 70128934a30d96ac3324deb6469c0150c42094fc | 121,471 |
def get_ssp_rk_coefficients(K):
"""
Get coefficients for the strong stability-preserving
Runge-Kutta method of order K. May return more stages
S than the order K to avid negative B coeffients and
provide more CFL stability (S >= K).
Returns RK SSP coefficients A, B and the effective CFL
multiplier C
See i.e
Ruuth - 2005 - "Global optimization of Explicit
Strong-Stability-Preserving Runge-Kutta methods",
Kubatko et al - 2008 - "Time step restriction for
Runge-Kutta discontinuous Galerkin methods on
triangular grids",
and several others starting with Shu & Osher (1988)
"""
C = 1.0
if K == 1:
# SSP(1,1): Forward Euler
A = [[1]]
B = [[1]]
elif K == 2:
# SSP(2,2): Two stage RK2 scheme
A = [[1], [1 / 2, 1 / 2]]
B = [[1], [0, 1 / 2]]
elif K == 3:
# SSP(3,3): Three stage RK3 SSP scheme
A = [[1], [3 / 4, 1 / 4], [1 / 3, 0, 2 / 3]]
B = [[1], [0, 1 / 4], [0, 0, 2 / 3]]
elif K == 4:
# SSP(5,4): five stage RK4 SSP scheme
A = [
[1.0],
[0.444370493651235, 0.555629506348765],
[0.620101851488403, 0, 0.379898148511597],
[0.178079954393132, 0, 0, 0.821920045606868],
[0, 0, 0.517231671970585, 0.096059710526147, 0.386708617503269],
]
B = [
[0.391752226571890],
[0, 0.368410593050371],
[0, 0, 0.251891774271694],
[0, 0, 0, 0.544974750228521],
[0, 0, 0, 0.063692468666290, 0.226007483236906],
]
C = 1.50818004918983
else:
raise NotImplementedError('No SSP RK method of order %d implemented' % K)
return A, B, C | b9573174db2d7ee94539ebcef5bf1d3ecab4eba6 | 121,474 |
def format_dna(dna, width=80):
"""
Format dna so each line is a fixed width.
Parameters
----------
dna : str
dna sequence.
width : int, optional
Width of dna in chars. Default is 80.
"""
ret = ''
n = len(dna)
for s in range(0, n, width):
e = s + width
if e > n:
e = n
ret += dna[s:e] + '\n'
return ret | 8f757ccad3d94306432c394f61c23e9b99a56391 | 121,477 |
import configparser
def readconf(filename='./parameters.txt'):
"""This function reads the input parameters from a file
Args:
filename: Input file in Windows .ini format. Comments should be provided as "#"
Returns:
conf: Configuration data.
"""
conf=configparser.ConfigParser(inline_comment_prefixes=('#'))
conf.read(filename)
return conf | e87e99ddaa6d29e51ef2d4994de28dd38591854b | 121,478 |
def convert_date(date):
"""
@brief: Convert date format from `dd.mm.yyyy` to `yyyy-mm-dd`
@param date: Input date
@return: Date in new format
@since: 1.0
"""
return date[6:] +'-'+ date[3:5] +'-'+ date[:2] | 69f53226de9c80a6f8bfc7dca27f02d37a7477b2 | 121,480 |
def find(node, key):
"""Find a node with a given key within a BST."""
# For a balanced BST, this func only takes O(log N); otherwise it's O(N)
if node is None:
return None
if key == node.key:
return node
if key < node.key:
return find(node.left, key)
if key > node.key:
return find(node.right, key) | 0d503ad9ecaac27d46db729a810975397f9dd768 | 121,481 |
def _int_lossless(v: float) -> int:
""" Convert *v* to an integer only if the conversion is lossless, otherwise raise an error. """
assert v % 1.0 == 0.0, f'expected int, got {v!r}'
return int(v) | 879a1fe61e797ca6df2a45f50f5389fbf3d86d56 | 121,491 |
import re
def _reformat_url_to_docusaurus_path(url: str) -> str:
"""Removes the site portion of a GE url.
Args:
url: the url including the GE site that should be converted to a Docusaurus absolute link.
"""
return re.sub(r"^https://docs\.greatexpectations\.io", "", url).strip() | 0a66c5abb6a58bfa65ede195c0deaab64e1b3ead | 121,494 |
def subtype_ids(elements, subtype):
"""
returns the ids of all elements of a list that have a certain type,
e.g. show all the nodes that are ``TokenNode``\s.
"""
return [i for (i, element) in enumerate(elements)
if isinstance(element, subtype)] | 0d3e6293c6f73b97eb513f40e13fcb696a972a81 | 121,495 |
import struct
def decode_ieee(val_int, double=False):
"""Decode Python int (32 bits integer) as an IEEE single or double precision format
Support NaN.
:param val_int: a 32 or 64 bits integer as an int Python value
:type val_int: int
:param double: set to decode as a 64 bits double precision,
default is 32 bits single (optional)
:type double: bool
:returns: float result
:rtype: float
"""
if double:
return struct.unpack("d", struct.pack("Q", val_int))[0]
else:
return struct.unpack("f", struct.pack("I", val_int))[0] | a396281a4e2640ffbd385b9edbf8c0484d51e3d4 | 121,500 |
def make_identifier(classname):
"""
Given a class name (e.g. CountryData) return an identifer
for the data-table for that class.
"""
identifier = [ classname[0].lower() ]
for c in classname[1:]:
if c.isupper():
identifier.extend(["_", c.lower()])
else:
identifier.append(c)
return "".join(identifier) | a5f4a63d5d53678dc4146d1789d908371127396b | 121,503 |
def _GenerateAndClearAggregators(emitter, registers, count):
"""Prepare aggregators and emit aggregator clear code."""
emitter.EmitNewline()
emitter.EmitComment('Clear aggregators.')
aggregators = [registers.QuadRegister() for unused_i in range(count)]
for i in range(count):
if i < 3:
emitter.EmitVMov('i32', aggregators[i], emitter.ImmediateConstant(0))
else:
emitter.EmitVMov('i32', aggregators[i], aggregators[i - 3])
return aggregators | ca61b83e80e7009085d44c8ff06044abe33e53a5 | 121,508 |
def units_conversion(units_id='SI'):
"""Computes the units conversion from SI units used internally to the
desired display units.
Parameters
----------
units_id: str
String variable identifying units (English, SI) SI is the default.
Returns
-------
units: dict
dictionary of unit conversion and labels
"""
if units_id == 'SI':
units = {'L': 1,
'Q': 1,
'A': 1,
'V': 1,
'label_L': '(m)',
'label_Q': '(m3/s)',
'label_A': '(m2)',
'label_V': '(m/s)',
'ID': 'SI'}
else:
units = {'L': 1.0 / 0.3048,
'Q': (1.0 / 0.3048)**3,
'A': (1.0 / 0.3048)**2,
'V': 1.0 / 0.3048,
'label_L': '(ft)',
'label_Q': '(ft3/s)',
'label_A': '(ft2)',
'label_V': '(ft/s)',
'ID': 'English'}
return units | 6c7e7dbaa9c71b7b9db172041b4654200b617102 | 121,512 |
import re
def get_first_number(input_string, as_string=False):
"""
Returns the first number of the given string
:param input_string: str
:param as_string: bool, Whether the found number should be returned as integer or as string
:return: variant, str || int
"""
found = re.search('[0-9]+', input_string)
if not found:
return None
number_str = found.group()
if not number_str:
return None
if as_string:
return number_str
number = int(number_str)
return number | d5ae0b0485dbda62ee42ce9d68c1b6dc5cd0bf30 | 121,515 |
def find_max_conflicts(conflicting_ids, cm, id_to_pr):
"""Return region ID of the region involved in the most conflicts
conflicting_ids -- list of PairedRegion IDs
cm -- ConflictMatrix object
id_to_pr -- dict of {region ID: PairedRegion}. Result of
PairedRegions.byId() method.
This methods returns the region ID (out of conflicting_ids) involved
in the most conflicts. If there is a single region with the most
conflicts, return it. Otherwise compare all regions with the
max number of conflicts on their gain. Gain is the length of
the region minus the cumulative length of all of its conflicting
regions. Return the one with the minimum gain. If both properties
are equal, return the region that starts closest to the 3' end.
"""
number_of_conflicts = {}
for pr_id in conflicting_ids:
noc = len(cm.conflictsOf(pr_id))
if noc not in number_of_conflicts:
number_of_conflicts[noc] = []
number_of_conflicts[noc].append(pr_id)
max_noc = max(number_of_conflicts.keys())
max_ids = number_of_conflicts[max_noc]
if len(max_ids) == 1:
return max_ids[0]
else:
len_diffs = {}
for pr_id in max_ids:
pr_len = id_to_pr[pr_id].Length
conf_len = sum([id_to_pr[i].Length for i in cm.conflictsOf(pr_id)])
diff = pr_len - conf_len
if diff not in len_diffs:
len_diffs[diff] = []
len_diffs[diff].append(pr_id)
min_ld = min(len_diffs.keys())
min_ids = len_diffs[min_ld]
if len(min_ids) == 1:
return min_ids[0]
else:
start_vals = {}
for pr_id in min_ids:
start = id_to_pr[pr_id].Start
start_vals[start] = pr_id
max_start = max(start_vals.keys())
return start_vals[max_start] | 6405580954956eae0ae1cc45c0dac9b622fc3dc7 | 121,518 |
def check_repeated(str1, str2):
"""
Given 2 string check if these strings have a diff of 1 character
if it's the case return the position of the character otherwise return None
"""
assert len(str1) == len(str2)
position = None
quantity = 0
for i in range(len(str1)):
if str1[i] != str2[i]:
quantity += 1
position = i
if quantity == 1:
return position
else:
return None | c6ad629c5c068bd763597c0bb1c384dbb7166c39 | 121,519 |
def tryfunc(func, arg):
"""
Return func(arg) or None if there's an exception.
"""
try:
return func(arg)
except:
return None | 5cb7587d619c01df3486e196a969f2d05a31479b | 121,523 |
def get_pixel_values(arr,pixels):
"""Get values of arr at pixels specified in pixels (Npix,2)"""
return arr[...,pixels[:,0],pixels[:,1]] | 1cba477b9d66a9cf9e6c7c935a0b4e56c46499d6 | 121,524 |
def get_line(pt1, pt2):
"""get line slope and bias from two points
y = slope * x + bias
"""
slope, bias = None, None
if pt1[0] != pt2[0]:
slope = (pt1[1] - pt2[1]) / (pt1[0] - pt2[0])
bias = pt1[1] - slope * pt1[0]
return slope, bias | f5b6482c1a6ad8adfcb4e83394b162af25d955f8 | 121,528 |
def adapt_list(lst) -> str:
"""
Adapt list entries before writing to database.
This function takes a list and serializes it in order to
write it to the sqlite database as string.
"""
return '|'.join(lst) | db9bd6a5c2a3e1c14659e72ca4bf9789b87f4586 | 121,530 |
def phrase_event(callbacks, parameters):
"""
Custom call for events with keywords in sentences (like say or whisper).
Args:
callbacks (list of dict): the list of callbacks to be called.
parameters (str): the actual parameters entered to trigger the callback.
Returns:
A list containing the callback dictionaries to be called.
Notes:
This function should be imported and added as a custom_call
parameter to add the event when the event supports keywords
in phrases as parameters. Keywords in parameters are one or more
words separated by a comma. For instance, a 'say yes, okay' callback
can be set to trigger when the player says something containing
either "yes" or "okay" (maybe 'say I don't like it, but okay').
"""
phrase = parameters.strip().lower()
# Remove punctuation marks
punctuations = ',.";?!'
for p in punctuations:
phrase = phrase.replace(p, " ")
words = phrase.split()
words = [w.strip("' ") for w in words if w.strip("' ")]
to_call = []
for callback in callbacks:
keys = callback["parameters"]
if not keys or any(key.strip().lower() in words for key in keys.split(",")):
to_call.append(callback)
return to_call | 136ddb8264eaa39d40fa94f201bdc9cf2afce2e3 | 121,531 |
def get_course_masquerade(user, course_key):
"""
Returns the masquerade for the current user for the specified course. If no masquerade has
been installed, then a default no-op masquerade is returned.
"""
masquerade_settings = getattr(user, 'masquerade_settings', {})
return masquerade_settings.get(course_key, None) | dcea62731779bd3be20005c514dfe34130f4bea5 | 121,532 |
def replace_date(source_date, target_date):
"""Replaces `source_date` with respect to `target_date`, replacing year,
month, day while preserving all other time information. The purpose of this
method is to provide valid date information for recurring reservations.
"""
return source_date.replace(
year=target_date.year, month=target_date.month, day=target_date.day) | 61f82c1fbb7a8e29f8d99c54699c29134d27e447 | 121,534 |
def get_argument(request, key, default_value):
"""Returns the request's value at key, or default_value
if not found
"""
if key in request.args:
return request.args[key][0]
return default_value | 9943393f1239ebc3e19702210a14ad3e8132a03b | 121,538 |
def length_function(list_of_values):
"""
finds the combined length of all sub-lists
:param list_of_values:
:return: combined length of all sub-lists
"""
counter = 0
for local_list in list_of_values:
counter += len(local_list)
return counter | 72e203c4d132b08c235a76f06c2e3153211e91c6 | 121,541 |
def matrix_transpose(matrix):
"""
Function to transpose a Matrix
Returns the transpose of a 2D matrix
"""
return [[matrix[j][i] for j in range(len(matrix))]
for i in range(len(matrix[0]))] | bbe1d600f622140d16e012d9f3c243f6673ac584 | 121,544 |
def IS(l,u,y,q):
"""
calculation of the Interval Score
l: left interval limit
u: right interval limit
y: argument of IS
q: quantile level corresponding to limits
Output
IS value in y for given l,u,q
"""
if y<l:
return 2*(l-y) + q*(u-l)
elif y>u:
return 2*(y-u) + q*(u-l)
else:
return q*(u-l) | f7cdda3d5de1a61ec2341faf0bd788dd4f9e0356 | 121,545 |
def project(data, mask, axis=None):
"""Project a slice of `data` where `mask` is True along `axis`."""
return data.compress(mask, axis=axis).sum(axis=axis) | 9afdbad3cf7d9e3cf8318f25cc23e34723871626 | 121,548 |
def _months_in_range(min_date, max_date):
"""Get a range of months between min_date and max_date, inclusive"""
months = []
for year in range(min_date.year, max_date.year + 1):
for month in range(1, 13):
if year == min_date.year and month < min_date.month:
continue
elif year == max_date.year and month > max_date.month:
continue
else:
months.append((year, month))
return months | 8487a52bc292da0a014b8d1cd7a57cf1f005431c | 121,553 |
def detrend_rm(array,days=213*5):
"""Alternate detrending method that removes the 5-year moving average over winter"""
return array - array.rolling(time=days,center=True,min_periods=1).mean() | 2d4e6ae5ef72377dde11486988dffe57fc2d3e98 | 121,560 |
import pathlib
def make_dir(path: pathlib.Path) -> pathlib.Path:
"""
Checks that path is a directory and then creates that directory if it doesn't exist
Parameters
----------
path: pathlib.Path
Directory to check
Returns
-------
pathlib.Path
Path to directory
"""
if path.is_file():
raise IOError(f"{path} is a file - must pass a directory")
if not path.exists():
path.mkdir(parents=True)
return path | 2c592d67bdd80a93ca7fc2d400f8a885ae36ad66 | 121,561 |
def get_data(file):
"""
Opens a file, and reads in data.
Parameters:
file - file path
Returns:
data - array of strings
"""
f = open(file,'r')
data = f.read()
f.close()
return data | 1f70681ff8d0c1e8f12db3dce0776b57540c703e | 121,562 |
def extract_molist_from_method_response(method_response,
in_hierarchical=False):
"""
Methods extracts mo list from response received from imc server i.e.
external method object
Args:
method_response (ExternalMethod Object): response
in_hierarchical (bool): if True, return all the hierarchical child of
managed objects
Returns:
List of ManagedObjects
Example:
response = handle.query_dn("sys/rack-unit-1", need_response=True)\n
molist = extract_molist_from_method_response(method_response=response,
in_hierarchical=True)
"""
mo_list = []
if hasattr(method_response, "out_config"):
if len(method_response.out_config.child) == 0:
return mo_list
else:
if len(method_response.out_configs.child) == 0:
return mo_list
if in_hierarchical:
if hasattr(method_response, "out_config"):
current_mo_list = method_response.out_config.child
else:
current_mo_list = method_response.out_configs.child
while len(current_mo_list) > 0:
child_mo_list = []
for mo in current_mo_list:
mo_list.append(mo)
while mo.child_count() > 0:
for child in mo.child:
mo.child_remove(child)
child.mark_clean()
child_mo_list.append(child)
break
current_mo_list = child_mo_list
else:
mo_list = method_response.out_configs.child
return mo_list | 9a828bd26ee825abc653124f9a00e17be8a5d22c | 121,566 |
def leading_zeros(l,n):
"""
If list l has less than n elements returns l with enough 0 elements
in front of the list to make it length n.
"""
if len(l) < n:
return(([0] * (n - len(l))) + l)
else:
return l | 1714194326b099289a92ad6c11f47f4849aec128 | 121,571 |
def cleanup_community(community):
"""Given a dictionary of a community, return a new dictionary for output as
JSON."""
comm_data = community
comm_data["id"] = str(community["_id"])
comm_data["user"] = str(community["user"])
del comm_data["_id"]
return comm_data | 949202252b4b3318c9fccaff016b723961161092 | 121,581 |
import pytz
def convert_to_UTC(dt):
"""
This function converts a datetime object with timezone information to a datetime object in UTC.
"""
tz_utc = pytz.utc
dt_utc = dt.astimezone(tz_utc)
return dt_utc | 02747a5b31cd6e5ac7443314aad9b640b01b5395 | 121,585 |
def cnvrt(val: str) -> str:
"""Convert special XML characters into XML entities."""
val = str(val)
val = val.replace("&", "&")
val = val.replace('"', """)
val = val.replace("'", "'")
val = val.replace("<", "<")
val = val.replace(">", ">")
return val | eec021eebd52fc4a9747d355bf5524002c0a632a | 121,590 |
def newer_103(splitos, third):
"""
Return True if given split OS version is 10.3.X or newer.
:param splitos: OS version, split on the dots: [10, 3, 3, 2205]
:type: list(int)
:param third: The X in 10.3.X.
:type third: int
"""
newer = True if ((splitos[1] >= 4) or (splitos[1] == 3 and splitos[2] >= third)) else False
return newer | 20fbf034be6a03f18ccc5326e7860c8a76363aab | 121,596 |
def polygon_centroid(*points):
"""
Calculates center point of given polygon.
Args:
points: ((float, float),)
Collection of points as (x, y) coordinates.
Returns:
(float, float)
Center point as (x, y) coordinates.
"""
x = sum(p[0] for p in points) / len(points)
y = sum(p[1] for p in points) / len(points)
return x, y | d666c4911b5dba0fabc20c5bb7183d2531bc0788 | 121,599 |
def create_cursor_from_old_cursor(old_cursor, table_class):
"""This method creates the cursor from an existing cursor.
This is mainly used for creating lookup cursor during db operations on
other database tables.
Args:
old_cursor: existing cursor from which important params are evaluated.
table_class: table for which the cursor is being created.
Returns:
cursor
"""
cursor = table_class.create_vtgate_cursor(old_cursor._conn,
old_cursor.tablet_type,
old_cursor.is_writable())
return cursor | 2d06f9bc2031797bcad84b09f5ef2e878a421e7a | 121,600 |
def legendre_symbol(a, p):
"""Compute the Legendre symbol."""
if a % p == 0: return 0
ls = pow(a, (p - 1)//2, p)
return -1 if ls == p - 1 else ls | 50869b86c42629c49ffb36db606bab616b21ea8a | 121,608 |
def _get_size(max_size, image):
"""
Returns a 2-tuple of (width, height).
Calculates a new width and height given a width, height.
The larger of the width and height will be the max_size
The smaller of the two will be calculated so that the ratio is the
same for the new width and height.
"""
width = image.size[0]
height = image.size[1]
if width > height:
return max_size, int(max_size * height / width)
else:
return int(max_size * width / height), max_size | 2a652c50fa0cd9ecd86752e1c89816cddc18bdf7 | 121,623 |
def _binary_op(fn):
"""Wrapper that restricts `fn` to have the correct signature."""
def binary_op_wrapper(x, y, name=None):
return fn(x, y, name=name)
return binary_op_wrapper | d0151a51586ffbe5d8a3bb8336c88c304fe09c97 | 121,626 |
def find_by_name(name, value_list):
"""Find a value in list by name."""
return next((value for value in value_list if value.name == name), None) | dd5a9cf25b301689349e84c1981bd5dca60adf75 | 121,628 |
import hmac
import hashlib
import base64
def compute_hmac_base64(key, data):
"""Return the Base64 encoded HMAC-SHA1 using the provide key"""
h = hmac.new(key, None, hashlib.sha1)
h.update(data)
return base64.b64encode(h.digest()) | 8f138b8c0bf88ebabeebc56cdae8b716d61fab22 | 121,631 |
def get_control_count(cmd):
"""
Return the number of control qubits of the command object cmd
"""
return len(cmd.control_qubits) | 405f9c525db409f4f3fb71eba9e95e0ee5a5fa1b | 121,632 |
def get_packet_ip_tos_field(packet):
"""
returns types of services field from packet
Args:
packet (`obj`): packet object obtained from scapy module
Returns:
returns types of services field
"""
return packet.get_field('tos').i2repr(packet, packet.tos) | 8ca8567a259fa48453cd69bd70884d68607ac505 | 121,633 |
def assign_gpu(tknz_out, gpu):
"""
Assign tokenizer tensors to GPU(s)
Params:
tknz_out (dict): dict containing tokenizer tensors within CPU
gpu (int): gpu device
Returns: the dict containing tokenizer tensors within GPU(s)
"""
if type(gpu) == int:
device = 'cuda:' + str(gpu)
else:
device = 'cpu'
tokens_tensor = tknz_out['input_ids'].to(device)
token_type_ids = tknz_out['token_type_ids'].to(device)
attention_mask = tknz_out['attention_mask'].to(device)
# assign GPU(s) tokenizer tensors to output dict
output = {
'input_ids': tokens_tensor,
'token_type_ids': token_type_ids,
'attention_mask': attention_mask
}
return output | 23e7b2d7c62f4be4d0514a5edda86aac745327fc | 121,634 |
def make_laser_sensor(fov, dist_range, angle_increment, occlusion):
"""
Returns string representation of the laser scanner configuration.
For example: "laser fov=90 min_range=1 max_range=10"
Args:
fov (int or float): angle between the start and end beams of one scan (degree).
dist_range (tuple): (min_range, max_range)
angle_increment (int or float): angular distance between measurements (rad).
occlusion (bool): True if consider occlusion
Returns:
str: String representation of the laser scanner configuration.
"""
fovstr = "fov=%s" % str(fov)
rangestr = "min_range=%s max_range=%s" % (str(dist_range[0]), str(dist_range[1]))
angicstr = "angle_increment=%s" % (str(angle_increment))
occstr = "occlusion_enabled=%s" % str(occlusion)
return "laser %s %s %s %s" % (fovstr, rangestr, angicstr, occstr) | fbc090a9d81f146e8948df5218eabd6758e38e1c | 121,636 |
def center_crop(img, new_width, new_height):
"""Code similar to `center_crop` in TorchVision, with changes.
Changes from TorchVision:
- Works on 2D and 3D frames, instead of 2D only
- Works on numpy ndarray frames, instead of PIL Image frames.
"""
width, height = img.shape[0], img.shape[1] # Get dimensions
left = int(round((width - new_width) / 2))
right = int(round((width + new_width) / 2))
top = int(round((height - new_height) / 2))
bottom = int(round((height + new_height) / 2))
if len(img.shape) == 2:
return img[left:right, top:bottom]
if len(img.shape) == 3:
return img[left:right, top:bottom, :]
raise ValueError(f"image shape {img.shape} can only have 2 or 3 dimensions") | 79891ec9c61e05888cb64487f07f9974ac49ca1e | 121,641 |
import string
def _ed1(token):
"""
Return tokens the edit distance of which is one from the given token
"""
insertion = {letter.join([token[:i], token[i:]]) for letter in string.ascii_lowercase for i in range(1, len(token) + 1)}
deletion = {''.join([token[:i], token[i+1:]]) for i in range(1, len(token) + 1)}
substitution = {letter.join([token[:i], token[i+1:]]) for letter in string.ascii_lowercase for i in range(1, len(token) + 1)}
transposition = {''.join([token[:i], token[i+1:i+2], token[i:i+1], token[i+2:]]) for i in range(1, len(token)-1)}
return set.union(insertion, deletion, substitution, transposition) | 2b8a2a312e2ebeeb936ee83e547824a1314ff7de | 121,642 |
def get_amount_episodes(episodes: str) -> int:
"""
Takes in the animethemes syntax of episodes and returns it's amoutn
"""
a = 0
for ep in episodes.split(', '):
if '-' in ep:
start,end = ep.split('-')
a += int(end)-int(start)
else:
a += int(ep)
return a | 29239f030a5c1a3aff7714786ab8e13241f51e74 | 121,644 |
def notas(* num, sit=False):
"""
-> Função para analisar notas e situações de vários alunos.
:param num: Uma ou mais notas dos alunos (aceita várias)
:param sit: valor opcional, indicando se deve ou não adicionar a situação
:return: dicionário com várias informações sobre a turma
"""
print('-'*75)
resumo = {}
totnum = maior = menor = soma = 0
for c, n in enumerate(num):
totnum += 1
soma += n
resumo['total'] = totnum
if c == 0:
maior = menor = n
resumo['maior'] = n
resumo['menor'] = n
else:
if n > maior:
maior = n
resumo['maior'] = maior
elif n < menor:
menor = n
resumo['menor'] = menor
resumo['média'] = soma / totnum
if sit:
if resumo['média'] >= 7:
resumo['situação'] = 'BOA'
elif resumo['média'] < 5:
resumo['situação'] = 'RUIM'
else:
resumo['situação'] = 'RAZOÁVEL'
return resumo | 5243b6d858d372bd40ae2693db25134387242fae | 121,645 |
import time
def timestr_unix(time_str):
"""
transfer formatted timestamp to unix time.
Args:
time_str (str): formated time string.
Returns:
int: unix time.
"""
time_format_with_hill = '%Y-%m-%dT%H:%M:%S.%f%z'
time_str = time_str[:26] + time_str[-6:]
time_format = time.strptime(time_str, time_format_with_hill)
return int(time.mktime(time_format)) | fcffd97576e579702634ca80f9f45b9990b47b82 | 121,647 |
def get_veth_slot_info_cmd(lpar_id, slotnum):
"""
get virtual ethernet slot information
For IVM, vswitch field is not supported.
:param lpar_id: LPAR id
:param slotnum: veth slot number
:returns: A HMC command to get the virtual ethernet adapter information.
"""
return ("lshwres -r virtualio --rsubtype eth --level "
"lpar --filter lpar_ids=%(lparid)s,slots=%(slot)s "
"-F is_trunk,trunk_priority,ieee_virtual_eth,"
"port_vlan_id,addl_vlan_ids" %
{'lparid': lpar_id, 'slot': slotnum}) | e73ee822030a1cb9b4763d97bc33b6a307077a79 | 121,648 |
def unique(seq):
"""Return True if there are no duplicate elements in sequence seq."""
for i in range(len(seq)):
for j in range(i+1, len(seq)):
if seq[i] == seq[j]:
return False
return True | ea903e71754c67e00183e8bd5b72bce708475107 | 121,652 |
def compute_gradient_LS(y, tx, w):
"""
compute the gradient of least squares model.
Input:
- y = the label
- tx = the samples
- w = the weights for LS model
Output:
- gradient = the gradient for given (y,tx,w)
"""
e = y - tx.dot(w)
n_sample = y.shape[0]
gradient = -1/n_sample*tx.T.dot(e)
return gradient | b5bcb02c442ee184a641d97bbe6d2266afa5292c | 121,653 |
def trim_whitespace(str):
"""calls .strip() on passed str"""
return str.strip() | 4650533e3eca2dd5a88b7557d6c9a4bdc85ca35a | 121,654 |
def get_swapped_indices(length):
"""Returns a list of swapped index pairs. For example, if length = 6, then
function returns [1, 0, 3, 2, 5, 4], i.e. every index pair is swapped.
Args:
length (int): Length of swapped indices.
"""
return [i + 1 if i % 2 == 0 else i - 1 for i in range(length)] | 3aed3b398b843985013da4fb7ce0411b1747b438 | 121,661 |
from pathlib import Path
import hashlib
def md5sum(path: str) -> str:
"""
Calculate the MD5 hash of a file as a hex digest
:param path:
:return:
"""
p = Path(path)
assert p.is_file()
return hashlib.md5(p.read_bytes()).hexdigest() | d3b2a825d799285593c61d403c5d88ca91dcbe2c | 121,668 |
import json
def load_json(config_path):
"""Load json file content
Args:
config_path (str): Path to json file.
Returns:
dict: config dictionary.
"""
with open(config_path, "r") as fhandle:
default_config = json.load(fhandle)
return default_config | d4924cd90857ac5b8cf63e942a6914e595132d30 | 121,669 |
def adjacent_product(grid: list[list[int]], n: int, coordinate: tuple[int, int], direction: tuple[int, int]) -> int:
"""Get product of `n` adjacent numbers in `grid`
Args:
grid: Matrix-like list
n: Number of adjacent numbers in product
coordinate: Start position in product
direction: Direction for getting adjacent numbers (vertical, horizontal, diagonal)
Examples:
>>> grid = [[8, 2, 22, 97], [49, 49, 99, 40], [81, 49, 31, 73], [52, 70, 95, 23]]
Horizontal (8 * 2 * 22 * 97):
>>> print(adjacent_product(grid, 4, (0, 0), (1, 0)))
34144
Vertical (97 * 40 * 73):
>>> print(adjacent_product(grid, 3, (3, 0), (0, 1)))
283240
Up-left to down-right diagonal (49 * 31 * 23)
>>> print(adjacent_product(grid, 3, (1, 1), (1, 1)))
34937
Up-right to down-left diagonal (97 * 99)
>>> print(adjacent_product(grid, 2, (3, 0), (-1, 1)))
"""
product = 1
for i in range(n):
number = grid[coordinate[1] + direction[1] * i][coordinate[0] + direction[0] * i]
if number == 0:
return 0
product *= number
return product | b9adfd0ba85863798d37e3a50ca5034119b49b4e | 121,670 |
def bounded(v, l, u):
"""
Returns bounded value: l if v < i, u if v > u, l otherwise
:param v: Value
:param l: Lower bound
:param u: Upper bound
:return:
"""
return min(max(v, l), u) | e30387b19038efc16bbcc88448a2a5eb3e3d32e7 | 121,674 |
def getCode(sn):
""" Gets the code, which is the last 3-4 characters of all 2008+ serial numbers, depending on length """
return sn[8:] | ce5e18b58c8172852faac149351141df16520b04 | 121,676 |
def first_element(array):
"""
returns the first element of an array or the value of an scalar.
Parameters
----------
array : xarray.DataArray
array with 0 or more dimensions.
Returns
-------
float :
first value.
"""
if array.size > 1:
return float(array[0])
else:
return float(array) | 9c5be6cb160629f2a60121428a359a1e5e18511a | 121,678 |
from urllib.request import urlopen
import gzip
def tomso_open(filename, *args, **kwargs):
"""Wrapper function to open files ending with `.gz` with built-in
`gzip` module or paths starting with `http` using
`urllib.request.urlopen`, otherwise use normal open. `.gz` and
normal modes take the same arguments as `open` and `gzip.open` and
return a file object."""
if filename.startswith('http'):
return urlopen(filename)
elif filename.lower().endswith('.gz'):
return gzip.open(filename, *args, **kwargs)
else:
return open(filename, *args, **kwargs) | 73e27a7e2b6ac928f3f368b129c115efb3c9ec15 | 121,680 |
def get_local_id_from_curie_id(curie_id: str):
"""
This function returns the local ID from a CURIE ID, where a CURIE ID consists of "<Prefix>:<Local ID>".
For example, the function would return "C3540330" for CURIE ID "umls:C3540330".
"""
assert ':' in curie_id
return curie_id.split(':')[1] | 4d264d6cd5f54c7bd7d0386025fd876e626e74f3 | 121,681 |
def DoNotEdit(prefix='# '):
"""Return standard warning to generated files"""
t = [ '',
'WARNING: This file is generated do not edit.',
'',
'Contents written by Stacki.',
'' ]
s = ''
for line in t:
s += '%s%s\n' % (prefix, line)
return s | 4428f7d49ffc699eec15f1d39e62856424507951 | 121,682 |
def get_validation_data(error):
"""
Returns custom validation message based on error
:param error: {ValidationError} error
:return: {tuple} messsage, errors
"""
errors = None
message = error.schema.get('message') or error.message
messages = error.schema.get('messages')
if messages is not None:
validator = error.validator if error.validator in messages else 'default'
if messages.get(validator) is not None and error.path[0]:
message = messages.get(validator)
errors = { error.path[0]: [ messages.get(validator) ] }
return message, errors | ee7e8c1e2b7da71b0ee160bf922fe3c733e32fda | 121,683 |
from datetime import datetime
import pytz
def from_timestamp(value):
"""Transform a timestamp in a tz-aware datetime."""
if isinstance(value, int) or isinstance(value, float):
return datetime.fromtimestamp(value, pytz.utc)
return None | 6a3a66fa5b3c06bb505b7935630e385564650f9b | 121,685 |
def rename_key(key):
"""Rename state_dict key."""
# ResidualBlockWithStride: 'downsample' -> 'skip'
if ".downsample.bias" in key or ".downsample.weight" in key:
return key.replace("downsample", "skip")
return key | d7a5638fca107ea31d6910ce7730c4376fdeedd6 | 121,687 |
from math import cos, sin, pi
def laglongToCoord(theta: float, phi: float):
"""Convert lagtitude and longitude to xyz coordinate."""
theta, phi = theta/180*pi, phi/180*pi
return sin(theta)*cos(phi), sin(phi), cos(theta)*cos(phi) | 13faf15366badec7718c6fc04b2fdf04dc597927 | 121,689 |
import re
import string
def clean_str(inp_str: str) -> str:
"""Removes non printable characters from the string
Reference:
https://stackoverflow.com/a/52540226
Arguments:
inp_str {str} -- The input string, to be cleaned.
Returns:
{str} -- The cleaned string
"""
return re.sub(f'[^{re.escape(string.printable)}]', '', inp_str) | 36a42eacc070a32b41934b9cdf55d8d59b1b4182 | 121,690 |
def reformat_filter(fields_to_filter_by):
"""Get a dictionary with all of the fields to filter
Args:
fields_to_filter_by (dict): Dictionary with all the fields to filter
Returns:
string. Filter to send in the API request
"""
filter_req = ' and '.join(
f"{field_key} eq '{field_value}'" for field_key, field_value in fields_to_filter_by.items() if field_value)
return filter_req | ba8da8efe456c47d2b9598126812647ea8120185 | 121,696 |
def process_longitude(cell):
"""Return the longitude from a cell."""
long = cell.strip().split("/")[1]
long = long.strip()
if len(long) == 8:
sign = 1
long = long[:7]
else:
sign = -1
if long[0] == "0":
deg = int(
str(long[1]) + str(long[2]),
)
else:
deg = int(
str(long[0]) + str(long[1]) + str(long[2]),
)
return sign * float(
deg
+ int(
str(long[3]) + str(long[4]),
) / 60
+ int(
str(long[5]) + str(long[6]),
) / 3600
) | ae14421b84e931009bec9d23c31a639d234c2665 | 121,699 |
def get_speed_grade(config):
"""
Returns the speed associated with this device
Args:
config (dictionary): configuration dictionary
Return:
(string) speed code (-1, -2, -3, -1L, etc...)
Raises:
Nothing
"""
#split the device value with "-" and get the last value
#add the '-' back on when it is returned
speed = config["device"].split("-")[-1]
speed = speed.strip()
speed = "-%s" % speed
return speed | 540112050b8a4386d6f44d4ec163190416cc4efa | 121,701 |
def _filepath_to_path(filepath):
"""
Convert FilePath to a regular path.
"""
return filepath.path | db1094b99d9296c8e44b471de30eee37b41ac253 | 121,702 |
import torch
def torch_quadratic(array, matrix):
"""Compute the quadratic form in pytorch.
Parameters
----------
array : torch.Tensor
matrix : torch.Tensor
Returns
-------
ndarray
The quadratic form evaluated for each x.
"""
squared_values = array * (array @ matrix)
return torch.sum(squared_values, dim=-1, keepdim=True) | f8e25b9cca99e8e9547409fe684759c42a2e3dc9 | 121,706 |
import torch
def rot_matrix_from_quaternion(q):
"""
Construct rotation matrix from quaternion
"""
# Shortcuts for individual elements (using wikipedia's convention)
qi, qj, qk, qr = q[..., 0], q[..., 1], q[..., 2], q[..., 3]
# Set individual elements
R00 = 1.0 - 2.0 * (qj ** 2 + qk ** 2)
R01 = 2 * (qi * qj - qk * qr)
R02 = 2 * (qi * qk + qj * qr)
R10 = 2 * (qi * qj + qk * qr)
R11 = 1.0 - 2.0 * (qi ** 2 + qk ** 2)
R12 = 2 * (qj * qk - qi * qr)
R20 = 2 * (qi * qk - qj * qr)
R21 = 2 * (qj * qk + qi * qr)
R22 = 1.0 - 2.0 * (qi ** 2 + qj ** 2)
R0 = torch.stack([R00, R01, R02], dim=-1)
R1 = torch.stack([R10, R11, R12], dim=-1)
R2 = torch.stack([R10, R21, R22], dim=-1)
R = torch.stack([R0, R1, R2], dim=-2)
return R | 80a7a7110bde1377b7a1ed4c77ad67d5fbf6d688 | 121,714 |
def dump_table(dynamodb_table):
"""Downloads the contents of a dynamodb table and returns them as a list.
Iterates through the contents of a dynamodb scan() call, which returns a
LastEvaluatedKey until there are no results left in the scan. Appends each
chunk of data returned by scan to an array for further use.
Args:
dynamodb_table: A boto3 Table object from which all data will be read
into memory and returned.
Returns:
A list of items downloaded from the dynamodb table. In this case, each
item is a bus route as generated in initialize_db.py.
"""
result = []
response = dynamodb_table.scan()
result.extend(response['Items'])
while 'LastEvaluatedKey' in response.keys():
response = dynamodb_table.scan(ExclusiveStartKey=response['LastEvaluatedKey'])
result.extend(response['Items'])
return result | 67eae0bf4feaa0005ee2e9327e4eacfd88ae4c88 | 121,715 |
from typing import List
import json
def load_json(file: str) -> List[List[str]]:
"""
Loads json file and returns list of list
:param file: Path to file to load
:return: List of lists from loaded JSON
"""
with open(file) as f:
ret: List[List[str]] = json.load(f)
return ret | 00f458b7e967c0536c09a0325ed816587ded376b | 121,717 |
def info_fn(book_id):
"""
Construct filename for info.xml file.
Args:
book_id (int/str): ID of the book, without special characters.
Returns:
str: Filename in format ``info_BOOKID.xml``.
"""
return "info_%s.xml" % str(book_id)
# return "info.xml" | 1a889fd88705c529165d8acf87b05862200c08fa | 121,719 |
def parse_pid(pid):
""" Parse the mesos pid string,
:param pid: pid of the form "id@ip:port"
:type pid: str
:returns: (id, ip, port)
:rtype: (str, str, str)
"""
id_, second = pid.split('@')
ip, port = second.split(':')
return id_, ip, port | 5a154390c96f97df8cbeb93e7ee3127b2d469141 | 121,721 |
def translate_to_bytes(value: str) -> float:
"""
This is a helper function to convert values such as 1PB into a bytes.
:param value: str. Size representation to be parsed
:return: float. Value in bytes
"""
k = 1024
sizes = [
"KB",
"MB",
"GB",
"TB",
"PB"
]
if value.endswith("Bytes"):
return float(value.rstrip("Bytes"))
else:
for power, size in enumerate(sizes, 1):
if value.endswith(size):
return float(value.rstrip(size)) * (k ** power)
raise ValueError("Cannot translate value") | e058ee8f5be783e52cff32f35b7378944a4284b0 | 121,724 |
def _RemovePrefix(path, prefix):
"""Removes prefix from path if path starts with prefix. Returns path."""
return path[len(prefix):] if path.startswith(prefix) else path | 94c2b376888f7833f5f89ecdb35c09cd437eb7ce | 121,725 |
def previous_real_word(words, i):
"""Returns the first word from words before position i that is non-null"""
while i > 0:
i -= 1
if words[i] != "":
break
return words[i] | 917817794afc049f0439cf4c991693f4c6a74cef | 121,726 |
def clean_codebook(codebook):
"""Clean the codebock and add information about column type.
This function:
* indexes the dataframe on the ``variable`` column
* adds a data type column which is used for cleaning
* drops one column which does not appear in the data
* adds a missing space in a value in the coding column to aid in
parsing coding strings when recoding values
* adds a missing sentinel value for child weight variables
* renames the ``health_care_experience`` column to ``hce``
Args:
codebook (dataframe): original GHDx codebook
Returns:
(dataframe)
"""
df = codebook.set_index('variable')
df.loc[df.coding.notnull(), 'type'] = 'categorical'
df.loc[df.coding.isnull(), 'type'] = 'numeric'
df.loc[df.index.str.startswith('word_'), 'type'] = 'word'
df.loc[['site', 'g2_01', 'g2_02'], 'type'] = 'info'
# Some numeric variables have a sentinel value for missing which appears
# in the coding coding. This value is always a set of 9s as "Don't Know"
# Since this is the only coding it appears at the begining of the string
num_with_dk = df.coding.str.contains('^9+ "Don\'t Know"').fillna(False)
df.loc[num_with_dk, 'type'] = 'numeric'
# These regexs are designned to NOT match the string '[specify unit]',
# which is a numeric encoding of the unit
freetext_re = 'specified|, specify|from the certificate|Record from where'
df.loc[df.question.str.contains(freetext_re), 'type'] = 'freetext'
# This columns is not actually in the data
df.drop('gs_diagnosis', inplace=True)
# The codebook is missing a space between the 1 and "Grams" which causes
# the mapping from coding function to fail
df.loc['c1_08a', 'coding'] = ('1 "Grams" 8 "Refused to Answer" '
'9 "Don\'t Know"')
# The codebook does not mention that the values 9999 is used as a sentinel
# for missing for child weight at previous medical visits
df.loc[['c5_07_1', 'c5_07_2'], 'coding'] = '9999 "Don\'t Know"'
df.rename(columns={'health_care_experience': 'hce'}, inplace=True)
order = ['question', 'module', 'type', 'hce', 'coding']
return df[order] | 4392cbe8bd4084b0572bec59befa91d8e46e03f9 | 121,729 |
def getTabName(header, index):
"""Get the name of the table at index from above tables generator.
Expects the header string and the index of the table."""
name = header.rindex(' ', 0, index) #start of the name.
return header[name + 1: index] | f69391404758a6a41784113cc46ccdcd4e6f3508 | 121,733 |
def convert_to_minutes(seconds_played):
"""
Converts seconds into minutes.
:param seconds_played:
:return: Minutes played
:rtype: float
"""
minutes = seconds_played / 60.0
return round(minutes, 2) | d96a306bc3e0c0c047cc155fbd074c6debff832f | 121,740 |
def _geo_sum(r: int, n: int):
"""Calculate the geometric sum for ratio, r, and number of terms, n."""
return (1 - r ** n) / (1 - r) | c847e4172c835fdded0a911a0f2dd40879a30ece | 121,744 |
def broadcast(singular, width: int):
"""Fill an array of the given width from the singular data provided."""
# Warning: the initial use case for this utility function is to repackage a Future of width 1 as a
# Future of greater width, but this relies on an assumption about Future.result() that may change.
# When *result()* is called, gmxapi *always* converts data of width 1 to a value of *dtype*, whereas a
# Future of width > 1 gives its result as a list. See https://gitlab.com/gromacs/gromacs/-/issues/2993
# and related issues.
return [singular] * width | df6afa6056edeb277aa1c36ad8be59b968facae2 | 121,748 |
import unicodedata
import re
def slugify(string):
"""Slugifies a string.
Based on public domain code from https://github.com/zacharyvoase/slugify
"""
normalized_string = str(unicodedata.normalize("NFKD", string))
no_punctuation = re.sub(r"[^\w\s-]", "", normalized_string).strip().lower()
slug = re.sub(r"[-\s]+", "-", no_punctuation)
return slug | 27ef8a800f89dc69b3cec2a653cdfdb248a6232b | 121,749 |
def get_measure(element):
"""gets measure of an element
Arguments: element [Element]: element you want to find the measure of
Return: Measure Number [int]: measure number found in measure's attribute
"""
while element is not None and element.tag != '{http://www.music-encoding.org/ns/mei}measure':
element = element.getparent()
return element.attrib['n'] | d7a7d8a203924c8e50c88740e8eca72346cc4b33 | 121,750 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.