seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def pad_sentence_batch(sentence_batch, pad_int):
"""Pad char seq with <PAD> so that each char sequence of a batch has the same length"""
max_seq = max([len(seq) for seq in sentence_batch])
padded_batch=[]
for seq in sentence_batch:
temp=[]
for char in seq:
temp.append(char)
... | bigcode/self-oss-instruct-sc2-concepts |
def moveIntToBoolList(i):
"""
Convert an integer in the range [0, 7] to a list of 3 boolean values, corresponding to the binary representation
:param i: The integer
:return: The list of 3 boolean values
"""
# not using loops or append because this is faster, and this method only needs to work fo... | bigcode/self-oss-instruct-sc2-concepts |
def as_text(value):
"""Returns the string representation of given value
Arguments:
value {any} -- Value to get the string representation for
Returns:
stringified text {String} -- String representation of given value
"""
return "" if value is None else str(value) | bigcode/self-oss-instruct-sc2-concepts |
import random
def gen_mac(last_octet=None):
"""Generate a random MAC address that is in the qemu OUI space and that
has the given last octet.
"""
return "52:54:00:%02x:%02x:%02x" % (
random.randint(0x00, 0xFF),
random.randint(0x00, 0xFF),
last_octet,
) | bigcode/self-oss-instruct-sc2-concepts |
def user_privileges(connection):
"""Get the list of privileges for the authenticated user.
The response includes the name, ID, and description of each
privilege and specifies which projects the privileges are valid for.
Args:
connection: MicroStrategy REST API connection object
Returns:
... | bigcode/self-oss-instruct-sc2-concepts |
def combine_first_last_name(df):
"""
Combine first and last name if df has those columns.
"""
if 'first_name' in df.columns and 'last_name' in df.columns:
df['full_name'] = df['first_name'] + ' ' + df['last_name']
df.drop(['first_name', 'last_name'], axis=1, inplace=True)
return df | bigcode/self-oss-instruct-sc2-concepts |
def min_if_exist(n1, n2):
"""
Returns the minimum between two numbers, or the only defined number
(in case the other is `None`) or `None` if none of the numbers are defined.
"""
if n1 is None and n2 is None:
return None
elif n1 is None:
return n2
elif n2 is None:
retu... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def generate_identifier(metadata: str) -> str:
"""Generate a (hopefully) unique identifier."""
obj = hashlib.md5(metadata.encode())
dig = obj.hexdigest()
return str(int(dig[:6], 16)) | bigcode/self-oss-instruct-sc2-concepts |
import re
def check_global_attr_against_regex(ds, attr, regex):
"""
Returns 0 if attribute `attr` not found, 1 if found but doesn't match
and 2 if found and matches `regex`.
:param ds: netCDF4 Dataset object
:param attr: global attribute name [string]
:regex: a regular expression definition [... | bigcode/self-oss-instruct-sc2-concepts |
def ordinal(n, combine=False):
"""
Return the ordinal of the number n.
If combine then return the number concatenated with the ordinal
"""
number_string = str(n) if combine else ""
special_cases = {1: "st", 2: "nd", 3: "rd"}
if not 10 <= n % 100 <= 20 and n % 10 in special_cases:
re... | bigcode/self-oss-instruct-sc2-concepts |
def npieces(request):
"""Number of collocation pieces."""
return request.param | bigcode/self-oss-instruct-sc2-concepts |
def apply_op(input_layer, operation, *op_args, **op_kwargs):
"""Applies the given operation to this before without adding any summaries.
Args:
input_layer: The input layer for this op.
operation: An operation that takes a tensor and the supplied args.
*op_args: Extra arguments for operation.
**op_k... | bigcode/self-oss-instruct-sc2-concepts |
def extract_job_fields(tags):
"""Extracts common job's metric fields from TaskResultSummary.
Args:
tags (list of str): list of 'key:value' strings.
"""
tags_dict = {}
for tag in tags:
try:
key, value = tag.split(':', 1)
tags_dict[key] = value
except ValueError:
pass
spec_name... | bigcode/self-oss-instruct-sc2-concepts |
def replace_string(text, replacements=None, whitespace=True):
"""A wrapper around str.replace where replacements is a dictionary:
original_string -> replacement_string
whitespace=True surounds the replacement with whitespaces.
"""
if not replacements:
return text
for ori, rpl in repl... | bigcode/self-oss-instruct-sc2-concepts |
def get_domain(url: str, /) -> str:
"""Get domain from an url"""
return url.split('//')[-1].split('/')[0].split('?')[0] | bigcode/self-oss-instruct-sc2-concepts |
def rectangles_intersect(rect1, rect2):
"""Returns True if two rectangles intersect."""
return all([(rect1[1][i] >= rect2[0][i]) and
(rect2[1][i] >= rect1[0][i]) for i in range(2)]) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
def typename(o: Any) -> str:
"""Return the full name (including module) of the type of o.
>>> typename(5)
'int'
>>> typename('text')
'str'
>>> typename(np.array([1]))
'numpy.ndarray'
"""
# https://stackoverflow.com/a/2020083
name: str = o.__class__.__qualname__
module =... | bigcode/self-oss-instruct-sc2-concepts |
def null_count(df):
"""
Check a dataframe for nulls and return the number of missing values
"""
# Example Input (df = pd.DataFrame):
# > | column 0 | column 1 | column 2 |
# > | ----------- | ----------- | ----------- |
# > | NaN | 9 | 10 |
# > | 4 ... | bigcode/self-oss-instruct-sc2-concepts |
def round(addr: int, align: int, up: bool = False) -> int:
"""Round an address up or down based on an alignment.
Args:
addr: the address
align: the alignment value
up: Whether to round up or not
Returns:
The aligned address
"""
if addr % align == 0:
return ... | bigcode/self-oss-instruct-sc2-concepts |
def is_group(message) -> bool:
"""Whether message was sent at a group."""
# See "type" at https://core.telegram.org/bots/api#chat.
return 'group' in message.chat.type | bigcode/self-oss-instruct-sc2-concepts |
def is_not_excluded_type(file, exclude_types):
"""Return False if file type excluded, else True"""
if exclude_types:
for exclude_type in exclude_types:
if file.lower().endswith(exclude_type.lower()):
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
from functools import wraps
def consumer(func):
"""A decorator, advances func to its first yield point when called.
"""
@wraps(func)
def wrapper(*args, **kw):
gen = func(*args, **kw)
gen.next()
return gen
return wrapper | bigcode/self-oss-instruct-sc2-concepts |
def excel_to_python(command_string):
"""
Returns the python equivalent of many excel formula names
"""
d = {
'SUM' : 'np.sum',
'AVERAGE' : 'np.mean',
'MAX' : 'np.max',
'MIN' : 'np.min',
'MEDIAN' : 'np.median',
'MODE' :... | bigcode/self-oss-instruct-sc2-concepts |
def get_end_pos(cls, start_pos, dimensions, left=False, up=False):
"""
calculate the end position if were to build an array of items
:param cls: Type
:param start_pos: (int, int)
:param dimensions: (int, int)
:param left: bool: default builds rightward
:param up: bool: default builds downwar... | bigcode/self-oss-instruct-sc2-concepts |
def find_out_of_order_packet_indices(packet_ns):
"""
Return indices of packets which have apparently arrived out-of-order.
Specifically: return indices of any packet number which was less than the
previous packet number. For example, for the list of packet numbers:
0, 1, 2, 3, 5, 4, 6, 7.
re... | bigcode/self-oss-instruct-sc2-concepts |
import base64
def base64_encode(s):
"""Encode a URL-safe string.
:type s: six.text_type
:rtype: six.text_type
"""
# urlsafe_b64encode() returns six.binary_type so need to convert to
# six.text_type, might as well do it before stripping.
return base64.urlsafe_b64encode(s).decode('utf-8').... | bigcode/self-oss-instruct-sc2-concepts |
def resultIsSuccess(res):
"""
JSON-decoded stake pool responses have a common base structure that enables
a universal success check.
Args:
res (dict): The freshly-decoded-from-JSON response.
Returns:
bool: True if result fields indicate success.
"""
try:
return res[... | bigcode/self-oss-instruct-sc2-concepts |
def _create_array_rec(dimensions: int, sizes: list, initialization_value: int = 0) -> list:
"""Auxiliary recursive function for creating a new matrix consisting on lists of lists.
This method assumes that the parameters were previously validated.
:param int dimensions: the number of dimensions to create. ... | bigcode/self-oss-instruct-sc2-concepts |
def _extract(dct, keys):
""" Helper function to extract a list of keys from a dict and return these
in a new dict.
"""
tmp = {}
for key in keys:
try:
tmp[key] = dct.pop(key)
except KeyError:
pass
return tmp | bigcode/self-oss-instruct-sc2-concepts |
def subtree_ids(treeview, x, level=0):
"""
Return a list of tuples containing the ids and levels for *x* and every element below it in the Treeview *treeview*.
The level of *x* is 0, children of *x* are 1, and so forth.
"""
id_list = list()
id_list.append((x, level))
for y in treeview.get_c... | bigcode/self-oss-instruct-sc2-concepts |
def get_interval(value, intervals):
"""
Returns the index of the interval the value lies in.
:param value: Value for which to find the interval.
:param intervals: List or tuple of interval with values which represent the upper boundary of each interval.
The first interval starts at 0 and ends ar th... | bigcode/self-oss-instruct-sc2-concepts |
def comma_code(items):
""" Combines list into a string of the form item1, item2, and item 3
Args:
items (list): List of strings
Returns:
string: list items combined into a string
"""
item_len = len(items)
if item_len == 0:
return ''
elif item_len == 1:
r... | bigcode/self-oss-instruct-sc2-concepts |
def ignore_escape(path: str) -> str:
"""
Escape a path appropriately for a docker ignore file.
"""
special_chars = "\\*?[]"
return "".join("\\" + ch if ch in special_chars else ch for ch in path) | bigcode/self-oss-instruct-sc2-concepts |
import time
def month_and_year_to_epoch(month_no, year):
""" Convert a month and year to the epoch time for the first second of
said month. """
month_str = str(month_no)
if len(month_str) == 1:
month_str = "0"+month_str
date_and_time = "01."+month_str+"."+str(year)+" 00:00:01"
pattern ... | bigcode/self-oss-instruct-sc2-concepts |
import re
def executable_script(src_file, gallery_conf):
"""Validate if script has to be run according to gallery configuration
Parameters
----------
src_file : str
path to python script
gallery_conf : dict
Contains the configuration of Sphinx-Gallery
Returns
-------
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Any
from typing import Sequence
def get_nested(data: Dict[str, Any], keys: Sequence[str]) -> Any:
"""
Get a value from a nested dictionary.
Args:
data (Dict[str, Any]): The dictionary to get the value from.
keys (Sequence[str]): The keys to get t... | bigcode/self-oss-instruct-sc2-concepts |
def to_int(text):
"""
extract digits from text
"""
return ''.join([char for char in text if char.isdigit()]) | bigcode/self-oss-instruct-sc2-concepts |
def lerp(input1, input2, mask):
"""Lerp between two values based on a 0-1 mask value.
When mask is 0, return input1. When mask is 1, return input2.
Otherwise blend between the two."""
return ((1 - mask) * input1) + (mask * input2) | bigcode/self-oss-instruct-sc2-concepts |
import time
def timeit(func):
"""Decorator to time a single run of a task"""
def wrapper(*arg, **kw):
t0 = time.time()
res = func(*arg, **kw)
t1 = time.time()
res.elapsed = (t1 - t0)
if not res.desc:
res.desc = func.__name__
return res
return wra... | bigcode/self-oss-instruct-sc2-concepts |
def get_P_Elc_game_standby(P_Elc_game_standby_measured):
"""待機時の消費電力を計算する
Parameters
----------
P_Elc_game_standby_measured : float
待機時の平均消費電力(実測値), W
Returns
----------
P_Elc_game_standby : float
稼働時消費電力, W
"""
P_Elc_game_standby = P_Elc_game_standby_m... | bigcode/self-oss-instruct-sc2-concepts |
def norm1(x):
"""Normalize to the unit sphere."""
return x / x.square().sum(axis=-1, keepdims=True).sqrt().clamp(1e-12) | bigcode/self-oss-instruct-sc2-concepts |
from unittest.mock import Mock
def mock_config() -> Mock:
"""Returns the configuration mock object."""
mock_config = Mock()
mock_config.host = "mock_host"
mock_config.url = "mock_url"
mock_config.session.get = "mock_get"
mock_config.session.post = "mock_post"
return mock_config | bigcode/self-oss-instruct-sc2-concepts |
def has_series(event) -> bool:
"""
Check if the event belongs to a series.
:param event:
:type event: dict
:rtype: bool
"""
return "series" in event and event["series"]["id"] | bigcode/self-oss-instruct-sc2-concepts |
def dd_start_value_map_nb(record, ts):
"""`map_func_nb` that returns start value of a drawdown."""
return ts[record['start_idx'], record['col']] | bigcode/self-oss-instruct-sc2-concepts |
def bool_to_one_or_zero(value):
"""
Converts a boolean value into an integer
:param value: A boolean value
:type value: bool
:return: 1 or 0
:rtype: int
"""
return 1 if value else 0 | bigcode/self-oss-instruct-sc2-concepts |
def per_form_un(number):
"""
works out, for the lattice parameters of t-LLZO, defects per cubic cm
args:
number (float): defect per formula unit
returns:
per_cubic_cm: defect per cubic cm
"""
per_unit_cell = number * 8
per_cubic_angstrom = per_unit_cell / (13.003 * 13.003 * ... | bigcode/self-oss-instruct-sc2-concepts |
import random
def find_trigram(vocab, pair=False):
"""Find random set of related words in the vocab dictionary.
If a valid pair is passed, return the third word in the trigram.
Otherwise, randomly choose and return a key pair from the dictionary.
"""
if pair in vocab:
return random.choice... | bigcode/self-oss-instruct-sc2-concepts |
def get_package_version(packages, package):
"""
Get version of installed package.
:param packages: installed packages and versions, keyed by package
name
:type packages: dict of str or unicode => str or unicode
:param package: Package name
:type package: str or unicode
:return: Package ... | bigcode/self-oss-instruct-sc2-concepts |
def get_means_of_booleans(data, boolean_cols):
""" Put boolean_cols of the data in a uniform format and
compute the mean per customer.
Parameters
----------
data: The DataFrame.
boolean_cols: array-like of column names with boolean values to
process.
Returns
-------
Dat... | bigcode/self-oss-instruct-sc2-concepts |
def get_lib_name(lib):
"""Returns the name of a library artifact, eg. libabc.a -> abc
Args:
lib (File): A library file
Returns:
str: The name of the library
"""
# NB: The suffix may contain a version number like 'so.1.2.3'
libname = lib.basename.split(".", 1)[0]
if libname... | bigcode/self-oss-instruct-sc2-concepts |
def calculate_avg_delay_wait(avg_delays):
"""
Calculate average delay or waiting value.
"""
avg_delays_dict = {}
for lambda_rate, avg_delay_list in avg_delays.items():
avg_value = sum(avg_delay_list) / len(avg_delay_list)
avg_delays_dict[lambda_rate] = avg_value
return avg_delays... | bigcode/self-oss-instruct-sc2-concepts |
import struct
def bytes_to_int(byte_stream):
"""Convert bytes to integer"""
return struct.unpack(">L", byte_stream)[0] | bigcode/self-oss-instruct-sc2-concepts |
def factorial(n):
""" Naive computation of factorial(n) with products. Not recursive."""
if n <= 0: return 1.0
else:
f = 1.0
for i in range(2, n+1):
f *= i
return float(f) | bigcode/self-oss-instruct-sc2-concepts |
import requests
import json
def get_pushshift_submissions(query, sub):
"""
Retrieves Reddit submissions matching query term over a given interval
Parameters
----------
query : str
Query term to match in the reddit submissions
sub : str
Submission match query
Returns
-------
... | bigcode/self-oss-instruct-sc2-concepts |
def _test_rast(h):
"""Sun raster file"""
if h.startswith(b'\x59\xA6\x6A\x95'):
return 'rast' | bigcode/self-oss-instruct-sc2-concepts |
def filter_float(value):
"""
Filter given float value.
:param value: given value
:type value: float
:return: filtered version of value
"""
if isinstance(value, (float, int)):
return value
return None | bigcode/self-oss-instruct-sc2-concepts |
def invert_for_next(current):
"""
A helper function used to invert
the orientation indicator of the
next panel based on the current panel
i.e. if a parent is horizontal a
child panel must be vertical
:param current: Current parent
orientation
:type current: str
:return: child... | bigcode/self-oss-instruct-sc2-concepts |
def merge_station_subloc(station_dbase,station_subloc,default_z):
"""Merge BayDeltaSCHISM station database with subloc file, producing the union of all stations and sublocs including a default entry for stations with no subloc entry
Parameters
----------
station_dbase : DataFrame
This should... | bigcode/self-oss-instruct-sc2-concepts |
def isWinner(data,c1,c2):
"""
This function takes the preference ranking data as an input parameter. It computes the
head to head winner for the two candidates that are passed into it as parameters.
If the first candidate passed as a paramter wins against the second candidate, then
the function will ... | bigcode/self-oss-instruct-sc2-concepts |
def outgoing_synapses(q, N = None, rel='>',include_inferred=True):
"""
Get all the outgoing synapses from neurons in a QueryWrapper object.
Parameters
----------
q: query.QueryWrapper
The query to search for outgoing synapses
N: int or None
Filter for number of synapses (default... | bigcode/self-oss-instruct-sc2-concepts |
def revertDateTimeToLongString(dt):
"""
Turns a date/time into a long string as needed by midas code.
"""
return str(dt).replace("-", "").replace(" ", "").replace("T", "").replace(":", "") | bigcode/self-oss-instruct-sc2-concepts |
def deny(user, record):
"""Deny access."""
return False | bigcode/self-oss-instruct-sc2-concepts |
import pathlib
def is_empty_dir(path: str) -> bool:
"""Checks if path is emptry directory
e.g
j.sals.fs.is_empty_dir("/home/rafy/empty_dir") -> True
j.sals.fs.is_empty_dir("/home/rafy") -> False
Args:
path (str): path to check if empty directory
Returns:
bool: True ... | bigcode/self-oss-instruct-sc2-concepts |
import ast
def datAst(dat):
"""
Get the ast node of a DAT holding Python code
Args:
dat: the dat to analyze
Returns:
ast node of the DAT's text. Will be ast.Module at top
"""
return ast.parse(dat.text) | bigcode/self-oss-instruct-sc2-concepts |
def get_signature_algorithm(alg_type, alg_hash):
"""
Returns signature algorithm for ACM PCA
Args:
isEC: true if Elliptic Curve certificate
alg_type: Hash Algorithm from cryptography package to find
Raises:
ValueError: Algorithm type not supported
"... | bigcode/self-oss-instruct-sc2-concepts |
def frozen (db, user, date, order = '+') :
""" Get frozen freeze-records >= date. If some are found, the date
is frozen. By default the first record returned is the first
after date. But sometimes we want the *last* freeze record. Then
we can specify order = '-'.
"""
f = db.daily_rec... | bigcode/self-oss-instruct-sc2-concepts |
import time
def toJulian2(date):
"""
Converts date and time to Modified Julian Date.
Uses time functions. Note that date has to be in Python time format.
:return: Modified Julian Date
:rtype: float
"""
sec = time.mktime(date)
days = (sec - time.timezone) / 86400.0
jday = days + 40... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
from typing import Union
import math
def calculate_gain(nonlinearity: str, param: Optional[Union[int, float]] = None):
"""
Return the recommended gain value for the given nonlinearity function.
The values are as follows:
================= =================================... | bigcode/self-oss-instruct-sc2-concepts |
def left_path_clear(Rover, safe_pixs=1500):
"""
Check if sufficient room on left.
Keyword arguments:
safe_pixs -- minimum number of pixels on left to deem left path clear
"""
nav_pixs_left = len(Rover.nav_angles_left)
return nav_pixs_left >= safe_pixs | bigcode/self-oss-instruct-sc2-concepts |
def ligand_residue_vs_water_hbonds(hbonds, solvent_resn, ligand):
"""
Split hbonds into those involving residue and ligand directly and those
mediated by water molecules.
"""
ligand_residue_hbonds, water_hbonds = [], []
for hbond in hbonds:
frame_idx, atom1_label, atom2_label, itype = hb... | bigcode/self-oss-instruct-sc2-concepts |
def stations_by_river(stations):
"""
Given list of stations, return a dict of all the stations on a river
"""
rivers = {}
for station in stations:
if station.river in rivers:
rivers[station.river].append(station)
else:
rivers[station.river] = [station]
ret... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
import pkg_resources
def get_current_environment_requirements() -> Dict[str, str]:
"""Returns a dict of package requirements for the environment that
the current python process is running in."""
return {
distribution.key: distribution.version
for distribution in pkg... | bigcode/self-oss-instruct-sc2-concepts |
def take(dataset, num_examples=-1, **unused_kwargs):
"""Takes the first `num_examples` examples from the dataset.
This is done to simulate that the dataset is smaller than it actually is. The
result will be cached via `tf.data.Dataset.cache`. This ensures that the same
examples get repeated if `dataset` is st... | bigcode/self-oss-instruct-sc2-concepts |
def derived_P_species(df_R, f_TDP):
"""
Calculate: Total P as the sum of TDP and PP
SRP as a function of TDP
for both the daily mass flux and the concentrations
Inputs: reach results dataframe; value to multiply TDP by to get SRP
Returns: dataframe of reach results, with ex... | bigcode/self-oss-instruct-sc2-concepts |
def bp_star_rating(tot_group_rate, oa_reviews):
"""
Function to compute business review per star rating
star_rate = tot_group_rate / oa_reviews * 100%
"""
star_rate = (int(tot_group_rate) / int(oa_reviews)) * 100
m = round(star_rate, 2)
return m | bigcode/self-oss-instruct-sc2-concepts |
import re
from typing import OrderedDict
def parse_region(regstr):
"""
Parse the given region string into one of the following 4 cases:
1. annulus
2. pie (cxc)
3. pie + annulus (ftools/xmm)
4. other
For the first 3 cases, the return is a dictionary like:
{ 'shape': 'pie', 'xc': 55... | bigcode/self-oss-instruct-sc2-concepts |
def get_state_result(state):
"""Get result from Prefect state object."""
return state.result() | bigcode/self-oss-instruct-sc2-concepts |
def multiFind(string,substring):
"""Return a list if integers indicating where the substring begins in the string.
Substrings are not allowed to overlap themselves:
multifind('pppp','pp') = [0,2]
If there are no matches, return []
"""
start = 0
indices = []
while True:
start ... | bigcode/self-oss-instruct-sc2-concepts |
def permute_all_atoms(labels, coords, permutation):
"""
labels - atom labels
coords - a set of coordinates
permuation - a permutation of atoms
Returns the permuted labels and coordinates
"""
new_coords = coords[:]
new_labels = labels[:]
for i in range(len(permutation)):
new_... | bigcode/self-oss-instruct-sc2-concepts |
def github(path):
"""
:param path: relative (to the root) path of a file in the glottolog data repository
:return: URL to a file in Glottolog's data repository on GitHub
"""
return 'https://github.com/glottolog/glottolog/blob/master/{0}'.format(path) | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_vocabs_from_string(string):
"""
Search in the string to find BODC vocabularies (P01, P06 etc.
Returns a dict where:
key = vocabulary
value = code
"""
result = re.findall('SDN:[A-Z0-9]*::[A-Z0-9]*', string)
vocabs = {}
for item in result:
spl... | bigcode/self-oss-instruct-sc2-concepts |
def bezier_point(cps, t):
"""
Cubic Bezier curve interpolation
B(t) = (1-t)^3 * P0 + 3t(1-t)^2 * P1 + 3t^2(1-t) * P2 + t^3 * P3
"""
p = ((1 - t) ** 3) * cps[0, :]
p += 3 * t * ((1 - t) ** 2) * cps[1, :]
p += 3 * (t ** 2) * (1 - t) * cps[2, :]
p += (t ** 3) * cps[3, :]
return p | bigcode/self-oss-instruct-sc2-concepts |
def process_tariff(utilityrate, tariff_dict, net_billing_sell_rate):
"""
Instantiate the utilityrate5 PySAM model and process the agent's rate json object to conform with PySAM input formatting.
Parameters
----------
agent : 'pd.Series'
Individual agent object.
Returns
-------
... | bigcode/self-oss-instruct-sc2-concepts |
import re
def sanitize(instr, pattern=r'\W', replace=''):
"""Sanitize characters in string.
Default removes all non-alphanumeric characters.
"""
return re.sub(pattern, replace, instr) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
def tuple_(obj: Any) -> tuple:
"""Converts any object to tuple. ``string`` to ``(string,)``."""
if isinstance(obj, str):
return obj,
try:
return tuple(obj)
except TypeError:
return obj, | bigcode/self-oss-instruct-sc2-concepts |
def get_gen_loss(crit_fake_pred):
"""
Return the loss of a generator given the critic's scores of generator's fake images.
:param crit_fake_pred: the critic's scores of the fake images
:return: gen_loss: a scalar loss value for current batch of generator
"""
gen_loss = -1 * crit_fake_pred.mean()... | bigcode/self-oss-instruct-sc2-concepts |
def get_fully_qualified_name(func):
"""
gets the fully qualified name of given function.
it returns `module_name.function_name`.
for example: `pyrin.api.services.create_route`.
:param function func: function to get its fully qualified name.
it must be a stand-alone functi... | bigcode/self-oss-instruct-sc2-concepts |
def get_tokens(sequences, lower=False, upper=False):
"""Returns a sorted list of all unique characters of a list of sequences.
Args:
sequences: An iterable of string sequences.
lower: Whether to lower-case sequences before computing tokens.
upper: Whether to upper-case sequences before computing tokens... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def sha256(fp_in, block_size=65536):
"""Generates SHA256 hash for a file
:param fp_in: (str) filepath
:param block_size: (int) byte size of block
:returns: (str) hash
"""
sha = hashlib.sha256()
with open(fp_in, 'rb') as fp:
for block in iter(lambda: fp.read(block_size), b''):
sh... | bigcode/self-oss-instruct-sc2-concepts |
import glob
def xpand(args):
"""
Expand command line arguments.
Arguments:
args: List of arguments.
Returns:
Expanded argument list.
"""
xa = []
for a in args:
g = glob.glob(a)
if g:
xa += g
else:
xa += [a]
return xa | bigcode/self-oss-instruct-sc2-concepts |
def delete_srv6_behavior(database, key, grpc_address=None, grpc_port=None,
segment=None, action=None, device=None, table=None,
nexthop=None, lookup_table=None, interface=None,
segments=None, metric=None, fwd_engine=None,
... | bigcode/self-oss-instruct-sc2-concepts |
def format_days(days):
"""
Converts a list of tuples with a date into a list of tuples with a string
representation of the date
:param days: List of tuples from database with datetime in second position
:return: List of tuples as described above
"""
formatted = []
for day in days:
... | bigcode/self-oss-instruct-sc2-concepts |
def head_tail_middle(src):
"""Returns a tuple consisting of the head of a enumerable, the middle
as a list and the tail of the enumerable. If the enumerable is 1 item, the
middle will be empty and the tail will be None.
>>> head_tail_middle([1, 2, 3, 4])
1, [2, 3], 4
"""
if len(src) == 0:... | bigcode/self-oss-instruct-sc2-concepts |
import json
def load_json(file):
"""Loads a JSON file and returns it as a dict"""
with open(file) as f:
return json.load(f) | bigcode/self-oss-instruct-sc2-concepts |
def B2IQUV_TMS(B, sign_uv=1, sign_q=1):
"""Convert sky brightness matrix to I, Q, U, V"""
B11 = B[0, 0, :, :]
B12 = B[0, 1, :, :]
B21 = B[1, 0, :, :]
B22 = B[1, 1, :, :]
stokes = {}
stokes['I'] = (B11 + B22) / 2.
stokes['Q'] = sign_q * sign_uv * (B11 - B22) / 2.
stokes['U'] = sign_u... | bigcode/self-oss-instruct-sc2-concepts |
def filter_tags(rules, tags=[]):
"""
Filter the rules object for rules that have a certain tag
:param rules: YARA rules JSON object
:param tags: the selected tags
:return: list of filtered rules
"""
filtered_rules = []
# Process the rules
for rule in rules:
for tag in tags:
... | bigcode/self-oss-instruct-sc2-concepts |
import codecs
import yaml
def parse_yaml_or_json(path):
"""
Return parsed YAML or JSON for a path to a file.
"""
with codecs.open(path, mode='r', encoding='utf-8') as infile:
doc = yaml.safe_load(infile)
return doc | bigcode/self-oss-instruct-sc2-concepts |
def less_than(values, target_loc, puzzle_input):
"""if the first parameter is less than the second parameter, it stores 1 in
the target location. Otherwise it stores 0.
"""
if values[0] < values[1]:
puzzle_input[0, target_loc] = 1
else:
puzzle_input[0, target_loc] = 0
return puzz... | bigcode/self-oss-instruct-sc2-concepts |
def solution(resources, args):
"""Problem 6 - Version 1
Manually calculate the sum of squares and the square of the sum.
Parameters:
args.number The upper limit of the range of numbers to use
for the calculation (i.e. 1 to args.number)
Return:
(1^2 + 2^2 + ... | bigcode/self-oss-instruct-sc2-concepts |
def semester_year_to_term_key(semester, year):
"""
Convert semester and year to a 4-digit term number
"""
semester = str(semester).strip().lower()
return 1000 + int(year) % 100 * 10 + ["spring", "summer", "fall"].index(semester) * 2 + 4 | 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.