content
stringlengths 39
9.28k
| sha1
stringlengths 40
40
| id
int64 8
710k
|
---|---|---|
import logging
def split_dataframe_by_column(df, column):
"""
Purpose:
Split dataframe into multipel dataframes based on uniqueness
of columns passed in. The dataframe is then split into smaller
dataframes, one for each value of the variable.
Args:
df (Pandas DataFrame): DataFrame to split
column (string): string of the column name to split on
Return
split_df (Dict of Pandas DataFrames): Dictionary with the
split dataframes and the value that the column maps to
e.g false/true/0/1
"""
logging.info('Spliting Dataframes on Column')
logging.info(
'Columns to Split on: {column}'.format(column=column)
)
column_values = df[column].unique()
split_df = {}
for column_value in column_values:
split_df[str(column_value)] = df[df[column] == column_value]
return split_df | 3983c7270032f6a6bc8f6963f0da1ffada139216 | 288,334 |
def standard_codec_name(name: str) -> str:
"""
Map a codec name to the preferred standardized version.
The preferred names were taken from this list published by IANA:
U{http://www.iana.org/assignments/character-sets/character-sets.xhtml}
@param name:
Text encoding name, in lower case.
"""
if name.startswith("iso8859"):
return "iso-8859" + name[7:]
return {
"ascii": "us-ascii",
"euc_jp": "euc-jp",
"euc_kr": "euc-kr",
"iso2022_jp": "iso-2022-jp",
"iso2022_jp_2": "iso-2022-jp-2",
"iso2022_kr": "iso-2022-kr",
}.get(name, name) | e9f30c9cb9da065f300900923e9b9ce5bac255e9 | 70,801 |
def normalize_disp(dataset_name):
"""Function that specifies if disparity should be normalized"""
return dataset_name in ["forward_facing"] | b97141606ad7efa32501d6ad6dd2e97fde791a91 | 410,008 |
def has_same_pattern(ruler_intervals1, ruler_intervals2):
"""
Check whether the give two ruler interval lists have the same pattern
Args:
ruler_intervals1: a list of ruler-intervals
ruler_intervals2: a list of ruler-intervals
Returns:
True or False
"""
if len(ruler_intervals1) != len(ruler_intervals2):
return False
if ruler_intervals1[0].left_open != ruler_intervals2[0].left_open or ruler_intervals1[-1].right_open != ruler_intervals2[-1].right_open:
return False
for ruler1, ruler2 in zip(ruler_intervals1, ruler_intervals2):
if abs(ruler1.right_value-ruler1.left_value) != abs(ruler2.right_value - ruler2.left_value):
return False
return True | 8cc9aba474347b4e4493a3c44dc204d9af0354b4 | 199,294 |
def tlv_file_xml(tlv_data_xml, tmp_path):
"""Return the path to an XML file containing the test tree."""
path = tmp_path / "expected.xml"
path.write_bytes(tlv_data_xml)
return path | ef01ff58cf3afe7cd08eec98689c69b24c308b20 | 173,382 |
import random
import string
def random_alphanumeric(length=5, upper_case=False):
"""Generate a random alphanumeric string of given length
:param length: the size of the string
:param upper_case: whether to return the upper case string
"""
if upper_case:
return ''.join(random.choice(
string.ascii_uppercase + string.digits) for _ in range(length))
else:
return ''.join(random.choice(
string.ascii_lowercase + string.digits) for _ in range(length)) | d9072421639d629516911b72b451905d08063cc9 | 625,247 |
def csc_cumsum_i(p, c, n):
"""
p [0..n] = cumulative sum of c [0..n-1], and then copy p [0..n-1] into c
@param p: size n+1, cumulative sum of c
@param c: size n, overwritten with p [0..n-1] on output
@param n: length of c
@return: sum (c), null on error
"""
nz = 0
nz2 = 0.0
for i in range(n):
p[i] = nz
nz += c[i]
nz2 += c[i] # also in double to avoid CS_INT overflow
c[i] = p[i] # also copy p[0..n-1] back into c[0..n-1]
p[n] = nz
return int(nz2) # return sum (c [0..n-1]) | ab567b6b357fc7e5e1b0a961b9b66d88487a0e7f | 697,125 |
def sent_length(sentence):
""" Returns sentence length without spaces. """
return sum(1 for c in sentence if c != ' ') | cde1e2e93e99a9c97d68a514b0fd31841de46d04 | 518,256 |
def bounding_boxes_xyxy2xywh(bbox_list):
"""
Transform bounding boxes coordinates.
:param bbox_list: list of coordinates as: [[xmin, ymin, xmax, ymax], [xmin, ymin, xmax, ymax]]
:return: list of coordinates as: [[xmin, ymin, width, height], [xmin, ymin, width, height]]
"""
new_coordinates = []
for box in bbox_list:
new_coordinates.append([box[0],
box[1],
box[2] - box[0],
box[3] - box[1]])
return new_coordinates | da55bf46bc65bffb999ab7de9ddaedb333718f53 | 100,532 |
def filter_polygons(state, header):
"""
Removes any non-polygon sources from the state file.
We are only interested in parsing parcel data, which is
marked as Polygon in the state file.
"""
filtered_state = []
for source in state:
if 'Polygon' in source[header.index('geometry type')]:
filtered_state.append(source)
return filtered_state | d100e6a4e87dccdc42c7217dc1e793e4353237e2 | 7,081 |
def _get_zone(gcdns, zone_name):
"""Gets the zone object for a given domain name."""
# To create a zone, we need to supply a zone name. However, to delete a
# zone, we need to supply a zone ID. Zone ID's are often based on zone
# names, but that's not guaranteed, so we'll iterate through the list of
# zones to see if we can find a matching name.
available_zones = gcdns.iterate_zones()
found_zone = None
for zone in available_zones:
if zone.domain == zone_name:
found_zone = zone
break
return found_zone | 20d746cbf8caa3f55e39856862868ed0c0d7aa31 | 533,809 |
from typing import List
from typing import Any
def getListDifference(listOne: List[Any], listTwo: List[Any]) -> List[Any]:
""" Return difference (items that are unique just to a one of given lists)
of a given lists.
Note:
Operation does not necessary maintain items order!
Args:
listOne: first list to compare.
listTwo: second list to compare.
"""
difference = list(set(listOne).symmetric_difference(set(listTwo)))
return difference | 5839988761a8f242828c8526d75e2b7ea8aea2f3 | 37,114 |
import click
def routes_file_option(help_text=None):
"""Option for providing a routes file instead of pulling from content."""
if help_text is None:
help_text = 'Use routes file to load routes instead of loading from files.'
def _decorator(func):
return click.option(
'--routes-file', '--routes_file', type=str, default=None,
help=help_text)(func)
return _decorator | 8aaf1e916e5101f6427a2dbb35c9d9077ac50138 | 366,277 |
def _convert_float(value):
"""Convert an "exact" value to a ``float``.
Also works recursively if ``value`` is a list.
Assumes a value is one of the following:
* :data:`None`
* an integer
* a string in C "%a" hex format for an IEEE-754 double precision number
* a string fraction of the format "N/D"
* a list of one of the accepted types (incl. a list)
Args:
value (Union[int, str, list]): Values to be converted.
Returns:
Union[float, list]: The converted value (or list of values).
"""
if value is None:
return None
elif isinstance(value, list):
return [_convert_float(element) for element in value]
elif isinstance(value, int):
return float(value)
elif value.startswith("0x") or value.startswith("-0x"):
return float.fromhex(value)
else:
numerator, denominator = value.split("/")
return float(numerator) / float(denominator) | 7896c97dafd577b6eefec452f5983c8c06c5f831 | 682,086 |
import time
def annotate_heatmap(im, # the AxesImage to be labeled
# a 2D numpy array of shape (N, M) containing the standard deviations to be used to annotate
# the heatmap
std,
# a 2D python array containing Boolean values indicating whether each single cell contains
# data or not
mask,
# the format of the annotations inside the heatmap. This should be either 'time' or 'speed'
ann_format='time',
# a pair of colors. The first is used for values below a threshold, the second for those above
textcolors=("black", "white"),
# value in data units according to which the colors from textcolors are applied.
# If None (the default) uses the middle of the colormap as separation
threshold=None,
# all other arguments are forwarded to each call to `text` used to create the text labels
**textkw):
""" A function to annotate a heatmap.
Args:
im: The AxesImage to be labeled
std: A 2D numpy array of shape (N, M) containing the standard deviations to be used to annotate the heatmap
mask: A 2D python array containing Boolean values indicating whether each single cell contains data or not
ann_format: The format of the annotations inside the heatmap. This should be either 'time' or 'speed'
(default: 'time')
textcolors: A pair of colors. The first is used for values below a threshold, the second for those above
(default: ("black", "white"))
threshold: Value in data units according to which the colors from textcolors are applied.
If None (the default) uses the middle of the colormap as separation (default: None)
**textkw: All other arguments are forwarded to each call to `text` used to create the text labels
"""
# get data from 'im' AxesImage
data = im.get_array()
# normalize the threshold to the images color range
if threshold is not None:
threshold = im.norm(threshold)
else: # if threshold was not provided set threshold using the middle of the colormap as separation
threshold = im.norm(data.max()) / 2.
# Set default alignment to center, but allow it to be overwritten by textkw.
kw = dict(horizontalalignment="center",
verticalalignment="center")
kw.update(textkw)
# if the annotation is not of type 'time' nor 'speed', raise error
if ann_format != 'time' and ann_format != 'speed':
raise ValueError('Unknown format type.')
# initialize texts list to be empty
texts = []
# loop over the data
for i in range(data.shape[0]):
for j in range(data.shape[1]):
if mask[i][j]: # skip data point if its mask value is true
continue
# update color depending on the current data point
kw.update(color=textcolors[int(im.norm(data[i, j]) > threshold)])
if ann_format == 'time': # if the annotation is of type 'time'
# create text of type 'time' for the current data point
text = im.axes.text(j, i, '{}\n+/-{:4.0f}s'
.format(time.strftime("%H:%M:%S",
time.gmtime(float(data[i, j]))), std[i, j]), **kw)
else: # if the annotation is of type 'speed'
# create text of type 'speed' for the current data point
text = im.axes.text(j, i, '{:6.3f}it/s\n+/-\n{:6.3f}it/s'.format(data[i, j],
std[i, j]), **kw)
# append generated text to texts list
texts.append(text)
return texts | dc85f08ecdecb49c4f8b170ce331117f677f5075 | 98,932 |
def add_terminating_slash_to_url(url):
"""
adds terminating slash if necessary to main input URL
"""
if url[-1] != '/':
url += '/'
return url | 3f4e871891ddc3930e6b40238616038fee086bef | 349,954 |
def streamPrint(token: str = '', saveToken: str = '', printToken: bool = True):
"""
Helper function to take a token candidate, save destination, and print if requested.
Args:
token: New string to append.
saveToken: Save token string stream.
printToken:
Returns: appended string with new token.
"""
saveToken += token
if printToken:
print(token)
return saveToken | b30d57e458f407cd6642f443a97774acbada3d92 | 542,744 |
def is_start_main_block(inputstring):
"""Check if line is the first line of the main block of data"""
return inputstring.startswith("Location: ") or inputstring.startswith('Site Number: ') | 480cf3cab6b0a3c569960d85f1cef92df300875c | 157,347 |
def fillout(template, adict):
"""returns copy of template filled out per adict
applies str.replace for every entry in adict
"""
rval = template[:]
for key in adict:
rval = rval.replace(key, adict[key])
return rval | b06551896f2cd3eafbe75fbfa6ab7885fbd34813 | 468,862 |
def booleanize_list(vals, null_vals=['no', 'none', 'na', 'n/a', '']):
"""Return a list of true/false from values."""
out = []
for val in vals:
val = val.strip().lower()
out.append(val and val not in null_vals)
return out | 296026dd59731a593a1a47704de73237d35af835 | 217,438 |
def is_die_attr_ref(attr):
"""
Returns True if the DIE attribute is a reference.
"""
return bool(attr.form in ('DW_FORM_ref1', 'DW_FORM_ref2',
'DW_FORM_ref4', 'DW_FORM_ref8',
'DW_FORM_ref')) | f00ee94396e66f2a3d81648698e29d6d3fe2885a | 212,867 |
def calc_subrange(range_max, sub_amount, weight):
"""
return the start and stop points that are sub_amount distance apart and
contain weight, without going outside the provided range
"""
if weight > range_max or sub_amount > range_max:
raise ValueError("sub_amount and weight must be less than range_max. range_max %s, sub_amount %s, weight %s" % (range_max, sub_amount, weight))
half_amount = sub_amount / 2
bottom = weight - half_amount
top = bottom + sub_amount
if top <= range_max and bottom >= 0:
return (bottom, top)
elif weight > range_max / 2:
# weight is on the upper half, start at the max and go down
return (range_max - sub_amount, range_max)
else:
# weight is on the lower have, start at 0 and go up
return (0, sub_amount) | e0c020b32a0b73f109e843df1a9eccbe805cc252 | 535,574 |
from typing import Tuple
from typing import List
def _resolve_dim(slicer_index: Tuple, slicer_dim: List) -> List:
""" Extracts new dim after applying slicing index and maps it back to the original index list. """
new_slicer_dim = []
reduced_mask = []
for _, curr_idx in enumerate(slicer_index):
if isinstance(curr_idx, (tuple, list, slice)):
reduced_mask.append(0)
else:
reduced_mask.append(1)
for curr_dim in slicer_dim:
if reduced_mask[curr_dim] == 0:
new_slicer_dim.append(curr_dim - sum(reduced_mask[:curr_dim]))
return new_slicer_dim | 5535fadbf29fabf8343af44e5daf16d1cfec36e2 | 495,481 |
import re
def curlify(content: str) -> str:
"""
Adds a pair of curly braces to the content. If the content already contains curly brackets, nothing will happen.
Example:
- curlify("Hello") returns "{Hello}".
- curlify("{Hello}") returns "{Hello}".
"""
curlify_pattern = re.compile(r'^{.*}$', re.DOTALL)
# Check if curly brackets are already set
if not re.fullmatch(curlify_pattern, content):
# Add extra curly brackets to title. Preserves lowercase/uppercase in BIBTeX
content = "{{{}}}".format(content)
return content | a45b6805eb3250f74fea913478d93f49e09b12cf | 116,029 |
import re
def text_reformat(text):
"""lowercase without punctuation"""
return re.sub(r'[^\w\s]', '', text.lower()) | 60f87486f65ddaf17919cf3ddbc72923597ddb08 | 96,812 |
import asyncio
import random
async def task_coro(pid):
"""Coroutine non-deterministic task"""
await asyncio.sleep(random.randint(0, 2) * 0.1)
print('Task %s done' % pid)
return random.choice([True, False, False, False, False, False, False, False, False, False, False, False]) | f88861797c5d36608b7d2ff7a4ccf79e64132062 | 620,779 |
def items_in_this_page(ls_resp, mode=None):
"""
Returns a dictionary of data record and/or collections from the given
listing response from DataFed
Parameters
----------
ls_resp : protobuf message
Message containing the listing reply
mode : str, optional
Set to "d" to only get datasets from the listing
Set to "c" to only get collections from the listing
Leave unset for all items in the listing
Returns
-------
dict
Keys are IDs and values are the title for the object
"""
data_objects = dict()
if not mode:
# return everything - records and collections
for item in ls_resp[0].item:
data_objects[item.title] = item.id
else:
for item in ls_resp[0].item:
# return only those that match with the mode (dataset / collection)
if item.id.startswith(mode):
data_objects[item.title] = item.id
return data_objects | 24241b2acf1bf20a47c0c69263209df6424dcfa9 | 125,363 |
def wrap_to_180(lon):
"""Wrapps longitude to -180 to 180 degrees."""
lon[lon>180] -= 360.
return lon | f1b8e9ac40e35a39b88afffb51de79a12df11c50 | 372,930 |
def get_command_help_messsage(command: str) -> str:
"""
Get the help message for a command.
Parameters
----------
command : str
Name of the command.
Returns
-------
str
Command's help message.
"""
return f'Show {command} command help message.' | 246e645d28569c346d08d1e2470d5db5c7ea40cc | 501,771 |
def find_attribute(rcv, xpath, attribute_name):
"""Find an attribute in the RCV record which can have either zero or one occurrence. Return a textual representation
of the attribute, including special representations for the case of zero or multiple, constructed using the
attribute_name parameter."""
attributes = rcv.findall(xpath)
if len(attributes) == 0:
return '{} missing'.format(attribute_name)
elif len(attributes) == 1:
return attributes[0].text
else:
return '{} multiple'.format(attribute_name) | bb1dc226b1489fb8f5534770fa3dda2748c65d6f | 243,418 |
from typing import Optional
def prepare_error_message(message: str, error_context: Optional[str] = None) -> str:
"""
If `error_context` is not None prepend that to error message.
"""
if error_context is not None:
return error_context + ": " + message
else:
return message | ea95d40797fcc431412990706d5c098a07986156 | 5,521 |
def is_matrix(A):
"""Checks if an array is a matrix
Args:
A (jax.numpy.ndarray): A JAX array
Returns:
bool: True if the array is a matrix, False otherwise.
"""
return A.ndim == 2 | 114cd7a8c08b842e5bd85495e1c764f229f421e8 | 375,677 |
def group(text, size):
"""Group ``text`` into blocks of ``size``.
Example:
>>> group("test", 2)
['te', 'st']
Args:
text (str): text to separate
size (int): size of groups to split the text into
Returns:
List of n-sized groups of text
Raises:
ValueError: If n is non positive
"""
if size <= 0:
raise ValueError("n must be a positive integer")
return [text[i:i + size] for i in range(0, len(text), size)] | 55e8cc79de23651b764648a655d41220253f90b8 | 574,364 |
from typing import List
import glob
def get_l10n_files() -> List[str]:
"""取得所有翻譯相關檔案列表,包括.pot .po .mo。
Returns:
List[str]: 翻譯相關檔案列表,包括.pot .po .mo。
"""
po_parser = 'asaloader/locale/*/LC_MESSAGES/asaloader.po'
pot_file = 'asaloader/locale/asaloader.pot'
po_files = glob.glob(po_parser)
mo_files = [po_file.replace('.po', '.mo') for po_file in po_files]
files = [pot_file] + po_files + mo_files
return files | a783679261e7c9bd617728946d01a440b51cfb6a | 703,302 |
from typing import List
def close_gap_to_1(prev_vals: List[float], fraction: float) -> float:
"""
Reduce the difference between the last value and one (full mobility) according to the "fraction" request.
"""
prev_val = prev_vals[-1]
return (1.0 - prev_val) * fraction + prev_val | ba597fe3df369d3a4072e8765d12ae22d0cd9557 | 419,252 |
import time
import re
def get_time(string):
""" Convert GitHub timestamp to epoch """
return time.mktime(
time.strptime(re.sub(r"Z", "", str(string)), "%Y-%m-%dT%H:%M:%S")
) | 007790eb7429ef534e06ef4de6753878107c565f | 209,505 |
import re
def _check_for_run_information(sample_name):
"""
Helper function to try and find run ID information of the form RunXX_YY
"""
m = re.match('^Run\d+_\d+$', sample_name)
if m is not None:
return True
else:
return False | 1ddf51cc723b7831912952c1aacf4095dbcb9d9a | 94,025 |
def create_url(hostname, port=None, isSecure=False):
"""
Create a RawSocket URL from components.
:param hostname: RawSocket server hostname (for TCP/IP sockets) or
filesystem path (for Unix domain sockets).
:type hostname: str
:param port: For TCP/IP sockets, RawSocket service port or ``None`` (to select default
ports ``80`` or ``443`` depending on ``isSecure``. When ``hostname=="unix"``,
this defines the path to the Unix domain socket instead of a TCP/IP network socket.
:type port: int or str
:param isSecure: Set ``True`` for secure RawSocket (``rss`` scheme).
:type isSecure: bool
:returns: Constructed RawSocket URL.
:rtype: str
"""
# assert type(hostname) == str
assert type(isSecure) == bool
if hostname == 'unix':
netloc = "unix:%s" % port
else:
assert port is None or (type(port) == int and port in range(0, 65535))
if port is not None:
netloc = "%s:%d" % (hostname, port)
else:
if isSecure:
netloc = "{}:443".format(hostname)
else:
netloc = "{}:80".format(hostname)
if isSecure:
scheme = "rss"
else:
scheme = "rs"
return "{}://{}".format(scheme, netloc) | 66db7e468649ab89f3795a1ed71dc5f05ce9365b | 380,588 |
def _lag_observations(observations, lag, stride=1):
""" Create new trajectories that are subsampled at lag but shifted
Given a trajectory (s0, s1, s2, s3, s4, ...) and lag 3, this function will generate 3 trajectories
(s0, s3, s6, ...), (s1, s4, s7, ...) and (s2, s5, s8, ...). Use this function in order to parametrize a MLE
at lag times larger than 1 without discarding data. Do not use this function for Bayesian estimators, where
data must be given such that subsequent transitions are uncorrelated.
Parameters
----------
observations : list of int arrays
observation trajectories
lag : int
lag time
stride : int, default=1
will return only one trajectory for every stride. Use this for Bayesian analysis.
"""
obsnew = []
for obs in observations:
for shift in range(0, lag, stride):
obsnew.append(obs[shift:][::lag])
return obsnew | 65537ed7e19eaa28750cfaea1649d9de73e69678 | 169,265 |
def get_play_mode(instruction_set):
"""
Get the play_mode, type of execution arrangement.
:param instruction_set: json object
:return: play_mode value
"""
result = instruction_set.get("play_mode")
if result is None:
raise ValueError("Play mode not found in instruction_set data.")
return result | 6393c035716f436158f952143b362ac220c216ee | 324,290 |
def expand_id_map(id_map, all_ids):
""" Ensures all ids within all_ids are included as keys in the mapping """
unmapped_ids = list(set(all_ids).difference(id_map.keys()))
for i in unmapped_ids:
id_map[i] = i
return id_map | 10e80cc2d3a84de745bc03f09f56c197b5bab13a | 615,931 |
def css_rgb(color, a=False):
"""Get a CSS `rgb` or `rgba` string from a `QtGui.QColor`."""
return ("rgba({}, {}, {}, {})" if a else "rgb({}, {}, {})").format(*color.getRgb()) | f3f15c2c5fdb7317f679cc080b4f0c6fb343f45a | 665,509 |
from typing import Any
def create_property(attr: str, default: Any, type_annotation: type) -> property:
"""Return a property descriptor given config attribute."""
def fget(self) -> Any:
if attr in self._env_overrides:
return self._env_overrides[attr]
if attr in self._config:
return self._config[attr]
return self._defaults[attr]
def fset(self, value: Any) -> None:
self._config[attr] = value
def fdel(self) -> None:
self._config[attr] = default
doc = f"Configuration {attr}[{type_annotation}]"
return property(fget, fset, fdel, doc) | d7359b49a666e8826797d297e6642bd0736a0191 | 654,030 |
def is_thm_included(thm, splits, library_tags):
"""Decides whether the theorem is included in the selection.
This function can be used for filtering for theorems belonging to
the allowed splits and library tags.
Args:
thm: Theorem object to be decided for inclusion.
splits: Of type List[proof_assistant_pb2.Theorem.Split], the list of
training splits for which tasks should be generated for.
library_tags: List of strings for the library tags to be processed. If
empty, then all library tags are allowed.
Returns:
Boolean indicating whether the theorem is included in the selection.
"""
return thm.training_split in splits and (
(not library_tags or (set(thm.library_tag) & library_tags))) | 621e789ae2a254f727f591ec75a0b78a1130aaa0 | 309,638 |
def interface_r_cos(polarization, n_i, n_f, cosTh_i, cosTh_f):
"""
reflection amplitude (from Fresnel equations)
polarization is either "s" or "p" for polarization
n_i, n_f are (complex) refractive index for incident and final
th_i, th_f are (complex) propegation angle for incident and final
(in radians, where 0=normal). "th" stands for "theta".
"""
if polarization == 's':
return ((n_i * cosTh_i - n_f * cosTh_f) /
(n_i * cosTh_i + n_f * cosTh_f))
elif polarization == 'p':
return ((n_f * cosTh_i - n_i * cosTh_f) /
(n_f * cosTh_i + n_i * cosTh_f))
else:
raise ValueError("Polarization must be 's' or 'p'") | fd7da775fbba9c411ff2a461aa8d41c673fe8584 | 668,587 |
def term_frequency(text, word):
"""Takes in a text (list of strings) and calculates
TF(t) = (number of times term appears in text) / (total number of terms in a text)"""
total_words = len(text)
word_in_text = text.count(word)
try:
return float(word_in_text) / float(total_words)
except ZeroDivisionError:
return 0 | 4d773a13e5b3698bdbb8ea280a8997c6d2eab530 | 281,391 |
import time
def gen_test_packet(sender="server", size=3000):
"""
Generates a simple test packet, containing a decent amount of data,
as well as the timestamp of generation and the sender.
"""
# Packet containing 'size' floats
data = [0.0 if i % 2 == 0 else 1.0 for i in range(size)]
timestamp = "{}".format(time.time())
packet = {"data": data, "timestamp": timestamp, "sender": sender}
return packet | f51651e755f8579158a485f0a2a56ba3791eaec1 | 284,482 |
import csv
def write_colocated_gates(coloc_gates, fname):
"""
Writes the position of gates colocated with two radars
Parameters
----------
coloc_gates : dict
dictionary containing the colocated gates parameters
fname : str
file name where to store the data
Returns
-------
fname : str
the name of the file where data has written
"""
with open(fname, 'w', newline='') as csvfile:
csvfile.write('# Colocated radar gates data file\n')
csvfile.write('# Comment lines are preceded by "#"\n')
csvfile.write('#\n')
fieldnames = [
'rad1_ray_ind', 'rad1_rng_ind', 'rad1_ele', 'rad1_azi', 'rad1_rng',
'rad2_ray_ind', 'rad2_rng_ind', 'rad2_ele', 'rad2_azi', 'rad2_rng']
writer = csv.DictWriter(csvfile, fieldnames)
writer.writeheader()
for i, rad1_ray_ind in enumerate(coloc_gates['rad1_ray_ind']):
writer.writerow({
'rad1_ray_ind': rad1_ray_ind,
'rad1_rng_ind': coloc_gates['rad1_rng_ind'][i],
'rad1_ele': coloc_gates['rad1_ele'][i],
'rad1_azi': coloc_gates['rad1_azi'][i],
'rad1_rng': coloc_gates['rad1_rng'][i],
'rad2_ray_ind': coloc_gates['rad2_ray_ind'][i],
'rad2_rng_ind': coloc_gates['rad2_rng_ind'][i],
'rad2_ele': coloc_gates['rad2_ele'][i],
'rad2_azi': coloc_gates['rad2_azi'][i],
'rad2_rng': coloc_gates['rad2_rng'][i]})
csvfile.close()
return fname | aaf7421036f39c898a3ee9e7c166ce24cdda6b4e | 670,851 |
def aslist(item):
"""
aslist wraps a single value in a list, or just returns the list
"""
return item if type(item) == list else [item] | e9b3a9f189f74243d713e896dfbbd002e78abada | 27,536 |
def add_user_tag(func):
""" Add the attribute __user_tag__ to func.
:params func: a non-builtin function to decorate
:type func: function
:rtype: function
"""
func.__user_tag__ = "YiranChe"
return func | da940697113afd7cba2b5ef7de822546be6bf925 | 471,176 |
import re
def remove_tag(string):
"""
Most of web scrapped data contains html tags.
It can be removed from below re script
Parameters
----------
text: str
Text selected to apply transformation.
Examples:
---------
```python
sentence="Markdown sentences can use <br> for breaks and <i></i> for italics"
remove_tag(sentence)
>>> 'Markdown sentences can use for breaks and for italics'
```
"""
text = re.sub('<.*?>', '', string)
return text | 284f07aed99a403d1a99efce6e37b5564e9f8401 | 108,997 |
def detailed_event_metrics_to_list(detailed_event_results):
""" Converting detailed event metric results to a list (position of each item is fixed)
Argument:
detailed_event_results (dictionary): as provided by the 3rd item in the results of eval_events function
Returns:
list: Item order: 0. correct, 1. deletions 2. merged, 3. fragmented, 4. fragmented and merged, 5. fragmenting, 6. merging, 7. fragmenting and merging, 8. insertions, 9. total of actual events, 10. total of detected events
"""
return [
detailed_event_results["C"],
detailed_event_results["D"],
detailed_event_results["M"],
detailed_event_results["F"],
detailed_event_results["FM"],
detailed_event_results["F'"],
detailed_event_results["M'"],
detailed_event_results["FM'"],
detailed_event_results["I'"],
detailed_event_results["total_gt"],
detailed_event_results["total_det"],
] | b6baeb8548d035982a2bd5bab88deb915d9f99cc | 368,502 |
def inRange(v1, minVal = 0, maxVal = 1):
"""
Check if every value in v1 is in the range (minVal, maxVal)
"""
for v in v1:
if v < minVal or v > maxVal:
return False
return True | c166f7d9aaa94988eb4e245cb41c34b44ace86cf | 572,902 |
import random
def generate_mac_address(type="XEN"):
"""
<comment-ja>
ランダムなMACアドレスを生成する
(XENなら、00:16:3e:00:00:00 から 00:16:3e:7f:ff:ff の範囲)
(KVMなら、52:54:00:00:00:00 から 52:54:00:ff:ff:ff の範囲)
@param type: ハイパーバイザのタイプ (XEN or KVM)
@return: MACアドレス
</comment-ja>
<comment-en>
Generate random MAC address
(if hypervisor is XEN, generates address by range between 00:16:3e:00:00:00 and 00:16:3e:7f:ff:ff)
(if hypervisor is KVM, generates address by range between 52:54:00:00:00:00 and 52:54:00:ff:ff:ff)
@param type: The type of hypervisor (XEN or KVM)
@return: The string that stands for MAC address
</comment-en>
"""
if type == "KVM":
mac = [ 0x52, 0x54, 0x00,
random.randint(0x00, 0xff),
random.randint(0x00, 0xff),
random.randint(0x00, 0xff) ]
else:
mac = [ 0x00, 0x16, 0x3e,
random.randint(0x00, 0x7f),
random.randint(0x00, 0xff),
random.randint(0x00, 0xff) ]
return ':'.join(["%02x" % x for x in mac]) | 573a1568c2705eb0e108104f3b9e0e2f484770d2 | 330,727 |
def explore_or_choose_direction(current_village_number):
"""Ask the user whether he/she would like to explore the current village or move to a different village."""
while True:
print("")
print("Would you like to explore village {} or move to a different village? Enter explore or move.".format(current_village_number))
user_explore_or_move_chosen = input("> ")
user_explore_or_move_chosen = user_explore_or_move_chosen.lower()
if user_explore_or_move_chosen == "explore" or user_explore_or_move_chosen == "move":
return user_explore_or_move_chosen
else:
print("")
print("I'm sorry, I didn't understand that.") | ee0f75b3b245be4245427981da249f13554353cd | 289,533 |
def getNumBlocksToMine(chanBlocks):
"""
get number blocks to mine to fund the channels including extra 100 to spend the blocks
:param chanBlocks: the outputs of coinbase txs put in blocks
:return: int
"""
cbs = 0
for block in chanBlocks:
cbs += len(block)
blocksToMine = cbs + 100
return blocksToMine | 21d4c3d5f5d1c497b21e135a3bd5cf53144efe58 | 248,581 |
from datetime import datetime
def timestamp2isoformat(timestamp):
"""
This function converts a timestamp (float) to a string in the
ISO 8061 date format
"""
date = datetime.fromtimestamp(timestamp)
return date.isoformat() | e1c6d68821c0986b658328dc32ea70d7f9c58919 | 453,615 |
def maybe(f, default):
"""Evaluate f and return the value; return default on error."""
try:
return f()
except: # noqa: E722
return default | 0d23ed11df5ded9e2f7f122c64f4bc4c7fab3d74 | 533,539 |
import importlib
def construct_instance(fq_name, kwargs):
"""
Constructs an instance of the class from the fully qualified name expanding
the kwargs during construction. e.g. fq_name(**kwargs)
:param fq_name: The fully qualified class name.
:param kwargs: Keyword args (a dict) to be expanded.
:return: An instance of the class
"""
class_data = fq_name.split(".")
module_path = ".".join(class_data[:-1])
class_str = class_data[-1]
if kwargs is None:
kwargs = {}
module = importlib.import_module(module_path)
return getattr(module, class_str)(**kwargs) | 2007446ea66e321b35824153b6b304dad53dac6f | 460,646 |
def alpha_numeric_filter(string):
"""Takes a string and returns a filtered string with only alpha-numeric characters"""
filtered = ""
for char in string:
if char.isalnum() or char == ' ':
filtered += char
if char == '\n':
continue
return filtered | e9bd4337489203024fb1052cd3f30e7657d709e1 | 203,365 |
def get_readme_description(head_string: str) -> str:
"""
Parse the head of README and get description.
:param head_string: A string containing title, description and images.
:return: Stripped description string.
"""
# Split title section and rule out empty lines.
parts = list(filter(bool, head_string.splitlines()))
if len(parts) < 3:
raise Exception('README should contain title, description and image.')
description = parts[1].strip()
return description | a37d01565461b028874ca725f0473f87470b8816 | 590,617 |
def linear_annuity_mapping_fprime(underlying, alpha0, alpha1):
"""linear_annuity_mapping_fprime
first derivative of linear annuity mapping function.
See :py:func:`linear_annuity_mapping_func`.
The function calculates following formula:
.. math::
\\alpha^{\prime}(S) := \\alpha_{0.}
where
:math:`S` is underlying,
:math:`\\alpha_{0}` is alpha0.
:param float underlying:
:param float alpha0:
:param float alpha1: not used.
:return: value of first derivative of linear annuity mapping function.
:rtype: float.
"""
return alpha0 | ff57723cad7ade65644744dc30abb6db5c1e6b95 | 697,518 |
import hashlib
def generage_sha1(text: str) -> str:
"""Generate a sha1 hash string
Args:
text (str): Text to generate hash
Returns:
str: sha1 hash
"""
hash_object = hashlib.sha1(text.encode('utf-8'))
hash_str = hash_object.hexdigest()
return hash_str | 3df62f7607db571b45e82d18e756861c84699513 | 689,973 |
def validate_port(confvar):
"""
Validate that the value of confvar is between [0, 65535].
Returns [(confvar, error_msg)] or []
"""
port_val = confvar.get()
error_res = [(confvar, 'Port should be an integer between 0 and 65535 (inclusive).')]
try:
port = int(port_val)
if port < 0 or port > 65535:
return error_res
except ValueError:
return error_res
return [ ] | a200fd85f417c7e9a958a97f02c6aa8b6ed381bf | 517,881 |
import json
def to_json_string(my_obj):
"""
Function that returns the JSON representation of an object.
Args:
my_obj (str): Surce object
Returns:
JSON representation.
"""
return json.dumps(my_obj) | 18e51b0ae242ef99ec3831a915b9a1693e25281a | 621,817 |
def event_blocknumbers(events):
"""given a list of events returns the block numbers containing events"""
return {ev.blocknumber for ev in events} | 442432b1c2b795d3373a17925b79a14a44469480 | 254,999 |
def perimeter_square(length):
"""
.. math::
perimeter = 4 * length
Parameters
----------
length: float
length of one side of a square
Returns
-------
perimeter: float
perimeter of the square
"""
return length * 4 | 07b8eefed384636a254c1ca84d861bebf80782ec | 651,751 |
import torch
def demean(tensor, dim=-1):
"""
Demeans the input tensor along the specified dimension(s)
Parameters
----------
tensor : Tensor
the input tensor
dim : int or list or tuple (optional)
the dimension(s) along the operation is performed (default is -1)
Returns
-------
Tensor
the demeaned tensor
"""
return tensor - torch.mean(tensor, dim=dim, keepdim=True) | dcf9a40ca9895f76966970fd970ace68750e90a9 | 184,233 |
import six
def bytes_increment(b):
"""Increment and truncate a byte string (for sorting purposes)
This functions returns the shortest string that sorts after the given
string when compared using regular string comparison semantics.
This function increments the last byte that is smaller than ``0xFF``, and
drops everything after it. If the string only contains ``0xFF`` bytes,
`None` is returned.
"""
assert isinstance(b, six.binary_type)
b = bytearray(b) # Used subset of its API is the same on Python 2 and 3.
for i in range(len(b) - 1, -1, -1):
if b[i] != 0xff:
b[i] += 1
return bytes(b[:i+1])
return None | 197031de601f9754bb44648ed5bc2198096d827e | 219,876 |
def goal_error(name):
"""Adds a string which occurs in the
output of coq if a goal is admitted.
Arguments:
- `name`: a goal name
"""
return "*** [ {0!s}".format(name) | 85d2fc3ece04e4f43a60736acc388437d65a5d68 | 583,011 |
def label2yolobox(labels, info_img, maxsize, lrflip):
"""
Transform coco labels to yolo box labels
Args:
labels (numpy.ndarray): label data whose shape is :math:`(N, 5)`.
Each label consists of [class, x, y, w, h] where \
class (float): class index.
x, y, w, h (float) : coordinates of \
left-top points, width, and height of a bounding box.
Values range from 0 to width or height of the image.
info_img : tuple of h, w, nh, nw, dx, dy.
h, w (int): original shape of the image
nh, nw (int): shape of the resized image without padding
dx, dy (int): pad size
maxsize (int): target image size after pre-processing
lrflip (bool): horizontal flip flag
Returns:
labels:label data whose size is :math:`(N, 5)`.
Each label consists of [class, xc, yc, w, h] where
class (float): class index.
xc, yc (float) : center of bbox whose values range from 0 to 1.
w, h (float) : size of bbox whose values range from 0 to 1.
"""
h, w, nh, nw, dx, dy = info_img
x1 = labels[:, 1] / w
y1 = labels[:, 2] / h
x2 = (labels[:, 1] + labels[:, 3]) / w
y2 = (labels[:, 2] + labels[:, 4]) / h
labels[:, 1] = (((x1 + x2) / 2) * nw + dx) / maxsize
labels[:, 2] = (((y1 + y2) / 2) * nh + dy) / maxsize
labels[:, 3] *= nw / w / maxsize
labels[:, 4] *= nh / h / maxsize
if lrflip:
labels[:, 1] = 1 - labels[:, 1]
return labels | 1eb05502c22e7ad28fbac05a8131a6f16b0efa5f | 566,361 |
def parse_extension(extension):
"""Parse a single extension in to an extension token and a dict
of options.
"""
# Naive http header parser, works for current extensions
tokens = [token.strip() for token in extension.split(';')]
extension_token = tokens[0]
options = {}
for token in tokens[1:]:
key, sep, value = token.partition('=')
value = value.strip().strip('"')
options[key.strip()] = value
return extension_token, options | 11b205ce3e304cfd697c53a06e554a07a615d3c0 | 320,130 |
def _ToWebSafeString(per_result, internal_cursor):
"""Returns the web safe string combining per_result with internal cursor."""
return str(per_result) + ':' + internal_cursor | 61f8465d9e6e0634c4d99a402cbfc011a9bac717 | 286,364 |
def get_binary(community):
"""Binary variables for community."""
return [f"y_{org_id}" for org_id in community.organisms.keys()] | 4f92ac9c80dcf3125f9825aacbf304e6fb689605 | 608,952 |
def initialize_bins(start, end, width):
"""
Generate a list of interval borders.
@param start: The left border of the first interval.
@param end: The left border of the last interval.
@param width: The width of each interval.
@return: The list of interval borders.
"""
return list(range(start + width, end + width, width)) | 6118ce31574dec47755462a2ac190e51e15a4bcf | 207,126 |
from pathlib import Path
def get_label(f):
"""
f = '../celeba_man/fake/9992_split.jpg'
get_label(f) -> 'fake'
"""
return Path(f).parts[-2] | a2f70e1a25022c8a6975f2f48f811ae34b51314c | 157,297 |
def _mdtraj_summary(wizard, context, result):
"""Standard summary of MDTraj CVs: function, atom, topology"""
cv = result
func = cv.func
topology = cv.topology
indices = list(cv.kwargs.values())[0]
atoms_str = " ".join([str(topology.mdtraj.atom(i)) for i in indices[0]])
summary = (f" Function: {func.__name__}\n"
f" Atoms: {atoms_str}\n"
f" Topology: {repr(topology.mdtraj)}")
return [summary] | b5bfdfc39dd8f62e6046397438a05e2ed069bffb | 149,387 |
def ovs_version_str(host):
""" Retrieve OVS version and return it as a string """
mask_cmd = None
ovs_ver_cmd = "ovs-vsctl get Open_vSwitch . ovs_version"
with host.sudo():
if not host.exists("ovs-vsctl"):
raise Exception("Unable to find ovs-vsctl in PATH")
mask_cmd = host.run(ovs_ver_cmd)
if not mask_cmd or mask_cmd.failed or not mask_cmd.stdout:
raise Exception("Failed to get OVS version with command '{cmd}'"
.format(cmd=ovs_ver_cmd))
return mask_cmd.stdout.strip('"\n') | 607ffbb2ab1099e86254a90d7ce36d4a9ae260ed | 13,822 |
def variant_display_name(variant):
"""Construct a display name for a variant."""
display_name = "{}: {}: {}".format(
variant["Product SKU"],
variant["Product Name"],
variant["Question|Answer"]
)
return display_name.strip() | 8ef91205873f87769e3a1169208fd7174a4e5346 | 107,828 |
def hello(friend_name):
""" Returns a greeting for a friend name
:param friend_name: Name of friend to greet
:type friend_name: str
:return: Greeting to friend
"""
return 'Hello, {}!'.format(friend_name) | 56c77f6e29f751bbc01b1e24addb517b673f0b75 | 251,558 |
def serialize_none(x):
"""Substitute None with its string representation."""
return str(x) if x is None else x | 4f983c98d4f669a07ae4f8b71c0eeb9abd1fec06 | 272,166 |
import pprint
def pretty_str(obj):
"""Wrapper for the pprint.pformat function that generates a formatted
string representation of the input object.
"""
return pprint.pformat(obj, indent=4, width=79) | a4efc6cdb55a776e29598ca227e187459c66d688 | 348,123 |
def ascii_symbol_to_integer(character):
"""Convert ascii symbol to integer."""
if(character == ' '):
return 0
elif(character == '+'):
return 1
elif(character == '#'):
return 2 | ec50241bd6c7ae8bfc9f0ebcdfd194e597f5e8a4 | 151,435 |
def min_npix(npix):
"""
Minimum npix criteria
Parameters
----------
npix : int
The minimum number of pixels in a leaf
"""
def result(structure, index=None, value=None):
return len(structure.values()) >= npix
return result | fc078cc37ecd10638bcb0d8c3abaaa2de63f5dd8 | 429,582 |
def nopat(operating_income, tax_rate):
"""
nopat = Net Operating Profit After Tax
"""
return operating_income * (1-(tax_rate/100)) | de002f10b5deebf22e6a53428bbef663df649783 | 647,760 |
def mergesort_reversed(list):
"""
A mergesort implementation. The only difference is that it sorts the input list in a REVERSED ORDER.
I.e. the elements are sorted in a DESCENDING order.
:param list:
:type list: list
:return: list sorted in descending order
:rtype: list
"""
def _merge(left,right):
"""
The "conquert" part of merge-sort. Compare two lists item, by item, and append the one that is greater.
This ensures the descending order of this implementation of mergesort.
:param left: an input sorted with mergesort
:type left: list
:param right: an input sorted with mergesort
:type right: list
:return: merged and sorted list (in descending order) or all elements from left and right lists
"""
merged = []
left_index,right_index = 0,0
while left_index < len(left) and right_index < len(right):
if left[left_index] < right[right_index]:
merged.append(right[right_index])
right_index += 1
else:
merged.append(left[left_index])
left_index += 1
merged += left[left_index:]
merged += right[right_index:]
return merged
def _mergesort(items):
"""
The "divide" part of the mergesort. Recurrently calls mergesort to split array into a single element lists
(left and right). Merges those two lists, returning a sorted list in a descending order.
"""
if len(items) <= 1:
return items
mid = len(items) // 2
left = items[:mid]
right = items[mid:]
left = _mergesort(left)
right = _mergesort(right)
return _merge(left, right)
return _mergesort(list) | 3d6ba0cff8132f1e2b6deb9bced8ad35e3efeee9 | 447,340 |
def predict_cluster(x, centroids):
"""
Given a vector of dimension D and a matrix of centroids of dimension VxD,
return the id of the closest cluster
:params np.array x:
the data to assign
:params np.array centroids:
a matrix of cluster centroids
:returns int:
cluster assignment
"""
return ((x - centroids) ** 2).sum(axis=1).argmin(axis=0) | 3cbd582bd3a947e3d0a11ad05db1ca98547372e5 | 96,175 |
def get_id_pairs(track_list):
"""Create a list of (sid, eid) tuples from a list of tracks. Tracks without an eid will have an eid of None."""
return [(t["id"], t.get("playlistEntryId")) for t in track_list] | 8711a96d9c1367c2d5c151d6dc3d9be69b3aced6 | 136,604 |
def _is_audio_link(link):
"""Checks if a given link is an audio file"""
if "type" in link and link["type"][:5] == "audio":
return True
if link["href"].endswith(".mp3"):
return True
return False | 4551771b6e0b568c24d0c8e1234c4ffd086460e6 | 252,007 |
def weighted_average(items, weights):
"""
Returns the weighted average of a list of items.
Arguments:
items is a list of numbers.
weights is a list of numbers, whose sum is nonzero.
Each weight in weights corresponds to the item in items at the same index.
items and weights must be the same length.
"""
num = 0
denom = 0
assert len(items) > 0
assert len(items) == len(weights) #Verifying the lengths are equal
for i in range(0,len(items)):
num = num+(items[i]*weights[i]) #Calculate weighted avg
denom += weights[i]
return num/denom | bd535be8d39bafb2598add9f858878c8f0726c3f | 265,616 |
import socket
def current_fqdn() -> str:
"""Returns fully-qualified domain main (FQDN) of current machine"""
return socket.getfqdn() | e74005b306db756907bf34ddf0ee0bb1e2bbd8e0 | 433,250 |
from typing import Any
def logging_filter_log_records_for_chat(record: Any) -> bool:
"""Filters log records suitable for interactive chat."""
return (
record.msg.startswith("decoded")
or record.msg.startswith(" ->")
or record.msg.startswith("Restoring parameters from")
) | fae587aa8a6985667a24429db618da0b93743882 | 614,044 |
def MultiplyList(myList):
"""
multiplying the numbers in list
input: list
output: returns the multiplication
of numbers in given list
"""
# Multiply elements one by one
result = 1
for x in myList:
result = result * x
return result | c852428ea3d34e780c50b7b58bb22083d4743ea4 | 338,879 |
def rename_entity_id(old_name):
"""
Given an entity_id, rename it to something else. Helpful if ids changed
during the course of history and you want to quickly merge the data. Beware
that no further adjustment is done, also no checks whether the referred
sensors are even compatible.
"""
rename_table = {
"sensor.old_entity_name": "sensor.new_entity_name",
}
if old_name in rename_table:
return rename_table[old_name]
return old_name | c2461fda461392404694f7ac084a9f86a2b40c9f | 120,517 |
def getColName(col):
""" The column name is the concatination of the table's "abbr" and the column name.
If abbr doesn't exist, it's just the column name
"""
strAbbr = col.parentNode.parentNode.getAttribute('abbr')
if len(strAbbr) > 0:
return strAbbr + '_' + col.getAttribute('name')
return col.getAttribute('name') | d05b205665cff9e6859769edfd338fe97fdfa157 | 409,706 |
def get_method_name(name):
# type: (str) -> str
"""Get a method name from a fully qualified method name."""
pos = name.rfind('::')
if pos == -1:
return name
return name[pos + 2:] | d2e9c0865cac417f88fe8b4812ac629b3f0303e3 | 314,735 |
def _stringify(major: int, minor: int, micro: int = 0, releaselevel: str = 'final', serial: int = 0, **kwargs) -> str:
"""Stringifies a version number based on version info given. Follows :pep:`440`.
Releaselevel is the status of the given version, NOT the project itself.
All versions of an alpha or beta should be a 'final' releaselevel.
Serial is only taken into account if releaselevel is not 'final' or 'release'.
For developmental releases, post releases, and local release specifications, see
https://www.python.org/dev/peps/pep-0440/#normalization
| Ex: (2021, 9) -> 2021.9
| Ex: (0, 3, 2, 'beta') -> 0.3.2b
| Ex: (1, 0, 0, 'release') -> 1.0
| Ex: (3, 10, 0, 'candidate', 0) -> 3.10rc
| Ex: (3, 9, 1, 'alpha', 3) -> 3.9.2a3
| Ex: (3, 9, 1, dev=2) -> 3.9.2.dev2
| Ex: (3, 9, 2, 'preview', 3, post=0, post_implicit=True, dev=5) -> 3.9.2pre3-0.dev5
| Ex: (1, 0, local='ubuntu', local_ver='2', local_ver_sep='-') -> 1.0+ubuntu-2
:param major: First and most important version number.
:param minor: Second and less important version number.
:param micro: Last and least important version number.
:param releaselevel: Status of current version.
:param serial: Separate version number of an Alpha/Beta for an upcoming release version.
:keyword local: Local release type, ex: 'ubuntu'
:keyword local_ver: Local release version
:keyword local_ver_sep: Local release seperator
:keyword pre_sep: Pre-release seperator
:keyword pre_ver_sep: Pre-release version seperator
:keyword post: Post-release version
:keyword post_implicit: Post-release version
:keyword post_sep: Post-release seperator
:keyword post_ver_sep: Post-release version seperator
:keyword dev: Developmental release version
:keyword dev_sep: Developmental release seperator
:keyword dev_post: Developmental Post-release version
:keyword dev_post_sep: Developmental Post-release seperator
:keyword dev_post_ver_sep: Developmental Post-release version seperator
:return: String representation of version number.
:raises TypeError: Version numbers are not integers.
:raises ValueError: Version separators are not in the allowed chars.
"""
(local, local_ver, local_ver_sep, pre_sep, pre_ver_sep,
post, post_spelling, post_implicit, post_sep, post_ver_sep,
dev, dev_sep, dev_post, dev_post_sep, dev_post_ver_sep) = (
kwargs.pop('local', None),
kwargs.pop('local_ver', 0),
kwargs.pop('local_ver_sep', '.'),
kwargs.pop('pre_sep', ''),
kwargs.pop('pre_ver_sep', ''),
kwargs.pop('post', None),
kwargs.pop('post_spelling', 'post'),
kwargs.pop('post_implicit', False),
kwargs.pop('post_sep', ''),
kwargs.pop('post_ver_sep', ''),
kwargs.pop('dev', None),
kwargs.pop('dev_sep', ''),
kwargs.pop('dev_post', None),
kwargs.pop('dev_post_sep', ''),
kwargs.pop('dev_post_ver_sep', ''),
)
releaselevel = releaselevel.strip()
separators: tuple[str, ...] = ('', '.', '-', '_')
post_spellings: tuple[str, ...] = ('post', 'rev', 'r')
release_levels: tuple[str, ...] = ('a', 'b', 'c', 'rc', 'pre', 'alpha', 'beta', 'candidate', 'preview', 'final', 'release')
for attr in ('major', 'minor', 'micro', 'local_ver', 'post', 'dev', 'dev_post'):
if vars()[attr] is not None and not isinstance(vars()[attr], int):
raise TypeError(f'Argument "{attr}" should be of type {int}') # pragma: no cover
if (False in (sep in separators for sep in (pre_sep, pre_ver_sep, post_sep, post_ver_sep, dev_sep, dev_post_sep, dev_post_ver_sep)) or
local_ver_sep not in separators[1:]):
raise ValueError(f'A separator given is not in allowed separators {separators}')
if post_spelling not in post_spellings:
raise ValueError(f'Post-release spelling not allowed as "{post_spelling}"')
if releaselevel not in release_levels:
raise ValueError(f'Release level "{releaselevel}" is not in known release levels')
v_number: str = f'{major}.{minor}'
v_number += f'.{micro}' if micro else ''
if releaselevel and releaselevel not in ('final', 'release'):
if releaselevel in ('candidate', 'c'):
releaselevel = 'rc'
if releaselevel in ('alpha', 'beta'):
releaselevel = releaselevel[0]
if releaselevel == 'preview':
releaselevel = 'pre'
v_number += pre_sep
v_number += releaselevel if len(releaselevel) <= 3 else releaselevel[0]
v_number += f'{pre_ver_sep}{serial}' if serial else ''
if post is not None:
sep = f'{post_sep}{post_spelling}' if not post_implicit else '-'
v_number += f'{sep}{post_ver_sep if post else ""}{post if post or sep == "-" else ""}'
if dev is not None:
v_number += f'{dev_sep}dev{dev if dev else ""}'
if dev_post is not None:
sep = f'{dev_post_sep + post_spelling}' if not post_implicit else '-'
v_number += f'{sep}{dev_post_ver_sep if dev_post else ""}{dev_post if dev_post or sep == "-" else ""}'
if local is not None:
v_number += f'+{local + local_ver_sep}{local_ver}'
return v_number | e55d6a68260dcf153608ffc4db2eef7fab288cef | 210,251 |
from typing import Tuple
def egcd(a: int, b: int)->Tuple[int, int, int]:
"""Extended Euclidean algorithm to compute the gcd
Taken from https://en.wikibooks.org/wiki/Algorithm_Implementation/Mathematics/Extended_Euclidean_algorithm
Returns:
A tuple (g, x, y) where a*x + b*y = gcd(x, y)"""
if a == 0:
return (b, 0, 1)
g, x, y = egcd(b % a, a)
return (g, y - (b // a) * x, x) | 8fcc2bdd0e8de089cff912536cff273d8cec842a | 271,737 |
def is_iterable(obj) -> bool:
"""Whether the given object is iterable or not.
This is tested simply by invoking ``iter(obj)`` and returning ``False`` if
this operation raises a TypeError.
Args:
obj: The object to test
Returns:
bool: True if iterable, False else
"""
try:
iter(obj)
except TypeError:
return False
return True | 0be1d1e6c372465093bc4f12800a9727793542ee | 216,366 |
def compact_counts_to_100_shots(counts):
"""Compact counts to 100 shots
This helps to reduce animation generation time, and file size
Args:
counts (dict): job result counts, e.g. For 1024 shots: {'000': 510, '111': 514}
Returns:
dict: the compacted-counts, e.g. {'000': 51, '111': 51}
"""
big_counts = counts.copy()
if (sum(counts.values())>100):
total = sum(big_counts.values())/100
for x in big_counts:
big_counts[x] = int(big_counts[x]/total)
big_counts = {x:y for x,y in big_counts.items() if y!=0}
if (big_counts=={}): return counts
return big_counts | dd5fdad65d67bb82c2c2bc3f1e084b5731d5b7c6 | 467,836 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.