seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def insert_instr(qobj, exp_index, item, pos):
"""Insert a QasmQobjInstruction into a QobjExperiment.
Args:
qobj (Qobj): a Qobj object
exp_index (int): The index of the experiment in the qobj.
instruction(QasmQobjInstruction): instruction to insert.
pos (int): the position to ins... | bigcode/self-oss-instruct-sc2-concepts |
def __points_to_dict(points):
"""transform list of [x, y] into a dict() where {x: y}"""
return {p[0]: p[1] for p in points} | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def CalculateSha256Checksum(filename):
"""Calculate the sha256 checksum for filename."""
sha = hashlib.sha256()
with open(filename, 'rb') as f:
data = f.read(65536)
while len(data) > 0:
sha.update(data)
data = f.read(65536)
return sha.hexdigest() | bigcode/self-oss-instruct-sc2-concepts |
def escapeBelString(belstring):
"""Escape double quotes in BEL string"""
return belstring.replace('"', '\\"') | bigcode/self-oss-instruct-sc2-concepts |
def first_and_last(sequence):
"""Returns the first and last elements of a sequence"""
return sequence[0], sequence[-1] | bigcode/self-oss-instruct-sc2-concepts |
def multiplica(x, y=2.0):
"""Multiplica dos números, por defecto el primero por 2."""
return x * y | bigcode/self-oss-instruct-sc2-concepts |
def get_floor(directions):
"""
Get the floor for Santa.
Parameters
----------
directions : str
A string of parentheses representing directions. An opening parenthesis,
(, means he should go up one floor, and a closing parenthesis, ), means
he should go down one floor.
R... | bigcode/self-oss-instruct-sc2-concepts |
def get_randaug(aug: str) -> str:
"""Returns a string representing the RandAugment op to use during preprocessing."""
l, m = {
'light0': (2, 0),
'light1': (2, 10),
'medium1': (2, 15),
'medium2': (2, 15),
'strong1': (2, 20),
'strong2': (2, 20),
'extreme1': (4, 15),
'ex... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def compare_hash(file_a: str, file_b: str) -> bool:
"""Compute and compare the hashes of two files"""
print("Comparing: ")
print(" File_A: "+file_a)
print(" File_B: "+file_b)
file_a_hash = hashlib.sha256(open(file_a, 'rb').read()).digest()
file_b_hash = hashlib.sha... | bigcode/self-oss-instruct-sc2-concepts |
import re
def expand_sharded_pattern(file_pattern: str) -> str:
"""Expand shards in the given pattern for filenames like base@shards.
For example, '/path/to/basename@3' to expand to
'/path/to/basename-00000-of-00003'
'/path/to/basename-00001-of-00003'
'/path/to/basename-00002-of-00003'
Args:
f... | bigcode/self-oss-instruct-sc2-concepts |
import math
def _get_beta(steering_angle: float, wheel_base: float) -> float:
"""
Computes beta, the angle from rear axle to COG at instantaneous center of rotation
:param [rad] steering_angle: steering angle of the car
:param [m] wheel_base: distance between the axles
:return: [rad] Value of beta... | bigcode/self-oss-instruct-sc2-concepts |
def three_to_one_gates_and_measurement_bob(q1, q2, q3):
"""
Performs the gates and measurements for Bob's side of the 3->1 protocol
:param q1: Bob's qubit from the first entangled pair
:param q2: Bob's qubit from the second entangled pair
:param q3: Bob's qubit from the third entangled pair
:ret... | bigcode/self-oss-instruct-sc2-concepts |
import smtplib
def smtp_connection(c):
"""Create an SMTP connection from a Config object"""
if c.smtp_ssl:
klass = smtplib.SMTP_SSL
else:
klass = smtplib.SMTP
conn = klass(c.smtp_host, c.smtp_port, timeout=c.smtp_timeout)
if not c.smtp_ssl:
conn.ehlo()
conn.starttls... | bigcode/self-oss-instruct-sc2-concepts |
def config_loader_mock_no_creds(config_key):
"""Return mocked config values."""
if config_key == "energy_recorder.api_url":
return "http://pod-uri:8888"
elif config_key == "energy_recorder.api_user":
return ""
elif config_key == "energy_recorder.api_password":
return ""
else:... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
from pathlib import Path
def add_extension(file_path: Union[str, Path], extension: str) -> Union[str, Path]:
"""Adds the extension to the file path if it is not present.
Parameters
----------
file_path : Union[str, Path]
The path to the file.
extension : str
... | bigcode/self-oss-instruct-sc2-concepts |
def compute_average_cosine_similarity(square_norm_of_sum, num_vectors):
"""Calculate the average cosine similarity between unit length vectors.
Args:
square_norm_of_sum: The squared norm of the sum of the normalized vectors.
num_vectors: The number of vectors the sum was taken over.
Returns:
A float... | bigcode/self-oss-instruct-sc2-concepts |
def ignoreStrReplace(line, cur, rep):
"""Wrapper for str.replace to ignore strings"""
if '"' in line:
#Split string at quotation marks
lsplit = line.split('"')
#Replace items contained within even partitions
lsplit[::2] = [spl.replace(cur, rep) for spl in lsplit[::2]]
#Re... | bigcode/self-oss-instruct-sc2-concepts |
def encode(char, offset):
"""Shift any letters by a given offset. Ignore non-letter characters."""
if char < 97 or char > 122:
return chr(char)
char += offset
if char > 122:
char -= 26
return chr(char) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
import math
def near_duplicate_similarity_cached(
gold: Tuple[str],
pred: Tuple[str],
threshold: float = 0.1,
) -> float:
"""
Computes the approximate token-level accuracy between gold and pred.
Returns:
token-level accuracy - if not exact match an... | bigcode/self-oss-instruct-sc2-concepts |
def deltatime_str(deltatime_seconds: float) -> str:
"""
Convert time in a format appropriate of time.
Parameters
----------
deltatime_seconds : float
Represents the elapsed time in seconds
Returns
-------
time_str : str
Represents time in a format hh:mm:ss
Examples... | bigcode/self-oss-instruct-sc2-concepts |
import unicodedata
import re
def clean_filename(name, replace_empty=""):
"""
Make a user-supplied string safe for filename use.
Returns an ASCII-encodable string based on the input string that's safe for
use as a component of a filename or URL. The returned value is a string
containing only lower... | bigcode/self-oss-instruct-sc2-concepts |
import math
def logistic_loss(f_x,y_true):
"""
Compute the logistic_loss loss given the returned value f_x from
a linear discrimination function on the feature x and its label y.
Please use logarithm with base = 2
"""
return math.log(1+math.exp(-f_x*y_true),2) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Any
def remove_none_values_recursively(dictionary: Dict[Any, Any]) -> Dict[Any, Any]:
""" Recursively removes the key value pairs where the value is None.
This is a recursive function which tries to find key value pairs where the value is None and
then remove ... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
from typing import Union
from typing import Mapping
from typing import Tuple
from typing import Dict
def get_compression_method(
compression: Optional[Union[str, Mapping[str, str]]]
) -> Tuple[Optional[str], Dict[str, str]]:
"""
Simplifies a compression argument to a compressio... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def reshape_data(data_list, batch_first=True, collapse_dims=False):
"""Concat input/output data and clear buffers
Args:
data_list (list): list of tensors of equal, arbitrary shape where the
batch_dim is either 0 or 1 depending on self.batch_first.
batch_first (bool, optiona... | bigcode/self-oss-instruct-sc2-concepts |
def tostr(data):
"""convert bytes to str"""
if type(data) is bytes and bytes is not str:
data = data.decode('utf8')
return data | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
def get_object_name(obj: Any) -> str:
"""Get a human-readable name of a Python object, e.g. a pipeline component.
obj (Any): The Python object, typically a function or class.
RETURNS (str): A human-readable name.
"""
if hasattr(obj, "name") and obj.name is not None:
... | bigcode/self-oss-instruct-sc2-concepts |
def required_error(name):
"""
The error message presented when a required field is not present
"""
return "You must specify a value for {0}".format(" ".join(name.split("_"))) | bigcode/self-oss-instruct-sc2-concepts |
def deep_merge(first: dict, second: dict) -> dict:
"""
Dict deep merge function
Merge recursive second dict in first and return it
>>> deep_merge({},{})
{}
>>> deep_merge({'key': 'value'}, {'key': 'value'})
{'key': 'value'}
>>> deep_merge({'key': 'value'}, {'key': 'new_value', 'second_k... | bigcode/self-oss-instruct-sc2-concepts |
def play_one(env, model, eps, gamma, copy_period):
"""
Plays a single episode. During play, the model is updated, and the total
reward is accumulated and returned.
Parameters
----------
env : gym.Env
Environment.
model : NumpyDQNObsSingle
Model instance.
eps : numeric
... | bigcode/self-oss-instruct-sc2-concepts |
def curvature(cs, x):
"""
Return the curvature (inverse radius of curvature) of the lane.
Parameters:
cs: CubicSpline
Instance of the CubicSpline calss
x: float or array of floats
Points at which to evaluate the curvature
>>> from eksternlab import curvature
>>> x = [0.23... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
def pad(left: int, right: int, top: int, bottom: int) -> Tuple[Tuple[int, int], Tuple[int, int]]:
"""Set padding of element.
Args:
left: Left padding.
right: Right padding.
top: Top padding.
bottom: Bottom padding.
Returns
----------
padding: The padding ... | bigcode/self-oss-instruct-sc2-concepts |
def all_validate_to(func):
"""
Validate that all elements in the given list pass the validation of the
given validator function.
>>> f = all_validate_to(positive())
>>> f([10, 20, 30])
True
>>> f([10, 0, 30])
False
>>> f([10, 10, -100])
False
>>> f = all_validate_to(in_range... | bigcode/self-oss-instruct-sc2-concepts |
def get_neighbor_distances(ntw, v0, l):
"""Get distances to the nearest vertex neighbors along
connecting arcs.
Parameters
----------
ntw : spaghetti.Network
A spaghetti network object.
v0 : int
The vertex ID.
l : dict
The key is a tuple (start vertex, end vertex... | bigcode/self-oss-instruct-sc2-concepts |
def stations_by_river(stations):
"""
Groups stations by the river they are on.
Args:
stations: list of MonitoringStation objects
Returns:
A dictionary mapping river names (string) to a list of MonitoringStation objects
"""
ret = {}
for s in stations:
river = s.river
... | bigcode/self-oss-instruct-sc2-concepts |
def truncate_name(text):
"""Ensure the comic name does not exceed 100 characters."""
return text[:100] | bigcode/self-oss-instruct-sc2-concepts |
def with_prefix(prefix, name):
"""Adds prefix to name."""
return "/".join((prefix, name)) | bigcode/self-oss-instruct-sc2-concepts |
def split_stream_name(ui_stream_name):
""" Splits the hyphenated reference designator and stream type into a tuple of
(mooring, platform, instrument, stream_type, stream)
"""
mooring, platform, instrument = ui_stream_name.split('-', 2)
instrument, stream_type, stream = instrument.split('_', 2)
s... | bigcode/self-oss-instruct-sc2-concepts |
import pickle
def _load_command_store_from_pickle(file_name):
"""Load the command store from a pickle file."""
return pickle.load(open(file_name, "rb")) | bigcode/self-oss-instruct-sc2-concepts |
def plateInput_files(pldef_params):
"""
Get ordered list of plateInput files given plate_definitio pararmeters.
Parameters
----------
pldef_params : dictionary
Should likely be the output of io.fp_platedef_params()
"""
return [pldef_params[f'plateInput{N+1}'] for
N in r... | bigcode/self-oss-instruct-sc2-concepts |
def decode(x):
"""Decode in case input is bytes-like
"""
try:
x = x.decode()
return x
except:
return x | bigcode/self-oss-instruct-sc2-concepts |
def getNameBuiltwithpip(lines):
"""
Used if buildWithPip == True.
If the file contains "%define pipname packagename", returns packagename.
None otherwise
"""
name = None
for line in lines:
if line.startswith("%define"):
if "pip_name" in line:
name = line.s... | bigcode/self-oss-instruct-sc2-concepts |
def tickDiff(t1, t2):
"""
Returns the microsecond difference between two ticks.
t1:= the earlier tick
t2:= the later tick
...
print(pigpio.tickDiff(4294967272, 12))
36
...
"""
tDiff = t2 - t1
if tDiff < 0:
tDiff += (1 << 32)
return tDiff | bigcode/self-oss-instruct-sc2-concepts |
def limit(num, minimum=1, maximum=255):
"""Limits input 'num' between minimum and maximum values.
Default minimum value is 1 and maximum value is 255."""
return max(min(num, maximum), minimum) | bigcode/self-oss-instruct-sc2-concepts |
def occursInEq(var, deq):
""" Detects if a variable appears within a delta equation.
"""
return (var == deq.clo1.expr) or (var == deq.clo2.expr) | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def Digest(manifest):
"""Compute the digest of the manifest."""
return 'sha256:' + hashlib.sha256(manifest).hexdigest() | bigcode/self-oss-instruct-sc2-concepts |
def fromHomogeneous(M):
""" Return the linear and affine parts of a homogenous matrix :math:`M = [A, b]`.
Parameters
----------
M : numpy array of float, shape (*, num_dims, num_dims + 1) or (*, num_dims + 1, num_dims + 1)
Matrix representing an affine transformation in homogeneous coordinates.... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def apply_filterbank(specgram, filterbank):
"""
Apply a filterbank on specgram
Args:
specgram: [..., F, T]
filterbank: [F, N]. N is the number of filters
Returns:
[..., N, T]
"""
# Pack batch
shape = specgram.size()
specgram = specgram.reshape(-1,... | bigcode/self-oss-instruct-sc2-concepts |
def readProcessed(
serverName, itemIds, startDate, endDate, resampleIntervalMS, aggregates
):
"""Reads processed values from the OPC-HDA server.
Processed values are calculated values, based on the aggregate
function requested for each item. The list of aggregates can be
obtained by calling system.... | bigcode/self-oss-instruct-sc2-concepts |
def filter_rules_action(user_actions, rules):
"""
Divide the list of rules by user_actions to editable and viewonly subsets
:param user_actions: list of actions allowed for normal user
:param rules: list of rules to be filtered
:return: editable, viewonly lists
"""
editable = []
viewonly... | bigcode/self-oss-instruct-sc2-concepts |
def has_compatible_scheme(url):
"""Check whether the given URL uses a scheme compatible with and intended to be used by apt."""
return url.startswith(('http://', 'https://')) | bigcode/self-oss-instruct-sc2-concepts |
import torch
def vec_like(n, tensor):
"""
Returns a 2-D tensor with a vector containing zeros with same size as the input.
"""
assert n > 0, (type(n), n)
assert len(tensor.shape) >= 1, tensor.shape
vec = torch.zeros(n, 1, device=tensor.device, dtype=tensor.dtype)
return vec[None].rep... | bigcode/self-oss-instruct-sc2-concepts |
def alter_data(df, context):
"""
Perform any alterations here on the Pandas DataFrame "df".
For example, here is how you might drop the "education" column
from indicator ENV1-3-2:
if context['indicator_id'] == 'ENV1-3-2':
df = df.drop(columns=['education'])
"""
# Don't forget to re... | bigcode/self-oss-instruct-sc2-concepts |
def arg_neither_empty_nor_all_whitespace(_, arg: str) -> bool:
"""
Tests if the single argument is not None
:param _: Ignored (typically mapped to `self` for bound methods)
:param arg: The argument to be tested
:return: True if arg is neither an empty string nor a string consisting only of whitespa... | bigcode/self-oss-instruct-sc2-concepts |
def sumlist(x, y):
"""
Sums two lists of the same shape elementwise. Returns the sum.
"""
z = x
for i in range(0, len(z)):
if isinstance(x[i], list) and isinstance(y[i], list):
z[i] = sumlist(x[i], y[i])
else:
z[i] = x[i] + y[i]
return z | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def dict_list_cartesian_product(**kwargs) -> list:
""" Given a dictionary whose values are lists, creates a list with every possible dictionary combination and regular unpacked values.
Adapted from the Propheticus function in propheticus.shared.Utils.cartesianProductDictionaryLists. """
keys, valu... | bigcode/self-oss-instruct-sc2-concepts |
def split_mtx(X, n_folds=200):
"""
Split a matrix/Tensor into n parts.
Useful for processing large matrices in batches
"""
X_folds = []
fold_len = X.shape[0]//n_folds
for i in range(n_folds):
start = i * fold_len
if i == n_folds -1:
end = X.shape[0]
else:
end = (i + 1) * fold_len
... | bigcode/self-oss-instruct-sc2-concepts |
def merge_dicts_lists(parent_dict, merge_dict):
"""
Function to add two dictionaries by adding lists of matching keys
:param parent_dict: The Dict to which the second dict should be merged with
:param merge_dict: Dict to be merge with the parent
:return: Dict having the two inputs merged
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def FindSubstr(subseq, seq, expAt, wobble):
"""
Here we search for model parts pre and post barcode within a sequence
from reads.
subseq (str) Subsequence within string we're looking for
seq (str) Full sequence to search subseq within
expAt (int) expected at location of subseq
wobble (int) ... | bigcode/self-oss-instruct-sc2-concepts |
def extract_relevant (msg):
""" Extracts relevant (to the app) headers & info from a GMail message """
headers_to_extract = set (["subject", "from", "message-id"])
headers = msg["payload"]["headers"]
data = dict ()
data ["id"] = msg ["id"]
data ["thread_id"] = msg ["threadId"]
for heade... | bigcode/self-oss-instruct-sc2-concepts |
import re
def stringify_segments(sent_dict_list, segment_type):
"""
Converts a list of sentences (Doc objects) into strings based on their segment number, to pass to a model.
:param sent_dict_list: The dictionary list containing the list of sentences.
:param segment_type: The type of segment to conver... | bigcode/self-oss-instruct-sc2-concepts |
import ntpath
def extract_filename(path_filename):
"""
In case the customer uses a path instead of a filename, we extract the filename
If it is just a filename, then we return it back directly.
Using ntpath to make sure it works on all platforms.
Note the filename could be empty
:param path_f... | bigcode/self-oss-instruct-sc2-concepts |
def extract_coord(var_name):
"""Assuming prefix_R_C format, return (prefix,row,column) tuple.
prefix is of type string, row and column are integers.
The "nowhere" coordinate has form prefix_n_n. To indicate this,
(-1, -1) is returned as the row, column position.
If error, return None or throw exc... | bigcode/self-oss-instruct-sc2-concepts |
import json
def _read_city_name(path: str) -> str:
"""read city name from json file in the log folder
Args:
path: path to the json city_name in the log folder
Returns:
city_name: city name of the current log, either 'PIT' or 'MIA'
"""
with open(path, "r") as f:
city_name = ... | bigcode/self-oss-instruct-sc2-concepts |
def complex_product(a_re, a_im, b_re, b_im):
"""
Computes the complex product of a and b, given the real and imaginary components of both.
:param a_re: real component of a
:param a_im: imaginary component of a
:param b_re: real component of a
:param b_im: imaginary component of a
:return: tu... | bigcode/self-oss-instruct-sc2-concepts |
def get_species_counts(individuals):
"""
Returns a dictionary with species name as the key and the number of
individuals in that species as the value.
:param individuals:
:return:
"""
species_counts = {}
for individual in individuals:
species = individual.split("_")... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Callable
from functools import reduce
def pipe(*fns: Callable) -> Callable:
"""
Returns a function invoking 'fns' in sequence left to right, the first
with the initial arguments, each thereafter with the last return value.
>>> pipe(lambda x, y, z: x + y + z, lambda x: x + 1)(1, 2, ... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def cross_broadcast(x: torch.Tensor, y: torch.Tensor):
"""
Cross broadcasting for 2 tensors
:param x: torch.Tensor
:param y: torch.Tensor, should have the same ndim as x
:return: tuple of cross-broadcasted tensors x, y. Any dimension where the size of x or y is 1
is expa... | bigcode/self-oss-instruct-sc2-concepts |
def remove_country_code(language):
"""
Returns only the ISO-639-1 language part of the provided language string,
that may also contain a ISO-3166 country part as suffix.
:param language:
:return:
"""
if '-' in language:
return language.split('-')[0]
if '_' in language:
re... | bigcode/self-oss-instruct-sc2-concepts |
def first_line(text, keep_empty=False, default=None):
"""First line in 'data', if any
Args:
text (str | list | None): Text to examine
keep_empty (bool): When False skip empty lines (+ strip spaces/newlines), when True don't filter (strip newlines only)
default (str | None): Default to r... | bigcode/self-oss-instruct-sc2-concepts |
def index_nest(nest, index):
"""Index a nested object, using a tuple of indices or keys in the case of dicts.
Parameters
----------
nest
The nested object to index.
index
A tuple of indices for indexing.
"""
ret = nest
for i in index:
ret = ret[i]
return ret | bigcode/self-oss-instruct-sc2-concepts |
def get_common_characters(character_counter, coverage=1.0):
"""
Get the most common characters of a language.
Parameters
----------
character_counter : collections.Counter
coverage : float, optional (default: 1.0)
Take the most common characters that make up `coverage` of the dataset
... | bigcode/self-oss-instruct-sc2-concepts |
def replace(text, from_string, to_string):
"""Replace a string."""
return text.replace(from_string, to_string) | bigcode/self-oss-instruct-sc2-concepts |
def stationary(t):
"""Probe is stationary at location h = 2, v = 0"""
return 0.*t, 2/16 + 0*t, 0*t | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Dict
from typing import Tuple
def simplify_experiments(experiments: List[Dict]) -> List[List[Tuple[str, ...]]]:
"""Converts a list of experiments into a list of lists of tuples, where
each tuple represents a crossing in a given experiment.
:param experiments:
... | bigcode/self-oss-instruct-sc2-concepts |
def signature_parse(content: str, signature: str) -> bool:
"""Parses given text looking for the presence of a given signature. Returns ``True`` if the signature was found,
``False`` otherwise.
:param content: str
:param signature: str
:return: bool
"""
if content.find(signature) != -1:
... | bigcode/self-oss-instruct-sc2-concepts |
import string
def parse_a3m(filename):
"""Load a3m file to list of sequences
Parameters:
-----------
filename : str
path to a3m file
Returns:
--------
seqs : list
list of seqs in MSA
"""
seqs = []
table = str.maketrans(dict.fromkeys(string.ascii_lowercase))
... | bigcode/self-oss-instruct-sc2-concepts |
def frequency_text(hz):
"""
return hz as readable text in Hz, kHz, MHz or GHz
"""
if hz < 1e3:
return "%.3f Hz" % hz
elif hz < 1e6:
return "%.3f kHz" % (hz / 1e3)
elif hz < 1e9:
return "%.3f MHz" % (hz / 1e6)
return "%.3f GHz" % (hz / 1e9) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
def rebase_donate_argnums(donate_argnums, static_argnums) -> Tuple[int, ...]:
"""Shifts donate to account for static.
>>> rebase_donate_argnums((3, 4), (0, 1))
(1, 2)
Args:
donate_argnums: An iterable of ints.
static_argnums: An iterable of ints.
Returns:
A tuple of u... | bigcode/self-oss-instruct-sc2-concepts |
def old_vertex_from_dummy(dummy: int, key: int, biggest) -> int:
"""Old vertex ID from the dummy vertex ID"""
if dummy < 0:
return -(dummy + (biggest + 1) * (key - 1) + 1)
return dummy | bigcode/self-oss-instruct-sc2-concepts |
def interval_start(DateTime):
"""Return the default start of the recurrence interval."""
return DateTime(2014, 4, 1, 0) | bigcode/self-oss-instruct-sc2-concepts |
import socket
def is_connected() -> bool:
"""Check if connected to Internet."""
try:
# connect to the host -- tells us if the host is actually reachable
sock = socket.create_connection(('connectivitycheck.gstatic.com', 80))
if sock is not None:
sock.close()
return T... | bigcode/self-oss-instruct-sc2-concepts |
import threading
def new_thread(name=None):
"""Creates new thread decorator.
Args:
name (str): Thread name.
Returns:
function: New thread decorator.
"""
def decorator(f):
"""Decorator which calls function on a new thread.
Args:
f (fun... | bigcode/self-oss-instruct-sc2-concepts |
def r_to_p(r, d, rtype='EI'):
"""
Inverse of the p_to_r function.
Parameters
----------
r : float
The RB error rate
d : int
Number of dimensions of the Hilbert space
rtype : {'EI','AGI'}, optional
The RB error rate rescaling convention.
Returns
-------
... | bigcode/self-oss-instruct-sc2-concepts |
import random
def successfulStarts(eventProb, numTrials):
"""Assumes eventProb is a float representing a probability
of a single attempt being successful. numTrials a positive int
Returns a list of the number of attempts needed before a
success for each trial."""
triesBeforeSuccess = []
for t ... | bigcode/self-oss-instruct-sc2-concepts |
def default_step_condition_factory(target_version, step_name):
"""Create a default condition used by upgrade steps.
The created condition checks if the step was already successfully ran
and skip it if it is the case.
"""
def default_step_condition(alembic, failed_migration, *args):
if faile... | bigcode/self-oss-instruct-sc2-concepts |
def _idempotent(method):
"""Return whether *method* is idempotent."""
return method in ('GET', 'HEAD', 'PUT') | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_contents (fname):
"""
Return the contents of the given file.
Strip comments (lines starting with ;)
"""
if type(fname) == list:
contents = '\n'.join(fname)
else:
fp = open (fname, "r")
contents = fp.read()
fp.close()
return re.sub(r... | bigcode/self-oss-instruct-sc2-concepts |
def isiter(x):
"""
Returns `True` if the given value implements an valid iterable
interface.
Arguments:
x (mixed): value to check if it is an iterable.
Returns:
bool
"""
return hasattr(x, '__iter__') and not isinstance(x, (str, bytes)) | bigcode/self-oss-instruct-sc2-concepts |
def Latentc(tempc):
"""Latent heat of condensation (vapourisation)
INPUTS:
tempc (C)
OUTPUTS:
L_w (J/kg)
SOURCE:
http://en.wikipedia.org/wiki/Latent_heat#Latent_heat_for_condensation_of_water
"""
return 1000 * (2500.8 - 2.36 * tempc + 0.0016 * tempc ** 2 - 0.00006 * tempc ** 3... | bigcode/self-oss-instruct-sc2-concepts |
def image_proc_normalize( image ):
"""
Normalize image pixel component values to 0-1 range.
"""
output_image = []
for row in image:
output_row = []
for pixel in row:
if isinstance( pixel, float ) or isinstance( pixel, int ):
output_row.append( pixel / 255 ... | bigcode/self-oss-instruct-sc2-concepts |
def rollout(tree, s, depth):
"""Rollout from the current state s.
Parameters
----------
tree : :py:class:`ast_toolbox.mcts.MCTSdpw.DPWTree`
The seach tree.
s : :py:class:`ast_toolbox.mcts.AdaptiveStressTesting.ASTState`
The current state.
depth : int
The maximum search d... | bigcode/self-oss-instruct-sc2-concepts |
import urllib.request
import shutil
def download(url, file=None):
"""
Pass file as a filename, open file object, or None to return the request bytes
Args:
url (str): URL of file to download
file (Union[str, io, None]): One of the following:
- Filename of output file
... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def compute_classification_logits(pooled_output, output_weights_cls, output_bias_cls):
"""Computes logits for each classification of the sequence.
Args:
pooled_output: <float>[batch_size, hidden_dim] Output of the pooler (BertPooler) on top of the encoder layer.
Returns:
logit... | bigcode/self-oss-instruct-sc2-concepts |
def _get_base_step(name: str):
"""Base image step for running bash commands.
Return a busybox base step for running bash commands.
Args:
name {str}: step name
Returns:
Dict[Text, Any]
"""
return {
'image': 'busybox',
'name': name,
'script': '#!/bin/sh\n... | bigcode/self-oss-instruct-sc2-concepts |
def find_ss_regions(dssp_residues, loop_assignments=(' ', 'B', 'S', 'T')):
"""Separates parsed DSSP data into groups of secondary structure.
Notes
-----
Example: all residues in a single helix/loop/strand will be gathered
into a list, then the next secondary structure element will be
gathered i... | bigcode/self-oss-instruct-sc2-concepts |
def tabulate(lines):
"""
Add a tab before each line in the list
"""
out = []
for line in lines:
out.append(" {}".format(line))
return out | bigcode/self-oss-instruct-sc2-concepts |
def is_2nd_after_1st(event_stat_1, event_stat_2):
"""Returns true if 2nd event has a later minute / second as the first"""
min_1 = event_stat_1.minute
sec_1 = event_stat_1.second
min_2 = event_stat_2.minute
sec_2 = event_stat_2.second
return min_1 * 60 + sec_1 < min_2 * 60 + sec_2 | bigcode/self-oss-instruct-sc2-concepts |
import requests
def live_url_check(url):
"""
This function takes an URL and check whether it is live or not. If it is live return True and False otherwise.
:param url: a Uniform Resource Locator(URL) of a website
:return: True or False
"""
r = requests.head(url)
# print(r.status_code)
... | bigcode/self-oss-instruct-sc2-concepts |
def getkey(d,key,default):
"""gets key from dict (d), if key does not exist, return default"""
if key in d:
return d[key]
else:
return default | 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.