seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
from typing import List
def parse_to_lines(content: str) -> List[str]:
"""Metin içerisindeki satırların listesini oluşturur
Arguments:
content {str} -- Metin
Returns:
List[str] -- Satır listesi
Examles:
>>> parse_to_lines('Selam\\nNaber\\nNasılsın')
['Selam', 'Naber'... | bigcode/self-oss-instruct-sc2-concepts |
def update_state(reactants, products, state, rxn_ind, reverse):
"""
Updating the system state based on chosen reaction, during kMC simulation.
Args:
reactants: (n_rxns x 2) array, each row containing reactant mol_index of forward reaction
products: (n_rxns x 2) array, each row containing pr... | bigcode/self-oss-instruct-sc2-concepts |
def get_param_value(mode, memory, ptr):
"""Returns the value of the parameter at memory[ptr] based on the mode"""
# position mode
if mode == 0:
return memory[memory[ptr]]
# immediate mode
elif mode == 1:
return memory[ptr]
else:
raise Exception | bigcode/self-oss-instruct-sc2-concepts |
def calc_tstart(num_bins, binsize, t_stop):
"""
Calculates the start point from given parameter.
Calculates the start point :attr:`t_start` from the three parameter
:attr:`t_stop`, :attr:`num_bins` and :attr`binsize`.
Parameters
----------
num_bins: int
Number of bins
binsize: ... | bigcode/self-oss-instruct-sc2-concepts |
import requests
def get_rates(url):
"""Method to get currency rates and returns status of request(boolean)
and request response in JSON format.
@:param str url: Exchange site url
@:return boolean: True for successful response, else False.
@:return dict: Response in case of success else empty dict... | bigcode/self-oss-instruct-sc2-concepts |
def _guess_desc(fname):
"""Attempts to guess the menu entry description from the function name."""
return fname.title().replace("_", " ") | bigcode/self-oss-instruct-sc2-concepts |
def make_actual_args(members):
"""Comma-separated name list used in actual arguments
a, b, c
"""
return ", ".join(name for _, name in members) | bigcode/self-oss-instruct-sc2-concepts |
def update_parser(parser):
"""Parse the arguments from the CLI and update the parser."""
parser.add_argument(
'--prepro_step',
type=str,
default='preprocessing', #'slicing', 'preprocessing'
help='To execute a preprocessing method')
#this is for allfeatures_preprocessi... | bigcode/self-oss-instruct-sc2-concepts |
import json
def readJSONDict(filename):
"""
Retrieve stored dict from JSON file
"""
jsondict = {}
with open(filename, 'rb') as infile:
jsondata = infile.read()
jsondict = json.loads(jsondata)
return jsondict | bigcode/self-oss-instruct-sc2-concepts |
def is_member_of_group(status: str):
"""check, whether a given status indicates group-association
Args:
status (str): status to check
Returns:
bool: is a person with status in this group?
"""
possibleStati = ['creator', 'administrator', 'member', 'restricted']
return status in... | bigcode/self-oss-instruct-sc2-concepts |
def yaml_transformer(value: str) -> str:
"""A YAML transformer for Ruamel that places a blank line between each top level section."""
lines = value.splitlines()
output = []
for line_no, line in enumerate(lines):
if line_no and not line.startswith(' '):
output.append('')
out... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
def __attempt_replace(line_args: str, labels_locs: Dict[str, int]) -> str:
"""
Atttempt to replace a label with its memory address.
:param line_args: Part of the line including the arguments.
:param labels_locs: Labels and their memory addresses.
:return: Line with the labe... | bigcode/self-oss-instruct-sc2-concepts |
def agg_loss(method):
"""
Extract aggregate loss from full name of method.
Args:
method (str): full name of method
Returns:
str: aggregate loss
"""
if method[:6] == "hinge_":
return method[6:]
if method[:9] == "logistic_":
return method[9:]
if method[:7]... | bigcode/self-oss-instruct-sc2-concepts |
def nullility_corr(data, method="pearson"):
"""Calculates the nullility correlation between features in a DataFrame.
Leverages pandas method to calculate correlation of nullility. Note that
this method drops NA values to compute correlation. It also employs
`check_missingness` decorator to ensure DataF... | bigcode/self-oss-instruct-sc2-concepts |
import re
def clean_spaces(text: str) -> str:
"""Removes any consecutive white spaces in the text, as well as preceding and
trailing whitespaces.
Arguments:
text:
The text to be filtered.
Returns:
The filtered text.
"""
return re.sub(
" +", " ", text
)... | bigcode/self-oss-instruct-sc2-concepts |
def get_active_branch(repo):
"""Returns the active branch of the given local repository.
Args:
repo(git.Repo): Git Repo instance
Returns:
str: The name of the active branch.
"""
return repo.active_branch.name | bigcode/self-oss-instruct-sc2-concepts |
def df_set_diag(df, val, copy=True):
"""
Sets the diagonal of a dataframe to a value. Diagonal in this case is anything where row label == column label.
:param df: pd.DataFrame
DataFrame to modify
:param val: numeric
Value to insert into any cells where row label == column label
:pa... | bigcode/self-oss-instruct-sc2-concepts |
def normalized_intersection(bbox1, bbox2):
"""
Intersection that is normalized with respect to the first bbox.
:param bbox1: bounding boxes in the format [left, top, right, bottom]
and shape [4]; dtype has to be np.ndarray or list
:param bbox2: bounding boxes in the format [left, top, right, bot... | bigcode/self-oss-instruct-sc2-concepts |
def get_token_index(text, offset, tokens):
"""
>>> text = "A quick brownDasheyBhgx fox jump's over the lazy dog"
>>> tokens = ['[CLS]', 'a', 'quick', 'brown', '##das', '##hey', '##bh',
... '##g', '##x', 'fox', 'jump', "'", 's', 'over', 'the', 'lazy',
... 'dog', '[SEP]']
>>> t... | bigcode/self-oss-instruct-sc2-concepts |
def const(v):
"""Return the value passed."""
def f(data):
return v
return f | bigcode/self-oss-instruct-sc2-concepts |
import torch
def LSIGF_DB(h, S, x, b=None):
"""
LSIGF_DB(filter_taps, GSO, input, bias=None) Computes the output of a
linear shift-invariant graph filter (graph convolution) on delayed
input and then adds bias.
Denote as G the number of input features, F the number of output features,
... | bigcode/self-oss-instruct-sc2-concepts |
def pad(source: str, pad_len: int, align: str) -> str:
"""Return a padded string.
:param source: The string to be padded.
:param pad_len: The total length of the string to be returned.
:param align: The alignment for the string.
:return: The padded string.
"""
return "{s:{a}{n}}".format(s=s... | bigcode/self-oss-instruct-sc2-concepts |
import configparser
def read_setup_cfg(fname="setup.cfg"):
"""
Read the setup.cfg file into a dictionary.
"""
config = configparser.ConfigParser()
# Use read_file to get a FileNotFoundError if setup.cfg is missing. Using
# read returns an empty config instead of raising an exception.
with ... | bigcode/self-oss-instruct-sc2-concepts |
def removeListDups(base_list,remove_list):
"""Remove items from one list from another
Args:
base_list (list): list to keep the non-duplicated values from
remove_list (list): list of items to remove from base_list
Returns:
list : list of items in base_list NOT in remove_list
"""... | bigcode/self-oss-instruct-sc2-concepts |
def test_cache_memoize_arg_normalization(cache):
"""
Test taht cache.memoize() normalizes argument ordering for positional and keyword
arguments.
"""
@cache.memoize(typed=True)
def func(a, b, c, d, **kargs):
return (a, b, c, d)
for args, kargs in (
((1, 2, 3, 4), {"e": 5}),... | bigcode/self-oss-instruct-sc2-concepts |
def to_integer(obj):
"""Converts `obj` to an integer.
Args:
obj (str|int|float): Object to convert.
Returns:
int: Converted integer or ``0`` if it can't be converted.
Example:
>>> to_integer(3.2)
3
>>> to_integer('3.2')
3
>>> to_integer('3.9')
... | bigcode/self-oss-instruct-sc2-concepts |
def get_clinvar_accession_from_clinvarset(elem):
"""
Gets the Clinvar accession from a ClinVarSet element
:param elem: ClinVarSet Element
:return: ClinVar Accession
"""
## elem.xpath("//ClinVarAccession")[0].attrib['Acc'] ## this only works sometimes
try:
# return elem.xpath("//Clin... | bigcode/self-oss-instruct-sc2-concepts |
def children(node):
"""Returns a list containing all child nodes
of a Traversable type node. Returns empty list
when the node has no children. Used by BF/DF/Flat
iterative tree visitor functions."""
try:
k = node.getChildren()
return k
except:
return [] | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
from typing import Tuple
def divmod_int(numerator: Union[int, float], denominator: Union[int, float]) -> Tuple[int, int]:
"""Return the result of divmod, as a tuple of integers."""
quotient, remainder = divmod(numerator, denominator)
return int(quotient), int(remainder) | bigcode/self-oss-instruct-sc2-concepts |
import string
def clean_tokens(tokens):
"""Tokens are lower-cased, stripped of punctuation, and filtered for NULL."""
tokens = [w.lower().strip(string.punctuation) for w in tokens]
tokens = [w for w in tokens if w]
tokens = tokens or ["NULL"]
return tokens | bigcode/self-oss-instruct-sc2-concepts |
def class_mix_data(data):
"""
> input:
[[label, ...], [label, ...], [label, ...], ... ]
> output:
[ [[label, ...], [label, ...], [label, ...], ... ], <- class 0
[[label, ...], [label, ...], [label, ...], ... ], <- class 1
.
.
.
[[label, ...], [label, ...], ... | bigcode/self-oss-instruct-sc2-concepts |
def show_in_nav_for(level=0, icon=None):
"""
Use as a class / method decorator to flag an exposed object in the site navigation
@show_in_nav_for(users.guest)
@expose
class SubPage:
...
"""
def decorate(f):
f.show_in_nav = level
f.icon = icon
f.exposed = True
... | bigcode/self-oss-instruct-sc2-concepts |
def get_sha1_or_none(repo, ref):
"""Return string of the ref's commit hash if valid, else None.
:repo: a callable supporting git commands, e.g. repo("status")
:ref: string of the reference to parse
:returns: string of the ref's commit hash if valid, else None.
"""
commit = repo("rev-parse", "-... | bigcode/self-oss-instruct-sc2-concepts |
def anchor_in_soup(soup, anchor_name):
"""Find if a given anchor id is present in a HTML data"""
return bool(soup.find("", {"id" : anchor_name})) or bool(soup.find("", {"name": anchor_name})) | bigcode/self-oss-instruct-sc2-concepts |
def is_dualtor(tbinfo):
"""Check if the testbed is dualtor."""
return "dualtor" in tbinfo["topo"]["name"] | bigcode/self-oss-instruct-sc2-concepts |
def read_lines(path):
"""
Reads lines from file into list with leading and trailing whitespace removed.
"""
with path.open() as f:
lines = f.readlines()
lines = [l.strip() for l in lines]
return lines | bigcode/self-oss-instruct-sc2-concepts |
def get_no_aliens(sett, alien_width):
"""Determine the number of aliens that fit in a row.
Spacing between each alien is equal to half alien width"""
available_space_x = sett.screen_width - 1.5 * alien_width
no_of_aliens = int(available_space_x / (1.5 * alien_width))
return no_of_aliens | bigcode/self-oss-instruct-sc2-concepts |
def greet(adventurer: str) -> str:
"""
returns a greeting string that greets the title cased adventurers name
>>> greet('bob')
'Hello Brave Bob'
:param adventurer: the name of the adventurer to greet
:return: a greeting "Hello ..."
"""
return f"Hello Brave {adventurer.title()}" | bigcode/self-oss-instruct-sc2-concepts |
import re
def process_tex(lines):
"""
Remove unnecessary section titles from the LaTeX file.
"""
new_lines = []
for line in lines:
line = re.sub(r'^\s*\\strong{See Also:}\s*$', r'\paragraph{See Also}', line)
if (line.startswith(r'\section{sknano.')
or line.startswith(r... | bigcode/self-oss-instruct-sc2-concepts |
def split_csp_str(val):
""" Split comma separated string into unique values, keeping their order.
:returns: list of splitted values
"""
seen = set()
values = val if isinstance(val, (list, tuple)) else val.strip().split(',')
return [x for x in values if x and not (x in seen or seen.add(x))] | bigcode/self-oss-instruct-sc2-concepts |
def parse_incar(incar):
"""
Parameters
----------
incar: str
Path to VASP incar
Returns
-------
encut: int
Energy Cutoff
"""
encut = None
with open(incar, "r") as f:
for line in f:
if "ENCUT" in line:
encut = float(line.split("... | bigcode/self-oss-instruct-sc2-concepts |
def find_indices(nums, val):
"""Given a list, find the two indices that sum to a specific value"""
for i, outer_num in enumerate(nums):
for j, inner_num in enumerate(nums):
if outer_num + inner_num == val:
return (i, j)
return False | bigcode/self-oss-instruct-sc2-concepts |
def expandtabs(s, tabstop=8, ignoring=None):
"""Expand tab characters `'\\\\t'` into spaces.
:param tabstop: number of space characters per tab
(defaults to the canonical 8)
:param ignoring: if not `None`, the expansion will be "smart" and
go from one tabstop to th... | bigcode/self-oss-instruct-sc2-concepts |
def getOutputShape(model, index = -1):
"""
Gets the shape of a single output. For compatibility returns the shape
of the last output if there are multiple outputs.
Return:
Numeric dimensions, omits dimensions that have no value. eg batch
size.
"""
s = []
... | bigcode/self-oss-instruct-sc2-concepts |
def dice_outcome_extractor(run):
"""Return the atmospheric temperature of the final state."""
return run.states[-1].TATM | bigcode/self-oss-instruct-sc2-concepts |
import random
def random_threshold_sequence(n,p,seed=None):
"""
Create a random threshold sequence of size n.
A creation sequence is built by randomly choosing d's with
probabiliy p and i's with probability 1-p.
s=nx.random_threshold_sequence(10,0.5)
returns a threshold sequence of length 10... | bigcode/self-oss-instruct-sc2-concepts |
def is_np_chunk(tree):
"""
Returns true if given tree is a NP chunk.
A noun phrase chunk is defined as any subtree of the sentence
whose label is "NP" that does not itself contain any other
noun phrases as subtrees.
"""
if tree.label() == 'NP' and \
not list(tree.subtrees(lambda ... | bigcode/self-oss-instruct-sc2-concepts |
def linear(x, root):
""" Returns a decay factor based on the linear function
.. math::
f(x) = \\begin{cases} -x/root + 1 & \\mbox{if} x < root; \\\\
0 & otherwise.
\\end{cases}
:param x: The function argument *x*.
... | bigcode/self-oss-instruct-sc2-concepts |
def get_flows_from_logbook(logbook, persistence_backend):
"""
Gets all flows for a logbook
:param obj logbook: A TaskFlow logbook
:param obj persistence_backend: A connection to the persistence backend
:return iter[obj, ..] all_flows: An iterable of flow objects
"""
return persistence_backen... | bigcode/self-oss-instruct-sc2-concepts |
def to_layer(operation_list, num_wires):
"""Convert the given list of operations to a layer.
Args:
operation_list (list[~.Operation]): List of Operations in the layer
num_wires (int): Number of wires in the system
Returns:
list[Union[~.Operation,None]]: The corresponding layer
... | bigcode/self-oss-instruct-sc2-concepts |
def add_ids(edges):
"""
Adds ids to edges missing ids
"""
for e in edges:
if 'id' not in e:
e['id'] = e['subject'] + '-' + e['predicate'] + '-' + e['object']
return edges | bigcode/self-oss-instruct-sc2-concepts |
from typing import Hashable
def _key_from_dict(d) -> Hashable:
"""Convert nested dict into a frozen, hashable structure usable as a key."""
if isinstance(d, dict):
return frozenset((k, _key_from_dict(v)) for k, v in d.items())
elif isinstance(d, (list, tuple)):
return tuple(map(_key_from_dict, d))
els... | bigcode/self-oss-instruct-sc2-concepts |
def compute_optalpha(norm_r, norm_Fty, epsilon, comp_alpha=True):
"""
Compute optimal alpha for WRI
Parameters
----------
norm_r: Float
Norm of residual
norm_Fty: Float
Norm of adjoint wavefield squared
epsilon: Float
Noise level
comp_alpha: Bool
Whether ... | bigcode/self-oss-instruct-sc2-concepts |
def _return_ordered_config(unordered_config: dict, template_config: dict) -> dict:
"""Orders the keys in unordered_config according to the order in template_config.
Note this function assumes all keys in both dictionaries are identical,
including all nested dictionaries.
"""
# create a dictionary ... | bigcode/self-oss-instruct-sc2-concepts |
def num_to_bitstring(num, length):
"""Returns string of bits from number, truncated at length.
Algorithm: While the number storing the bitvector is greater than
zero, find the last digit as (num mod 2) and then bit-shift the string to
the right to delete the last digit. Add the digits into a string fr... | bigcode/self-oss-instruct-sc2-concepts |
import re
def embolden(word, quote):
"""Make word bold in quote, regardless of but maintaining case"""
return re.sub(r"(" + word + r")", r"<b>\1</b>", quote, flags=re.I) | bigcode/self-oss-instruct-sc2-concepts |
def get_function_name(stack_outputs, function_logical_id):
"""Obtains the function name from given stack outputs.
:type stack_outputs: dict
:param stack_outputs: CloudFormation stack outputs.
:type function_logical_id: str
:param function_logical_id: logical ID of the function resource.
:rtyp... | bigcode/self-oss-instruct-sc2-concepts |
def header_population(headers):
"""make column headers from a list
:param headers: list of column headers
:return: a list of dictionaries
"""
return [{'id': field, 'name': field, 'field': field, 'sortable': True} for field in headers] | bigcode/self-oss-instruct-sc2-concepts |
def getRawTimes(grid):
""" A helper function to get all times inside a grid, returns a list of times
"""
times=[]
for i in range(grid.getDomainSet().getLength()):
times.append(grid.getDomainSet()[i].getValue())
return times | bigcode/self-oss-instruct-sc2-concepts |
def Activate(line):
"""Checks if we are reading nodes, elements, or something else
Parameters
----------
line : string
The line to check for activation
Returns
-------
active : string
'nodes' if we are going to read nodes, 'elems' if we are going to read
... | bigcode/self-oss-instruct-sc2-concepts |
import json
def prettydump(pdu_obj):
"""Unpack PDU dictionary and dump it as a JSON formatted string"""
return json.dumps(pdu_obj, indent=4, sort_keys=True) | bigcode/self-oss-instruct-sc2-concepts |
def allof(*items):
""" allof(*items) → Return the result of “all(…)” on all non-`None` arguments """
return all(item for item in items if item is not None) | bigcode/self-oss-instruct-sc2-concepts |
def negative_dice_parse(dice: str) -> str:
"""
:param dice: Formatted string, where each line is blank or matches
t: [(t, )*t]
t = (0|D|2T|FT|2F|F|T)
(note: T stands for Threat here)
:return: Formatted string matching above, except tokens are r... | bigcode/self-oss-instruct-sc2-concepts |
def bridge_h_1(current_state, goal_state):
"""
adds up the amount of time remaining on the left side
:param current_state:
:param goal_state:
:return:
"""
h = 0
for x in current_state.state[0].values():
h += x
return h | bigcode/self-oss-instruct-sc2-concepts |
from typing import OrderedDict
def merge_list(col1, col2):
"""
Given two sequences col1 and col2, returns a list of the
items in them, in order, omitting any from col2 that are also
in col1.
"""
cs = OrderedDict()
for c in col1:
cs[c] = 0.0
for c in col2:
cs[c] = 0.0
... | bigcode/self-oss-instruct-sc2-concepts |
def show_seconds(value, show_units):
"""Return nicely formatted seconds."""
if value is None:
return "unknown"
if show_units:
return f"{value} s"
return value | bigcode/self-oss-instruct-sc2-concepts |
def calculate_n50(contigs, assembly_size):
"""Calculate the n50 of the assembly."""
n50_stats = {'n50': 0, 'l50': 0}
total_length = 0
total_contigs = 0
for length in contigs:
total_length += length
total_contigs += 1
if total_length >= assembly_size//2:
n50_stats[... | bigcode/self-oss-instruct-sc2-concepts |
def write_iter_in_file(path_to_file_write, iterable, fun_prepline=None, mode="w"):
"""
Write a iterable as text line in file
>>> mi_iterable = ["line1", "line2", "line3"]
>>> write_iter_in_file("file.txt", mi_iterable)
3
:param path_to_file_write: path file where write
:param iterable: Ite... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import DefaultDict
def __distinct_elems(mols: List[DefaultDict[str, int]]) -> List[str]:
"""Get the distinct elements that form the molecules."""
elems = set()
for mol in mols:
for key in mol:
elems.add(key)
return list(elems) | bigcode/self-oss-instruct-sc2-concepts |
import random
def delay_exponential(base, growth_factor, attempts):
"""Calculate time to sleep based on exponential function.
The format is::
base * growth_factor ^ (attempts - 1)
If ``base`` is set to 'rand' then a random number between
0 and 1 will be used as the base.
Base must be gr... | bigcode/self-oss-instruct-sc2-concepts |
def implies(a: bool, b: bool) -> bool:
"""Implication (IF...THEN)"""
return (not a) or b | bigcode/self-oss-instruct-sc2-concepts |
def _get_acq_time(start, default_value=-1):
"""Private helper function to extract the heuristic count time
The SPEC-style plans inject a heuristic 'count_time' (which has
different meanings in different contexts) as a top-level key in the
RunStart document.
Parameters
----------
start : Do... | bigcode/self-oss-instruct-sc2-concepts |
def _DictToTuple(to_sort):
"""Converts a dictionary into a tuple of keys sorted by values.
Args:
to_sort: A dictionary like object that has a callable items method.
Returns:
A tuple containing the dictionary keys, sorted by value.
"""
items = to_sort.items()
items.sort(key=lambda pair: pair[1])
... | bigcode/self-oss-instruct-sc2-concepts |
def file_contains_doctests(path):
"""Scan a python source file to determine if it contains any doctest examples.
Parameters
----------
path : str
Path to the module source file.
Returns
-------
flag : bool
True if the module source code contains doctest examples.
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def parse_hex_color(color):
"""Parses a hex format color string, i.e. #ccc or #12ab34, into an (r, g, b) tuple."""
color = color.strip('#')
if len(color) == 3:
color = ''.join(ch*2 for ch in color)
if len(color) == 6:
r = int(color[0:2], base=16) / 255
g = int(color[2:4], base=16... | bigcode/self-oss-instruct-sc2-concepts |
def cal_intersection(points):
"""
Calculate the intersection of diagonals.
x=[(x3-x1)(x4-x2)(y2-y1)+x1(y3-y1)(x4-x2)-x2(y4-y2)(x3-x1)]/[(y3-y1)(x4-x2)-(y4-y2)(x3-x1)]
y=(y3-y1)[(x4-x2)(y2-y1)+(x1-x2)(y4-y2)]/[(y3-y1)(x4-x2)-(y4-y2)(x3-x1)]+y1
:param points: (x1, y1), (x2, y2), (x3, y3), (x4, y4).
... | bigcode/self-oss-instruct-sc2-concepts |
def alignValue(value, align):
"""
Align a value to next 'align' multiple.
>>> alignValue(31, 4)
32
>>> alignValue(32, 4)
32
>>> alignValue(33, 4)
36
Note: alignValue(value, align) == (value + paddingSize(value, align))
"""
if value % align != 0:
return value + alig... | bigcode/self-oss-instruct-sc2-concepts |
def make_list(value):
"""Return a list of items from a comma-separated string.
Surrounding whitespace will be stripped from the list items. If the
provided string is empty, an empty list will be returned. This function
will also accept the value None and return an empty list.
"""
if value is No... | bigcode/self-oss-instruct-sc2-concepts |
def nestedmap(f, args, type=list):
"""
Map `f` over `args`, which contains elements or nested lists
"""
result = []
for arg in args:
if isinstance(arg, type):
result.append(list(map(f, arg)))
else:
result.append(f(arg))
return result | bigcode/self-oss-instruct-sc2-concepts |
import math
def part_1(memory_loc):
"""Get the manhattan distance from a location to the centre of a
(1-indexed) spiral array
Arguments
---------
memory_loc : int, the location of the starting point. Locations are
numbered anticlockwise from the centre, and head right first, e.g.
... | bigcode/self-oss-instruct-sc2-concepts |
def parserDateToString(date):
"""Funkcja zmieniająca obiekt datetime.date na string postaci YYYYMMDD"""
date = str(date)
date = date.replace('-','')
return date | bigcode/self-oss-instruct-sc2-concepts |
def rgb_to_hex(rgb):
"""Converts an rgb tuple to hex string for web.
>>> rgb_to_hex((204, 0, 0))
'CC0000'
"""
return ''.join(["%0.2X" % c for c in rgb]) | bigcode/self-oss-instruct-sc2-concepts |
import pytz
def tz_aware(dt, tz):
"""
Ensures that a datetime object is time zone aware.
Only makes changes to naive datetime objects.
:param dt: datetime -- any valid datetime object
:param tz: string in IANA time zone database format -- the timezone to attach to the object
:returns: datetim... | bigcode/self-oss-instruct-sc2-concepts |
def poly_desc(W, b):
"""Creates a string description of a polynomial."""
result = 'y = '
for i, w in enumerate(W):
result += '{:+.2f} x^{} '.format(w, len(W) - i)
result += '{:+.2f}'.format(b[0])
return result | bigcode/self-oss-instruct-sc2-concepts |
def get_prefix(network):
"""Convert network type to prefix of address
:param network: testnet or mainnet
:type network: str
:returns: tbnb or bnb
"""
return 'tbnb' if network == 'testnet' else 'bnb' | bigcode/self-oss-instruct-sc2-concepts |
def __insert_color_custom(txt, s, c):
"""insert HTML span style into txt. The span will change the color of the
text located between s[0] and s[1]:
txt: txt to be modified
s: span of where to insert tag
c: color to set the span to"""
return txt[:s[0]] + '<span style="font-weight: bold;color: {0}... | bigcode/self-oss-instruct-sc2-concepts |
def normURLPath(path):
"""
Normalise the URL path by resolving segments of '.' and '..'.
"""
segs = []
pathSegs = path.split('/')
for seg in pathSegs:
if seg == '.':
pass
elif seg == '..':
if segs:
segs.pop()
else:
seg... | bigcode/self-oss-instruct-sc2-concepts |
def compose1(f, g):
"""Return a function that composes f and g.
f, g -- functions of a single argument
"""
def h(x):
return f(g(x))
return h | bigcode/self-oss-instruct-sc2-concepts |
def get_messages_per_weekday(msgs):
"""Gets lists of messages for each day of the week (7 lists in a dictionary total).
Args:
msgs (list of MyMessage objects): Messages.
Returns:
A dictionary such as:
{
day_of_the_week (int 0-6): list off all messages sent on th... | bigcode/self-oss-instruct-sc2-concepts |
def aq(string):
"""
Add the quotes " characters around a string if they are not already there.
Parameters
----------
string : str
just a string to be formatted
Returns
-------
str
a string with " character at the beginning and the end
"""
tmp = string
if n... | bigcode/self-oss-instruct-sc2-concepts |
def _is_valid_back_ref(index):
"""
Helper method used to ensure that we do not use back-reference values
that would produce illegal byte sequences (ones with byte 0xFE or 0xFF).
Note that we do not try to avoid null byte (0x00) by default, although it would be technically possible as well.
:param in... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def edge_loss(disp, img):
"""Computes the smoothness loss for a disparity image
The color image is used for edge-aware smoothness
"""
grad_disp_x = torch.abs(disp[:, :, :, :-1] - disp[:, :, :, 1:])
grad_disp_y = torch.abs(disp[:, :, :-1, :] - disp[:, :, 1:, :])
grad_img_x = torch... | bigcode/self-oss-instruct-sc2-concepts |
def event_split(string, event_type):
"""Return a list of event type and event action.
Args:
string (str): The supplied string that will be splitted.
event_type (str): The event type (execute, log, set, etc).
Returns:
list: A list of the splitted string
Examples:
>>> is... | bigcode/self-oss-instruct-sc2-concepts |
def format_time( seconds ):
"""
Formats the time, in seconds, to a nice format. Unfortunately, the :py:class:`datetime <datetime.datetime>` class is too unwieldy for this type of formatting. This code is copied from :py:meth:`deluge's format_time <deluge.ui.console.utils.format_utils.format_time>`.
:param ... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
from pydantic import BaseModel # noqa: E0611
import importlib
def build_model(model: Any, backend: str) -> BaseModel:
"""
Build a correct model wrapper given the backend
:param model: any neural network models, see backend folder for more
details
:param backen... | bigcode/self-oss-instruct-sc2-concepts |
import re
def version_greater_or_equal_than(version_str, other_version_str):
""" Checks if a version number is >= than another version number
Version numbers are passed as strings and must be of type "N.M.Rarb" where N, M, R
are non negative decimal numbers < 1000 and arb is an arbitrary string.
For ... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def fixture_family_tag_names(vcf_tag_name: str, family_tag_name: str) -> List[str]:
"""Return a list of the family tag names"""
return [vcf_tag_name, family_tag_name] | bigcode/self-oss-instruct-sc2-concepts |
import math
def Percentile(values, percentile):
"""Returns a percentile of an iterable of values. C = 1/2
The closest ranks are interpolated as in "C = 1/2" in:
https://en.wikipedia.org/wiki/Percentile
"""
values = sorted(values)
index = len(values) * percentile - 0.5
floor = max(math.floor(index), 0... | bigcode/self-oss-instruct-sc2-concepts |
import math
def distance(p0, p1):
"""
returns distance between two pubg points in meters
:param p0: point 1
:param p1: point 2
:return:
"""
return math.sqrt((p0[0] - p1[0]) ** 2 + (p0[1] - p1[1]) ** 2 +
(p0[2] - p1[2]) ** 2) / 100 | bigcode/self-oss-instruct-sc2-concepts |
def ask_for_continuation(iteration: int) -> bool:
"""
Ask the user if we can proceed to execute the sandbox.
:param iteration: the iteration number.
:return: True if the user decided to continue the execution, False otherwise.
"""
try:
answer = input(
"Would you like to proc... | 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.