seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def check_for_code(module):
"""
Check if there's at least one class or one function in the module.
"""
fd = open(module, 'r')
for line in fd:
if line.startswith('def ') or line.startswith('class '):
fd.close()
return True
fd.close()
return False | bigcode/self-oss-instruct-sc2-concepts |
def bytes_endswith(x: bytes, suffix: bytes) -> bool:
"""Does given bytes object end with the subsequence suffix?
Compiling bytes.endswith, with no range arguments, compiles this function.
This function is only intended to be executed in this compiled form.
Args:
x: The bytes object to examine.... | bigcode/self-oss-instruct-sc2-concepts |
def find_allocas(func):
"""
Find allocas that can be promoted to registers. We do this only if the
alloca is used only in load and store operations.
"""
allocas = set()
for op in func.ops:
if (op.opcode == 'alloca' and
all(u.opcode in ('load', 'store') for u in func.uses[... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def search_word_from(
db: List[str], query: str, split_token: str = "", ingore_case: bool = True
) -> List[str]:
"""Search str qurey from list of str db. If split_token is given,
split each str in db by split_token and check for exact match.
If ingore_case is True, ignore case.... | bigcode/self-oss-instruct-sc2-concepts |
def currency(value=0.0, currency='R$'):
"""
#EN-US:
→ Formats the value to display it as a monetary value.
:param value: the value to be formatted.
:param currency: (Optional) the currency symbol that will be
used for formatting. The default is Real (R$).
:return: the value formatted with th... | bigcode/self-oss-instruct-sc2-concepts |
def filters_logical_and(f1, f2, f3):
"""
given three filters, returns the logical and of these filters
in the order: f1 AND f2 AND f3.
Parameters:
-----------
f[1/2/3]: `dict`
filter expression to be combined.
Returns... | bigcode/self-oss-instruct-sc2-concepts |
import json
def generate_ctx(row, input_lifespan=0, output_lifespan=2):
"""
Generates json objects for the input and output contexts, containing their names and lifespans,
from a dictionary corresponding to a row in a dataframe.
Example format:
{"name": "await_18", "lifespan": 0}
: param row... | bigcode/self-oss-instruct-sc2-concepts |
def get_model_fields(model):
"""
Retrieves all non-auto- and non-relation- fields from the supplied model and returns as a list
"""
return list(
filter(
lambda x: x.get_internal_type() != "AutoField"
and not getattr(x, "is_relation"),
model._meta.get_fields(),... | bigcode/self-oss-instruct-sc2-concepts |
def calculate_stats(array):
"""Return min, max, avg in the given array.
"""
_count = 0
_max = _sum = 0.0
_min = None
for number in array:
_count += 1
if _min is None or number < _min:
_min = number
if number > _max:
_max = number
_sum += nu... | bigcode/self-oss-instruct-sc2-concepts |
import random
def choose_from_options(options, name, selection="user"):
"""
Prints out options from a list, and returns the requested option.
:param options: dict or Array, options to choose from. If dict, the value entries are assumed to be docstrings
explaining the individual options
:param... | bigcode/self-oss-instruct-sc2-concepts |
def flatten(items):
"""Flattens a potentially nested sequence into a flat list.
:param items: the sequence to flatten
>>> flatten((1, 2))
[1, 2]
>>> flatten([1, (2, 3), 4])
[1, 2, 3, 4]
>>> flatten([1, (2, [3, 4]), 5])
[1, 2, 3, 4, 5]
"""
retval = []
for item in ite... | bigcode/self-oss-instruct-sc2-concepts |
def __is_dunder(attr_name: str) -> bool:
""" check if a given attr_name is `double underscored` one.
"""
return (
attr_name.startswith('__') and
attr_name.endswith('__')
) | bigcode/self-oss-instruct-sc2-concepts |
def barcode_header(date, price):
"""Format barcode header info line
date: datetime object
price: float
barcode_header takes a datetime object and a float,
representing the price and formats them as so:
MSTAR YYYY-MM-DD DAY P.p
Example:
MSTAR 2016-11-12 SAT 1.2
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def is_guc_configurable(cursor, guc):
"""Check if guc is a preset parameter
https://www.postgresql.org/docs/current/static/runtime-config-preset.html
"""
cursor.execute("""
SELECT EXISTS
(SELECT 1
FROM pg_settings
WHERE context <> 'internal'
AND... | bigcode/self-oss-instruct-sc2-concepts |
def init_filter(df, report=False):
"""Keep relevant subset of topics"""
keep_topics = ['economy', 'europe', 'health', 'crime', 'education', 'immigration', 'law']
groups = df.groupby('topic')
sub_df = df[df['topic'].isin(keep_topics)]
sub_groups = sub_df.groupby('topic')
if report:
print(... | bigcode/self-oss-instruct-sc2-concepts |
import re
def parse_gtf_attr_line(attr_line):
"""parse a GTF attributes line"""
if len(attr_line) == 0:
return {}
attr_line = [x.split(' ') for x in re.split('; +', attr_line.replace('"', ''))]
attr_line[-1][-1] = attr_line[-1][-1].rstrip().replace(';', '')
return dict(attr_line) | bigcode/self-oss-instruct-sc2-concepts |
import six
def is_string(value):
"""Return a boolean value indicating whether the value is a string or not.
This method is compatible with both Python 2.7 and Python 3.x.
NOTE:
1. We can't use isinstance(string_value, str) because strings in Python 2.7 can have "unicode" type.
2. We can't use isi... | bigcode/self-oss-instruct-sc2-concepts |
def iterative_lcs(var1, var2):
"""
:param var1: variable
:param var2: 2nd variable to compare and finding common sequence
:return: return length of longest common subsequence
examples:
>>> iterative_lcs("abcd", "abxbxbc")
3
>>> iterative_lcs([1, 2, 4, 3], [1, 2, 3, 4])
3
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def color_amount(accel_component):
"""Convert acceleration component (x, y, or z) to color amount (r, g, or b)"""
standard_gravity = 9.81 # Acceleration (m/s²) due to gravity at the earth’s surface
accel_magnitude = abs(accel_component) # Ignore the direction
constrained_accel = min(accel_magnitude, s... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Iterable
from typing import Any
def pretty_function(name: str, args: Iterable[Any]) -> str:
"""Produce a pretty textual description of a function call.
Produce a string describing a function call. This is of the form:
name(args[0], args[1], ...)
Arguments:
name: Name of fu... | bigcode/self-oss-instruct-sc2-concepts |
def insertFace(bm, v):
"""
insert face using an array of vertices indices
:param bm:
:param v: list of vertices indices
"""
a = []
for k in range(len(v)):
a.append(bm.verts[v[k]])
f = bm.faces.new(a)
bm.faces.ensure_lookup_table()
return f | bigcode/self-oss-instruct-sc2-concepts |
def accuracy_calculation(actual_label, predicted_label):
"""计算准确率
:param actual_label: 真实类标
:param predicted_label: 模型预测的类标
:return: 准确率(百分制)
"""
correct_count = 0
for i in range(len(actual_label)):
if actual_label[i] == predicted_label[i]:
correct_count += 1
return c... | bigcode/self-oss-instruct-sc2-concepts |
def conv_8to16(v):
""" Conversion d'une variable 8 bits en 16 bits
:param v: var (8b)
:return: 16bit conversion """
return ((v << 8) + v) & 0xFFFF | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
from pathlib import Path
def endswith(path, suffixes: Tuple[str, ...]) -> bool:
"""
Returns whether the path ends with one of the given suffixes.
If `path` is not actually a path, returns True. This is useful
for allowing interpreters to bypass inappropriate paths, but
alw... | bigcode/self-oss-instruct-sc2-concepts |
def decode(param):
"""Decodes the given param when it is bytes."""
if isinstance(param, (float, int)):
return param
return param.decode("utf-8") | bigcode/self-oss-instruct-sc2-concepts |
def good_response(response):
"""
Returns True if the response is HTML.
"""
resp_type = response.headers['Content-Type'].lower()
return response.status_code == 200 and \
resp_type is not None and resp_type.find('html') > -1 | bigcode/self-oss-instruct-sc2-concepts |
import re
def capital_case_without_symbols(name: str) -> str:
"""
Determine the name of the output file by stripping
all special characters and capital casing the words.
:param name: Deck name (unsanitized)
:return: Sanitized deck name
"""
word_characters_only_regex = re.compile(r"[^\w]")
... | bigcode/self-oss-instruct-sc2-concepts |
def LineColour(argument):
"""Dictionary for switching line colours where appropriate"""
switcher = {
'Black': 'k',
'Red': 'r',
'Green': 'g',
'Blue': 'b'
}
return switcher.get(argument, argument) | bigcode/self-oss-instruct-sc2-concepts |
def getNetwork(networks, name):
"""
Get the network with a specific name. This method does not create a network
if no network exists with the given name.
Arguments:
networks -- Network objects for searching.
name -- Name the network shall have.
Returns:
network object on s... | bigcode/self-oss-instruct-sc2-concepts |
def getTag(read, tagId):
"""
Returns the specified tag or None from an AlignmentRecord
"""
for i in read.tags:
if i[0] == tagId:
return i[1]
return None | bigcode/self-oss-instruct-sc2-concepts |
def merge_lists(results_from_fc):
"""
Function for merging multiple lists
"""
combined_list = []
for li in results_from_fc:
combined_list.extend(li)
return combined_list | bigcode/self-oss-instruct-sc2-concepts |
import math
def zr2uv(zr, wavelength, sinalpha, refr_index, magnification=1.0):
"""Return u,v in optical units from z,r given in units of the wavelength.
For excitation, magnification should be 1.
Examples
--------
>>> numpy.allclose(zr2uv((1e3, 1e3), 488, 0.9, 1.33),
... (13.... | bigcode/self-oss-instruct-sc2-concepts |
def set_convolution_options(opts, convolution_options=None):
"""Set the IPU convolution options for the session.
.. code-block:: python
# Set "availableMemoryProportion" flag to "0.1"
opts = create_ipu_config()
opts = set_convolution_options(opts,
convolution_options={"availableMemoryP... | bigcode/self-oss-instruct-sc2-concepts |
def select_all_reads(conn):
"""
Query all rows in the reads table
:param conn: the Connection object
:return:
"""
cur = conn.cursor()
cur.execute("SELECT * FROM reads")
rows = cur.fetchall()
return rows | bigcode/self-oss-instruct-sc2-concepts |
def check_equals(generated_value, expected_value, **kwargs):
"""Check that generated_value is equal to expected_value."""
return generated_value == expected_value | bigcode/self-oss-instruct-sc2-concepts |
async def auto_increment_mongo(client, database, collection):
"""Retrieve the next _id for a given Mongo collection
that's based on _id being a simple integer."""
db = getattr(client, database)
collection = getattr(db, collection)
last_id_list = list(
collection.aggregate([{"$group": {"_id":... | bigcode/self-oss-instruct-sc2-concepts |
import configparser
from pathlib import Path
def get_path_setting(name=''):
"""
Gets a path specified in the Files section of the settings.ini file.
:param name: One of the variable names in the FILES section of settings.ini
:return: Path object from the pathlib library
"""
config = configpars... | bigcode/self-oss-instruct-sc2-concepts |
def int_32_lsb(x: int):
"""
Get the 32 least significant bits.
:param x: A number.
:return: The 32 LSBits of x.
"""
return int(0xFFFFFFFF & x) | bigcode/self-oss-instruct-sc2-concepts |
def __index_query(query, key: str) -> float:
""" Returns a property of the query class, keyed by a string.
The key must be one of:
['Memory', 'Duration', 'Bytes Processed', 'Bytes Billed']
Args:
query (BigQueryResult): A BigQuery result class
key (string): A key ... | bigcode/self-oss-instruct-sc2-concepts |
def mapSeries(requestContext, seriesList, mapNode):
"""
Short form: ``map()``
Takes a seriesList and maps it to a list of seriesList. Each seriesList has the
given mapNode in common.
.. note:: This function is not very useful alone. It should be used with :py:func:`reduceSeries`
.. code-block:: none
... | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def arbitrary_string(size=4, base_text=None):
"""
Return size characters from base_text, repeating the base_text infinitely
if needed.
"""
if not base_text:
base_text = 'test'
return ''.join(itertools.islice(itertools.cycle(base_text), size)) | bigcode/self-oss-instruct-sc2-concepts |
def is_sequence(x):
"""Algorithmically determines if x is a sequence."""
try:
len(x)
x[0:0]
return True
except:
return False | bigcode/self-oss-instruct-sc2-concepts |
def getWebImgType_file(filename):
"""
Get image file type of an image stored in disk. Can be used to verify if an image is available for web.
:param filename: The file you want to verify.
:return: Image file type. If image is invalid, returns False.
"""
data = open(filename,'rb').read(11)
#... | bigcode/self-oss-instruct-sc2-concepts |
import requests
import json
def get_token(keyword, timespan):
"""
Retrieves a token from Google Trends, based on the keyword and timespan.
This function is a deritative of a function within Pytrends by
github.com/GeneralMills. Licensed under the Apache license, version 2.0.
Changes made by githu... | bigcode/self-oss-instruct-sc2-concepts |
def _toolkit_get_topk_bottomk(values, k=5):
"""
Returns a tuple of the top k values from the positive and
negative values in a SArray
Parameters
----------
values : SFrame of model coefficients
k: Maximum number of largest positive and k lowest negative numbers to return
Returns
-... | bigcode/self-oss-instruct-sc2-concepts |
import socket
def get_ip_using_standard_if(host='8.8.8.8'):
"""
Gets the ip of the 'standard interface'
Source: https://stackoverflow.com/a/7335145
Args:
host (str): optional ip of a host to connect to. Default is '8.8.8.8'
Returns: own ip address on standard interface
"""
s = so... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def load_timestamps(timestamp_file):
"""Load timestamps from file."""
# Read and parse the timestamps
timestamps = []
with open(timestamp_file, 'r') as f:
for line in f.readlines():
# NB: datetime only supports microseconds, but KITTI timestamps
... | bigcode/self-oss-instruct-sc2-concepts |
def get_sum(value1, value2):
"""Return the sum of two values."""
return value1 + value2 | bigcode/self-oss-instruct-sc2-concepts |
def total_hazard_perceived_by_town(hazards: list, town_id: int, facilities: list) -> int:
"""
For the specified town retrieve the total risk caused by opened facility
:param hazards: list of list, describe every hazard for the couple (town,facility)
:param town_id: the town of interest
:param facil... | bigcode/self-oss-instruct-sc2-concepts |
def calc_iou(box_a, box_b):
"""
Calculate the Intersection Over Union of two boxes
Each box specified by upper left corner and lower right corner:
(x1, y1, x2, y2), where 1 denotes upper left corner, 2 denotes lower right corner
Returns IOU value
"""
# Calculate intersection, i.e. area of overlap between the 2 ... | bigcode/self-oss-instruct-sc2-concepts |
def LeapYear(year):
"""Leapyear returns 1 if year is a leap year and 0 otherwise. Note that leap years
famously fall on all years that divide by 4 except those that divide by 100 but
including those that divide by 400."""
if year%4:
return 0
elif year%100:
return 1
elif year%400:
return 0
else:
return 1 | bigcode/self-oss-instruct-sc2-concepts |
def FormatTimestamp(timestamp):
"""Returns a string representing timestamp in RFC3339 format.
Args:
timestamp: A datetime.datetime object.
Returns:
A timestamp string in format, which is accepted by Cloud Logging.
"""
return timestamp.strftime('%Y-%m-%dT%H:%M:%SZ') | bigcode/self-oss-instruct-sc2-concepts |
def _split_version_id(full_version_id):
"""Return server and version.
Args:
full_version_id: Value in the format that is set in the 'CURRENT_VERSION_ID'
environment var. I.e. 'server:server_version.minor_version'.
Returns:
(server, server_version) tuple, or (None, server_version) if this is the
... | bigcode/self-oss-instruct-sc2-concepts |
def _g_theta(theta,p):
"""
:param theta: dimensionless electron temperature
:param p: electron power law slope
:return: correction term for power law electron distribution
"""
aa = (6.0 + 15.0 * theta) / (4.0 + 5.0 * theta)
gamma_m = 1e0 + aa * theta
gtheta = ((p-1.0)*(1e0+aa*theta)/((p-... | bigcode/self-oss-instruct-sc2-concepts |
def metadata_key(config):
"""
Build a key to a file in the 'metadata' directory of the published dataset.
"""
def func(filename) -> str:
return f"{config.s3_publish_key}/metadata/{filename}"
return func | bigcode/self-oss-instruct-sc2-concepts |
def _tostr(x):
"""
Convert a value to the native string format.
Parameters
----------
x : str or bytes
value to convert to a native string.
Returns
-------
str
"""
if isinstance(x, bytes):
return x.decode()
else:
return str(x) | bigcode/self-oss-instruct-sc2-concepts |
import sqlite3
def db_connector(filepath):
"""
Creates an SQLite server from the given filepath
:param filepath: the location of the SQLite database
:return: An SQLite connection
"""
print("Initiating connection to database")
return sqlite3.connect(filepath) | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
import json
def load_params(model_dir: Path) -> dict:
"""
Load params from json
Args:
model_dir (Path): model directory path
Returns:
dict: dictionary of params
"""
file_name = model_dir / 'params.json'
with open(file_name, 'r') as f:
para... | bigcode/self-oss-instruct-sc2-concepts |
def count(rdd, field_name):
"""Perform a word count on the specified field of the input rdd by tokenizing the text.
Return an rdd of dicts with "word" and "count" fields.
"""
# Split the text in the records into lowercase words
words = rdd.flatMap(lambda r: r[field_name].lower().split())
# Gen... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Any
from typing import Union
from typing import List
def get_kernel_shape(attributes: Dict[str, Any]) -> Union[List[float], None]:
"""
Get the kernel shape from a dictionary of a model's attributes
:param attributes: a dictionary of a model's attributes
:ret... | bigcode/self-oss-instruct-sc2-concepts |
def _create_id(data_set_id, record_id):
"""
The record_ids are not necessarily globally unique, because they're user provided and
are only guaranteed to be unique within a collection. So that we have a unique primary
key we're joining them with a colon.
>>> _create_id('foo', 'bar')
'foo:bar'
... | bigcode/self-oss-instruct-sc2-concepts |
def all_none(*args):
"""Return True if all arguments passed in are None."""
return all(a is None for a in args) | bigcode/self-oss-instruct-sc2-concepts |
import gzip
def read_file(filepath):
"""
Read normal or gz file (based on their extension .gz)
"""
data = None
if filepath.endswith(".gz"):
with gzip.open(filepath, "rb") as f:
data = f.read()
else:
with open(filepath, 'r') as myfile:
data = myfile.read(... | bigcode/self-oss-instruct-sc2-concepts |
import math
def _is_external(a, b):
""" Check if blob b is outside blob a
:param a: first blob. This is larger than b.
:param b: second blob. This is smaller than a.
:returns: if b is outside the radius of a
"""
ay, ax, ar = a
by, bx, br = b
d = math.sqrt((ax - bx)**2 + (ay - by)**2)... | bigcode/self-oss-instruct-sc2-concepts |
def find_complete_faces(indices, faces):
"""
Given a set of vertices, find the ones that make complete faces.
Parameters
----------
indices : list of integers
indices to connected vertices
faces : list of lists of three integers
the integers for each face are indices to vertices... | bigcode/self-oss-instruct-sc2-concepts |
import re
def year_grabber(year_str: str):
"""
From a string containing a year, possibly more than one, pull out the first.
>>> year_grabber("1948194819491949195019501951")
'1948'
>>> year_grabber("abs1987")
'1987'
>>> year_grabber("1987a")
'1987'
>>> year_grabber("<y>1916̵... | bigcode/self-oss-instruct-sc2-concepts |
def subsumed(id, s_visited_id, STKMAX):
"""Helper for is_term_id and is_surv_id
---
If id is (q,in_str,stk_str)
and exists a member (q1,in_str1,stk_str1) in s_visited_id
then subsumed is True if q==q1, in_str==in_str1
and stk_str1 starts with st... | bigcode/self-oss-instruct-sc2-concepts |
def get_number(s):
""" Check that s is number
If s is a number, returns it as a float. If not, returns s without modification.
Inputs:
s - An input string or number
Outputs:
value - Either float(s) or False if s cannot be cast to float
"""
try:
return float(s)
e... | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_github(text):
"""
Fetches GitHub and GitHub's gist urls from the text obtained from the resume.
:param text:(unicode string) parsed text from the resume.
:return: a list of GitHub and Gist urls
"""
github_url = []
githubs = re.findall('.*[\w\.-]*github[\w\.-]*.*', text)
... | bigcode/self-oss-instruct-sc2-concepts |
def get_files(folder, restrict_to_folder=False):
"""
Gets all files in a folder + subfolders
:param folder: pathlib.Path object
:param restrict_to_folder: bool. If false also
the files in the subdirectories are found
"""
if not restrict_to_folder:
return [x for x ... | bigcode/self-oss-instruct-sc2-concepts |
def post_process_human_data(human_data):
"""Remove unwanted space and solves double shad(ཉིས་ཤད་) split cases
Args:
human_data (str): human segmented data
Returns:
str: clean human segmented data
"""
human_data = human_data.replace('། །', '།།')
human_data = human_data.replace(... | bigcode/self-oss-instruct-sc2-concepts |
def tempo(msg):
"""Returns the usec tempo value from a tempo meta message."""
return (msg[3] << 16) + (msg[4] << 8) + msg[5] | bigcode/self-oss-instruct-sc2-concepts |
def load_wordlist(filename):
"""Load a list of word from a file (one word per line)"""
words = []
with open(filename, 'r') as f:
for line in f:
words.append(line.strip().lower())
return words | bigcode/self-oss-instruct-sc2-concepts |
import json
def __convert_json(string):
""" Converts a string into JSON format. If the conversion fails,
returns None.
"""
try:
return json.loads(string)
except:
return None | bigcode/self-oss-instruct-sc2-concepts |
def divisors_to_string(divs):
"""
Convert a list of numbers (representing the orders of cyclic groups
in the factorization of a finite abelian group) to a string
according to the format shown in the examples.
INPUT:
- ``divs`` -- a (possibly empty) list of numbers
OUTPUT: a string represe... | bigcode/self-oss-instruct-sc2-concepts |
def get_def_class(word):
"""
get_def_class()
Purpose: Checks for a definitive classification at the word level.
@param word. A string
@return 1 if the word is a test term,
2 if the word is a problem term,
3 if the word is a treatment term,
0 ... | bigcode/self-oss-instruct-sc2-concepts |
def validate_font_size(size):
"""
Returns whether or not given size is an acceptable font size.
"""
try:
size = int(size)
except:
return False
return 0 < size < 70 | bigcode/self-oss-instruct-sc2-concepts |
def to_lowercase(text):
"""
Transform all characters to lowercase
:param text: input text
:return: transformed text
"""
return text.lower() | bigcode/self-oss-instruct-sc2-concepts |
def read_byte(file):
""" Read a byte from file """
out = ord(file.read(1))
return out | bigcode/self-oss-instruct-sc2-concepts |
def find_colours(shapes):
""" Takes a list of shapes with cells (y, x, colour) and finds their common and uncommon colours.
Note that uncommon colours are a nested list, where each nested list corresponds to uncommon colours
of a particular shape - different shapes could have different uncommon colours.
... | bigcode/self-oss-instruct-sc2-concepts |
def get_HNF_diagonals(n):
"""Finds the diagonals of the HNF that reach the target n value.
Args:
n (int): The target determinant for the HNF.
Retruns:
diags (list of lists): The allowed values of the determinant.
"""
diags = []
for i in range(1,n+1):
if... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def get_date_time() -> str:
"""get the current system date time
Args:
None
Returns:
(str): date time in the format of Y-m-d-H-M-S
"""
now = datetime.now()
return now.strftime("%Y-%m-%d-%H-%M-%S") | bigcode/self-oss-instruct-sc2-concepts |
def file_extension(filename):
"""
Get file extension from filename
"""
return filename.rsplit('.', 1)[1].lower() | bigcode/self-oss-instruct-sc2-concepts |
def version_diff(version1, version2):
"""Return string representing the diff between package versions.
We're interested in whether this is a major, minor, patch or 'other'
update. This method will compare the two versions and return None if
they are the same, else it will return a string value indicati... | bigcode/self-oss-instruct-sc2-concepts |
def get_vector_length_squared(carla_vector):
"""
Calculate the squared length of a carla_vector
:param carla_vector: the carla vector
:type carla_vector: carla.Vector3D
:return: squared vector length
:rtype: float64
"""
return carla_vector.x * carla_vector.x + \
carla_vector.y ... | bigcode/self-oss-instruct-sc2-concepts |
def version_str(version_info):
"""Format the python version information"""
return "{}.{}".format(version_info[0], version_info[1]) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Set
from typing import Dict
def _sorted_value_indices(values: Set) -> Dict[str, int]:
"""Converts values to a Dict mapping to unique indexes.
Values will be sorted.
Example:
>>> _sorted_value_indices({"b", "a", "c", "a"})
{"a": 0, "b": 1, "c": 2}
"""
return {va... | bigcode/self-oss-instruct-sc2-concepts |
import requests
import json
def isdisambiguation(pagename):
"""Given a wikipedia page name, returns True if that page is a disambiguation page and False otherwise
:param pagename: The name of a wikipedia page
:type pagename: String
:return: True if pagename is the name of a wikipedia page in... | bigcode/self-oss-instruct-sc2-concepts |
def _strip_lines(latex_string):
"""Strip Lines in Latex Source
Arguments:
latex_string {string} -- LateX Source
Returns:
string -- Latex with lines striped
"""
lines = latex_string.splitlines()
result = []
for line in lines:
result.append(line.strip())
return "\... | bigcode/self-oss-instruct-sc2-concepts |
def ms_to_seconds(time: float) -> float:
"""
Convert milliseconds to seconds.
Parameters
----------
time : float
A ``float`` of time in milliseconds.
Returns
-------
float
Returns a ``float`` of the converted time in seconds.
"""
return round(time / 1000, 3) | bigcode/self-oss-instruct-sc2-concepts |
def get_stat_output(args, first_year, stats_dict, top_words, data_list):
"""
Function to format output statistics for one subset of corpus between
first_year and first_year + args.year_split.
input:
args (argparse object): input arguments
first_year (int): start year... | bigcode/self-oss-instruct-sc2-concepts |
import base64
def base64_from_hex(hexstr):
"""
Returns the base64 string for the hex string specified
:param hexstr: The hex string to convert to base64
:return: The base64 value for the specified hes string
"""
return base64.b64encode(bytes(bytearray.fromhex(hexstr))).decode("utf8") | bigcode/self-oss-instruct-sc2-concepts |
def __dict_replace(s, d):
"""Replace substrings of a string using a dictionary."""
for key, value in d.items():
s = s.replace(key, value)
return s | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
from typing import Sequence
import torch
from typing import Mapping
def to_device(inp: Union[Sequence[torch.Tensor], torch.Tensor, Mapping[str, torch.Tensor]],
device: Union[torch.device, str], detach: bool = False,
**kwargs) -> \
Union[Sequence[torch.Tenso... | bigcode/self-oss-instruct-sc2-concepts |
def K(A,L=None):
"""
Function we are trying to maximize: sum_{i<j} A[L[i]][L[j]]
A is m x m matrix,
L is a subset of range(m) (or defaults to range(m) if no L given)
"""
if L==None:
L = range(len(A))
return sum([A[L[i]][L[j]] for j in range(len(L)) for i in range(j)]) | bigcode/self-oss-instruct-sc2-concepts |
def degree_to_DMS(degree):
"""Convert from plain degrees format to DMS format of geolocalization.
DMS: "Degrees, Minutes, Seconds" is a format for coordinates at the surface
of earth. Decimal Degrees = degrees + (minutes/60) + (seconds/3600)
This measure permit to gain in precision when a degree... | bigcode/self-oss-instruct-sc2-concepts |
def safe_str_cmp(a, b):
"""Compare two strings in constant time."""
if len(a) != len(b):
return False
r = 0
for c, d in zip(a, b):
r |= ord(c) ^ ord(d)
return r == 0 | bigcode/self-oss-instruct-sc2-concepts |
import torch
def prod_matrix(pts_src: torch.Tensor, pts_dst: torch.Tensor):
"""
Returns the matrix of "x_i * y_j".
:param pts_src: [R, D] matrix
:param pts_dst: [C, D] matrix
:return: [R, C, D] sum matrix
"""
x_col = pts_src.unsqueeze(1)
y_row = pts_dst.unsqueeze(0)
return x_col * ... | bigcode/self-oss-instruct-sc2-concepts |
import math
def _pad(text, block_size):
"""
Performs padding on the given plaintext to ensure that it is a multiple
of the given block_size value in the parameter. Uses the PKCS7 standard
for performing paddding.
"""
no_of_blocks = math.ceil(len(text)/float(block_size))
pad_value = int(no_... | bigcode/self-oss-instruct-sc2-concepts |
import math
def distance(pt_a, pt_b):
""" Calculate distance between 2 points.
@params:
pt_a: (x, y)
pt_b: (x, y)
"""
return math.sqrt((pt_a[0] - pt_b[0])**2 + (pt_a[1] - pt_b[1])**2) | 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.