seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def string_list_handler(option_value=None):
"""Split a comma-separated string into a list of strings."""
result = None
if option_value is not None:
result = option_value.split(',')
return result | bigcode/self-oss-instruct-sc2-concepts |
def IsImageFile(ext):
"""IsImageFile(ext) -> bool
Determines if the given extension corresponds to an image file (jpg, bmp,
or png).
arguments:
ext
string corresponding to extension to check.
returns:
bool corresponding to whether it is an image file.
... | bigcode/self-oss-instruct-sc2-concepts |
def ensure_support_staging_jobs_have_correct_keys(
support_and_staging_matrix_jobs: list, prod_hub_matrix_jobs: list
) -> list:
"""This function ensures that all entries in support_and_staging_matrix_jobs have
the expected upgrade_staging and eason_for_staging_redeploy keys, even if they are
set to fals... | bigcode/self-oss-instruct-sc2-concepts |
def readlines_with_strip(filename):
"""Reads lines from specified file with whitespaced removed on both sides.
The function reads each line in the specified file and applies string.strip()
function to each line which results in removing all whitespaces on both ends
of each string. Also removes the newli... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Counter
def most_frequent(List):
"""Counts the most_frequent element in list"""
occurence_count = Counter(List)
return occurence_count.most_common(1)[0][0] | bigcode/self-oss-instruct-sc2-concepts |
def CountBenchmarks(benchmark_runs):
"""Counts the number of iterations for each benchmark in benchmark_runs."""
# Example input for benchmark_runs:
# {"bench": [[run1, run2, run3], [run1, run2, run3, run4]]}
def _MaxLen(results):
return 0 if not results else max(len(r) for r in results)
return [(name, _M... | bigcode/self-oss-instruct-sc2-concepts |
def window(x, win_len, win_stride, win_fn):
"""
Apply a window function to an array with window size win_len, advancing at win_stride.
:param x: Array
:param win_len: Number of samples per window
:param win_stride: Stride to advance current window
:param win_fn: Callable window function. Takes ... | bigcode/self-oss-instruct-sc2-concepts |
def iswritable(f):
"""
Returns True if the file-like object can be written to. This is a common-
sense approximation of io.IOBase.writable.
"""
if hasattr(f, 'writable'):
return f.writable()
if hasattr(f, 'closed') and f.closed:
# This mimics the behavior of io.IOBase.writable... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def batch_inference_result_split(results: List, keys: List):
"""
Split inference result into a dict with provided key and result dicts.
The length of results and keys must match
:param results:
:param keys:
:return:
"""
ret = {}
for result, key in zip(resul... | bigcode/self-oss-instruct-sc2-concepts |
def read_ip_config(filename):
"""Read network configuration information of kvstore from file.
The format of configuration file should be:
[ip] [base_port] [server_count]
172.31.40.143 30050 2
172.31.36.140 30050 2
172.31.47.147 30050 2
172.31.30.180 30050 2
Note t... | bigcode/self-oss-instruct-sc2-concepts |
def get_table_row(table, td_text):
""" Find a row in a table that has td_text as one column's text """
td = table.find('td', string=td_text)
if td is None:
return None
return td.find_parent('tr') | bigcode/self-oss-instruct-sc2-concepts |
def breakpoint_callback(frame, bp_loc, dict):
"""This callback is registered with every breakpoint and makes sure that the
frame containing the breakpoint location is selected """
# HACK(eddyb) print a newline to avoid continuing an unfinished line.
print("")
print("Hit breakpoint " + str(bp_loc))
... | bigcode/self-oss-instruct-sc2-concepts |
import pathlib
def _stringify_path(path_or_buffer):
"""Convert path like object to string
Args:
path_or_buffer: object to be converted
Returns:
string_path_or_buffer: maybe string version of path_or_buffer
"""
try:
_PATHLIB_INSTALLED = True
except ImportError:
... | bigcode/self-oss-instruct-sc2-concepts |
def _get_gmt_dict(filename):
"""Parse gmt files and get gene sets."""
with open(filename, 'r') as f:
content = [line.strip().split('\t') for line in f]
return {pathway[0]: pathway[2:] for pathway in content} | bigcode/self-oss-instruct-sc2-concepts |
def EqualSpacedColmunTable(items,
table_width=80,
table_indent=2,
column_pad=2):
"""Construct a table of equal-spaced columns from items in a string array.
The number of columns is determined by the data. The table will contain at
... | bigcode/self-oss-instruct-sc2-concepts |
def make_voc_seed_func(entry_rate, start_time, seed_duration):
"""
Create a simple step function to allow seeding of the VoC strain at a particular point in time.
"""
def voc_seed_func(time, computed_values):
return entry_rate if 0. < time - start_time < seed_duration else 0.
return voc_se... | bigcode/self-oss-instruct-sc2-concepts |
import socket
def init_socket(port):
"""
Init socket at specified port. Listen for connections.
Return socket obj.
Keyword arguments:
port -- port at whicch to init socket (int)
"""
connection_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connection_socket.bind(('', port))
connection_socket.l... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def _split_list(string: str) -> List[str]:
"""Assumes an input of the form `[s1, s2, s3, ..., sn]`,
where each si may itself contain lists."""
assert string[0] == "[" and string[-1] == "]"
nesting_depth = 0
all_strings = []
current_string = ""
for character in strin... | bigcode/self-oss-instruct-sc2-concepts |
def get_model_state_dict(model):
"""Get model state dict."""
return {k: v for k, v in model.state_dict().items()} | bigcode/self-oss-instruct-sc2-concepts |
import ast
def calculate_issues_count(issues: str) -> int:
""" Parse issues list and calculate number of issues. """
return len(ast.literal_eval(issues)) | bigcode/self-oss-instruct-sc2-concepts |
def _contains_isolated_cores(label, cluster, min_cores):
"""Check if the cluster has at least ``min_cores`` of cores that belong to no other cluster."""
return sum([neighboring_labels == {label} for neighboring_labels in cluster.neighboring_labels]) >= min_cores | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
def upper(value) -> Optional[str]:
"""Converter to change a string to uppercase, if applicable"""
return value.upper() if isinstance(value, str) else None | bigcode/self-oss-instruct-sc2-concepts |
def _call_member(obj, name, args=None, failfast=True):
""" Calls the specified method, property or attribute of the given object
Parameters
----------
obj : object
The object that will be used
name : str
Name of method, property or attribute
args : dict, optional, default=None
... | bigcode/self-oss-instruct-sc2-concepts |
def doc_view(request):
"""View for documentation route."""
return {
'page': 'Documentation'
} | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def bounding_box_to_polygon(
left: float, bottom: float, right: float, top: float
) -> List[List[float]]:
"""
Transform bounding box to polygon
:param left: left bound
:param bottom: bottom bound
:param right: right bound
:param top: top bound
:return: polygon
... | bigcode/self-oss-instruct-sc2-concepts |
def strnum(prefix: str, num: int, suffix: str = "") -> str:
"""
Makes a string of the format ``<prefix><number><suffix>``.
"""
return f"{prefix}{num}{suffix}" | bigcode/self-oss-instruct-sc2-concepts |
def get_region_dict(region, maxRegionSize=None, tilesource=None):
"""Return a dict corresponding to region, checking the region size if
maxRegionSize is provided.
The intended use is to be passed via **kwargs, and so either {} is
returned (for the special region -1,-1,-1,-1) or {'region':
region_dic... | bigcode/self-oss-instruct-sc2-concepts |
def initialize_back_prop(AL, Y, AL_prime, Y_prime):
"""
Initialize backward propagation
Arguments:
:param AL -- output of the forward propagation L_model_forward()... i.e. neural net predictions (if regression)
i.e. neural net probabili... | bigcode/self-oss-instruct-sc2-concepts |
def replaceline(f, match, lines):
"""Replace matching line in file with lines."""
for i in range(len(f)):
if match in f[i]:
return f[:i] + lines + f[i+1:]
return f | bigcode/self-oss-instruct-sc2-concepts |
import requests
def http_get(url, fout=None):
"""Download a file from http. Save it in a file named by fout"""
print('requests.get({URL}, stream=True)'.format(URL=url))
rsp = requests.get(url, stream=True)
if rsp.status_code == 200 and fout is not None:
with open(fout, 'wb') as prt:
... | bigcode/self-oss-instruct-sc2-concepts |
import yaml
def read_yaml(yaml_file):
"""Read a yaml file.
Args:
yaml_file (str): Full path of the yaml file.
Returns:
data (dict): Dictionary of yaml_file contents. None is returned if an
error occurs while reading.
"""
data = None
with open(yaml_file) as f:
... | bigcode/self-oss-instruct-sc2-concepts |
def c_escaped_string(data: bytes):
"""Generates a C byte string representation for a byte array
For example, given a byte sequence of [0x12, 0x34, 0x56]. The function
generates the following byte string code:
{"\x12\x34\x56", 3}
"""
body = ''.join([f'\\x{b:02x}' for b in data])
ret... | bigcode/self-oss-instruct-sc2-concepts |
def test_object_type(obj: object, thetype: type):
"""Tests if the given object is of the specified type. Returns a Boolean True or False.
Examples:
>>> myint = 34
>>> test_object_type(myint, int)
True
>>> isinstance(myint, int)
True
>>> test_object_type(myint, s... | bigcode/self-oss-instruct-sc2-concepts |
import re
def remove_leading_space(string: str) -> str:
"""
Remove the leading space of a string at every line.
:param string: String to be processed
:type string: str
:return: Result string
:rtype: str
**Example:**
.. code-block:: python
string = " Hello \\nWorld!"
... | bigcode/self-oss-instruct-sc2-concepts |
def qb_account(item_title):
"""
Given an item title, returns the appropriate QuickBooks class and account
Parameter: item_title
Returns: item_class, item_account
Note that this is only guaranteed to work for Ticketleap sales, not
PayPal invoices.
"""
if 'Northern' in item... | bigcode/self-oss-instruct-sc2-concepts |
def bottom_row(matrix):
"""
Return the last (bottom) row of a matrix.
Returns a tuple (immutable).
"""
return tuple(matrix[-1]) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
def success_of_action_dict(**messages) -> Dict:
"""Parses the overall success of a dictionary of actions, where the key is an action name and the value is a dictionarised Misty2pyResponse. `overall_success` is only true if all actions were successful.
Returns:
Dict: The dictio... | bigcode/self-oss-instruct-sc2-concepts |
def clip(value, min, max):
"""Clips (limits) the value to the given limits.
The output is at least `min`, at most `max` and `value` if that value
is between the `min` and `max`.
Args:
value: to be limited to [min, max]
min: smallest acceptable value
max: greatest acceptable val... | bigcode/self-oss-instruct-sc2-concepts |
def is_variable_geometry(xmldoc):
"""
Tries to guess whether the calculation involves changes in
geometry.
"""
itemlist = xmldoc.getElementsByTagName('module')
for item in itemlist:
# Check there is a step which is a "geometry optimization" one
if 'dictRef' in list(item.attri... | bigcode/self-oss-instruct-sc2-concepts |
def convertConfigDict(origDict, sep="."):
"""
For each key in the dictionary of the form <section>.<option>,
a separate dictionary for is formed for every "key" - <section>,
while the <option>s become the keys for the inner dictionary.
Returns a dictionary of dictionary.
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def parse_csv_data(csv_filename: str) -> list[str]:
"""Returns a list of strings representing each row in a given file"""
file = open("data/" + csv_filename, "r", encoding="utf-8")
lstrows = []
for line in file:
lstrows.append(line.rstrip())
file.close()
return lstrows | bigcode/self-oss-instruct-sc2-concepts |
def merge_means(mu1, mu2, n1, n2):
"""Merges means. Requires n1 + n2 > 0."""
total = n1 + n2
return (n1 * mu1 + n2 * mu2) / total | bigcode/self-oss-instruct-sc2-concepts |
import six
def get_comparable_revisits(query_metadata_table):
"""Return a dict location -> set of revisit locations for that starting location."""
revisit_origins = {
query_metadata_table.get_revisit_origin(location)
for location, _ in query_metadata_table.registered_locations
}
inter... | bigcode/self-oss-instruct-sc2-concepts |
def torch_to_np(images):
"""Transforms the unnormalized output of a gan into a numpy array
Args:
images (torch.tensor): unnormalized output of a gan
Returns:
(numpy.array)
"""
return ((images.clamp(min=-1, max=1) + 1) / 2).permute(0, 2, 3, 1).cpu().detach().numpy() | bigcode/self-oss-instruct-sc2-concepts |
def lookup_dunder_prop(obj, props, multi=False):
"""
Take an obj and lookup the value of a related attribute
using __ notation.
For example if Obj.a.b.c == "foo" then lookup_dunder (Obj, "a__b__c") == "foo"
"""
try:
if "__" in props:
head, tail = props.split("__", 1)
... | bigcode/self-oss-instruct-sc2-concepts |
import operator
def filter_prefix(candidates: set[str], prefix: str = '', ones_operator=operator.ge) -> int:
"""Filter a set of binary number strings by prefix, returning a single int.
This function considers a set of candidate strings, which must encode
valid binary numbers. They are iteratively filtere... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def precisionk(actual, predicted, topk=(1, 5)):
"""
Computes the precision@k for the specified values of k.
# Parameters
actual : `Sequence[Sequence[int]]`, required
Actual labels for a batch sized input.
predicted : `Sequence[Sequence[int]]`, required
Predicted labels f... | bigcode/self-oss-instruct-sc2-concepts |
def image_size(img):
"""
Gets the size of an image eg. 350x350
"""
return tuple(img.shape[1:: -1]) | bigcode/self-oss-instruct-sc2-concepts |
def revcomp(s):
"""Returns the reverse compliment of a sequence"""
t = s[:]
t.reverse()
rc = {'A':'T', 'C':'G', 'G':'C', 'T':'A', 'N':'N'}
t = [rc[x] for x in t]
return t | bigcode/self-oss-instruct-sc2-concepts |
def relu(x, c = 0):
"""
Compute the value of the relu function with parameter c, for a given point x.
:param x: (float) input coordinate
:param c: (float) shifting parameter
:return: (float) the value of the relu function
"""
return c + max(0.0, x) | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def is_notebook(path: Path) -> bool:
"""
Checks whether the given file path is Jupyter Notebook or not.
Parameters
----------
path: Path
Path of the file to check whether it is Jupyter Notebook or not.
Returns
------
Returns True when file is Jupyter N... | bigcode/self-oss-instruct-sc2-concepts |
def is_highlighted_ins(e):
"""Returns True if e matches the following pattern:
<ins>highlighted</ins> text:
See `fragment_chunks` comment for the details
"""
if len(e) != 0:
return False
if not e.text:
return False
if e.text != 'highlighted':
return False
i... | bigcode/self-oss-instruct-sc2-concepts |
async def admin(mixer):
"""Generate an admin user."""
admin = mixer.blend('example.models.User', email='admin@example.com', is_super=True)
admin.password = admin.generate_password('pass')
return await admin.save(force_insert=True) | bigcode/self-oss-instruct-sc2-concepts |
def bw24(x):
"""Return the bit weight of the lowest 24 bits of x"""
x = (x & 0x555555) + ((x & 0xaaaaaa) >> 1)
x = (x & 0x333333) + ((x & 0xcccccc) >> 2)
x = (x + (x >> 4)) & 0xf0f0f
return (x + (x >> 8) + (x >> 16)) & 0x1f | bigcode/self-oss-instruct-sc2-concepts |
def project_data(samples, U, K):
"""
Computes the reduced data representation when
projecting only on to the top "K" eigenvectors
"""
# Reduced U is the first "K" columns in U
reduced_U = U[:, :K]
return samples.dot(reduced_U) | bigcode/self-oss-instruct-sc2-concepts |
def ROStime_to_NTP64(ROStime):
""" Convert rospy.Time object to a 64bit NTP timestamp
@param ROStime: timestamp
@type ROStime: rospy.Time
@return: 64bit NTP representation of the input
@rtype: int
"""
NTPtime = ROStime.secs << 32
# NTPtime |= nanoseconds * 2^31 / 1x10^9
NTPtime |= i... | bigcode/self-oss-instruct-sc2-concepts |
def reverse_dict(dictionary):
"""Reverse a dictionary.
Keys become values and vice versa.
Parameters
----------
dictionary : dict
Dictionary to reverse
Returns
-------
dict
Reversed dictionary
Raises
------
TypeError
If there is a value which is un... | bigcode/self-oss-instruct-sc2-concepts |
def expp_xor_indep(p1, p2):
"""
Probability of term t1 XOR t2 being 1 if t1 is 1 with p1 and t2 is 1 with p2.
t1 and t2 has to be independent (no common sub-term).
Due to associativity can be computed on multiple terms: t1 ^ t2 ^ t3 ^ t4 = (((t1 ^ t2) ^ t3) ^ t4) - zipping.
XOR:
a b | r
... | bigcode/self-oss-instruct-sc2-concepts |
def noOut(_):
"""Outputs nothing."""
return None | bigcode/self-oss-instruct-sc2-concepts |
import torch
def conv3x3(in_channel, out_channel, stride=1, padding=1,dilation=1, bias=True):
"""3x3 convolution with padding"""
return torch.nn.Conv2d(in_channel,
out_channel,
kernel_size=(3,3),
stride=(stride,stride),
... | bigcode/self-oss-instruct-sc2-concepts |
def length_of_range(range):
"""Helper- returns the length of a range from start to finish in ms"""
return range[1] - range[0] | bigcode/self-oss-instruct-sc2-concepts |
def listify(x, none_value=[]):
"""Make a list of the argument if it is not a list."""
if isinstance(x, list):
return x
elif isinstance(x, tuple):
return list(x)
elif x is None:
return none_value
else:
return [x] | bigcode/self-oss-instruct-sc2-concepts |
def unique(iterable):
"""Return an iterable of the same type which contains unique items.
This function assumes that:
type(iterable)(list(iterable)) == iterable
which is true for tuples, lists and deques (but not for strings)
>>> unique([1, 2, 3, 1, 2, 3, 4, 2, 3, 4, 1, 1, 2])
[1, 2, 3, 4]
... | bigcode/self-oss-instruct-sc2-concepts |
def qc_syntax_test(self):
"""
It verifies that wf.data contains the recomentated data structure to pass
the rest of the QC test. Each parameter (for example, TEMP) and each index
(for example, TIME) must have a column with the flags of the values
(for example, TEMP_QC and TIME_QC).
Returns
... | bigcode/self-oss-instruct-sc2-concepts |
def modified(number, percent):
"""return the amount (or any other number) with added margin given by percent parameter
(result has type float)
"""
if percent:
return number * (100 + percent) / 100.
else:
return float(number) | bigcode/self-oss-instruct-sc2-concepts |
def print_bytearray(array: bytearray) -> str:
"""Outputs string of all bytes in HEX without any formatting.
Parameters
----------
array : byte array
The byte array to be printed.
Returns
-------
str
A string representation of the byte array in HEX format.
"""
string... | bigcode/self-oss-instruct-sc2-concepts |
def get_row_nnz(mat, row):
"""Return the number of nonzeros in row.
"""
return mat.indptr[row+1] - mat.indptr[row] | bigcode/self-oss-instruct-sc2-concepts |
import torch
def zero_out_col_span(xfft, col, start_row, end_row=None):
"""
Zero out values for all data points, channels, in the given column and row
span.
:param xfft: input complex tensor
:param col: the col number to zero out value
:param start_row: the start row (inclusive, it is zeroed ... | bigcode/self-oss-instruct-sc2-concepts |
def weWantThisPixel(col, row):
""" a function that returns True if we want # @IndentOk
the pixel at col, row and False otherwise
"""
if col%10 == 0 and row%10 == 0:
return True
else:
return False | bigcode/self-oss-instruct-sc2-concepts |
import calendar
def date_to_dow(y, m, d):
"""
Gets the integer day of week for a date. Sunday is 0.
"""
# Python uses Monday week start, so wrap around
w = calendar.weekday(y, m, d) + 1
if w == 7:
w = 0
return w | bigcode/self-oss-instruct-sc2-concepts |
def hi_to_wbgt(HI):
""" Convert HI to WBGT using emprical relationship from Bernard and Iheanacho 2015
WBGT [◦C] = −0.0034 HI2 + 0.96 HI−34; for HI [◦F]
Args:
HI = heat index as an array
"""
WBGT = -0.0034*HI**2 + 0.96*HI - 34
return WBGT | bigcode/self-oss-instruct-sc2-concepts |
def shimbel(w):
"""
Find the Shimbel matrix for first order contiguity matrix.
Parameters
----------
w : W
spatial weights object
Returns
-------
info : list
list of lists; one list for each observation which stores
the shortest order between i... | bigcode/self-oss-instruct-sc2-concepts |
def counts_to_probabilities(counts):
""" Convert a dictionary of counts to probalities.
Argument:
counts - a dictionary mapping from items to integers
Returns:
A new dictionary where each count has been divided by the sum
of all entries in counts.
Example:
>>> counts_to_prob... | bigcode/self-oss-instruct-sc2-concepts |
def array_set_diag(arr, val, row_labels, col_labels):
"""
Sets the diagonal of an 2D array to a value. Diagonal in this case is anything where row label == column label.
:param arr: Array to modify in place
:type arr: np.ndarray
:param val: Value to insert into any cells where row label == column l... | bigcode/self-oss-instruct-sc2-concepts |
import json
def _format_modules(data):
"""Form module data for JSON."""
modules = []
# Format modules data for json usage
for item in data:
if item.startswith('module_'):
val_json = json.loads(data[item])
modules.append(val_json)
return modules | bigcode/self-oss-instruct-sc2-concepts |
def get_sparkconfig(session):
""" Returns config information used in the SparkSession
Parameters
----------
session : SparkSession
Returns
-------
dict : Dictionary representing spark session configuration
"""
conf = session.sparkContext.getConf().getAll()
return conf | bigcode/self-oss-instruct-sc2-concepts |
def stride_chainid_to_pdb_chainid(stride_chainid):
"""
Convert a STRIDE chainid to a PDB chainid.
STRIDE uses '-' for a 'blank' chainid while PDB uses ' ' (space).
So all this does is return the stride_chainid unless it is '-', then
it returns ' '.
Parameters:
stride_chainid - the STRID... | bigcode/self-oss-instruct-sc2-concepts |
def doc_to_labels(document):
"""
Converts document to a label: list of cluster ids.
:param document: Document object
:return: list of cluster ids.
"""
labels = []
word_to_cluster = document.words_to_clusters()
cluster_to_id = {cluster:cluster_id for cluster_id, cluster in enumerate(docum... | bigcode/self-oss-instruct-sc2-concepts |
def _GetChangePath(change):
"""Given a change id, return a path prefix for the change."""
return 'changes/%s' % str(change).replace('/', '%2F') | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def list_hash(str_list):
"""
Return a hash value for a given list of string.
:param str_list: a list of strings (e.g. x_test)
:type str_list: list (of str)
:returns: an MD5 hash value
:rtype: str
"""
m = hashlib.md5()
for doc in str_list:
try:
m.... | bigcode/self-oss-instruct-sc2-concepts |
def computeDelayMatrix(lengthMat, signalV, segmentLength=1):
"""
Compute the delay matrix from the fiber length matrix and the signal
velocity
:param lengthMat: A matrix containing the connection length in
segment
:param signalV: Signal velocity in m/s
:par... | bigcode/self-oss-instruct-sc2-concepts |
def present(ds, t0):
"""
Return clouds that are present at time `t0`
"""
# time of appearance
tmin = ds.tmin
# time of disappearance
tmax = ds.tmax
m = (tmin <= t0) & (t0 <= tmax)
return m | bigcode/self-oss-instruct-sc2-concepts |
def WI_statewide_eqn(Qm, A, Qr, Q90):
"""Regression equation of Gebert and others (2007, 2011)
for estimating average annual baseflow from a field measurement of streamflow
during low-flow conditions.
Parameters
----------
Qm : float or 1-D array of floats
Measured streamflow.
A : f... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def time_elapsed_since(start):
"""Computes elapsed time since start."""
timedelta = datetime.now() - start
string = str(timedelta)[:-7]
ms = int(timedelta.total_seconds() * 1000)
return string, ms | bigcode/self-oss-instruct-sc2-concepts |
import ipaddress
def is_valid_ip(ip: str):
"""Return True if IP address is valid."""
try:
if ipaddress.ip_address(ip).version == (4 or 6):
return True
except ValueError:
return False | bigcode/self-oss-instruct-sc2-concepts |
def get_user_id(user):
"""Return id attribute of the object if it is relation, otherwise return given value."""
return user.id if type(user).__name__ == "User" else user | bigcode/self-oss-instruct-sc2-concepts |
def append_a(string):
"""Append "_a" to string and return the modified string"""
string = '{}{}'.format(string, '_a')
return string | bigcode/self-oss-instruct-sc2-concepts |
def disable_control_flow_v2(unused_msg):
"""Decorator for a function in a with_control_flow_v2 enabled test class.
Blocks the function from being run with v2 control flow ops.
Args:
unused_msg: Reason for disabling.
Returns:
The wrapped function with _disable_control_flow_v2 attr set to True.
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def get_list_uniques(_list):
"""
This function returns the unique/s value/s of a given list.
:param _list: List
:return: List containing unique values.
"""
ret = []
for it in _list:
if it not in ret:
ret.append(it)
return ret | bigcode/self-oss-instruct-sc2-concepts |
def vi700(b4, b5):
"""
Vegetation Index 700 (Gitelson et al., 2002).
.. math:: VI700 = (b5 - b4)/(b5 + b4)
:param b4: Red.
:type b4: numpy.ndarray or float
:param b5: Red-edge 1.
:type b5: numpy.ndarray or float
:returns VI700: Index value
.. Tip::
Gitelson, A. A., Kaufm... | bigcode/self-oss-instruct-sc2-concepts |
import json
def get_json(json_str, encoding='utf-8'):
"""
Return a list or dictionary converted from an encoded json_str.
json_str (str): JSON string to be decoded and converted
encoding (str): encoding used by json_str
"""
return json.loads(json_str.decode(encoding)) | bigcode/self-oss-instruct-sc2-concepts |
def joueur_continuer() -> bool:
""" Cette fonction est utilisée pour demander au joueur s'il veut continuer ou non de piocher.
Returns:
bool: Retourne True si le joueur veut piocher, False sinon.
"""
continuer_le_jeux = input("Voulez-vous piocher? y ou n ")
if continuer_le_jeux == "y":
... | bigcode/self-oss-instruct-sc2-concepts |
def resend_strawpoll(jenni, input):
""".resendstrawpoll - Resends the last strawpoll link created"""
if hasattr(jenni.config, "last_strawpoll"):
channel = input.sender
if channel in jenni.config.last_strawpoll:
return jenni.say(jenni.config.last_strawpoll[channel])
jenni.say("No ... | bigcode/self-oss-instruct-sc2-concepts |
import re
def replaceTags(value, data_record):
"""
As efficiently as possible, replace tags in input string with corresponding values in
data_record dictionary.
The idea is to iterate through all of the elements of the data_record, and replace each
instance of a bracketed key in the input string ... | bigcode/self-oss-instruct-sc2-concepts |
def LastLineLength(s):
"""Returns the length of the last line in s.
Args:
s: A multi-line string, including newlines.
Returns:
The length of the last line in s, in characters.
"""
if s.rfind('\n') == -1: return len(s)
return len(s) - s.rfind('\n') - len('\n') | bigcode/self-oss-instruct-sc2-concepts |
def input_int(prompt: str, min_val: int = 1, max_val: int = 5) -> int:
"""Get an integer from the user"""
while True:
try:
user_input = int(input(prompt))
if min_val <= user_input <= max_val:
return user_input
print("Value not within range. Try again!"... | bigcode/self-oss-instruct-sc2-concepts |
import pathlib
def get_test_cases(which_subset):
"""Return a list of test case files."""
assert which_subset in ("valid", "invalid")
cwd = pathlib.Path(__file__).parent.resolve()
test_dir = cwd / ".." / "demes-spec" / "test-cases" / which_subset
files = [str(file) for file in test_dir.glob("*.yaml... | bigcode/self-oss-instruct-sc2-concepts |
def is_info_hash_valid(data: bytes, info_hash: bytes) -> bool:
"""
Checks if the info_hash sent by another peer matches ours.
"""
return data[28:48] == info_hash | bigcode/self-oss-instruct-sc2-concepts |
def dict_diff(a, b):
"""Returns the difference between two dictionaries.
Parameters
----------
a : dict
The dictionary to prefer different results from.
b : dict
The dictionary to compare against.
Returns
-------
dict
A dictionary with only the different keys: v... | bigcode/self-oss-instruct-sc2-concepts |
def read_ccloud_config(config_file):
"""Read Confluent Cloud configuration for librdkafka clients"""
conf = {}
with open(config_file) as fh:
for line in fh:
line = line.strip()
if line[0] != "#" and len(line) != 0:
parameter, value = line.strip().split('=', 1... | 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.