seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
import torch
def get_box_attribute(probability):
"""
Return the argmax on `probability` tensor.
"""
return torch.argmax(probability, dim=-1) | bigcode/self-oss-instruct-sc2-concepts |
def parse_arg_array(arguments):
"""
Parses array of arguments in key=value format into array
where keys and values are values of the resulting array
:param arguments: Arguments in key=value format
:type arguments: list(str)
:returns Arguments exploded by =
:rtype list(str)
"""
resu... | bigcode/self-oss-instruct-sc2-concepts |
def get_json_data(json_dict):
"""
Parameters
----------
json_dict : :obj:`dict`
QCJSON dictionary.
Returns
-------
:obj:`list` [:obj:`int`]
Atomic numbers of all atoms
:obj:`list` [:obj:`float`]
Cartesian coordinates.
:obj:`float`
Total energy of the... | bigcode/self-oss-instruct-sc2-concepts |
def get_total(shopping_list, prices):
"""
Getting shopping list and prices for goods in it,
returns total cost of available products.
>>> goods = {'Apple': 2.5, 'Pear': 1, 'Pumpkin': 1.5}
>>> prices = {'Apple': 9.50, 'Pear': 23.80, 'Pumpkin': 4.50}
>>> get_total(goods, prices)
54.3
If... | bigcode/self-oss-instruct-sc2-concepts |
def create_index_query(node_type, indexed_property):
""" Create the query for the index statement. See:
https://neo4j.com/docs/cypher-manual/current/indexes-for-search-performance/
"""
print(f'CREATE INDEX ON :{node_type}({indexed_property});')
return f'CREATE INDEX ON :{node_type}({indexed_property... | bigcode/self-oss-instruct-sc2-concepts |
def get_indexes(dfobj, value):
"""Get a list with location index of a value or string in the
DataFrame requested.
Parameters
----------
dfobj : pandas.DataFrame
Data frame where the value will be searched.
value : str, int, float
String, integer or float to be searched.
Ret... | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def unwrap_fullargspec(func):
"""recursively searches through wrapped function to get the args"""
func_dict = func.__dict__
if "__wrapped__" in func_dict:
return unwrap_fullargspec(func_dict["__wrapped__"])
else:
return inspect.getfullargspec(func) | bigcode/self-oss-instruct-sc2-concepts |
def squared_error(prediction, observation):
"""
Calculates the squared error.
Args:
prediction - the prediction from our linear regression model
observation - the observed data point
Returns:
The squared error
"""
return (observation - prediction) ** 2 | bigcode/self-oss-instruct-sc2-concepts |
from typing import Counter
def recover_message(messages, least_frequent=False):
"""For each position in the recovered message,
find the most- (least-) frequently-occurring
character in the same position in the set of
raw messages.
"""
i = len(messages) if least_frequent else 1
return ''.jo... | bigcode/self-oss-instruct-sc2-concepts |
def strip_leading_zeros(version: str) -> str:
"""
Strips leading zeros from version number.
This converts 1974.04.03 to 1974.4.3 as the format with leading month and day zeros is not accepted
by PIP versioning.
:param version: version number in CALVER format (potentially with leading 0s in date an... | bigcode/self-oss-instruct-sc2-concepts |
def tie_account_to_order(AccountKey, order):
"""tie_account_to_order - inject the AccountKey in the orderbody.
An order specification is 'anonymous'. To apply it to an account it needs
the AccountKey of the account.
Parameters
----------
AccountKey: string (required)
the accountkey
... | bigcode/self-oss-instruct-sc2-concepts |
def renamefromto(row, renaming):
"""Rename keys in a dictionary.
For each (oldname, newname) in renaming.items(): rename row[oldname] to
row[newname].
"""
if not renaming:
return row
for old, new in renaming.items():
row[new] = row[old]
del row[old] | bigcode/self-oss-instruct-sc2-concepts |
import json
def is_bootstrap(event):
"""
Determines if the message sent in was for an bootstrap action -
Bootstrap (success) events are always just strings so loading it as json should
raise a ValueError
"""
try:
message = json.loads(event['Records'][0]['Sns']['Message'])
if is... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
import yaml
def to_yaml_str(val: Any) -> str:
"""
:param val: value to get yaml str value of
:return: direct str cast of val if it is an int, float, or bool, otherwise
the stripped output of yaml.dump
"""
if isinstance(val, (str, int, float, bool)):
return st... | bigcode/self-oss-instruct-sc2-concepts |
def remove_comments(line):
"""
Remove all comments from the line
:param line: assembly source line
:return: line without comments (; ....)
"""
comment = line.find(';')
if comment >= 0:
line = line[0:comment]
return line | bigcode/self-oss-instruct-sc2-concepts |
import re
def like(matchlist: list, array: list, andop=False):
"""Returns a list of matches in the given array by doing a comparison of each object with the values given to the matchlist parameter.
Examples:
>>> subdir_list = ['get_random.py',
... 'day6_15_payload-by-port.py',
... '... | bigcode/self-oss-instruct-sc2-concepts |
def colvec(vec):
""" Convert to column vector """
return vec.reshape(-1, 1) | bigcode/self-oss-instruct-sc2-concepts |
def parse_genes(gene_file):
"""Select gene to exclude: where sgt column is not 'yes'
input: csv file with genes
return: set of genes which should be exluded"""
to_exlude = set()
with open(gene_file) as lines:
next(lines)
for line in lines:
gene, _, _, sgt = line.split('\... | bigcode/self-oss-instruct-sc2-concepts |
def intervals_to_list(data):
"""Transform list of pybedtools.Intervals to list of lists."""
return [interval.fields for interval in data] | bigcode/self-oss-instruct-sc2-concepts |
def consume(queue_name):
"""
Decorate a function to signal it is a WCraaS consumer and provide its queue name.
>>> @consume("awesome_queue")
... def func(): pass
...
>>> func.is_consume
True
>>> func.consume_queue
'awesome_queue'
"""
def decorator(fn):
fn.is_consume ... | bigcode/self-oss-instruct-sc2-concepts |
def presale_investor_4(accounts) -> str:
"""Test account planted in fake_seed_investor_data.csv"""
return accounts[9] | bigcode/self-oss-instruct-sc2-concepts |
import numbers
def is_numeric(value):
"""Return True if value is really numeric (int, float, whatever).
>>> is_numeric(+53.4)
True
>>> is_numeric('53.4')
False
"""
return isinstance(value, numbers.Number) | bigcode/self-oss-instruct-sc2-concepts |
def RIGHT(string, num_chars=1):
"""
Returns a substring of length num_chars from the end of a specified string. If num_chars is
omitted, it is assumed to be 1. Same as `string[-num_chars:]`.
>>> RIGHT("Sale Price", 5)
'Price'
>>> RIGHT('Stock Number')
'r'
>>> RIGHT('Text', 100)
'Text'
>>> RIGHT('Te... | bigcode/self-oss-instruct-sc2-concepts |
import math
def degrees(d):
"""Convert degrees to radians.
Arguments:
d -- Angle in degrees.
"""
return d / 180 * math.pi | bigcode/self-oss-instruct-sc2-concepts |
def gasoline_cost_sek(dist, sekpl=20.0, kmpl=9.4):
"""Gets cost of commute via car in Swedish Krona.
Input
dist: distance in kilometers (numeric)
sekpl: Swedish Krona (SEK) per liter (L). Obtained from gasoline_price() function.
kmpl: Kilometers (km) per liter (L). (Fuel efficiency)
... | bigcode/self-oss-instruct-sc2-concepts |
def reverse_array_2(arr, start, end):
"""
A method to reverse an array within the given start and end ranges
Space complexity = O(1)
Time complexity = O(n)/2
:param arr: The array to reverse
:param start: The start index within array to reverse
:param end: The end index within array to rev... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Any
def pad_list(l: List[Any], length: int, item: Any) -> List[Any]: # noqa: E741
"""Pads a list to the specified length.
Note that if the input list is longer than the specified length it is not
truncated.
Args:
l: The input list.
length: ... | bigcode/self-oss-instruct-sc2-concepts |
def get_user_id(flickr, user):
"""Get the user_id from the username."""
user_data = flickr.people.findByUsername(username=user)
return user_data['user']['id'] | bigcode/self-oss-instruct-sc2-concepts |
import math
def angle_to_pixel(angle, fov, num_pixels):
"""
angle: object angle
fov: field of view of the camera
num_pixels: number of pixels along the dimension that fov was measured
"""
if angle > 90.0 or angle < -90.0:
raise ValueError
x = math.tan(math.radians(angle))
limi... | bigcode/self-oss-instruct-sc2-concepts |
def create_data_dict(data):
"""
Function to convert data to dictionary format
Args:
-----------
data: train/dev data as a list
Returns:
--------
a dictionary containing dev/train data
"""
train = {}
train['para'] = []
train['answer'] = []
train['question'] = []
... | bigcode/self-oss-instruct-sc2-concepts |
import re
def replace_halogen(smiles):
"""
Replace halogens with single letters (Cl -> L and Br -> R), following
Olivecrona et al. (J Cheminf 2018).
"""
br = re.compile('Br')
cl = re.compile('Cl')
smiles = br.sub('R', smiles)
smiles = cl.sub('L', smiles)
return smiles | bigcode/self-oss-instruct-sc2-concepts |
def form_dataframe_to_arrays(df):
"""
Convert dataframes into arrays in both variables and target
"""
feature_order = list(df.filter(regex="[^M_t+\d]").columns)
X = df.filter(regex="[^M_t+\d]").values
Y = df.filter(regex="[\+]").values.flatten()
return X,Y,feature_order | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
import re
def _read_url_slug(file_contents: str) -> Optional[str]:
"""Returns slug parsed from file contents, None if not found."""
regex = r"""url=[^"]+\.[^"]+\/(?P<slug>[-\w]+)(\/|[\w.]+)?\""""
match = re.search(regex, file_contents, re.VERBOSE)
if match:
return m... | bigcode/self-oss-instruct-sc2-concepts |
def permute_dimensions(x, pattern):
"""Transpose dimensions.
pattern should be a tuple or list of
dimension indices, e.g. [0, 2, 1].
"""
pattern = tuple(pattern)
return x.transpose(pattern) | bigcode/self-oss-instruct-sc2-concepts |
import base64
def _make_user_code(code: str) -> str:
"""Compose the user code into an actual base64-encoded string variable."""
code = base64.b64encode(code.encode("utf8")).decode("utf8")
return f'USER_CODE = b"{code}"' | bigcode/self-oss-instruct-sc2-concepts |
def find_missing_items(intList):
"""
Returns missing integers numbers from a list of integers
:param intList: list(int), list of integers
:return: list(int), sorted list of missing integers numbers of the original list
"""
original_set = set(intList)
smallest_item = min(original_set)
l... | bigcode/self-oss-instruct-sc2-concepts |
def AsList(arg):
"""return the given argument unchanged if already a list or tuple, otherwise return a single
element list"""
return arg if isinstance(arg, (tuple, list)) else [arg] | bigcode/self-oss-instruct-sc2-concepts |
import io
def has_fileno(stream):
"""
Cleanly determine whether ``stream`` has a useful ``.fileno()``.
.. note::
This function helps determine if a given file-like object can be used
with various terminal-oriented modules and functions such as `select`,
`termios`, and `tty`. For m... | bigcode/self-oss-instruct-sc2-concepts |
def select_dropdown(options, id=None):
"""Generate a new select dropdown form
Parameters
----------
options: List[str]
list of options the user can select
id: str
DOM id used to refer to this input form
"""
html_options = ''.join(f'<option>{opt}</option>' for opt in options... | bigcode/self-oss-instruct-sc2-concepts |
def read(path):
"""
Read a file
"""
with open(path) as file_:
return file_.read() | bigcode/self-oss-instruct-sc2-concepts |
def createDict(data, index):
"""
Create a new dictionnay from dictionnary key=>values:
just keep value number 'index' from all values.
>>> data={10: ("dix", 100, "a"), 20: ("vingt", 200, "b")}
>>> createDict(data, 0)
{10: 'dix', 20: 'vingt'}
>>> createDict(data, 2)
{10: 'a', 20: 'b'}
... | bigcode/self-oss-instruct-sc2-concepts |
def is_port_vlan_member(config_db, port, vlan):
"""Check if port is a member of vlan"""
vlan_ports_data = config_db.get_table('VLAN_MEMBER')
for key in vlan_ports_data:
if key[0] == vlan and key[1] == port:
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
import random
def uniformly_split_num(
sum: int,
n: int,
) -> List[int]:
"""Generate `n` non-negative numbers that sum up to `sum`"""
assert n > 0, 'n should be > 0'
assert sum >= 0, 'sum should be >= 0'
random_numbers = [random.randint(0, sum) for _ in range(n - 1)]
... | bigcode/self-oss-instruct-sc2-concepts |
def _update_count_down(previous_count_down_minutes, check_mail_interval, current_time, start_time, main_window) -> int:
"""
Utility method, update status message text ("count down") until next mail check begins
:param previous_count_down_minutes: current state of counter
:param check_mail_interval: give... | bigcode/self-oss-instruct-sc2-concepts |
async def get_int_list(redis, key):
"""Get a list of integers on redis."""
str_list = await redis.lrange(key, 0, -1)
int_list = [int(i) for i in str_list]
return int_list | bigcode/self-oss-instruct-sc2-concepts |
def swap_list_order(alist):
"""
Args:
alist: shape=(B, num_level, ....)
Returns:
alist: shape=(num_level, B, ...)
"""
new_order0 = len(alist[0])
return [[alist[i][j] for i in range(len(alist))] for j in range(new_order0)] | bigcode/self-oss-instruct-sc2-concepts |
def PWM_scorer(seq, pwm, pwm_dict, pwm_type):
"""
Generate score for current seq given a pwm.
"""
seq_score = 0.0
for i in range(0, len(seq)):
seq_score += pwm[pwm_dict[seq[i:i+1]]][i]
return seq_score | bigcode/self-oss-instruct-sc2-concepts |
def _collect_facts(operators):
"""
Collect all facts from grounded operators (precondition, add
effects and delete effects).
"""
facts = set()
for op in operators:
facts |= op.preconditions | op.add_effects | op.del_effects
return facts | bigcode/self-oss-instruct-sc2-concepts |
import math
def _brevity_penalty(candidate, references):
"""Calculate brevity penalty.
As the modified n-gram precision still has the problem from the short
length sentence, brevity penalty is used to modify the overall BLEU
score according to length.
An example from the paper. There are three r... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
import json
def hash_dump(data):
"""Hash an arbitrary JSON dictionary by dumping it in sorted order, encoding it in UTF-8, then hashing the bytes.
:param data: An arbitrary JSON-serializable object
:type data: dict or list or tuple
:rtype: str
"""
return hashlib.sha512(json.dum... | bigcode/self-oss-instruct-sc2-concepts |
def clean_dict(dictionary):
""" Remove items with None value in the dictionary and recursively in other nested dictionaries. """
if not isinstance(dictionary, dict):
return dictionary
return {k: clean_dict(v) for k, v in dictionary.items() if v is not None} | bigcode/self-oss-instruct-sc2-concepts |
def get_padding_prp(hparams):
"""Get padding for pad_rotate_project measurements"""
if hparams.dataset == 'mnist':
paddings = [[0, 0], [6, 6], [6, 6], [0, 0]]
elif hparams.dataset == 'celebA':
paddings = [[0, 0], [14, 14], [14, 14], [0, 0]]
else:
raise NotImplementedError
ret... | bigcode/self-oss-instruct-sc2-concepts |
def get_post_data(request):
"""
Attempt to coerce POST json data from the request, falling
back to the raw data if json could not be coerced.
:type request: flask.request
"""
try:
return request.get_json(force=True)
except:
return request.values | bigcode/self-oss-instruct-sc2-concepts |
def sort_by_hw_count(user):
"""Sort students by the number of completed homeworks"""
return sum([1 if hw['status'] == 'success' else 0 for hw in user['homeworks']]) | bigcode/self-oss-instruct-sc2-concepts |
def getOrientation( geom , camera=True):
"""
build and return a dictionary storing the orientation for geom
orientDict <- getOrientation( geom )
"""
orientMem = {}
orientMem['rotation'] = geom.rotation[:]
orientMem['translation'] = geom.translation.copy()
orientMem['scale'] = geom.scal... | bigcode/self-oss-instruct-sc2-concepts |
def patch_from_tupled_dict(tupled_dict):
""" Creates a nested dictionary that f90nml can interpret as a patch."""
patch = {}
for replace_this, replace_val in tupled_dict.items():
group, field = replace_this
group, field = group.lower(), field.lower()
gdict = patch.get(group, {})
... | bigcode/self-oss-instruct-sc2-concepts |
import yaml
def yaml_to_base_type(node, loader):
"""
Converts a PyYAML node type to a basic Python data type.
Parameters
----------
node : yaml.Node
The node is converted to a basic Python type using the following:
- MappingNode -> dict
- SequenceNode -> list
- Sca... | bigcode/self-oss-instruct-sc2-concepts |
import re
def find_note_contents_start(md_text_lines):
"""
Some notes in Bear contain #tags near the title. This returns the index in the list that\
isn't the title or contains tags. If no index found, return len(md_text_lines)
"""
# Start at 1 to skip the title
# Look for regex matches of tag... | bigcode/self-oss-instruct-sc2-concepts |
def resize_fn(attributions, inputs, mode):
"""Mocked resize function for test."""
del inputs, mode
return attributions | bigcode/self-oss-instruct-sc2-concepts |
def print_module(module, print_flag=None):
"""Returns module in XML format. Accepts only {dict}.\n
- Only works with one module at a time: otherwise iteration is needed.
- Module "value" field accepts str type or [list] for datalists.
- Use print_flag to show modules' XML in STDOUT.
"""
data = d... | bigcode/self-oss-instruct-sc2-concepts |
def flatten(lists):
"""
flattens a list of lists x
"""
result = []
for x in lists:
for elem in x: result.append(elem)
return result | bigcode/self-oss-instruct-sc2-concepts |
import math
def format_memory_size(bytes):
"""Return a humanly readable formatting of 'bytes' using powers of 1024.
"""
units = ('Bytes', 'KB', 'MB', 'GB', 'TB')
if bytes < 1024:
return '%d %s' % (bytes, units[0])
else:
scale = min(math.floor(math.log(bytes, 1024)), len(units)-1)
... | bigcode/self-oss-instruct-sc2-concepts |
def optimal_summands(n: int):
"""
Gets the maximum number of distinct prizes.
>>> optimal_summands(6)
[1, 2, 3]
>>> optimal_summands(8)
[1, 2, 5]
>>> optimal_summands(2)
[2]
"""
if n <= 2:
return [n]
opt_sum = 0
summands = []
for num in range(1, n):
... | bigcode/self-oss-instruct-sc2-concepts |
import random
def gen_ran_len_lst(n=500):
"""Returns a random 0, n length list of 0, n random numbers."""
lst = []
for i in range(random.randrange(0, n)):
lst.append(random.randrange(0, n))
return lst | bigcode/self-oss-instruct-sc2-concepts |
def sum_multiples(n):
"""Returns the sum of multiples of three and five below n"""
assert n >= 0
return sum([i for i in range(n) if (not i%3) or (not i%5)]) | bigcode/self-oss-instruct-sc2-concepts |
import collections
def compute_dominators(func, cfg):
"""
Compute the dominators for the CFG, i.e. for each basic block the
set of basic blocks that dominate that block. This means that every path
from the entry block to that block must go through the blocks in the
dominator set.
dominato... | bigcode/self-oss-instruct-sc2-concepts |
def structure_to_composition(series, reduce=False):
"""
Converts a Structure series to a Composition series
Args:
series: a pd.Series with pymatgen.Structure components
reduce: (bool) whether to return a reduced Composition
Returns:
a pd.Series with pymatgen Composition compone... | bigcode/self-oss-instruct-sc2-concepts |
from typing import OrderedDict
import json
import warnings
def read_json(file_path, encoding='UTF-8', ordered=True):
"""Read a JSON file.
Wraps the json.load() method.
Arguments:
file_path {str} -- path of file to read
Keyword Arguments:
encoding {str} -- encoding to read the file ... | bigcode/self-oss-instruct-sc2-concepts |
def rotate(scale, n):
""" Left-rotate a scale by n positions. """
return scale[n:] + scale[:n] | bigcode/self-oss-instruct-sc2-concepts |
from functools import reduce
def getattrs(obj, attrs, default=None):
"""
Get attrs from obj
:param obj: object
:param attrs: string or iterable object
:param default: default value
:return: obj attr value if existed, otherwise default value
"""
if not attrs:
return obj
if ... | bigcode/self-oss-instruct-sc2-concepts |
def get_comparative_word_freq(freqs):
"""
Returns a dictionary of the frequency of words counted relative to each other.
If frequency passed in is zero, returns zero
:param freqs: dictionary
:return: dictionary
>>> from gender_novels import novel
>>> novel_metadata = {'author': 'Hawthorne,... | bigcode/self-oss-instruct-sc2-concepts |
def triplet_pattern(t):
"""Convert an arbitrary 3-tuple into a string specifying the distinct elements."""
if t[0] == t[1] == t[2]:
return "AAA"
if t[0] == t[1]:
return "AAB"
if t[1] == t[2]:
return "ABB"
return "ABC" | bigcode/self-oss-instruct-sc2-concepts |
def set_emulated_vision_deficiency(type: str) -> dict:
"""Emulates the given vision deficiency.
Parameters
----------
type: str
Vision deficiency to emulate.
**Experimental**
"""
return {"method": "Emulation.setEmulatedVisionDeficiency", "params": {"type": type}} | bigcode/self-oss-instruct-sc2-concepts |
def parse_args(args):
"""
This parses the arguments and returns a tuple containing:
(args, command, command_args)
For example, "--config=bar start --with=baz" would return:
(['--config=bar'], 'start', ['--with=baz'])
"""
index = None
for arg_i, arg in enumerate(args):
if not a... | bigcode/self-oss-instruct-sc2-concepts |
import ssl
import socket
def get_ssl_serversocket(file_certchain, file_privatekey, bindoptions, password_privkey=None):
"""
Create a SSL based server socket. Useage:
conn, addr = ssock.accept()
data = conn.recv()
conn.send(data)
Certificate/private key can be create via:
openssl req -x509... | bigcode/self-oss-instruct-sc2-concepts |
def ParseCodePoint(s):
"""Parses the pua string representation.
The format of the input is either:
- empty string
- hexadecimal integer.
- hexadecimal integer leading '>'.
We're not interested in empty string nor '>'-leading codes, so returns None
for them.
Note that '>'-leading code means it is "seco... | bigcode/self-oss-instruct-sc2-concepts |
def checksum_min_max(sheet_file):
"""Return the sum of each row's max - min"""
result = 0
with open(sheet_file) as f:
sheet_list = f.readlines()
for row in sheet_list:
int_row = [int(i) for i in row.split('\t')]
result = result + (max(int_row) - min(int_row))
re... | bigcode/self-oss-instruct-sc2-concepts |
def _isCharEnclosed(charIndex, string):
""" Return true if the character at charIndex is enclosed in double quotes (a string) """
numQuotes = 0 # if the number of quotes past this character is odd, than this character lies inside a string
for i in range(charIndex, len(string)):
if string[i] == '"':... | bigcode/self-oss-instruct-sc2-concepts |
def soap_auth(client, tenant, username, password):
"""Authenticate to the web services"""
if not tenant:
return client.service.authenticate(
username=username, password=password
)
return client.service.authenticateTenant(
tenantName=tenant, username=username, password=pa... | bigcode/self-oss-instruct-sc2-concepts |
def correct_mag(m0, X, k):
"""Correct magnitude for airmass and extinction.
Parameters
----------
m0 : float
Apparent magnitude.
X : float
Airmass.
k : float
Extinction coefficient.
Returns
-------
m : float
The corrected apparent magnitude.
"""... | bigcode/self-oss-instruct-sc2-concepts |
def split_off_attrib(xpath):
"""
Splits off attribute of the given xpath (part after @)
:param xpath: str of the xpath to split up
"""
split_xpath = xpath.split('/@')
assert len(split_xpath) == 2, f"Splitting off attribute failed for: '{split_xpath}'"
return tuple(split_xpath) | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def hash_file(path):
"""
Returns the SHA-256 hash of a file.
Parameters
----------
path : `str`
The path of the file to be hashed.
Returns
-------
`str`
SHA-256 hash of the file.
References
----------
* https://stackoverflow.com/a/22058673
... | bigcode/self-oss-instruct-sc2-concepts |
def str2list(v):
"""
Transform user input list(arguments) to be list of string.
Multiple options needs comma(,) between each options.
ex)
--strategies ST01
--strategies ST01,ST02,ST03
:param v: (string) user input
:return: list of option string. (ex - ['ST01', 'ST02', 'ST03')
... | bigcode/self-oss-instruct-sc2-concepts |
import json
def retrieve_ecli(ecli, db_session):
"""
Retrieves the ecli from a database
:param ecli: The ECLI identifier
:param db_session: a sqlalchemy session object
"""
res = db_session.execute('select * from cases where ecli=:ecli',
{"ecli":ecli})
... | bigcode/self-oss-instruct-sc2-concepts |
def conjugate_strand(strand):
"""Given a dna strand, re-write it as it's reverse complement."""
basepair = {'a': 't', 't': 'a', 'g': 'c', 'c': 'g'}
rev_strand = ''.join(basepair[s] for s in strand[::-1]
if s in basepair.keys())
return rev_strand | bigcode/self-oss-instruct-sc2-concepts |
def binary(val):
""" validates if the value passed is binary (true/false)"""
if type(val) == bool:
return val
else:
raise ValueError("random seed is a boolean flag") | bigcode/self-oss-instruct-sc2-concepts |
def fixture_to_tables(fixture):
""" convert fixture into *behave* examples
:param fixture: a dictionary in the following form::
{
"test1name":
{
"test1property1": ...,
"test1property2": ...,
...
},
"test2nam... | bigcode/self-oss-instruct-sc2-concepts |
def extract_message(result): # pragma: no cover
"""Extracts the original message from a parsing result."""
return result.get('text', {}) | bigcode/self-oss-instruct-sc2-concepts |
import re
def available_space(ctx, device):
"""
Determine the available space on device such as bootflash or stby-bootflash:
:param ctx:
:param device: bootflash / stby-bootflash: / harddisk: / stby-harddisk:
:return: the available space
"""
available = -1
output = ctx.send('dir ' + ... | bigcode/self-oss-instruct-sc2-concepts |
def ssh_host(config, host):
"""Get the full user/host pair for use in SSH commands."""
return '{}@{}'.format(config.user, host) | bigcode/self-oss-instruct-sc2-concepts |
def getKey(spc):
"""
Returns a string of the species that can serve as a key in a dictionary.
"""
return spc.label | bigcode/self-oss-instruct-sc2-concepts |
import operator
def get_ecdf(array, reverse=False):
"""
Generate the empirical distribution function.
:param array: array_like
:param reverse: bool
:return: float -> float
"""
n = len(array)
op = operator.ge if reverse else operator.le
def ecdf(t):
m = sum(op(x, t) for x i... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def obb2poly_v1(rboxes):
"""Convert oriented bounding boxes to polygons.
Args:
obbs (torch.Tensor): [x_ctr,y_ctr,w,h,angle]
Returns:
polys (torch.Tensor): [x0,y0,x1,y1,x2,y2,x3,y3]
"""
x = rboxes[:, 0]
y = rboxes[:, 1]
w = rboxes[:, 2]
h = rboxes[:, 3]
... | bigcode/self-oss-instruct-sc2-concepts |
def join_url(*components: str) -> str:
"""Concatenates multiple url components into one url.
Args:
*components:
Multiple url components.
Returns:
A complete url.
"""
clean = [str(comp).strip('/') for comp in components]
return '/'.join(clean) | bigcode/self-oss-instruct-sc2-concepts |
def unique_path(path):
"""
Given a path, determine if all its elements are single-valued predicates. If so, the path is unique,
regardless of length. If any one of the steps in the path has a non single-valued predicated, the path is not
unique.
:param path: a definition path
:return: True if ... | bigcode/self-oss-instruct-sc2-concepts |
def _get_requirements_to_disable(old_requirements, new_requirements):
"""
Get the ids of 'CreditRequirement' entries to be disabled that are
deleted from the courseware.
Args:
old_requirements(QuerySet): QuerySet of CreditRequirement
new_requirements(list): List of requirements being ad... | bigcode/self-oss-instruct-sc2-concepts |
def update(cur_aggregate, new_value):
"""For a new value new_value, compute the new count, new mean, the new m_2.
* mean accumulates the mean of the entire dataset.
* m_2 aggregates the squared distance from the mean.
* count aggregates the number of samples seen so far.
"""
(count, mean, m_2) =... | bigcode/self-oss-instruct-sc2-concepts |
def getStringForAndDifferential(a, b, c):
"""
AND = valid(x,y,out) = (x and out) or (y and out) or (not out)
"""
command = "(({0} & {2}) | ({1} & {2}) | (~{2}))".format(a, b, c)
return command | bigcode/self-oss-instruct-sc2-concepts |
def read_data(filename):
"""
Reads raw space image format data file into a string
"""
data = ''
f = open(filename, 'r')
for line in f:
data += line.strip('\n')
f.close()
return data | bigcode/self-oss-instruct-sc2-concepts |
def get_descriptors_text(dl):
"""
Helper function that separates text descriptors from the mixture
of text and uris that is returned from Agritriop
Parameters
----------
dl : list
Descriptor list.
Returns
-------
list
list of text descritors only.
"""
retur... | 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.