seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
import re
def preprocess(text_string):
"""
Accepts a text string and replaces:
1) urls with URLHERE
2) lots of whitespace with one instance
3) mentions with MENTIONHERE
This allows us to get standardized counts of urls and mentions
Without caring about specific people mentioned
"""
space_pattern = '\s+'
giant_url_regex = ('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|'
'[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+')
mention_regex = '@[\w\-]+'
parsed_text = re.sub(space_pattern, ' ', text_string)
parsed_text = re.sub(giant_url_regex, '', parsed_text)
parsed_text = re.sub(mention_regex, '', parsed_text)
return parsed_text | bigcode/self-oss-instruct-sc2-concepts |
def to_query_str(params):
"""Converts a dict of params to afaln actual query string.
Args:
params: dict of simple key-value types, where key is a string and
value is a string or something that can be converted into a
string. If value is a list, it will be converted to a comma-
delimited string (e.g., thing=1,2,3)
Returns:
A URI query string starting with '?', or and empty string if there
are no params (the dict is empty).
"""
if not params:
return ''
# PERF: This is faster than a list comprehension and join, mainly
# because it allows us to inline the value transform.
query_str = '?'
for k, v in params.items():
if v is True:
v = 'true'
elif v is False:
v = 'false'
elif isinstance(v, list):
# PERF(kgriffs): map is faster than list comprehension in
# py26 and py33. No significant different in py27
v = ','.join(map(str, v))
else:
v = str(v)
query_str += k + '=' + v + '&'
return query_str[:-1] | bigcode/self-oss-instruct-sc2-concepts |
def writexl_new_content_types_text(db):
"""
Returns [Content_Types].xml text
:param pylightxl.Database db: database contains sheetnames, and their data
:return str: [Content_Types].xml text
"""
# location: [Content_Types].xml
# inserts: many_tag_sheets, tag_sharedStrings
# note calcChain is part of this but it is not necessary for excel to open
xml_base = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n' \
'<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">\r\n' \
'<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>\r\n' \
'<Default Extension="xml" ContentType="application/xml"/>\r\n' \
'<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>\r\n' \
'{many_tag_sheets}\r\n' \
'{tag_sharedStrings}\r\n' \
'<Override PartName="/docProps/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml"/>\r\n' \
'<Override PartName="/docProps/app.xml" ContentType="application/vnd.openxmlformats-officedocument.extended-properties+xml"/>\r\n' \
'</Types>'
xml_tag_sheet = '<Override PartName="/xl/worksheets/sheet{sheet_id}.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>\r\n'
xml_tag_sharedStrings = '<Override PartName="/xl/sharedStrings.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml"/>\r\n'
many_tag_sheets = ''
for sheet_id, _ in enumerate(db.ws_names, 1):
many_tag_sheets += xml_tag_sheet.format(sheet_id=sheet_id)
if db._sharedStrings:
tag_sharedStrings = xml_tag_sharedStrings
else:
tag_sharedStrings = ''
rv = xml_base.format(many_tag_sheets=many_tag_sheets,
tag_sharedStrings=tag_sharedStrings)
return rv | bigcode/self-oss-instruct-sc2-concepts |
import importlib
def import_object(string: str):
"""Import an object from a string.
The object can be a function, class or method.
For example: `'keras.layers.Dense.get_weights'` is valid.
"""
last_object_got = None
seen_names = []
for name in string.split("."):
seen_names.append(name)
try:
last_object_got = importlib.import_module(".".join(seen_names))
except ModuleNotFoundError:
last_object_got = getattr(last_object_got, name)
return last_object_got | bigcode/self-oss-instruct-sc2-concepts |
def time_in_range(start, end, x):
"""
Return true if x is in the range [start, end]
"""
if start <= end:
return start <= x <= end
else:
return start <= x or x <= end | bigcode/self-oss-instruct-sc2-concepts |
import posixpath
def extract_version(module_name):
"""
extract the version number from the module name provided.
:param module_name: <str> the module to find version in.
:return: <int> version number.
"""
# module_name_v0000.py --> module_name, _v0000.py --> _v0000
return posixpath.splitext(module_name.split('_v')[-1])[0] | bigcode/self-oss-instruct-sc2-concepts |
def indices(lst, element):
""" A function that searches for all occurrences of an element in a list """
result = []
offset = -1
while True:
try:
offset = lst.index(element, offset + 1)
except ValueError:
return result
result.append(offset) | bigcode/self-oss-instruct-sc2-concepts |
def next_greatest_letter(letters: list[str], target: str) -> str:
"""Returns the the smallest element in the list that is larger than the given target
Args:
letters:
A list of sorted characters drawn from the lowercase latin
alphabet that also wraps around. For example, if the target is
target = 'z' and letters = ['a', 'b'], the answer is 'a'.
target:
The letter target for which we are to find the smallest
strictly greater element.
Examples:
>>> next_greatest_letter(["c", "f", "j"],"a")
'c'
>>> next_greatest_letter(["c", "f", "j"],"c")
'f'
>>> next_greatest_letter(["c", "f", "j"],"d")
'f'
>>> next_greatest_letter(["c", "f", "j"],"g")
'j'
>>> next_greatest_letter(["c", "f", "j"],"j")
'c'
>>> next_greatest_letter(["c", "f", "j"],"k")
'c'
"""
if not letters:
return ""
start_idx, end_idx = 0, len(letters) - 1
while start_idx <= end_idx:
mid_idx = start_idx + (end_idx - start_idx) // 2
if letters[mid_idx] <= target:
start_idx = mid_idx + 1
elif letters[mid_idx] > target: # pragma: no branch
end_idx = mid_idx - 1
# If start_idx pointer exceeded the array bounds, this implies that
# letters[-1] < next_greatest_letter < letters[0] which further implies
# that `letters[0]` is the smallest element strictly greater than `target`
next_greatest_letter_idx = start_idx if start_idx < len(letters) else 0
return letters[next_greatest_letter_idx] | bigcode/self-oss-instruct-sc2-concepts |
import math
def floatToJson(x):
"""Custom rule for converting non-finite numbers to JSON as quoted strings: ``"inf"``, ``"-inf"``, and ``"nan"``.
This avoids Python's bad habit of putting literal ``Infinity``, ``-Infinity``, and ``NaN``
in the JSON (without quotes)."""
if x in ("nan", "inf", "-inf"):
return x
elif math.isnan(x):
return "nan"
elif math.isinf(x) and x > 0.0:
return "inf"
elif math.isinf(x):
return "-inf"
else:
return x | bigcode/self-oss-instruct-sc2-concepts |
def points_to_vec(pt1, pt2, flip = False):
"""
Converts the coordinate of two points (pt1 > pt2) to a vector
flip: bool, default = False
If the coordinate system should be flipped such that higher y-coords
are lower (e.g. needed when working with images in opencv).
"""
vx = pt2[0] - pt1[0]
vy = pt1[1] - pt2[1] if flip else pt2[1] - pt1[1]
return vx, vy | bigcode/self-oss-instruct-sc2-concepts |
def rbits_to_int(rbits):
"""Convert a list of bits (MSB first) to an int.
l[0] == MSB
l[-1] == LSB
0b10000
| |
| \\--- LSB
|
\\------ MSB
>>> rbits_to_int([1])
1
>>> rbits_to_int([0])
0
>>> bin(rbits_to_int([1, 0, 0]))
'0b100'
>>> bin(rbits_to_int([1, 0, 1, 0]))
'0b1010'
>>> bin(rbits_to_int([1, 0, 1, 0, 0, 0, 0, 0]))
'0b10100000'
"""
v = 0
for i in range(0, len(rbits)):
v |= rbits[i] << len(rbits)-i-1
return v | bigcode/self-oss-instruct-sc2-concepts |
def esi_Delta(Delta, q):
"""
Calculate equivalent step index (esi) Delta for a graded-index fiber.
Args:
Delta : relative refractive index [-]
Returns:
equivalent relative refractive index [-]
"""
return q * (2 + q) / (1 + q)**2 * Delta | bigcode/self-oss-instruct-sc2-concepts |
def read_worksheet(worksheet_name, workbook):
"""Read worksheet table to list of dicts
"""
output = []
try:
data = workbook[worksheet_name].values
except KeyError:
print("Worksheet {} not found".format(worksheet_name))
return output
keys = next(data)
data = list(data)
for row in data:
item = dict()
for key, value in zip(keys, row):
if key is not None:
item[key] = value
else:
if value is not None:
print(worksheet_name, value, "had no column name")
output.append(item)
return output | bigcode/self-oss-instruct-sc2-concepts |
def generate_macs_args(flags):
"""
This is a helper function that takes the sim options and outputs the start the macs_args
:param flags:
:return macs_args:
"""
macs_args = None
if '-macs_file' in flags:
macs_args = [flags['-macs_file'][0][0], flags['-length'][0][0], "-I", flags['-I'][0][0]]
elif '-macsswig' in flags:
macs_args = [flags['-macsswig'][0][0], flags['-length'][0][0], "-I", flags['-I'][0][0]]
elif '-macs' in flags:
macs_args = [flags['-macs'][0][0], flags['-length'][0][0], "-I", flags['-I'][0][0]]
else:
# This option should never be reached since it errors out in housekeeping
print("There is no sim option given. Check your model file.")
exit(1)
return macs_args | bigcode/self-oss-instruct-sc2-concepts |
def _expand(dict_in):
""" Convert {key1: list1, key2: list2} to
{list1[0]: key1, list1[1]: key1, list2[0]: key2 etc}
"""
dict_out = {}
for key in dict_in:
for item in dict_in[key]:
dict_out[item] = key
return dict_out | bigcode/self-oss-instruct-sc2-concepts |
def replacer(svgFile, toReplace, newData):
"""
Searches through SVG file until it finds a toReplace, once found, replaces it with newData
"""
for count in range(0,len(svgFile)):
found = svgFile[count].find(toReplace) #Check if the current line in the SVG file has the required string
if not (found == -1):
location = (svgFile[count]).find(toReplace) #We know exact location on the line that Name and Twitter are
partone = (str(svgFile[count])[:location]) #Grab part of line before the searched for string
parttwo = (str(svgFile[count])[(location+len(toReplace)):]) #Grab part of line after the searched for string
svgFile[count] = partone + newData + parttwo
break
return svgFile | bigcode/self-oss-instruct-sc2-concepts |
def get_delimited_string_from_list(_list, delimiter=', ', wrap_values_with_char=None, wrap_strings_with_char=None):
"""Given a list, returns a string representation of that list with specified delimiter and optional string chars
_list -- the list or tuple to stringify
delimiter -- the the character to seperate all values
wrap_values_with_char -- if specified, will wrap all values in list with this character in the representation
wrap_strings_with_char -- if specified, will wrap only values of type str with this character in the representation
"""
if wrap_values_with_char is not None:
return delimiter.join('{wrapper}{val}{wrapper}'.format(
val=v,
wrapper=wrap_values_with_char
) for v in _list)
elif wrap_strings_with_char is not None:
return delimiter.join(str(v) if not isinstance(v, str) else '{wrapper}{val}{wrapper}'.format(
val=v,
wrapper=wrap_strings_with_char
) for v in _list)
else:
return delimiter.join(str(v) for v in _list) | bigcode/self-oss-instruct-sc2-concepts |
def get_yaml(path):
"""
Return the Yaml block of a post and the linenumbers of it.
"""
end = False
yaml = ""
num = 0
with open(path, 'r', encoding='utf-8') as f:
for line in f.readlines():
if line.strip() == '---':
if end:
break
else:
end = True
continue
else:
num += 1
yaml += line
return yaml, num | bigcode/self-oss-instruct-sc2-concepts |
def bitcount(num):
"""
Count the number of bits in a numeric (integer or long) value. This
method is adapted from the Hamming Weight algorithm, described (among
other places) at http://en.wikipedia.org/wiki/Hamming_weight
Works for up to 64 bits.
:Parameters:
num : int
The numeric value
:rtype: int
:return: The number of 1 bits in the binary representation of ``num``
"""
# Put count of each 2 bits into those 2 bits.
num = num - ((num >> 1) & 0x5555555555555555)
# Put count of each 4 bits into those 4 bits.
num = (num & 0x3333333333333333) + ((num >> 2) & 0x3333333333333333)
# Put count of each 8 bits into those 8 bits.
num = (num + (num >> 4)) & 0x0f0f0f0f0f0f0f0f
# Left-most bits.
return int((num * 0x0101010101010101) >> 56) | bigcode/self-oss-instruct-sc2-concepts |
def _pad_binary(bin_str, req_len=8):
"""
Given a binary string (returned by bin()), pad it to a full byte length.
"""
bin_str = bin_str[2:] # Strip the 0b prefix
return max(0, req_len - len(bin_str)) * '0' + bin_str | bigcode/self-oss-instruct-sc2-concepts |
def income3(households):
"""
Dummy for for income group 3
"""
return (households['income_category'] == 'income group 3').astype(int) | bigcode/self-oss-instruct-sc2-concepts |
def _deep_flatten(items): # pylint: disable=invalid-name
"""Returns a list of objects, flattening sublists/subtuples along the way.
Example: _deep_flatten([1, (2, 3, (4, 5), [6, 7]), [[[8]]]]) would return
the list [1, 2, 3, 4, 5, 6, 7, 8].
Args:
items: An iterable. If elements of this iterable are lists or tuples, they
will be (recursively) flattened until non-list non-tuple objects are
reached.
Returns:
A list of non-list, non-tuple objects.
"""
def _flat_gen(xs): # pylint: disable=invalid-name
for x in xs:
if isinstance(x, (list, tuple)):
for y in _flat_gen(x):
yield y
else:
yield x
return list(_flat_gen(items)) | bigcode/self-oss-instruct-sc2-concepts |
def depth2inv(depth):
"""
Invert a depth map to produce an inverse depth map
Parameters
----------
depth : torch.Tensor or list of torch.Tensor [B,1,H,W]
Depth map
Returns
-------
inv_depth : torch.Tensor or list of torch.Tensor [B,1,H,W]
Inverse depth map
"""
if isinstance(depth, tuple) or isinstance(depth, list):
return [depth2inv(item) for item in depth]
else:
inv_depth = 1. / depth.clamp(min=1e-6)
inv_depth[depth <= 0.] = 0.
return inv_depth | bigcode/self-oss-instruct-sc2-concepts |
def get_unit_string_from_comment(comment_string):
"""return unit string from FITS comment"""
bstart = comment_string.find("[")
bstopp = comment_string.find("]")
if bstart != -1 and bstopp != -1:
return comment_string[bstart + 1: bstopp]
return None | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
import torch
def _size_repr(key: str, item: Any) -> str:
"""String containing the size / shape of an object (e.g. a tensor, array)."""
if isinstance(item, torch.Tensor) and item.dim() == 0:
out = item.item()
elif isinstance(item, torch.Tensor):
out = str(list(item.size()))
elif isinstance(item, list):
out = f"[{len(item)}]"
else:
out = str(item)
return f"{key}={out}" | bigcode/self-oss-instruct-sc2-concepts |
def _strip(json_str):
"""Strip //-prefixed comments from a JSON string."""
lines = []
for line in json_str.split('\n'):
pos = line.find('//')
if pos > -1:
line = line[:pos]
lines.append(line)
return '\n'.join(lines) | bigcode/self-oss-instruct-sc2-concepts |
def load_yolo_predictions(txt_path, classes=None):
"""Return a list of records from YOLO prediction file.
Each record is a list `[label, box, score]`, where the box contains
coordinates in YOLOv5 format. `score` can be None if text file does
not contain scores, and `label` is either integer, or string if the
mapping `classes` is provided.
"""
result = []
for line in open(txt_path, "r"):
label, x_c, y_c, w, h, *rest = line.split()
label = int(label)
if classes:
label = classes[label]
box = [float(x_c), float(y_c), float(w), float(h)]
score = float(rest[0]) if rest else None
result.append([label, box, score])
return result | bigcode/self-oss-instruct-sc2-concepts |
def group_changes(changes):
"""Consolidate same-position insertions and deletions into single changes.
"""
insertions = [c for c in changes if c.change_type == 'insert']
deletions = [c for c in changes if c.change_type == 'delete']
mutations = [c for c in changes if c.change_type == 'mutate']
inserted_locations = [ins.position for ins in insertions]
grouped_insertions = []
for i, ins in enumerate(insertions):
if i > 0:
if ins.position == insertions[i-1].position:
grouped_insertions[-1].output_material += ins.output_material
continue
grouped_insertions.append(ins)
grouped_deletions = []
for i, dlt in enumerate(deletions):
if i > 0:
if dlt.position == deletions[i-1].position+2 and dlt.position-1 not in inserted_locations:
grouped_deletions[-1].input_material += dlt.input_material
continue
grouped_deletions.append(dlt)
return sorted(grouped_insertions + grouped_deletions + mutations, key=lambda x: x.position) | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def hashstring(s: str) ->str:
"""
Generating an "unique" user id from the sha224 algorithm.
"""
return hashlib.sha224(s.encode('ascii')).hexdigest() | bigcode/self-oss-instruct-sc2-concepts |
import re
def deNumerize(text:str) -> str:
"""Removes numbers from strings"""
regex_pattern = re.compile(pattern = r'[0-9]', flags=re.UNICODE)
return regex_pattern.sub(r'', text) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Any
def get_schema_type(arg_schema: Dict[str, Any]) -> str:
"""Returns the schema type for an argument.
Args:
arg_schema: dict(str, *). Schema for an argument.
Returns:
str. Returns schema type by extracting it from schema.
"""
return arg_schema['schema']['type'] | bigcode/self-oss-instruct-sc2-concepts |
def extractScopeLFN(scope_lfn):
""" Extract the scope and LFN from the scope_lfn string """
# scope_lfn = scope:lfn -> scope, lfn
_dummy = scope_lfn.split(':')
return _dummy[0], _dummy[1] | bigcode/self-oss-instruct-sc2-concepts |
def set_style(style,
text_color='white',
highlight_hover=True,
mini_zoom=False,
th_mini_font_size=6,
enforce_size=False,
td_width=15,
td_height=15):
"""Imposes some styling options on a DataFrame.style object."""
properties = [
{
'selector': 'td',
'props': [
('color', text_color),
]
},
{
'selector':
'table',
'props': [
('table-layout', 'fixed'),
('width', '100%'),
('height', '100%'),
]
},
{
'selector': '',
'props': [('border-collapse', 'collapse')]
},
{
'selector': 'table, tr, th, td',
'props': [('border', '1px solid black')]
},
]
if enforce_size:
properties.append({
'selector':
'tr, th, td',
'props': [('overflow', 'hidden'), ('text-overflow',
'clip'), ('width',
'{}px'.format(td_width)),
('height',
'{}px'.format(td_height)), ('max-width',
'{}px'.format(td_width)),
('max-height', '{}px'.format(td_height)), ('white-space',
'nowrap')]
})
if highlight_hover:
properties.append({
'selector': 'tr:hover',
'props': [('background-color', 'yellow')]
})
if mini_zoom:
properties.extend([{
'selector': 'th',
'props': [('font-size', '{}pt'.format(th_mini_font_size))]
}, {
'selector': 'td',
'props': [('padding', '0em 0em'),
('font-size', '1px')]
}, {
'selector': 'td:hover',
'props': [
('max-width', '200px'),
('font-size', '12pt'),
('padding', '10px')]
}, {
'selector': 'th:hover',
'props': [
('max-width', '200px'),
('font-size', '12pt'),
('padding', '10px')]
}, {
'selector': 'tr:hover',
'props': [
('max-width', '200px'),
('font-size', '12pt'),
('padding', '10px')]
}])
return style.set_table_styles(properties).set_table_attributes('border=1') | bigcode/self-oss-instruct-sc2-concepts |
def _hasfield(model_fields, field_name):
"""
Check if field name exists in list of model fields
:param list model_fields: List of Django Model object fields
:param string field_name: attribute string, dotted or dunderscored.
example: 'user.first_name' or 'user__first_name'
:returns: Field object or False
"""
for field in model_fields:
if field.name == field_name:
return field
return False | bigcode/self-oss-instruct-sc2-concepts |
def enum_solutions(node):
"""
>>> node = {'entry': {'lemma': u'EOS'}}
>>> enum_solutions(node)
[[u'EOS']]
>>> node = {
... 'entry': {'lemma': u'これ'},
... 'next': [
... {
... 'entry': {'lemma': u'は'},
... 'next': [
... {
... 'entry': {'lemma': u'テスト'},
... 'next': [
... {
... 'entry': {'lemma': u'EOS'},
... 'next': [],
... },
... ],
... }
... ]
... }
... ]
... }
>>> enum_solutions(node)
[[u'\xe3\x81\x93\xe3\x82\x8c', u'\xe3\x81\xaf', u'\xe3\x83\x86\xe3\x82\xb9\xe3\x83\x88', u'EOS']]
"""
results = []
if node['entry']['lemma'] == u'EOS':
return [[u'EOS']]
for nnode in node['next']:
for solution in enum_solutions(nnode):
results.append([node['entry']['lemma']] + solution)
return results | bigcode/self-oss-instruct-sc2-concepts |
def postprocess(var_list):
"""수집한 환자수 후처리
Args:
var_list: 후처리 할 문자열 list
Returns:
(list) var_list 순서대로 후처리된 결과
"""
result = []
for var in var_list:
var = var.replace(',', '').strip()
if '.' in var:
var = float(var)
elif var == '-':
var = 0
elif var:
var = int(var)
else:
var = None
result.append(var)
return result | bigcode/self-oss-instruct-sc2-concepts |
def edit_distance(left_word: str, right_word: str) -> int:
""" The difference between same-length words in number of edits
The result is the edit distance of the two words (number of
substitutions required to tranform left_word into right_word).
Args:
left_word: One word to compare
right_word: The other word to compare
Returns:
An integer representing the edit distance
Raises:
ValueError: If the lengths of the word args are different
"""
if len(left_word) != len(right_word):
raise ValueError("Word ladder words must be same length")
distance = 0;
for i in range(len(left_word)):
if left_word[i] != right_word[i]:
distance += 1
return distance | bigcode/self-oss-instruct-sc2-concepts |
def convert_to_undirected(G):
"""Return a new undirected representation of the graph G."""
return G.to_undirected() | bigcode/self-oss-instruct-sc2-concepts |
def make_tuple(input):
"""
returns the input as a tuple. if a string is
passed, returns (input, ). if a tupple is
passed, returns the tupple unmodified
"""
if not isinstance(input, (tuple, list)):
input = (input,)
return input | bigcode/self-oss-instruct-sc2-concepts |
def rawformat(x, pos):
"""
Generic number formatter to help log plot look nice
"""
if (x < 1000): return '%1.0f' % x
if (x < 10000): return '%1.1fK' % (x/1000.0)
if (x < 1000000): return '%1.0fK' % (x/1000.0)
if (x < 1e9): return '%1.1fM' % (x/1.0e6)
if (x < 1e12): return '%1.1fB' % (x/1.0e9)
return '%1.1fT' % (x/1.0e12) | bigcode/self-oss-instruct-sc2-concepts |
def get_nested_attr(obj, attr, default=None):
"""Get nested attributes of an object."""
attrs = attr.split(".")
for a in attrs:
try:
obj = getattr(obj, a)
except AttributeError:
if default:
return default
else:
raise
return obj | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def validate_proof(previous_proof, proof):
"""
Validates the new proof.
:param int previous_proof: Proof of the previous block
:param int proof: Potential proof of the next block
:return bool: True if the new proof is valid, False if not
"""
attempt = f'{previous_proof}{proof}'.encode()
hashed_attempt = hashlib.sha256(attempt).hexdigest()
return hashed_attempt[:4] == '0000' | bigcode/self-oss-instruct-sc2-concepts |
def split_barcode(barcode, return_gg=False):
"""Splits a barcode sequence into part A, part C, and part B sequences."""
split = barcode.split("-")
if len(split) == 2:
# Remove the gem group from the barcode
barcode, gem_group = split
else:
gem_group = None
assert len(barcode) == 16
part_a, part_c, part_b = barcode[:7], barcode[7:9], barcode[9 : 9 + 7]
if return_gg:
return part_a, part_c, part_b, gem_group
return part_a, part_c, part_b | bigcode/self-oss-instruct-sc2-concepts |
import math
def compute_idfs(documents):
"""
Given a dictionary of `documents` that maps names of documents to a list
of words, return a dictionary that maps words to their IDF values.
Any word that appears in at least one of the documents should be in the
resulting dictionary.
"""
# Slightly modified from lecture 6 code: tfidf.py
# Create set of all words found in all documents
words = set()
for document in documents:
words.update(documents[document])
idfs = dict()
for word in words:
# Find number of docs that each word appears in
f = sum(word in documents[document] for document in documents)
# idf formula: log( total documents / # of docs containing word )
idf = math.log(len(documents) / f)
idfs[word] = idf
return idfs | bigcode/self-oss-instruct-sc2-concepts |
import csv
def _readcsv(file):
"""Read a CSV file into a multidimensional array of rows and columns."""
rows = []
with open(file, newline='') as csvfile:
reader = csv .reader(csvfile, delimiter=',', quotechar='"')
headers = next(reader, None) # headers
for row in reader:
rows.append([float(x) for x in row])
return headers, rows | bigcode/self-oss-instruct-sc2-concepts |
def format_txt_desc(node):
"""
Formats a XML node into a plain text format.
"""
desc_buf = ''
for desc in node.childNodes:
if desc.nodeName == "#text":
desc_buf += desc.data + "\n"
elif desc.nodeName == "p":
desc_buf += desc.firstChild.data + "\n"
for chld in desc.childNodes:
if chld.nodeName == "ul":
desc_buf += "\n"
for li in chld.getElementsByTagName("li"):
desc_buf += "\t -" + li.firstChild.data + "\n"
return desc_buf.strip() + "\n" | bigcode/self-oss-instruct-sc2-concepts |
def sum_attributes(triplet):
"""
return the sum of the attributes of a triplet
ie: triplet = (((2, 2, 2, 2), (3, 3, 3, 3), (1, 2, 3, 1)))
returns [6, 7, 8, 6] <- [2+3+1, 2+3+2, 2+3+3, 2+3+1]
"""
return [sum(a) for a in zip(*triplet)] | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
from typing import Iterable
from typing import Any
def flatten_to_list(obj: Union[Iterable[Any], Any]) -> Union[list[Any], Any]:
"""
Flattens iterable to a non-nested list
Function ignores strings and treats as non-iterable
:param obj: iterable of nested iterables
:return: list of non-iterable objects
"""
if (not isinstance(obj, Iterable)) or isinstance(obj, str):
return obj
else:
out = []
for item in obj:
if (not isinstance(item, Iterable)) or isinstance(item, str):
out.append(item)
else:
out += flatten_to_list(item)
return out | bigcode/self-oss-instruct-sc2-concepts |
def clean_team_name(team_names):
"""Take a list of team_names, modify the names to match the format specified in br_references, and return a new list
Args:
team_names: a list of team_names to be checked for validity, and if needed, modified
"""
new_team_names = []
for team in team_names:
new_team_names.append(''.join(a for a in team if a.isalpha() or a.isspace() or a.isdigit()).upper())
return new_team_names | bigcode/self-oss-instruct-sc2-concepts |
from typing import Iterable
from typing import Callable
def any_matches(iterable: Iterable, cond_fn: Callable = bool) -> bool:
"""
Returns `True` if `cond_fn` is `True`
for one or more elements in `iterable`.
Parameters
----------
iterable : Iterable
The iterable to be checked
cond_fn : Callable
The condition function to be applied
"""
return any(map(cond_fn, iterable)) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Set
def get_valid_name_permutations(param_name: str) -> Set[str]:
"""Get all underscore permutations for provided arg name"""
return {
"_",
param_name,
f"_{param_name}",
f"{param_name}_",
} | bigcode/self-oss-instruct-sc2-concepts |
def add_arguments(parser, create_group=True):
"""A helper function to add standard command-line options to make an API
instance.
This adds the following command-line options:
--btn_cache_path: The path to the BTN cache.
Args:
parser: An argparse.ArgumentParser.
create_group: Whether or not to create a subgroup for BTN API options.
Defaults to True.
Returns:
Either the argparse.ArgumentParser or the subgroup that was implicitly
created.
"""
if create_group:
target = parser.add_argument_group("BTN API options")
else:
target = parser
target.add_argument("--btn_cache_path", type=str)
return target | bigcode/self-oss-instruct-sc2-concepts |
def import_object(module_name, attribute_name):
"""Import an object from its absolute path.
Example:
>>> import_object('datetime', 'datetime')
<type 'datetime.datetime'>
"""
module = __import__(module_name, {}, {}, [attribute_name], 0)
return getattr(module, attribute_name) | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_prefix(curie):
"""Get prefix from CURIE."""
match = re.fullmatch(r'([a-zA-Z.]+):\w+', curie)
if match is None:
raise ValueError(f'{curie} is not a valid CURIE')
return match[1] | bigcode/self-oss-instruct-sc2-concepts |
def cross(v1, v2):
"""
Returns the cross product of the given two vectors
using the formulaic definition
"""
i = v1[1] * v2[2] - v2[1] * v1[2]
j = v1[0] * v2[2] - v2[0] * v1[2]
k = v1[0] * v2[1] - v2[0] * v1[1]
return [i, -j, k] | bigcode/self-oss-instruct-sc2-concepts |
def iterable(item):
"""If item is iterable, returns item. Otherwise, returns [item].
Useful for guaranteeing a result that can be iterated over.
"""
try:
iter(item)
return item
except TypeError:
return [item] | bigcode/self-oss-instruct-sc2-concepts |
def xy_to_uv76(x, y): # CIE1931 to CIE1976
""" convert CIE1931 xy to CIE1976 u'v' coordinates
:param x: x value (CIE1931)
:param y: y value (CIE1931)
:return: CIE1976 u', v' """
denominator = ((-2 * x) + (12 * y) + 3)
if denominator == 0.0:
u76, v76 = 0.0, 0.0
else:
u76 = (4 * x) / denominator
v76 = (9 * y) / denominator
return u76, v76 # CIE1976 u', v' | bigcode/self-oss-instruct-sc2-concepts |
def parent(n: int) -> int:
"""Return the index of the parent of the node with a positive index n."""
return (n - 1) // 2 | bigcode/self-oss-instruct-sc2-concepts |
import collections
import itertools
def find_repeat(data):
"""You notice that the device repeats the same frequency change list over and
over. To calibrate the device, you need to find the first frequency it
reaches twice.
>>> find_repeat([+1, -1])
0
>>> find_repeat([+3, +3, +4, -2, -4])
10
>>> find_repeat([-6, +3, +8, +5, -6])
5
>>> find_repeat([+7, +7, -2, -7, -4])
14
"""
count = collections.defaultdict(int)
value = 0
for increment in itertools.cycle(data):
count[value] += 1
if count[value] == 2:
return value
value += increment | bigcode/self-oss-instruct-sc2-concepts |
def _next_power_of_two(value):
"""Return the first power of 2 greater than or equal to the input."""
power = 1
while power < value:
power *= 2
return power | bigcode/self-oss-instruct-sc2-concepts |
import math
def Tan(num):
"""Return the tangent of a value"""
return math.tan(float(num)) | bigcode/self-oss-instruct-sc2-concepts |
def _read_file(path):
"""Default read() function for use with hash_files()."""
with open(path,"rb") as f:
return f.read() | bigcode/self-oss-instruct-sc2-concepts |
def string_is_comment(a_string):
"""Is it a comment starting with a #."""
return a_string[0] == "#" | bigcode/self-oss-instruct-sc2-concepts |
def wrap(item):
"""Wrap a string with `` characters for SQL queries."""
return '`' + str(item) + '`' | bigcode/self-oss-instruct-sc2-concepts |
def recvn(sock, n):
"""
Read n bytes from a socket
Parameters
----------
sock - socket.socket
The socket to read from
n - int
The number of bytes to read
"""
ret = b''
read_length = 0
while read_length < n:
tmp = sock.recv(n - read_length)
if len(tmp)==0:
return ret
ret += tmp
read_length += len(tmp)
if read_length != n:
raise #"Low level Network ERROR: "
return ret | bigcode/self-oss-instruct-sc2-concepts |
def is_palindrome(n):
"""Returns True if integer n is a palindrome, otherwise False"""
if str(n) == str(n)[::-1]:
return True
else:
return False | bigcode/self-oss-instruct-sc2-concepts |
import textwrap
def prepare_description(report):
"""Constructs a description from a test report."""
raw = report['description']
# Wrap to at most 80 characters.
wrapped = textwrap.wrap(raw, 80)
description = wrapped[0]
if len(wrapped) > 1:
# If the text is longer than one line, add an ellipsis.
description += '...'
return description | bigcode/self-oss-instruct-sc2-concepts |
import torch
def select_nms_index(scores: torch.Tensor,
boxes: torch.Tensor,
nms_index: torch.Tensor,
batch_size: int,
keep_top_k: int = -1):
"""Transform NMS output.
Args:
scores (Tensor): The detection scores of shape
[N, num_classes, num_boxes].
boxes (Tensor): The bounding boxes of shape [N, num_boxes, 4].
nms_index (Tensor): NMS output of bounding boxes indexing.
batch_size (int): Batch size of the input image.
keep_top_k (int): Number of top K boxes to keep after nms.
Defaults to -1.
Returns:
tuple[Tensor, Tensor]: (dets, labels), `dets` of shape [N, num_det, 5]
and `labels` of shape [N, num_det].
"""
batch_inds, cls_inds = nms_index[:, 0], nms_index[:, 1]
box_inds = nms_index[:, 2]
# index by nms output
scores = scores[batch_inds, cls_inds, box_inds].unsqueeze(1)
boxes = boxes[batch_inds, box_inds, ...]
dets = torch.cat([boxes, scores], dim=1)
# batch all
batched_dets = dets.unsqueeze(0).repeat(batch_size, 1, 1)
batch_template = torch.arange(
0, batch_size, dtype=batch_inds.dtype, device=batch_inds.device)
batched_dets = batched_dets.where(
(batch_inds == batch_template.unsqueeze(1)).unsqueeze(-1),
batched_dets.new_zeros(1))
batched_labels = cls_inds.unsqueeze(0).repeat(batch_size, 1)
batched_labels = batched_labels.where(
(batch_inds == batch_template.unsqueeze(1)),
batched_labels.new_ones(1) * -1)
N = batched_dets.shape[0]
# expand tensor to eliminate [0, ...] tensor
batched_dets = torch.cat((batched_dets, batched_dets.new_zeros((N, 1, 5))),
1)
batched_labels = torch.cat((batched_labels, batched_labels.new_zeros(
(N, 1))), 1)
# sort
is_use_topk = keep_top_k > 0 and \
(torch.onnx.is_in_onnx_export() or keep_top_k < batched_dets.shape[1])
if is_use_topk:
_, topk_inds = batched_dets[:, :, -1].topk(keep_top_k, dim=1)
else:
_, topk_inds = batched_dets[:, :, -1].sort(dim=1, descending=True)
topk_batch_inds = torch.arange(
batch_size, dtype=topk_inds.dtype,
device=topk_inds.device).view(-1, 1).expand_as(topk_inds)
batched_dets = batched_dets[topk_batch_inds, topk_inds, ...]
batched_labels = batched_labels[topk_batch_inds, topk_inds, ...]
# slice and recover the tensor
return batched_dets, batched_labels | bigcode/self-oss-instruct-sc2-concepts |
def dict_from_cursor(cursor):
"""
Convert all rows from a cursor of results as a list of dicts
:param cursor: database results cursor
:return: list of dicts containing field_name:value
"""
columns = [col[0] for col in cursor.description]
return [
dict(zip(columns, row))
for row in cursor.fetchall()
] | bigcode/self-oss-instruct-sc2-concepts |
def parse_rmc_status(output, lpar_id):
"""
Parses the output from the get_rmc_status() command to return the RMC
state for the given lpar_id.
:param output: Output from IVM command from get_rmc_status()
:param lpar_id: LPAR ID to find the RMC status of.
:returns status: RMC status for the given LPAR. 'inactive' if lpar_id
not found.
"""
# Output example:
# 1,active
# 2,none
# 3,none
# 4,none
# 5,none
# Be sure we got output to parse
if not output:
return 'inactive'
# Inspect each line
for item in output:
# If lpar_id matches this line's lpar_id, return that status
if item.split(',')[0] == str(lpar_id):
return item.split(',')[1]
# If we got here, we didn't find the lpar_id asked for.
return 'inactive' | bigcode/self-oss-instruct-sc2-concepts |
def miles_to_kilometers(miles):
"""Convert miles to kilometers
PARAMETERS
----------
miles : float
A distance in miles
RETURNS
-------
distance : float
"""
# apply formula
return miles*1.609344 | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def _get_timestamped_path(
parent_path: Path,
middle_path,
child_path='',
timestamp='',
create=True,
):
"""
Creates a path to a directory by the following pattern:
parent_path / middle_path / [child_path] / [timestamp]
:param parent_path:
:param middle_path:
:param child_path:
:param timestamp
:param create: if True (default) will create all the directories in the path
:return: pathlib.Path object
"""
dir_path = parent_path / middle_path / child_path / timestamp
if create:
dir_path.mkdir(parents=True, exist_ok=True)
return dir_path | bigcode/self-oss-instruct-sc2-concepts |
def node2code(nodes, with_first_prefix=False):
"""
convert a node or a list of nodes to code str, e.g.
" import paddle" -> return "import paddle"
" import paddle" -> return "import paddle"
"""
if not isinstance(nodes, list):
nodes = [nodes]
code = ''
is_first_leaf = True
for node in nodes:
for leaf in node.leaves():
if is_first_leaf:
code = code + leaf.value
is_first_leaf = False
else:
code = code + str(leaf)
return code | bigcode/self-oss-instruct-sc2-concepts |
def is_int(int_string: str):
"""
Checks if string is convertible to int.
"""
try:
int(int_string)
return True
except ValueError:
return False | bigcode/self-oss-instruct-sc2-concepts |
def _get_course_marketing_url(config, course):
"""
Get the url for a course if any
Args:
config (OpenEdxConfiguration): configuration for the openedx backend
course (dict): the data for the course
Returns:
str: The url for the course if any
"""
for course_run in course.get("course_runs", []):
url = course_run.get("marketing_url", "")
if url and config.base_url in url:
return url.split("?")[0]
return None | bigcode/self-oss-instruct-sc2-concepts |
def try_get_value(obj, name, default):
"""
Try to get a value that may not exist.
If `obj.name` doesn't have a value, `default` is returned.
"""
try:
return getattr(obj, name)
except LookupError:
return default | bigcode/self-oss-instruct-sc2-concepts |
def count_null_urls(conn):
""" Queries the sqlite3 table unpaywall and finds the number of Nones in pdf_url"""
cur = conn.cursor()
query = """
SELECT count(*)
FROM unpaywall
WHERE pdf_url IS NOT NULL """
cur.execute(query)
return cur.fetchone()[0] | bigcode/self-oss-instruct-sc2-concepts |
def check_win(secret_word, old_letters_guessed):
"""
this function checks whether the player was able to guess the secret word and thus won the game
:param secret_word: the word the player has to guess
:param old_letters_guessed: all the characters the player has already guessed
:type secret_word: str
:type old_letters_guessed: list
:return: "TRUE" if all the letters that make up the secret word are included in the list of
letters the user guessed otherwise, "FALSE"
:rtype: bool
"""
winner = True
for char in secret_word:
if char not in old_letters_guessed:
winner = False
return winner | bigcode/self-oss-instruct-sc2-concepts |
def Axes_Set_Breakaxis(bottom_ax,top_ax,h,v,direction='v'):
"""
Remove the spines for between the two break axes (either in vertical
or horizontal direction) and draw the "small break lines" between
them.
Parameters:
-----------
direction: the direction of the two break axes, could either be
'horizontal/h' or 'vertical/v'
bottom_ax/top_ax: in case of direction == 'v', it means the bottom and
the top axes; in case of direction == 'h', it means the left and
the right axes.
h/v: the horizontal/vertical length of the small bar that appears between
the two break axes. 'h' for horizontal length and 'v' for vertical
length. Note they are always in unit of fractions of the BOTTOM/LEFT
axes.
"""
def get_axes_height(axes):
pos = axes.get_position()
return pos.bounds[3]
def get_axes_width(axes):
pos = axes.get_position()
return pos.bounds[2]
if direction in ['vertical','v']:
# hide the spines between ax and bottom_ax
top_ax.spines['bottom'].set_visible(False)
bottom_ax.spines['top'].set_visible(False)
top_ax.xaxis.tick_top()
bottom_ax.xaxis.tick_bottom()
top_ax.tick_params(labeltop='off') # don't put tick labels at the top
bottom_axheight = get_axes_height(bottom_ax)
top_axheight = get_axes_height(top_ax)
#plot for the top_ax
v1=v*bottom_axheight/top_axheight # as the v is given in unit of
# bottom_ax, we need to
# change into for the top_ax.
kwargs = dict(transform=top_ax.transAxes, color='k', clip_on=False)
top_ax.plot((-h,+h),(-v1,+v1), **kwargs) # top-left diagonal
top_ax.plot((1-h,1+h),(-v1,+v1), **kwargs) # top-right diagonal
#plot for the bottom_ax
kwargs.update(transform=bottom_ax.transAxes) # switch to the bottom axes
bottom_ax.plot((-h,+h),(1-v,1+v), **kwargs) # bottom-left diagonal
bottom_ax.plot((1-h,1+h),(1-v,1+v), **kwargs) # bottom-right diagonal
elif direction in ['horizontal','h']:
left_ax = bottom_ax
right_ax = top_ax
left_ax.spines['right'].set_visible(False)
right_ax.spines['left'].set_visible(False)
left_ax.yaxis.tick_left()
right_ax.yaxis.tick_right()
right_ax.tick_params(labelleft='off') # don't put tick labels at the top
left_axwidth = get_axes_width(left_ax)
right_axwidth = get_axes_width(right_ax)
#plot for the right_ax
h1=h*left_axwidth/right_axwidth # as the h is given in unit of
# left_ax, we need to
# change into for the right_ax.
kwargs = dict(transform=right_ax.transAxes, color='k', clip_on=False)
right_ax.plot((-h1,+h1),(-v,+v), **kwargs) # right-bottom diagonal
right_ax.plot((-h1,+h1),(1-v,1+v), **kwargs) # right-top diagonal
#plot for the left_ax
kwargs.update(transform=left_ax.transAxes) # switch to the left axes
left_ax.plot((1-h,1+h),(-v,+v), **kwargs) # left-bottom diagonal
left_ax.plot((1-h,1+h),(1-v,1+v), **kwargs) | bigcode/self-oss-instruct-sc2-concepts |
def islistoflists(arg):
"""Return True if item is a list of lists.
"""
claim = False
if isinstance(arg, list):
if isinstance(arg[0], list):
claim = True
return claim | bigcode/self-oss-instruct-sc2-concepts |
def date_to_str(ts):
"""
Convert timestamps into strings with format '%Y-%m-%d %H:%M:%S'.
Parameters
----------
ts : pd.timestamp
Timestamp.
Returns
-------
str
Strings with format '%Y-%m-%d %H:%M:%S'.
"""
return ts.strftime('%Y-%m-%d %H:%M:%S') | bigcode/self-oss-instruct-sc2-concepts |
def list_to_tuple(x):
""" Make tuples out of lists and sets to allow hashing """
if isinstance(x, list) or isinstance(x, set):
return tuple(x)
else:
return x | bigcode/self-oss-instruct-sc2-concepts |
import gzip
import pickle
import logging
def load_obj(filename):
"""
Load saved object from file
:param filename: The file to load
:return: the loaded object
"""
try:
with gzip.GzipFile(filename, 'rb') as f:
return pickle.load(f)
except OSError:
logging.getLogger().warning('Old, invalid or missing pickle in %s. Please regenerate this file.' % filename)
return None | bigcode/self-oss-instruct-sc2-concepts |
import base64
def b64urlencode(message):
"""
This function performs url safe base64 encoding.
:param message: Message to encode,
:return: Encoded string.
"""
return base64.urlsafe_b64encode(message) | bigcode/self-oss-instruct-sc2-concepts |
def lesser(tup,value):
"""
Returns the number of elements in tup strictly less than value
Examples:
lesser((5, 9, 1, 7), 6) returns 2
lesser((1, 2, 3), -1) returns 0
Parameter tup: the tuple to check
Precondition: tup is a non-empty tuple of ints
Parameter value: the value to compare to the tuple
Precondition: value is an int
"""
assert type(tup) == tuple, 'tup isnt a tuple'
assert len(tup) >= 1, 'tuple cant be empty'
assert type(value) == int, 'value isnt an int'
count = 0
for index in tup: # assigns index as a element in tup equiv to index = tup[:]?
if index < value:
count += 1
return count
# pass | bigcode/self-oss-instruct-sc2-concepts |
def problem_19_1(x, y):
""" Write a function to swap a number in place without temporary variables. """
# Bit-wise operations.
#x = x ^ y
#y = x ^ y
#x = x ^ y
#return (x, y)
# Arithmetic operations.
x = x - y
y = y + x
x = y - x
return (x, y) | bigcode/self-oss-instruct-sc2-concepts |
def generate_bs_pointers(bs_lengths, bs_size):
"""
It generates the pointers (i.e. time indexes) of each modified sax word into the original time-series data
:param bs_lengths: list of modified sax words
:type bs_lengths: list of str
:param bs_size: window size (in the original time-series) of a single sax word
:type bs_size: int
:return: list of pointers to the original time-series
:rtype: list of list of int
"""
bs_pointers = []
start_pointer = 0
for bs_len_item in bs_lengths:
end_pointer = start_pointer + bs_size + bs_len_item - 1
pointer_list = list(range(start_pointer, end_pointer))
bs_pointers.append(pointer_list)
start_pointer = start_pointer + bs_len_item
return bs_pointers | bigcode/self-oss-instruct-sc2-concepts |
def upper_first(text: str) -> str:
"""
Capitalizes the first letter of the text.
>>> upper_first(text='some text')
'Some text'
>>> upper_first(text='Some text')
'Some text'
>>> upper_first(text='')
''
>>> upper_first(text='_some text')
'_some text'
:param text: to be capitalized
:return: text with the first letter capitalized
"""
if len(text) == 0:
return ''
return text[0].upper() + text[1:] | bigcode/self-oss-instruct-sc2-concepts |
def parse(line):
"""Parses HH:MM:SS text -> (time,text)"""
parts = line.strip().split(" ")
return (parts[0], " ".join(parts[1:]) ) | bigcode/self-oss-instruct-sc2-concepts |
def last(mention):
""" Compute the last token of a mention.
Args:
mention (Mention): A mention.
Returns:
The tuple ('last', TOKEN), where TOKEN is the (lowercased) last token
of the mention.
"""
return "last", mention.attributes["tokens"][-1].lower() | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
from typing import Iterable
def elem(n: Any, it: Iterable[Any]) -> bool:
"""
Determine if iterable object contains the given element
Args:
n: Value to validate
it: Iterable object
Examples:
>>> fpsm.elem(2, range(10))
True
>>> fpsm.elem(1, range(2, 4))
False
"""
return n in list(it) | bigcode/self-oss-instruct-sc2-concepts |
def to_camel(string):
"""Convert a snake_case string to CamelCase"""
return "".join(word.capitalize() for word in string.split("_")) | bigcode/self-oss-instruct-sc2-concepts |
def get_temperature_number(temp_str):
"""
Given a temperature string of the form "48.8 °C", return the first number
(in this example, 48). Also handles strings of the form "48,8 °C" that
apparently can exist (at least when reading the response from a file)
:param temp_str: Temperature string
:return: Temperature number (in string form)
"""
if 'Â' in temp_str:
return temp_str[:-6]
else:
return temp_str[:-5] | bigcode/self-oss-instruct-sc2-concepts |
import re
def squish(text):
"""Turn any run of whitespace into one space."""
return re.sub(r"\s+", " ", text) | bigcode/self-oss-instruct-sc2-concepts |
def compute_union_of_regions( regions ):
"""Compute a non-overlapping set of regions covering the same position as the input regions.
Input is a list of lists or tuples [ [a1,b1], ... ]
Output is a similar list. All regions are assumed to be closed i.e. to contain their endpoints"""
result = []
regions = sorted( regions, key = lambda w: w[0] )
if len( regions ) == 0:
return result ;
current_region = regions[0]
for i in range(1, len(regions)):
current_endpoint = current_region[1]
if regions[i][0] <= current_endpoint+1:
current_region[1] = max( current_endpoint, regions[i][1] )
else:
result.append( current_region )
current_region = regions[i]
result.append( current_region )
return result | bigcode/self-oss-instruct-sc2-concepts |
def get_grid_coupling_list(width, height, directed=True):
"""Returns a coupling list for nearest neighbor (rectilinear grid) architecture.
Qubits are numbered in row-major order with 0 at the top left and
(width*height - 1) at the bottom right.
If directed is True, the coupling list includes both [a, b] and [b, a] for each edge.
"""
coupling_list = []
def _qubit_number(row, col):
return row * width + col
# horizontal edges
for row in range(height):
for col in range(width - 1):
coupling_list.append((_qubit_number(row, col), _qubit_number(row, col + 1)))
if directed:
coupling_list.append((_qubit_number(row, col + 1), _qubit_number(row, col)))
# vertical edges
for col in range(width):
for row in range(height - 1):
coupling_list.append((_qubit_number(row, col), _qubit_number(row + 1, col)))
if directed:
coupling_list.append((_qubit_number(row + 1, col), _qubit_number(row, col)))
return coupling_list | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def get_month_number(month):
"""
Get the month in numeric format or 'all'
Parameters
----------
month : int or str
Returns
-------
n_month : int or 'all'
Month in numeric format, or string 'all'
"""
if isinstance(month, str):
if month == 'current':
n_month = datetime.today().month
elif month == '':
n_month = 'all'
else:
if len(month) == 3:
n_month = datetime.strptime(month, '%b').month
else:
try:
n_month = datetime.strptime(month, '%B').month
except ValueError:
print('Wrong month: {0}'.format(month))
raise
elif isinstance(month, int):
if not (0 < month < 13):
raise ValueError('Wrong month: {0}'.format(month))
else:
n_month = month
else:
raise ValueError('Wrong month: {0}'.format(month))
return n_month | bigcode/self-oss-instruct-sc2-concepts |
def name_matches(texnode, names):
"""
Returns True if `texnode`'s name is on one of the names in `names`.
"""
if hasattr(texnode, 'name') and texnode.name in names:
return True
else:
return False | bigcode/self-oss-instruct-sc2-concepts |
async def absent(
hub,
ctx,
name,
zone_name,
resource_group,
record_type,
connection_auth=None,
**kwargs,
):
"""
.. versionadded:: 1.0.0
Ensure a record set does not exist in the DNS zone.
:param name:
Name of the record set.
:param zone_name:
Name of the DNS zone.
:param resource_group:
The resource group assigned to the DNS zone.
:param record_type:
The type of DNS record in this record set. Record sets of type SOA can be updated but not created
(they are created when the DNS zone is created). Possible values include: 'A', 'AAAA', 'CAA', 'CNAME',
'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
:param connection_auth:
A dict with subscription and authentication parameters to be used in connecting to the
Azure Resource Manager API.
Example usage:
.. code-block:: yaml
Ensure record set absent:
azurerm.dns.record_set.absent:
- name: test_set
- zone: test_zone
- resource_group: test_group
- record_type: test_type
"""
ret = {"name": name, "result": False, "comment": "", "changes": {}}
if not isinstance(connection_auth, dict):
if ctx["acct"]:
connection_auth = ctx["acct"]
else:
ret[
"comment"
] = "Connection information must be specified via acct or connection_auth dictionary!"
return ret
rec_set = await hub.exec.azurerm.dns.record_set.get(
ctx,
name,
zone_name,
resource_group,
record_type,
azurerm_log_level="info",
**connection_auth,
)
if "error" in rec_set:
ret["result"] = True
ret["comment"] = "Record set {0} was not found in zone {1}.".format(
name, zone_name
)
return ret
if ctx["test"]:
ret["comment"] = "Record set {0} would be deleted.".format(name)
ret["result"] = None
ret["changes"] = {
"old": rec_set,
"new": {},
}
return ret
deleted = await hub.exec.azurerm.dns.record_set.delete(
ctx, name, zone_name, resource_group, record_type, **connection_auth
)
if deleted:
ret["result"] = True
ret["comment"] = "Record set {0} has been deleted.".format(name)
ret["changes"] = {"old": rec_set, "new": {}}
return ret
ret["comment"] = "Failed to delete record set {0}!".format(name)
return ret | bigcode/self-oss-instruct-sc2-concepts |
import socket
import errno
def check_port_is_available(host, port):
"""Check if a given port it's available
Parameters
----------
host : str
port : int
Returns
-------
available : bool
"""
available = True
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind((host, port))
except socket.error as error:
if error.errno == errno.EADDRINUSE:
available = False
s.close()
return available | bigcode/self-oss-instruct-sc2-concepts |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.