seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def csv_to_set(x):
"""Convert a comma-separated list of strings to a set of strings."""
if not x:
return set()
else:
return set(x.split(",")) | bigcode/self-oss-instruct-sc2-concepts |
import re
def optimade_filter_conversion(filter_expr):
"""
Convert optimade filters to oqmdap formationenergy filters
Input:
:str : original filter expression
Output:
:str : converted filter expression
"""
filter_expr_out = filter_expr
# General conversion
filter_expr_... | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def isderivedclass(klass, parent):
"""
Test if klass is derived from a parent class.
Parameters:
klass A <class 'klass'> object.
parent Class type or string name of the parent class.
Returns
True or False.
"""
try:
name = parent.__name__
except AttributeError:
nam... | bigcode/self-oss-instruct-sc2-concepts |
def argmin(l):
"""
Get index of min element in list
"""
return min(zip(l, range(len(l))))[1] | bigcode/self-oss-instruct-sc2-concepts |
def date_range_overlap(start_1, end_1, start_2, end_2):
"""
Based on: https://stackoverflow.com/questions/9044084/efficient-date-range-overlap-calculation-in-python
"""
latest_start = max(start_1, start_2)
earliest_end = min(end_1, end_2)
delta = (earliest_end - latest_start).days + 1
return... | bigcode/self-oss-instruct-sc2-concepts |
def _maven_artifact(group, artifact, version, packaging = None, classifier = None, override_license_types = None, exclusions = None, neverlink = None):
"""
Generates the data map for a Maven artifact given the available information about its coordinates.
Args:
group: *Required* The Maven artifact c... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Type
from enum import Enum
def string_to_konan_enum(
enum_string: str,
enum_class: Type,
) -> Enum:
"""Create an enum object from enum_string.
If the enum_class does NOT have a corresponding enum_string, then return enum_class.Other
enum_class must include the Other type
:p... | bigcode/self-oss-instruct-sc2-concepts |
import bs4
def is_navigable_string(obj):
"""Is navigable string."""
return isinstance(obj, bs4.NavigableString) | bigcode/self-oss-instruct-sc2-concepts |
def core_result_type(selectable, s):
"""Given a SQLAlchemy Core selectable and a connection/session, get the
type constructor for the result row type."""
result_proxy = s.execute(selectable.limit(0))
return result_proxy._row_getter | bigcode/self-oss-instruct-sc2-concepts |
def f(x, y):
"""
Function that will be optimized
Parameters
----------
x : float
Value for parameter x.
y : float
Value for parameter x.
Returns
-------
float
Function value for f(x,y).
"""
if (x**2 + y**2) <= 2:
return (1-x)**2 + 100*((... | bigcode/self-oss-instruct-sc2-concepts |
import math
def normalize_weight(weight):
"""AS3 accepts ratios between 0 and 100 whereas Octavia
allows ratios in a range of 0 and 256, so we normalize
the Octavia value for AS3 consumption.
We also round up the result since we want avoid having a 0
(no traffic received at all) when setting a we... | bigcode/self-oss-instruct-sc2-concepts |
def sgi_1973_to_2016(sgi_id: str) -> str:
"""
Convert the slightly different SGI1973 to the SGI2016 id format.
:examples:
>>> sgi_1973_to_2016("B55")
'B55'
>>> sgi_1973_to_2016("B55-19")
'B55-19'
>>> sgi_1973_to_2016("E73-2")
'E73-02'
"""
if "-" n... | bigcode/self-oss-instruct-sc2-concepts |
def valid_user_input(ui: str) -> bool:
"""Determines if the passed string is a valid RPS choice."""
if ui == "rock" or ui == "paper" or ui == "scissors":
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def filter_data(data, condition):
"""
Remove elements that do not match the condition provided.
Takes a data list as input and returns a filtered list.
Conditions should be a list of strings of the following format:
'<field> <op> <value>'
where the following operations are valid: >, <, >=, <=,... | bigcode/self-oss-instruct-sc2-concepts |
def vec_neg(a):
"""
Negates a vector element-wise
Parameters
----------
a: list[]
A vector of scalar values
Returns
-------
list[]
The negated vector of a
"""
# return [-a[n] for n in range(len(a))]
return [*map(lambda ai: -ai, a)] | bigcode/self-oss-instruct-sc2-concepts |
def SumString(table : list) -> str:
"""
Connects all the strings in the list to a single string, optimal for the output of JLua.GetLuaString()
:param table: A string list like generated by readlines() or GetLuaString()
:return: The Connected string
"""
sumstring = ""
for string in table: su... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
from typing import Mapping
from typing import Collection
def is_arraylike(obj: Any) -> bool:
"""Determine if the provided object is an non-mapping generic container type such as an array,\
tuple or set.
Example:
>>> from collectionish.utils import is_arraylike
>>>
... | bigcode/self-oss-instruct-sc2-concepts |
def paint_text(text_str, color_str):
"""
Adds markup around given text.
Supports some colors by name instead of hexadecimal.
:param text_str:
:param color_str: (str) Hexadecimal color.
:return: (str)
"""
return '[color={color_str}]{text_str}[/color]'.format(text_str=text_str,
... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def get_files_under_dir(root, pattern):
"""Construct list of path objects given pattern under the root directory.
"""
root = Path(root)
if root.exists():
return [p for p in root.glob(pattern) if p.is_file()]
else:
raise FileNotFoundError(f"Direcotry {root}... | bigcode/self-oss-instruct-sc2-concepts |
def compute_r_parameter(ago_susceptible: int, current_susceptible: int, current_infected: int) -> float:
"""
Function for compute infection ratio parameter based od SIR model.
Parameters
----------
ago_susceptible: int, required
Amount of susceptible people one interval before current itera... | bigcode/self-oss-instruct-sc2-concepts |
def rotate_right(x, y):
"""
Left rotates a list x by the number of steps specified
in y.
Examples:
>>> from sympy.utilities.iterables import rotate_right
>>> a = [0, 1, 2]
>>> rotate_right(a, 1)
[2, 0, 1]
"""
if len(x) == 0:
return x
y = len(x) - y % len(x)
retur... | bigcode/self-oss-instruct-sc2-concepts |
import difflib
def difflib_overlap(word_token1: list, word_token2: list) -> float:
""" Get similarity percentage from matching sequences between two strings """
seq = difflib.SequenceMatcher(a=word_token1, b=word_token2)
# Return similarity percentage based on difflib library Sequence Matcher
return... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
from typing import Callable
def find_nonmatching_fields(item: Any, match_fn: Callable[[Any], bool], *fields):
"""Check that the given fields of an object match the output of a function.
:param item: Any object with attributes to check.
:param match_fn: A callable function. Each att... | bigcode/self-oss-instruct-sc2-concepts |
def get_node_labels(session):
"""Returns all node labels in use in the database."""
result = session.run("MATCH (n) RETURN DISTINCT labels(n) as label")
labels = []
for record in result:
labels.append(record.get("label")[0])
return labels | bigcode/self-oss-instruct-sc2-concepts |
def _XYDict(x_value, y_value, first='x', second='y'):
"""Take in x and y coordinates and return in dictionary form.
Args:
x_value: The value of the x coordinate.
y_value: The value of the y coordinate.
first: The key for first field.
second: The key for second field.
Returns:
A dict with a x... | bigcode/self-oss-instruct-sc2-concepts |
import json
def load_config(config_filepath):
"""
Using a json file with the master configuration (config file for each part of the pipeline),
return a dictionary containing the entire configuration settings in a hierarchical fashion.
"""
with open(config_filepath) as cnfg:
config = json.... | bigcode/self-oss-instruct-sc2-concepts |
def find_nearest_datapoint(lat, lon, ds):
"""Find the point in the dataset closest to the given latitude and longitude"""
datapoint_lats = ds.coords.indexes["latitude"]
datapoint_lons = ds.coords.indexes["longitude"]
lat_nearest = min(datapoint_lats, key=lambda x: abs(x - lat))
lon_nearest = min(dat... | bigcode/self-oss-instruct-sc2-concepts |
def ignore_files(files, ignore):
"""Ignore files based on a search term of interest.
Parameters
----------
files : list of str
File list.
ignore : str
String to use to drop files from list.
Returns
-------
list of str
File list with ignored files dropped.
""... | bigcode/self-oss-instruct-sc2-concepts |
def BoxLength(box):
"""Returns the box length given the box coordinates."""
return box[1::2] - box[0::2] | bigcode/self-oss-instruct-sc2-concepts |
def get_analyze_query(graph_name):
"""Format an ANALYZE query with the name of the inserted RDF graph."""
return f"ANALYZE {graph_name}" | bigcode/self-oss-instruct-sc2-concepts |
def validate(observation):
"""Make sure the observation table is valid, or raise an error."""
if observation is not None and type(observation) == dict:
return observation
elif type(observation) == list:
return observation
else:
raise RuntimeError('Must return dictionary from act(... | bigcode/self-oss-instruct-sc2-concepts |
from functools import reduce
import operator
def product(values, base=1):
"""Get the product of the given values.
:param values: An iterable of values to be multiplied.
:param base: Applied to the beginning of the calculation.
:type base: int
"""
return reduce(operator.mul, values, base) | bigcode/self-oss-instruct-sc2-concepts |
def get_name_from_kwarg(var):
"""
Given some kwarg name, return the original variable name.
:param var: A string with a (internal) kwarg name
:return: The original variable name
"""
return var.replace('#kwarg_', '') | bigcode/self-oss-instruct-sc2-concepts |
def get_appendix_data(df, table):
"""
Given Appendix A DataFrame df and table name,
return Sequence, Start, and End numbers as lists.
"""
df = df[df['name'] == table]
return df['seq'].tolist(), df['start'].tolist(), df['end'].tolist() | bigcode/self-oss-instruct-sc2-concepts |
def is_nonzero(delta):
"""Return True if any element of 2D list is nonzero."""
nonzero = False
for row in delta:
for element in row:
if element != 0:
nonzero = True
return nonzero | bigcode/self-oss-instruct-sc2-concepts |
def parse_tags(tags):
"""
>>> parse_tags('writing')
'writing'
>>> parse_tags(['news', 'steemit', 3, {'5': {}, '3': {}, '1': {}}, {'39': {}, '45': {}, '11': {}}, {}, 'esteem'])
['news', 'steemit', 'esteem']
>>> parse_tags(['dlive', 'dlive-broadcast', 'game', 'DLIVEGAMING'])
['dlive', 'dliv... | bigcode/self-oss-instruct-sc2-concepts |
import re
def account_token(doc):
"""Flag user accounts with custom .is_account attribute"""
pattern = re.compile(r"@\w+")
for token in doc:
if bool(re.match(pattern, token.text)):
token._.is_account = True
return doc | bigcode/self-oss-instruct-sc2-concepts |
import warnings
def check_model(model: str) -> str:
"""Check model is 'aces' or 'btsettl'.
Parameters
----------
model: str
Model name. Should be either 'aces' or 'btsettl'.
Returns
-------
model: str
Valid model output; either 'aces' or 'btsettl'.
"""
if model == "ph... | bigcode/self-oss-instruct-sc2-concepts |
def rstrip_special(line, JUNK="\n \t"):
"""
Returns the given line stripped of specific trailing characters
(spaces, tabs, and newlines by default).
Note that line.rstrip() would also strip sundry control characters,
the loss of which can interfere with Emacs editing, for one thing.
(Used by t... | bigcode/self-oss-instruct-sc2-concepts |
import re
from pathlib import Path
def get_bibtex(filename):
""" Tries to extract a bibtex key from a filename and returns it.
If no bibtex key is found the function returns the filename (without suffix). """
bibtex = re.match(r'^[a-zA-Z]*\d{4}[a-z]?', Path(filename).stem)
if bibtex:
bibt... | bigcode/self-oss-instruct-sc2-concepts |
def requirements_file_to_list(fn="requirements.txt"):
"""read a requirements file and create a list that can be used in setup.
"""
with open(fn, 'r') as f:
return [x.rstrip() for x in list(f) if x and not x.startswith('#')] | bigcode/self-oss-instruct-sc2-concepts |
def resolve_aliases(kwargs, aliases):
"""Check and resolve to a standard label for any potential aliases.
Parameters
----------
kwargs : dict
Dictionary of labels and their values.
aliases : dict
Dictionary of label names and their list of aliases.
Returns
-------
out_k... | bigcode/self-oss-instruct-sc2-concepts |
import re
def rename_state_keys(state, keys_regex, replacement):
"""Rename keys from state that match a regex; replacement can use capture groups"""
regex = re.compile(keys_regex)
return {
(k if not regex.findall(k) else regex.sub(replacement, k)): v
for k, v in state.items()
} | bigcode/self-oss-instruct-sc2-concepts |
def hsv_to_rgb(h, s, v):
"""Converts HSV value to RGB values
Hue is in range 0-359 (degrees), value/saturation are in range 0-1 (float)
Direct implementation of:
http://en.wikipedia.org/wiki/HSL_and_HSV#Conversion_from_HSV_to_RGB
"""
h, s, v = [float(x) for x in (h, s, v)]
hi = (h / 60) % ... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
def check_class_number(class_number: str) -> Tuple[bool, str]:
""" Check class number"""
if int(class_number) < 1 or int(class_number) > 18:
return False, "Le numéro de classe doit être compris entre 1 et 18"
return True, "" | bigcode/self-oss-instruct-sc2-concepts |
def pad(string, max_len):
"""
add some leading spaces to string to bring it up to max_len.
"""
string = str(string)
return " "*(max_len - len(string)) + string | bigcode/self-oss-instruct-sc2-concepts |
def get_coverage_of_namespace(assembly, covered_lines, name_space, total_lines):
"""Get the coverage of a namespace."""
assembly_name = assembly["@Name"]
assembly_covered_lines = assembly["@CoveredStatements"]
assembly_total_lines = assembly["@TotalStatements"]
if assembly_name.startswith(name_spac... | bigcode/self-oss-instruct-sc2-concepts |
def has_next_page(json_data):
"""Check for more labels."""
page_info = json_data.get("data").get(
"repository").get("labels").get("pageInfo")
if page_info.get("hasNextPage"):
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def get_grid_coordinates(imgnum,gridsize,w,h):
""" given an image number in our sprite, map the coordinates to it in X,Y,W,H format"""
y = (imgnum - 1)/gridsize
x = (imgnum -1) - (y * gridsize)
imgx = x * w
imgy =y * h
return "%s,%s,%s,%s" % (imgx,imgy,w,h) | bigcode/self-oss-instruct-sc2-concepts |
def trans_attr(attr, lang):
"""
Returns the name of the translated attribute of the object <attribute>_<lang_iso_code>.
For example: name_es (name attribute in Spanish)
@param attr Attribute whose name will form the name translated attribute.
@param lang ISO Language code that will be the suffix of the translated ... | bigcode/self-oss-instruct-sc2-concepts |
import time
def time_fn(lbd):
"""
Times an expression.
If you need to time the operation:
result = heavy_function()
Then just write:
result = time_fn(lambda : heavy_function())
"""
start = time.time()
res = lbd()
end = time.time()
print("TIME: %... | bigcode/self-oss-instruct-sc2-concepts |
def begin(stacklogger):
"""Log the default begin message"""
return stacklogger.log() | bigcode/self-oss-instruct-sc2-concepts |
import struct
def int2bytes(i):
"""
Convert int to bytes.
:param i: 32 bit integer inside range -2147483648, 2147483647
:return: 4 bytes
"""
if not isinstance(i, int):
raise TypeError("i must be int")
return struct.pack("i", i) | bigcode/self-oss-instruct-sc2-concepts |
def build_speechlet_response(output, card_title=None, card_content=None, reprompt='',
should_end_session=True):
"""
Contructs ``response`` dictionary with the proper struture to allow
Alexa to talk to the user. Optionally takes ``card_title`` and
``card_content`` to build ou... | bigcode/self-oss-instruct-sc2-concepts |
def format_number(num: float) -> str:
"""
Format strings at limited precision
:param num: anything that can print as a float.
:return: str
I've read articles that recommend no more than four digits before and two digits
after the decimal point to ensure good svg rendering. I'm being generous a... | bigcode/self-oss-instruct-sc2-concepts |
def get_attribute_values(elements,name):
""" returns a list of attributes 'name' from a list of elements """
attribute_values = []
for element in elements:
attributes = element.attributes
for n in range(attributes.length):
attribute = attributes.item(n)
if attribute.n... | bigcode/self-oss-instruct-sc2-concepts |
def _get_request(context):
"""
Fetch the request from the context.
This enforces the use of the template :class:`~django.template.RequestContext`,
and provides meaningful errors if this is omitted.
"""
assert 'request' in context, "The fluent_pages_tags library requires a 'request' object in the... | bigcode/self-oss-instruct-sc2-concepts |
def vals_are_multiples(num, vals, digits=4):
"""decide whether every value in 'vals' is a multiple of 'num'
(vals can be a single float or a list of them)
Note, 'digits' can be used to specify the number of digits of accuracy
in the test to see if a ratio is integral. For example:
... | bigcode/self-oss-instruct-sc2-concepts |
def parse_callback(callback, reduce=True):
"""
Parses callbacks for CellRenderers: it splits the
callback from its arguments if present. Additionally this method will
not create singleton argument lists, but pass them as a single argument.
Returns the callback and its argu... | bigcode/self-oss-instruct-sc2-concepts |
def _ComputeIpv4NumHosts(network_size):
"""Derives the number of hosts in an IPv4 network from the size.
"""
return 2 ** (32 - network_size) | bigcode/self-oss-instruct-sc2-concepts |
def linear(u, v, d):
"""
Linear interpolation.
Args:
u (float)
v (float)
d (float): the relative distance between the two to return.
Returns:
float. The interpolated value.
"""
return u + d*(v-u) | bigcode/self-oss-instruct-sc2-concepts |
import pickle
def read_pickle(filename):
""" Function that reads pickled data and returns it in memory
INPUTS:
filename (str): name of pickle file to be read
OUTPUTS:
unserialized_data (?): data read from pickle file, can be nearly any form
"""
with open(filename, 'rb') as handle:
unserialized_data ... | bigcode/self-oss-instruct-sc2-concepts |
def str_to_bytes(string):
"""Encode a string in bytes."""
return string.encode("utf-8") | bigcode/self-oss-instruct-sc2-concepts |
def in_polygon(x, y, vertices):
"""
Determine if a point (x,y) is inside a polygon with given vertices
Ref: https://www.eecs.umich.edu/courses/eecs380/HANDOUTS/PROJ2/InsidePoly.html
"""
n_pts = len(vertices)
i = 0
j = n_pts - 1
c = False
while i < n_pts:
if (
# ... | bigcode/self-oss-instruct-sc2-concepts |
import base64
def bytes_to_b64str(data_bytes) -> str:
"""Convert binary to base64-encoded string."""
encoded_bytes = base64.b64encode(data_bytes)
return encoded_bytes.decode("ascii") | bigcode/self-oss-instruct-sc2-concepts |
def prepare(data):
"""Restructure/prepare data about merges for output."""
sha = data.get("sha")
commit = data.get("commit")
message = commit.get("message")
tree = commit.get("tree")
tree_sha = tree.get("sha")
return {"message": message, "sha": sha, "tree": {"sha": tree_sha}} | bigcode/self-oss-instruct-sc2-concepts |
def lin_func_2(pars, xvals):
"""Return quadratic function of the form pars[0]*x + pars[1]*x*x"""
return pars[0]*xvals + pars[1]*xvals*xvals | bigcode/self-oss-instruct-sc2-concepts |
import random
def random_bdays(n):
"""
Returns a list of integers between 1 and 365, with length (n)
"""
t = []
for i in range(n):
bday = random.randint(1, 365)
t.append(bday)
return t | bigcode/self-oss-instruct-sc2-concepts |
def get_category(output, categories):
"""
Return the most probable category/language
from output tensor.
"""
top_n, top_i = output.data.topk(1)
category_i = top_i[0][0]
return categories[category_i], category_i | bigcode/self-oss-instruct-sc2-concepts |
def len_str_list(lis):
"""returns sum of lengths of strings in list()"""
res = 0
for x in lis:
res += len(x)
return res | bigcode/self-oss-instruct-sc2-concepts |
def safe_get_key(dictionary, keys, default):
"""
Examples
--------
>>> d = dict(a=2, b=2, c=dict(d=12, e=45, f=dict(g=32)))
>>> safe_get_key(d, 'a', 1)
2
>>> safe_get_key(d, ['a'], 1)
2
>>> safe_get_key(d, ['asdf'], 1)
1
>>> safe_get_key(d, ['c', 'f', 'g'], 1)
32
>>> ... | bigcode/self-oss-instruct-sc2-concepts |
def create_partitions(aut, partition_list, state_function, obs_events):
"""
Compute the fixed point of the partioning.
@param aut: Automaton being partioned.
@type aut: L{BaseAutomaton}
@param partition_list: Initial state partitions.
@type partition_list: C{list} of C{set} of L{State}
... | bigcode/self-oss-instruct-sc2-concepts |
def _denormalize_to_coco_bbox(bbox, height, width):
"""Denormalize bounding box.
Args:
bbox: numpy.array[float]. Normalized bounding box. Format: ['ymin', 'xmin',
'ymax', 'xmax'].
height: int. image height.
width: int. image width.
Returns:
[x, y, width, height]
"""
y1, x1, y2, x2 = bb... | bigcode/self-oss-instruct-sc2-concepts |
def health() -> dict:
"""Health Check for the server.
Returns:
dict:
Health status in a dictionary.
"""
return {'Message': 'Healthy'} | bigcode/self-oss-instruct-sc2-concepts |
def _parse_redis_connection(connection):
"""
Parse redis connection to host, db
:param connection: redis connection
:return: host, db
"""
connection_kwargs = connection.connection_pool.connection_kwargs
return (
connection_kwargs.get('host', 'local'),
connection_kwargs.get('p... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Iterable
from typing import List
def _fmt(a: Iterable) -> List[str]:
"""Formats each element in `a` into strings.
Args:
a (Iterable): Iterable.
Returns:
List[str]: Returns a list with the formatted elements.
"""
return list(map(lambda a: f'{a:.3f}', a)) | bigcode/self-oss-instruct-sc2-concepts |
def subset_data(data, col):
"""
Creates list of categories for column used to populate
dropdown menus
:param data: pd.DataFrame
generated from app_wrangling.call_boardgame_data()
:param col: string, column generate list for
:return list(exp_series.unique()): list of strings
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def lines_to_list(infile):
""" put all words in a file into a list """
nested_list = [line.split() for line in infile]
# nested_list = []
# for line in infile:
# nested_list.append(line.split())
flat_list = [item for inner_list in nested_list for item in inner_list]
# flat_list = []
... | bigcode/self-oss-instruct-sc2-concepts |
def _1(value):
"""
Integer decoder.
```python
>>> from Tyf import decoders
>>> decoders._1((1, ))
1
>>> decoders._1((1.0, "6", 0b111))
(1, 6, 7)
```
"""
return int(value[0]) if len(value) == 1 else tuple(int(v) for v in value) | bigcode/self-oss-instruct-sc2-concepts |
import re
def normalize_newlines(string):
"""Adjust all line endings to be the Linux line break, \\x0a."""
return re.compile("\x0d\x0a|\x0d").sub("\x0a", string) | bigcode/self-oss-instruct-sc2-concepts |
def parse_years(year_range):
"""Parse year_range into year list.
Args:
year_range: A string in the format aaaa-bbbb.
Returns:
A list of years from aaaa to bbbb, including both ends.
"""
st, ed = year_range.split("-")
st, ed = int(st), int(ed)
return [year for year in range(st... | bigcode/self-oss-instruct-sc2-concepts |
def kebab_to_snake(name: str) -> str:
"""Convert `name` from kebab-case to snake_case."""
return name.replace("-", "_").lower() | bigcode/self-oss-instruct-sc2-concepts |
def tail1(filepath, n):
"""Similate Unix' tail -n, read in filepath, parse it into a list,
strip newlines and return a list of the last n lines"""
with open(filepath) as f:
return [line.strip() for line in f.readlines()[-n:]] | bigcode/self-oss-instruct-sc2-concepts |
def is_a(x, n=None):
"""
Check whether a list is a non-decreasing parking function.
If a size `n` is specified, checks if a list is a non-decreasing
parking function of size `n`.
TESTS::
sage: from sage.combinat.non_decreasing_parking_function import is_a
sage: is_a([1,1,2])
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
def bytes_to_string(obj: Any):
"""
Converts a bytes object into a string
:param obj: Any type of object
:return: If the object is of type bytes it returns it's string representation, else returns
the object itself
"""
if isinstance(obj, bytes):
return obj.dec... | bigcode/self-oss-instruct-sc2-concepts |
import functools
def accumulate(
items,
func=lambda x, y: x + y):
"""
Cumulatively apply the specified function to the elements of the list.
Args:
items (iterable): The items to process.
func (callable): func(x,y) -> z
The function applied cumulatively to the f... | bigcode/self-oss-instruct-sc2-concepts |
def _center_to_coco_bbox(bbox):
"""
from center format
to (tlx, tly, w, h)
:param bbox:
:return:
"""
tlx = bbox[0] - bbox[2] / 2
tly = bbox[1] - bbox[3] / 2
return [(tlx), (tly), (bbox[2]), (bbox[3])] | bigcode/self-oss-instruct-sc2-concepts |
def capitalize_header(key):
""" Returns a capitalized version of the header line such as
'content-type' -> 'Content-Type'.
"""
return "-".join([
item if item[0].isupper() else item[0].upper() + item[1:]
for item in key.split("-")
]) | bigcode/self-oss-instruct-sc2-concepts |
def complement_strand(dna):
"""
Finds the reverse complement of a dna.
Args:
dna (str): DNA string (whose alphabet contains the symbols 'A', 'C', 'G', and 'T').
Returns:
str: the reverse complement string of a dna.
"""
reverse_complement = ""
for character in dna[::-1]:
... | bigcode/self-oss-instruct-sc2-concepts |
def get_grouping_from_another_yang_model(yang_model_name: str,
conf_mgmt) -> list:
""" Get the YANG 'grouping' entity
Args:
yang_model_name - YANG model to search
conf_mgmt - reference to ConfigMgmt class instance,
it have yJs... | bigcode/self-oss-instruct-sc2-concepts |
def create_device_name(tracked_asset_pair: str) -> str:
"""Create the device name for a given tracked asset pair."""
return f"{tracked_asset_pair.split('/')[0]} {tracked_asset_pair.split('/')[1]}" | bigcode/self-oss-instruct-sc2-concepts |
def to_std_dicts(value):
"""Convert nested ordered dicts to normal dicts for better comparison."""
if isinstance(value, dict):
return {k: to_std_dicts(v) for k, v in value.items()}
elif isinstance(value, list):
return [to_std_dicts(v) for v in value]
else:
return value | bigcode/self-oss-instruct-sc2-concepts |
def process_param(param, offset):
"""Process a single parameter produced by `get_function_parameter_names`."""
# Ignore args with default values, since Rope considers them assignments.
if "=" in param:
return []
# Strip off any type annotation.
first_colon_index = param.find(":")
if fir... | bigcode/self-oss-instruct-sc2-concepts |
def reformat_replace_star_list_with_dash_list(text):
"""
Replaces bullet lists starting with `*` with the lists starting with `-`
:param text: Original text
:return: New text without `*` bullet lists
"""
lines = text.split('\n')
new_text = ''
for line in lines:
if line.strip().s... | bigcode/self-oss-instruct-sc2-concepts |
def ec_list(mod):
"""
Retuns a list of elasticity coefficients of a model.
The list contains both species and parameter elasticity coefficients and
elasticity coefficients follow the syntax of 'ec_reaction_sp-or-param'.
Parameters
----------
mod : PysMod
The Pysces model contains t... | bigcode/self-oss-instruct-sc2-concepts |
def get_spec_padding(ispec, nspec, bundlesize):
"""
Calculate padding needed for boundary spectra
Args:
ispec: starting spectrum index
nspec: number of spectra to extract (not including padding)
bundlesize: size of fiber bundles; padding not needed on their edges
returns specmi... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Any
def remove_unused_flags(user_calc_params: Dict[str, Any]) -> Dict[str, Any]:
"""
Removes unused flags in the INCAR, like EDIFFG if you are doing NSW = 0.
Parameters
----------
user_calc_params
User-specified calculation parameters
Return... | bigcode/self-oss-instruct-sc2-concepts |
def bBalancedPar(p):
"""check if parenthesis are balanced no matter the content"""
l = 0
for c in p:
if c == ord(b"("):
l += 1
elif c == ord(b")"):
l -= 1
if l < 0:
return False
if l != 0:
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
def unary_plus(op):
""":yaql:operator unary +
Returns +op.
:signature: +op
:arg op: operand
:argType op: number
:returnType: number
.. code::
yaql> +2
2
"""
return +op | bigcode/self-oss-instruct-sc2-concepts |
from typing import Mapping
def delimited_file_to_dict(path : str,
delimiter : str=',') -> Mapping[str,str]:
"""
Returns a dictionary populated by lines from a file where
the first delimited element of each line is the key and
the second delimited element is the value.
... | 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.