seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def evaluate_velocity_at_bottom(layer, prop):
"""
Evaluate material properties at bottom of a velocity layer.
.. seealso:: :func:`evaluate_velocity_at_top`, :func:`evaluate_velocity_at`
:param layer: The velocity layer to use for evaluation.
:type layer: :class:`~numpy.ndarray`, dtype = :py:const:... | bigcode/self-oss-instruct-sc2-concepts |
def format_recursive(template, arguments):
"""
Performs str.format on the template in a recursive fashion iterating over
lists and dictionary values
>>> template = {
... 'a': 'Value {a}',
... 'b': {
... 'a': 'Value {a}',
... 'b': 'Value {b}',
... },
... 'c': ['Value {a}'... | bigcode/self-oss-instruct-sc2-concepts |
def _get_block_sizes(resnet_size):
"""The number of block layers used for the Resnet model varies according
to the size of the model. This helper grabs the layer set we want, throwing
an error if a non-standard size has been selected.
"""
choices = {
18: [2, 2, 2, 2],
34: [3, 4, 6, 3],
50: [... | bigcode/self-oss-instruct-sc2-concepts |
async def get_manifest(db, ref_id: str) -> dict:
"""
Generate a dict of otu document version numbers keyed by the document id. This is used to make sure only changes
made at the time the index rebuild was started are included in the build.
:param db: the application database client
:param ref_id: t... | bigcode/self-oss-instruct-sc2-concepts |
def get_active_web_certificate(course, is_preview_mode=None):
"""
Retrieves the active web certificate configuration for the specified course
"""
certificates = getattr(course, 'certificates', {})
configurations = certificates.get('certificates', [])
for config in configurations:
if conf... | bigcode/self-oss-instruct-sc2-concepts |
import ctypes
def struct_pack(structure):
"""
Pack a :py:class:`ctypes.Structure` object and convert it to a packed string.
:param structure: The structure instance to convert
:type structure: :py:class:`ctypes.Structure`
:return: The structure instance converted to a string.
:rtype: str
"""
return ctypes.st... | bigcode/self-oss-instruct-sc2-concepts |
def fivePercent(distances, percentage = 0.05):
"""
Calculates the cutoff by which a distance is considered close.
Arguments:
distances -- A dictionary with the distances as keys and their frequency as values
Keyword arguments:
percentage -- Float where the cutoff should be (i.e. 0.05 for the closest 5 percent o... | bigcode/self-oss-instruct-sc2-concepts |
import time
def date_to_timestamp(date):
"""
Converts a date, format 2020-01-23
to a timestamp, format 12322342
"""
return time.mktime(time.strptime(date, "%Y-%m-%d")) | bigcode/self-oss-instruct-sc2-concepts |
def get_corner_points(contour):
"""
Get all corner points of the hexagonal target.
Returns a list of 8 points, starting with the top left and going clockwise.
"""
# First actually convert to points
points = [point[0] for point in contour]
# Find the top left point
# This should be the l... | bigcode/self-oss-instruct-sc2-concepts |
import functools
def delegate_manager(method):
"""
Delegate method calls to base manager, if exists.
"""
@functools.wraps(method)
def wrapped(self, *args, **kwargs):
if self._base_manager:
return getattr(self._base_manager, method.__name__)(*args, **kwargs)
return metho... | bigcode/self-oss-instruct-sc2-concepts |
def get_values(data, attribute):
"""gets all values from data[attribute] where data is a Pandas DataFrame
>>> data = pd.read_csv('./datasets/credit.csv', delimiter = ',')
>>> get_values(data, 'Housing')
array(['own', 'free', 'rent'], dtype=object)
"""
return data[attribute].unique() | bigcode/self-oss-instruct-sc2-concepts |
import re
def tokenize_by_sentence(text: str) -> tuple:
"""
Splits a text into sentences, sentences into tokens, tokens into letters
Tokens are framed with '_'
:param text: a text
:return: a tuple of sentence with tuples of tokens split into letters
e.g.
text = 'She is happy. He is happy.'... | bigcode/self-oss-instruct-sc2-concepts |
def list_api_revision(client, resource_group_name, service_name, api_id):
"""Lists all revisions of an API."""
return client.api_revision.list_by_service(resource_group_name, service_name, api_id) | bigcode/self-oss-instruct-sc2-concepts |
def convertTypes(value):
"""Helper to convert the type into float or int.
Args:
value(str): The value that will be converted to float or int.
Returns:
The converted value.
"""
value = value.strip()
try:
return float(value) if '.' in value else int(value)
except... | bigcode/self-oss-instruct-sc2-concepts |
def collect_expected(dataset):
""" Peel of the target values from the dataset """
expected = []
for sample in dataset:
expected.append(sample[0])
return expected | bigcode/self-oss-instruct-sc2-concepts |
def get_perfdata(label, value, uom, warn, crit, min, max):
"""Returns 'label'=value[UOM];[warn];[crit];[min];[max]
"""
msg = "'{}'={}".format(label, value)
if uom is not None:
msg += uom
msg += ';'
if warn is not None:
msg += str(warn)
msg += ';'
if crit is not None:
... | bigcode/self-oss-instruct-sc2-concepts |
def minmax(array):
"""Find both min and max value of arr in one pass"""
minval = maxval = array[0]
for e in array[1:]:
if e < minval:
minval = e
if e > maxval:
maxval = e
return minval, maxval | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def valida_data(data: str) -> bool:
"""Valida a data de uma requisição
Args:
data (str): 2022-01-19
Returns:
True: Se a data corresponder ao formato yyyy-mm-dd
False: Se a data não corresponder ao formato yyyy-mm-dd
"""
try:
datetime.... | bigcode/self-oss-instruct-sc2-concepts |
def prefixify(d: dict, p: str):
"""Create dictionary with same values but with each key prefixed by `{p}_`."""
return {f'{p}_{k}': v for (k, v) in d.items()} | bigcode/self-oss-instruct-sc2-concepts |
import torch
def is_long_tensor(tensor: torch.Tensor) -> bool:
"""
Returns True if a tensor is a long tensor.
"""
if torch.is_tensor(tensor):
return tensor.type().endswith("LongTensor")
else:
return False | bigcode/self-oss-instruct-sc2-concepts |
def _as_friendly_string(s):
"""Converts a bytestring to a text string.
To avoid encoding errors caused by arbitrary high characters (allowed in
PICO-8 source), this replaces all high characters with underscores.
Args:
s: The bytestring.
Returns:
The text string with high character... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def build_classifier_confidence(input_channels: int) -> torch.nn.Sequential:
"""
Create sequential module for classifier confidence score.
:param input_channels: Number of input activation maps.
:return: Sequential module.
"""
return torch.nn.Sequential(
torch.nn.Linear(i... | bigcode/self-oss-instruct-sc2-concepts |
def get_bitstream_type(field, db_object):
"""Retrieves the bitstream type from the device image object"""
device_image = getattr(db_object, 'image', None)
if device_image:
return device_image.bitstream_type
return None | bigcode/self-oss-instruct-sc2-concepts |
def startswith(x, lst):
""" Select longest prefix that matches x from provided list(lst)
:param x: input string
:param lst: prefixes to compare with
:return: longest prefix that matches input string if available otherwise None
"""
longest_prefix = None
for prefix in lst:
if x.starts... | bigcode/self-oss-instruct-sc2-concepts |
def bytes_to_str(value):
"""Return UTF-8 formatted string from bytes object."""
return bytes(value).decode('UTF-8') | bigcode/self-oss-instruct-sc2-concepts |
def convert(ruta):
"""Función para convertir una lista a string con las posiciones de la ruta
separadas por '-'
Args:
ruta: Una lista con las posiciones de la ruta
Returns:
ruta_c: Un string con las posiciones de la ruta separadas por '-'
"""
s = [str(i) for i in ruta]
rut... | bigcode/self-oss-instruct-sc2-concepts |
import functools
def rgetattr(obj, attr, *args):
"""Get chained properties.
Usage
-----
>>> class Pet:
def __init__(self):
self.favorite_color = "orange"
>>> class Person:
def __init__(self):
self.pet = Pet()
>>> p = Person()
>>> rge... | bigcode/self-oss-instruct-sc2-concepts |
def same_entries(a, b):
""" checks if entries a and b represent the same publication """
for key in ['ID', 'doi', 'hal_id', 'title', 'chapter']:
if key in a and key in b and a[key].lower() == b[key].lower():
return True
if 'title' in a and 'chapter' in b and a['title'].lower() == b['chap... | bigcode/self-oss-instruct-sc2-concepts |
def create_technologies(connector, technology_list):
"""
Creates the ``technologies`` table in Temoa.
Parameters
----------
connector : sqlite connector
The connection to an sqlite database
technology_list : list of ``Technology`` objects
All of the technologies initialized in ... | bigcode/self-oss-instruct-sc2-concepts |
def get_security_args(security, d):
"""
Returns the parameters in d that are prepended with the string in security.
"""
ud = {}
for key in d:
if security + '_' in key:
if key.startswith(security + '_'):
ukey = key.replace(security + '_', '')
ud[uke... | bigcode/self-oss-instruct-sc2-concepts |
def vaporViscosity(T, vVP):
"""
vaporViscosity(T, vVP)
vaporViscosity (micropoise) = A + B*T + C*T^2
Parameters
T, temperature in Kelvin
vVP, A=vVP[0], B=vVP[1], C=vVP[2]
A, B, and C are regression coefficients
Returns
vapor viscosity in micropoise at T
"""
r... | bigcode/self-oss-instruct-sc2-concepts |
def bubble_sort(arr):
"""
My Python implementation of bubble sort
Sorts a list of numbers and returns the sorted list
Time complexity: O(n^2)
Space complexity: O(1)
"""
# One iteration for each element
for i in range(len(arr)):
# One pass through list for
for j in ran... | bigcode/self-oss-instruct-sc2-concepts |
import mimetypes
def guess_mime_type(filepath):
"""Guess the MIME type for the given file path. If no reasonable guess can
be determined, `application/octet-stream` is returned.
Args:
filepath: path to the file
Returns:
the MIME type string
"""
return mimetypes.guess_type(fil... | bigcode/self-oss-instruct-sc2-concepts |
from pydantic import BaseModel # noqa: E0611
from typing import Any
def diff_models(from_: BaseModel, to_: BaseModel) -> dict[str, Any]:
"""
Return a dict with differences of the second in relation to the first model.
Useful for getting only the fields that have changed before an update,
for example.... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
import torch
def mask_from_lens(lens, max_len: Optional[int] = None):
"""Return an element-wise boolean mask of length less that `max_len`.
Args:
lens ([type]): [description]
max_len (Optional[int]): max length. Defaults to None.
Returns:
tensor:
"... | bigcode/self-oss-instruct-sc2-concepts |
def check_args(argv):
"""
Validates `main()` input arguments
:param argv: program arguments
:return: True/False
"""
if len(argv) != 3:
print("Github login and password are expected as script parameters")
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
def time_to_str(sec):
"""Convert seconds to days, hours, minutes and seconds."""
days, remainder = divmod(sec, 60 * 60 * 24)
hours, remainder = divmod(remainder, 60 * 60)
minutes, seconds = divmod(remainder, 60)
_str = ""
if days > 0:
_str += "{:d} days, ".format(int(days))
if hours ... | bigcode/self-oss-instruct-sc2-concepts |
def filedate(filename):
"""Extract the date from the filename"""
return filename[1:9] | bigcode/self-oss-instruct-sc2-concepts |
def read_emb(src_path: str, trg_path: str, pass_header: bool=True, top_tokens: int=50_000):
"""
Read tokens of word2vec style embeddings to List[str].
:param src_path str: path to word2vec-style source language embeddings
:param trg_path str: path to word2vec-style target language embeddings
:param... | bigcode/self-oss-instruct-sc2-concepts |
def standardize(x):
"""
Standardizes a Series or DataFrame.
"""
return (x - x.mean()) / x.std() | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def sanitize(output):
"""Sanitize a dictionary or a list of dictionaries as follows:
* remove 'tel:+'/'alias:' prefixes from 'to'/'from'/'address' keys' values
* add 'obfuscated' key when 'from' key is present
* convert 'timestamp' keys' values to datetime obje... | bigcode/self-oss-instruct-sc2-concepts |
def hex2rgb(color):
"""Turns a "#RRGGBB" hexadecimal color representation into a (R, G, B)
tuple.
Arguments:
color -- str
Return: tuple
"""
code = color[1:]
if not (len(color) == 7 and color[0] == "#" and code.isalnum()):
raise ValueError('"%s" is not a valid color' % color... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
def build_trial_facets(trial_file_counts: Dict[str, int]):
"""
Convert a mapping from trial ids to file counts into a list of facet specifications.
"""
return [
{"label": trial_id, "count": count}
for trial_id, count in trial_file_counts.items()
] | bigcode/self-oss-instruct-sc2-concepts |
def XmlDataTable_to_XmlFile(xml_data_table,file_name="test.xml"):
"""Converts the XMLModel DataTable to a file on disk using the save method"""
xml_data_table.save(file_name)
return file_name | bigcode/self-oss-instruct-sc2-concepts |
def set_default_attr(obj, name, value):
"""Set the `name` attribute of `obj` to `value` if the attribute does not already exist
Parameters
----------
obj: Object
Object whose `name` attribute will be returned (after setting it to `value`, if necessary)
name: String
Name of the attri... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
def get_next_branch_state(branch_symbol: str, state: int) -> Tuple[int, int]:
"""Enforces the grammar rules for SELFIES Branch symbols.
Given the branch symbol and current derivation state, retrieves
the initial branch derivation state (i.e. the derivation state that the
new ... | bigcode/self-oss-instruct-sc2-concepts |
def A_approx_deph(Qload_deph, deltaT_diff_deph, Kt_approx):
"""
Calculates the approximate heatransfer area.
Parameters
----------
Qload_deph : float
The heat load of dephlegmator, [W] , [J/s]
deltaT_diff_deph : float
The coefficient difference of temperatures, [C]
Kt_approx ... | bigcode/self-oss-instruct-sc2-concepts |
def update_dict_using_dict(dict1, dict2, operator):
"""
Updates the elements of dict1 with the elements of dict2 using the given operator.
Returns a
Args:
dict1 (dict): Dictionary.
dict2 (dict): Dictionary.
operator (function): Can use the operator module to get basic operators... | bigcode/self-oss-instruct-sc2-concepts |
import requests
import json
def get_push_shift_data(query, after, before, sub):
"""
Gets comments for a given keyword between two dates for a single subreddit
up to a limit of 1000
Args:
- query: keyword to search for
- after: start search date as a unix timestamp
... | bigcode/self-oss-instruct-sc2-concepts |
def _report_error(info):
""" Interprets the return code of the odr routine.
Parameters
----------
info : int
The return code of the odr routine.
Returns
-------
problems : list(str)
A list of messages about why the odr() routine stopped.
"""
stopreason = ('Blank',
... | bigcode/self-oss-instruct-sc2-concepts |
def cs_to_ms(cs):
"""Convert Centisecods to Milliseconds"""
return cs * 10 | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_life_range(source):
"""
Return the birth and death year from _source (as a tuple).
Return empty strings if not available.
"""
years = []
for event in ["from", "to"]:
if source["lifespan"].get(event):
date = source["lifespan"][event].get("date", "")
... | bigcode/self-oss-instruct-sc2-concepts |
def reverse_and_add(n):
"""Returns n + reversed(n)."""
return n + int(str(n)[::-1]) | bigcode/self-oss-instruct-sc2-concepts |
def one(s):
"""Get one element of a set"""
return next(iter(s)) | bigcode/self-oss-instruct-sc2-concepts |
def boxes_to_geojson(boxes, class_ids, crs_transformer, class_map,
scores=None):
"""Convert boxes and associated data into a GeoJSON dict.
Args:
boxes: list of Box in pixel row/col format.
class_ids: list of int (one for each box)
crs_transformer: CRSTransformer use... | bigcode/self-oss-instruct-sc2-concepts |
def perturb(x, prn):
"""
Randomly perturb an integer point.
Parameters
----------
x : tuple of int
Point to be perturbed
prn : prng.MRG32k3a object
Returns
-------
tuple of float
The perturbed point
"""
q = len(x)
return tuple(x[i] + 0.3*(prn.random() - ... | bigcode/self-oss-instruct-sc2-concepts |
import re
def generate_content_type(type, version=2):
"""
Generate the Content-Type header, including a version number
Content-Types look like: application/vnd.ozp-iwc+json;version=1
"""
try:
version = re.findall(r'version=(\d+)', type)[0]
# version number found already - just use... | bigcode/self-oss-instruct-sc2-concepts |
def LogFiles(log_prefix):
"""Determines the filenames for the instmake log and the make output log
by using an arbitrary prefix. Returns a tuple of the two filenames
(instmake_log, make_log)."""
imlog = log_prefix + ".imlog"
mklog = log_prefix + ".make.out"
return (imlog, mklog) | bigcode/self-oss-instruct-sc2-concepts |
def mapVal(inputPos, in_min, in_max, out_min, out_max):
""" This function will linearly scale an incoming value
belonging to a certain range (in_max - in_min) to a new
value in the out range (out_max - out_min). """
scale = ((out_max - out_min) / (in_max - in_min))
return float(((in... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
import re
from typing import Dict
def find_latest_xml_file(dir_name: Path) -> Path:
"""
Find the latest timestamped xml files, with un-timestamped files as a fallback if no timestamped file is found
:raise FileNotFoundError: if either file can't be found
"""
name_pattern ... | bigcode/self-oss-instruct-sc2-concepts |
def translate(text, conversion_dict, before=lambda _: _):
""" Translate words from a text using a conversion dictionary
@brief text The text to be translated
@brief conversion_dict The conversion dictionary
@brief before A function to transform the input
"""
# if empty:
if not text: return ... | bigcode/self-oss-instruct-sc2-concepts |
def prune_by_tum_detect(iqms):
"""Prunes to only contain IQMs for imgs with identifiable tumour
Parameters
----------
iqms : dict
The dict of IQMs for one beamformer
Returns
-------
pruned_iqms : dict
The dict of the IQMs for all images which had an identifiable
tum... | bigcode/self-oss-instruct-sc2-concepts |
import logging
from datetime import datetime
def log_time(target, message, log_method=None, target_args=None, target_kwargs=None):
"""Execute target and log the start/elapsed time before and after execution"""
logger = logging.info
if log_method is not None:
logger = log_method
start_time = datetime.now()
lo... | bigcode/self-oss-instruct-sc2-concepts |
def lowercase_f(x):
"""
Returns all strings in a Pandas Series `x` in lowercase.
"""
return x.str.lower() | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
def invert_results_dict(
results: dict[str, dict[str, dict[str, dict[str, list]]]]
) -> list[dict[str, Any]]:
"""
Flatten the results nested dictionary into a CSV-writable format.
Results has the following nested structure as input:
dict[directory, dict[trial, dict[cut, dict... | bigcode/self-oss-instruct-sc2-concepts |
def _construct_grounding_map(rows):
"""Construct grounding map from rows in a grounding_map csv file
Parameters
----------
rows : list
List of rows from a grounding map csv file. File should contain seven
columns, the first of which is an agent text. The remaining columns
contai... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
def get_next_id(current_id: int, size: int, total: int) -> Optional[int]:
"""Get next id.
Assumes a simple list.
Args:
current_id: Current element index.
size: Size of a page.
total: Total elements.
Returns:
``None``, if there is no next p... | bigcode/self-oss-instruct-sc2-concepts |
def _parse_offset_limit(request):
"""Parse offset and limit values from a given Flask request and return
a tuple containing both.
"""
offset = request.args.get("offset", default=0, type=int)
limit = request.args.get("limit", default=None, type=int)
if limit is not None:
limit = offset + ... | bigcode/self-oss-instruct-sc2-concepts |
def location(self) -> str:
"""Get the raw location inside the document
:returns: The location inside the document
"""
return self.url.split("#")[1] | bigcode/self-oss-instruct-sc2-concepts |
def ucfirst(string):
"""
Convert the first character of a string to uppercase.
"""
return string[:1].upper() + string[1:] | bigcode/self-oss-instruct-sc2-concepts |
import csv
def read_lun_file(filename):
"""Read lun csv file and return the list."""
lunlist = []
with open(filename, 'r') as cvsfile:
filereader = csv.reader(cvsfile, delimiter=',')
for row in filereader:
lunlist.append(row)
del lunlist[0]
return lunlist | bigcode/self-oss-instruct-sc2-concepts |
def IC_NIS(ic_cc, ic_ca, ic_pp, ic_pa, p_nis_a, p_nis_c):
"""
Calculates the predicted binding affinity value
based on the IC-NIS model.
"""
return -0.09459*ic_cc + -0.10007*ic_ca + 0.19577*ic_pp + -0.22671*ic_pa \
+ 0.18681*p_nis_a + 0.13810*p_nis_c + -15.9433 | bigcode/self-oss-instruct-sc2-concepts |
import re
def omitCommas(row):
"""
Locates data parts with double quotes and removes commas within them.
Parameters:
row (str): The csv string to be searched for double quotes.
Returns:
(str): The same string without double quotes and extra commas.
"""
cases = re.findall('"[^"]+"', row)
replaced = [re.... | bigcode/self-oss-instruct-sc2-concepts |
def d8n_get_all_images_topic_bag(bag):
"""
Returns the (name, type) of all topics that look like images.
"""
tat = bag.get_type_and_topic_info()
consider_images = [
'sensor_msgs/Image',
'sensor_msgs/CompressedImage',
]
all_types = set()
found = []
topics = tat.t... | bigcode/self-oss-instruct-sc2-concepts |
def get_window_content(center, whole_context, windows_size):
"""given whole context, center then return window's content in range windows_size by character
Args:
center(str): center word
whole_context(str): whole context
windows_size(int): window size
Returns:
list: window'... | bigcode/self-oss-instruct-sc2-concepts |
import re
def sanitize_filename(filename, allow_spaces=False):
"""Strips invalid characters from a filename.
Considers `POSIX "fully portable filenames"
<http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_282>`__
valid. These include:
A-Z a-z 0-9 ._-
Filename... | bigcode/self-oss-instruct-sc2-concepts |
def get_zip_filename(book_id):
""" Get the filename for a zip document with the book identifier. """
return book_id + ".zip" | bigcode/self-oss-instruct-sc2-concepts |
def eta1_Vargaftik_and_Yargin(TK):
"""Dynamic viscosity of Li monomers
Dynamic viscosity of the monomers as a function of temperature.
Parameters
----------
TK
K, temperature
Returns
-------
η, Pa s
References
----------
Vargaftik, N B, and V S Yargin.
Ch 7.4:... | bigcode/self-oss-instruct-sc2-concepts |
def composeMap(fun1, fun2, l):
"""
Returns a new list r where each element in r is fun2(fun1(i)) for the
corresponding element i in l
:param fun1: function
:param fun2: function
:param l: list
:return: list
"""
# Fill in
new = []
for i in l:
t = fun2(fun1(i))
... | bigcode/self-oss-instruct-sc2-concepts |
def indented(text, level, indent=2):
"""Take a multiline text and indent it as a block"""
return "\n".join("%s%s" % (level * indent * " ", s) for s in text.splitlines()) | bigcode/self-oss-instruct-sc2-concepts |
def _test_data(**overrides):
"""Returns a valid set of test data to use during API integration tests
overrides allows the caller to replace one or more items in the returned
dictionary without having to specify the entire thing every time.
"""
test_data = {
'sender': 'someemail@somedomain.c... | bigcode/self-oss-instruct-sc2-concepts |
def list_to_dict(l):
"""Turn a l of tuples into a dictionary."""
return {k: v for v, k in l} | bigcode/self-oss-instruct-sc2-concepts |
def make_range_partition(min_val, max_val):
"""
Returns a new partitioning function that partitions keys in the range
*[min_val:max_val]* into equal sized partitions.
The number of partitions is defined by the *partitions* parameter
"""
r = max_val - min_val
f = "lambda k, n, p: int(round(f... | bigcode/self-oss-instruct-sc2-concepts |
def load_alist(path):
"""Read `alist`-file [MacKay]_ and return nested list describing the
parity-check matrix of a code.
Many code examples can be found in [UniKL]_.
Input
-----
path:str
Path to file to be loaded.
Output
------
alist: list
A nested list containing... | bigcode/self-oss-instruct-sc2-concepts |
def CreateLocalSsdMessage(resources, messages, device_name, interface,
zone=None):
"""Create a message representing a local ssd."""
if zone:
disk_type_ref = resources.Parse('local-ssd',
collection='compute.diskTypes',
... | bigcode/self-oss-instruct-sc2-concepts |
def get_fixture_value(request, name):
"""Get the given fixture from the pytest request object.
getfuncargvalue() is deprecated in pytest 3.0, so we need to use
getfixturevalue() there.
"""
try:
getfixturevalue = request.getfixturevalue
except AttributeError:
getfixturevalue = re... | bigcode/self-oss-instruct-sc2-concepts |
def hex_to_rgb(color):
"""Convert the color from HEX coordinates to RGB coordinates."""
color = color.lstrip('#')
size = 1 if len(color) == 3 else 2
factor = 2 if len(color) == 3 else 1
return tuple(int(color[i * size:i * size + size] * factor, 16) for i in range(3)) | bigcode/self-oss-instruct-sc2-concepts |
def perc_unaligned(n_items, n_aligned, n_targs, **kwargs):
"""
Calculates the percent of items that are unaligned
Args:
n_items: ndarray (same dims as n_targs)
n_aligned: ndarray (same dims as n_targs)
n_targs: ndarray (same dims as n_items)
Returns:
perc: float
... | bigcode/self-oss-instruct-sc2-concepts |
import pickle
def load_data(file):
"""Load (preprocessed) data from file."""
with open(file, 'rb') as dr:
X = pickle.load(dr)
gene_names = pickle.load(dr)
return X, gene_names | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
from typing import List
import re
import itertools
def get_expanded_article_pages(page_ref: Optional[str]) -> List[int]:
"""['p. D-D', 'p. D', 'p. D, D ', 'p. D, D-D ', 'p.D-D', 'p.D',
'p. D-D, D ', 'page D', 'p., D-D', 'p. D-D, D-D ']"""
if page_ref is None:
return []... | bigcode/self-oss-instruct-sc2-concepts |
def norm_grid_description(grid_desc):
"""Normalize a grid description into a canonical form.
Examples
--------
>>> from landlab.grid.create import norm_grid_description
>>> grid_desc = [
... (3, 4), {"xy_spacing": 4.0, "xy_of_lower_left": (1.0, 2.0)}
... ]
>>> normed_items = list(n... | bigcode/self-oss-instruct-sc2-concepts |
def remove_label(sentence):
"""
Input: A sentence picked out from the dataset with the label at the end.
Output: A tuple (sentence, label)
"""
return (sentence.strip()[: -1].strip(), sentence.strip()[-1]) | bigcode/self-oss-instruct-sc2-concepts |
import logging
import random
def load_apprentice_persona_list(personas_fpath: str, shuffle: bool):
"""
Reads a list of curated apprentice personas.
"""
logging.info('Loading personas.')
with open(personas_fpath, 'r') as pf:
personas = [p.strip() for p in pf if p.strip()]
logging.info(f... | bigcode/self-oss-instruct-sc2-concepts |
def layout_one(title):
"""Formating layout for plotly visualization graph containing multiple variables of one company
Args:
title of graph
Returns:
layout configuration
"""
layout = dict(title = title,
legend = dict(
orientation = 'h',
x = -0.01,
... | bigcode/self-oss-instruct-sc2-concepts |
import ast
def replace_fields(node, **kwds):
"""
Return a node with several of its fields replaced by the given values.
"""
new_kwds = dict(ast.iter_fields(node))
for key, value in kwds.items():
if value is not new_kwds[key]:
break
else:
return node
new_kwds.upd... | bigcode/self-oss-instruct-sc2-concepts |
def lookup(obj, *path):
"""Lookups repeatedly the items in the list `path` of the object `obj`. In
case any `IndexError` or `KeyError` is thrown, `None` is returned. For
example the call `safe_lookup(obj, "a", 0, "b")` returns
`obj["a"][0]["b"]` when it exists and `None` otherwise."""
try:
r... | bigcode/self-oss-instruct-sc2-concepts |
def stripnl(s):
"""remove newlines from a string (and remove extra whitespace)"""
s = str(s).replace("\n", " ")
return ' '.join(s.split()) | bigcode/self-oss-instruct-sc2-concepts |
def mod_12(any_int):
"""
Returns the value of the input modulo 12
Params:
* any_int (int): any integer
Returns:
* the integer modulo 12
"""
return any_int % 12 | bigcode/self-oss-instruct-sc2-concepts |
def map_color(text, key='fontcolor'):
"""Map the text to a color.
The text is mapped to a color.
:param text: string of text to be mapped to a color. 'error' and
'fail' in the text will map to 'red'.
:param key: in returned dictionary, the key to use that corresponds to
... | bigcode/self-oss-instruct-sc2-concepts |
def compute_cumulants(moments):
"""
Compute the cumulants from the moments up to order 4
"""
assert len(moments) >= 4, "You must have moments at least up to order 4."
kappas = [0] * 4
kappas[0] = moments[0]
kappas[1] = moments[1] - moments[0] ** 2
kappas[2] = moments[2] - 3 * moments[1]... | 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.