seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
import functools
import operator
def compute_check(msg):
""" Compute the check value for a message
AUCTUS messages use a check byte which is simply the XOR of all
the values of the message.
"""
if len(msg) == 0:
return 0
return functools.reduce(operator.xor, msg) | bigcode/self-oss-instruct-sc2-concepts |
def trivium_annexum_numerordinatio_locali(
trivium: str) -> str:
"""trivium_annexum_numerordinatio_locali
Args:
trivium (str): /Path to file/@eng-Latn
de_codex (str): /Numerordinatio/@eng-Latn
Returns:
str: numerordinatio_locali
Exemplōrum gratiā (et Python doctest, id... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Dict
def can_sum(target_sum: int, nums: List, memo: Dict = {}) -> bool:
"""
:param target_sum: non negative target sum
:param nums: List of non negative numbers
:param memo: memoization i.e. hash map to store intermediate computation results
:return: Bool... | bigcode/self-oss-instruct-sc2-concepts |
import requests
def create_private_contribution(username="",password=""):
"""
Create a private contribution on earthref.org/MagIC.
Parameters
----------
username : str
personal username for MagIC
password : str
password for username
Returns
---------
response: API... | bigcode/self-oss-instruct-sc2-concepts |
def _get_bbox(gdf):
"""Get tuple bounding box (total bounds) from GeoDataFrame"""
xmin, ymin, xmax, ymax = gdf.total_bounds
return (xmin, ymin, xmax, ymax) | bigcode/self-oss-instruct-sc2-concepts |
def parse_dnsstamp_address(address, default_port=None):
"""
Parses an address from a DNS stamp according to the specification:
- unwraps IPv6 addresses from the enclosing brackets
- separates address string into IP(v4/v6) address and port number,
if specified in the stamp address
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def mod_family_accession(family_accession):
"""Reduces family accession to everything prior to '.'."""
return family_accession[:family_accession.index('.')] | bigcode/self-oss-instruct-sc2-concepts |
from typing import Callable
def is_hiqed(fun: Callable, fun_name: str) -> bool:
"""check if this function has been registered in HiQ system
The function could be one of:
full_qualified_name="<method 'read' of '_io.TextIOWrapper' objects>", fun_name='read'
full_qualified_name='<function main... | bigcode/self-oss-instruct-sc2-concepts |
def unique(seq):
"""Remove duplicate elements from seq. Assumes hashable elements.
Ex: unique([1, 2, 3, 2, 1]) ==> [1, 2, 3] # order may vary"""
return list(set(seq)) | bigcode/self-oss-instruct-sc2-concepts |
def join_base_url_and_query_string(base_url: str, query_string: str) -> str:
"""Joins a query string to a base URL.
Parameters
----------
base_url: str
The URL to which the query string is to be attached to.
query_string: str
A valid query string.
Returns
-------
str
... | bigcode/self-oss-instruct-sc2-concepts |
def get_empirical_tput(tbs, ttime):
"""
Returns the empirical throughput
:param tbs: total bytes sent for each flow as a dict
:param ttime: total time for a session for each flow as a dict
:return: a dict type containing all flow ids with their emp throughputs
"""
etput = {}
for l in tbs... | bigcode/self-oss-instruct-sc2-concepts |
import re
def xml_get_tag(xml, tag, parent_tag=None, multi_line=False):
"""
Returns the tag data for the first instance of the named tag, or for all instances if multi is true.
If a parent tag is specified, then that will be required before the tag.
"""
expr_str = '[<:]' + tag + '.*?>(?P<matched_t... | bigcode/self-oss-instruct-sc2-concepts |
import re
def remove_from_polymer(polymer, unit):
"""Remove all occurrences of unit, regardless of polarity from polymer."""
regex = f'{unit}'
return re.sub(regex, '', polymer, flags=re.IGNORECASE) | bigcode/self-oss-instruct-sc2-concepts |
def greatest_increase_or_decrease_in_profits(change_in_profits_and_losses_list, increase_or_decrease, key_1, key_2):
"""Determine the greatest increase or decrease in profits (date and amount) over the entire period.
Args:
change_in_profits_and_losses_list (dict): Changes in profits and losses containi... | bigcode/self-oss-instruct-sc2-concepts |
def test_model(model, test_data):
"""
Run predictions.
Args:
model: Trained model.
test_data: Test dataset.
Returns:
List of NumPy arrays containing predictions.
"""
return model.predict(test_data.dataset.data, num_iteration=model.best_iteration) | bigcode/self-oss-instruct-sc2-concepts |
def userspec_from_params(user, password):
"""Given username and password, return a dict containing them."""
return dict(
username=user,
password=password,
) | bigcode/self-oss-instruct-sc2-concepts |
def argmax(seq, func):
""" Return an element with highest func(seq[i]) score; tie
goes to first one.
>>> argmax(['one', 'to', 'three'], len)
'three'
"""
return max(seq, key=func) | bigcode/self-oss-instruct-sc2-concepts |
def get_input_size(dataset_name):
"""
Returns the size of input
"""
dataset_name = dataset_name.lower()
mapping = {
'mnist': 28 * 28,
'adult': 6,
'pums': 4,
'power': 8
}
if dataset_name not in mapping:
err_msg = f"Unknown dataset '{dataset_name}'. Ple... | bigcode/self-oss-instruct-sc2-concepts |
def quote(string: str) -> str:
"""
Wrap a string with quotes iff it contains a space. Used for interacting with command line scripts.
:param string:
:return:
"""
if ' ' in string:
return '"' + string + '"'
return string | bigcode/self-oss-instruct-sc2-concepts |
import math
def dunn_individual_word(total_words_in_corpus_1,
total_words_in_corpus_2,
count_of_word_in_corpus_1,
count_of_word_in_corpus_2):
"""
applies Dunning log likelihood to compare individual word in two counter objects
:pa... | bigcode/self-oss-instruct-sc2-concepts |
def evg_project_str(version):
"""Return the evergreen project name for the given version."""
return 'mongodb-mongo-v{}.{}'.format(version.major, version.minor) | bigcode/self-oss-instruct-sc2-concepts |
def rdkitSubstrMatches(targetRdkitMol, refRdkitMol, *args, **kwargs):
"""
Matches two rdkit mol object graphs with each other.
Outputs a list of tuples of corresponding atoms indices.
Arguments:
----------
targetRdkitMol : object
target rdkit molecule object
refRdkitMol : object
... | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_jump_pattern(stripped, function_name):
"""
Return regexp pattern used to identify jump assembly lines. Support
for stripped and non-stripped versions.
Need to match non-stripped lines:
'0x00007ffff7fbf124 <+68>: jmp 0x7ffff7fbf7c2 <test_function+1762>'
and stripped lines:
... | bigcode/self-oss-instruct-sc2-concepts |
def vo_from_fqan(fqan):
"""
Get the VO from a full FQAN
Args:
fqan: A single fqans (i.e. /dteam/cern/Role=lcgadmin)
Returns:
The vo + group (i.e. dteam/cern)
"""
components = fqan.split('/')[1:]
groups = []
for c in components:
if c.lower().startswith('role='):
... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def array_to_tensor(array, device):
"""Convert numpy array to tensor."""
return torch.FloatTensor(array).to(device) | bigcode/self-oss-instruct-sc2-concepts |
def math_expression_type(text):
"""
Custom Type which expects a valid math expression
:param str text: the text which was matched as math expression
:returns: calculated float number from the math expression
:rtype: float
"""
return float(eval(text)) | bigcode/self-oss-instruct-sc2-concepts |
def overlaps(region_1, region_2):
"""
Find if two regions overlaps
a region is defined as dictionary with
chromosome/contig, start- and end position given
Args:
region_1/region_2(dict): dictionary holding region information
Returns:
overlapping(bool)... | bigcode/self-oss-instruct-sc2-concepts |
def preprocess_prediction_data(data, tokenizer):
"""
It process the prediction data as the format used as training.
Args:
data (obj:`List[List[str, str]]`):
The prediction data whose each element is a text pair.
Each text will be tokenized by jieba.lcut() function.
... | bigcode/self-oss-instruct-sc2-concepts |
def _himmelblau(coord):
"""See https://en.wikipedia.org/wiki/Himmelblau%27s_function."""
x, y = coord[..., 0], coord[..., 1]
return (x**2 + y - 11)**2 + (x + y**2 - 7)**2 | bigcode/self-oss-instruct-sc2-concepts |
def approx_Q_top(A, B, T, sigma=1, C=None):
"""
Approximate expression for the (a)symmetric top partition function. The expression is adapted from Gordy and Cook,
p.g. 57 equation 3.68. By default, the prolate top is used if the C constant is not specified, where B = C.
Oblate case can also be specified... | bigcode/self-oss-instruct-sc2-concepts |
def check_items_exist(res) -> bool:
"""Checks whether any product returned."""
return True if len(res['hits']['hits']) > 0 else False | bigcode/self-oss-instruct-sc2-concepts |
def classes(*names, convert_underscores=True, **names_and_bools):
"""Join multiple class names with spaces between them.
Example
-------
>>> classes("foo", "bar", baz=False, boz=True, long_name=True)
"foo bar boz long-name"
Or, if you want to keep the underscores:
>>> classes("foo", "bar... | bigcode/self-oss-instruct-sc2-concepts |
def format_image_results(registry_response_dict):
"""
Response attribute content is formatted correctly for the Images
:param response: response object with content attribute
:return: dict of various images
"""
if not isinstance(registry_response_dict, dict):
raise TypeError('registry_r... | bigcode/self-oss-instruct-sc2-concepts |
def datetime_to_int(datetime):
"""Convert datetime to 17 digit integer with millisecond precision."""
template = (
'{year:04d}'
'{month:02d}'
'{day:02d}'
'{hour:02d}'
'{minute:02d}'
'{second:02d}'
'{millisecond:03d}'
)
priority = int(
templ... | bigcode/self-oss-instruct-sc2-concepts |
def ComputeLabelX(Array):
"""Compute label x coordinate"""
X = min(Array)+ (max(Array)-min(Array))/2
return X | bigcode/self-oss-instruct-sc2-concepts |
def str2re(s):
"""Make re specific characters immune to re.compile.
"""
for c in '.()*+?$^\\':
s = s.replace(c, '['+c+']')
return s | bigcode/self-oss-instruct-sc2-concepts |
def int_to_bytes(x):
""" 32 bit int to big-endian 4 byte conversion. """
assert x < 2 ** 32 and x >= -(2 ** 32)
return [(x >> 8 * i) % 256 for i in (3, 2, 1, 0)] | bigcode/self-oss-instruct-sc2-concepts |
import imp
import unittest
def skipIfModuleNotInstalled(*modules):
"""Skipping test decorator - skips test if import of module
fails."""
try:
for module in modules:
imp.find_module(module)
return lambda func: func
except ImportError:
return unittest.skip("Test skipp... | bigcode/self-oss-instruct-sc2-concepts |
def voter_address_retrieve_doc_template_values(url_root):
"""
Show documentation about voterAddressRetrieve
"""
required_query_parameter_list = [
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, ... | bigcode/self-oss-instruct-sc2-concepts |
def _arrow_to_numpy(arrow_table, schema):
"""Helper function that converts an Arrow Table to a dictionary
containing NumPy arrays. The memory buffers backing the given Arrow Table
may be destroyed after conversion if the resulting Numpy array(s) is not a
view on the Arrow data.
See https://arrow.ap... | bigcode/self-oss-instruct-sc2-concepts |
def delay_feedback_gain_for_t60(delay_samp, fs, t60):
"""
Calculate the gain needed in a feedback delay line
to achieve a desired T60
Parameters
----------
delay_samp : int
The delay length in samples
fs : float
Sample rate
t60 : float
The desired T60 [seconds]
... | bigcode/self-oss-instruct-sc2-concepts |
def get_test_mode_user(prefix='', rconn=None):
"""Return user_id of test mode, or None if not found"""
if rconn is None:
return
try:
test_user_id = int(rconn.get(prefix+'test_mode').decode('utf-8'))
except:
return
return test_user_id | bigcode/self-oss-instruct-sc2-concepts |
def query_create_fact_table() -> str:
"""[this returns the query used for creating fact table. It uses the immigration and temperature tables' view.]
Returns:
str: [query to extract fact table.]
"""
# defining query for creating fact table by joining temperature and immigration data
query =... | bigcode/self-oss-instruct-sc2-concepts |
import shutil
def get_free_space_bytes(folder):
""" Return folder/drive free space (in bytes)
"""
try:
total, _, free = shutil.disk_usage(folder)
return total, free
except:
return 0, 0 | bigcode/self-oss-instruct-sc2-concepts |
def filter_df(df,col,word):
"""Filters out any entries that do not have word(string regex) in the columns specified (col)"""
return df[df[col].str.contains(word,na=False)] | bigcode/self-oss-instruct-sc2-concepts |
def difference(list_1, list_2):
""" Deterministically find the difference between two lists
Returns the elements in `list_1` that are not in `list_2`. Behaves deterministically, whereas
set difference does not. Computational cost is O(max(l1, l2)), where l1 and l2 are len(list_1)
and len(list_2), respe... | bigcode/self-oss-instruct-sc2-concepts |
def scale_dimensions(width, height, longest_side):
""" Calculates image ratio given a longest side
returns a tupple with ajusted width, height
@param width: integer, the current width of the image
@param height: integer, the current height of the image
@param longest_side: the longest side of t... | bigcode/self-oss-instruct-sc2-concepts |
def xorNA(x):
"""Return x if x is not None, or return 'NA'."""
return str(x) if x is not None else 'NA' | bigcode/self-oss-instruct-sc2-concepts |
def update_dcid(dcid, prop, val):
"""Given a dcid and pv, update the dcid to include the pv.
Args:
dcid: current dcid
prop: the property of the value to add to the dcid
val: the value to add to the dcid
Returns:
updated dcid as a string
"""
val_dcid = val.split(":")[-... | bigcode/self-oss-instruct-sc2-concepts |
def genderint_to_string(dataframe,
gender_integer_map):
"""Transforms gender encoded as an integer to a string
INPUT:
dataframe: DataFrame that includes gender encoded as an integer
gender_integer_map: Dictionary that describes the mapping of a
... | bigcode/self-oss-instruct-sc2-concepts |
def _create_index_for_annotation_row(row):
"""Parse the row from annotation file to get chrom and positions.
Parameters
----------
row: pd.DataFrame row
Row of annotation dataframe
Returns
-------
index: array_like
Array of 1-based positions on chromosome
"""
co... | bigcode/self-oss-instruct-sc2-concepts |
def to_list(obj):
"""Convert a list-like object to a list.
>>> to_list([1, 2, 3])
[1, 2, 3]
>>> to_list("a,b,c")
['a', 'b', 'c']
>>> to_list("item")
['item']
>>> to_list(None)
[]
"""
if isinstance(obj, (list, tuple)):
return obj
elif isinstance(obj, str):
... | bigcode/self-oss-instruct-sc2-concepts |
def stock_payoff(S,PP):
"""This function takes Spot price range(S), and purchase price(PP) of the stock as inputs
and returns stock payoff """
return (S-PP) | bigcode/self-oss-instruct-sc2-concepts |
import math
def log(a,b):
"""
Returns the logarithm of a to the base b.
"""
return math.log(a,b) | bigcode/self-oss-instruct-sc2-concepts |
def get_max_score(scores):
""" gets maximum score from a dictionary """
max_value = 0
max_id = -1
for i in scores.keys():
if scores[i] > max_value:
max_value = scores[i]
max_id = i
return max_id | bigcode/self-oss-instruct-sc2-concepts |
def select_files(flist, pattern):
""" Remove fnames from flist that do not contain 'pattern'. """
return [fname for fname in flist if pattern in fname] | bigcode/self-oss-instruct-sc2-concepts |
import logging
def _build_stream_formatter() -> logging.Formatter:
"""Default formatter for log messages. Add timestamps to log messages."""
return logging.Formatter(
fmt="[%(levelname)s %(asctime)s] %(output_name)s: %(message)s",
datefmt="%m-%d %H:%M:%S",
) | bigcode/self-oss-instruct-sc2-concepts |
import math
def tdewpoint_from_relhum(t, h):
"""Compute the Dewpoint temperature.
Parameters
----------
t: array
temperature [C].
h : array
relative humidity [%].
Returns
-------
array
Dewpoint temperature at current timestep.
Example
-------
tdewpoint_from_relhum(20,50) == 9.27... | bigcode/self-oss-instruct-sc2-concepts |
def label_seq(data):
"""
Input:
data: dictionary of text, begin_sentences, end_sentences
Output:
a sequence of labels where each token from the text is assiciated with a label:
regular token --> O
begin sentences token --> BS
end sentences token --> ES
... | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def get_classes_in(__module, predicate=None, return_name=False):
"""Gets all class symbols stored within a Python module.
:param __module: The module to get the classes from.
:type __module: :class:`types.ModuleType`
:param predicate: A callable to pass to inspect.getmembers to filter ... | bigcode/self-oss-instruct-sc2-concepts |
def data_storage_account_settings(conf):
# type: (dict) -> str
"""Retrieve input data storage account settings link
:param dict conf: configuration object
:rtype: str
:return: storage account link
"""
return conf['storage_account_settings'] | bigcode/self-oss-instruct-sc2-concepts |
def from_datastore(entity):
"""Translates Datastore results into the format expected by the
application.
Datastore typically returns:
[Entity{key: (kind, id), prop: val, ...}]
This returns:
{id: id, prop: val, ...}
"""
if not entity:
return None
if isinstance(entity... | bigcode/self-oss-instruct-sc2-concepts |
def calc_gsd_cross(altitude,
focal_length,
pixel_dim_cross):
"""
ground sample distance (gsd) is the distance between pixel centers measured
on the ground.
https://en.wikipedia.org/wiki/Ground_sample_distance
Returns
-------
double : meters per pixel
... | bigcode/self-oss-instruct-sc2-concepts |
def set_lat_lon_attrs(ds):
""" Set CF latitude and longitude attributes"""
ds["lon"] = ds.lon.assign_attrs({
'axis' : 'X',
'long_name' : 'longitude',
'standard_name' : 'longitude',
'stored_direction' : 'increasing',
'type' : 'double',
'units' : 'degrees_east',
... | bigcode/self-oss-instruct-sc2-concepts |
def afill(start, end, ntries):
"""A function that fill evenly spaced values between two numbers"""
step = (end-start)/float(ntries+1) if ntries > 0 else 0
final_list = [float(start) + (i+1)*step for i in range(ntries)]
return(final_list) | bigcode/self-oss-instruct-sc2-concepts |
def overwrite_tags_with_parameters(tagged_lines,parameter_strings):
"""
Takes tagged lines and the respective options and creates a
valid Python source file.
---Inputs---
tagged_lines : {list}
list of all lines making up the tagged source code of the
user's solver (all lines included... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def to_epoch(ogtime):
"""Convert formatted time to Unix/epoch time."""
fstr = '%Y-%m-%dT%H:%M:%S.%fZ'
epoch = datetime(1970, 1, 1)
finaltime = (datetime.strptime(ogtime, fstr) - epoch).total_seconds()
return finaltime | bigcode/self-oss-instruct-sc2-concepts |
def fetch(field, *source_records, **kwds):
"""Return the value from the first record in the arguments that
contains the specified field. If no record in the chain contains
that field, return the default value. The default value is specified
by the "default" keyword argument or None. If keyword argument
... | bigcode/self-oss-instruct-sc2-concepts |
import re
def truncate_html_words(s, num, end_text='...'):
"""Truncates HTML to a certain number of words.
(not counting tags and comments). Closes opened tags if they were correctly
closed in the given html. Takes an optional argument of what should be used
to notify that the string has been truncat... | bigcode/self-oss-instruct-sc2-concepts |
def Square(x, a, b, c):
"""Second order polynomial
Inputs:
-------
``x``: independent variable
``a``: coefficient of the second-order term
``b``: coefficient of the first-order term
``c``: additive constant
Formula:
--------
``a*x^2 + b*x + c``
"""
r... | bigcode/self-oss-instruct-sc2-concepts |
def insert_row(table_name, values):
"""Inserts a row in 'table_name' with values as 'values'"""
query = f'INSERT INTO {table_name} VALUES ('
no_attrs = len(values)
# Add values to query
for i in range(0, no_attrs - 1):
query += f'{values[i]}, '
# Add semicolon for last value
query... | bigcode/self-oss-instruct-sc2-concepts |
def rank_models(ckpt_path2dfs, metric, maximize_metric):
"""Rank models according to the specified metric.
Args:
ckpt_path2dfs (dict): mapping from ckpt_path (str) to (pred_df, gt_df)
metric (function): metric to be optimized, computed over two
DataFrames, namely the predictions and... | bigcode/self-oss-instruct-sc2-concepts |
import six
def convert_to_unicode(text):
"""Converts `text` to Unicode (if it's not already), assuming utf-8 input."""
if six.PY3:
if isinstance(text, str):
return text
elif isinstance(text, bytes):
return text.decode("utf-8", "ignore")
else:
raise V... | bigcode/self-oss-instruct-sc2-concepts |
def assemble_replace_dict(command, use_gpu, additions, queue, time, ngpu):
"""Create dictionary to update BASH submission script for torque.
Parameters
----------
command : type
Command to executer through torque.
use_gpu : type
GPUs needed?
additions : type
Additional c... | bigcode/self-oss-instruct-sc2-concepts |
def _annotate_table(data_table, keyword_dict, num_sources, product="tdp"):
"""Add state metadata to the output source catalog
Parameters
----------
data_table : QTable
Table of source properties
keyword_dict : dict
Dictionary containing FITS keyword values pertaining to the data pr... | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def cycle(collection):
""":yaql:cycle
Makes an iterator returning elements from the collection as if it cycled.
:signature: collection.cycle()
:receiverArg collection: value to be cycled
:argType collection: iterable
:returnType: iterator
.. code::
yaql> [1, 2]... | bigcode/self-oss-instruct-sc2-concepts |
def boolean_content_matcher(string_array: str, substring: str):
"""Returns a list of tuples containing True/False if the substring is found in each element in the array.
Examples:
>>> text_list = ['lambda functions are anonymous functions.',
... 'anonymous functions dont have a name.',
... | bigcode/self-oss-instruct-sc2-concepts |
import requests
def perform_post_request(session, url, data=None, headers=None, encoding=None):
"""
Performs post request.
:param session: `Request` session
:param url: URL for `Request` object
:param data: (optional) Dictionary, list of tuples, bytes, or
file-like object to send in the bod... | bigcode/self-oss-instruct-sc2-concepts |
def apply_first(seq):
"""Call the first item in a sequence with the remaining
sequence as positional arguments."""
f, *args = seq
return f(*args) | bigcode/self-oss-instruct-sc2-concepts |
import warnings
def multichain(self, *others):
"""Makes self inherit from multiple prototypes.
Any relationship with previous parent prototypes will be removed.
When the parent prototypes share attributes with the same name, the
parent prototype that is first in the list of prototypes will
provid... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def _transform_body_for_vscode(body: str) -> List[str]:
"""snippetのbodyをvscode用に変換する.
改行区切りのlist, space4つをtabに変換.
:param body: string of a snippet body
:return body_for_vscode: vscode-snippet形式のbody
"""
body_list = body.split('\n')
body_for_vscode = [b.replace(' ... | bigcode/self-oss-instruct-sc2-concepts |
def name_eq(name):
"""add a 'name' attribute (a string most likely) to a function"""
def wrapper(f):
f.name = name
return f
return wrapper | bigcode/self-oss-instruct-sc2-concepts |
def get_voc_abb(vocation: str) -> str:
"""Given a vocation name, it returns an abbreviated string"""
vocation = str(vocation)
abbrev = {'none': 'N', 'druid': 'D', 'sorcerer': 'S', 'paladin': 'P', 'knight': 'K', 'elder druid': 'ED',
'master sorcerer': 'MS', 'royal paladin': 'RP', 'elite knight'... | bigcode/self-oss-instruct-sc2-concepts |
def isWikiTable(tag):
"""Filter for determining if a given element is a WikiMedia table entry
"""
return tag.name == 'table' and 'class' in tag.attrs and 'wikitable' in tag.attrs['class'] | bigcode/self-oss-instruct-sc2-concepts |
def get_file_contents(filename):
""" Given a filename,
return the contents of that file
"""
try:
with open(filename, 'r') as f:
# It's assumed our file contains a single line,
# with our API key
return f.read().strip()
except FileNotFoundError:
... | bigcode/self-oss-instruct-sc2-concepts |
def close_ring(coordinates):
"""
Makes sure the ring is closed; if it is not, then closes the ring.
:param coordinates: a collection of coordinates representing a polygon
:return: a closed ring
"""
if coordinates[0] != coordinates[-1]:
coordinates.append(coordinates[0])
return coord... | bigcode/self-oss-instruct-sc2-concepts |
def fracval(frac):
"""Return floating point value from rational."""
if frac.find("/") == -1:
return float(frac)
else:
x = frac.split("/")
return float(x[0]) / float(x[1]) | bigcode/self-oss-instruct-sc2-concepts |
def is_record(path: str) -> bool:
"""
Is filename a record file?
:param (str) path: User-supplied filename.
:return: True if filename is valid record file; otherwise False.
:rtype: bool
"""
return path.find("..") == -1 | bigcode/self-oss-instruct-sc2-concepts |
def _read_creds(
filename: str
) -> tuple:
"""Read credentials and home latlong from login.conf file."""
creds_dict = {}
with open(filename) as f:
for line in f:
(key, val) = line.split()
creds_dict[key] = val
return (
creds_dict['email'], creds_dict['password... | bigcode/self-oss-instruct-sc2-concepts |
def count_neighbors_wrap_around(grid2count, posInRow, posInCol, row_Count, col_Count):
"""returns number of ALIVE neighbors from a given position on a given grid using wrap around approach"""
count = 0
for x in range(-1, 2):
for y in range(-1, 2):
if grid2count[(posInRow + x) % row_Coun... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Sequence
from typing import Optional
from typing import List
def build_tree(
tree_structure: Sequence,
multiline_pad: int = 1,
pad_depth: Optional[List[int]] = None,
_indent_data: Optional[list] = None,
) -> str:
"""
Build a tree graph from a nested list.
Each item in t... | bigcode/self-oss-instruct-sc2-concepts |
import re
def add_pre_main_init(startup: str) -> str:
"""Add pw_stm32cube_Init call to startup file
The stm32cube startup files directly call main(), while pigweed expects to
do some setup before main is called. This could include sys_io or system
clock initialization.
This adds a call to `pw_st... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def open_uniform_knot_vector(count: int, order: int, normalize=False) -> List[
float]:
"""
Returns an open (clamped) uniform knot vector for a B-spline of `order` and `count` control points.
`order` = degree + 1
Args:
count: count of control points
order: ... | bigcode/self-oss-instruct-sc2-concepts |
def getsymbol(tree):
"""Get symbol name from valid ``symbol`` in ``tree``
This assumes that ``tree`` is already examined by ``isvalidsymbol``.
"""
return tree[1] | bigcode/self-oss-instruct-sc2-concepts |
def __reconstruct_spectrum(theta, sig_matrix):
"""
Reconstruct the spectrum using the estimated mixture proportions of the reference signatures and the signature matrix.
:param theta: estimated mixture proportions (numpy.array)
:param sig_matrix: The matrix containing the weights of each mutational ty... | bigcode/self-oss-instruct-sc2-concepts |
def unlock(server_id, **kwargs):
"""Unlock server."""
url = '/servers/{server_id}/action'.format(server_id=server_id)
req = {"unlock": None}
return url, {"json": req} | bigcode/self-oss-instruct-sc2-concepts |
import re
def mk_rule_fn(rule, name):
"""Test helper for converting camelCase names to
underscore_function_names and returning a callable rule fn."""
parts = re.sub('(?!^)([A-Z][a-z]+)', r' \1', name).split()
parts.insert(0, 'with')
fn_name = '_'.join(map(lambda x: x.lower(), parts))
retur... | bigcode/self-oss-instruct-sc2-concepts |
def _ParseTaskId(task_id):
"""Parses a command ID from a task ID.
Args:
task_id: a task ID.
Returns:
(request_id, command_id)
"""
if task_id is None:
raise ValueError("task_id cannot be None")
ids = task_id.split("-", 2)
if len(ids) == 3:
return ids[0], ids[1]
return None, ids[0] | bigcode/self-oss-instruct-sc2-concepts |
from bs4 import BeautifulSoup
def get_wiki_from_spotlight_by_name(spotlight, name):
"""Given the spotlight output, and a name string, e.g. 'hong kong'
returns the wikipedia tag assigned by spotlight, if it exists, else '-'."""
actual_found = 0
parsed_spotlight = BeautifulSoup(spotlight.text, 'lxml')
... | bigcode/self-oss-instruct-sc2-concepts |
def twos_complement(n: int, w: int = 16) -> int:
"""Two's complement integer conversion."""
# Adapted from: https://stackoverflow.com/a/33716541.
if n & (1 << (w - 1)):
n = n - (1 << w)
return n | 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.