seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def _round(*args, unit=1):
"""Return `args` normalized by `unit` and rounded."""
return tuple(round(x / unit, 3) for x in args) | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Union
from typing import cast
def concat_tokens(tokens: List[Union[str, bool]]) -> str:
"""Concatenate the tokens in the output list.
Parameters
----------
tokens: list
List of string and boolean values
Returns
-------
string
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def box(text: str, lang: str = "") -> str:
"""Put content in a code block
Parameters
----------
text: :class:`str`
The text to place in the code block
lang: :class:`str`
The language for the block
Defaults to an empty string
"""
ret = "```{}\n{}```".format(lang, text... | bigcode/self-oss-instruct-sc2-concepts |
def pulses_plugin(pulses_workbench):
"""Setup the workbench and return the pulses manager plugin.
"""
return pulses_workbench.get_plugin('exopy.pulses') | bigcode/self-oss-instruct-sc2-concepts |
import typing
def py_sorted(numbers: typing.List[int]) -> typing.List[int]:
"""The Python sorted algorithm.
Args:
numbers (typing.List[int]): A list of integers.
Returns:
typing.List[int]: A list of integers ordered from smallest value
to largest value.
"""
return sorted(... | bigcode/self-oss-instruct-sc2-concepts |
def _DetermineNamespacePrefix(unused_url):
"""Returns the SOAP prefix to use for definitions within the given namespace.
Args:
unused_url: string The URL of the namespace. The DFA library doesn't
actually check this value.
Returns:
string The SOAP namespace prefix to use for the given na... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
from typing import Set
def _process_line(line: str) -> Tuple[str, str, Set[str]]:
"""Return the pathway name, url, and gene sets associated.
:param line: gmt file line
:return: pathway name
:return: pathway info url
:return: genes set associated
"""
name, info, *e... | bigcode/self-oss-instruct-sc2-concepts |
def supplies_value(value):
"""Creates a function that returns the specified value when invoked."""
return lambda _: value | bigcode/self-oss-instruct-sc2-concepts |
def calculate_text_size(text):
"""
Simplistic function that calculate a size of a text based on the number and type of characters.
It uses an averaged size for lower/upper-case, digits, spaces and underscores.
It also assumes that the font is using latex "scriptsize" text size.
"""
text_size = 0... | bigcode/self-oss-instruct-sc2-concepts |
def search_linearw(a, x):
"""
Returns the index of x in a if present, None elsewhere.
"""
i = 0
while i < len(a) and a[i] != x:
i += 1
if i == len(a):
return None
else:
return i | bigcode/self-oss-instruct-sc2-concepts |
def equal(a, b):
"""
Case insensitive string compare.
@param a: String to compare.
@param b: String to compare.
@return: True if equal, False if not.
"""
return a.lower() == b.lower() | bigcode/self-oss-instruct-sc2-concepts |
import csv
def parseList(string):
"""
Decomposes strings like '"val1,val2",val3,"val4,val5"'
into a list of strings:
[ 'val1,val2' ,'val3', 'val4,val5' ]
"""
for line in csv.reader([string],delimiter=","):
values = line
#for i,value in enumerate(values):
# values[i] = valu... | bigcode/self-oss-instruct-sc2-concepts |
def _csr_filename(file_prefix):
"""
Construct the name of a file for use in storing a certificate signing
request.
:param str file_prefix: base file name for the certificate signing request
(without the extension)
:return: certificate signing request file name
:rtype: str
"""
re... | bigcode/self-oss-instruct-sc2-concepts |
def _load_version() -> str:
"""Load version from VERSION file"""
from pathlib import Path # pylint: disable=import-outside-toplevel
here = Path(__file__).parent.resolve()
with open(str(here / "VERSION")) as version_file:
return version_file.read().strip() | bigcode/self-oss-instruct-sc2-concepts |
import gzip
def fopen(p, flag="r"):
"""Opens as gzipped if appropriate, else as ascii."""
if p.endswith(".gz"):
if "w" in flag:
return gzip.open(p, "wb")
else:
return gzip.open(p, "rt")
else:
return open(p, flag) | bigcode/self-oss-instruct-sc2-concepts |
import math
def encode_integer_vlq(value: int) -> bytes:
"""Encode an integer with the unsigned VLQ encoding.
:param int value:
The value to encode. Must be a non-negative integer.
:return: ``value`` encoded as a variable-length integer in VLQ format.
:rtype: bytes
"""
if value < 0:
... | bigcode/self-oss-instruct-sc2-concepts |
def bbox_xr(dataset):
"""Get the lon/lat bounding box (minx, miny, maxx, maxy) from an xarray dataset"""
if "lat" in dataset.coords:
y = dataset["lat"]
elif "y" in dataset.coords:
y = dataset["y"]
else:
raise ValueError("dataset {} must contain 'lat' or 'y'".format(dataset))
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
from typing import List
from typing import Dict
def all_checks_passed(runs: Optional[List[Dict]]) -> Optional[bool]:
"""
check whether all checks from a PR head ref have completed and passed
"""
if runs is None:
return None
for c in runs:
if c['status'] ... | bigcode/self-oss-instruct-sc2-concepts |
import re
def txt2list(txt_path=None):
"""
Load txt file and split the sentences into a list of strings
"""
if txt_path is None:
raise ValueError("txt_path must be specified as a named argument! \
E.g. txt_path=../dataset/yourfile.txt")
# Read input sequences from .txt file and pu... | bigcode/self-oss-instruct-sc2-concepts |
def _annotate_point(ax, annot_tuple, xytext=None, **kwargs):
"""
Use ax to annotate a given tuple.
annot_tuple should be (text, (x,y))
but can have additional postional or keyword args
EG: (text, (x,y), {'rotation': 45})
Extra args will be merged with kwargs. This allows for global se... | bigcode/self-oss-instruct-sc2-concepts |
def remove_duplicates(lst: list):
"""Remove duplicates from list while preserving order."""
vals = set()
return [i for i in lst if i not in vals and (vals.add(i) or True)] | bigcode/self-oss-instruct-sc2-concepts |
import copy
def _create_output_header(header):
"""Create the header of the output file from the input file.
Keep most metadata, but remove view, multiView and channel information and add comment.
"""
header = copy.deepcopy(header)
header['channels'] = {}
header.pop('view', None)
header.po... | bigcode/self-oss-instruct-sc2-concepts |
def _common_neighbors(set_one: list, set_two: list) -> int:
"""
Calculate Common neighbors score for input lists
:param set_one: A list of graph nodes -> part one
:param set_two: A list of graph nodes -> part two
:return: Common neighbours score
"""
return len(set(set_one) & set(set_two)) | bigcode/self-oss-instruct-sc2-concepts |
def parse_thumbprint_from_openssl_output(raw_fingerprint):
"""Parses the thumbprint value from the raw OpenSSL output.
Example output from openSSL:
SHA1 Fingerprint=3B:C3:70:46:00:0C:B2:0B:F9:86:98:CF:9D:11:DF:EB:22:B7:41:F5
Returns:
string : The certificate thumbprint.
"""
return raw_... | bigcode/self-oss-instruct-sc2-concepts |
def make_versioned_tag(tag, version):
""" Generate a versioned version of a tag. """
return '%s-%d' % (tag, version) | bigcode/self-oss-instruct-sc2-concepts |
import yaml
def parse_config(config_file):
"""Parses a config file written in the YAML-format.
"""
return yaml.load(config_file, Loader=yaml.FullLoader) | bigcode/self-oss-instruct-sc2-concepts |
def var(image):
"""The variance of pixel intensities"""
return image.var() | bigcode/self-oss-instruct-sc2-concepts |
def PATCH_getControlSurfaceCount(tixi, comp_seg_uid):
"""
Function to get the number of Control Surfaces
Function 'getControlSurfaceCount' returns the number of control surface
(only TED) on a given component segment.
Args:
:tixi (TIXI Handle): TIXI Handle of the CPACS file
:comp_s... | bigcode/self-oss-instruct-sc2-concepts |
def mix_labellers(labellers, class_name="MixtureLabeller"):
"""Combine Labeller classes dynamically.
The Labeller class aims to split plot labeling in ArviZ into atomic tasks to maximize
extensibility, and the few classes provided are designed with small deviations
from the base class, in many cases on... | bigcode/self-oss-instruct-sc2-concepts |
def test_size(STDictonary_root, count=0):
"""Test function for the size counter of the STDict-class, STDictonary_root = root of STDict to test , O(n)"""
if STDictonary_root is None:
return count
else:
count += 1
count = test_size(STDictonary_root._left, count)
count = test_si... | bigcode/self-oss-instruct-sc2-concepts |
def tab(contents, num_spaces):
"""
Inserts the specified amount of spaces in front of each line of the contents
"""
return "\n".join(["%s%s" % (" " * num_spaces, line) for line in contents.splitlines()]) | bigcode/self-oss-instruct-sc2-concepts |
def desnake(string):
"""snake_case -> snake case"""
return " ".join(string.split("_")) | bigcode/self-oss-instruct-sc2-concepts |
def get_longest_matching_prefix(word, prefix_list):
"""Find the longest prefix of word that is in prefix_list. None otherwise."""
to_return = None
for i in range(len(word)):
prefix = word[: i + 1]
if prefix in prefix_list:
to_return = prefix
return to_return | bigcode/self-oss-instruct-sc2-concepts |
def gp_predict(gpmodel, para_array_rescaled):
"""Returns a Gaussian Process prediction of PCA weights
Parameters
----------
gpmodel: GPflow object
Trained GPflow model corresponding to a particular redshift
para_array_rescaled: ndarray of shape (5, )
Rescaled Cosmological paramete... | bigcode/self-oss-instruct-sc2-concepts |
def onedmoffat(x, H, A, dx, alpha, beta):
"""
Returns a 1-dimensional moffat of form
H + A * (1 + ((x-dx)/alpha)**2)**(-beta) """
return H + A * (1 + ((x-dx)/alpha)**2)**(-beta) | bigcode/self-oss-instruct-sc2-concepts |
def user_is_resource_editor(user):
"""
Single test for whether a user is in the Resource Editor group
"""
return user.groups.filter(name="Resource Editor").exists() | bigcode/self-oss-instruct-sc2-concepts |
import json
def load_endpoint_json(path):
"""
Loads a given JSON file & returns it.
:param path: The path to the JSON file
:type path: string
:returns: The loaded data
"""
with open(path, 'r') as endpoints_file:
return json.load(endpoints_file) | bigcode/self-oss-instruct-sc2-concepts |
import difflib
def closest_title(title, series):
"""
Return closest movie name in a given dataframe.
-------
Parameters:
title (string): Movie name
series: (pandas Series): Series to search for closest title
"""
matches = difflib.get_close_matches(title, series)
if matches:
... | bigcode/self-oss-instruct-sc2-concepts |
def rosenbrock(tensor):
"""
Compute Rosenbrock function.
# https://en.wikipedia.org/wiki/Test_functions_for_optimization
"""
x, y = tensor
return (1 - x) ** 2 + 100 * (y - x ** 2) ** 2 | bigcode/self-oss-instruct-sc2-concepts |
def merge_intervals(intervals, delta= 0.0):
"""
A simple algorithm can be used:
1. Sort the intervals in increasing order
2. Push the first interval on the stack
3. Iterate through intervals and for each one compare current interval
with the top of the stack and:
A. If current interval... | bigcode/self-oss-instruct-sc2-concepts |
def ten_recipes_result(recipes, puzzle):
"""Return 10 recipes after the recipe number puzzle."""
return ''.join(str(num) for num in recipes[puzzle:puzzle + 10]) | bigcode/self-oss-instruct-sc2-concepts |
def scrub(input_string):
"""Clean an input string (to prevent SQL injection).
Parameters
----------
input_string : str
Returns
-------
str
"""
return "".join(k for k in input_string if k.isalnum()) | bigcode/self-oss-instruct-sc2-concepts |
def read_torrent_file(filepath):
"""Reads torrent file from filesystem and returns its contents."""
f = open(filepath, 'rb')
contents = f.read()
f.close()
return contents | bigcode/self-oss-instruct-sc2-concepts |
def get_log_print_level(client):
"""Get log print level
Returns:
Current log print level
"""
return client.call('get_log_print_level') | bigcode/self-oss-instruct-sc2-concepts |
def drawCutoffVert(ax,x,cl="r",lb="",ls="--",lw=.5):
"""
This method draws a vertical cutoff line or lines
:Arguments:
:type ax: matplotlib axis
:param ax: axis to draw lines on
:type x: int/float or list of ints/floats
:param x: x value(s) on which to draw cutoff lines
... | bigcode/self-oss-instruct-sc2-concepts |
def new_bname(filename, suffix):
""" return a new basename (without path, without extension, + suffix) """
filename = filename[filename.rfind("/"):]
filename = filename[:filename.rfind(".")]
return filename + "_" + suffix | bigcode/self-oss-instruct-sc2-concepts |
def compare_version(version1, version2):
"""
Compare version strings.
Return 1 if version1 is after version2;
-1 if version1 is before version2;
0 if two versions are the same.
"""
v1_arr = version1.split(".")
v2_arr = version2.split(".")
len1 = len(v1_arr)
len2 = le... | bigcode/self-oss-instruct-sc2-concepts |
import csv
def load_csv(csvpath):
"""Reads the CSV file from path provided.
Args:
csvpath (Path): The csv file path.
Returns:
A header list
A list of lists that contains the rows of data from the CSV file.
"""
with open(csvpath, "r") as csvfile:
data = []
... | bigcode/self-oss-instruct-sc2-concepts |
def wrap_line(line):
"""Add end of line at character eighty, to match PDB record standard."""
output = ""
for i in range(0, len(line), 80):
output += "%s\n" % line[i : i + 80]
return output | bigcode/self-oss-instruct-sc2-concepts |
import re
def compare(asm_simulation_output, asm_correct_outputs):
"""
Compare the student's circuit output with the correct one
:param asm_simulation_output: File containing the simulated outputs
:param asm_correct_outputs: File containing the correct outputs
:return: Percentage of correctness
... | bigcode/self-oss-instruct-sc2-concepts |
def quick_sort(collection):
"""Pure implementation of quick sort algorithm in Python
:param collection: some mutable ordered collection with heterogeneous
comparable items inside
:return: the same collection ordered by ascending
Examples:
>>> quick_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
... | bigcode/self-oss-instruct-sc2-concepts |
def getGRBComboQuery(GRB):
"""
Get the several versions of a GRB name that could come up in ADS searches.
E.g., 010222A, 10222A, GRB010222A, GRB1022A
:param GRB:
The GRB to get name combinations of.
:type GRB:
:class:`str`
:returns:
String of GRB name combinations separa... | bigcode/self-oss-instruct-sc2-concepts |
def to_pomdp_file(agent, output_path=None,
discount_factor=0.95):
"""
Pass in an Agent, and use its components to generate
a .pomdp file to `output_path`.
The .pomdp file format is specified at:
http://www.pomdp.org/code/pomdp-file-spec.html
Note:
* It is assumed that th... | bigcode/self-oss-instruct-sc2-concepts |
import math
def calc_sides(coords, angle):
"""Calculates the four points of the car (top and bottom right & left)"""
length = 50
top_left = [
coords[0] + math.cos(math.radians(360 - (angle + 30))) * length,
coords[1] + math.sin(math.radians(360 - (angle + 30))) * length
]
top_right... | bigcode/self-oss-instruct-sc2-concepts |
def strip_comments(line,ws_too=False):
"""
Strips comments from a line (and opptionally leading/trailing whitespace).
"""
bam = -1
ix = 0
while True:
bam = line[ix:].find('#',bam + 1)
if bam == -1:
break
bam = ix + bam
if bam == 0:
return '... | bigcode/self-oss-instruct-sc2-concepts |
import csv
def read_csv(path):
"""
Reads the CSV file at path, and returns a list of rows. Each row is a
dictionary that maps a column name to a value in that column, as a string.
"""
output = []
for row in csv.DictReader(open(path)):
output.append(row)
return output | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def from_epoch(epoch: int, tz_offset: int = 0) -> datetime:
"""
Returns a datetime from an epoch int with optional UTC timezone offset
"""
return datetime.fromtimestamp((epoch - tz_offset) / 1000) | bigcode/self-oss-instruct-sc2-concepts |
def base32_decode(base32_value: str) -> int:
"""
Convert base32 string to integer
Example 'A' -> 10
"""
return int(base32_value, 32) | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def get_text_as_list(self) -> List:
"""
Returns the text in it's logical form as a list of lines.
:param self: Texteditor-Class
:return: List of lines containing the text. Lines cane be empty Strings.
"""
return self.line_string_list | bigcode/self-oss-instruct-sc2-concepts |
def add_milliseconds_to_epoch_time(epoch_time):
"""
Add 1 millisecond so we would not get duplicate incidents.
Args:
epoch_time: Epoch time as it is in the raw_content
Returns:
epoch_time with 1 more millisecond.
"""
epoch_time = int(epoch_time / 1000 + 1) / 1000
return epoch... | bigcode/self-oss-instruct-sc2-concepts |
def _check_uniqueness_of_entries(data_set, data_set_name=None, raise_exception=True):
"""
Check if all entries in iterable are unique in iterable
Parameters
----------
data_set : [list, set]
iterable containing the entries to test for uniqueness
data_set_name : str, optional
the... | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_element_namespace(element):
"""
Gets the namespace of an element.
:param element: Element to get the namespace of.
:return: Namespace of given element.
"""
result = re.match("{.+}", element.tag)
return result.group(0) if result else "" | bigcode/self-oss-instruct-sc2-concepts |
def sequences_to_dictionary(sequence, index):
""" Converts a sequence of sequences to a dictionary, where the dictionary key is the entry at
index in the subsequence, i.e. if index = 1 then:
[[1, "45"], [2, "46"]]
becomes
{
"45": [1, "45"],
"46": [2, "46"]
}
Args:
... | bigcode/self-oss-instruct-sc2-concepts |
def check_valid_multiple(category: str, field: str, val: str, multiple: int) -> str:
"""Check valid value being a multiple
Parameters
----------
category : str
category of open insider screener
field : str
field from category of open insider screener
val : str
value's fi... | bigcode/self-oss-instruct-sc2-concepts |
def escape_facet_value(value: str) -> str:
"""Escape and quote a facet value for an Algolia search."""
value = value.replace('"', r"\"").replace("'", r"\'")
value = f'"{value}"'
return value | bigcode/self-oss-instruct-sc2-concepts |
def add(a: float, b: float):
"""
Add two floats.
This is a very nice function that performs the following operation
.. math:: c = a + b
Parameters
----------
a : float
First parameter
b : float
Second parameter
Returns
-------
c : float
This value ... | bigcode/self-oss-instruct-sc2-concepts |
import yaml
def update_config(cfg):
""" Updates the config file with the given settings. """
with open('config.yml', 'w') as outfile:
yaml.dump(cfg, outfile, default_flow_style=False)
return None | bigcode/self-oss-instruct-sc2-concepts |
import re
def dict_from_sdkconfig(path):
"""
Parse the sdkconfig file at 'path', return name:value pairs as a dict
"""
regex = re.compile(r"^([^#=]+)=(.+)$")
result = {}
with open(path) as f:
for line in f:
m = regex.match(line)
if m:
result[m.gr... | bigcode/self-oss-instruct-sc2-concepts |
def add_options(options):
"""
A decorator to add a set of options to a click command. This allows options that
are used in multiple places to be defined in one place.
:param options: A list of click options to add to the command
"""
def _add_options(func):
for option in reversed(option... | bigcode/self-oss-instruct-sc2-concepts |
def getBridgeDBPID(pidfile="bridgedb.pid"):
"""Read the ``bridgedb.pid`` file in **rundir**, if it exists, to get the
PID.
:param str pidfile: The path to the BridgeDB pidfile.
:rtype: int
:returns: The process ID, if available, otherwise ``0``.
"""
fh = None
try:
fh = open(pidf... | bigcode/self-oss-instruct-sc2-concepts |
import re
def latexify_spacegroup(spacegroup_symbol):
"""
Generates a latex formatted spacegroup. E.g., P2_1/c is converted to
P2$_{1}$/c and P-1 is converted to P$\overline{1}$.
Args:
spacegroup_symbol:
A spacegroup symbol
Returns:
A latex formatted spacegroup with p... | bigcode/self-oss-instruct-sc2-concepts |
def query_mysql(cnx, query, args=None, dict_=False):
"""Run query and return results."""
cursor = cnx.cursor(dictionary=dict_)
cursor.execute(query, args)
results = cursor.fetchall()
cursor.close()
return results | bigcode/self-oss-instruct-sc2-concepts |
def add_homeruns(user, player_id, hrs):
"""Add a hr by a player
Parameters:
user: the dictionary of the user (dict)
player_id: the player id (int)
hrs: the number of hr hit (int)
Returns:
user: the update user (dict)
"""
for __ in range(0, hrs):
user['game'][... | bigcode/self-oss-instruct-sc2-concepts |
def remove_properties_containing_None(properties_dict):
"""
removes keys from a dict those values == None
json schema validation might fail if they are set and
the type or format of the property does not match
"""
# remove empty properties - as validations may fail
new_dict = dict()
for... | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def drop(n, seq):
""" The sequence following the first n elements
>>> list(drop(2, [10, 20, 30, 40, 50]))
[30, 40, 50]
See Also:
take
tail
"""
return itertools.islice(seq, n, None) | bigcode/self-oss-instruct-sc2-concepts |
def zodiac_compatibility(user_sign, friend_sign):
""" Using comparison operators and conditionals, returns a given compatibility message.
Parameters
----------
user_sign : str
The user's zodiac sign as determined by their birthday input.
friend_sign : str
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Callable
def delete(route: str, additional_methods: List[str]=[]) -> Callable:
"""
States that a function will be executed when a DELETE request
is sent to the server.
"""
return lambda func: (route, 'DELETE', func, additional_methods) | bigcode/self-oss-instruct-sc2-concepts |
def get_category_from_topchart_url(url: str) -> str:
"""Return the category from an url.
Throws an error if the url isn't recognized.
"""
category = url.split("/")[3]
# check category
if category not in [
"films",
"series",
"jeuxvideo",
"livres",
"bd",
... | bigcode/self-oss-instruct-sc2-concepts |
def is_output_node(node):
"""
Determine whether a RedBaron node may be expected to generate output.
Parameters
----------
node : <Node>
a RedBaron Node.
Returns
-------
bool
True if node may be expected to generate output, otherwise False.
"""
if node.type == 'p... | bigcode/self-oss-instruct-sc2-concepts |
def rk4_backward(f, x, h, **kwargs):
"""Implements a backwards classic Runge-Kutta integration RK4.
Parameters
----------
f : callable
function to reverse integrate, must take x as the first argument and
arbitrary kwargs after
x : numpy array, or float
state needed by functi... | bigcode/self-oss-instruct-sc2-concepts |
def car_blueprint_filter(blueprint_library):
"""
Exclude the uncommon vehicles from the default CARLA blueprint library
(i.e., isetta, carlacola, cybertruck, t2).
Parameters
----------
blueprint_library : carla.blueprint_library
The blueprint library that contains all models.
Retur... | bigcode/self-oss-instruct-sc2-concepts |
def multiply_vector(vector: list, number: float) -> list:
"""Multiply a vector."""
multiplied_vector = [value * number for value in vector]
return multiplied_vector | bigcode/self-oss-instruct-sc2-concepts |
def _format_deps(deps_list):
"""Maps a list of dependencies into a single string."""
stripped_deps = [l.strip() for l in sorted(deps_list)]
indented_quoted_deps = [' "{}",'.format(l) for l in stripped_deps]
return '\n'.join(indented_quoted_deps) | bigcode/self-oss-instruct-sc2-concepts |
def identity(x):
"""A function that does nothing (the default parse action)"""
return x | bigcode/self-oss-instruct-sc2-concepts |
def is_letter_guessed_correctly(player_input, secret_word):
""" check whether the (guessed_letter/ player_input) is in the secret_word
Arguments:
player_input (string): the player_input
secret_word (string): the secret, random word that the player should guess
Returns:
boolean: True if the player_in... | bigcode/self-oss-instruct-sc2-concepts |
def RCI_calc(mutual_information, reference_entropy):
"""
Calculate RCI (Relative classifier information).
:param mutual_information: mutual information
:type mutual_information : float
:param reference_entropy: reference entropy
:type reference_entropy : float
:return: RCI as float
"""... | bigcode/self-oss-instruct-sc2-concepts |
def solve_optimisation_investment(model):
"""
Parameters
----------
model : oemof.solph.Model
The oemof model, which is optimized.
Returns
-------
dict : Results of optimisation. Contains:
- 'oemof' : Complete "oemof" results of the energy system optimisation (.results['mai... | bigcode/self-oss-instruct-sc2-concepts |
def d_file_query(query_utils):
""" Retrieve D1 or D2 data.
Args:
query_utils: object containing:
file_utils: fileD1 or fileD2 utils
sess: database session
agency_code: FREC or CGAC code for generation
start: beginning of period for... | bigcode/self-oss-instruct-sc2-concepts |
def rgb2hex(rgb) -> str:
"""Convert an RGB sequence to a hexadecimal color.
The values of the sequence need to be in ``range(256)``.
>>> rgb2hex([0, 255, 255])
'#00ffff'
"""
return '#%02x%02x%02x' % tuple(rgb) | bigcode/self-oss-instruct-sc2-concepts |
def time_diff(end, start):
"""Take two times formatted HHMM and return end-start, in hours."""
end = 60 * int(end[:2]) + int(end[2:])
start = 60 * int(start[:2]) + int(start[2:])
return float(end-start) / 60 | bigcode/self-oss-instruct-sc2-concepts |
def filter_bad_ra_dec(table_data):
"""Remove targets with bad RA and/or Dec values from the input table.
Use the column masks to find which entries have bad RA or Dec values.
These will be excluded from the Mirage catalog.
Parameters
----------
table_data : astropy.table.Table
Input tab... | bigcode/self-oss-instruct-sc2-concepts |
def get_parent_key(key):
"""
Gets the key of the parent object. Assumes keys are formatted like
param1__param2__param__3__...
Parameters
----------
key: str
The key whose parent we want.
Output
------
parent_key: str
The parent key
"""
return '__'.join(key.... | bigcode/self-oss-instruct-sc2-concepts |
def is_remote(url):
"""Checks whether the specified value is a remote url.
"""
prefixes = ["http", "file", "git"]
for prefix in prefixes:
if url.startswith(prefix):
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
from bs4 import BeautifulSoup
def title_card_factory(title: str, sub_title: str, image_link: str = ""):
"""
For creating title card HTML.
Args:
title (str): Title on the title card.
sub_title (str): The subtitle below the title card.
image_link (str, optional): The image on the ti... | bigcode/self-oss-instruct-sc2-concepts |
import math
def G(x, sigma):
"""
Calculates a gaussian kernel"""
return ((1 / (2 * math.pi * pow(sigma, 2))) *
math.exp(-(pow(x, 2) / (2 * pow(sigma, 2))))) | bigcode/self-oss-instruct-sc2-concepts |
from typing import AbstractSet
import pathlib
def get_available_gpus() -> AbstractSet[int]:
"""Return available gpu index numbers.
Returns:
AbstractSet[int]: index numbers of available GPUs
"""
try:
p = pathlib.Path("/proc/driver/nvidia/gpus")
gpu_count = len(list(p.iterdir()... | bigcode/self-oss-instruct-sc2-concepts |
def flip_bbox(bbox, size, y_flip=False, x_flip=False):
"""Flip bounding boxes accordingly.
The bounding boxes are expected to be packed into a two dimensional
tensor of shape :math:`(R, 4)`, where :math:`R` is the number of
bounding boxes in the image. The second axis represents attributes of
the bo... | bigcode/self-oss-instruct-sc2-concepts |
def pointToGridIndex(x, y, z, sx=1.0, sy=1.0, sz=1.0, ox=0.0, oy=0.0, oz=0.0):
"""
Convert real point coordinates to index grid:
:param x, y, z: (float) coordinates of a point
:param nx, ny, nz: (int) number of grid cells in each direction
:param sx, sy, sz: (float) cell size in each directio... | bigcode/self-oss-instruct-sc2-concepts |
def round_robin(
num_tasks,
num_resources,
verbose=False):
"""Round-Robin scheduling algorithm.
Parameters
----------
num_tasks : int
Number of tasks
num_resources : int
Number of resources
verbose : bool [default=False]
True if messages should be... | bigcode/self-oss-instruct-sc2-concepts |
def normalize_prisma_url(url: str) -> str | None:
""" Correct common Prisma Cloud API URL misconfigurations """
if not url:
return None
return url.lower().replace('//app', '//api').replace('http:', 'https:').rstrip('/') | 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.