seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def pil_coord_to_tesseract(pil_x, pil_y, tif_h):
""" Convert PIL coordinates into Tesseract boxfile coordinates:
in PIL, (0,0) is at the top left corner and
in tesseract boxfile format, (0,0) is at the bottom left corner.
"""
return pil_x, tif_h - pil_y | bigcode/self-oss-instruct-sc2-concepts |
def sort_fractions_by_denominator(fractions):
"""
The function takes a list of `Fraction` objects as its argument.
It returns a list of the fractions sorted by its denominator.
Use a lambda expression for the key function.
For example,
INPUT: [1/2, 3/4, 2/3]
OUTPUT: [3/4, 2/3, 1/2]
"""
... | bigcode/self-oss-instruct-sc2-concepts |
import requests
import time
def get_mac_address_vendor(mac_address: str, retries: int = 10) -> str:
""" """
# Can also use https://macvendors.co/api/{mac_address} for a richer payload
prefix = ''.join(mac_address.split(':')[0:3])
response = requests.get(f'https://macvendors.com/query/{prefix}')
... | bigcode/self-oss-instruct-sc2-concepts |
def fixture_env_name() -> str:
"""Get the name of a testing environment"""
return "D_marshmallow" | bigcode/self-oss-instruct-sc2-concepts |
def get_optimizer(dataset_name):
"""
Arguments
---------
dataset_name (str): name of dataset being trained
Returns
-------
optimizer (dict): parameters defining the optimizer to use during
training.
"""
if "noscope" in dataset_name:
# We use... | bigcode/self-oss-instruct-sc2-concepts |
def get_training_status(api, cfg, job_id, model_name):
"""
Gets the status of the given training job id
Arguments :
api : object, API object to access CloudML Engine
cfg : dict, Configurations from yaml file
job_id : string, Job ID of the training job
model_name : string, Na... | bigcode/self-oss-instruct-sc2-concepts |
def grazing(vs, eaten, zooplankton):
"""Zooplankton grows by amount digested, eaten decreases by amount grazed"""
return {eaten: - vs.grazing[eaten], zooplankton: vs.grazing[eaten]} | bigcode/self-oss-instruct-sc2-concepts |
def normalize(lines: str) -> str:
""" Remove trailing whitespace from each line,
keeping all line breaks except the last."""
return '\n'.join(line.rstrip() for line in lines.strip().splitlines()) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Tuple
def dense_dict(dictionary: Dict, removables: Tuple = (None,)) -> Dict:
"""Return a dictionary ignoring keys with None values, recursively."""
return {
k: dense_dict(v) if isinstance(v, dict) else v
for k, v in dictionary.items()
if v not... | bigcode/self-oss-instruct-sc2-concepts |
def combine_lines(components, element_list, background):
"""
Combine results for different lines of the same element.
And also add pileup, userpeak, background, compton and elastic.
Parameters
----------
components : dict
output results from lmfit
element_list : list
list of... | bigcode/self-oss-instruct-sc2-concepts |
def alg_int(u, v):
"""
Given two slopes, compute their algebraic intersection number.
"""
a, b = u
c, d = v
return a*d - b*c | bigcode/self-oss-instruct-sc2-concepts |
import torch
def bound_and_scale(scale, bounds):
"""
Combination of scaling and bounding
Args:
scale (torch.tensor): divide input by this value
bounds (torch.tensor): tuple, clamp to (bounds[0], bounds[1])
"""
return lambda x: torch.clamp(x / scale, bounds[0], bounds[1]) | bigcode/self-oss-instruct-sc2-concepts |
def nexus_infile(myid,itwist):
""" nexus style input name
Args:
myid (str): prefix
itwist (int): twist index
Returns:
str: input filename
"""
prefix = myid.split('.')[0]
infile = '.'.join([prefix,'g%s'%str(itwist).zfill(3),'twistnum_%d'%itwist,'in','xml'])
return infile | bigcode/self-oss-instruct-sc2-concepts |
def flip_subarray_params(input_params):
"""
Helper function to switch the row and column entries in a SUBARRAY tuple
"""
assert isinstance(input_params, (tuple,list))
assert len(input_params) == 4
output_params = [input_params[1],
input_params[0],
... | bigcode/self-oss-instruct-sc2-concepts |
def count(catalog):
"""Given a Catalog, return the number of strings actually translated."""
translated = [m for m in
catalog
if m.string]
return len(translated) | bigcode/self-oss-instruct-sc2-concepts |
def _parse_user_ids(users, client):
"""parse a string of users separated by commas into IDS"""
ids = []
split_users = users.split(',')
for u in split_users:
u = u.strip()
if len(u) > 0:
uid = client.users.list(query=u)
if uid:
ids.append(uid[0]['id... | bigcode/self-oss-instruct-sc2-concepts |
import socket
def IPv4(ip_addr):
"""
Validate a string as an IPv4 address. See `man 3 inet` for details.
"""
ip_addr = str(ip_addr)
try:
socket.inet_aton(ip_addr)
except socket.error:
raise ValueError('Invalid IPv4 address: %s' % ip_addr)
return ip_addr | bigcode/self-oss-instruct-sc2-concepts |
def cg_has_node(cg, node):
"""
Return True if the cluster graph contains the corresponding node
:param cg:
:param node:
:return:
"""
return cg.nodes().__contains__(node) | bigcode/self-oss-instruct-sc2-concepts |
def get_movie_data_both_channels (data, movie_ID):
"""Pull out track data in both channels for one movie out of a dataframe.
Args:
data (Pandas dataframe): Parsed tracks for each movie, as created by the
read_2color_data function of the parse_trackmate module. Contains
the follo... | bigcode/self-oss-instruct-sc2-concepts |
def create_in_term_for_db_queries(values, as_string=False):
"""
Utility method converting a collection of values (iterable) into a tuple
that can be used for an IN statement in a DB query.
:param as_string: If *True* the values of the list will be surrounded
by quoting.
:type as_string: :cl... | bigcode/self-oss-instruct-sc2-concepts |
def __pos__(self) :
"""Return self"""
return self; | bigcode/self-oss-instruct-sc2-concepts |
def parse_bq_record(bq_record):
"""Parses a bq_record to a dictionary."""
output = {}
for key in bq_record:
output[key] = [bq_record[key]]
return output | bigcode/self-oss-instruct-sc2-concepts |
def dumps(blackbird):
"""Serialize a blackbird program to a string.
Args:
blackbird (BlackbirdProgram): a :class:`BlackbirdProgram` object
Returns:
str: the serialized Blackbird program
"""
return blackbird.serialize() | bigcode/self-oss-instruct-sc2-concepts |
def select_all_photo_thumbnail(session):
"""Get a list of all image thumbnails from db"""
session.execute("""
SELECT url, title FROM photos
""")
return session.fetchall() | bigcode/self-oss-instruct-sc2-concepts |
import re
def is_copy_modify_with_no_change(diff_header):
"""Returns true if similarity index is 100% in the diff header."""
return re.search(r"(?m)^similarity index 100%", diff_header) | bigcode/self-oss-instruct-sc2-concepts |
from functools import reduce
def modeOfLengths(input):
"""
PROTOTYPE:
modeOfLengths(input)
DESCRIPTION:
Finds the mode (most frequently occurring value) of the lengths of the lines.
ARGUMENTS:
- input is list of lists of data
RETURNS:
mode as integer
"""
freq = {}
... | bigcode/self-oss-instruct-sc2-concepts |
def create_route_map(obj):
"""
Iterates of all attributes of the class looking for attributes which
have been decorated by the @on() decorator It returns a dictionary where
the action name are the keys and the decorated functions are the values.
To illustrate this with an example, consider the foll... | bigcode/self-oss-instruct-sc2-concepts |
from typing import BinaryIO
def _bytes_match(fd: BinaryIO, expected: bytes) -> bool:
"""Peeks at the next bytes to see if they match the expected."""
try:
offset = fd.tell()
data = fd.read(len(expected))
fd.seek(offset)
return data == expected
except IOError:
return... | bigcode/self-oss-instruct-sc2-concepts |
def splitPath(path, sep='/'):
"""
Chops the first part of a /-separated path and returns a tuple
of the first part and the tail.
If no separator in the path, the tail is None
"""
sepIdx = path.find(sep)
if sepIdx < 0:
return (path, None)
return path[:sepIdx], path[se... | bigcode/self-oss-instruct-sc2-concepts |
def is_valid_deck(deck):
"""(list of int) -> bool
Precondition: the length of input list is a list of number.
Return true iff the input deck is a valid deck of cards,
which means number of cards in the deck is consecutive.
Return false if the input deck is not a valid deck of cards.
>>> deck ... | bigcode/self-oss-instruct-sc2-concepts |
import math
def _daylight_hours(sunset_hour_angle_radians):
"""
Calculate daylight hours from a sunset hour angle.
Based on FAO equation 34 in Allen et al (1998).
:param sunset_hour_angle_radians: sunset hour angle, in radians
:return: number of daylight hours corresponding to the sunset hour an... | bigcode/self-oss-instruct-sc2-concepts |
import math
def lg(n):
"""
Returns logarithm of n in base 2.
"""
return math.log(n, 2) | bigcode/self-oss-instruct-sc2-concepts |
def strip_quotes(string):
"""
Strips quotes off the ends of `string` if it is quoted
and returns it.
"""
if len(string) >= 2:
if string[0] == string[-1]:
if string[0] in ('"', "'"):
string = string[1:-1]
return string | bigcode/self-oss-instruct-sc2-concepts |
def __get_token(path: str):
"""
Get the API token from the container's file system.
"""
with open(path, "r", encoding="utf-8") as file:
return file.read() | bigcode/self-oss-instruct-sc2-concepts |
def _get_element_attr_or_none(document, selector, attribute):
"""
Using a CSS selector, get the element and return the given attribute value, or None if no element.
Args:
document (HTMLElement) - HTMLElement document
selector (str) - CSS selector
attribute (str) - The attribute to g... | bigcode/self-oss-instruct-sc2-concepts |
def invert_sign(num):
"""Change sign of number or add/remove leading sign of str."""
if isinstance(num, (float, int)):
return -1 * num
elif isinstance(num, str):
if num.startswith('-'):
return num[1:]
return '-{0}'.format(num)
raise ValueError(
'Num needs to b... | bigcode/self-oss-instruct-sc2-concepts |
def as_microsoft(expression):
"""
Decorated function is added to the provided expression as the Microsoft
vender specific as_sql override.
"""
def dec(func):
setattr(expression, 'as_microsoft', func)
return func
return dec | bigcode/self-oss-instruct-sc2-concepts |
def _get_like_function_shapes_chunks(a, chunks, shape):
"""
Helper function for finding shapes and chunks for *_like()
array creation functions.
"""
if shape is None:
shape = a.shape
if chunks is None:
chunks = a.chunks
elif chunks is None:
chunks = "auto"
... | bigcode/self-oss-instruct-sc2-concepts |
def get_div_ids_by_level(divs, level):
"""
Returns a list of all div ids with level.
"""
if not isinstance(divs, list):
divs = [divs]
ids = []
for div in divs:
if div['level'] == level:
ids.append(div['id'])
# no need to check subdivs
cont... | bigcode/self-oss-instruct-sc2-concepts |
def new_admin(user, password_hasher):
""" Create new admin user for testing. """
User = user
# Admin user mock data
admin_user_data = {
"username": "admin",
"email": "admin@email.com",
"password": password_hasher.hash("admin"),
}
new_admin = User(**admin_user_data)
... | bigcode/self-oss-instruct-sc2-concepts |
import six
def flatten_content_tree(roots, depth=0):
"""
Transforms a tree into a list with ``indent`` as the depth of a node
in the original tree.
"""
results = []
for key, values in six.iteritems(roots):
elem, nodes = values
elem.update({
'path': key,
... | bigcode/self-oss-instruct-sc2-concepts |
def image_count(list_bboxes, list_classes):
"""
统计全图各个类别的数量。
:param list_bboxes: BoundingBoxs list
:param list_classes: Classes list
:return: 各个类别的数量.
"""
class_num = [0]*len(list_classes)
for i in range(0, len(list_bboxes)):
x1 = list_bboxes[i].xmin
y1 = list_bboxes[i... | bigcode/self-oss-instruct-sc2-concepts |
def bdev_ocf_create(client, name, mode, cache_line_size, cache_bdev_name, core_bdev_name):
"""Add an OCF block device
Args:
name: name of constructed OCF bdev
mode: OCF cache mode: {'wb', 'wt', 'pt', 'wa', 'wi', 'wo'}
cache_line_size: OCF cache line size. The unit is KiB: {4, 8, 16, 32,... | bigcode/self-oss-instruct-sc2-concepts |
def binary_search(search_list, search_key):
"""Find the index of a value of a key in a sorted list using
a binary search algorithm. Returns the index of the value if
found. Otherwise, returns -1.
"""
left_idx, right_idx = 0, len(search_list) - 1
# while True:
while left_idx <= right_idx:
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def beam_options_to_args(options: dict) -> List[str]:
"""
Returns a formatted pipeline options from a dictionary of arguments
The logic of this method should be compatible with Apache Beam:
https://github.com/apache/beam/blob/b56740f0e8cd80c2873412847d0b336837429fb9/sdks/pytho... | bigcode/self-oss-instruct-sc2-concepts |
def tasks_get_filtered(taskid_list, module):
"""
Get tasks information from a list of tasks.
Parameters
----------
taskid_list : list
List of task IDs to get.
module : AnsibleModule
Ansible module.
Returns
-------
list
List of tasks from CVP.
"""
tas... | bigcode/self-oss-instruct-sc2-concepts |
import math
def cos_sin_deg(deg):
"""Return the cosine and sin for the given angle
in degrees, with special-case handling of multiples
of 90 for perfect right angles
"""
deg = deg % 360.0
if deg == 90.0:
return 0.0, 1.0
elif deg == 180.0:
return -1.0, 0
elif deg == 270.... | bigcode/self-oss-instruct-sc2-concepts |
def get_header_idx(fname):
"""
Opens the file from fname and returns the row index corresponding to the
header row (with all the column name field information)
"""
blanks = []
with open(fname,'r') as f:
lines = f.readlines()
for i, line in enumerate(lines):
if li... | bigcode/self-oss-instruct-sc2-concepts |
def get_dotfield_value(dotfield, d):
"""
Explore dictionary d using dotfield notation and return value.
Ex: d = {"a":{"b":1}}.
get_dotfield_value("a.b",d) => 1
"""
fields = dotfield.split(".")
if len(fields) == 1:
return d[fields[0]]
else:
first = fields[0]
re... | bigcode/self-oss-instruct-sc2-concepts |
def permutations(numbers, descents):
"""Compute number of permutations with specified number of descents"""
if descents in (0, numbers - 1):
return 1
add0 = (descents + 1) * permutations(numbers - 1, descents)
add1 = (numbers - descents) * permutations(numbers - 1, descents - 1)
return (ad... | bigcode/self-oss-instruct-sc2-concepts |
def fahr_to_celsius(temp_fahr):
"""Convert temperature from Fahrenheit to Celsius"""
temp_celsius = (temp_fahr - 32) * 5 / 9.0
return temp_celsius | bigcode/self-oss-instruct-sc2-concepts |
from typing import OrderedDict
def parse_info(soup):
"""Parse rent and detail descriptions from soup
Arguments:
soup: the soup object to parse from
Returns:
information (dict): parsed information
"""
info = OrderedDict()
infoSection = soup.select("div.detailInfo.clearfix")[... | bigcode/self-oss-instruct-sc2-concepts |
def fix_line_breaks(s):
"""
Convert \r\n and \r to \n chars. Strip any leading or trailing whitespace
on each line. Remove blank lines.
"""
l = s.splitlines()
x = [i.strip() for i in l]
x = [i for i in x if i] # remove blank lines
return "\n".join(x) | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def shasha(msg):
"""SHA256(SHA256(msg)) -> HASH object"""
res = hashlib.sha256(hashlib.sha256(msg).digest())
return res | bigcode/self-oss-instruct-sc2-concepts |
def get_data_types_query() -> str:
"""
Define custom data types inside a database.
"""
# Define data types.
query = """
CREATE TYPE AssetClass AS ENUM ('futures', 'etfs', 'forex', 'stocks', 'sp_500');
CREATE TYPE Frequency AS ENUM ('minute', 'daily', 'tick');
CREATE TYPE ContractType AS ... | bigcode/self-oss-instruct-sc2-concepts |
def utrue(x,y):
"""
Return true solution for a test case where this is known.
This function should satisfy u_{xx} + u_{yy} = 0.
"""
utrue = x**2 - y**2
return utrue | bigcode/self-oss-instruct-sc2-concepts |
def consists_of(seq, types):
"""
Check that the all elements from the "seq" argument (sequence) are among the types passed as the "types" argument.
@param seq: The sequence which elements are to be typed.
@param types: A tuple of types to check.
@type types: tuple
@return: Whether the check ... | bigcode/self-oss-instruct-sc2-concepts |
def get_unique_value(query_set, field_name, value):
"""Gets a unique name for an object corresponding to a particular
django query. Useful if you've defined your field as unique
but are system-generating the values. Starts by checking
<value> and then goes to <value>_2, <value>_3, ... until
... | bigcode/self-oss-instruct-sc2-concepts |
def bias_term(ci, ref, meta_dict, n_range):
"""
Compute the bias term to be subtracted off the cross spectrum to compute
the covariance spectrum. Equation in Equation in footnote 4 (section 2.1.3,
page 12) of Uttley et al. 2014.
Assumes power spectra are raw (not at all normalized, and not Poisson-... | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def contains_peroxide(structure, relative_cutoff=1.2):
"""
Determines if a structure contains peroxide anions.
Args:
structure:
Input structure.
relative_cutoff:
The peroxide bond distance is 1.49 Angstrom. Relative_cutoff * 1.49
stipul... | bigcode/self-oss-instruct-sc2-concepts |
def calculate_param_b(
operating_frequency: float,
atmosphere_height_of_max: float,
atmosphere_semi_width: float,
atmosphere_max_plasma_frequency_squared: float) -> float:
"""
Calculates the B parameter following Hill 1979
"""
atmosphere_base_height = atmosphere_height_of... | bigcode/self-oss-instruct-sc2-concepts |
def get_snapshot_run_correlation_id(test_run_name, snapshot_type):
"""Returns the qualified string to use as correlation id.
Keyword arguments:
test_run_name -- the test run name for this run
snapshot_type -- either 'full' or 'incremental'
"""
return f"{test_run_name}_{snapshot_type}" | bigcode/self-oss-instruct-sc2-concepts |
def prune_cells(grid):
"""Given a grid, scan each row for solved cells, and remove those
numbers from every other cell in the row.
Note that 'grid' can be an iterable of rows, columns, or 3x3 squares.
Since the component cells (sets) are modified in-place it still works
if you rearrange things.... | bigcode/self-oss-instruct-sc2-concepts |
def _copy_cursor(cursor):
"""Returns a new cursor with the same properites that won't affect the original
@cursor: any cursor that hasn't already been iterated over
@return: new cursor with same attributes
"""
new_cursor = cursor.collection.find()
new_cursor.__dict__.update(cursor.__dict__)
... | bigcode/self-oss-instruct-sc2-concepts |
def _build_link_header(links):
"""
Builds a Link header according to RFC 5988.
The format is a dict where the keys are the URI with the value being
a dict of link parameters:
{
'/page=3': {
'rel': 'next',
},
'/page=1': {
'rel': ... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def scale_model(model, scale):
"""Scale the parameters of a model.
Args:
model (torch.nn.Module): the models whose parameters will be scaled.
scale (float): the scaling factor.
Returns:
torch.nn.Module: the module with scaled parameters.
"""
params = model.na... | bigcode/self-oss-instruct-sc2-concepts |
def printXYZ(self):
"""Print X, Y, and Z components."""
return ("[%f, %f, %f]" % (self.x, self.y, self.z)) | bigcode/self-oss-instruct-sc2-concepts |
def _check_columns(df_to_check, cols) -> None:
"""Check that a list of required column names is in a data frame
Args:
df_to_check: A DataFrame to check columns on.
cols (Iterable[str]): Required columns.
Returns:
None
Raises:
ValueError: if required cols are not a subset... | bigcode/self-oss-instruct-sc2-concepts |
def is_classdef(leaf):
"""
Returns true if the leaf is the beginning of a class definition
"""
return leaf.type == 'keyword' and leaf.value == 'class' | bigcode/self-oss-instruct-sc2-concepts |
def get_play_speed(ctx):
"""获取机器人运行速度
Args:
ctx (context.Context): 登陆上下文
Retures:
Success (int): 机器人运行速度
Failure (None): None
"""
return ctx.tran.request("GET", "/v2/paramservice/robot/playspeed")["data"] | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def sieve_of_eratosthenes(n: int) -> List[int]:
"""
Simple Sieve of Eratosthenes algorithm to return all primes up to n.
:param n: the upper bound on the primes
:return: the list of primes in order
>>> sieve_of_eratosthenes(0)
[]
>>> sieve_of_eratosthenes(1)
[]... | bigcode/self-oss-instruct-sc2-concepts |
import errno
def _recv(sock, size):
"""sock.recv() with retry on EINTR"""
while True:
try:
return sock.recv(size)
except IOError as e:
if e.errno != errno.EINTR:
raise | bigcode/self-oss-instruct-sc2-concepts |
def oncePerStep(sprite, game, name):
""" Utility for guaranteeing that an event gets triggered only once per time-step on each sprite. """
name = "_"+name
if hasattr(sprite, name):
# bounce only once per timestep, even if there are multiple collisions
if sprite.__dict__[name] == game.time:
... | bigcode/self-oss-instruct-sc2-concepts |
import requests
import json
def post_json(url, data):
"""Helper method send HTTP POST requests to Elasticsearch."""
return requests.post(
url,
data=json.dumps(data),
headers={'Content-Type': 'application/json'},
) | bigcode/self-oss-instruct-sc2-concepts |
def build_site_url(site,url,secure=False):
"""
Build an absolute URL for a given site
"""
protocol='http'
if secure:
protocol='https'
return u'%s://%s%s' % (protocol,site.domain,url) | bigcode/self-oss-instruct-sc2-concepts |
def _CodepointString(unicode_text):
"""Converts unicode string to string of integers in uppercase hex.
Integers correspond to the codepoints within the string. Each integer is
followed by a space.
Args:
unicode_text: unicode string
Returns:
string
"""
return " ".join("%04X" % ord(c) for c in un... | bigcode/self-oss-instruct-sc2-concepts |
def get_tables(client, dataset):
"""
Get the names of all tables in a bigquery dataset.
client: bigquery connection
dataset: a connected bigquery dataset
Returns a list of all tables in the dataset
"""
return [table.table_id for table in client.list_tables(dataset)] | bigcode/self-oss-instruct-sc2-concepts |
def store_true(arg, _, args, acc):
"""
lambda that store a True boolean value on the parser result
"""
acc[arg] = True
return args, acc | bigcode/self-oss-instruct-sc2-concepts |
def hour_decimal(dt):
""" For example, the time 12:45 becomes 12.75 """
return dt.hour + dt.minute/60 | bigcode/self-oss-instruct-sc2-concepts |
import json
import base64
def get_token_claim(jwt, claim):
"""Extract a claim from a JWT token without validating it."""
# Directly decode the base64 claims part without pulling in any JWT libraries
# (since we're not validating any signatures).
claims = jwt.split(".")[1]
# Pad the JWT claims bec... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def _path_datafile(filename):
"""
Get absolute path to toolbox datafile
:param filename: relative pathname of datafile
:type filename: str
:raises ValueError: File does not exist
:return: Absolute path relative to *roboticstoolbox* folder
:rtype: str
Get the ... | bigcode/self-oss-instruct-sc2-concepts |
from urllib.parse import quote, urlsplit, urlunsplit
def idna2ascii(url):
"""Converts unicode url to ascii"""
parts = urlsplit(url)
return urlunsplit((
parts.scheme,
parts.netloc.encode('idna').decode('ascii'),
quote(parts.path),
quote(parts.query, '='),
quote(parts... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
from typing import Callable
def apply_to_all(dictionary: dict[Any, Any], func: Callable[[Any], Any]) -> Any:
"""Recursively apply a callable to all elements (keys + values) of a dictionary."""
if type(dictionary) != dict:
return func(dictionary)
return {func(k): apply_to_all... | bigcode/self-oss-instruct-sc2-concepts |
def xrsplit(array):
"""
Split an array to a list of all the components.
Parameters
----------
array: xarray.DataArray
Array to split.
Returns
-------
sp_list: list of xarray.DataArrays
List of shape 0 xarray.DataArrays with coordinates.
"""
sp_list = [sa for sa... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def now() -> int:
"""
Get UNIX-style time since epoch in seconds.
Returns
-------
int
Time since epoch in seconds.
"""
return int(datetime.now().timestamp() * 1000) | bigcode/self-oss-instruct-sc2-concepts |
def netInputIndex(s, current, x, y):
"""
Helper function for gameToNetInput. Get the index of the list to update
:param s: The piece at the position being looked at
:param current: The currently selected piece, None if no piece is selected
:param x: The x coordinate of the position being looked at
... | bigcode/self-oss-instruct-sc2-concepts |
def get_missing_face_hierarchical_keywords(iptc_data, face_list=None):
"""Checks if keywords need to be added for faces. Returns the keywords that need
to be added."""
missing_keywords = []
if face_list == None:
face_list = iptc_data.region_names
for name in face_list:
# Look for ... | bigcode/self-oss-instruct-sc2-concepts |
def find_period(traj):
"""Find approximate period of oscillation using the last two
peak event times in voltage"""
try:
evs = traj.getEventTimes('peak_ev')
return evs[-1] - evs[-2]
except:
return 0 | bigcode/self-oss-instruct-sc2-concepts |
def dB2gain(dB):
"""Convert dB to multiplicative gain"""
return 10.0**(dB/20.0) | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def to_unixtime(t):
"""Return float of total seconds since Unix time."""
return (t - datetime(1970, 1, 1, 0, 0, 0)).total_seconds() | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
from typing import List
def read_filelist(filepath: Path) -> List[str]:
"""
Read a list of files from a file (one file per line). Lines beginning with # are ignored
:param filepath: The path of the file containing filenames
:return: A list of filenames as strings
"""
a... | bigcode/self-oss-instruct-sc2-concepts |
def getSeqLens(fastaf):
"""Return a table with length in kilobases for each seq in fastaf."""
lenout = {}
curRec, curLen = None, 0
with open(fastaf) as ff:
for line in ff:
line = line.strip()
if len(line) == 0:
continue
if line[0] == '>':
... | bigcode/self-oss-instruct-sc2-concepts |
import json
def make_series_key(key, tags, attributes):
"""Utility function for making a series key POST body, used mainly for
the series creation API endpoint.
:param string key: the series key
:rtype: string"""
return json.dumps({'key': key, 'tags': tags, 'attributes': attributes}) | bigcode/self-oss-instruct-sc2-concepts |
def _get_macro_edge_reversal_conflicts_with_existing_descriptor(
reverse_base_class_name, reverse_target_class_name, existing_descriptor
):
"""Return a (possibly empty) list of reversal conflicts relative to an existing macro edge."""
errors = []
if reverse_base_class_name != existing_descriptor.base_cl... | bigcode/self-oss-instruct-sc2-concepts |
def generate_db_url(user, password, host, db_name, protocol = "mysql+pymysql"):
"""
Utility function for generating database URL
This function generates a database URL with the mysql and pymysql protocol for use with pandas.read_sql()
Parameters
----------
user : str
The username for the... | bigcode/self-oss-instruct-sc2-concepts |
def _env_to_bool(val):
"""
Convert *val* to a bool if it's not a bool in the first place.
"""
if isinstance(val, bool):
return val
val = val.strip().lower()
if val in ("1", "true", "yes", "on"):
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
def maybeint(string: str) -> Union[str, int]:
"""
Try to cast a string to a int
:param str string: to cast
:return: int(string) or string in case cast fails
"""
try:
return int(string)
except ValueError:
return string | bigcode/self-oss-instruct-sc2-concepts |
import pickle
def read_from_pickle(fn):
"""
Function to read data from a pickled file
Parameters
----------
fn : str
File directory.
data : any type, but recommend dictionary
data to read.
Returns
-------
data : same as data
Read in this variable.
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def htons(x):
"""Convert 16-bit positive integers from host to network byte order."""
return (((x) << 8) & 0xFF00) | (((x) >> 8) & 0xFF) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Sequence
def _parse_info(lines:Sequence[str]) -> dict:
"""Parse info.txt and return dictionary with relevant data"""
auto = lines[0] == "AUTO"
yaw, pitch, roll = map(float, lines[1].split(" "))
fov = float(lines[5])
return dict(
auto=auto,
fov=fov,
yaw=ya... | 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.