seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def norm_package_version(version):
"""Normalize a version by removing extra spaces and parentheses."""
if version:
version = ','.join(v.strip() for v in version.split(',')).strip()
if version.startswith('(') and version.endswith(')'):
version = version[1:-1]
version = ''.jo... | bigcode/self-oss-instruct-sc2-concepts |
def batch_sum(x):
"""Sums a tensor long all non-batch dimensions"""
return x.sum(tuple(range(1, x.dim()))) | bigcode/self-oss-instruct-sc2-concepts |
import re
import json
def parse_json(filename):
""" Parse a JSON file
First remove comments and then use the json module package
Comments look like :
// ...
or
/*
...
*/
"""
# Regular expression for comments
comment_re = re.compil... | bigcode/self-oss-instruct-sc2-concepts |
def field_type(field):
"""
Retrieves the type of a given field.
:param DjangoField field: A reference to the given field.
:rtype: str
:returns: The type of the field.
"""
return field.get_internal_type() | bigcode/self-oss-instruct-sc2-concepts |
def base4Encode(n, d):
""" Convert decimal notation to quaternary notation
We will use division and modulus recursively
n = decimal number
d = number of digits for quaternary representation
>>> base4Encode(22, 4)
[0, 1, 1, 2]
"""
alphabet = [0, 1, 2, 3]
quat = []
base = len(alp... | bigcode/self-oss-instruct-sc2-concepts |
def normalize(df, data_params):
"""Apply data scales.
Applies data scaling factors to df using data_params.
Args:
df (pd.DataFrame): with columns 'ds', 'y', (and potentially more regressors)
data_params (OrderedDict): scaling values,as returned by init_data_params
with ShiftSca... | bigcode/self-oss-instruct-sc2-concepts |
def get_phase_start_stop(data):
"""
Get start and stop for a phase or subphase from the input time series data where start is
indicated by a value of 1 and stop is indicated by a value of 0 in the time series data
:param data: the time series data list
:return: the indices in the data list for the s... | bigcode/self-oss-instruct-sc2-concepts |
import pickle
def read_pickle(filename):
"""Read object from pickle format.
Parameters
----------
filename : str
Input file.
Returns
-------
obj : object
Python object.
"""
with open(filename, "rb") as f:
return pickle.load(f) | bigcode/self-oss-instruct-sc2-concepts |
def kernel_file_name(ns):
"""Given kernel info namespace, return reasonable file name."""
assert hasattr(ns, 'length')
length = ns.length
if isinstance(length, (tuple, list)):
length = 'x'.join(str(x) for x in length)
postfix = ''
if ns.scheme == 'CS_KERNEL_STOCKHAM_BLOCK_CC':
... | bigcode/self-oss-instruct-sc2-concepts |
import time
import random
import requests
def _get_page(url, s=None):
"""
Utility function to play nice when scraping.
This will also fetch a page according to a session or a simple get.
"""
if not url:
# What's a proper null requests object?
return None
# Play nice
time.s... | bigcode/self-oss-instruct-sc2-concepts |
def only_first_4_patches(tensor, n_imgs=4):
"""
Batch truncation function
:param tensor: batch
:param n_imgs: number of patches to keep
:return: truncated batch
"""
return tensor[0:n_imgs] | bigcode/self-oss-instruct-sc2-concepts |
def _add_dates_to_sections(schedule):
"""
Adds term start/end dates to sections that do not have them (ie non-PCE)
"""
for section in schedule.sections:
if section.start_date is None:
if section.summer_term == "B-term":
section.start_date = schedule.term.bterm_first_... | bigcode/self-oss-instruct-sc2-concepts |
def truncate_after(d, n):
"""Truncate first timestamp dictionary D after N entries."""
sorted_lst = sorted(d.items(), key=lambda a: a[1][0])
return dict(sorted_lst[:n]) | bigcode/self-oss-instruct-sc2-concepts |
def round_off(value, digits=2):
"""
Rounding off the value
:param float value: Value to be rounded
:param digits: Digit to kept as after point
:return float: Rounded value
"""
return float(("{0:.%sf}" % digits).format(value)) | bigcode/self-oss-instruct-sc2-concepts |
def hamming_distance(str_1: str, str_2: str) -> int:
"""Return the hamming distance between two strings of equal length
Arguments:
str_1 {str} -- first string
str_2 {str} -- second string
Returns:
int -- hamming distance
Example:
>>> hamming_distance("ATATACATACGCG... | bigcode/self-oss-instruct-sc2-concepts |
import base64
def DecodeWithKey(key, string):
"""
Decode with Key
Takes your encoded string and decodes it with another string(key)
string = "w5PDisOlw5fDlA=="
key = "key"
>> "Hello"
"""
dec = []
enc = base64.urlsafe_b64decode(string).decode()
for i in range(len(enc)):
... | bigcode/self-oss-instruct-sc2-concepts |
import pyarrow
def deserialize(data):
"""
Deserialize bytes into an object using pyarrow
Args:
bytes: a bytes object containing serialized with pyarrow data.
Returns:
Returns a value deserialized from the bytes-like object.
"""
return pyarrow.deserialize(data) | bigcode/self-oss-instruct-sc2-concepts |
def createTwoDimensionBoard(height=3, width=3):
"""
Create a array in 2 dimensions fill with ' '
"""
return [[' ' for i in range(width)] for j in range(height)] | bigcode/self-oss-instruct-sc2-concepts |
def apply(object, args=None, kwargs=None):
"""Call a callable object with positional arguments taken from the
tuple args, and keyword arguments taken from the optional dictionary
kwargs; return its results.
"""
if args is None:
args = ()
if kwargs is None:
kwargs = {}
return ... | bigcode/self-oss-instruct-sc2-concepts |
def get_item_hrefs(result_collection):
"""
Given a result_collection (returned by a previous API call that
returns a collection, like get_bundle_list() or search()), return a
list of item hrefs.
'result_collection' a JSON object returned by a previous API
call.
Returns a list, which may be... | bigcode/self-oss-instruct-sc2-concepts |
def Sign(number):
"""
Sign(number)
Return the mathematical sign of the given number.
"""
return number and (-1, 1)[number > 0] | bigcode/self-oss-instruct-sc2-concepts |
def get_img_url(img_src, url_base):
"""
Get an image url from the src attribute af an image, and the page base url
"""
if not img_src:
return None
if not "//" in img_src: ## it's not an absolute url
if img_src[0] == "/":
img_src = img_src[1:]
img_src = url_base + ... | bigcode/self-oss-instruct-sc2-concepts |
def last_replace(s, old, new, number_of_occurrences):
"""
Replaces last n occurrences of the old string with the new one within the string provided
:param s: string to replace occurrences with
:param old: old string
:param new: new string
:param number_of_occurrences: how many occurrences shoul... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def rgb_to_rgba(rgb: torch.Tensor, fill: float = 1.0):
"""
Converts tensor from 4 channels into 3.
Alpha layer will be filled with 1 by default, but can also be specified.
[... 3 H W] -> [... 4 H W]
"""
alpha_channel = torch.full_like(rgb[..., :1, :, :], fill_value=fill)
retur... | bigcode/self-oss-instruct-sc2-concepts |
def link(href, text):
"""Generate a link"""
return '<a href="' + href + '">' + text + '</a>' | bigcode/self-oss-instruct-sc2-concepts |
def getDuplicateElements(lst):
""" Return the elements that are duplicated in list """
if lst == None or type(lst) != list:
raise ValueError("lst must be a list.")
return list(set([x for x in lst if lst.count(x) > 1])) | bigcode/self-oss-instruct-sc2-concepts |
def std(image):
"""The standard deviation of pixel intensities"""
return image.std() | bigcode/self-oss-instruct-sc2-concepts |
def copy_docstring(source):
"""Decorator function to copy a docstring from a `source` function to a `target` function.
The docstring is only copied if a docstring is present in `source`, and if none is present in `target`. Takes
inspiration from similar in `matplotlib`.
Parameters
----------
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Mapping
from typing import Any
def update_analytics_params(stream_slice: Mapping[str, Any]) -> Mapping[str, Any]:
"""
Produces the date range parameters from input stream_slice
"""
return {
# Start date range
"dateRange.start.day": stream_slice["dateRange"]["start.da... | bigcode/self-oss-instruct-sc2-concepts |
def _mesh_to_surf_cards(mesh, divs):
"""Prepares the surface cards for mesh_to_geom."""
surf_cards = ""
count = 1
for i, dim in enumerate("xyz"):
for div in divs[i]:
surf_cards += "{0} p{1} {2}\n".format(count, dim, div)
count += 1
return surf_cards | bigcode/self-oss-instruct-sc2-concepts |
def normalize_component(value):
"""Normalize component to be in the 0 - 255 range"""
if value < 0:
return 0
if value > 255:
return 255
return value | bigcode/self-oss-instruct-sc2-concepts |
def move_matrix(coef,mat_1,mat_2,add_mat):
"""
Do matrix calculations without messing with numpy.
Inputs:
coef: coefficient for the current matrix combination
centroid: the centroid matrix
point: the point by which to alter the centroid
Output: a single combined matrix, represe... | bigcode/self-oss-instruct-sc2-concepts |
def remove_empty_fields(obj: dict) -> dict:
"""
Removes empty fields from NetBox objects.
This ensures NetBox objects do not return invalid None values in fields.
:param obj: A NetBox formatted object
"""
return {k: v for k, v in obj.items() if v is not None} | bigcode/self-oss-instruct-sc2-concepts |
import logging
def dataset_factory(*args, **kwargs):
"""Factory to get correct dataset class based on name
Parameters
----------
dataset_class_name : str
Class name
Default value "None"
Raises
------
NameError
Class does not exists
Returns
-------
Dat... | bigcode/self-oss-instruct-sc2-concepts |
def _popcount(int):
"""Returns the number of 1 bits in the input."""
count = 0
for bit in range(0, 32):
count = count + ((int >> bit) & 1)
return count | bigcode/self-oss-instruct-sc2-concepts |
import torch
def try_gpu(i=0):
"""
Return gpu(i) if exists, otherwise return cpu().
Extracted from https://github.com/d2l-ai/d2l-en/blob/master/d2l/torch.py
"""
if torch.cuda.device_count() >= i + 1:
return torch.device(f'cuda:{i}')
return torch.device('cpu') | bigcode/self-oss-instruct-sc2-concepts |
from typing import Sequence
def array_to_sentence_string(
array: Sequence[str],
connector: str = "and",
) -> str:
"""Join an array of things into a string by separating with commas and the
word "and" for the last one.
Args:
array: The Array of Strings to join.
connector: Word used... | bigcode/self-oss-instruct-sc2-concepts |
import io
def image_models_to_csv(images: list):
"""
Given a list of Image models, convert the result to an in-memory CSV. This allows faster transfers to the database
via COPY FROM.
"""
csv_images = io.StringIO()
for image in images:
row = '\t'.join(list(image.values())) + '\n'
... | bigcode/self-oss-instruct-sc2-concepts |
def sort_values(df, columns, order='asc'):
"""
Sort DataFrame
:param df: DataFrame
:param columns: name of the columns to sort
:param order: asc or desc
:return: DataFrame
"""
ascending = order != 'desc'
return df.sort_values(columns, ascending=ascending) | bigcode/self-oss-instruct-sc2-concepts |
def batch_matrix(w, batch_size):
"""
batch a weight matrix
:param w: [M, N]
:param batch_size: B
:return: [B, M, N]
"""
return w.unsqueeze(0).expand(batch_size, -1, -1) | bigcode/self-oss-instruct-sc2-concepts |
def diff_dicts(dicts, ignore=None):
""" Given a sequence of dicts, returns
common, [difference1, difference2, ...]
where `commmon` is a dict containing items in all dicts, and `differenceN` is a dict containing keys
unique to the corresponding dict in `dicts`, ignor... | bigcode/self-oss-instruct-sc2-concepts |
def formartweek(week_num):
"""
格式化周期数,如1是周日
:param week_num: 数值
:return: 返回中文周
"""
week=['周日','周一','周二','周三','周四','周五','周六']
return week[week_num-1] | bigcode/self-oss-instruct-sc2-concepts |
def get_driver_readiness(config: dict) -> str:
"""Get the code_readiness config setting."""
return config.get("code_readiness", "Release") | bigcode/self-oss-instruct-sc2-concepts |
def format_direction(direction):
"""
Examples
--------
>>> format_direction('ra')
'ra'
>>> format_direction('el')
'alat'
>>> format_direction('az')
'alon'
"""
lowerdir = direction.lower()
if lowerdir == 'el':
return 'alat'
elif lowerdir == 'az':
return... | bigcode/self-oss-instruct-sc2-concepts |
def get_soundex(name):
"""Get the soundex code for the string"""
name = name.upper()
soundex = ""
soundex += name[0]
dictionary = {"BFPV": "1", "CGJKQSXZ":"2", "DT":"3", "L":"4", "MN":"5", "R":"6", "AEIOUHWY":"."}
for char in name[1:]:
for key in dictionary.keys():
if char in... | bigcode/self-oss-instruct-sc2-concepts |
def is_subsequence(subtext: str, text: str) -> bool:
"""
>>> is_subsequence('pe', 'apple')
True
>>> is_subsequence('ep', 'apple')
False
"""
if len(subtext) == 0:
return True
i = 0
for symbol in text:
if symbol == subtext[i]:
i += 1
if i == len(... | bigcode/self-oss-instruct-sc2-concepts |
import posixpath
def posix_relpath(path, root):
"""posix.relpath() that keeps trailing slash."""
out = posixpath.relpath(path, root)
if path.endswith('/'):
out += '/'
return out | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def combichem(reactant_1_SMILES: list, reactant_2_SMILES: list):
""" "
Gets all possible combinations between two uneven lists of
reactants
Args:
reactant_1_SMILES (list): List of reactant one smiles
reactant_2_SMILES (list): List of reactant two smiles
Returns:
... | bigcode/self-oss-instruct-sc2-concepts |
def get_subsecond_component(frac_seconds, frac_seconds_exponent,
subsec_component_exponent, upper_exponent_limit):
"""Return the number of subseconds from frac_seconds *
(10**frac_seconds_exponent) corresponding to subsec_component_exponent that
does not exceed upper_exponent_lim... | bigcode/self-oss-instruct-sc2-concepts |
def flatten(x):
"""
Collapse image data from (C, H, W) to (C, H * W)
"""
return x.view(x.size(0), -1) | bigcode/self-oss-instruct-sc2-concepts |
def get_device(module):
"""Returns the device of the module's parameters."""
device = None
for param in module.parameters():
if device is None:
device = param.device
continue
if device != param.device:
raise ValueError("Parameters are allocated on differen... | bigcode/self-oss-instruct-sc2-concepts |
def get_model_constants(model_settings):
"""
Read constants from model settings file
Returns
-------
constants : dict
dictionary of constants to add to locals for use by expressions in model spec
"""
return model_settings.get('CONSTANTS', {}) | bigcode/self-oss-instruct-sc2-concepts |
def trim_suffix(s, suffix):
"""Removes a suffix from a string if it exists"""
return s[: -len(suffix)] if s.endswith(suffix) else s | bigcode/self-oss-instruct-sc2-concepts |
def _HexAddressRegexpFor(android_abi):
"""Return a regexp matching hexadecimal addresses for a given Android ABI."""
if android_abi in ['x86_64', 'arm64-v8a', 'mips64']:
width = 16
else:
width = 8
return '[0-9a-f]{%d}' % width | bigcode/self-oss-instruct-sc2-concepts |
def _fbeta_score(beta, p, r):
"""Compute the F-beta score for a given precision and recall."""
return (1 + beta ** 2) * (p * r) / ((beta ** 2 * p) + r + 1e-100) | bigcode/self-oss-instruct-sc2-concepts |
def LineIsComment(line):
"""Whether this entire line is a comment (and whitespace).
Note: This doesn't handle inline comments like:
[ # Blah blah.
But we discourage those in general, so shouldn't be a problem.
"""
return line.lstrip().startswith('#') | bigcode/self-oss-instruct-sc2-concepts |
def _attributeLinesToDict(attributeLines):
"""Converts a list of obo 'Term' lines to a dictionary.
:param attributeLines: a list of obo 'Term' lines. Each line contains a key
and a value part which are separated by a ':'.
:return: a dictionary containing the attributes of an obo 'Term' entry.
... | bigcode/self-oss-instruct-sc2-concepts |
def remove_letter(letter, string):
"""Removes all occurrences of a given letter from a string."""
string_without_letter = string.replace(letter, '')
return string_without_letter | bigcode/self-oss-instruct-sc2-concepts |
def dummy_training_data(dummy_dataset):
"""Returns training data from `dummy_dataset`.
"""
training_data = {'x_train': [dummy_dataset.idx_seq['train']['word'],
dummy_dataset.idx_seq['train']['char']],
'x_valid': None,
'x_test': None,... | bigcode/self-oss-instruct-sc2-concepts |
def get_role(username, role_db):
"""Take username from user and return its role.
"""
return role_db.query.filter(role_db.username == username).first() | bigcode/self-oss-instruct-sc2-concepts |
def remove_empty_parameters(data):
"""Accepts a dictionary and returns a dict with only the key, values where the values are not None."""
return {key: value for key, value in data.items() if value is not None} | bigcode/self-oss-instruct-sc2-concepts |
def find_sponsor(sponsorid, sponsor_dictionary):
"""
Given a sponsorid, find the org with that sponsor. Return True and URI
if found. Return false and None if not found
"""
try:
uri = sponsor_dictionary[sponsorid]
found = True
except:
uri = None
found = False
... | bigcode/self-oss-instruct-sc2-concepts |
def qmf(h):
"""Returns the quadrature mirror filter of a given filter"""
g = h[::-1]
g = g.at[1::2].set(-g[1::2])
return g | bigcode/self-oss-instruct-sc2-concepts |
def opacity_button(data_ix, mean_ix):
"""Configures opacity drop down menu.
Args:
data_ix: iterable with data index at 1 and mean index at 0.
mean_ix: iterable with data index at 0 and mean index at 1.
Returns:
opacity_menu: config dict for layout
"""
reset_opac = [1] * le... | bigcode/self-oss-instruct-sc2-concepts |
def _format_block_id(chunk_num):
# type: (int) -> str
"""Create a block id given a block (chunk) number
:param int chunk_num: chunk number
:rtype: str
:return: block id
"""
return '{0:08d}'.format(chunk_num) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Callable
def similarize_distance(distance_measure: Callable) -> Callable:
"""
Takes a distance measure and converts it into a information_density measure.
Args:
distance_measure: The distance measure to be converted into information_density measure.
Returns:
The in... | bigcode/self-oss-instruct-sc2-concepts |
def mat_tris(mesh):
"""Returns dict: mat_name -> list_of_triangle_indices"""
m_ps = {}
idx_tri = 0
for p in mesh.polygons:
mat = mesh.materials[p.material_index] if mesh.materials else None
mat_name = mat.name if mat else "__BDX_DEFAULT"
if not mat_name in m_ps:
m_p... | bigcode/self-oss-instruct-sc2-concepts |
import re
def parse_range(range_str):
"""
Generates an object of type range for the specified range.
Parameters
----------
range_str : str
A string indicating a range. Corresponds to either of the
following formats.
* '[0-9]+'
* '[0-9]+-[0-9]+'
Returns
--... | bigcode/self-oss-instruct-sc2-concepts |
def getsize(data):
""" return smallest possible integer size for the given array """
maxdata = max(data)
assert maxdata < 2**32
if maxdata < 256:
return 1
elif maxdata < 65536:
return 2
else:
return 4 | bigcode/self-oss-instruct-sc2-concepts |
import torch
def sequence_mask(lengths, max_seq_length=None, dtype=torch.bool):
"""
Returns a mask tensor representing the first N positions of each cell.
lengths: integer tensor, all its values <= maxlen.
max_seq_length: scalar integer tensor, size of last dimension of returned tensor.
Default is the ma... | bigcode/self-oss-instruct-sc2-concepts |
import typing
def canonicalize_headers(
headers: typing.Union[typing.Dict[str, str], typing.List[typing.Tuple[str, str]]]
) -> typing.Dict[str, typing.List[str]]:
"""
HTTP headers are case-insensitive. Join equivalent headers together.
"""
if isinstance(headers, dict):
headers = [
... | bigcode/self-oss-instruct-sc2-concepts |
def weight_path(spec_path, element_path):
"""Determine the weighting number for a matchingRule path spec applied to an actual element path from a
response body.
Both paths are passed in as lists which represent the paths split per split_path()
In spec version 2 paths should always start with ['$', 'bo... | bigcode/self-oss-instruct-sc2-concepts |
import platform
import struct
def _ioc_encode(direction, number, structure):
"""
ioctl command encoding helper function
Calculates the appropriate spidev ioctl op argument given the direction,
command number, and argument structure in python's struct.pack format.
Returns a tuple of the calculated op and the... | bigcode/self-oss-instruct-sc2-concepts |
def pluralize(text: str, amount: int) -> str:
"""'Pluralizes' a string if a given amount is plural.
Example:
pluralize('egg', 2) -> 'eggs'
pluralize('python', 1) ->
"""
return text + 's' if amount > 1 else text | bigcode/self-oss-instruct-sc2-concepts |
def remove_rows_matching(df, column, match):
"""
Return a ``DataFrame`` with rows where `column` values match `match` are removed.
The selected `column` series of values from the supplied Pandas ``DataFrame`` is compared
to `match`, and those rows that match are removed from the DataFrame.
:param ... | bigcode/self-oss-instruct-sc2-concepts |
def export_network(name: str, batch_size: int, *args, **kwargs) -> str:
""" Exports a network by name and returns the path to the output file.
@param name Network name (options: simple_cnn, deep_mnist, resnet, wide_resnet).
@param batch_size Minibatch size to use
@param args Other arguments... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def heaviside(data):
"""
A `heaviside step function <https://en.wikipedia.org/wiki/Heaviside_step_function>`_
that truncates numbers <= 0 to 0 and everything else to 1.
"""
return torch.where(
data <= torch.zeros_like(data),
torch.zeros_like(data),
torch.ones_l... | bigcode/self-oss-instruct-sc2-concepts |
def expand_cli_args(args):
"""
Expand a list of possibly comma separated arguments, removing duplicates.
:param args: The list of arguments to expand.
:return: The set of unique arguments.
"""
items = set()
for arg in args: # "a.jpg,b.png"
for arg_ in [n.strip() for n in arg.split(... | bigcode/self-oss-instruct-sc2-concepts |
def tx_capacity_cost_rule(mod, g, p):
"""
Capacity cost for new builds in each period (sum over all vintages
operational in current period).
"""
return sum(
mod.TxNewLin_Build_MW[g, v]
* mod.tx_new_lin_annualized_real_cost_per_mw_yr[g, v]
for (gen, v) in mod.TX_NEW_LIN_VNTS_O... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
def get_int_bounds(type_str: str) -> Tuple[int, int]:
"""Returns the lower and upper bound for an integer type."""
size = int(type_str.strip("uint") or 256)
if size < 8 or size > 256 or size % 8:
raise ValueError(f"Invalid type: {type_str}")
if type_str.startswith("u")... | bigcode/self-oss-instruct-sc2-concepts |
def tf_to_10(x):
"""
Maps true/false to 1/0
"""
if x == True:
return 1
elif x == False:
return 0
return x | bigcode/self-oss-instruct-sc2-concepts |
def _is_unpoly(self) -> bool:
"""Request is triggered by Unpoly"""
return (
'HTTP_X_UP_VERSION' in self.META
or 'HTTP_X_UP_MODE' in self.META
or 'HTTP_X_UP_TARGET' in self.META
or 'HTTP_X_UP_VALIDATE' in self.META
) | bigcode/self-oss-instruct-sc2-concepts |
def get_directed_and_undirected_edges(adjacency_matrix):
"""
Given an adjacency matrix, which contains both directed and undirected edges,
this function returns two adjancy matrices containing directed and undirected edges separately.
Useful for plotting the difference causal graph.
Parameters
... | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def sort_and_groupby(l, key=None):
"""Returns a generator of (key, list), sorting and grouping list by key."""
l.sort(key=key)
return ((k, list(g)) for k, g in itertools.groupby(l, key)) | bigcode/self-oss-instruct-sc2-concepts |
def is_query(parsed_sql):
"""
Determine if the input SQL statement is a query.
Parameters
----------
parsed_sql: sqlparse.sql.Statement
SQL statement that has been parsed with ``sqlparse.parse()``.
Returns
-------
bool
True if statement type is SELECT and the second non... | bigcode/self-oss-instruct-sc2-concepts |
def BitStringToByteString(bs):
"""Convert a pyasn1.type.univ.BitString object to a string of bytes."""
def BitsToInt(bits):
return sum(v * (2 ** (7 - j)) for j, v in enumerate(bits))
return bytes(
bytearray([BitsToInt(bs[i:i + 8]) for i in range(0, len(bs), 8)])) | bigcode/self-oss-instruct-sc2-concepts |
def getTransientStates(m):
"""Returns a list with the indices of the non-absorbing states of the matrix m"""
t= list(range(len(m)))
for r in range(len(m)):
if(sum(m[r])==0): t.remove(r)
return t | bigcode/self-oss-instruct-sc2-concepts |
def lerp(a, b, t):
""" blend the value from start to end based on the weight
:param a: start value
:type a: float
:param b: end value
:type b: float
:param t: the weight
:type t: float
:return: the value in between
:rtype: float
"""
return a * (1 - t) + b * t | bigcode/self-oss-instruct-sc2-concepts |
def process(proc_data):
"""
Final processing to conform to the schema.
Parameters:
proc_data: (dictionary) raw structured data to process
Returns:
List of dictionaries. Structured data with the following schema:
[
{
"line": integer,
"c... | bigcode/self-oss-instruct-sc2-concepts |
def format_slack_message(table_name, metric, avg_time, increase, stddev, stddev_old):
""" Formats slack message using slack emojis.
:param table_name: BigQuery table name that was analysed.
:param metric: string with metric name.
:param avg_time: calculated average time for recent data of given metric.... | bigcode/self-oss-instruct-sc2-concepts |
def comp_radius(self):
"""Compute the radius of the two circle that contains all the ventilation
ducts
Parameters
----------
self : VentilationPolar
A VentilationPolar object
Returns
-------
(Rmin, Rmax): tuple
Tuple of circle radius [m]
"""
self.check()
... | bigcode/self-oss-instruct-sc2-concepts |
def frequency_table(text, k):
"""returns frequency table for k_mers of length k in the text"""
d = {}
i = 0
while i <= len(text)-k:
pattern = text[i:i+k]
d[pattern] = d.get(pattern, 0) + 1
i = i+1
return d | bigcode/self-oss-instruct-sc2-concepts |
def process_data(employee_list):
"""
Takes the employee list built by read_employees() and does a count of the Department data
"""
department_list = []
for employee_data in employee_list:
department_list.append(employee_data['Department'])
department_data = {}
for department_name ... | bigcode/self-oss-instruct-sc2-concepts |
def is_tribe(parcels):
"""
Dummy for tribal areas.
"""
tribal_mpas = ['AK', 'FM', 'GR', 'SA', 'SN', 'TC']
return parcels['mpa'].isin(tribal_mpas).astype(int) | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
import textwrap
def generate_build_file_contents(name: str, dependencies: List[str]) -> str:
"""Generate a BUILD file for an unzipped Wheel
Args:
name: the target name of the py_library
dependencies: a list of Bazel labels pointing to dependencies of the library
R... | bigcode/self-oss-instruct-sc2-concepts |
def get_list_of_active_skills(utterances):
"""
Extract list of active skills names
Args:
utterances: utterances, the first one is user's reply
Returns:
list of string skill names
"""
result = []
for uttr in utterances:
if "active_skill" in uttr:
result.... | bigcode/self-oss-instruct-sc2-concepts |
import math
def switchSymmetry(mlist, upperToLower=True):
"""
A symmetric 2-d NxN array can be stored in memory as a list of (N*(N+1)/2) numbers. The order depends
on whether the upper-diagonal or lower-diagonal portion of the array is being stored. This method switches
between the two representation... | bigcode/self-oss-instruct-sc2-concepts |
def get_and_update_or_create(model, filter_params, defaults):
""" get or create with default values applied to existing instances
{model}.objects.get_or_create(*{filter_params}, defaults={defaults})
Arguments:
model {django.db.models.Model} -- The model the queryset gets applied to
fil... | bigcode/self-oss-instruct-sc2-concepts |
def byte_to_int16(lsb, msb):
"""
Converts two bytes (lsb, msb) to an int16
:param lsb: Least significant bit
:param msb: Most significant bit
:return: the 16 bit integer from the two bytes
"""
return (msb << 8) | lsb | bigcode/self-oss-instruct-sc2-concepts |
def generate_number_lines(number_of_lines=6, start=0, end=20):
"""
Generates number lines as a tool for practicing mathematics such as addition or subtraction.
:param number_of_lines: Specify the number of lines to have on the page
:param start: start value for the number line as an integer
:param e... | 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.