seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def trim_block(multiline_str):
"""Remove empty lines and leading whitespace"""
result = ""
for line in multiline_str.split("\n"):
line = line.lstrip()
if line != '':
result += "%s\n" % line
return result.rstrip() | bigcode/self-oss-instruct-sc2-concepts |
def intersect_trees(tree1, tree2):
"""Shrink two trees to contain only overlapping taxa.
Parameters
----------
tree1 : skbio.TreeNode
first tree to intersect
tree2 : skbio.TreeNode
second tree to intersect
Returns
-------
tuple of two TreeNodes
resulting trees c... | bigcode/self-oss-instruct-sc2-concepts |
def filter_none(kwargs):
"""
Remove all `None` values froma given dict. SQLAlchemy does not
like to have values that are None passed to it.
:param kwargs: Dict to filter
:return: Dict without any 'None' values
"""
n_kwargs = {}
for k, v in kwargs.items():
if v:
n_kwa... | bigcode/self-oss-instruct-sc2-concepts |
def _quote(text):
"""Enclose the string with quotation characters"""
return '\'{0}\''.format(text) | bigcode/self-oss-instruct-sc2-concepts |
def filter_by_year(df, filter_cat="conc_yy", year=1990):
"""Filter df by year, either with conception year ('conc_yy')
or birth year ('dob_yy')
"""
df = (
df[df[filter_cat] == year]
.groupby(
[
"conc_yy",
"conc_month",
"dob_yy",... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
import shutil
def get_config(repo_path: Path, filename: str) -> Path:
"""Get a config file, copied from the test directory into repo_path.
:param repo_path: path to the repo into which to copy the config file.
:param filename: name of the file from the test directory.
:return... | bigcode/self-oss-instruct-sc2-concepts |
def create_tag_cloud_html(tag_cloud_name, tags, level_weights):
"""Create HTML code for the tag cloud.
``tag_cloud_name`` is the CSS style name used for the generated
tag cloud. It should be the same value as passed to
``create_tag_cloud_css``.
``tags`` and ``level_weights`` are the return values ... | bigcode/self-oss-instruct-sc2-concepts |
def get_tables_from_mapping(source_table, dest_fields, source_dest_map):
"""
Obtain a petl tables from a source petl table and some mappings
source_table: petl table
dest_fields: list
source_dest_map: dict
Returns
dest_table: petl table
"""
source_fields = list(source_table... | bigcode/self-oss-instruct-sc2-concepts |
def second(xs):
"""Grab the second item from a list-like thing."""
return xs[1] | bigcode/self-oss-instruct-sc2-concepts |
from typing import Callable
import re
def remove_link_ids() -> Callable[[str], str]:
"""Create function to remove link ids from rendered hyperlinks."""
def _remove_link_ids(render: str) -> str:
"""Remove link ids from rendered hyperlinks."""
re_link_ids = re.compile(r"id=[\d\.\-]*?;")
... | bigcode/self-oss-instruct-sc2-concepts |
def fails_if_called(test, msg="This function must not be called.",
arguments=True):
"""
Return a new function (accepting any arguments)
that will call test.fail(msg) if it is called.
:keyword bool arguments: If set to ``False``, then we will
not accept any arguments. This ca... | bigcode/self-oss-instruct-sc2-concepts |
def qualifiedClassName(obj):
"""
Utility method for returning the fully qualified class name of an instance.
Objects must be instances of "new classes."
"""
return obj.__module__ + "." + type(obj).__name__ | bigcode/self-oss-instruct-sc2-concepts |
import torch
def pairwise_distance(node_feature):
"""
Compute the l2 distance between any two features in a group of features
:param node_feature: a group of feature vectors organized as batch_size x channels x number_of_nodes
"""
batch_size = node_feature.shape[0]
node_feature = node_fea... | bigcode/self-oss-instruct-sc2-concepts |
def is_six_band(frequency: int) -> bool:
"""determines if a channel frequency is in the 6.0-7.125 GHz ISM band"""
if frequency > 5900 and frequency < 7125:
return True
else:
return False | bigcode/self-oss-instruct-sc2-concepts |
def setify(i):
"""
Iterable to set.
"""
return set(i) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Set
def compute_number_of_edge_types(
tied_fwd_bkwd_edge_types: Set[int], num_fwd_edge_types: int, add_self_loop_edges: bool
) -> int:
"""Computes the number of edge types after adding backward edges and possibly self loops."""
return 2 * num_fwd_edge_types - len(tied_fwd_bkwd_edge_type... | bigcode/self-oss-instruct-sc2-concepts |
import re
def uppercase_lowercase(a_string):
"""Assumes a_string is a string
returns a boolean, True is a_string contains one upper case letter
followed by lower case letters
else False
"""
regex = "[A-Z][a-z]+"
results = re.search(regex, a_string)
return bool(results) | bigcode/self-oss-instruct-sc2-concepts |
def _get_mean_dist(data: list):
"""
Calculates the average euclidian distance matrix from prior training c-means.
-----------------------------------------------------------------------------------
!!! For statistical evaluation !!!
------------------------------------------------------------------... | bigcode/self-oss-instruct-sc2-concepts |
def gray_augment(is_training=True, **kwargs):
"""Applies random grayscale augmentation."""
if is_training:
prob = kwargs['prob'] if 'prob' in kwargs else 0.2
return [('gray', {'prob': prob})]
return [] | bigcode/self-oss-instruct-sc2-concepts |
def winsorize_at_explicit_input(x, lower_bound, upper_bound):
"""
Winsorizes the array x at the lower_bound and upper_bound.
:param x: a numpy array-like object
:param lower_bound: a scalar for the lower bound
:param upper_bound: a scalar for the upper bound
:return: the winsorized array
""... | bigcode/self-oss-instruct-sc2-concepts |
def _parse_str_to_dict(x):
"""Convert "k1:v1,k2:v2" string to dict
Args:
x (str): Input string
Returns:
dict: Dictionary {"k1": "v1", "k2": "v2"}
"""
d = {}
for p in x.split(","):
if ":" in p:
k, v = p.split(":")
d[k] = v
return d | bigcode/self-oss-instruct-sc2-concepts |
def subject_tag_get_all(client, subject_id, session=None):
"""Get a list of tags for a specific subject."""
return client.subject_tag_get_all(subject_id=subject_id) | bigcode/self-oss-instruct-sc2-concepts |
def _extract_fields_from_row(row, element):
"""Pluck data from the provided row and element."""
row_data = []
fields = row.find_all(element)
for raw_field in fields:
field = raw_field.text.strip()
row_data.append(field)
return row_data | bigcode/self-oss-instruct-sc2-concepts |
def normalize_brightness_dict(brightness_dict):
"""Usually the distribution of the character brightness for a given font
is not as diverse as we would like it to be. This results in a pretty
poor result during the image to ASCII art conversion (if used as-is).
Because of this it's much better to normal... | bigcode/self-oss-instruct-sc2-concepts |
def all_smaller(nums1: set, nums2: set) -> bool:
"""Return whether every number in nums1 is less than every number in num2.
You may ASSUME that:
- nums1 is non-empty
- nums2 is non-empty
- nums1 and nums2 contain only integers and/or floats
>>> all_smaller({2}, {3})
True
>>> all_... | bigcode/self-oss-instruct-sc2-concepts |
def treasury_bill_price(discount_yield, days_to_maturity):
"""Computes price ot treasury bill"""
return 100 * (1 - days_to_maturity / 360 * discount_yield) | bigcode/self-oss-instruct-sc2-concepts |
import torch
def _get_test_data(with_boundary=True, identical=True):
"""
Produces test data in the format [Batch size x W x H], where batch size is 2, W=3 and H=3.
In the first batch the pixel at 3,2 is a boundary pixel and in the second pixel at 1,2
:param with_boundary: bool
if true there i... | bigcode/self-oss-instruct-sc2-concepts |
def _analyse_gdal_output(output):
"""
Analyse the output from gpt to find if it executes successfully.
Parameters
----------
output : str
Ouptut from gpt.
Returns
-------
flag : boolean
False if "Error" is found and True if not.
"""
# return false if "Error" is ... | bigcode/self-oss-instruct-sc2-concepts |
def normalized_current_date(datetime_col, min_date, max_date):
"""
Temporal feature indicating the position of the date of a record in the
entire time period under consideration, normalized to be between 0 and 1.
Args:
datetime_col: Datetime column.
min_date: minimum value of date.
... | bigcode/self-oss-instruct-sc2-concepts |
def _is_permutation_winning(my, result, count):
"""判断是否匹配(排列方式)
my: 排列数1
result: 排列数2
count: 匹配的位数
e.g.:
my = [9,9,8,5,6,3,8]
result = [2,0,3,5,6,4,9]
count = 2
return is True
"""
s, e = 0, count #逐个切片
while e <= len(result):
if my[s:e] == res... | bigcode/self-oss-instruct-sc2-concepts |
import string
import random
def random_string_generator(size=10, chars=string.ascii_uppercase + string.digits):
"""
Generate a random string of `size` consisting of `chars`
"""
return ''.join(random.choice(chars) for _ in range(size)) | bigcode/self-oss-instruct-sc2-concepts |
import torch
def sequence_mask(lengths, maxlen, dtype=None):
"""
Exact same behavior as tf.sequence_mask.
Thanks to Dimitris Papatheodorou
(https://discuss.pytorch.org/t/pytorch-equivalent-for-tf-sequence-mask/
39036).
"""
if maxlen is None:
maxlen = lengths.max()
mask = ~(tor... | bigcode/self-oss-instruct-sc2-concepts |
def ensure_list_or_tuple(obj):
"""
Takes some object and wraps it in a list - i.e. [obj] - unless the object
is already a list or a tuple instance. In that case, simply returns 'obj'
Args:
obj: Any object
Returns:
[obj] if obj is not a list or tuple, else obj
"""
return [ob... | bigcode/self-oss-instruct-sc2-concepts |
import requests
def get_agents(url, agents_tag, headers):
"""Get the agents."""
req = requests.get(url + "/agents/", headers=headers)
if req.status_code != 200:
raise ValueError("Unable to get the token")
return [a for a in req.json()["results"] if agents_tag in a["parameters"]["tags"]] | bigcode/self-oss-instruct-sc2-concepts |
def section(name):
"""
Returns regex matching the specified section. Case is ignored in name.
"""
return r'(?<=\n)={2,} *' + fr'(?i:{name})' + r' *={2,}' | bigcode/self-oss-instruct-sc2-concepts |
import time
import re
def to_kubernetes_name(name, prefix=""):
"""
Returns a valid and unique kubernetes name based on prefix and name, replacing characters in name as necessary
see https://kubernetes.io/docs/concepts/overview/working-with-objects/names/
"""
unique_id = str(time.time()).replace(".... | bigcode/self-oss-instruct-sc2-concepts |
def target_state(target_dict):
"""Converting properties to target states
Args:
target_dict: dictionary containing target names as keys and target objects as values
Returns:
dictionary mapping target name to its state
"""
if {} == target_dict:
return None
result = {}
... | bigcode/self-oss-instruct-sc2-concepts |
def F_calc(TP, FP, FN, beta):
"""
Calculate F-score.
:param TP: true positive
:type TP: int
:param FP: false positive
:type FP: int
:param FN: false negative
:type FN: int
:param beta: beta coefficient
:type beta: float
:return: F-score as float
"""
try:
resu... | bigcode/self-oss-instruct-sc2-concepts |
def title_case(sentence):
"""
Capitalize the first letter of every word.
Parameters
----------------
sentence: string
The sentence to be put into title case.
Returns
----------------
capitalized: string
The input string in title case.
"""
if sentence == sentenc... | bigcode/self-oss-instruct-sc2-concepts |
def testme(si):
"""Revert a string, filtering out the vowel characters"""
so = ''.join([c for c in reversed(si) if c.lower() not in 'aeiouy'])
return so, len(so) | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def get_md5(file: str) -> str:
"""
Get the md5code of file.
:param file: The path of file.
:return: The md5code of file
"""
m = hashlib.md5()
with open(file, 'rb') as f:
for line in f:
m.update(line)
md5code = m.hexdigest()
return md5code | bigcode/self-oss-instruct-sc2-concepts |
def mergeDicts(dict1, dict2):
"""Merge two dictionaries."""
res = {**dict1, **dict2}
return res | bigcode/self-oss-instruct-sc2-concepts |
def dict_keys_lower(d):
"""list of dictionary keys in lower case"""
return list(map(str.lower, d.keys())) | bigcode/self-oss-instruct-sc2-concepts |
def expand(x, y, cals, shown, length, width):
"""
Expand empty position with no bombs surrounded
:param x: horizontal position
:param y: vertical position
:param cals: matrix of numbers
:param shown: list of positions shown
:param length: length of the board
:param width: width of the bo... | bigcode/self-oss-instruct-sc2-concepts |
def get_batch_token_embeddings(layer_hidden_states, attention_mask, rm_special_tokens=False):
""" remove padding and special tokens
Args:
layer_hidden_states: (N, L, D)
attention_mask: (N, L) with 1 indicate valid bits, 0 pad bits
rm_special_tokens: bool, whether to remove special tokens... | bigcode/self-oss-instruct-sc2-concepts |
import copy
def get_social_config(env):
"""
Arguments:
env: Arena-Blowblow-Sparse-2T2P-Discrete
Returns:
[[0,1],[2,3]]
"""
xTxP = env.split("-")[-2]
T = int(xTxP.split("T")[0])
P = int(xTxP.split("T")[1].split("P")[0])
policy_i = 0
all_list = []
for t in ran... | bigcode/self-oss-instruct-sc2-concepts |
def delete_at(my_list=[], idx=0):
"""
deletes an element from a list at a given index
"""
l_len = len(my_list)
if idx >= l_len or idx < 0:
return (my_list)
del my_list[idx]
return (my_list) | bigcode/self-oss-instruct-sc2-concepts |
import random
def _get_pin(length=5):
""" Return a numeric PIN with length digits """
return random.sample(range(10**(length-1), 10**length), 1)[0] | bigcode/self-oss-instruct-sc2-concepts |
def swap_byte_order(arr_in):
"""Swap the byte order of a numpy array to the native one.
Parameters
----------
arr_in : `~numpy.ndarray`
Input array.
Returns
-------
arr_out : `~numpy.ndarray`
Array with native byte order.
"""
if arr_in.dtype.byteorder not in ("=", "... | bigcode/self-oss-instruct-sc2-concepts |
def determineTranslation(translation,reference_orientation):
"""
Convert a translation in the world reference frame to a translation in
the steroid reference frame.
"""
return translation*reference_orientation.I | bigcode/self-oss-instruct-sc2-concepts |
def is_empty(value: object) -> bool:
"""
Check if value is None or not empty in case if not None.
"""
return (value is None) or (not value) | bigcode/self-oss-instruct-sc2-concepts |
def count_attached(mol):
"""
Counts the number of atoms labelled 'attached'.
Parameters
----------
mol : :class:`rdkit.Chem.rdchem.Mol`
A molecule to have 'attached' atoms counted.
Returns
-------
:class:`int`
The number of atoms with the property 'attached' in `mol`.
... | bigcode/self-oss-instruct-sc2-concepts |
def remove_method_from_itemname(itemname):
"""Return an itemname without any method name in it"""
return itemname.split(':')[0] | bigcode/self-oss-instruct-sc2-concepts |
def num(s):
"""Function will try to convert the variable to a float. If not possible it will return the original variable."""
try:
return float(s)
except:
return s | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def is_class(obj):
"""
Returns True if obj is a class, else False.
"""
return inspect.isclass(obj) | bigcode/self-oss-instruct-sc2-concepts |
def sum_even_values(d: dict) -> int:
"""Returns the sum of all even values in d, using recursion if d contains nested dictionaries."""
total = 0
for value in d.values():
if type(value) == int:
if not value % 2:
total += value
elif type(value) == dict:
... | bigcode/self-oss-instruct-sc2-concepts |
import re
def string_builder(string):
""" To match DaCe variable naming conventions, replaces all undesired
characters with "_".
"""
newstring = string
if string[0].isdigit():
newstring = "_" + string
out = re.sub("[^a-zA-Z0-9_]", "_", newstring)
return out | bigcode/self-oss-instruct-sc2-concepts |
def translate_service_orm_to_json(orm):
"""Translate ORM to JSON for response payload."""
ret = {"service_id": orm.service_id, "schema": orm.schema, "config": {}}
for config in orm.configs:
if config.hostname not in ret["config"]:
ret["config"][config.hostname] = {}
ret["config"]... | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def _is_non_defaulted_positional_args(param: inspect.Parameter) -> bool:
"""Returns True if `param` is a positional argument with no default."""
return ((param.kind == param.POSITIONAL_OR_KEYWORD or
param.kind == param.POSITIONAL_ONLY) and
param.default is param.empty) | bigcode/self-oss-instruct-sc2-concepts |
def idems(dit):
"""Convenience function for iterating dict-likes.
If dit.items is defined, call it and return the result.
Otherwise return dit itself.
"""
return dit.items() if hasattr(dit, 'items') else dit | bigcode/self-oss-instruct-sc2-concepts |
def parse_data_url(data_url):
"""
Parse a data url into a tuple of params and the encoded data.
E.g.
>>> data_url = "data:image/png;base64,ABC123xxx"
>>> params, encoded_data = parse_data_url(data_url)
>>> params
('image/png', 'base64')
>>> data
'ABC123xxx'
"""
# e.... | bigcode/self-oss-instruct-sc2-concepts |
def are_strings(*args):
"""Tells wheter all the argument passed are of type string"""
return all(map(lambda _: type(_) is str, args)) | bigcode/self-oss-instruct-sc2-concepts |
def get_host(environ):
"""
Return the real host for the given environment.
"""
if 'HTTP_X_FORWARDED_HOST' in environ:
return environ['HTTP_X_FORWARDED_HOST']
elif 'HTTP_HOST' in environ:
return environ['HTTP_HOST']
result = environ['SERVER_NAME']
if (environ['wsgi.url_scheme'... | bigcode/self-oss-instruct-sc2-concepts |
def any_difference_of_one(stem, bulge):
"""
See if there's any difference of one between the two
ends of the stem [(a,b),(c,d)] and a bulge (e,f)
:param stem: A couple of couples (2 x 2-tuple) indicating the start and end
nucleotides of the stem in the form ((s1, e1), (s2, e2))
:pa... | bigcode/self-oss-instruct-sc2-concepts |
def fuzzy_not(mfx):
"""
Fuzzy NOT operator, a.k.a. complement of a fuzzy set.
Parameters
----------
mfx : 1d array
Fuzzy membership function.
Returns
-------
mfz : 1d array
Fuzzy NOT (complement) of `mfx`.
Notes
-----
This operation does not require a unive... | bigcode/self-oss-instruct-sc2-concepts |
def get_group_cv_splits(groups, cv):
"""
Presplit the groups using the given cross-validation scheme.
Normally, the train/test split is done right before training and testing,
but this function will presplit the data for all cross folds before any
training/testing is done.
This is us... | bigcode/self-oss-instruct-sc2-concepts |
def power_pump(flate_pump_feed, rho_F, g, head_pump, ECE_motor, ECE_trans):
"""
Calculates the power of pump.
Parameters
----------
flate_pump_feed : float
The flow rate pump for Feed [m**3 / h]
rho_F : float
The density of feed, [kg / m**3]
head_pump : float
The hy... | bigcode/self-oss-instruct-sc2-concepts |
def bin2hex(strbin):
"""
Convert a string representing a binary number into a string
representing the same value in hexadecimal format.
"""
dic = { "0000":"0",
"0001":"1",
"0010":"2",
"0011":"3",
"0100":"4",
"0101":"5",
"0110":"... | bigcode/self-oss-instruct-sc2-concepts |
def walk_derivation(derivation, combiner, leaf):
"""
Traverse a derivation as returned by parser.item.Chart.kbest. Apply combiner to
a chart Item and a dictionary mapping nonterminals (and indices) to the result of
all child items.
"""
if type(derivation) is not tuple:
if derivation =... | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_skipped_reason(data):
"""Return test case skip reason from report string.
Args:
data(str): test case report
Returns:
str: skip reason or None
"""
try:
reason_rules = re.compile("Skipped:(.*?)..$")
return ('\n'.join(reason_rules.findall(data))).s... | bigcode/self-oss-instruct-sc2-concepts |
import binascii
import logging
def checkHeader(filename, headers, size):
"""
The checkHeader function reads a supplied size of the file and checks against known signatures to determine
the file type.
:param filename: The name of the file.
:param headers: A list of known file signatures for the fil... | bigcode/self-oss-instruct-sc2-concepts |
def replace_tup(tupl, old, new, count=-1):
"""
Creates a copy of ``tupl`` with all occurrences of value ``old`` replaced by ``new``.
Objects are replaced by value equality, not id equality (i.e. ``==`` not ``is``).
If the optional argument ``count`` is given, only the first count occurrences are
... | bigcode/self-oss-instruct-sc2-concepts |
def identifier_to_flag(identifier):
"""
Turn an identifier back into its flag format (e.g., "Flag" -> --flag).
"""
if identifier.startswith('-'):
raise ValueError('expected identifier, not flag name: %r' % identifier)
ret = identifier.lower().replace('_', '-')
return '--' + ret | bigcode/self-oss-instruct-sc2-concepts |
import csv
def write_csv(csv_list, filename):
"""
writes a single csv file to the current directory
:param csv_list: 2d list containing the csv contents
:param filename: name of the newly created csv file
:return: True if write successful, False if not
"""
try:
with open(filename,... | bigcode/self-oss-instruct-sc2-concepts |
def ptsort(tu):
"""Return first element of input."""
return tu[0] | bigcode/self-oss-instruct-sc2-concepts |
def probe(value):
"""
Factorization of n by probing.
:param n: value to factorize.
:returns: all proper divisors of n.
>>> probe(10)
[1, 2, 5, 10]
>>> probe(12)
[1, 2, 3, 4, 6, 12]
"""
value = abs(value)
limit = value // 2
divisors = [1]
divisor = 2
while divis... | bigcode/self-oss-instruct-sc2-concepts |
def find_ancilla_values(counts, ancilla_qubits, ancilla_location = 0):
"""Returns a dictionary with a count of each possible ancilla bit string.
Parameters
----------
counts : dictionary
counts for each possible output bit string
ancilla_qubits : int
number of ancilla qubits
anc... | bigcode/self-oss-instruct-sc2-concepts |
def destroy_lvol_store(client, uuid=None, lvs_name=None):
"""Destroy a logical volume store.
Args:
uuid: UUID of logical volume store to destroy (optional)
lvs_name: name of logical volume store to destroy (optional)
Either uuid or lvs_name must be specified, but not both.
"""
if (... | bigcode/self-oss-instruct-sc2-concepts |
def url_normalize(url: str):
"""
Convert a URL into the standard format
"""
if url.startswith('//'):
return 'http:' + url
if url.startswith('www'):
return 'http://' + url
if not url.startswith('http'):
return 'http://' + url
return url | bigcode/self-oss-instruct-sc2-concepts |
def gaze_duration(interest_area, fixation_sequence):
"""
Given an interest area and fixation sequence, return the gaze duration on
that interest area. Gaze duration is the sum duration of all fixations
inside an interest area until the area is exited for the first time.
"""
duration = 0
fo... | bigcode/self-oss-instruct-sc2-concepts |
def decrypt(ciphertext, cipher, shift):
"""
Caesar decryption of a ciphertext using a shifted cipher.
:param ciphertext: the encrypted plaintext to decrypt.
:param cipher: set of characters, shifted in a directed to used for character substitution.
:param shift: offset to rotate cipher.
:return... | bigcode/self-oss-instruct-sc2-concepts |
import glob
def make_fileslist(path_list):
"""Get lists of files from paths which may contains wildcards and symbols."""
ret = []
for p in path_list:
ret += glob.glob(p)
return ret | bigcode/self-oss-instruct-sc2-concepts |
def T1_sequence(length, target):
"""
Generate a gate sequence to measure relaxation time in a two-qubit chip.
Parameters
----------
length : int
Number of Identity gates.
target : int
Which qubit is measured.
Returns
-------
list
Relaxation sequence.
""... | bigcode/self-oss-instruct-sc2-concepts |
def create_element(doc, parent, tag, value=None, attributes=None):
"""
Creates an XML element
"""
ele = doc.createElement(tag)
parent.appendChild(ele)
if value:
text = doc.createTextNode(u"%s" % value)
ele.appendChild(text)
if attributes:
[ele.setAttribute(k, str(v)) ... | bigcode/self-oss-instruct-sc2-concepts |
def get_min_max_values(data, col1, col2):
"""
extracts min and max value of two columns
:param data: ptcf data frame
:param col1: column 1
:param col1: column 2
:return: dict of min and max values of two columns
"""
return {
'ds1_min' : data[col1].min(),
'ds1_max' : data[col1].max(),
'ds2_... | bigcode/self-oss-instruct-sc2-concepts |
def create_dict_node_enode(set_proj_nodes, neighbors_dict, H, node, dict_node_enode, dict_enode_node):
"""
A function to create useful dictionaries to represent connections between nodes that are in the embedding and
nodes that are not in the embedding.
:param set_proj_nodes: Set of the nodes that are i... | bigcode/self-oss-instruct-sc2-concepts |
def upper(value):
"""Uppercase the string passed as argument"""
return value.upper() if value else value | bigcode/self-oss-instruct-sc2-concepts |
def pwr2modp(k, p):
"""Return 2**k mod p for any integer k"""
if k < 0:
assert p & 1
return pow((p + 1) >> 1, -k, p)
return pow(2, k, p) | bigcode/self-oss-instruct-sc2-concepts |
def QuadraticLimbDarkening(Impact, limb1, limb2):
"""Quadratic limb darkening. Kopal 1950, Harvard Col. Obs. Circ., 454, 1"""
return 1 - limb1 * (1 - Impact) - limb2 * (1 - Impact) ** 2 | bigcode/self-oss-instruct-sc2-concepts |
import re
def parse_bucket_url(url):
"""
Parse s3 url to get bucket name and object name.
input: s3://test/templates/3.0/post_install.sh
output: {"bucket_name": "test", "object_key": "templates/3.0/post_install.sh", "object_name": "post_install.sh"}
"""
match = re.match(r"s3://(.*?)/(.*)", ur... | bigcode/self-oss-instruct-sc2-concepts |
def scan_reverse(f, arr):
"""Scan over a list in reverse, using a function"""
r=list(arr)
for i in reversed(range(len(r))[1:]):
r[i-1] = f(r[i-1],r[i])
return r | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def juxtapose_text(text_a, text_b, buffer_len=15):
"""Places text_a to the left of text_b with a buffer of spaces in between"""
lines_a = text_a.splitlines()
lines_b = text_b.splitlines()
longest_line_length_a = max(map(len, lines_a))
paired_lines = itertools.zip_longest(lines_a, ... | bigcode/self-oss-instruct-sc2-concepts |
def color2gray(x):
"""Convert an RGB or RGBA (Red Green Blue Alpha) color tuple
to a grayscale value."""
if len(x) == 3:
r, g, b = x
a = 1
elif len(x) == 4:
r, g, b, a = x
else:
raise ValueError("Incorrect tuple length")
return (r * 0.299 + 0.587*g + 0.114*b) *... | bigcode/self-oss-instruct-sc2-concepts |
def pax_to_human_time(num):
"""Converts a pax time to a human-readable representation"""
for x in ['ns', 'us', 'ms', 's', 'ks', 'Ms', 'G', 'T']:
if num < 1000.0:
return "%3.3f %s" % (num, x)
num /= 1000.0
return "%3.1f %s" % (num, 's') | bigcode/self-oss-instruct-sc2-concepts |
def check_answer(guess, a_followers, b_followers):
"""Take the user guess and follower counts and returns if they got it right."""
if a_followers > b_followers:
return guess == "a"
else:
return guess == "b" | bigcode/self-oss-instruct-sc2-concepts |
def to_yellow(string):
""" Converts a string to yellow color (8bit)
Returns:
str: the string in yellow color
"""
return f"\u001b[33m{string}\u001b[0m" | bigcode/self-oss-instruct-sc2-concepts |
def parse_json(request):
"""
Default content parser for JSON
"""
return request.json | bigcode/self-oss-instruct-sc2-concepts |
def getUrl(sIpAddress):
"""Returns the full cgi URL of the target"""
return 'http://' + sIpAddress + '/cgi-bin/xml-cgi' | bigcode/self-oss-instruct-sc2-concepts |
def _initial_gaussian_params(xm, ym, z, width=5):
"""
Guesses the initial 2D Gaussian parameters given a spatial filter.
Parameters
----------
xm : array_like
The x-points for the filter.
ym : array_like
The y-points for the filter.
z : array_like
The actual data t... | bigcode/self-oss-instruct-sc2-concepts |
import re
def requires(prefix=''):
"""Retrieve requirements from requirements.txt
"""
try:
reqs = map(str.strip, open(prefix + 'requirements.txt').readlines())
return [req for req in reqs if not re.match(r'\W', req)]
except Exception:
pass
return [] | 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.