seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def collapsed(cube, *args, **kwargs):
"""Collapses the cube with given arguments.
The cell methods of the output cube will match the cell methods
from the input cube. Any cell methods generated by the iris
collapsed method will not be retained.
Args:
cube (iris.cube.Cube):
A Cu... | bigcode/self-oss-instruct-sc2-concepts |
def parse_requirements(filename):
""" load requirements from a pip requirements file """
lineiter = (line.strip() for line in open(filename))
return [
line
for line in lineiter
if line and not line.startswith("#") and not line.startswith('git+')
] | bigcode/self-oss-instruct-sc2-concepts |
import csv
def load_csv(filename, label_col):
"""
Loads a csv file containin the data, parses it
and returns numpy arrays the containing the training
and testing data along with their labels.
:param filename: the filename
:return: tuple containing train, test data np arrays and labels
"""... | bigcode/self-oss-instruct-sc2-concepts |
def split_event(line):
"""Splits a line into tokens divided by one or more spaces."""
tokens = list(filter(None, line.split(' '))) # split by whitespace
return (tokens[1], *tokens[-4:]) | bigcode/self-oss-instruct-sc2-concepts |
def parameter_substitutions_for_sample(
sample, labels, sample_id, relative_path_to_sample
):
"""
:param sample : The sample to do substitution for.
:param labels : The column labels of the sample.
:param sample_id : The merlin sample id for this sample.
:param relative_path_to_sample : The rela... | bigcode/self-oss-instruct-sc2-concepts |
def natural_bounds(rank, nb_ingredients):
"""
Computes the upper and lower bounds of the proportion of an ingredient depending on its rank and the number of
ingredients in the product given that they are in decreasing proportion order.
Examples:
>>> natural_bounds(2, 4)
(0.0, 50.0)
... | bigcode/self-oss-instruct-sc2-concepts |
def _is_float(value):
""" Check whether a value is a float or not.
"""
try:
value = float(value)
return True
except (TypeError, ValueError):
return False | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
def merge_freqs(tfs1: Dict[str, int], tfs2: Dict[str, int]) -> Dict[str, int]:
"""
Merges term-frequencies from tfs1 and tfs2 dictionaries.
This is an inplace operation i.e. It updates the largest dictionary in the argument inplace
and returns that as result.
"""
# keep... | bigcode/self-oss-instruct-sc2-concepts |
import math
def classify_fixxation(eye_x, eye_y, d_time, treshhold):
"""
a function that classifies fixxations based on a threshhold in pixel per second
:param eye_x: an indexable datastructure with the x eye coordinates
:param eye_y: an indexable datastructure with the y eye coor... | bigcode/self-oss-instruct-sc2-concepts |
def extract_end_bits(num_bits, pixel):
"""
Extracts the last num_bits bits of each value of a given pixel.
example for BW pixel:
num_bits = 5
pixel = 214
214 in binary is 11010110.
The last 5 bits of 11010110 are 10110.
^^^^^
The inte... | bigcode/self-oss-instruct-sc2-concepts |
import codecs
import json
def load(path):
"""Loads a single Zeppelin notebook. For now just a wrapper around json.load"""
with codecs.open(path, mode="r", encoding="UTF-8") as fr:
try:
return json.load(fr)
except json.JSONDecodeError:
return {} | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def find_positions(arr: List[str],
mask: List[bool]) -> List[int]:
"""Set positions and tokens.
Args:
tokens: List of tokens and untokens.
mask: Mask for tokens.
Returns:
List of positions of tokens.
"""
pos... | bigcode/self-oss-instruct-sc2-concepts |
def _get_val(v):
"""get val from a function or a value"""
if callable(v):
return v()
return v | bigcode/self-oss-instruct-sc2-concepts |
import json
def search_for_game_id(game_name: str):
"""
Searches all_games_data.json file for occurences of game_name phrase, and saves findings to
found_games_data.json file.
:param game_name: string containing name of the game
:return: list containing found games as well as their id's
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def valid_image_array(image_array):
"""
Returns `True` if and image array is valid.
An image array is valid if it is in grayscale (having 2 dimensions) or in color
(having 3 dimensions)
:param image_array: Image as an array
:type image_array: :class:`~numpy:numpy.ndarray`
:return: Returns `... | bigcode/self-oss-instruct-sc2-concepts |
def run_mgmt_command(capsys):
"""Function fixture that runs a python manage.py with arguments
and returns the stdout and stderr as a tuple.
"""
def f(cmd_class, argv=None):
argv = argv or []
cmd = cmd_class()
cmd.run_from_argv(["manage.py"] + argv)
out, err = capsys.read... | bigcode/self-oss-instruct-sc2-concepts |
def matrix_to_images(data_matrix, mask):
"""
Unmasks rows of a matrix and writes as images
ANTsR function: `matrixToImages`
Arguments
---------
data_matrix : numpy.ndarray
each row corresponds to an image
array should have number of columns equal to non-zero voxels in the mask
... | bigcode/self-oss-instruct-sc2-concepts |
def filter_events(events, version_label=None, request_id=None, env_name=None):
"""
Method filters events by their version_label, request_id, or env_name if supplied,
or any combination if multiple are specified.
:param events: A list of `events` returned by the `DescribeEvents` API
:param version_l... | bigcode/self-oss-instruct-sc2-concepts |
def counter_to_dict(counter):
"""
Converts counter to dictionary, also replaces the numpy value to an int
"""
dic = {}
for key, value in counter.items():
dic[key] = int(value)
return dic | bigcode/self-oss-instruct-sc2-concepts |
def monster_in_cutout(monster, cutout):
"""
Return True if monster is in cutout.
"""
for i_monster, char_monster in enumerate(monster):
if char_monster == "#" and cutout[i_monster] == ".":
return False
else:
return True | bigcode/self-oss-instruct-sc2-concepts |
def slack_escape(text):
"""
Escapes special characters for Slack API.
https://api.slack.com/docs/message-formatting#how_to_escape_characters
"""
text = text.replace('&', '&')
text = text.replace('<', '<')
text = text.replace('>', '>')
return text | bigcode/self-oss-instruct-sc2-concepts |
from collections import Counter
def _get_majority_class(y):
"""Get the majority class.
Note that if two or more classes have the same occurrences, one of them is returned arbitrarily.
"""
mc = Counter(y).most_common()
return mc[0][0] | bigcode/self-oss-instruct-sc2-concepts |
def parse_sha256sum_file(filename):
"""
Takes a SHA256 checksum file and returns the values as a dict
:param filename: The file with SHA256 checksums
:return Mapping: Check sums from file
"""
with open(filename, 'r') as file:
string = file.read()
string = string.rstrip()
# Parse... | bigcode/self-oss-instruct-sc2-concepts |
import random
def freq_sample(freq: float, sample: float):
"""
Down or up sample a frequency based on a sample size. Sub unit frequencies are
rounded probabalistically.
:param freq: pre sampled frequency (integer)
:param sample: sample size (float)
:return: new frequency (integer)
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def chopnetOutputNode(chopnet):
"""Returns the chopnode inside the given chopnet that currently has its display flag set"""
for n in chopnet.children():
if n.isAudioFlagSet():
return n | bigcode/self-oss-instruct-sc2-concepts |
import uuid
def as_uuid(key: str) -> str:
""" Turn the given key into a uuid version 3. """
return str(uuid.uuid3(uuid.NAMESPACE_DNS, key)) | bigcode/self-oss-instruct-sc2-concepts |
def test_user(user_num):
"""Pre-defined user variables for testing purposes"""
users = {
"1": (5, "", 3, True, True, True, True, True),
"2": (0, "", 3, False, False, False, False, False),
"3": (2, "", 4, True, True, False, False, True),
"4": (1, "", 5, False, False, True, True, F... | bigcode/self-oss-instruct-sc2-concepts |
def ensure_tuple_size(tup, dim):
"""Returns a copy of `tup` with `dim` values by either shortened or padded with zeros as necessary."""
tup = tuple(tup) + (0,) * dim
return tup[:dim] | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
from contextlib import suppress
def safe_get(key, obj, default=None) -> Any:
"""
Safely retrieve key from object
Args:
obj: Any. target object
key: inner object adders token
default: value to return on failure
Returns:
on success: value of request... | bigcode/self-oss-instruct-sc2-concepts |
import json
def pretty_json(json_str):
"""Generates a pretty-print json from any json."""
return json.dumps(json.loads(json_str), indent=4) | bigcode/self-oss-instruct-sc2-concepts |
def _sensor(product_id):
"""Find sensor ID from product ID."""
sid = product_id[:2]
if sid == 'LC':
return 'OLI_TIRS'
elif sid == 'LO':
return 'OLI'
elif sid == 'LE':
return 'ETM'
elif sid == 'LT':
return 'TM'
elif sid == 'LM':
return 'MSS' | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def extract_date_sitename(directory_path,
sitename_location,
datetime_location):
"""Extract datetime and sitename from directory path names.
Parameters
-----------
directory_path : string
A path to the directory... | bigcode/self-oss-instruct-sc2-concepts |
def triple_length(m: int, n: int) -> int:
"""Returns the length of the triangle formed by the Pythagorean triple
(m^2 - n^2, 2mn, m^2 + n^2)."""
return 2 * m * (m + n) | bigcode/self-oss-instruct-sc2-concepts |
def extract_container_id_removal(line):
"""
Extract container id from a Removing line
Removing intermediate container 816abeca3961
"""
parts = line.strip().split(' ')
if len(parts) == 4:
return parts[3]
else:
raise Exception("Unrecognized docker removing line: " + l... | bigcode/self-oss-instruct-sc2-concepts |
def get_recommendation(risk_level):
"""
Returns a investment recommendation based on the choice of risk level
"""
recommendation = ""
if risk_level == 'None' or risk_level == 'none':
recommendation = "Investment recommendation: 100% bonds (AGG), 0% equities (SPY)"
elif ris... | bigcode/self-oss-instruct-sc2-concepts |
def digit_that_breaks_ordering_index(digits: list) -> int:
"""
Starting from last digit of given number, find the first
digit which breaks the sorted ordering. Let the index of
this found digit be 'i' and the digit be number[i].
:param digits: list of digits
:return: the index of the first digi... | bigcode/self-oss-instruct-sc2-concepts |
def specindex(nu1, nu2, f1, alpha):
"""
Calculate some flux given two wavelengths, one flux, and the spectral
index.
"""
return f1*(nu2/nu1)**(alpha) | bigcode/self-oss-instruct-sc2-concepts |
def find_sols(f, arr, sign_check_func = lambda x, y: x*y < 0, verbose = False):
"""
Given an array of section points, checks if function *f* has a solution
in any of the intervals formed by said points.
"""
sols = []
for i in range(len(arr)-1):
if sign_check_func(f(arr[i]), f(arr[i+1])):... | bigcode/self-oss-instruct-sc2-concepts |
def motifs_from_proto(motifs, is_one_dimensional=False):
"""
Utility function to transform motif locations back to single dimension
or multi-dimension location.
Parameter
---------
motifs : array_like
The protobuf formatted array.
is_one_dimensional : boolean
A flag to indic... | bigcode/self-oss-instruct-sc2-concepts |
def replacePlaceholder(sentence,placeholder,subsitute):
"""
This function replaces in a sentence a placeholder with a specified substitute
Input:
sentence: string representing a sentence
placeholder: string representing a placeholder that occurs in the supplied sentence
subsitute: s... | bigcode/self-oss-instruct-sc2-concepts |
def list_as_comma_string(bits, serial_comma=False):
"""
>>> list_as_comma_string([])
''
>>> list_as_comma_string(['hi'])
'hi'
>>> list_as_comma_string(['hi', 'there'])
'hi and there'
>>> list_as_comma_string(['hi', 'there', 'world'], serial_comma=False)
'hi, there and world'
... | bigcode/self-oss-instruct-sc2-concepts |
def auto_label(callable_or_expr):
"""
Given a callable or a string, extract a name for labeling axes.
Parameters
----------
callable_or_expr : String | Callable
Returns
-------
label : String
"""
if callable(callable_or_expr):
return getattr(callable_or_expr, "__name__"... | bigcode/self-oss-instruct-sc2-concepts |
def delete_tasks(project, params, items):
""" Delete tasks by ids
"""
project.delete_tasks(items)
return {'processed_items': len(items),
'detail': 'Deleted ' + str(len(items)) + ' tasks'} | bigcode/self-oss-instruct-sc2-concepts |
def get_x_indicator_variable_index(i, j, k, l, m, n):
"""
Map the i,j,k,l indices to the sequential indicator variable index
as generated by linear_objective_function_coefficients().
This is basically the (4-dimensional) 'array equation' (as per
row-major arrays in C for example).
Note that for... | bigcode/self-oss-instruct-sc2-concepts |
import re
from pathlib import Path
def import_public_key(app_path, device_name, keystring):
"""Import a public key for hyperglass-agent.
Arguments:
app_path {Path|str} -- hyperglass app path
device_name {str} -- Device name
keystring {str} -- Public key
Raises:
RuntimeErr... | bigcode/self-oss-instruct-sc2-concepts |
import random
def make_marker(bits=64):
""" Return a unique string that , for marking boundaries in text """
# i.e. '|-b1dda1c7f14cd89e-|'
# In python2, hex() on big numbers gives i.e. '0x3333333333L'.
# I'll drop the 1st two and last chars with [2:-1].
return '|-'+hex(random.getrandbits(64))[2:-... | bigcode/self-oss-instruct-sc2-concepts |
def get_openlibrary_key(key):
"""convert /books/OL27320736M into OL27320736M"""
return key.split("/")[-1] | bigcode/self-oss-instruct-sc2-concepts |
def factors(number):
"""
Find all of the factors of a number and return it as a list.
:type number: integer
:param number: The number to find the factors for.
"""
if not (isinstance(number, int)):
raise TypeError(
"Incorrect number type provided. Only integers are accepted.... | bigcode/self-oss-instruct-sc2-concepts |
import socket
def uds_reachable(uds_path, return_sock=False):
""" Check if the unix domain socket at path `uds_path` is reachable.
Parameters
----------
uds_path : str
return_sock: bool, optional (default is False)
Return the socket.
Returns
-------
bool, socket
If th... | bigcode/self-oss-instruct-sc2-concepts |
def mid_color(c1, c2):
"""Returns medium color between c1 and c2"""
r = int(0.5 * (c1[0] + c2[0]))
g = int(0.5 * (c1[1] + c2[1]))
b = int(0.5 * (c1[2] + c2[2]))
try:
a = int(0.5 * (c1[3] + c2[3]))
return (r, g, b, a)
except IndexError:
return (r, g, b) | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def validate_path(file_name):
"""
Validates if the passed-in argument is a valid path
Parameters
----------
file_name: str
Path to be validated
Returns
-------
tuple
Boolean status and dict to identify if the path is a file or directory
""... | bigcode/self-oss-instruct-sc2-concepts |
def _get_operator(spec, context):
"""
Gets operator from context
"""
try:
return context[spec]
except KeyError:
print(
f"Error: Operator ${spec} is not defined. Make sure you are importing it in the modules section."
)
raise | bigcode/self-oss-instruct-sc2-concepts |
def read_list(path):
"""
Reads a list containing one file per line.
Returns an index of line number - line content
"""
with open(path, 'r') as fhandle:
fdata = {}
for nline, line in enumerate(fhandle):
if not line.strip():
continue
# Remove ex... | bigcode/self-oss-instruct-sc2-concepts |
import re
def version_cmp(v1, v2):
"""
Compare two version strings and returns:
* `-1`: if `v1` is less than `v2`
* `0`: if `v1` is equal to `v2`
* `1`: if `v1` is greater than `v2`
Raises `ValueError` if versions are not well formated.
"""
vregex = r"(?P<whole>\d+(\.(\d+))*)"
v1... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Sequence
def string_list_to_html(string_list: Sequence[str]) -> str:
"""
Converts a string list to an HTML bullet list.
"""
if not string_list:
return "<p>None</p>"
item_list = [f"<li><code>{item}</code></li>" for item in string_list]
return "<ul>" + "".join(item_lis... | bigcode/self-oss-instruct-sc2-concepts |
def wrap(node, tag):
"""Wrap the given tag around a node."""
wrap_node = node.ownerDocument.createElement(tag)
parent = node.parentNode
if parent:
parent.replaceChild(wrap_node, node)
wrap_node.appendChild(node)
return wrap_node | bigcode/self-oss-instruct-sc2-concepts |
def square(x):
"""
Return x squared.
>>> square(3)
9
Extra tests:
>>> square(1)
1
>>> square(0)
0
>>> square(-4)
16
"""
return x * x | bigcode/self-oss-instruct-sc2-concepts |
import re
def part1(parser):
"""
count the number of imputs that complete match rule zero
"""
rule_count = 0
for line in parser.inputs:
match = re.match("^"+parser.rules['0']+"$", line)
if match:
rule_count+=1
return rule_count | bigcode/self-oss-instruct-sc2-concepts |
def net_gains(principal,expected_returns,years,people=1):
"""Calculates the net gain after Irish Capital Gains Tax of a given principal for a given expected_returns over a given period of years"""
cgt_tax_exemption=1270*people #tax free threashold all gains after this are taxed at the cgt_ta_rate
cgt_tax_r... | bigcode/self-oss-instruct-sc2-concepts |
def is_unitless(ds, variable):
"""
Returns true if the variable is unitless
Note units of '1' are considered whole numbers or parts but still represent
physical units and not the absence of units.
:param netCDF4.Dataset ds: An open netCDF dataset
:param str variable: Name of the variable
"... | bigcode/self-oss-instruct-sc2-concepts |
def int_to_base(val, bdgts):
""" Convert an integer into a string with a given base.
Args:
val: Integer value to convert
bdgts: List of base digits
Returns:
String corresponding to the integer
"""
# Check zero
if val == 0:
return bdgts[0]
# Check negative n... | bigcode/self-oss-instruct-sc2-concepts |
def average(values):
"""Averages the values in an iterable.
values: iterable containing numbers
"""
return sum(values) / float(len(values)) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Match
def replace_one_decorated_callable_start(m: Match) -> str:
"""Define the replacement function used in `correct_all_decorated_callable_starts`."""
start = int(m[5]) + int(m[6]) # number of decorators + line number of the first decorator
return f"{m[1]}/_type={m[2]}{m[3]}{start}:{m... | bigcode/self-oss-instruct-sc2-concepts |
def _GetFailureTestRefs(test_summary):
"""Gets a list of test summaryRef id of all failure test.
Args:
test_summary: dict, a dict of test summary object.
Returns:
A list of failure test case's summaryRef id.
"""
failure_test_refs = []
if 'subtests' in test_summary:
for sub_test_summary in test_... | bigcode/self-oss-instruct-sc2-concepts |
import warnings
def check_consecutive_ranks_on_same_nodes(mpi):
"""
Check that consecutive MPI ranks are on the same nodes, and
return a corresponding boolean. Print a warning message if
it is not the case, this this can affect performance.
"""
# Skip this function if there is only one MPI ran... | bigcode/self-oss-instruct-sc2-concepts |
def printBondedAtoms(bond, shiftdummySerial):
"""Generate bond atoms line
Parameters
----------
bond : Bond Object
Bond Object
shiftdummySerial : int
Shift to remove structural dummy atoms and get index (should be 4)
Returns
-------
bondLine : str
Bond line data... | bigcode/self-oss-instruct-sc2-concepts |
import json
def to_json(context) -> str:
"""Convert the selected Selection Sets of the current rig to JSON.
Selected Sets are the active_selection_set determined by the UIList
plus any with the is_selected checkbox on."""
arm = context.object
active_idx = arm.active_selection_set
json_obj =... | bigcode/self-oss-instruct-sc2-concepts |
def spaces(x, spa):
"""
spaces(x, spa)
Returns an array of the spacings from the original point given the distance
and the number of spaces.
"""
return list(map(lambda y: y * (x/spa), range(1, spa + 1))) | bigcode/self-oss-instruct-sc2-concepts |
import random
import string
def random_string(length=8):
"""Generate a random string of letters and numbers.
Args:
* *length* (int): Length of string, default is 8
Returns:
A string (not unicode)
"""
return "".join(
random.choice(string.ascii_letters + string.digits) for... | bigcode/self-oss-instruct-sc2-concepts |
import json
def pretty_print(js):
""" try to convert json to pretty-print format """
try:
return json.dumps(js, indent=4, separators=(",", ":"), sort_keys=True)
except Exception as e:
return "%s" % js | bigcode/self-oss-instruct-sc2-concepts |
def traditional_constants_icr_equation(tdd):
""" Traditional ICR equation with constants from ACE consensus """
a = 450
return a / tdd | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_matching_columns(dataframe, *args, **kwargs):
"""
Filter column whose names match the regular expressions defined in
``args``.
Args:
dataframe (pandas.DataFrame): Input DataFrame
\*args (List[str]): List of regular expressions matching column names
Keyword Args:
... | bigcode/self-oss-instruct-sc2-concepts |
def _clean_sample(sample, fields=None):
"""
Clean a sample resource from unnecessary fields
:param sample: the sample to clean
:type sample: dict
:return: Sample cleaned from unnecessary params
:rtype: dict
"""
if fields is None:
fields = ['_links', 'releaseDate', 'updateDate',... | bigcode/self-oss-instruct-sc2-concepts |
def train_network(net, epochs, training_data, validation_data, batch_size, callbacks, verbose=1):
"""
train a network on data for a fixed number of epochs
parameters:
net: network to train
epochs: number of epochs
training_data: training data under the format of numpy arrays (inputs,... | bigcode/self-oss-instruct-sc2-concepts |
def rgb(minimum, maximum, value):
"""Convert value within range to RGB."""
assert value <= maximum
assert value >= minimum
minimum, maximum = float(minimum), float(maximum)
r = 2 * (value - minimum) / (maximum - minimum)
b = int(max(0, 255 * (1 - r)))
r = int(max(0, 255 * (r - 1)))
g = 2... | bigcode/self-oss-instruct-sc2-concepts |
def binomial(n, k):
"""
Return binomial coefficient ('n choose k').
This implementation does not use factorials.
"""
k = min(k, n - k)
if k < 0:
return 0
r = 1
for j in range(k):
r *= n - j
r //= j + 1
return r | bigcode/self-oss-instruct-sc2-concepts |
def getConvergents(coeffs: list) -> list:
"""Calculates convergents of the continued fraction
Details: https://en.wikipedia.org/wiki/Continued_fraction
Parameters:
coeffs: list
coefficients of continued fractions
Returns:
result: list
list of tuples (nomina... | bigcode/self-oss-instruct-sc2-concepts |
def reverse_int(integer: int) -> int:
"""Reverse an integer."""
reversed_int = int(str(abs(integer))[::-1])
if integer < 0:
reversed_int *= -1
return reversed_int if -(2**31) < reversed_int < 2**31 - 1 else 0 | bigcode/self-oss-instruct-sc2-concepts |
def dekatrian_week(dek_day: int, dek_month: int) -> int:
"""Returns the Dekatrian week day from a Dekatrian date.
Here we can see the elegance of Dekatrian, since it's not necessary to
inform the year. Actually, barely it's necessary to inform the month,
as it's only needed to check if that is an Achron... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def add_sos(token_ids: List[List[int]], sos_id: int) -> List[List[int]]:
"""Prepend sos_id to each utterance.
Args:
token_ids:
A list-of-list of token IDs. Each sublist contains
token IDs (e.g., word piece IDs) of an utterance.
sos_id:
The ID of the... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
import pkg_resources
def get_pip_packages() -> Dict[str, str]:
"""
Returns a dictionary of pip packages names and their versions. Similar
to `$ pip freeze`
"""
return {
package.project_name: package.version
for package in pkg_resources.working_set
} | bigcode/self-oss-instruct-sc2-concepts |
def dominate(s1, s2):
""" Returns true if S1 dominates S2. S1 dominates S2 if S1 is better
(it our case lower) in the two fitness functions """
score1 = s1.get_fitness_score()
score2 = s2.get_fitness_score()
return False if (score1[0] > score2[0] or score1[1] > score2[1] or
(sco... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
import operator
def argmax(dict_: Dict):
"""
Get the argmax.
Parameters
----------
dict_ : dict
Returns
-------
argmax : tuple
Example
-------
>>> argmax({'a': 10, 'b': 70, 'c': 20})
'b'
"""
return max(dict_.items(), key=operator.itemg... | bigcode/self-oss-instruct-sc2-concepts |
def field_cleaner(field: str) -> str:
"""Convert field string from an html response into a snake case variable.
Args:
field (str): A dirty field string.
Example:
|Input | Output |
|------------------|------------------------|
|Previous Close |... | bigcode/self-oss-instruct-sc2-concepts |
import math
def multinomial(i_s):
"""Compute the multinomial (i_1 + ... + i_n)!/(i_1! ... i_n!)."""
itot = 0
denom = 1
for i in i_s:
itot += i
denom *= math.factorial(i)
return math.factorial(itot) / denom | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
def build_where(**conditions: Any) -> str:
"""
Build WHERE statement with several `conditions`
If no `conditions` passed return `WHERE 1 = 1`
In case if a value has primitive type it will be an equal condition and
in case if it is an iterable it will be an include condition... | bigcode/self-oss-instruct-sc2-concepts |
def build_user(first, last, **user_info):
#The double star tells python to make an empty dictionary
#so we can mix-and-match data types (e.g., string and int)
"""Build a dictionary containing user information"""
user_info['first'] = first
user_info['last'] = last
return user_info | bigcode/self-oss-instruct-sc2-concepts |
def _is_hd(release_name):
""" Determine if a release is classified as high-definition
:param release_name: release name to parse
:type release_name: basestring
:return: high-def status
:rtype: bool
"""
if "720" in release_name or "1080" in release_name:
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def assign_orchestrator(
self,
orchestrator: str,
ssl_enabled: str = "false",
keepalive_count: int = 0,
port: int = 0,
) -> bool:
"""Assign an Orchestrator to the appliance
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
*... | bigcode/self-oss-instruct-sc2-concepts |
import random
def random_password(choices, length):
""" Create Random strings
The random string is created out of the set of `string.ascii_letters` and `string.digits`.
Args:
length -- the length of the new random string
Returns:
A random string cosisting out of ascii letters and th... | bigcode/self-oss-instruct-sc2-concepts |
from typing import OrderedDict
def _set_table_column_names(names=None):
"""Define the table data columns to use in the html header.
Parameters
----------
names: collections.OrderedDict
The dictionary of string column header names and their types
Their types are the accepted google typ... | bigcode/self-oss-instruct-sc2-concepts |
import re
def clean_ne_records(record: str):
"""Base cleaning for ne records"""
record = record.replace("\t", " ").replace("|", " ").strip()
record = record.replace("\u200c", " ") # Nim-fasele
record = re.sub(" +", " ", record) # space cleaner
return record | bigcode/self-oss-instruct-sc2-concepts |
import json
def json_validation(template):
"""
Json validator
:param template: json template
:type template: object
:return: bool
"""
try:
json.loads(template)
except ValueError:
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
def simpleSubtractDictionaries(d1,d2):
"""
Subtract the elements of the second dictionary from the ones in the first dictionary. Assumes both share the same keys.
"""
assert set(d1.keys()) == set(d2.keys())
return dict([ (key, d1[key]-d2[key]) for key in d1]) | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def make_sim_exp_names(config, n_exp):
"""Helper to create simulator directory names using datetime and config"""
# Pull out some metadata
date = datetime.now().strftime('%Y%m%d_%H%M%S')
n_nonmot = config['exp_params']['n_non_motile']
n_mot = config['exp_params']['n_... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
def as_kafka_configuration_bool(value: Any) -> bool:
"""
Convert a value to a Python boolean, using the same conversions used by
the librdkafka configuration parser.
"""
# https://github.com/edenhill/librdkafka/blob/c8293af/src/rdkafka_conf.c#L1633-L1660
if isinstance(va... | bigcode/self-oss-instruct-sc2-concepts |
def calc_charge_trans(m_potential, x_potential, iv, elec_affinity_non_metal, d_mx_avg):
"""
Calculate the estimated charge transfer energy (eV) of a structure
:param m_potential: Float, the metal site Madelung potential in V
:param x_potential: Float, the non_metal site Madelung potential in V
:par... | bigcode/self-oss-instruct-sc2-concepts |
import re
def _extract_failed_ps_instances(err_msg):
"""Return a set of potentially failing ps instances from error message."""
tasks = re.findall("/job:ps/replica:0/task:[0-9]+", err_msg)
return set(int(t.split(":")[-1]) for t in tasks) | bigcode/self-oss-instruct-sc2-concepts |
def init_vault(client, shares=1, threshold=1):
"""Initialise vault.
:param client: Client to use for initiliasation
:type client: CharmVaultClient
:param shares: Number of key shares to create
:type shares: int
:param threshold: Number of keys needed to unseal vault
:type threshold: int
... | bigcode/self-oss-instruct-sc2-concepts |
def rw_at_form_temp(rw, rw_temperature, temperature_units, new_temperature):
"""
Converts formation water resistivity from a known temperature to formation temperature.
Parameters
----------
rw : float
Water Resistivity (ohmmm)
rw_temperature : float
Temperature Rw was measured ... | 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.