seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
import ast
def loadSong(fileName):
"""
Loads a song from a file as input.
fileName: Name of the file to be read from
"""
with open (fileName, 'r') as f:
testSong = ast.literal_eval(f.read())
return testSong | bigcode/self-oss-instruct-sc2-concepts |
import re
def is_rdemo(file_name):
"""
Return True if file_name matches a regexp for an R demo. False otherwise.
:param file_name: file to test
"""
packaged_demos = ["h2o.anomaly.R", "h2o.deeplearning.R", "h2o.gbm.R", "h2o.glm.R", "h2o.glrm.R", "h2o.kmeans.R",
"h2o.naiveBaye... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def inner_product_similarity(a: torch.Tensor, b: torch.Tensor, dim: int = 1) -> torch.Tensor:
"""
Calculate inner product of two vectors
Args:
a (T, shape = (B, N_{a}, E)), data_type=torch.float: the first batch of vector to be multiplied
b (T, shape = (B, N_{b}, E)), dat... | bigcode/self-oss-instruct-sc2-concepts |
def _split_namespace(tag):
"""Split a tag into namespace and local tag strings (PRIVATE)."""
try:
return tag[1:].split('}', 1)
except ValueError:
return ('', tag) | bigcode/self-oss-instruct-sc2-concepts |
def get_Q(W):
"""Return the apsect ratio Q=N/M of a rectangular matrix W"""
if W.shape[1] > W.shape[0]:
M, N = W.shape
else:
N, M = W.shape
Q = N / M
return Q | bigcode/self-oss-instruct-sc2-concepts |
import collections
def GetRevealedCards(development_cards_dict, game_rules):
"""Returns a dict from Deck to list of revealed development cards.
The last N cards from each list are considered revealed cards. All
other cards are considered still part of the unrevealed decks.
Params:
development_cards_dict... | bigcode/self-oss-instruct-sc2-concepts |
def get_highest_scoring_ids(ids_set, id2sc_dic,
scfp_list=False):
"""
Given a set of IDs, and a ID to score mapping, return highest
scoring ID(s) in list.
scfp_list:
If score is stored in first position of list, with ID
mapping to list in id2sc_dic.
>>> ... | bigcode/self-oss-instruct-sc2-concepts |
def walk_line(strings, max_x, max_y, coordinates, direction, path_char):
"""
Given some starting points and a direction, find any connected corners in said direction.
:param strings string - the text that may contain rectangles.
:param max_x int - the boundary/width of the text.
:param max_y int - ... | bigcode/self-oss-instruct-sc2-concepts |
def QuadraticOut(start=0.0, finish=1.0):
"""
Quadratically increasing, starts faster : f(x) = 2x - x^2
"""
def quadratic_out_easing(sprite, delta):
return start + (finish - start) * (2.0 * delta - delta * delta)
return quadratic_out_easing | bigcode/self-oss-instruct-sc2-concepts |
def format_hail_linreg(linreg_expr):
"""
Format hail linear regression struct from arrays into slope and intercept
:param StructExpression linreg_expr:
:return: Formatted StructExpression
:rtype: StructExpression
"""
return linreg_expr.annotate(
beta=linreg_expr.beta[1],
sta... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Set
from typing import Dict
import copy
def true_positives(
T: Set[int], X: Set[int], margin: int = 5, choose_earliest: bool = True
) -> Dict[int, int]:
"""Compute true positives without double counting.
If there is multiple detected positives in the margin of a true positive and choose... | bigcode/self-oss-instruct-sc2-concepts |
def list_sra_accessions(reads):
"""
Return a list SRA accessions.
"""
accessions = []
if reads is not None:
accessions = reads.keys()
return accessions | bigcode/self-oss-instruct-sc2-concepts |
def get_board_score(board):
"""
Calculates the score of the winning board as per the rules of the problem
:param board: List[List[str]]
:return: int
"""
score = 0
for row in board:
for num in row:
if num is not None:
score += int(num)
return score | bigcode/self-oss-instruct-sc2-concepts |
def integer_bisect(bound, f):
"""
Finds a pair of integers (a,b) such that f(a) <= 0 < f(b) and |a - b| == 1.
On entry, assumes that f(bound[0]) <= 0 < f(bound[1])
"""
if bound[1] - bound[0] == 1:
return bound
else:
midpoint = round(bound[0] + bound[1] / 2.0)
if f(midpoin... | bigcode/self-oss-instruct-sc2-concepts |
def members(SWcoord, NEcoord, particles):
"""
Helper function:
Return the sub-list of particles that exist in the
box defined by SWcoord and NE coord.
Parameters
----------
SWcoord: Coordinate
Coordinate of the SW corner of the box
NEcoord : Coordinate
Coordinate of the ... | bigcode/self-oss-instruct-sc2-concepts |
import yaml
def get_config(name: str = "config.yaml") -> dict:
"""
Parses an arbitrary config file. Assumes the default will be
'config.yaml'.
Args:
name (str): The name of the YAML file. Default is "config.yaml".
Returns:
opt (dict): A dictionary containing the parsed YAML file... | bigcode/self-oss-instruct-sc2-concepts |
def getclosest_ij(lats,lons,latpt,lonpt):
"""Function to find the index of the closest point to a certain lon/lat value."""
dist_sq = (lats-latpt)**2 + (lons-lonpt)**2 # find squared distance of every point on grid
minindex_flattened = dist_sq.argmin()
#return np.unravel_index(mini... | bigcode/self-oss-instruct-sc2-concepts |
def get_mouse_pos(mouse_pos, rows, width):
"""
Return the cell that has been clicked on with the mouse.
params:
mouse_pos (int, int): position of the cursor
rows (int): number of rows in the grid
width (int): width of the scren
return:
row, col (int, int): coordinates of ... | bigcode/self-oss-instruct-sc2-concepts |
import textwrap
def indent(block, indent=2):
"""Indent a multi-line text block by a number of spaces"""
return textwrap.indent(block.strip(), ' ' * indent) | bigcode/self-oss-instruct-sc2-concepts |
def breadth(decomp):
"""
Return the sum of the exponents in the decomposition of the argument.
Accepts an int or a Decomposition.
Called uppercase-Omega in number theory.
"""
return sum([decomp[p] for p in decomp]) | bigcode/self-oss-instruct-sc2-concepts |
def _get_target_hname(elt):
"""
elt is sthg like:
resource "xxx" {
target="#yyy"
some_elt {...}
}
return the concatenated "#yyy/xxx" or uses the tag of 'some_elt'
"""
cmd_name = elt.get("name") or elt.text
target = elt.get("target")
if cmd_name is not None and tar... | bigcode/self-oss-instruct-sc2-concepts |
def cross(v1, v2):
"""Cross product of two vectors"""
n = len(v1)
prod = n*[0]
if n == 3 and len(v2) == 3:
prod[0] = v1[1]*v2[2] - v1[2]*v2[1]
prod[1] = v1[2]*v2[0] - v1[0]*v2[2]
prod[2] = v1[0]*v2[1] - v1[1]*v2[0]
return prod | bigcode/self-oss-instruct-sc2-concepts |
from typing import Sequence
import itertools
def _partition_spins(spins: Sequence[int]) -> Sequence[int]:
"""Returns the indices for splitting an array into spin channels."""
return list(itertools.accumulate(spins))[:-1] | bigcode/self-oss-instruct-sc2-concepts |
def load_ply_header(ply_path):
""" load header info from ply file (triangle mesh or polygon mesh)
Args:
ply_path (str): path to ply file
Returns:
info (dict): a dictionary containing the parsed header
e.g.
info == {'storing_type': 'binary_little_endian',
... | bigcode/self-oss-instruct-sc2-concepts |
def getGuess(alreadyGuessed):
"""
Returns the letter the player entered.
Ensures the player enters a single letter and nothing else.
"""
while True:
print('Please guess a letter.')
guess = input()
guess = guess.lower()
if len(guess) != 1:
print('Only a sin... | bigcode/self-oss-instruct-sc2-concepts |
import calendar
def get_nth_weekday(year, month, weekday, n):
""" 指定年月の第n曜日の日付を取得する
:param int year: year
:param int month: month [1-12]
:param int weekday: weekday [0-6] 0:Mon ... 6:Sun
:param int n: nth
:rtype: datetime.date
:return: date
"""
if not (1 <= month <= 12 > 12 or 0 ... | bigcode/self-oss-instruct-sc2-concepts |
def process_smooth_dates_fit_inputs(x, y, dt_idx, reg_dates):
"""Sanitises the inputs to the SmoothDates fitting method"""
if hasattr(x, 'index') and hasattr(y, 'index'):
assert x.index.equals(y.index), 'If `x` and `y` have indexes then they must be the same'
if dt_idx is None:
dt_id... | bigcode/self-oss-instruct-sc2-concepts |
from typing import OrderedDict
def attributes_to_odict_gff(attributes):
"""
Parse the GFF attribute column and return a dict
"""
if attributes == ".":
return OrderedDict()
ret_gff = OrderedDict()
for attribute in attributes.strip().split(";"):
if len(attribute):
e... | bigcode/self-oss-instruct-sc2-concepts |
import ast
def is_list_stored_as_string(x):
"""
Determine whether a value is a list stored as a strong.
"""
if '[' in str(x) and ']' in str(x):
try:
lst_x = ast.literal_eval(str(x))
is_list = isinstance(lst_x, list)
assert is_list, "Expected list for the fol... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Dict
def _check_if_key_is_reported(key: str, results: List[Dict]) -> bool:
"""Check if a particular key is reported by some workers.
Args:
key (str): A key string.
results (List[Dict]): The results list returned from workers.
Returns:
A ... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Type
from typing import Any
def fullclassname(cls: Type[Any]) -> str:
"""
Returns the fully qualified class name of the input class.
"""
module = cls.__module__
name = cls.__qualname__
if module is not None and module != "__builtin__":
name = module + "." + name
... | bigcode/self-oss-instruct-sc2-concepts |
def get_sku_info(sku, config):
"""Returns a sku info dictionary for sku.
Args:
sku: String specifying machine's SKU.
config: Configuration containing sku_meta.
Returns:
A dictionary containing sku info for the given machine sku, including
- cpu
- cpu usable ratio
... | bigcode/self-oss-instruct-sc2-concepts |
from unittest.mock import patch
def _patch_async_setup_entry(return_value=True):
"""Patch the async entry setup of sonarr."""
return patch(
"homeassistant.components.sonarr.async_setup_entry", return_value=return_value,
) | bigcode/self-oss-instruct-sc2-concepts |
import re
def strip_whitespace(string):
""" Strip newline, tab and multple whitespace from a string
"""
return re.sub(' +', ' ',
string.replace('\n', ' ').replace('\t', ' ').strip()) | bigcode/self-oss-instruct-sc2-concepts |
def get(identifier):
"""Returns an activation function from a string. Returns its input if it
is callable (already an activation for example).
Args:
identifier (str or Callable or None): the activation identifier.
Returns:
:class:`nn.Module` or None
"""
if identifier is None:
... | bigcode/self-oss-instruct-sc2-concepts |
def CollectVotes(composite,data,badOnly):
""" collects the votes from _composite_ for the examples in _data_
**Arguments**
- composite: a composite model
- data: a list of examples to run through _composite_
- badOnly: if set only bad (misclassified) examples will be kept
**Returns**
... | bigcode/self-oss-instruct-sc2-concepts |
import binascii
def convertfrom_hex_notation(bytes_string: bytes):
"""Takes a given bytes object containing hex notation (e.g. b'\\x00\\x01\\x02\\x03') and returns a bytes object with the hexadecimal notation '\\x' glyphs removed from the output (or, transforming the output to the "Hexadecimal representation of b... | bigcode/self-oss-instruct-sc2-concepts |
def _value_error_on_false(ok, *args):
"""Returns None / args[0] / args if ok."""
if not isinstance(ok, bool):
raise TypeError("first argument should be a bool")
if not ok:
raise ValueError("call failed")
if args:
return args if len(args) > 1 else args[0]
return None | bigcode/self-oss-instruct-sc2-concepts |
def find_last(s, sub):
"""s and sub are non-empty strings
Returns the index of the last occurrence of sub in s.
Returns None if sub does not occur in s"""
if s.find(sub) == -1: # this is the return value for s.find if it's not there
return None
else:
ans = s.find(sub) # found... | bigcode/self-oss-instruct-sc2-concepts |
def get_action_value(mdp, state_values, state, action, gamma):
""" Computes Q(s,a) as in formula above """
v = 0
for next_state in mdp.get_next_states(state, action):
v += (mdp.get_transition_prob(state, action, next_state)
* (mdp.get_reward(state, action, next_state) + gamma * state_... | bigcode/self-oss-instruct-sc2-concepts |
def is_src_url(param):
"""
Check if a parameter is a URL and return True if so
NOTE: be careful about changing this as it will influence how devtool/recipetool command line handling works
"""
if not param:
return False
elif '://' in param:
return True
elif param.startswith('g... | bigcode/self-oss-instruct-sc2-concepts |
import json
def json_parser(result, auth_token, cls=None):
"""JSON Parser Method
This method transforms JSON data into usable Python objects, if required and
generally checks for errors. Moreover, in the case that the desired Python
object requires an authentication token, this function provides that... | bigcode/self-oss-instruct-sc2-concepts |
def contains_only_zeros(image_data):
"""
Determines if data patch should be omitted from AL training. Patches in the
border region of the image can contain only padding (only values of 0). This
messes with the AL query strategy because the model is very uncertain, but
the patches don't contribute to... | bigcode/self-oss-instruct-sc2-concepts |
def is_targeting_windows(pkg_vars):
"""Returns true if 'platform' in pkg_vars indicates Windows."""
return pkg_vars['platform'].startswith('windows-') | bigcode/self-oss-instruct-sc2-concepts |
def make(error, message=None, response=None):
"""
Make error or success API response.
:param error: True if the response format has to be as an error, False otherwise.
:param message: Error message.
:param response: Success dictionary response.
:return: API response.
"""
response_dict = ... | bigcode/self-oss-instruct-sc2-concepts |
def _recursive_dict_without_none(a_dict, exclude=None):
"""
Remove all entries with `None` value from a dict, recursively.
Also drops all entries with keys in `exclude` in the top level.
"""
if exclude is None:
exclude = []
result = {}
for (k, v) in a_dict.items():
if v is ... | bigcode/self-oss-instruct-sc2-concepts |
def version_contains_field(version, field):
""" Checks if the given dictionary contains the given field.
Args:
version: A dictionary containing version details.
field: A string representing a key path.
Returns:
A boolean indicating whether or not the version contains the field.
"""
version_fragme... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def sample_noises(size):
"""
Sample noise vectors (z).
"""
return torch.randn(size) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Generator
import pkg_resources
def get_plugins() -> Generator[pkg_resources.EntryPoint, None, None]:
"""Iterate over available plugins."""
return pkg_resources.iter_entry_points(group="stan.plugins") | bigcode/self-oss-instruct-sc2-concepts |
def add(a,b):
"""sum a and b"""
return a+b | bigcode/self-oss-instruct-sc2-concepts |
def ticket_to_order_ratio(total_tickets, total_orders):
"""Returns the ratio of tickets to orders.
Args:
total_tickets (int): Total chats, emails, or tickets in the period.
total_orders (int): Total orders in the period.
Returns:
Ratio of tickets to orders
"""
return (tota... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Iterable
from typing import List
def add_prefix_to_list(data: Iterable[str], prefix: str) -> List[str]:
"""Adds a prefix to every item in an iterable (e.g. a list). Returns a list"""
return [f"{prefix}{item}" for item in data] | bigcode/self-oss-instruct-sc2-concepts |
def str2bool(text):
"""Simple function to convert a range of values to True/False."""
return text.lower() in ["true", "yes", "1"] | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def utc_timestamp() -> int:
"""Return current utc timestamp rounded to nearest int"""
return int(datetime.utcnow().timestamp()) | bigcode/self-oss-instruct-sc2-concepts |
def sp(v, g):
"""Scalar product of the two vectors v and g
Parameters
----------
v : np.array
g : np.array
Returns
-------
float
"""
return (v * g).sum() | bigcode/self-oss-instruct-sc2-concepts |
def create_book(conn, book):
"""
Create a new book into the books table
:param conn:
:param book:
:return: book id
"""
sql = ''' INSERT INTO Kirjat(id, name, tekija, status, lainaaja, varaaja)
VALUES(?,?,?,?,?,?) '''
cur = conn.cursor()
cur.execute(sql, book)
return... | bigcode/self-oss-instruct-sc2-concepts |
import math
def sanitizeAngle(theta):
"""
Returns an angle between 0 and 2pi.
Parameters
----------
theta : float
an angle
Returns
-------
theta : float
an angle between 0 and 2*pi
"""
if theta < 0:
theta = theta + (1 + -1 * int(theta / (math.pi * 2.0... | bigcode/self-oss-instruct-sc2-concepts |
import re
def to_number(text):
""" Returns the converted decimal value or a value of None for input strings. """
# Return the value of None for any text that is null or set to 'Not Applicable'
if text == '' or 'Not Applicable' in text or 'not applicable' in text or text is None:
return None
... | bigcode/self-oss-instruct-sc2-concepts |
def cc_score_fct(i):
"""CC (Chamberlin-Courant) score function."""
if i == 1:
return 1
else:
return 0 | bigcode/self-oss-instruct-sc2-concepts |
import re
def split_program_by_processing_element_label(program_string):
"""
Split a program string into a list of individual processing element programs based on the location of <*> labels.
:param program_string: multiline string containing an assembly program with <*> labels
:return: the correspond... | bigcode/self-oss-instruct-sc2-concepts |
def _get_point_est(md_tuple):
"""Get point estimate in mean_difference/normalized_mean_difference."""
return md_tuple[0] | bigcode/self-oss-instruct-sc2-concepts |
import math
def day_fraction_to_time(fraction):
"""Convert day fraction to to time as (hour, min, sec, usec) tuple."""
subsec, sec = math.modf(round(fraction * 86400.0, 6)) # round to usec
sec, usec = int(sec), int(subsec * 1e6)
min_, sec = (
sec / 60,
sec % 60,
)
hour, min_ =... | bigcode/self-oss-instruct-sc2-concepts |
def _is_healthy_pure(get_health_func, instance):
"""Checks to see if a component instance is running healthy
Pure function edition
Args
----
get_health_func: func(string) -> complex object
Look at unittests in test_discovery to see examples
instance: (string) fully qualified name of co... | bigcode/self-oss-instruct-sc2-concepts |
def exp(n, m):
"""
Calculates m ^ n.
"""
if n == 1:
# m ^ 1 = m
return m
else:
# m ^ n = m * m ^ (n-1)
return m * exp(m, n - 1) | bigcode/self-oss-instruct-sc2-concepts |
def _bulk_identity_factory(key_columns):
"""Return a function that accepts a dict mapping and returns its identity
corresponding its key values mapped by `key_columns`.
"""
return lambda mapping: tuple(mapping.get(col.key) for col in key_columns) | bigcode/self-oss-instruct-sc2-concepts |
def map_labels(label):
"""
Purpose: a function used for the pandas library's ".apply()" method
to convert all the specific labels in the dataframe into general labels
Params: label(string) -> the label from every single row of the dataframe column
Returns: a general label (string)
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def get_diffusion_information(image) :
""" Return the diffusion information from the ``image`` metadata. The
diffusion information is a dictionary and may contain the following keys :
* ``"diffusion_bvalue"``
* ``"diffusion_gradient_orientation"``
"""
result = {}
i... | bigcode/self-oss-instruct-sc2-concepts |
def add_prefix(key, prefix):
"""Add prefix to key."""
if prefix:
key = "{}_{}".format(prefix, key)
return key | bigcode/self-oss-instruct-sc2-concepts |
def subs_filename(subs_id, lang='en'):
"""
Generate proper filename for storage.
"""
if lang == 'en':
return f'subs_{subs_id}.srt.sjson'
else:
return f'{lang}_subs_{subs_id}.srt.sjson' | bigcode/self-oss-instruct-sc2-concepts |
def index_to_word(searched_index, tokenizer):
"""
Takes an input integer index and returns the word it is mapped to.
Args:
searched_index: the integer index of the searched word
tokenizer: the tokenizer which contains the word-index mappings
Returns:
word: the actual string word that the index is mapped to
"... | bigcode/self-oss-instruct-sc2-concepts |
def _entity_type(value):
"""
Type function used for parsing --members/--entities arguments
from colon-separated values into a list of (type, name) 2-tuples.
"""
entity_type, entity_name = value.split(':')
return entity_type, entity_name | bigcode/self-oss-instruct-sc2-concepts |
def euclidean(p1: tuple[int, int], p2: tuple[int, int]) -> int:
"""Calculate the distance between two points.
Args:
p1: First point.
p2: Second point.
Returns:
The distance between the two points.
"""
diff_x = p1[0] - p2[0]
diff_y = p1[1] - p2[1]
return (diff_x ** 2... | bigcode/self-oss-instruct-sc2-concepts |
def is_ssl(socket):
"""True if socket is an active SSLSocket."""
return bool(getattr(socket, '_sslobj', False)) | bigcode/self-oss-instruct-sc2-concepts |
import mpmath
def _butter_analog_poles(n):
"""
Poles of an analog Butterworth lowpass filter.
This is the same calculation as scipy.signal.buttap(n) or
scipy.signal.butter(n, 1, analog=True, output='zpk'), but mpmath is used,
and only the poles are returned.
"""
poles = []
for k in ra... | bigcode/self-oss-instruct-sc2-concepts |
def predict(X_test, model):
"""Predicts labels of X_test with a specific model
Parameters:
X_test - dataframe represents the test genomes features vectors
model - the relevant model
Returns:
predictions - final predictions (0 - NHP, 1- HP)
predictions_probs - probability estimates
"""... | bigcode/self-oss-instruct-sc2-concepts |
def _is_secret_env(name):
"""Returns True if name might be a secret.
Uses a simple heuristic to test for a secret name.
"""
name_lower = name.lower()
secret_parts = ("password", "token", "secret")
return any(part in name_lower for part in secret_parts) | bigcode/self-oss-instruct-sc2-concepts |
def did_gateway_mfr_test_result_include_miner_key_pass(
gateway_mfr_test_result
):
"""
Returns true if gateway_mfr_test_result["tests"] has an entry where
"test": "miner_key(0)" and "result": "pass"
Input: {
"result": "pass",
"tests": [
{
"output": "ok",
... | bigcode/self-oss-instruct-sc2-concepts |
def pkg_name(file: str) -> str:
"""Returns name of the package to which the `file` belongs.
"""
return __import__(file).__package__ | bigcode/self-oss-instruct-sc2-concepts |
def is_extension(filename: str, extension: str) -> bool:
"""
Return ``True`` if filename has the same extension
as the target extension.
Parameters
----------
filename: :class:`str`
The filename that you want to compare with.
extension: :class:`str`
The target extension that... | bigcode/self-oss-instruct-sc2-concepts |
def romaine_v1(string):
"""
(str) -> int
Converts roman numerals to arabic numerals using string methods.
Restrictions: string must consist of M, D, C, X, V, and/or I. Otherwise it
will return 0 (which is to be expected anyway).
"""
string = string.strip()
string = string.lower()
no... | bigcode/self-oss-instruct-sc2-concepts |
def asscalar(a):
"""
Convert an array of size 1 to its scalar equivalent.
Parameters
----------
a : ndarray
Input array.
Returns
-------
out : scalar
Scalar of size 1 array.
Examples
--------
>>> np.asscalar(np.array([24]))
>>> 24
"""
return a.... | bigcode/self-oss-instruct-sc2-concepts |
def before_send(event, hint):
"""Don't log django.DisallowedHost errors in Sentry."""
if "log_record" in hint:
if hint["log_record"].name == "django.security.DisallowedHost":
return None
return event | bigcode/self-oss-instruct-sc2-concepts |
import torch
def siamese_collate(batch):
"""
This collator is used in Jigsaw approach.
Input:
batch: Example
batch = [
{"data": [img1,], "label": [lbl1, ]}, #img1
{"data": [img2,], "label": [lbl2, ]}, #img2
.... | bigcode/self-oss-instruct-sc2-concepts |
def get_PerformanceCode(doc, trialid, code=True):
"""
Returns the performance of the monkey in the given trial either as code or
abbreviation.
Args:
doc (odml.doc.BaseDocument):
odML Document of reach-to-grasp project
trialid (int):
ID of wanted trial
cod... | bigcode/self-oss-instruct-sc2-concepts |
def seconds_to_string(seconds):
"""
Convert run seconds into string representation
:param seconds: Number of seconds
:type seconds: int
:return: String in the format of 'Xd Xh Xm Xs' based on the provided elapsed time
:rtype: string
"""
day = int(seconds // (24 * 3600))
time_mod = se... | bigcode/self-oss-instruct-sc2-concepts |
def combine_text_columns(data_frame, to_drop):
"""
Helper function to convert all text rows of data_frame to single vector
"""
to_drop = set(to_drop) & set(data_frame.columns.tolist())
text_data = data_frame.drop(to_drop, axis=1)
text_data.fillna(' ', inplace=True)
return text_da... | bigcode/self-oss-instruct-sc2-concepts |
def format_manufacturer(manufacturer):
"""Format a manufacturer for tweeting"""
if manufacturer.twitter_handle:
return f'@{manufacturer.twitter_handle}'
return manufacturer.name | bigcode/self-oss-instruct-sc2-concepts |
def merge_dicts(*dicts,
filler = 0):
"""
=================================================================================================
merge_dicts(*dicts, filler)
This function takes an arbitrary number of dictionaries and merges them together. If a key is not
found in one o... | bigcode/self-oss-instruct-sc2-concepts |
def date_format_to_human(value):
"""
Convert Python format date to human.
Example:
>>> date_format_to_human('%Y-%m-%d')
YYYY-MM-DD
:param value: Date format example: %Y-%m
"""
maps = {
'%y': 'YY',
'%Y': 'YYYY',
'%m': 'MM',
'%d': 'DD',
}
f... | bigcode/self-oss-instruct-sc2-concepts |
def get_property(data, key):
"""
Get a property, either from a JSON response dictionary or a dataclass.
"""
if isinstance(data, dict):
return data[key]
return getattr(data, key) | bigcode/self-oss-instruct-sc2-concepts |
def _code_range_to_set(code_range):
"""Converts a code range output by _parse_code_ranges to a set."""
characters = set()
for first, last, _ in code_range:
characters.update(range(first, last+1))
return characters | bigcode/self-oss-instruct-sc2-concepts |
def train_decorator(actor, *args, **kwargs):
"""Wrapping decorator for the train method."""
return actor.train(*args, **kwargs) | bigcode/self-oss-instruct-sc2-concepts |
def get_grant_project_image_upload_path(instance, filename):
"""
Construct the upload path for an image for a ProjectGrant object.
"""
return str("grant-projects/{0}/{1}").format(instance.name, filename) | bigcode/self-oss-instruct-sc2-concepts |
import re
def segment_data(data, regexp):
"""Splits the data string into segments that either match or do not match
the regular expression 'regexp'. Other than re.split() (or "".split()),
which leave out the separation string, the segments matching 'regexp'
are included in the result.
Args:
... | bigcode/self-oss-instruct-sc2-concepts |
def toString(s):
"""
Formats a 2D list Sudoku puzzle into one line of integers
for easy writing to a file
"""
output = ""
for i in range(9):
for j in range(9):
output += str(s[i][j])
return output + "\n" | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Any
from typing import Iterable
def filter_dict(d: Dict[str, Any], exclude: Iterable[str]) -> Dict[str, Any]:
"""Return a new dict with specified keys excluded from the original dict
Args:
d (dict): original dict
exclude (list): The keys that are exc... | bigcode/self-oss-instruct-sc2-concepts |
def sign_to_int(signs):
"""
Convert a list to an integer.
[-1, 1, 1, -1], -> 0b0110 -> 6
"""
return int("".join('0' if x == -1 else '1' for x in signs),2) | bigcode/self-oss-instruct-sc2-concepts |
def int2hex(number):
"""Returns a string representation of the number as hex.
"""
return "%04X" % number | bigcode/self-oss-instruct-sc2-concepts |
def get_prior_genes(fname):
"""Get the list of prior genes."""
with open(fname, 'rt') as fh:
genes = fh.read().strip().split('\n')
return genes | bigcode/self-oss-instruct-sc2-concepts |
import math
def LogBinomialCoef(n, k):
"""Computes the log of the binomial coefficient.
http://math.stackexchange.com/questions/64716/
approximating-the-logarithm-of-the-binomial-coefficient
n: number of trials
k: number of successes
Returns: float
"""
return n * math.log(n) - k * m... | 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.