seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def _compute_ANN_row(tree, x):
"""
For a given survival tree and a feature vector, traverse down the tree to
find the feature vector's adaptive nearest neighbors.
Parameters
----------
tree : dictionary
Tree node of a decision tree. We traverse down the tree taking branches
that... | bigcode/self-oss-instruct-sc2-concepts |
def text_mention(text_content):
"""
处理微博正文中的用户@
:param text_content: 处理对象文本
:return: 是否含有@(1:有,0:无),@数量
"""
mention_nums = text_content.count("@")
if(mention_nums > 0):
return 1,mention_nums
else:
return 0,0 | bigcode/self-oss-instruct-sc2-concepts |
def classname(cls):
"""Return the full qualified name of a class"""
mod = cls.__module__
return cls.__name__ if mod is None else f"{mod}.{cls.__name__}" | bigcode/self-oss-instruct-sc2-concepts |
def overlap(a1, a2):
"""
Check if the given arrays have common elements
"""
return len(set(a1).intersection(set(a2))) > 0 | bigcode/self-oss-instruct-sc2-concepts |
def transpose(matrix):
"""return the transpose of a matrix stored as a 9-element tuple"""
return (matrix[0], matrix[3], matrix[6],
matrix[1], matrix[4], matrix[7],
matrix[2], matrix[5], matrix[8]) | bigcode/self-oss-instruct-sc2-concepts |
def propagate_taxids(res, ranks):
"""
Transfer taxonomy ids to unassigned ranks based on best known taxonomy
Example:
{'species': -1, 'family': -171549, 'genus': -171549, 'order': 171549, 'phylum': 976, 'class': 200643, 'superkingdom': 2}
should become
{'species': -171549, 'family': -171549, '... | bigcode/self-oss-instruct-sc2-concepts |
def flat_clfs(params) -> dict:
"""Flatten the classifiers for easier access."""
flat = {}
for clfs in params["classifiers"].values():
flat.update(clfs)
return flat | bigcode/self-oss-instruct-sc2-concepts |
def getStringForVariables(variables, wordsize):
"""
Takes as input the variable name, number of variables and the wordsize
and constructs for instance a string of the form:
x00, x01, ..., x30: BITVECTOR(wordsize);
"""
command = ""
for var in variables:
command += var + ","
comma... | bigcode/self-oss-instruct-sc2-concepts |
import json
def get_predictions(file):
"""
Returns prediction_list (class probabilities) and predicted_final_classes
:param file: file produced by save_json()
:return: prediction_list (class probabilities) and predicted_final_classes
"""
with open(file) as json_file:
data = json.load(j... | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def get_num_args(f):
"""
Find the number of arguments a function or method takes (excluding ``self``).
"""
if inspect.ismethod(f):
return f.__func__.__code__.co_argcount - 1
elif inspect.isfunction(f):
return f.__code__.co_argcount
else:
raise TypeError("... | bigcode/self-oss-instruct-sc2-concepts |
def getBiggestArea(freePlaceValues, place=1):
"""
Returns the biggest requested area from the freeMap.
If place is 1, the biggest will be returned
If place is 2, the second biggest will be returned
Etc
:param freePlaceValues: Whole map with free places
:param place: x biggest area (1./2./3./... | bigcode/self-oss-instruct-sc2-concepts |
def red(x):
"""Format a string red.
Returns:
The string `x` made red by terminal escape sequence.
"""
return f"\033[31m{x}\033[0m" | bigcode/self-oss-instruct-sc2-concepts |
def raster_ds_shape(raster_ds):
"""Return the number of rows and columns in an opened raster dataset
Args:
raster_ds: opened raster dataset
Returns:
tuple of raster rows and columns
"""
return raster_ds.RasterYSize, raster_ds.RasterXSize | bigcode/self-oss-instruct-sc2-concepts |
def get_ethertype_value(ethertype):
"""Convert string representation of ethertype to the numerical."""
if ethertype is None:
return None
mapping = {
'ipv4': 0x0800,
'ipv6': 0x86DD,
'arp': 0x806
}
return mapping.get(ethertype.lower()) | bigcode/self-oss-instruct-sc2-concepts |
import random
def rand_suffix(length=7):
"""Generate a random suffix of `length` chars"""
charset = '0123456789abcdefghijklmnopqrstuvwxyz'
return ''.join(random.choice(charset) for i in range(length)) | bigcode/self-oss-instruct-sc2-concepts |
def rename_columns_with_data_schema(dfx, data_schema):
"""
Renaming columns based on a specified data schema
:param dfx (dataframe): df with the columns that will be cleaned
:param data_schema (dictionary): data schema containing the clean column names
:return dfx (dataframe): df after renaming the... | bigcode/self-oss-instruct-sc2-concepts |
def default_wd_filter(x):
"""default weight decay filter."""
parameter_name = x.name
if parameter_name.endswith('.bias'):
# all bias not using weight decay
return False
if parameter_name.endswith('.gamma'):
# bn weight bias not using weight decay, be carefully for now x not inclu... | bigcode/self-oss-instruct-sc2-concepts |
def get_row_coords(horiz_line_coords):
"""Get top-left and bottom-right coordinates for each row from a list of horizontal lines"""
row_coords = []
for i in range(1, len(horiz_line_coords)):
if horiz_line_coords[i][1] - horiz_line_coords[i-1][3] > 1:
row_coords.append((horiz_line_coords[... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
from typing import List
def ensure_list(item: Any) -> List:
"""Ensure string is converted to a Path.
Args:
item (Any): Anything.
Returns:
The item inside a list if it is not already a list.
"""
if not isinstance(item, list):
item = [item]
return... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def join_analysis_path(data_path: Path, analysis_id: str, sample_id: str) -> Path:
"""
Returns the path to an analysis JSON output file.
:param data_path: the application data path
:param analysis_id: the id of the NuVs analysis
:param sample_id: the id of the parent samp... | bigcode/self-oss-instruct-sc2-concepts |
def get_value(deep_dict, path):
"""Return deep_dict[path[0]][path[1]..."""
value = deep_dict
for key in path:
value = value[key]
return value | bigcode/self-oss-instruct-sc2-concepts |
def is_draft(catalog_record):
"""
Is the catalog record a draft or not.
Args:
catalog_record (dict): A catalog record
Returns:
bool: True if record is a draft
"""
if catalog_record.get('state') == 'draft':
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def full_rb_decay(A, B, C, lambda_1, lambda_2, m):
"""Eq. (15) of Wood Gambetta 2018."""
return A + B * lambda_1 ** m + C * lambda_2 ** m | bigcode/self-oss-instruct-sc2-concepts |
def translate_list(dictionary, list_to_be_translated):
"""For a given list with entries and a dictionary, it return a new list
with the translated entries"""
translated = []
for i in list_to_be_translated:
translated.append(dictionary[i])
return translated | bigcode/self-oss-instruct-sc2-concepts |
def get_message_id(timestamp, topic):
"""Unify the way to get a unique identifier for the given message"""
return '{}{}'.format(timestamp, topic.replace('/', '_')) | bigcode/self-oss-instruct-sc2-concepts |
import networkx as nx
import pickle
import codecs
def plot_aces_conversion_graph(graph, filename, prog="dot", args=""):
"""
Plot given *aces-dev* conversion graph using
`Graphviz <https://www.graphviz.org/>`__ and
`pyraphviz <https://pygraphviz.github.io>`__.
Parameters
----------
graph :... | bigcode/self-oss-instruct-sc2-concepts |
def perform_group_by(h2oFrame, na):
"""
Given a H2OFrame h2oFrame, and the na treatment, perform chained group by aggregation and return the
results of aggregations in an H2OFrame.
:param h2oFrame:
:param na:
:return:
"""
grouped = h2oFrame.group_by("class")
grouped.count(na=na).min... | bigcode/self-oss-instruct-sc2-concepts |
def get_requirements(path):
""" Import user's requirement file and save as a variable """
user_requirements_list = []
with open(path, 'r') as filehandler:
user_requirements_list = [package_name.rstrip() for package_name in filehandler.readlines()]
return user_requirements_list | bigcode/self-oss-instruct-sc2-concepts |
def _CreateExceptionRetryHandler(exception):
"""Returns a retry handler for given exception(s).
Please see WithRetry class document for details.
"""
if not (isinstance(exception, type) and issubclass(exception, Exception) or
(isinstance(exception, tuple) and
all(issubclass(e, Exception) fo... | bigcode/self-oss-instruct-sc2-concepts |
def land(*fns):
"""
Functionally logical ands the given functions.
>>> lor(starts_with('123'), ends_with('asd'))('123asd')
True
>>> land(starts_with('123'), ends_with('asd'))('asd')
False
>>> land(starts_with('123'), ends_with('asd'))('123')
False
:param fns: Functions to and
:... | bigcode/self-oss-instruct-sc2-concepts |
def p_w_from_rh_p_and_ws(rh, p_ws):
"""
Calculate water vapor pressure from relative humidity and water vapor saturation pressure
Eq(6) in "CHAPTER 6 - PSYCHROMETRICS" in "2001 ASHRAE Fundamentals Handbook (SI)"
:param rh: relative humidity [-]
:type rh: double
:param p_ws: water vapor saturati... | bigcode/self-oss-instruct-sc2-concepts |
def getUser(ctx, *arg):
"""
returns a user id from either the arguments or if None is passed the sender
"""
if arg == (): # if no argument is passed go with sender
return(ctx.author.id)
else:
return(arg[0].strip('<!@> ')) | bigcode/self-oss-instruct-sc2-concepts |
def entuple(x,n=2):
"""
Make sure given value is a tuple. It is useful, for example, when you want to provide dimentions of an image either
as a tuple, or as an int - in which case you can use `(w,h) = entuple(x)`.
:param x: Either atomic value or a tuple. If the value is atomic, it is converted to a tu... | bigcode/self-oss-instruct-sc2-concepts |
def get_func_code_details(my_F):
"""Extract co_code, co_consts, co_argcount, func_defaults
"""
bytecode = my_F.__code__.co_code
consts = my_F.__code__.co_consts
argcount = my_F.__code__.co_argcount
defaults = my_F.__defaults__
return bytecode, consts, argcount, defaults | bigcode/self-oss-instruct-sc2-concepts |
def connection_table_to_matrix(conn_df, group_cols='bodyId', weight_col='weight', sort_by=None):
"""
Given a weighted connection table, produce a weighted adjacency matrix.
Args:
conn_df:
A DataFrame with columns for pre- and post- identifiers
(e.g. bodyId, type or instance)... | bigcode/self-oss-instruct-sc2-concepts |
def _SkipTreeCheck(input_api, output_api):
"""Check the env var whether we want to skip tree check.
Only skip if include/v8-version.h has been updated."""
src_version = 'include/v8-version.h'
if not input_api.AffectedSourceFiles(
lambda file: file.LocalPath() == src_version):
return False
return ... | bigcode/self-oss-instruct-sc2-concepts |
def translate_to_slack(datum, casa):
"""
For a single entry in the query results, create a dict with the relevant information.
"""
if datum['ementa'] == 'None':
resumo_tipo0 = 'Excerto'
resumo0 = datum['resumo']
else:
resumo_tipo0 = 'Ementa'
resumo0 = datum['emen... | bigcode/self-oss-instruct-sc2-concepts |
def _clip(value, lower, upper):
"""
Helper function to clip a given value based on a lower/upper bound.
"""
return lower if value < lower else upper if value > upper else value | bigcode/self-oss-instruct-sc2-concepts |
def parse_relative_year_value(relative_year: str) -> int:
"""
Parses a relative year value such as "去年"
:param relative_year: The year to parse
:return: An integer representing the relative value of the year, for example -1
"""
if relative_year == "去年":
return -1
if relative_year == ... | bigcode/self-oss-instruct-sc2-concepts |
import pkg_resources
def package_version(name=''):
"""
Get version of arbitrary package.
The function relies on introspection using :mod:`pkg_resources`.
Parameters
----------
name : :class:`str`
Name of package the version should be obtained for
Returns
-------
version ... | bigcode/self-oss-instruct-sc2-concepts |
import re
def findVars(expression):
"""Finds and extracts the variables in an expression using regex pattern matching.
Returns a list of matches in the given string."""
variableRegex = re.compile('[a-zA-Z][a-zA-Z0-9]*')
variables = re.findall(variableRegex, str(expression))
return variables | bigcode/self-oss-instruct-sc2-concepts |
def cif2float(cifnum):
"""
Convert a cif-floating point number that may include an uncertainty
indication to a proper floating point number.
In a .cif file the value "0.4254(4)" is a floating point number where
the digit in brackets gives the uncertainty. To convert this number to
a regular Pyt... | bigcode/self-oss-instruct-sc2-concepts |
import re
def splitCIGAR(CIGAR):
""" Takes CIGAR string from SAM and splits it into two lists: one with
capital letters (match operators), and one with the number of bases """
matchTypes = re.sub('[0-9]', " ", CIGAR).split()
matchCounts = re.sub('[A-Z]', " ", CIGAR).split()
matchCounts = [in... | bigcode/self-oss-instruct-sc2-concepts |
def extend_padding(ls_of_ls, padding=''):
"""
Takes in a lists of lists, returns a new list of lists
where each list is padded up to the length of the longest
list by [padding] (defaults to the empty string)
"""
maxlen = max(map(len, ls_of_ls))
newls = []
for ls in ls_of_ls:
if l... | bigcode/self-oss-instruct-sc2-concepts |
def _crawl(name, mapping):
"""
``name`` of ``'a.b.c'`` => ``mapping['a']['b']['c']``
"""
key, _, rest = name.partition('.')
value = mapping[key]
if not rest:
return value
return _crawl(rest, value) | bigcode/self-oss-instruct-sc2-concepts |
def get_enum(key_list, enum_dict):
"""Returns the mcf format of enum dcid list that represents a given value(s).
Used to convert a list of values which map to enums to their appropriate
enum dcid, as given by the enum_dict. For this import, enum_dict is either
ASSOCIATION_ENUM_DICT or EVIDENCE_ENUM_DIC... | bigcode/self-oss-instruct-sc2-concepts |
import re
def loxi_name(ident):
"""
Return the LOXI name of an openflow.h identifier
"""
# Order at the outer level matters as super strings are listed first
rules = [
# The following are for #define macros and have highest precedence
dict(OFP_MAX_TABLE_NAME_LEN = "OF_MAX_TABLE_NAME_LEN")... | bigcode/self-oss-instruct-sc2-concepts |
def rotate_list(alist):
"""Pop the last element of list out then put it into the first of list.
:param alist: A list that want to rotated.
:return alist: A rotated list.
"""
assert type(alist) == list
last = alist.pop()
alist.insert(0, last)
return alist | bigcode/self-oss-instruct-sc2-concepts |
def downgrade_sample_rate_of_labels(labels, original_sample_rate, needed_sample_rate):
"""This function downgrades sample rate of provided labels to needed_sample_rate
It is worked through calculating ratio between original_sample_rate and needed_sample_rate
and then thinning provided labels
:par... | bigcode/self-oss-instruct-sc2-concepts |
def fullname(o):
"""
Gives a full name (package_name.class_name) for a class / object in Python. Will
be used to load the correct classes from JSON files
"""
module = o.__class__.__module__
if module is None or module == str.__class__.__module__:
return o.__class__.__name__ # Avoid reporting __built... | bigcode/self-oss-instruct-sc2-concepts |
def Status2Int(protect_status):
"""
returns the int-value related to the input-str
Read / Write := 0
Write protect := 1
"""
rtn_value = 0
if 'yes' in protect_status.lower():
rtn_value = 1
return rtn_value | bigcode/self-oss-instruct-sc2-concepts |
def compute_normalized_rho_pars(u, b):
"""Compute normalized rho_0, rho_min given b, u=rho_min/rho_0
Parameters
----------
u : `float`
u = rho_min/rho_0 parameter.
b : `float`
b parameter
Returns
-------
rho_0, rho_min : (`float`, `float`)
"""
rho_0 = ((b + 2)/(... | bigcode/self-oss-instruct-sc2-concepts |
def return_success(data=None):
"""
Generates JSON for a successful API request
"""
if data is None:
return {"success": True}
return {"success": True, **data} | bigcode/self-oss-instruct-sc2-concepts |
def on_whitespace(s):
"""
Returns tokens taking whitespace as word boundaries
>>> on_whitespace('This is not a test.')
['This', 'is', 'not', 'a', 'test.']
Args:
s: a string
Returns:
list: a list of strings
"""
return s.split() | bigcode/self-oss-instruct-sc2-concepts |
def get_user_id(user_id: str) -> str:
"""
Formats the user_id to a plain format removing any <, < or @
:param user_id: slack id format
:type user_id: str
:return: plain user id
:rtype: str
"""
return user_id.strip("<>@") | bigcode/self-oss-instruct-sc2-concepts |
def converter(temperatures, convert):
"""Returns a sequence that converts each Celsius temperature to Fahrenheit
>>> def convert(x):
... return 9.0*x/5.0 + 32
>>> temperatures = [10, 20, 30, 40, 50]
>>> converter(temperatures, convert)
[50.0, 68.0, 86.0, 104.0, 122.0]
"""
return [co... | bigcode/self-oss-instruct-sc2-concepts |
def clean_specie_name(specie_str: str) -> str:
"""
Clean up the species name from '<element>\xa0<roman number for oxidation state>'
to '<element>'
"""
return specie_str.split("\xa0")[0] | bigcode/self-oss-instruct-sc2-concepts |
def is_integer(value, cast=False):
"""Indicates whether the given value is an integer. Saves a little typing.
:param value: The value to be checked.
:param cast: Indicates whether the value (when given as a string) should be cast to an integer.
:type cast: bool
:rtype: bool
.. code-block:: p... | bigcode/self-oss-instruct-sc2-concepts |
def ConvertPrivateIpv6GoogleAccess(choice):
"""Return PrivateIpv6GoogleAccess enum defined in mixer.
Args:
choice: Enum value of PrivateIpv6GoogleAccess defined in gcloud.
"""
choices_to_enum = {
'DISABLE':
'DISABLE_GOOGLE_ACCESS',
'ENABLE_BIDIRECTIONAL_ACCESS':
'ENABLE_BIDI... | bigcode/self-oss-instruct-sc2-concepts |
def _bitcmp(bit, bit_ref, wildcard='x'):
"""
Compares the string representation of a binary number ignoring any bits
on the reference string 'bit_ref' marked with a wildcard.
"""
bit = bit.replace('0b', '')
bit, bit_ref = list(bit), list(bit_ref)
bit.reverse(); bit_ref.reverse() # Start comp... | bigcode/self-oss-instruct-sc2-concepts |
import random
def random_saturation(im, lower=0.5, upper=1.5):
"""Random change saturation
Args:
im(numpy.array): one H,W,3 image
lower(float): change lower limit
upper(float): change upper limit
"""
if random.random() < 0.5:
im[:, :, 1] *= random.uniform(lower, u... | bigcode/self-oss-instruct-sc2-concepts |
def make_complex_matrix(m):
"""
Transforms a block 2x2 matrix of real and imaginary part into a complex matrix
:param m: block 2x2 real matrix as numpy/scipy array
:return: complex matrix as numpy/scipy array
"""
return m[:m.shape[0]/2, :m.shape[1]/2] + 1j * m[m.shape[0]/2:, :m.shape[1]/2] | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def fmt_timestamp(ts=None):
"""
Jinja filter to format date/time from timestamp.
"""
if ts is None:
return 'no-timestamp'
dt = datetime.fromtimestamp(int(ts))
pretty_time = dt.strftime('%m/%d/%y %I:%M %p')
return pretty_time | bigcode/self-oss-instruct-sc2-concepts |
import codecs
def load_utf8(filename):
"""Load UTF8 file."""
with codecs.open(filename, 'r', encoding='utf-8') as f:
return f.read() | bigcode/self-oss-instruct-sc2-concepts |
def build_info(file_name, meta_features):
"""Builds the info of a dataset in a presentable manner"""
info = {'dataset': int(file_name[:-5])}
for feat_name, value in meta_features.items():
new_name = feat_name.replace("_", " ")
info[new_name] = value
return info | bigcode/self-oss-instruct-sc2-concepts |
def train_test_split(features, target, split_ts):
"""
Splits all provided TimeSeries instances into train and test sets according to the provided timestamp.
Parameters
----------
features : TimeSeries
Feature TimeSeries instances to be split.
target : TimeSeries
Target TimeSerie... | bigcode/self-oss-instruct-sc2-concepts |
import colorsys
def hs_to_hex(hue: float, saturation: float) -> str:
"""Convert hue and saturation to a string hex color."""
rgb = colorsys.hsv_to_rgb(hue / 100, saturation / 100, 100)
return "#{:02x}{:02x}{:02x}".format(
round(rgb[0]), round(rgb[1]), round(rgb[2])
).upper() | bigcode/self-oss-instruct-sc2-concepts |
def phi(x, y, ck, i):
"""
The linear basis functions
Parameters
----------
x : np.array
x-values.
y : np.array
y-values.
ck : np.array
basis function coef. matrix.
i : int
which basis function to use.
Returns
-------
numpy.array
basis... | bigcode/self-oss-instruct-sc2-concepts |
def performance_measure(y_true, y_pred):
"""
Compute the performance metrics: TP, FP, FN, TN
Args:
y_true : 2d array. Ground truth (correct) target values.
y_pred : 2d array. Estimated targets as returned by a tagger.
Returns:
performance_dict : dict
Example:
>>> f... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def prep_images(images):
"""
preprocess images
Args:
images: pytorch tensor
"""
images = images.div(255.0)
images = torch.sub(images,0.5)
images = torch.mul(images,2.0)
return images | bigcode/self-oss-instruct-sc2-concepts |
def source_type_normalize(source_type):
"""
Make it easier to ignore small inconsistencies in these key word arguments.
>>> source_type_normalize("journals")
'journal'
>>> source_type_normalize("Journal")
'journal'
"""
ret_val = None
normal = {"journals": "journal",
"... | bigcode/self-oss-instruct-sc2-concepts |
def csdele(self, kcn1="", kcn2="", kcinc="", **kwargs):
"""Deletes local coordinate systems.
APDL Command: CSDELE
Parameters
----------
kcn1, kcn2, kcinc
Delete coordinate systems from KCN1 (must be greater than 10) to
KCN2 (defaults to KCN1) in steps of KCINC (defaults to 1). If ... | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def nth(iterable, n, default=None):
""" Returns the nth item or a default value.
This code is mildly adapted from the documentation.
N.B. This returns the *base-0* nth item in the iterator. For example,
nth(range(10), 1) returns 1.
"""
return next(itertools.islice(iterable,... | bigcode/self-oss-instruct-sc2-concepts |
import asyncio
async def compute_fancy_greeting(name: str, seen: int):
"""
Compute a personalized greeting, based on the number of times this @name had been seen before.
"""
templates = ["", "Welcome %s", "Nice to see you again %s", "Third time is a charm %s"]
if seen < len(templates):
gre... | bigcode/self-oss-instruct-sc2-concepts |
def transform(data, median, var_25_75):
"""Scale data using robust estimators.
Scale the data by subtracting the median and dividing by the
variance, i.e. the difference between the 75th and 25th percentiles.
Parameters
----------
data : pandas DataFrame, shape (n_spectra, n_freq_point... | bigcode/self-oss-instruct-sc2-concepts |
def get_tags(entities):
"""
Args:
entities (Iterable[Entity]): the entities in a sentence
Returns:
Set[str]: a set of their tags, excluding 'O'
"""
return {entity.tag for entity in entities} - {'O'} | bigcode/self-oss-instruct-sc2-concepts |
def g(x, y):
"""
A multivariate function for testing on.
"""
return -x**2 + y | bigcode/self-oss-instruct-sc2-concepts |
def verb_check(tag):
"""
:param tag: a string representing a POS-TAG
:return: boolean if the given tag belongs to the verb class
"""
return tag in ['VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ'] | bigcode/self-oss-instruct-sc2-concepts |
def parse_connector_version(version):
"""Parse a connector version string into a tuple (hadoop version, major version, minor version, patch version, release candidate)."""
hadoop_version, version = version.split("-", maxsplit=1)
hadoop_version = int(hadoop_version[6:])
release_candidate = None
if "... | bigcode/self-oss-instruct-sc2-concepts |
def vertices_generation(number_of_vertices):
"""
Generate the vertices list
:param number_of_vertices:
:return: vertices list in format [0, 1, 2, 3...]
"""
# here, the list is much more efficient than set
return [s for s in range(1, number_of_vertices + 1)] | bigcode/self-oss-instruct-sc2-concepts |
def get_E_pump_hs_d_t(E_pump_SW_d_t, E_pump_gsRW_d_t):
"""日付dの時刻tにおける1時間当たりのポンプの消費電力量 (8)
Args:
E_pump_SW_d_t(ndarray): 日付dの時刻tにおける1時間当たりの送水ポンプの消費電力量(kWh/h)
E_pump_gsRW_d_t(ndarray): 日付dの時刻tにおける1時間当たりの熱源水ポンプの消費電力量(kWh/h)
Returns:
ndarray: 日付dの時刻tにおける1時間当たりのポンプの消費電力量(kWh/h)
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def txt_category_to_dict(category_str):
"""
Parameters
----------
category_str: str of nominal values from dataset meta information
Returns
-------
dict of the nominal values and their one letter encoding
Example
-------
"bell=b, convex=x" -> {"bell": "b", "convex": "x"}
""... | bigcode/self-oss-instruct-sc2-concepts |
import logging
def get_logger(name):
"""Returns a customized logging object.
Multiple calls to with the same name will always return a reference to the same Logger object.
Args:
name (str): Dot-separated hierarchical name for the logger.
Returns:
Logger: An instance of :any:`logging... | bigcode/self-oss-instruct-sc2-concepts |
def derive_http_method(method, data):
"""Derives the HTTP method from Data, etc
:param method: Method to check
:type method: `str`
:param data: Data to check
:type data: `str`
:return: Method found
:rtype: `str`
"""
d_method = method
# Method not provided: Determine method from ... | bigcode/self-oss-instruct-sc2-concepts |
import time
def encode_tag(prefix, time_tuple, time_format):
""" Create a [prefix:time] playlist tag using specified time formatting.
Args:
prefix ::: (str) unique identifier for playlist series
time_tuple ::: (`time.struct_time` instance) time to encode in tag
time_format ::: (str) f... | bigcode/self-oss-instruct-sc2-concepts |
def drop_dupes(sequence):
"""Drop duplicate elements from a list or other sequence.
C.f. https://stackoverflow.com/a/7961390
"""
orig_type = type(sequence)
return orig_type(list(dict.fromkeys(sequence))) | bigcode/self-oss-instruct-sc2-concepts |
def kcalc(self, kplan="", mat="", kcsym="", klocpr="", **kwargs):
"""Calculates stress intensity factors in fracture mechanics analyses.
APDL Command: KCALC
Parameters
----------
kplan
Key to indicate stress state for calculation of stress intensity
factors:
0 - Plane stra... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def _get_activity_names_path(data_processed_dir: str) -> Path:
"""Returns path to the file with activity names.
"""
return Path(data_processed_dir, "activity_names.json") | bigcode/self-oss-instruct-sc2-concepts |
import typing
async def pagify_commands(coms: typing.List[str]) -> typing.List[str]:
"""Takes a list of command names and returns a pagified list
It will return a page of 15 commands
Parameters
----------
coms: List[:class:`str`]
The list of commands to iterate over
Returns
----... | bigcode/self-oss-instruct-sc2-concepts |
import sympy
def symbolize(pair):
"""Turn a pair of symbol names into a pair of symbols."""
return (sympy.Symbol('x' + str(pair[0])),sympy.Symbol('x' + str(pair[1]))) | bigcode/self-oss-instruct-sc2-concepts |
def list_all_videos(api_instance, location, account_id, access_token, page_size=100): # noqa
"""List all videos, using the API paging mechanism.
The default page_size is set to 100 (the API default is 25).
"""
done = False
skip = 0
all_videos = []
while not done:
list_videos = api_... | bigcode/self-oss-instruct-sc2-concepts |
import json
def DictToJSON(pydict):
"""Convert a dict to a JSON-formatted string."""
pretty_string = json.dumps(pydict, sort_keys=False, indent=2)
# json.dumps sometimes returns trailing whitespace and does not put
# a newline at the end. This code fixes these problems.
pretty_lines = pretty_string.split('... | bigcode/self-oss-instruct-sc2-concepts |
def get_sizeChange(size1, size2):
""" Returns change in size of an echo as the ratio of the larger size to
the smaller, minus 1. """
if (size1 < 5) and (size2 < 5):
return 0
elif size1 >= size2:
return size1/size2 - 1
else:
return size2/size1 - 1 | bigcode/self-oss-instruct-sc2-concepts |
import random
def random_crop2d(*images, min_perc=0.5, max_perc=1.):
"""Crop randomly but identically all images given.
Could be used to pass both mask and image at the same time. Anything else will
throw.
Warnings
--------
Only works for channel first images. (No channel image will not work... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def split_and_sum(tensor, N):
"""spliting a torch Tensor into a list of uneven sized tensors,
and sum each tensor and stack
Example:
A = torch.rand(10, 10)
N = [4,6]
split_and_sum(A, N).shape # (2, 10)
Args:
tensor (torch.Tensor): tensors to be split and ... | bigcode/self-oss-instruct-sc2-concepts |
def csv_list(l):
"""Format list to a string with comma-separated values.
"""
if len(l) == 0:
return ""
return ', '.join(map(str, l)) | bigcode/self-oss-instruct-sc2-concepts |
def var_name(string: str) -> str:
"""Strips out the Variable name from a string
:param string: e.g. $MY_PATH:$YOUR_PATH
:return string: e.g. MY_PATH
"""
key = ""
for char in string:
if char.isalpha() or char.isdigit() or char == "_":
key += char
else:
retu... | bigcode/self-oss-instruct-sc2-concepts |
def load_embeddings(path, dimension=300):
"""
Loads the embeddings from a word2vec formatted file.
word2vec format is one line per word and it's associated embedding
(dimension x floating numbers) separated by spaces
The first line may or may not include the word count and dimension
"""
vect... | bigcode/self-oss-instruct-sc2-concepts |
def nlineas(n):
"""Escribe n líneas o línea según el valor de n"""
if n == 0:
return "cero líneas"
elif n == 1:
return "una línea"
elif n == 2:
return "dos líneas"
else:
return "%d líneas" % n | bigcode/self-oss-instruct-sc2-concepts |
def getConfigIds(config):
"""Get a list of all config fields that have been set along with the ID.
:param config: The configuration object
:type config: configuration.Configuration
"""
fields = [
f + ': ' + str(getattr(config, f)) for f in dir(config)
if not f.startswith('_')
... | 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.