seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def cubo_oct_coord_test(x, y, z): # dist2 = 2
"""Test for coordinate in octahedron/cuboctahedron grid"""
return (x % 2 + y % 2 + z % 2) == 2 | bigcode/self-oss-instruct-sc2-concepts |
def get_colnames(main_colnames=None, error_colnames=None, corr_colnames=None,
cartesian=True):
"""
Utility function for generating standard column names
"""
if main_colnames is None:
if cartesian:
# main_colnames = [el for el in 'XYZUVW']
main_colnames = ... | bigcode/self-oss-instruct-sc2-concepts |
def jpeg_header_length(byte_array):
"""Finds the length of a jpeg header, given the jpeg data in byte array format"""
result = 417
for i in range(len(byte_array) - 3):
if byte_array[i] == 0xFF and byte_array[i + 1] == 0xDA:
result = i + 2
break
return result | bigcode/self-oss-instruct-sc2-concepts |
def get_cluster_id_by_name(dataproc, project_id, region, cluster_name):
"""Helper function to retrieve the ID and output bucket of a cluster by
name."""
for cluster in dataproc.list_clusters(project_id, region):
if cluster.cluster_name == cluster_name:
return cluster.cluster_uuid, cluste... | bigcode/self-oss-instruct-sc2-concepts |
def diagpq(p, q=0):
"""
Returns string equivalent metric tensor for signature (p, q).
"""
n = p + q
D = []
for i in range(p):
D.append((i*'0 ' +'1 '+ (n-i-1)*'0 ')[:-1])
for i in range(p,n):
D.append((i*'0 ' +'-1 '+ (n-i-1)*'0 ')[:-1])
return ','.join(D) | bigcode/self-oss-instruct-sc2-concepts |
def mag_to_flux(mag, zeropoint):
"""Convert a magnitude into a flux.
We get the conversion by starting with the definition of the magnitude scale.
.. math::
m = -2.5 \\log_{10}(F) + C
2.5 \\log_{10}(F) = C - m
F = 10^{\\frac{C-m}{2.5}}
:param mag: magnitdue to be converted ... | bigcode/self-oss-instruct-sc2-concepts |
def make_init_message(*, dim, order, dt, t_final,
nstatus, nviz, cfl, constant_cfl,
initname, eosname, casename,
nelements=0, global_nelements=0):
"""Create a summary of some general simulation parameters and inputs."""
return(
f"Initiali... | bigcode/self-oss-instruct-sc2-concepts |
def lmean (inlist):
"""
Returns the arithematic mean of the values in the passed list.
Assumes a '1D' list, but will function on the 1st dim of an array(!).
Usage: lmean(inlist)
"""
sum = 0
for item in inlist:
sum = sum + item
return sum/float(len(inlist)) | bigcode/self-oss-instruct-sc2-concepts |
def quote_remover(var):
"""
Helper function for removing extra quotes from a variable in case it's a string.
"""
if type(var) == str:
# If string, replace quotes, strip spaces
return var.replace("'", "").replace('"','').strip()
else:
# If not string, return input
... | bigcode/self-oss-instruct-sc2-concepts |
def float_to_fp(signed, n_bits, n_frac):
"""Return a function to convert a floating point value to a fixed point
value.
For example, a function to convert a float to a signed fractional
representation with 8 bits overall and 4 fractional bits (S3.4) can be
constructed and used with::
>>> s... | bigcode/self-oss-instruct-sc2-concepts |
import random
def random_replicate_name(len=12):
"""Return a random alphanumeric string of length `len`."""
out = random.choices('abcdefghijklmnopqrtuvwxyzABCDEFGHIJKLMNOPQRTUVWXYZ0123456789', k=len)
return ''.join(out) | bigcode/self-oss-instruct-sc2-concepts |
def hk_modes(hier_num):
"""
Generate modes in the HK hierarchy.
Parameters
----------
hier_num : int
Number in the HK hierarchy (hier_num = n means the nth model).
Returns
-------
p_modes : list
List of psi modes, represented as tuples.
Each tuple contains the h... | bigcode/self-oss-instruct-sc2-concepts |
def _is_target_node(node: str) -> bool:
"""Check if it is valid target node in BEL.
:param node: string representing the node
:return: boolean checking whether the node is a valid target in BEL
"""
if node.startswith('bp') or node.startswith('path'):
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def contrast(img, threshold):
"""
Constrast all pixels of an image given a threshold.
All pixels smaller or equal will be 0 and the other will be 255
"""
return (img > threshold) * 255 | bigcode/self-oss-instruct-sc2-concepts |
def _intended_value(intended, unspecified, actual, name, msg):
"""
Return the intended value if the actual value is unspecified or has
the intended value already, and otherwise raise a ValueError with the
specified error message.
Arguments:
* `intended`: The intended value, or sequence of va... | bigcode/self-oss-instruct-sc2-concepts |
def cortical_contrast(mean_gm, mean_wm):
"""Calculate the vertex-wise cortical contrast.
- cortical contrast = (mean WM intensity) - (mean GM intensity) /
( (mean WM intensity + mean GM intensity) / 2 )
:type mean_gm: float
:param mean_gm: The mean value of the gray matter ... | bigcode/self-oss-instruct-sc2-concepts |
def find_first(iterable, default=False, pred=None):
"""Returns the first true value in the iterable.
If no true value is found, returns *default*
If *pred* is not None, returns the first item
for which pred(item) is true.
"""
# first_true([a,b,c], x) --> a or b or c or x
# first_true([a,b... | bigcode/self-oss-instruct-sc2-concepts |
def model_set(model):
"""Converts a model from a dictionary representation to a set representation.
Given a ``model`` represented by a dictionary mapping atoms to Boolean values,
this function returns the *set* of atoms that are mapped to ``True`` in the dictionary.
Paramters
---------
model ... | bigcode/self-oss-instruct-sc2-concepts |
import logging
def get_type(node):
"""Get xpath-node's type.(recursive function).
Args:
node: The xpath-node's root.
Returns:
return xpath-node's type.
"""
if node.keyword not in ['leaf','leaf-list']:
return None
type_stmt = node.search_one("type")
if not type_stmt:... | bigcode/self-oss-instruct-sc2-concepts |
def dict_to_list(d):
"""Converts an ordered dict into a list."""
# make sure it's a dict, that way dict_to_list can be used as an
# array_hook.
d = dict(d)
return [x[-1] for x in sorted(d.items())] | bigcode/self-oss-instruct-sc2-concepts |
def halt_after_time(time,at_node,node_data,max_time=100):
"""
Halts after a fixed duration of time.
"""
return time>=max_time | bigcode/self-oss-instruct-sc2-concepts |
def text_html_table(caption=None):
"""Return a text HtmlTable with a given caption for testing."""
if caption:
caption = f"<caption>{caption}</caption>"
return f"""
<table>
{caption}
<tr></tr>
<tr></tr>
</table>
""" | bigcode/self-oss-instruct-sc2-concepts |
def is_command(text):
"""
Checks if `text` is a command. Telegram chat commands start with the '/' character.
:param text: Text to check.
:return: True if `text` is a command, else False.
"""
if (text is None): return None
return text.startswith('/') | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Tuple
def longest_path(dir_str: str) -> str:
"""
To find the longest path to any dir/file.
Can be easily modified to get the longest path to just a file
:param dir_str: Directory string containing the directory structure
:return: longest directory path (... | bigcode/self-oss-instruct-sc2-concepts |
def columns(thelist, n):
"""
Break a list into ``n`` columns, filling up each row to the maximum equal
length possible. For example::
>>> l = range(10)
>>> columns(l, 2)
[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]
>>> columns(l, 3)
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9]]
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Tuple
def configuration_key_intersection(*argv: List[Tuple[int, int]]
) -> List[Tuple[int, int]]:
"""Return the intersection of the passed configuration key lists.
Args:
*args (list[(int, int)]): any number of configuration ... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def find_first_in_list(txt: str, str_list: List[str]) -> int:
"""Returns the index of the earliest occurrence of an item from a list in a string
Ex: find_first_in_list('foobar', ['bar', 'fin']) -> 3
"""
start = len(txt) + 1
for item in str_list:
if start > txt.find... | bigcode/self-oss-instruct-sc2-concepts |
import json
def from_json(config_file_path):
"""Read data from a json file.
Check the file exists and create it if not.
We want to return an empty dict and not fail if the file contains no data.
:param config_file_path Path: Path representing the file-to-read.
:returns dict: config data (or an e... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def calcCellDeltaList(cell: List[int]) -> List[int]:
"""Calculates the list of step sizes for a cell
Args:
cell (list): List of bits in a cell (i.e. [0, 1, 2, 3])
Returns:
list: List of step sizes between levels in the cell
"""
l = len(cell)
prev = 0
... | bigcode/self-oss-instruct-sc2-concepts |
def some(predicate, seq):
"""If some element x of seq satisfies predicate(x), return predicate(x).
>>> some(callable, [min, 3])
1
>>> some(callable, [2, 3])
0
"""
for x in seq:
px = predicate(x)
if px: return px
return False | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_first_stacktrace(stderr_data):
"""If |stderr_data| contains stack traces, only returns the first one.
Otherwise returns the entire string."""
# Use question mark after .+ for non-greedy, otherwise it will match more
# than one stack trace.
sanitizer_stacktrace_regex = r'ERROR: [A-z]+Sanit... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def autograd_individual_gradients(X, y, forward_fn, parameters):
"""Compute individual gradients with a for-loop using autograd.
Loop over data (xₙ, yₙ) and compute ∇ℓ(xₙ, yₙ) with respect to `parameters`,
where ℓ is the forward function.
Note:
Individual gradients only make sen... | bigcode/self-oss-instruct-sc2-concepts |
import typing
def hex(b: typing.Optional[bytes]) -> str:
"""convert an optional bytes into hex-encoded str, returns "" if bytes is None"""
return b.hex() if b else "" | bigcode/self-oss-instruct-sc2-concepts |
def get_reserved_price(client, availability_zone, instance_type):
"""Gets price of a given reserved Linux instance type in a given availability zone."""
resp = client.describe_reserved_instances_offerings(
InstanceType=instance_type,
AvailabilityZone=availability_zone,
OfferingType="No U... | bigcode/self-oss-instruct-sc2-concepts |
def get_class_with_tablename(cls):
"""
Returns the first parent found (or the class itself) for given class which
has __tablename__ attribute set.
This function is needed for slug uniqueness testing when using concrete
inheritance.
:param cls: class to inspect
"""
mapper_args = {}
... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def convert_date(measured_time):
"""
Convert obtained from provider api date to correct for influxdb
:param measured_time:
:return: example - '2019-01-31T19:25:00Z'
"""
converted_measured_time = datetime.strptime(measured_time, "%Y-%m-%d %H:%M:%S")
return conv... | bigcode/self-oss-instruct-sc2-concepts |
def split_train_test(X, Y, trs_len=0.80):
"""
Split both X and Y into train and test sets.
trs_len - how much data should we use for training?
by default it's 0.80 meaning 80%, the remining
20% of the data will be used for testing.
"""
lx = len(X)
# 1 year train set ... | bigcode/self-oss-instruct-sc2-concepts |
def pair_right(f):
"""Returns a function that given a value x, returns a tuple of the form: (x, f(x)).
>>> add_one = pair_right(lambda x: x + 1)
>>> add_one(3)
(3, 4)
"""
def pair_right(x):
return x, f(x)
return pair_right | bigcode/self-oss-instruct-sc2-concepts |
def npqt(fmp, f0p, fmf0=4.88):
"""Calculate NPQt
NPQt = (4.88 / ((fmp / f0p) - 1)) - 1
:param fmp: Fm'
:param f0p: F0'
:param fmf0: Fv/Fm (default: 4.88)
:returns: NPQ (float)
"""
return (fmf0 / ((fmp / f0p) - 1)) - 1 | bigcode/self-oss-instruct-sc2-concepts |
def parse_arguments(parser):
"""Read user arguments"""
parser.add_argument('--path_model',
type=str, default='Model/weights.01.hdf5',
help='Path to the model to evaluate')
parser.add_argument('--path_data', type=str, default='data/data_test.pkl',
... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def convert_datetime(timestamp: int) -> datetime:
"""Convert a java microseconds timestamp from the ToonAPI to a datetime."""
return datetime.utcfromtimestamp(timestamp // 1000.0).replace(
microsecond=timestamp % 1000 * 1000
) | bigcode/self-oss-instruct-sc2-concepts |
import re
def ParseRevision(lines):
"""Parse the revision number out of the raw lines of the patch.
Returns 0 (new file) if no revision number was found.
"""
for line in lines[:10]:
if line.startswith('@'):
break
m = re.match(r'---\s.*\(.*\s(\d+)\)\s*$', line)
if m:
return int(m.group... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def dicom_strfdate( dt: datetime ) -> str:
"""
datetime -> dicom date
"""
return dt.strftime( "%Y%m%d" ) | bigcode/self-oss-instruct-sc2-concepts |
def get_depth(phylo_tree):
"""
Returns the depth of a tree.
"""
depth = 0
for terminal_node in phylo_tree.get_terminals(order='preorder'):
path_length = len(phylo_tree.get_path(target=terminal_node))
if path_length > depth:
depth = path_length
return depth | bigcode/self-oss-instruct-sc2-concepts |
import requests
def get_response_from_url(url):
"""Returns the Hue API response to a URL as json."""
response = requests.get(url).json()
return response | bigcode/self-oss-instruct-sc2-concepts |
def check_neighboring_blocks(block, grid):
"""
Given a block, return the immediate neighbors of the block.
Parameters
----------
block : tuple
The row and column of a block (row, col)
grid : ndarray
The numpy 2D array of containing blocks (1) and empty space (0)
Returns
... | bigcode/self-oss-instruct-sc2-concepts |
def left_of_line(point, p1, p2):
""" True if the point self is left of the line p1 -> p2
"""
# check if a and b are on the same vertical line
if p1[0] == p2[0]:
# compute # on which site of the line self should be
should_be_left = p1[1] < p2[1]
if should_be_left:
retu... | bigcode/self-oss-instruct-sc2-concepts |
def distinct_words(corpus):
""" Determine a list of distinct words for the corpus.
Params:
corpus (list of list of strings): corpus of documents
Return:
corpus_words (list of strings): list of distinct words across the corpus, sorted (using python 'sorted' function)
... | bigcode/self-oss-instruct-sc2-concepts |
def extractFeatures(pages, dataset):
"""
Extract the amount of page views for each student for each page
\n
:param pages: A list of all the (unique) pages to use \t
:type pages: list \n
:param dataset: A list of dictionaries, each dictionary representing one student and having at least the key "... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def rmse(hat_y, y):
"""RMSE
Args:
hat_y: 预测值
y: 真实值
Return:
('rmse', rmse): 评价指标名称,评价结果
"""
rmse = torch.sqrt(torch.mean(torch.pow(y - hat_y, 2)))
return 'rmse', rmse | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
def manhattan_distance(point1: Tuple[int, int], point2: Tuple[int, int]) -> int:
"""Calculate and return the Manhattan distance between two points.
:param point1: first point
:param point2: second point
:return: Manhattan distance between the two points
"""
x1, y1 = ... | bigcode/self-oss-instruct-sc2-concepts |
def get_dofs(data):
"""
Gets the number of target DOFs (i.e. the number of different motion
classes required to complete a trial).
"""
return len(data['target']['pose']) | bigcode/self-oss-instruct-sc2-concepts |
def precompute_idfs(wglobal, dfs, total_docs):
"""Pre-compute the inverse document frequency mapping for all terms.
Parameters
----------
wglobal : function
Custom function for calculating the "global" weighting function.
See for example the SMART alternatives under :func:`~gensim.model... | bigcode/self-oss-instruct-sc2-concepts |
def parse_tensor_name_with_slicing(in_str):
"""Parse tensor name, potentially suffixed by slicing string.
Args:
in_str: (str) Input name of the tensor, potentially followed by a slicing
string. E.g.: Without slicing string: "hidden/weights/Variable:0", with
slicing string: "hidden/weights... | bigcode/self-oss-instruct-sc2-concepts |
def get_runtime_and_maxRAM(dataset):
""" Return runtime in hours and max RAM in GB """
curr_dir = dataset + "/"
log = {}
logfile = curr_dir + dataset + ".log"
with open(logfile) as f:
for line in f:
if line.startswith("="):
continue
(key, val) = line.... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def double_sha256(string, as_hex=False):
"""
Get double SHA256 hash of string
:param string: String to be hashed
:type string: bytes
:param as_hex: Return value as hexadecimal string. Default is False
:type as_hex
:return bytes, str:
"""
if not as_hex:
retu... | bigcode/self-oss-instruct-sc2-concepts |
def lower_dict_keys(some_dict):
"""Convert all keys to lowercase"""
result = {}
for key, value in some_dict.items():
try:
result[key.lower()] = value
except AttributeError:
result[key] = value
return result | bigcode/self-oss-instruct-sc2-concepts |
import time
import math
def time_since(since):
"""
Calculate processed time in min and sec
:param since: time data when processing started
:return: string to show min and sec
"""
now = time.time()
s = now - since
m = math.floor(s / 60)
s -= m * 60
return '%dm %ds' % (m, s) | bigcode/self-oss-instruct-sc2-concepts |
def add_jekyll_header(html_str, layout, title, description):
"""
Add the Jekyll header to the html strings.
Args:
html_str (str): HTML of converted notebook.
layout (str): Jekyll layout to use.
title (str): Title to use.
description (str): Description to use
Returns:
... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def parse_iso8601(t):
"""Return datetime from ISO8601 string."""
return datetime.strptime(t, '%Y-%m-%dT%H:%M:%S.%fZ') | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_first_line_text_from_html(html_string):
"""reduce html to the first line of text and strip all html tags
"""
if html_string is None:
return None
p_div = re.compile(r"</?(p|div|br).*?>",
re.IGNORECASE | re.DOTALL)
html_string = p_div.sub("\n", html_s... | bigcode/self-oss-instruct-sc2-concepts |
def cskp(self, kcn="", kcs="", porig="", pxaxs="", pxypl="", par1="",
par2="", **kwargs):
"""Defines a local coordinate system by three keypoint locations.
APDL Command: CSKP
Parameters
----------
kcn
Arbitrary reference number assigned to this coordinate system.
Must be g... | bigcode/self-oss-instruct-sc2-concepts |
import re
def structure_from_viewer(status, atlas_layer, atlas):
"""
Get brain region info from mouse position in napari viewer.
Extract nx3 coordinate pair from napari window status string.
Return brainglobe (BG) structure number, name, hemisphere, and a
"pretty" string that can be displayed for... | bigcode/self-oss-instruct-sc2-concepts |
def altera_caractere(s, c, i):
"""
Altera um caractere em uma string
:param s: str; palavra a ser editada
:param c: chr; caractere substituto
:param i: int; indice do caractere a ser substituido
:return: str
"""
x = list(s)
x[i] = c
return ''.join(x) | bigcode/self-oss-instruct-sc2-concepts |
def normalize_context_key(string):
"""Normalize context keys
Function will normalize the string (remove white spaces and tailings)
Args:
string (str):
Returns:
Normalized string
"""
tmp = string[:1].upper() + string[1:]
return tmp.replace(" ", "") | bigcode/self-oss-instruct-sc2-concepts |
def cli(ctx, history_id, dataset_id, follow=False):
"""Get details related to how dataset was created (``id``, ``job_id``, ``tool_id``, ``stdout``, ``stderr``, ``parameters``, ``inputs``, etc...).
Output:
Dataset provenance information
For example::
{'id': '6fbd9b2274c62ebe',
... | bigcode/self-oss-instruct-sc2-concepts |
import six
def safe_utf8(string):
"""Returns bytes on Py3 and an utf-8 encoded string on Py2."""
if six.PY2:
return string.encode("utf-8")
else:
return string | bigcode/self-oss-instruct-sc2-concepts |
def clip_colours(colour_value):
""" This function ensures that our auto white balance module does not
exceed the limits of our RGB spectrum.
:param colour_value: The value of our colour channel.
:return: The normalised value of our colour channel.
"""
if colour_value <= 0:
# Value of ... | bigcode/self-oss-instruct-sc2-concepts |
import math
def mu_a(x, alpha_L=0.1, alpha_R=0.1):
"""
Calculates the asymetric alpha-trimmed mean
"""
# sort pixels by intensity - for clipping
x = sorted(x)
# get number of pixels
K = len(x)
# calculate T alpha L and T alpha R
T_a_L = math.ceil(alpha_L*K)
T_a_R = math.floor... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def get_relative_position_matrix(length, max_relative_position, direction, offset=True):
""" Generate matrix of relative positions between inputs ([..., length])."""
range_vec = torch.arange(length).long()
if torch.cuda.is_available():
range_vec = range_vec.cuda()
range_mat = rang... | bigcode/self-oss-instruct-sc2-concepts |
import yaml
def read_config(fname):
"""Read configuration file."""
with open(fname, 'r') as fid:
config = yaml.load(fid, yaml.SafeLoader)
return config | bigcode/self-oss-instruct-sc2-concepts |
def graph6n(data):
"""Read initial one or four-unit value from graph6 sequence. Return value, rest of seq."""
if data[0] <= 62:
return data[0], data[1:]
return (data[1]<<12) + (data[2]<<6) + data[3], data[4:] | bigcode/self-oss-instruct-sc2-concepts |
def _make_emm_plugin_finalizer(handle, allocations):
"""
Factory to make the finalizer function.
We need to bind *handle* and *allocations* into the actual finalizer, which
takes no args.
"""
def finalizer():
"""
Invoked when the MemoryPointer is freed
"""
# At e... | bigcode/self-oss-instruct-sc2-concepts |
def ps_weight_timemean(field, ps):
"""
This takes the surface pressure time mean of atmos_fields
input:
field xr.DataArray or xr.Dataset
ps surface pressure field with the same dimensions are field, it does not need the verical coordinates
return
same structure are field but ... | bigcode/self-oss-instruct-sc2-concepts |
def cite_key(extracted_cite):
"""Get a hashed key to represent a given ExtractedCite object, to check whether a new one is redundant."""
return hash((
extracted_cite.cite,
extracted_cite.normalized_cite,
extracted_cite.rdb_cite,
extracted_cite.rdb_normalized_cite,
extract... | bigcode/self-oss-instruct-sc2-concepts |
from functools import reduce
from operator import mul
def doubleFactorial(n):
"""
Returns double factorial of an integer.
"""
return reduce(mul, range(n, 0, -2)) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
def delete_api_gateway(api_gateway_client, api_gateway_id: str) -> Dict:
"""
Delete the API Gateway given ID.
Args:
api_gateway_client: API Gateway V2 Client.
api_gateway_id: API Gateway ID to delete.
Returns: The delete_api API response dict.
"""
retu... | bigcode/self-oss-instruct-sc2-concepts |
def cal_weight(from_x, from_y, to_x, to_y):
"""
calculate distance
Args:
from_x: x coordinate
from_y: y coordinate
to_x: x coordinate
to_y: y coordinate
Returns:
distance
"""
# return abs(from_x - to_x) + abs(from_y - to_y) # manhattan
return ((fro... | bigcode/self-oss-instruct-sc2-concepts |
def convert_datetimes_to_seconds(start_date, datetimes):
""" Converts difference in datetimes to total elapsed seconds.
Parameters
----------
start_date : datetime object
Start date to use for calculating total elapsed seconds.
datetimes : list of datetimes
List of datetimes to calc... | bigcode/self-oss-instruct-sc2-concepts |
import ast
def is_name_in_ptree(name, ptree):
"""
Return True if an ast.Name node with the given name as its id
appears anywhere in the ptree, False otherwise
"""
if not ptree:
return False
for node in ast.walk(ptree):
if isinstance(node, ast.Name) and (node.id == name):
... | bigcode/self-oss-instruct-sc2-concepts |
def get_location(http_info):
"""Extract the redirect URL from a pysaml2 http_info object"""
assert 'headers' in http_info
headers = http_info['headers']
assert len(headers) == 1
header_name, header_value = headers[0]
assert header_name == 'Location'
return header_value | bigcode/self-oss-instruct-sc2-concepts |
def modus_ponens(p, q):
"""Implements the modus ponens logic table: p -> q"""
if p:
return q
else:
return not p | bigcode/self-oss-instruct-sc2-concepts |
def interval_idx(x, xi):
"""
Given a grid of points xi (sorted smallest to largest) find in
which interval the point x sits. Returns i, where x \in [ xi[i],xi[i+1] ].
Raise ValueError if x is not inside the grid.
"""
assert x >= xi[0] and x <= xi[-1], ValueError(
'x=%g not in [%g,%g]' %... | bigcode/self-oss-instruct-sc2-concepts |
def atResolution(rect):
"""
Returns true iff the rectangle described is at resolution
"""
return True | bigcode/self-oss-instruct-sc2-concepts |
def _isSubsequenceContained(subSequence, sequence):# pragma: no cover
"""
Checks if the subSequence is into the sequence and returns a tuple that
informs if the subsequence is into and where. Return examples: (True, 7),
(False, -1).
"""
n = len(sequence)
m = len(subSequence)
for i in ra... | bigcode/self-oss-instruct-sc2-concepts |
def get_service(v1, service):
"""Get service spec for service"""
return v1.list_service_for_all_namespaces(watch=False, field_selector="metadata.name=%s"%service) | bigcode/self-oss-instruct-sc2-concepts |
def MakeSpecificSKUPropertiesMessage(messages, instance_properties,
total_count):
"""Constructs a specific sku properties message object."""
return messages.FutureReservationSpecificSKUProperties(
totalCount=total_count, instanceProperties=instance_properties) | bigcode/self-oss-instruct-sc2-concepts |
def gl_add_user_group_project(gl_project_group, gl_user, gl_access_level):
"""
Adds a Gitlab user to a Gitlab project or group at the given access level
:param gl_project_group: A Project or Group object
:param gl_user: A User instance
:param gl_access_level: A gitlab.Access_Level. Can be gitlab.GUE... | bigcode/self-oss-instruct-sc2-concepts |
def parse_dimensions(dimensions):
"""
Parse the width and height values from a dimension string. Valid values are
'1x1', '1x', and 'x1'. If one of the dimensions is omitted, the parse result
will be None for that value.
"""
width, height = [d.strip() and int(d) or None for d in dimensions.split... | bigcode/self-oss-instruct-sc2-concepts |
def is_subgraph(G, H):
"""
Checks whether G is a subgraph of H, that is whether all the edges of G belong to H
"""
edges1 = set(G.edges())
edges2 = set(H.edges())
return len(edges1) == len(edges1 & edges2) | bigcode/self-oss-instruct-sc2-concepts |
def ns_faint(item_name):
"""Prepends the faint xml-namespace to the item name."""
return '{http://www.code.google.com/p/faint-graphics-editor}' + item_name | bigcode/self-oss-instruct-sc2-concepts |
def get_admin_site_name(context):
"""
Get admin site name from context.
First it tries to find variable named admin_site_name in context.
If this variable is not available, admin site name is taken from request path
(it is first part of path - between first and second slash).
"""
admin_site_... | bigcode/self-oss-instruct-sc2-concepts |
def to_iso_format(
date_time):
"""
Return a string representing the date and time in ISO 8601 format,
YYYY-MM-DD HH:MM:SS.mmmmmm or, if microsecond is 0, YYYY-MM-DD HH:MM:SS
If utcoffset() does not return None, a 6-character string is appended,
giving the UTC offset in (signed) hours and mi... | bigcode/self-oss-instruct-sc2-concepts |
def re_fun(number):
"""递归调用,计算某个数的阶乘"""
if number == 1:
return number
return number * re_fun(number - 1) | bigcode/self-oss-instruct-sc2-concepts |
def get_data_matching_filter(filter_by, raw_data):
"""
Returns a list of data matching filter_by from a given STB's raw_data
:param filter_by: Tuple containing (filter_name, filter_value)
:param raw_data: Dictionary of raw stb_data for 1 STB.
:return: List of dictionary entries from flattened STB ma... | bigcode/self-oss-instruct-sc2-concepts |
def is_float(arg):
""" Returns True iff arg is a valid float """
if isinstance(arg, float) or isinstance(arg, int):
return True
try:
float(arg)
except ValueError:
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
def make_rest(step_size):
"""
this method constructs a placeholder for a rest note
"""
return {"rest":step_size} | bigcode/self-oss-instruct-sc2-concepts |
def get_sessions_by_dimensions(
service, profile_id, startDate, endDate, segment, dimensions, metrics="ga:sessions"
):
"""
Query the API for channel grouping for sessions WITH dimensions
And sort query output by the first dimension specified
Args:
service: authenticated connection objec... | bigcode/self-oss-instruct-sc2-concepts |
def backpointer_cell_to_string(cell):
"""Makes a string of a cell of a backpointer chart"""
s="["
for (k,rhs) in cell:
s+="(%i, %s)"%(k,",".join(rhs))
s+="]"
return s | bigcode/self-oss-instruct-sc2-concepts |
def cutStrAndAlignRight(s,length=8):
"""
Cuts the string down to the specified length and if it's shorter then it
aligns it to the right
"""
if len(s) >= length:
return s[0:8]
else:
return ' '*(length-len(s))+s | 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.