seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def _gr_text_to_no(l, offset=(0, 0)):
"""
Transform a single point from a Cornell file line to a pair of ints.
:param l: Line from Cornell grasp file (str)
:param offset: Offset to apply to point positions
:return: Point [y, x]
"""
x, y = l.split()
return [int(round(float(y))) - offset[0], int(round(flo... | bigcode/self-oss-instruct-sc2-concepts |
def _PyDate_FromTimestamp(space, w_type, w_args):
"""Implementation of date.fromtimestamp that matches the signature for
PyDateTimeCAPI.Date_FromTimestamp"""
w_method = space.getattr(w_type, space.newtext("fromtimestamp"))
return space.call(w_method, w_args) | bigcode/self-oss-instruct-sc2-concepts |
import time
def beats(text):
"""- Gets the current time in .beats (Swatch Internet Time)."""
if text.lower() == "wut":
return "Instead of hours and minutes, the mean solar day is divided " \
"up into 1000 parts called \".beats\". Each .beat lasts 1 minute and" \
" 26.4 s... | bigcode/self-oss-instruct-sc2-concepts |
def get_frame_interface(pkt):
"""Returns current frame interface id alias.
"""
iface_raw = pkt.frame_info._all_fields['frame.interface_id'].showname_value
ifname = ".".join(iface_raw.split()[1][1:-1].split(".")[:2])
return ifname | bigcode/self-oss-instruct-sc2-concepts |
import re
def norm_key(key_name):
"""
Normalize key names to not have spaces or semi-colons
"""
if key_name:
return re.sub('[;\s]', '_', key_name)
return None | bigcode/self-oss-instruct-sc2-concepts |
import math
def dB(x):
"""Returns the argument in decibels"""
return 20 * math.log10(abs(x)) | bigcode/self-oss-instruct-sc2-concepts |
def normalize_measurement(measure):
"""
Transform a measurement's value, which could be a string, into a real value - like a boolean or int or float
:param measure: a raw measurement's value
:return: a value that has been corrected into the right type
"""
try:
return eval(measure, {}, {}... | bigcode/self-oss-instruct-sc2-concepts |
def generate_entity_results(entity_class, count, **kwargs):
"""
generates entity results with given entity type using given keyword arguments and count.
:param type[BaseEntity] entity_class: entity class type to put in result.
:param int count: count of generated results.
:rtype: list[BaseEntity]
... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def get_iso_time() -> str:
"""
Return the current time in ISO 8601 format.
"""
return datetime.now().isoformat() | bigcode/self-oss-instruct-sc2-concepts |
import ast
from typing import TypeGuard
def _is_ipython_magic(node: ast.expr) -> TypeGuard[ast.Attribute]:
"""Check if attribute is IPython magic.
Note that the source of the abstract syntax tree
will already have been processed by IPython's
TransformerManager().transform_cell.
"""
return (
... | bigcode/self-oss-instruct-sc2-concepts |
def length(vec):
""" returns the length/norm of a numpy array
as the square root of the inner product with itself
"""
return vec.dot(vec) ** 0.5 | bigcode/self-oss-instruct-sc2-concepts |
def box_text(text: str) -> str:
"""
Draws an Unicode box around the original content
Args:
text: original content (should be 1 line and 80 characters or less)
Returns:
A three-line string. Unicode box with content centered.
"""
top = "┌" + "─" * (len(text) + 2) + "┐"
bot =... | bigcode/self-oss-instruct-sc2-concepts |
def strip_position(pos):
"""
Stripes position from +- and blankspaces.
"""
pos = str(pos)
return pos.strip(' +-').replace(' ', '') | bigcode/self-oss-instruct-sc2-concepts |
def index_map(i, d):
"""
The index map used mapping the from 2D index to 1D index
Parameters
----------
i : int, np.array
the index in the 2D case.
d : int
the dimension to use for the 2D index.
Returns
-------
int, np.array
1D index.
"""
return 2 *... | bigcode/self-oss-instruct-sc2-concepts |
def should_run_stage(stage, flow_start_stage, flow_end_stage):
"""
Returns True if stage falls between flow_start_stage and flow_end_stage
"""
if flow_start_stage <= stage <= flow_end_stage:
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
from pathlib import Path
from typing import Tuple
from typing import List
import re
import hashlib
def split_dataset(
root_dir: Union[str, Path], max_uttr_per_class=2 ** 27 - 1
) -> Tuple[List[Tuple[str, str]], List[Tuple[str, str]]]:
"""Split Speech Commands into 3 set.
Args... | bigcode/self-oss-instruct-sc2-concepts |
def get_launch_args(argv, separator=':='):
"""
Get the list of launch arguments passed on the command line.
Return a dictionary of key value pairs for launch arguments passed
on the command line using the format 'key{separator}value'. This will
process every string in the argv list.
NOTE: all ... | bigcode/self-oss-instruct-sc2-concepts |
def _add_months(date, delta):
"""Add months to a date."""
add_years = delta // 12
add_months = delta % 12
return date.replace(year=date.year + add_years,
month=date.month + add_months) | bigcode/self-oss-instruct-sc2-concepts |
def memoized_coin_change(amount, denoms, denoms_length):
"""
Memoized version
Parameters
----------
amount : int
Target amount
denoms : list<int>
denominations
denoms_length : int
number of unique denominations
Returns
-------
int
count of ways
... | bigcode/self-oss-instruct-sc2-concepts |
def _get_error_list(error_code):
"""
Get error list.
Args:
error_code (int): The code of errors.
Returns:
list, the error list.
"""
all_error_list = ["nan", "inf", "no_prev_tensor"]
error_list = []
for i, error_str in enumerate(all_error_list):
error = (error_cod... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
import requests
def get_page_text(url: str) -> Optional[str]:
"""
Download complete HTML text for a url
"""
cookies = {"devsite_wall_acks": "nexus-image-tos"}
request = requests.get(url, timeout=10, cookies=cookies)
if request.ok:
return request.text
req... | bigcode/self-oss-instruct-sc2-concepts |
def ssh_cmd_docker_container_exec(
detail, command_on_docker, wait_press_key=None
) -> str:
"""SSH command to execute a command inside a docker containter."""
wait_cmd = ""
if wait_press_key:
wait_cmd = "; echo 'Press a key'; read q"
return (
f"TERM=xterm ssh -t {detail['ec2InstanceI... | bigcode/self-oss-instruct-sc2-concepts |
def safestr(value):
"""
Turns ``None`` into the string "<None>".
:param str value: The value to safely stringify.
:returns: The stringified version of ``value``.
"""
return value or '<None>' | bigcode/self-oss-instruct-sc2-concepts |
def rest_api_parameters(in_args, prefix='', out_dict=None):
"""Transform dictionary/array structure to a flat dictionary, with key names
defining the structure.
Example usage:
>>> rest_api_parameters({'courses':[{'id':1,'name': 'course1'}]})
{'courses[0][id]':1,
'courses[0][name]':'course1'}
... | bigcode/self-oss-instruct-sc2-concepts |
def process_input(input: list[list[str]]) -> dict:
"""Convert the input data structure (lists of pairs of caves that are connected)
into a dict where each key is a cave and the corresponding value is a list of
all the caves it is contected to.
"""
input_processed = {}
cave_pairs = []
for ... | bigcode/self-oss-instruct-sc2-concepts |
import socket
def port_connected(port):
"""
Return whether something is listening on this port
"""
s = socket.socket()
s.settimeout(5)
try:
s.connect(("127.0.0.1", port))
s.close()
return True
except Exception:
return False | bigcode/self-oss-instruct-sc2-concepts |
import operator
def le(n: float):
""" assertsion function to validate target value less or equal than n
"""
def wrapper(x):
return operator.le(x, n)
return wrapper | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
import typing
from typing import Union
def deannotate(annotation: Any) -> tuple[Any]:
"""Returns type annotations as a tuple.
This allows even complicated annotations with Union to be converted to a
form that fits with an isinstance call.
Args:
annotation (Any): ty... | bigcode/self-oss-instruct-sc2-concepts |
import re
def template_to_regex(template):
"""Convert a string template to a parsable regular expression.
Given a data_path_format string template, parse the template into
a parsable regular expression string for extracting each %VAR%
variable.
Supported %VAR% variables:
* %EXPE... | bigcode/self-oss-instruct-sc2-concepts |
def calculate_points_for_street(street):
"""
Calculates the points for a given street
:param street: List of chips, that can be placed
:return: int with points for street
"""
points = 0
for chip in street:
# print(chip[0])
points += chip[0]
return points | bigcode/self-oss-instruct-sc2-concepts |
import re
def parse_show_udld_interface(raw_result):
"""
Parse the 'show udld interface {intf}' command raw output.
:param str raw_result: vtysh raw result string.
:rtype: dict
:return: The parsed result of the show udld command in a \
dictionary of the form:
::
{
... | bigcode/self-oss-instruct-sc2-concepts |
def remove_prefix(string: str, prefix: str) -> str:
"""
Removes a prefix substring from a given string
Params:
- `string` - The string to remove the prefix from
- `prefix` - The substring to remove from the start of `string`
Returns:
A copy of `string` without the given `prefix`
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def pgo_stage(stage):
"""
Returns true if LLVM is being built as a PGO benchmark
:return: True if LLVM is being built as a PGO benchmark, false if not
"""
return stage == "pgo" | bigcode/self-oss-instruct-sc2-concepts |
def ReadGoldStandard(gold_file):
"""Read in gold standard data."""
fp = open("../test_data/gold_data/%s" % gold_file, "rb")
gold_content = fp.read()
fp.close()
return gold_content | bigcode/self-oss-instruct-sc2-concepts |
import random
def interchanging_mutation(genome):
"""Performs Interchanging Mutation on the given genome. Two position
are randomly chosen and they values corresponding to these positions
are interchanged.
Args:
genome (required): The genome that is to be mutated.
Returns:
The mu... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def generate_numbers(parallel_steps: int) -> List[int]:
"""Generate a list of numbers from 0 to 'parallel_steps'."""
numbers = [i for i in range(parallel_steps)]
print(f"Numbers: {numbers}")
return numbers | bigcode/self-oss-instruct-sc2-concepts |
def _multi_line(in_string):
"""true if string has any linefeeds"""
return "\n" in str(in_string) | bigcode/self-oss-instruct-sc2-concepts |
def filter_values(values, **wanted):
"""
Return a list of desired Value objects.
:param networks:
list of Value dicts
:param wanted:
kwargs of field/value to filter on
"""
ret = []
for v in values:
if all(v.get(field) == value for field, value in wanted.items()):
... | bigcode/self-oss-instruct-sc2-concepts |
def BuildDtd(desc_json):
"""Create a list out of a single detailed timing descriptor dictionary.
Args:
desc_json: The dictionary of a single detailed timing descriptor info.
Returns:
A list of 18 bytes representing a single detailed timing descriptor.
"""
d = [0] * 18
# Set pixel ... | bigcode/self-oss-instruct-sc2-concepts |
def to_list(dataseq):
"""Converts a ctypes array to a list."""
return list(dataseq) | bigcode/self-oss-instruct-sc2-concepts |
def parse_top_output(out):
"""
Parses the output of the Docker CLI 'docker top <container>'. Note that if 'ps' output columns are modified and
'args' (for the command) is anywhere but in the last column, this will not parse correctly. However, the Docker API
produces wrong output in this case as well.
... | bigcode/self-oss-instruct-sc2-concepts |
def grep_init_lr(starting_epoch, lr_schedule):
"""
starting_epoch : starting epoch index (1 based)
lr_schedule : list of [(epoch, val), ...]. It is assumed to be sorted
by epoch
return
init_lr : learning rate at the starting epoch
"""
init_lr = lr_schedule[0][1]
for e, v in lr_... | bigcode/self-oss-instruct-sc2-concepts |
def _random_subset_weighted(seq, m, fitness_values, rng):
"""
Return m unique elements from seq weighted by fitness_values.
This differs from random.sample which can return repeated
elements if seq holds repeated elements.
Modified version of networkx.generators.random_graphs._random_subset
""... | bigcode/self-oss-instruct-sc2-concepts |
def add_tag(tag: str, s: str) -> str:
""" Adds a tag on either side of a string. """
return "<{}>{}</{}>".format(tag, s, tag) | bigcode/self-oss-instruct-sc2-concepts |
import ast
def ast_expr_from_module(node):
"""
Get the `ast.Expr` node out of a `ast.Module` node.
Can be useful when calling `ast.parse` in `'exec'` mode.
"""
assert isinstance(node, ast.Module)
assert len(node.body) == 1
assert isinstance(node.body[0], ast.Expr)
return node.body[0].... | bigcode/self-oss-instruct-sc2-concepts |
import math
def dInd_calc(TNR, TPR):
"""
Calculate dInd (Distance index).
:param TNR: specificity or true negative rate
:type TNR : float
:param TPR: sensitivity, recall, hit rate, or true positive rate
:type TPR : float
:return: dInd as float
"""
try:
result = math.sqrt((... | bigcode/self-oss-instruct-sc2-concepts |
import unicodedata
def normalize_unicode(text):
"""
Normalizes a string by converting Unicode characters to their simple
form when possible. This is done by using Normal Form KC of a string.
For example, the non-breaking space character (xa0) will be converted
to a simple space character.
Refe... | bigcode/self-oss-instruct-sc2-concepts |
import math
def wgs_to_tile( latitude, longitude, zoom):
"""Get google-style tile cooridinate from geographical coordinate
Note:
Note that this will return a tile coordinate. and a tile coordinate
is located at (0,0) or origin of a tile.
all tiles are 256x256. there are as many gps locations in... | bigcode/self-oss-instruct-sc2-concepts |
def mils(value):
"""Returns number in millions of dollars"""
try:
value = float(value) / 1000000
except (ValueError, TypeError, UnicodeEncodeError):
return ''
return '${0:,}M'.format(value) | bigcode/self-oss-instruct-sc2-concepts |
def get_integer(prompt):
"""
Get an integer from standard input (stdin).
The function keep looping and prompting until a valid
`int` is entered.
:param prompt: The string user will see
when prompted for input
:return: the `int` user has entered
"""
while True:
temp = in... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Dict
def dedup(l: List[str], suffix: str = "__", case_sensitive: bool = True) -> List[str]:
"""De-duplicates a list of string by suffixing a counter
Always returns the same number of entries as provided, and always returns
unique values. Case sensitive compariso... | bigcode/self-oss-instruct-sc2-concepts |
def cm2inch(*tupl):
"""
Convert a value or tuple of values from cm
to inches.
Source: https://stackoverflow.com/a/22787457
Input
---
tupl : float, int or tuple of arbitrary size
Values to convert
Returns
---
Converted values in inches.
"""
inch = 2.54
if is... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def directional_derivatives(lin_op, directions, device):
"""``lin_op`` represents a curvature matrix (either ``GGNLinearOperator`` or
``HessianLinearOperator`` from ``vivit.hessianfree``). ``directions`` is a
``D x nof_directions`` matrix, where ``nof_directions`` directions are stored
co... | bigcode/self-oss-instruct-sc2-concepts |
def apply_ant_t_delay(scan_rad):
"""Accounts for antenna time delay by extending the scan rad
Gets the "true" antenna radius used during a scan. Assumes ant_rad
is measured from the black-line radius on the plastic antenna stand.
Uses formula described in the M.Sc. thesis of Diego
Rodriguez-Herrera... | bigcode/self-oss-instruct-sc2-concepts |
import math
def compute_mcc(tp, fp, tn, fn):
"""
Compute the Matthew correlation coefficient.
Regarded as a good measure of quality in case of unbalanced classes.
Returns a value between -1 and +1. +1 represents perfect prediction, 0 random, and -1 total disagreement
between prediction and observa... | bigcode/self-oss-instruct-sc2-concepts |
def clean_text(text, patterns):
"""
Applies the given patterns to the input text. Ensures lower-casing of all text.
"""
txt = text
for pattern in patterns:
txt = pattern[0].sub(pattern[1], txt)
txt = ''.join([letter for letter in txt if (letter.isalnum() or letter.isspace())])
retur... | bigcode/self-oss-instruct-sc2-concepts |
def rk4_step(f, y, t, dt, params):
""" Returns the fourth order runge-kutta approximation of the change in `y` over the
timestep `dt`
Parameters
----------
f (callable): accepts `y`, `t` and all of the parameters in `params`
y (ndarray or float): current system stat... | bigcode/self-oss-instruct-sc2-concepts |
def get_incremental_iteration_dets(for_el):
"""
Look for the pattern:
pets = ['cat', 'dog']
for i in range(len(pets)):
print(f"My {pets[i]}")
For/target/Name id = i
iter/Call/func/Name id = range
args/Call/func/Name id = len
args/Name i... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
from typing import Tuple
import re
def _parse_addr(addr: str, allow_wildcard: bool = False) -> Optional[Tuple[str, str]]:
"""Safely parse an email, returning first component and domain."""
m = re.match(
(
r'([a-zA-Z0-9\-_\+\.]+)' +
('?' if allow_wild... | bigcode/self-oss-instruct-sc2-concepts |
def prepare_standard_scaler(X, overlap=False, indices=None):
"""Compute mean and standard deviation for each channel.
Parameters
----------
X : np.ndarray
Full features array of shape `(n_samples, n_channels, lookback, n_assets)`.
overlap : bool
If False, then only using the most r... | bigcode/self-oss-instruct-sc2-concepts |
def _list_intersection(list1, list2):
"""Compute the list of all elements present in both list1 and list2.
Duplicates are allowed. Assumes both lists are sorted."""
intersection = []
pos1 = 0
pos2 = 0
while pos1 < len(list1) and pos2 < len(list2):
val1 = list1[pos1]
val2 = list... | bigcode/self-oss-instruct-sc2-concepts |
import io
def read_input(input_file):
""" Read OpenAssessIt .md file """
if input_file:
if type(input_file) is str:
with io.open(input_file, encoding='utf-8') as stream:
return stream.read() | bigcode/self-oss-instruct-sc2-concepts |
def caesar(shift, data, shift_ranges=('az', 'AZ')):
"""
Apply a caesar cipher to a string.
The caesar cipher is a substition cipher where each letter in the given
alphabet is replaced by a letter some fixed number down the alphabet.
If ``shift`` is ``1``, *A* will become *B*, *B* will become *C*, ... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
def get_src(src: Optional[str], curie: str):
"""Get prefix of subject/object in the MappingSetDataFrame.
:param src: Source
:param curie: CURIE
:return: Source
"""
if src is None:
return curie.split(":")[0]
else:
return src | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def read_key(location: Path) -> str:
"""
reads a key from a text file containing one line
parameters:
location: Path
the location of the file to read from
"""
with location.open() as file:
return file.read().strip() | bigcode/self-oss-instruct-sc2-concepts |
def readGmtFile(gmtPath):
"""
Read GMT file. In GMT file each line consists of term ID, term name and genes,
all tab separated, no header.
:param str gmtPath: Path of the GMT file
:return: **geneSetsDict** (*dict*) – Dictionary mapping term IDs to set of genes.
:return: **gsIDToGsNameDict** (*dict*) – Dictionary... | bigcode/self-oss-instruct-sc2-concepts |
def second(seq):
"""Returns the second element in a sequence.
>>> second('ABC')
'B'
"""
seq = iter(seq)
next(seq)
return next(seq) | bigcode/self-oss-instruct-sc2-concepts |
def modelform_with_extras(form_cls, **extra_kwargs):
"""
Wrap a ModelForm in a class that creates the ModelForm-instance with
extra paramaters to the constructor.
This function is ment to to be returned by ModelAdmin.get_form in order
to easily supply extra parameters to admin forms.
"""
cl... | bigcode/self-oss-instruct-sc2-concepts |
def _message_from_pods_dict(errors_dict):
"""Form a message string from a 'pod kind': [pod name...] dict.
Args:
- errors_dict: a dict with keys pod kinds as string and values
names of pods of that kind
Returns: a string message
"""
msg_list = [
"{0}: {1}".format(k... | bigcode/self-oss-instruct-sc2-concepts |
import pickle
def pickle_load(fname):
"""
Load data from file using pickle.
"""
# load the model
loaded_object = pickle.load(open(fname, 'rb'))
return loaded_object | bigcode/self-oss-instruct-sc2-concepts |
def ari(b3, b5):
"""
Anthocyanin Reflectance Index (Gitelson, Chivkunova and Merzlyak, 2009).
.. math:: ARI = (1/b3) - (1/b5)
:param b3: Green.
:type b3: numpy.ndarray or float
:param b5: Red-edge 1.
:type b5: numpy.ndarray or float
:returns ARI: Index value
.. Tip::
Kar... | bigcode/self-oss-instruct-sc2-concepts |
import math
def angle_normalize(z):
""" convenience function to map an angle to the range [-pi,pi] """
return math.atan2(math.sin(z), math.cos(z)) | bigcode/self-oss-instruct-sc2-concepts |
import re
def filterBadLibraries(infiles, bad_samples):
"""
Takes a list of infiles, removes those files that match any pattern in list
of bad_samples, returns the filtered list of outfiles
"""
bad_samples = [re.compile(x) for x in bad_samples]
to_remove = []
for inf in infiles:
fo... | bigcode/self-oss-instruct-sc2-concepts |
from functools import reduce
from operator import getitem
def _get_by_path(tree, keys):
"""
Access a nested object in tree by sequence keys.
"""
return reduce(getitem, keys, tree) | bigcode/self-oss-instruct-sc2-concepts |
def analytical_domain(request):
"""
Adds the analytical_domain context variable to the context (used by
django-analytical).
"""
return {'analytical_domain': request.get_host()} | bigcode/self-oss-instruct-sc2-concepts |
def get_start_middle_end_point(line):
"""
Ger three point on line
Transform it to DB.Curve
:param line: Line
:type line: DB.Line
:return: Start, middle and end point of line
:rtype: [DB.XYZ, DB.XYZ, DB.XYZ]
"""
curve = line.GeometryCurve
start = curve.GetEndPoint(0)
end = cu... | bigcode/self-oss-instruct-sc2-concepts |
def eps(machine):
"""Return numeric tolerance for machine"""
return 1e-5 if machine == "x86" else 1e-8 | bigcode/self-oss-instruct-sc2-concepts |
def toint(x):
"""Convert x to interger type"""
try: return int(x)
except: return 0 | bigcode/self-oss-instruct-sc2-concepts |
def _normalize_string_values(field_values):
"""Normalize string values for passed parameters.
Normalizes parameters to ensure that they are consistent across queries where
factors such as case are should not change the output, and therefore not
require additional Telescope queries.
Args:
f... | bigcode/self-oss-instruct-sc2-concepts |
def cmd(required_params, *, needs_reply=False):
"""Create the internal structure describing a command
:param required_params: A list of parameters that must be included with the command.
:param needs_reply: The message needs to be replied to (and must have a uuid)."""
return required_params, needs_repl... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def _chop_model(model, remove=1):
"""
Removes the last layer from the model.
"""
model = torch.nn.Sequential(*(list(model.children())[:-remove]))
return model | bigcode/self-oss-instruct-sc2-concepts |
import json
def json_response(func):
""" Translates results of 'func' into a JSON response. """
def wrap(*a, **kw):
(code, data) = func(*a, **kw)
json_data = json.dumps(data)
return (code, { 'Content-type': 'application/json',
'Content-Length': len(json_data) },... | bigcode/self-oss-instruct-sc2-concepts |
import networkx
def get_superterms(term, hpo_g):
"""
Get all HPO terms upstream of a query term
"""
if hpo_g.nodes.get(term, None) is not None:
superterms = networkx.descendants(hpo_g, term)
superterms = [s for s in superterms if s is not None]
else:
superterms = []
r... | bigcode/self-oss-instruct-sc2-concepts |
def cohens_d_multiple(xbar1, xbar2, ms_with):
"""
Get the Cohen's-d value for a multiple comparison test.
Parameters
----------
> `xbar1`: the mean of the one of the samples in the test.
> `xbar2`: the mean of another of the samples in the test.
> `ms_with`: the mean-squared variability of the samples
Returns... | bigcode/self-oss-instruct-sc2-concepts |
def new_capacity_rule(mod, g, p):
"""
New capacity built at project g in period p.
Returns 0 if we can't build capacity at this project in period p.
"""
return (
mod.GenNewBin_Build[g, p] * mod.gen_new_bin_build_size_mw[g]
if (g, p) in mod.GEN_NEW_BIN_VNTS
else 0
) | bigcode/self-oss-instruct-sc2-concepts |
def find_key(d, nested_key):
"""Attempt to find key in dict, where key may be nested key1.key2..."""
keys = nested_key.split('.')
key = keys[0]
return (d[key] if len(keys) == 1 and key in d else
None if len(keys) == 1 and key not in d else
None if not isinstance(d[key], dict) el... | bigcode/self-oss-instruct-sc2-concepts |
def box_area(box):
"""the area of a box
Args:
box: (left, top, right, bottom)
"""
left, top, right, bottom = box
return (right-left+1) * (bottom-top+1) | bigcode/self-oss-instruct-sc2-concepts |
import re
def is_number(num_str):
"""
Determine whether the string can be converted to a number (int and float)
:param num_str:
:return:
"""
if not re.compile(r"^[-+]?[-0-9]\d*\.\d*|[-+]?\.?[0-9]\d*$").match(num_str):
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
def _form_c_loop_beg(ctx):
"""Form the loop beginning for C."""
return 'for({index}={lower}; {index}<{upper}, {index}++)'.format(
index=ctx.index, lower=ctx.lower, upper=ctx.upper
) + ' {' | bigcode/self-oss-instruct-sc2-concepts |
def _find_known(row):
"""Find variant present in known pathogenic databases.
"""
out = []
clinvar_no = set(["unknown", "untested", "non-pathogenic", "probable-non-pathogenic",
"uncertain_significance", "uncertain_significance", "not_provided",
"benign", "likel... | bigcode/self-oss-instruct-sc2-concepts |
def _advance_years(dt, years):
""" Advance a datetime object by a given number of years.
"""
return dt.replace(year=dt.year + years) | bigcode/self-oss-instruct-sc2-concepts |
def drop_cols_with_null(df):
"""
Drops all columns with null value.
:param df: Data Frame Object
:return: Data Frame Object
"""
return df.dropna(axis=1) | bigcode/self-oss-instruct-sc2-concepts |
def max_sub_array_sum(array):
"""Implementation of the Kadane's algorithm to solve the maximum sub-array
problem in O(n) time and O(1) space. It finds the maximum contiguous subarray
and print its starting and end index. Here it will return the indexes of the
slices between which there is the maximum hy... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
from typing import Dict
def nvl_attribute(name: str, obj: Union[None, Dict], default):
"""
Given an name and a value return
the dictionary lookup of the name
if the value is a dictionary.
The default is returned if not
found.
@param name: name to lookup
@param... | bigcode/self-oss-instruct-sc2-concepts |
def _fk(feature_name, channel, target):
"""Construct a dict key for a feature instance"""
return "{}::{}::{}".format(feature_name, channel, target) | bigcode/self-oss-instruct-sc2-concepts |
import re
def _get_module_doc(module):
"""Get and format the documentation for a module"""
doc = module.__doc__ or ""
# Replace headlines with bold text
doc = re.sub(r"([\w ]+:)\n-+", r"**\1**", doc)
num_hash = min(2, module.__name__.count("."))
return f"{'#' * num_hash} {module.__name__}\n{... | bigcode/self-oss-instruct-sc2-concepts |
def prod(seq):
# pylint: disable=anomalous-backslash-in-string
"""Product of a sequence of numbers.
Parameters
----------
seq : sequence
A sequence of numbers.
Returns
-------
float or int
Product of numbers.
Notes
-----
This is defined as:
.. math::
... | bigcode/self-oss-instruct-sc2-concepts |
def has_source_files( self ):
"""Checks if there are source files added.
:return: bool
"""
return bool(self._source_files) | bigcode/self-oss-instruct-sc2-concepts |
import re
def remove_tags(text):
"""Remove html tags from a string"""
clean = re.compile('<.*?>')
return re.sub(clean, '', text) | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def build_on_conflict_do_nothing_query(
columns: List[str],
dest_table: str,
temp_table: str,
unique_constraint: str,
dest_schema: str = "data",
) -> str:
"""
Construct sql query to insert data originally from `df` into `dest_schema.dest_table` via the
temporary... | 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.