seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def parse_egg_dirname(dn):
"""
Extrahiere die folgenden Informationen aus dem Namen:
- den Paketnamen
- die Versionsangabe
- das Python-Versionstupel
>>> parse_egg_dirname('visaplan.tools-1.0-py2.7.egg')
('visaplan.tools', '1.0', (2, 7))
Sonstige Namen werden nicht erkannt:
>>> pa... | bigcode/self-oss-instruct-sc2-concepts |
def _serialize_time(val):
"""Create a JSON encodable value of a time object."""
return val.isoformat() | bigcode/self-oss-instruct-sc2-concepts |
def signed_int_str(input_int: int):
"""
Converts an integer into a string that includes the integer's sign, + or -
:param int input_int: the input integer to convert to a signed integer string
:return str signed_int_str: the signed integer string
"""
if input_int >= 0:
return '+' + str(... | bigcode/self-oss-instruct-sc2-concepts |
def handle_object_placement(handle_to_self_field, potential_object, objectType, list=False):
"""
Helper function to checks to see if we can safely set a given field (handle_to_self_field)
to a potential_object by checking whether or not it is an instance of objectType.
:param handle_to_self_... | bigcode/self-oss-instruct-sc2-concepts |
def extract_ratelimit(headers_dict):
"""Returns rate limit dict, extracted from full headers."""
return {
"used": int(headers_dict.get("X-RateLimit-Used", 0)),
"expire": float(headers_dict.get("X-RateLimit-Expire", 0)),
"limit": int(headers_dict.get("X-RateLimit-Limit", 0)),
"rem... | bigcode/self-oss-instruct-sc2-concepts |
import math
def distance(node1,node2):
"""
Calculates distance between nodes in pixels
Parameters
----------
node1 : Treelib Node
first node
node2 : Treelib Node
second node
Returns
-------
distance : float
distance between nodes in pixels
... | bigcode/self-oss-instruct-sc2-concepts |
def format_weather_data(data_str):
""" Take weather data in weewx format and transform to param/value dict"""
## Data sample direct from weewx (shortened)
# "altimeter: 72.317316, ... maxSolarRad: None, ... windGustDir: 359.99994, windSpeed: 5.1645e-09"
# Replace "None" values with 0's
data_str =... | bigcode/self-oss-instruct-sc2-concepts |
def primes(imax):
"""
Returns prime numbers up to imax.
Parameters
----------
imax: int
The number of primes to return. This should be less or equal to 10000.
Returns
-------
result: list
The list of prime numbers.
"""
p = list(range(10000))
result = []
... | bigcode/self-oss-instruct-sc2-concepts |
def _pairwise(iterable):
""" Returns items from an iterable two at a time, ala
[0, 1, 2, 3, ...] -> [(0, 1), (2, 3), ...] """
iterable = iter(iterable)
return zip(iterable, iterable) | bigcode/self-oss-instruct-sc2-concepts |
def entitydata_form_add_field(form_data_dict, field_name, dup_index, value):
"""
Add field value to form data; if duplicate then reformat appropriately.
Updates and returns supplied form data dictionary.
"""
if field_name in form_data_dict:
suffix = "__%d"%dup_index
else:
suffix... | bigcode/self-oss-instruct-sc2-concepts |
def generate_bio_entity_tags(mentions, sentence_length):
"""
Generate BIO/IOB2 tags for entity detection task.
"""
bio_tags = ['O'] * sentence_length
for mention in mentions:
start = mention['start']
end = mention['end']
bio_tags[start] = 'B-E'
for i in range(start + ... | bigcode/self-oss-instruct-sc2-concepts |
def parseTime(t):
"""
Parses a time value, recognising suffices like 'm' for minutes,
's' for seconds, 'h' for hours, 'd' for days, 'w' for weeks,
'M' for months.
>>> endings = {'s':1, 'm':60, 'h':60*60, 'd':60*60*24, 'w':60*60*24*7, 'M':60*60*24*30}
>>> not False in [endings[i]*3 == parseT... | bigcode/self-oss-instruct-sc2-concepts |
def binary_search(array, target):
"""
array is assumed to be sorted in increasing values
Find the location i in the array such that array[i-1] <= target < array[i-1]
"""
lower = 0
upper = len(array)
while lower < upper: # use < instead of <=
x = lower + (upper - lower) // 2
... | bigcode/self-oss-instruct-sc2-concepts |
def f(N1, N2, Vg1, Vg2, Ec1, Ec2, Cg1, Cg2, Ecm, e):
"""
Parameters
----------
N1 : Int
Number of electrons on dot 1.
N2 : Int
Number of electrons on dot 1.
Vg1 : Float
Voltage on gate 1.
Vg2 : Float
Voltage on gate 2.
Ec1 : Float
Charging energy ... | bigcode/self-oss-instruct-sc2-concepts |
def findChIndex(c, str_in):
"""
Version 2: Using built-in methods.
Write a python function that returns the first index of a character 'c' in string
'str_in'.
If the character was not found it returns -1.
Ex:
findChIndex('a', 'dddabbb') will return 3
findChIndex('f', ... | bigcode/self-oss-instruct-sc2-concepts |
import copy
def plugin_init(config, ingest_ref, callback):
""" Initialise the plugin
Args:
config: JSON configuration document for the Filter plugin configuration category
ingest_ref: filter ingest reference
callback: filter callback
Returns:
data: JSON object t... | bigcode/self-oss-instruct-sc2-concepts |
def using_apt_get_on_parrotsec(line):
"""
Checks if your image uses parrotsec and uses apt-get.
This is discouraged - you should use apt instead.
"""
return "apt-get" in line | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
def apply_substitutions(command: str, substitutions: Dict[str, str]) -> str:
"""
Given a command string (with templates) and a substitution mapping, produce a
concrete command string that can be run in a shell.
Parameters
----------
command
A string to be execu... | bigcode/self-oss-instruct-sc2-concepts |
import math
def pi(var_lambda: float, gamma=1.4) -> float:
""""
Returns gas dynamic function pi
Parameters
----------
var_lambda: float
superficial velocity of flow
gamma: float
isentropic exponent (default 1.4)
Returns
-------
pi: float
values of GD funct... | bigcode/self-oss-instruct-sc2-concepts |
def get_versions(existings):
"""
Given gathered path, get all existing versions.
"""
versions = set()
for k, v in existings.items():
versions = versions.union(v)
return versions | bigcode/self-oss-instruct-sc2-concepts |
import operator
def format_as_results(sim_vec, topic_uid, doc_collection,
run_name='default_run'):
"""Formats a similarity vector as the TREC output.
The format of the system results contains 5 tab-separated
columns:
1. qid
2. iter
3. docno
4. rank
5. sim
6.... | bigcode/self-oss-instruct-sc2-concepts |
def entry_boundaries(entry):
"""
Get the start/end of an entry and order (start < end)
"""
start = entry.start
end = entry.stop
return start, end | bigcode/self-oss-instruct-sc2-concepts |
def linear_annealing(current_timestep, final_timestep, start_value, final_value):
"""
Linearly anneals a value from an initial value to a final value, given the current percentage.
"""
# Pô <3
percentage = min(1.0, current_timestep / final_timestep if final_timestep != 0 else 0)
current_eps = (f... | bigcode/self-oss-instruct-sc2-concepts |
def remove_subject(subject, metric, dict_exclude_subj):
"""
Check if subject should be removed
:param subject:
:param metric:
:param dict_exclude_subj: dictionary with subjects to exclude from analysis (due to bad data quality, etc.)
:return: Bool
"""
if metric in dict_exclude_subj.keys(... | bigcode/self-oss-instruct-sc2-concepts |
def flatten_binary_logits(logits, labels, ignore_index=None):
"""Flattens predictions in the batch (binary case) Remove labels equal to
'ignore_index'."""
logits = logits.view(-1)
labels = labels.view(-1)
if ignore_index is None:
return logits, labels
valid = (labels != ignore_index)
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
def safe_get_dict(data: Union[None, dict], key, default: dict) -> dict:
"""
This method is a safe getter function that returns a dict entry in case that the dict is provided and it contains
the key (where the value itself is a dict). Otherwise it returns the provided default value... | bigcode/self-oss-instruct-sc2-concepts |
def get_jid(log_name):
"""Strip path and file type from the log name to return the jid as int"""
return int(log_name.split('/')[-1].split('.')[0]) | bigcode/self-oss-instruct-sc2-concepts |
def get_bracket_depth(idx, left_bracket_indices, right_bracket_indices):
"""
Get the bracket depth of index idx.
Args:
idx (int): the index.
left_bracket_indices (list[int]): the left bracket index list.
right_bracket_indices (list[int]): the right bracket index list.
Returns:
... | bigcode/self-oss-instruct-sc2-concepts |
def epsilon_to_kappa(r_k, epsilon, delta=0.16):
"""Convert frequency r_k and strain epsilon
to corresponding r_k and kappa as consumed by
functions in `latticegeneration`.
Returns
-------
r_k2 : float
kappa : float
See also
--------
latticegeneration.generate_ks
"""
ret... | bigcode/self-oss-instruct-sc2-concepts |
def versions_match(versions):
"""Check if the versions are the same"""
base = None
for name in versions:
if base is None:
base = versions[name]
elif base != versions[name]:
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
def mk_optional_string(data, jfield):
"""
Returns either the string represented in a json structure, or an empty string if it's not present
:param data: json that may contain the jfield
:param jfield: the name of the field
:return if the field exists then it's returned; otherwise an empty string i... | bigcode/self-oss-instruct-sc2-concepts |
import re
import inspect
def get_source(match: re.Match) -> str:
"""Extract source code lines of a matched object and prepare them
to being injected into .ipynb code cell."""
match_object = eval(match.group()[9:-1])
source_lines = inspect.getsourcelines(match_object)[0]
new_lines = [line.rstrip() ... | bigcode/self-oss-instruct-sc2-concepts |
def call_behavior_action_input_pin(self, pin_name: str):
"""Find an input pin on the action with the specified name
:param pin_name:
:return: Pin with specified name
"""
pin_set = {x for x in self.inputs if x.name == pin_name}
if len(pin_set) == 0:
raise ValueError(f'Could not find inpu... | bigcode/self-oss-instruct-sc2-concepts |
def is_ipv4_address(addr):
"""Return True if addr is a valid IPv4 address, False otherwise."""
if (not isinstance(addr, str)) or (not addr) or addr.isspace():
return False
octets = addr.split('.')
if len(octets) != 4:
return False
for octet in octets:
if not octet.isdigit():
... | bigcode/self-oss-instruct-sc2-concepts |
def _sorted_data(lb_node_pairs):
"""
Return HTTP request body to be sent to RCv3 load_balancer_pools/nodes API
from list of (lb_id, node_id) tuples. The returned list is sorted to allow
easier testing with predictability.
:param list lb_node_pairs: List of (lb_id, node_id) tuples
:return: List ... | bigcode/self-oss-instruct-sc2-concepts |
def div_or_none(a,b):
"""Divide a by b. Return result or None on divide by zero."""
if b == 0:
return None
return a/b | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
def validate_state_of_charge_max(state_of_charge_max: Optional[float]) -> Optional[float]:
"""
Validates the state of charge max of an object.
State of charge max is always optional.
:param state_of_charge_max: The state of charge max of the object.
:return: The valida... | bigcode/self-oss-instruct-sc2-concepts |
def read_file(path=None) -> str:
"""
Function for reading the single file
:param path: path to the file
:return: data: data from the file
"""
if not path:
raise NameError('Required path to the file')
with open(path, 'r') as f:
data = f.read()
return data | bigcode/self-oss-instruct-sc2-concepts |
def timesheetentry_json(timesheetentry) -> dict:
""" Helper function to convert a TimeSheetEntry object into a json dict with nice date and time formatting """
data = {}
data['id'] = timesheetentry.id
data['project'] = timesheetentry.project.id
data['rse'] = timesheetentry.rse.id
data['date'] = ... | bigcode/self-oss-instruct-sc2-concepts |
def range_overlap(a, b):
"""
>>> range_overlap(("1", 30, 45), ("1", 45, 55))
True
>>> range_overlap(("1", 30, 45), ("1", 57, 68))
False
>>> range_overlap(("1", 30, 45), ("2", 42, 55))
False
"""
a_chr, a_min, a_max = a
b_chr, b_min, b_max = b
# must be on the same chromosome
... | bigcode/self-oss-instruct-sc2-concepts |
def scale(value, input_low, input_high, output_low, output_high):
"""Scale a value from one range to another"""
scaled_input = ((float(value) - input_low) / (input_high - input_low))
return ((scaled_input) * (output_high - output_low)) + output_low | bigcode/self-oss-instruct-sc2-concepts |
def get_group_usage(group, date, db):
"""
Query the database for group usage on a specific date.
:param group: str
:param date: str
:param db: object
:return usage: int
"""
terms = (group, date + '%',)
db.execute('SELECT * FROM `group_stats` WHERE `group` = ? AND `datetime` LIKE ?',... | bigcode/self-oss-instruct-sc2-concepts |
def iter_algorithm(d, n, p, corpus, pr):
"""
PR(p) = ( (1-d) / n ) + ( d * sum( PR(i) / NumLinks(i) ) )
i
d = dampening number; n = # of possible pages; p = page; i = incoming pages
"""
page_sum = 0
# This for loop will calcula... | bigcode/self-oss-instruct-sc2-concepts |
def has_attribute(ob, attribute):
"""
:func:`hasattr` swallows exceptions. :func:`has_attribute` tests a Python object for the
presence of an attribute.
:param ob:
object to inspect
:param attribute:
``str`` for the name of the attribute.
"""
return getattr(ob, attribute, No... | bigcode/self-oss-instruct-sc2-concepts |
def remove_stop_words(content, stopwords):
"""Removes the stopwords in an article.
:param tokens: The tokens of an article.
:type tokens: []str
:param stopwords: the list of stopwords
:type stopwords: []str
:return: The tokens of an article that are not stopwords.
:rtype: []str
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def defaultparamsfunc(curlag, sensdict, simparams):
"""
Just a pass through function.
"""
return(curlag, sensdict, simparams) | bigcode/self-oss-instruct-sc2-concepts |
def extract_fields(data, exclude=()):
"""Return a tuple of all fields in the DataFrames within *data*."""
features = set()
for station in data:
features = features | set(station['Data'].columns.tolist())
return sorted(list(features - set(exclude))) | bigcode/self-oss-instruct-sc2-concepts |
def spot_is_free(spot, candles, light):
"""
A spot is NOT free if the horizontal and vertical distance between
that and the light is less than the light strength
"""
for candle in candles:
x_dist = abs(candle[0] - spot[0])
y_dist = abs(candle[1] - spot[1])
if x_dist < light a... | bigcode/self-oss-instruct-sc2-concepts |
def _format_strings(the_string='', prefix='', suffix=''):
"""Small convenience function, allows easier logic in .format() calls"""
if the_string:
return '{0}{1}{2}'.format(prefix, the_string, suffix)
else:
return '' | bigcode/self-oss-instruct-sc2-concepts |
import torch
def extract_logits(out, task_ids, n_classes, device):
"""
Extract logits corresponding to task_ids from out.
Args:
out: Predictions
task_ids: Task ids
n_classes: Number of classes per task
"""
indices = (
(torch.arange(n_classes * out.size(0)) % n_clas... | bigcode/self-oss-instruct-sc2-concepts |
def task_flake8(output_file):
"""Run flake8 over the code base and benchmarks."""
opts = ''
if output_file:
opts += f'--output-file={output_file}'
return {
'actions': [f"flake8 {opts} scipy benchmarks/benchmarks"],
'doc': 'Lint scipy and benchmarks directory',
} | bigcode/self-oss-instruct-sc2-concepts |
def GetMachMsgOOLDescriptorSummary(desc):
""" Returns description for mach_msg_ool_descriptor_t * object
"""
format_string = "{: <#020x} {: <#020x} {: <#010x}"
out_string = format_string.format(desc, desc.address, desc.size)
return out_string | bigcode/self-oss-instruct-sc2-concepts |
def has_duplicates(t):
"""Returns True if any element appears more than once in a sequence.
t: list returns: bool
"""
s = t[:] # make a copy of t to avoid modifying the parameter
s.sort()
for i in range(len(s)-1):
if s[i] == s[i+1]: # check for adjacent eleme... | bigcode/self-oss-instruct-sc2-concepts |
def _tx_resource_for_name(name):
""" Return the Transifex resource name """
return "taiga-back.{}".format(name) | bigcode/self-oss-instruct-sc2-concepts |
import re
def remove_svg_dimensions(svg_data):
"""Remove explicit height and width attributes from an svg, if present."""
desired_index = 0
svg_lines = svg_data.split("\n")
for index, line in enumerate(svg_lines):
if "<svg" in line:
desired_index = index
break
line = svg_lines[desired_index]
line = re.... | bigcode/self-oss-instruct-sc2-concepts |
def make_collections_query(value, tag=None):
"""Creates sql and values to query database for collections."""
# init buffers
sqls = []
values = []
# init value
value_like = "%%%s%%" % value.lower()
# search by DBID
if tag == '[ID]':
sqls.append("(id = ?)""")
... | bigcode/self-oss-instruct-sc2-concepts |
def count_from_0(index, collection):
"""Numbering function: consecutive integers starting at 0."""
return index | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
import configparser
def lit_config(filenames: list[Path]) -> dict:
"""Lecture du fichier de configuration.
Args:
filenames: liste de répertoires où trouver le fichier de configuration.
Returns: dict créé à partir de la section 'paths',
contenant des répertoires e... | bigcode/self-oss-instruct-sc2-concepts |
def get_json_carts(response):
"""Get rendered cart's templates from JsonResponse."""
return response.json()['header'], response.json()['table'] | bigcode/self-oss-instruct-sc2-concepts |
def list_average(score_list):
"""
Utility function to get the average of a list.
Args:
score_list: List containing real numbers that must be averaged
Returns:
Float representing the average of the values in the provided list
"""
if len(score_list) == 0:
return -100
... | bigcode/self-oss-instruct-sc2-concepts |
def get_azs(region=''):
"""The intrinsic function Fn::GetAZs returns an array that lists all \
Availability Zones for the specified region.
Because customers have access to different Availability Zones, the
intrinsic function Fn::GetAZs enables template authors to write
templates that adapt to the ... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Iterator
def ascii_table(dictset: Iterator[dict], limit: int = 5):
"""
Render the dictset as a ASCII table.
NOTE:
This exhausts generators so is only recommended to be used on lists.
Parameters:
dictset: iterable of dictionaries
The dictset to render
... | bigcode/self-oss-instruct-sc2-concepts |
def item_version(item):
"""
Split the item and version based on sep ':'
"""
sep = ':'
count = item.count(sep)
if count == 0:
return item, None
elif count == 1:
return item.split(sep)
else:
msg = "Found multiple instances of '%s'" % sep
raise ValueError(msg... | bigcode/self-oss-instruct-sc2-concepts |
def bits_table_h() -> dict[int, int]:
"""The table of the maximum amount of information (bits) for the version H.
Returns:
dict[int, int]: Dictionary of the form {version: number of bits}
"""
table = {
1: 72, 2: 128, 3: 208, 4: 288, 5: 368, 6: 480, 7: 528, 8: 688, 9: 800,
10: 97... | bigcode/self-oss-instruct-sc2-concepts |
import json
def safe_json_load(in_str):
"""
safely load json strings as dictionaries
:param in_str: string with encoded json
:return: dict
>>> safe_json_load('{"bob": 5}')
{'bob': 5}
>>> safe_json_load('{"bob": [1,2,3]}')
{'bob': [1, 2, 3]}
>>> safe_json_load('{"bob": [1,2,3}')
... | bigcode/self-oss-instruct-sc2-concepts |
def pretty_dict(d, indent=0):
"""Pretty the output format of a dictionary.
Parameters
----------
d
dict, the input dictionary instance.
indent
int, indent level, non-negative.
Returns
-------
res
str, the output string
"""
res = ""
for k, v in d.item... | bigcode/self-oss-instruct-sc2-concepts |
def get_keyword(token):
"""If ``token`` is a keyword, return its lowercase name.
Otherwise return ``None``.
"""
if token.type == 'ident':
return token.lower_value | bigcode/self-oss-instruct-sc2-concepts |
def clean_full_uri(request):
"""Return the full URI without querystrings"""
return '%s://%s%s' % ('https' if request.is_secure() else 'http',
request.get_host(), request.path) | bigcode/self-oss-instruct-sc2-concepts |
def str_to_bool(string_in: str):
"""convert a string to boolean
Args:
string_in (string): Text from config file value
Raises:
ValueError: Cannot convert the string to a bool as it isn't True or False
Returns:
Boolean: True/False value
"""
if string_in.lower() == "true"... | bigcode/self-oss-instruct-sc2-concepts |
def find_twin(device_id, device_list):
"""
Locate the emulated twin of source device with identifier device_id.
Parameters
----------
device_id : str
Identifier of original device for which the twin is located.
device_list : list
List of device dictionaries in project fetched by... | bigcode/self-oss-instruct-sc2-concepts |
def countTokens(vendorRDD):
""" Count and return the number of tokens
Args:
vendorRDD (RDD of (recordId, tokenizedValue)): Pair tuple of record ID to tokenized output
Returns:
count: count of all tokens
"""
return vendorRDD.map(lambda x: len(x[1])).reduce(lambda a, b: a + b) | bigcode/self-oss-instruct-sc2-concepts |
import ctypes
def create_string_buffer(value, size=None):
"""Create a ctypes string buffer.
Converts any string to a bytes object before calling
ctypes.create_string_buffer().
Args:
value (object): value to pass to ctypes.create_string_buffer()
size (int, optional): sze to pass to ctypes.cre... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
from typing import MutableSequence
def aslist(thing: Any) -> MutableSequence[Any]:
"""Wrap any non-MutableSequence/list in a list."""
if isinstance(thing, MutableSequence):
return thing
return [thing] | bigcode/self-oss-instruct-sc2-concepts |
import multiprocessing
def _run_in_process(target, *args, **kwargs):
"""Runs target in process and returns its exitcode after 10s (None if still alive)."""
process = multiprocessing.Process(target=target, args=args, kwargs=kwargs)
process.daemon = True
try:
process.start()
# Do not nee... | bigcode/self-oss-instruct-sc2-concepts |
def total_after(integer_number):
"""Returns the total number of grains on the chess board for given number of squares.
See README file for how it is calculated.
The calculation is essentially a Geometric series where a=1, r=2 and the sum of such a series is given by
a(1-r**n)
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
import math
def logarithmic_utility(
utility_params_by_good_id: Dict[str, float],
quantities_by_good_id: Dict[str, int],
quantity_shift: int = 1,
) -> float:
"""
Compute agent's utility given her utility function params and a good bundle.
:param utility_params_by_good_... | bigcode/self-oss-instruct-sc2-concepts |
def receive_all(sock, n):
"""
Helper function to fully receive an arbitrary amount of data from a socket.
:param sock: Socket connection
:param n: Number of bytes to receive
:return: Received data
"""
data = b''
while len(data) < n:
packet = sock.recv(n - len(data))
if n... | bigcode/self-oss-instruct-sc2-concepts |
def get_dict_modes(dict):
"""Finds the keys of the modes of a dictionary
@param dict: A dictionary of the form {"key":#}
"""
highest_count = dict[max(dict)]
modes = []
for key in dict:
if dict[key] == highest_count:
modes.append(key)
return modes | bigcode/self-oss-instruct-sc2-concepts |
import requests
def fetch_ontologies(enhanced_keywords):
"""
Fetch the connected ontology for each enhanced keyword.
Parameters
----------
enhanced_keywords: list
List of enhanced keywords in string format
Returns
-------
A list of dictionaries. Each one containing the ontolo... | bigcode/self-oss-instruct-sc2-concepts |
def entity_key(entity):
"""
Generate a key for the given entity that is unique within the
project.
"""
key = entity.key or entity.string
return ":".join([entity.resource.path, key]) | bigcode/self-oss-instruct-sc2-concepts |
import re
def split_entries(text, split_expr):
"""Splits text into entries according to split expression"""
return re.split(split_expr, text)[1:] | bigcode/self-oss-instruct-sc2-concepts |
def custom_attention_masks(input_ids):
"""Creates attention mask for the given inputs"""
attention_masks = []
# For each sentence...
for sent in input_ids:
# Create the attention mask.
# - If a token ID is 0, then it's padding, set the mask to 0.
# - If a token ID is > 0, t... | bigcode/self-oss-instruct-sc2-concepts |
import binascii
def unhexlify(blob):
"""
Takes a hexlified script and turns it back into a string of Python code.
"""
lines = blob.split('\n')[1:]
output = []
for line in lines:
# Discard the address, length etc. and reverse the hexlification
output.append(binascii.unhexlify(li... | bigcode/self-oss-instruct-sc2-concepts |
def make_geotransform(x_len, y_len, origin):
"""
Build an array of affine transformation coefficients.
Parameters:
x_len (int or float): The length of a pixel along the x axis.
Generally, this will be a positive value.
y_len (int of float): The length of a pixel along the y axi... | bigcode/self-oss-instruct-sc2-concepts |
def splitblocks(lst, limit):
"""Split list lst in blocks of max. limit entries. Return list of blocks."""
res = []
start = 0
while start < len(lst):
res.append(lst[start:start + limit])
start += limit
return res | bigcode/self-oss-instruct-sc2-concepts |
def get_P_Elc_game_play(P_Elc_game_play_measured):
"""稼働時の消費電力を計算する
Parameters
----------
P_Elc_game_play_measured : float
稼働時の平均消費電力(実測値), W
Returns
----------
P_Elc_game_play : float
稼働時消費電力, W
"""
P_Elc_game_play = P_Elc_game_play_measured
... | bigcode/self-oss-instruct-sc2-concepts |
def _is_subrange(rng1, rng2):
"""Return True iff rng1 is wholly inside rng2"""
# Nonpolymers should have an empty range
if rng1 == (None, None) or rng2 == (None, None):
return rng1 == rng2
else:
return rng1[0] >= rng2[0] and rng1[1] <= rng2[1] | bigcode/self-oss-instruct-sc2-concepts |
def role_ids_for_account(dynamo_table, account_number):
"""
Get a list of all role IDs in a given account by querying the Dynamo secondary index 'account'
Args:
account_number (string)
Returns:
list: role ids in given account
"""
role_ids = set()
results = dynamo_table.que... | bigcode/self-oss-instruct-sc2-concepts |
def reconnect(device, **kwargs):
"""Reconnect an unreal device
Parameters
----------
device (UnrealDevice): an unreal device instance
kwargs (dict): keyword arguments
Returns
-------
bool: connection status
"""
result = device.reconnect(**kwargs)
return result | bigcode/self-oss-instruct-sc2-concepts |
import torch
def negative_sampling(batch, num_nodes, head_corrupt_prob, device='cpu'):
""" Samples negative examples in a batch of triples. Randomly corrupts either heads or tails."""
bs, ns, _ = batch.size()
# new entities to insert
corruptions = torch.randint(size=(bs * ns,),low=0, high=num_nodes, ... | bigcode/self-oss-instruct-sc2-concepts |
def lie_bracket(element_1, element_2):
"""
Unfolds a Lie bracket. It is assumed that the second element is homogeneous (the bracket grows to the left).
Returns a string encoding the result of unfolding: each addend is represented as a sequence of indeces (which
are separated by '.'), the addends are sep... | bigcode/self-oss-instruct-sc2-concepts |
def UsersInvolvedInTemplate(template):
"""Return a set of all user IDs referenced in the template."""
result = set(
template.admin_ids +
[fv.user_id for fv in template.field_values if fv.user_id])
if template.owner_id:
result.add(template.owner_id)
for av in template.approval_values:
result.upda... | bigcode/self-oss-instruct-sc2-concepts |
def ibmqx(index):
"""
Creates one of the IBM Quantum Experience coupling maps based on the index provided
Args:
index (integer between 2 and 5): specify which of the QX chips should be returned
Returns:
dict
{
"qubits" : the number of qubits in the coupling map
... | bigcode/self-oss-instruct-sc2-concepts |
import collections
def find_duplicate_basenames(paths):
"""Return a dict mapping duplicate basenames to their full paths."""
pathmap = collections.defaultdict(list)
for p in paths:
pathmap[p.name].append(p)
# Remove any entries that only have one item in their associated list
for name in l... | bigcode/self-oss-instruct-sc2-concepts |
def get_calendar(intent_message, default_calendar):
"""
Get the calendar from an intent.
This returns the default calendar if the intent doesn't have a calendar.
Parameter intent_message: the intent message
Parameter default_calendar: the default calendar
"""
# The user has specified a ca... | bigcode/self-oss-instruct-sc2-concepts |
def is_binary(data):
""" Return True if the input series (column of dataframe) is binary """
return len(data.squeeze().unique()) == 2 | bigcode/self-oss-instruct-sc2-concepts |
def job_id(conf):
# type: (dict) -> str
"""Get job id of a job specification
:param dict conf: job configuration object
:rtype: str
:return: job id
"""
return conf['id'] | bigcode/self-oss-instruct-sc2-concepts |
import random
def _generate_placeholder_string(x, default_placeholder="{}"):
"""Generate and return a string that does not appear in `x`."""
placeholder = default_placeholder
rng = random.Random(5)
while placeholder in x:
placeholder = placeholder + str(rng.randint(0, 9))
return placeholder | bigcode/self-oss-instruct-sc2-concepts |
import configparser
def configure(config_file='../docs/default_config.ini'):
"""
Reads a configuration (INI format) file that specifies the three working
directories for binary image files, as well as the preferred database
connection.
A configuration file should contain two sections:
1. A ... | bigcode/self-oss-instruct-sc2-concepts |
def approximates(ref_point, point, max_deviation):
"""Helper function to check if two points are the same within the specified deviation."""
x = ref_point[0] - max_deviation <= point[0] <= ref_point[0] + max_deviation
y = ref_point[1] - max_deviation <= point[1] <= ref_point[1] + max_deviation
... | 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.