seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def getattr_(entity, attribute):
"""Either unpack the attribute from every item in the entity
if the entity is a list, otherwise just return the attribute
from the entity. Returns None if the entity is either None
or empty."""
if entity in (None, []):
return None
if isinstance(entity, li... | bigcode/self-oss-instruct-sc2-concepts |
import binascii
def HexifyBuffer(string_buffer):
"""Return a string with the hex representation of a string buffer."""
chars = []
for char in string_buffer:
chars.append(binascii.hexlify(char))
return '\\x{0:s}'.format('\\x'.join(chars)) | bigcode/self-oss-instruct-sc2-concepts |
def finished_prediction(status):
"""
Gets prediction of finished game
:param status:
:return: 1.0 if white wins, 0.0 if black wins, 0.5 if draw
"""
finished_dict = {"w": 1.0, "b": 0.0, "d": 0.5}
return finished_dict[status] | bigcode/self-oss-instruct-sc2-concepts |
import json
def pp(s):
"""
Pretty print JSON string.
"""
return json.dumps(s, indent=4) | bigcode/self-oss-instruct-sc2-concepts |
def transform_coords(coords, swap, reflect):
"""
coords - a set of coordinates
swap - the swap transformation (i.e. (0, 2, 1) --> (x, z, y))
reflect - the reflection transformation (i.e. (1, -1, 1) --> (x, -y, z))
Returns the transformed coordinates
"""
new_coords = []
for i in range(le... | bigcode/self-oss-instruct-sc2-concepts |
def compute_trapped_rain_water(heights: list[int]) -> int:
"""
Given n non-negative integers representing an elevation map (height)
where the width of each bar is 1,
compute how much water it can trap after raining.
Notes:
if `left_max_height` and `right_max_height` are the maximum heights
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
from pathlib import Path
def _try_touch_file(target) -> Optional[Path]:
"""Test to see if we have permissions to create a file at ``target``.
If the target already exists, it will not be touched. If it does not
exist, this function attempts to create it and delete it (i.e... | bigcode/self-oss-instruct-sc2-concepts |
def read_to_whitespace(fptr, track):
"""
Read, skipping over white space. Then read all non-whitespace until one
character of white space is consumed. Return the non-whitespace that was
read. If the end of the file is encountered, return any non-whitespace if
available, or an empty bytes string.
... | bigcode/self-oss-instruct-sc2-concepts |
def reopen_to(fhandle, path, mode):
"""
close a filehandle and return a new one opened for the specified path and mode.
example: sys.stdout = reopen_to(sys.stdout, "/tmp/log.txt", "w")
Parameters:
fhandle (file): the file handle to close (may be None)
path (str): the new path to open
... | bigcode/self-oss-instruct-sc2-concepts |
import re
def check_input(new_ver):
""" Ensure that user input matches the format X.X.X """
pat = r'\d+.\d+.\d+'
if not re.match(pat, new_ver):
print("The new version must be in the format X.X.X (ex. '0.6.0')")
return True | bigcode/self-oss-instruct-sc2-concepts |
def ignore_exception_handler(ex):
""" acts as if no exception was raised, equivalent to except: pass"""
return None | bigcode/self-oss-instruct-sc2-concepts |
def modNeg90To90(angle_deg):
"""Returns a modulo between -90 and 90"""
return (angle_deg + 90)%180-90 | bigcode/self-oss-instruct-sc2-concepts |
def image(title, desc, image_name, group=None, height=None):
"""
Builds an image element. Image elements are primarily created
and then wrapped into an image gallery element. This is not required
behavior, however and it's independent usage should be allowed depending
on the behavior required.
... | bigcode/self-oss-instruct-sc2-concepts |
def flatten(l):
"""Utility function to flatten an iter of iters into an iter."""
return [item for sublist in l for item in sublist] | bigcode/self-oss-instruct-sc2-concepts |
def _int_str_to_bit_str(int_str, num_bits, msb_first):
"""
Convert an integer string to num_bits bits string.
Example:
int_string_to_bit_str('0x5', 4) -> '0101'
int_string_to_bit_str('0x3', 4, msb_first=false) -> '1010'
"""
data = int(int_str, 0) # use radix 0 to automatically deduc... | bigcode/self-oss-instruct-sc2-concepts |
def get_padding(kernel, dilations, axis):
"""
Calculates required padding for given axis
Args:
kernel: A tuple of kernel height and width
dilations: A tuple of dilation height and width
axis: 0 - height, 1 width
Returns:
An array that contains a length of padding at the ... | bigcode/self-oss-instruct-sc2-concepts |
def update_variables(variables, constraints):
"""Updates all variables with their neighboring variables and constraints."""
for constraint in constraints:
scope = constraints[constraint].variables
for var in scope:
variables[var].add_constraint(constraint)
variables[var].... | bigcode/self-oss-instruct-sc2-concepts |
def are_elements_oriented(subgraph_elements):
"""Check wheter all the elements of a subgraph have
an orientation value `[+/-]`.
"""
for id_, orientation in subgraph_elements.items():
if orientation is None:
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
def ramp(s, width, annealing_time):
"""Schedule with a ramp shape.
Args:
s (float):
The mid-point of the ramp, as a fraction of the annealing time.
width (float):
The width of the ramp, as a fraction of the annealing time. Note
that QPUs have a maximum slope... | bigcode/self-oss-instruct-sc2-concepts |
import optparse
def LoadOptionsFromFlags(argv):
"""Parse command-line arguments.
Args:
argv: The program argument vector (excluding the script name)
Returns:
A dictionary with key-value pairs for each of the options
"""
usage_string = 'python dsplcheck.py [options] [DSPL XML file or zip archive]'
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
def create_result_dict() -> Dict:
""" Create the results dictionary """
return {"Title": None, "Issue Type": None, "Severity": None,
"CWE": None, "Vulnerable File": None, "Details": []} | bigcode/self-oss-instruct-sc2-concepts |
import six
def commalist(value):
"""
Convert a comma separated string into a list
If ``value`` is already a list or tuple it will
be returned.
"""
if isinstance(value, six.string_types):
return [v.strip() for v in value.split(',')]
if isinstance(value, (set, list)):
return ... | bigcode/self-oss-instruct-sc2-concepts |
def MaskField(**kwargs):
"""Create a new field for a :py:class:`~.KeyspacesRegion` that will write
out a mask value from a keyspace.
Parameters
----------
field : string
The name of the keyspace field to store the mask for.
tag : string
The name of the keyspace tag to store the ... | bigcode/self-oss-instruct-sc2-concepts |
def search_linear(xs, target):
""" Find and return the index of target in sequence xs """
for (i, v) in enumerate(xs):
if v == target:
return i
return -1 | bigcode/self-oss-instruct-sc2-concepts |
def check_private_exponent(a, B=512):
"""
Checks the bit length of the given private exponent.
If you've asked for a random number of bit length at least :param:`B`, but are retrieving
numbers that are smaller than said size, you might want to check your RNG.
>>> B = 8
>>> a = 0b11111111
>... | bigcode/self-oss-instruct-sc2-concepts |
def _is_removed(tensor_name, removed_op_names):
"""Determine whether the named tensor is an output of a removed op."""
for removed_op_name in removed_op_names:
if tensor_name.split(':')[0] == removed_op_name:
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def map_title_from_list(number, title_list):
"""Used during the iterative inserts in fn:write_to_db - if number matches
the number within title_list, write title to db.
:arg number: string containing RFC number
:arg title_list: list of all rfc titles from fn:get_title_list
:returns result: string ... | bigcode/self-oss-instruct-sc2-concepts |
def find_instance_of_digit(train_labels, digit):
""" find_instance_of_digit function
Find the first instance of a digit within the given labels and returns
its index.
Args
----
train_labels : np.array
list of labels
digit : Number
digit to search for
Returns
------... | bigcode/self-oss-instruct-sc2-concepts |
def get_string_content(line):
"""
Get the quoted string content from a line.
:param line: a string which contains a quoted substring
:return: the string between the quotes
"""
first_index = line.find('\"') + 1
last_index = line.rfind('\"')
content = line[first_index:last_index]
conte... | bigcode/self-oss-instruct-sc2-concepts |
def sum_2d(a):
"""
Sum all the values in a matrix together.
:param a: (list) 2D matrix containing values to be summed
:return: (int/float) sum value of the matrix.
"""
# Check if given matrices are of "list" type
if type(a) != list:
raise TypeError('Error xm01: Incorrect type, m... | bigcode/self-oss-instruct-sc2-concepts |
def number_of_tweets_per_day(df):
"""
Function will count number of tweets per day
Arguments:
takes a Pandas DataFrame as input
Returns:
a new DataFrame grouped by day
(new column 'Date') with the
number of tweets for that day
"""
df["D... | bigcode/self-oss-instruct-sc2-concepts |
def allowed_to_preview(user):
"""
Is the user allowed to view the preview?
Users are only allowed to view the preview if they are authenticated, active and staff.
:param user: A User object instance.
:return: Boolean.
"""
if (
user.is_authenticated and
user.is_active and
... | bigcode/self-oss-instruct-sc2-concepts |
def filter(nodes, labels=[]):
"""Filter nodes which matches labels"""
labels = set(labels)
filterd_nodes = {}
for k, spec in nodes.items():
node_labels = set(spec.get('labels', []))
matched_labels = labels & node_labels
if matched_labels == labels:
filterd_nodes[k] = ... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def generate_unique_key(master_key_path, url):
"""
master_key_path: str Path to the 32-byte Master Key (for S3 Encryption)
url: str S3 URL (e.g. https://s3-us-west-2.amazonaws.com/bucket/file.txt)
Returns: str 32-byte unique key generated for that URL
"... | bigcode/self-oss-instruct-sc2-concepts |
from string import digits
def remove_numbers(string: str) -> str:
"""Strips numbers from a string
Eg, a1b2c3 -> abc
Args:
string (str): String to clean
Returns:
str: Provided string without numbers
"""
return string.translate(str.maketrans("", "", digits)) | bigcode/self-oss-instruct-sc2-concepts |
import re
def add_uuid_dashes(uuid):
"""Convert a plain UUID (i.e. "65ea51744ce54bee...") to a dashed
UUID (i.e. 65ea5174-4ce5-4bee-...)
"""
if uuid is None:
return None
else:
p = re.compile(r"(\w{8})(\w{4})(\w{4})(\w{4})(\w{12})")
return p.sub(r"\1-\2-\3-\4-\5", uuid) | bigcode/self-oss-instruct-sc2-concepts |
def service(func):
"""
Service decorator
This will add a tag property to a function called 'is_service' so that
the function/method can be identified as a service.
When writing a Measurement class, any method that is to be offered as
a service can be tagged with the @service decorator
e.g.
... | bigcode/self-oss-instruct-sc2-concepts |
def transpose_list(values):
"""Transposes a list of lists. Can be used to convert from `time-major` format to `batch-major` format and vice
versa.
Example:
Input::
[[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]]
Output::
[[1, 5, 9],
... | bigcode/self-oss-instruct-sc2-concepts |
def add_or_merge(dictionary, key, values):
"""
Add or merge the values in 'values' to 'dictionary' at 'key'
"""
if key in dictionary:
if isinstance(values, list):
dictionary[key] = dictionary[key] + values
else:
dictionary[key].update(values)
else:
dic... | bigcode/self-oss-instruct-sc2-concepts |
def is_toa5(record):
""" Utility function to check if a supplied record (as generated by hievpy.search) is in TOA5 format
Input
-----
Required
- record: record object returned by the search function
Returns
-------
True or False
"""
if record['format'] == 'TOA5' and record['f... | bigcode/self-oss-instruct-sc2-concepts |
def get_icon_name(x):
"""
Returns the icon name from a CDragon path
"""
return x.split('/')[-1] | bigcode/self-oss-instruct-sc2-concepts |
def get_gz(tar):
"""Get list of files in tarfile ending with 'gz'"""
batch_results = [tar.extractfile(f) for f in tar.getmembers()
if f.name.endswith('gz')]
return batch_results | bigcode/self-oss-instruct-sc2-concepts |
import re
def max_num1(x: str)->int:
"""
Input: String
Output: Integer
Finds the maximum integer in the string
"""
c = re.findall("\d+",x)
n = map(int,c)
return max(n) | bigcode/self-oss-instruct-sc2-concepts |
def whitespace_normalize_name(name):
"""Return a whitespace-normalized name."""
return ' '.join(name.split()) | bigcode/self-oss-instruct-sc2-concepts |
def _GetSuspectedCLFoundByHeuristicForCompile(analysis):
"""For compile failure, gets the suspected revision found by heuristic."""
if not analysis or not analysis.result:
return None
for failure in analysis.result.get('failures', []):
if (failure['step_name'].lower() == 'compile' and
len(failure... | bigcode/self-oss-instruct-sc2-concepts |
def pxe_mac(mac):
"""
Create a MAC address file for pxe builds.
Add O1 to the beginning, replace colons with hyphens and downcase
"""
return "01-" + mac.replace(":", "-").lower() | bigcode/self-oss-instruct-sc2-concepts |
def getDistance(posn1, posn2):
"""Helper for getSeeds that calculates the cartesian distance between two tuple points."""
distX = (posn1[0] - posn2[0]) ** 2
distY = (posn1[1] - posn2[1]) ** 2
return (distX + distY) ** 0.5 | bigcode/self-oss-instruct-sc2-concepts |
def make_safe_filename(name):
"""Replace characters that are not allowed in windows file names."""
for char in ('/', '\\', ':', '*', '?', '"', '<', '>', '|'): # Windows illegal folder chars
if char in name:
name = name.replace(char, " ")
# replacables: ['∕','⧵' ,'˸','⁎','ॽ','“'... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def _valid_date(date_value):
"""Validate a transaction date."""
try:
transaction_date = datetime.strptime(date_value, "%d/%m/%Y")
return transaction_date is not None
except ValueError:
return False | bigcode/self-oss-instruct-sc2-concepts |
import math
def pressure_lrc ( density, r_cut ):
"""Calculates long-range correction for Lennard-Jones pressure."""
# density, r_cut, and the results, are in LJ units where sigma = 1, epsilon = 1
sr3 = 1.0 / r_cut**3
return math.pi * ( (32.0/9.0) * sr3**3 - (16.0/3.0) * sr3 ) * density**2 | bigcode/self-oss-instruct-sc2-concepts |
import torch
def load_checkpoint(checkpoint_path, model, optimizer, lr_scheduler, epoch, best_score, best_val_logs):
"""Load training states from a checkpoint file.
Args:
checkpoint_path (srt): path to the checkpoint file to load.
model (torch.nn.Module): model.
optimizer (torch.optim... | bigcode/self-oss-instruct-sc2-concepts |
def check_refs(fn):
"""Decorator to check if required references for an object
are set. If it finds missing references, it will raise an
exception. Example:
@requires("retiring", "bad_speculation", "frontend_bound")
class BackendBound(object):
@check_refs
def _compute(self, ev):
... | bigcode/self-oss-instruct-sc2-concepts |
def predicate_1(x: int) -> bool:
"""Return true if the integer is 3."""
return x == 3 | bigcode/self-oss-instruct-sc2-concepts |
def split_train(sequence, numInputs, numOutputs, numJumps):
""" Returns sets to train a model
i.e. X[0] = sequence[0], ..., sequence[numInputs]
y[0] = sequence[numInputs+1], ..., sequence[numInputs+numOutputs]
...
X[k] = sequence[k*numJumps], ..., sequence[k*numJumps+n... | bigcode/self-oss-instruct-sc2-concepts |
def runtest(name, args):
"""
Run the named test.
"""
print("\x1B[1m:: {} \x1B[0m".format(name))
if name not in globals():
print("ERROR: Unrecognized test: '{}'".format(name))
return
return globals()[name].run(args) | bigcode/self-oss-instruct-sc2-concepts |
def filter_lines(code, line_spec):
"""Removes all lines not matching the line_spec.
Args:
code The code to filter
line_spec The line specification. This should be a comma-separated
string of lines or line ranges, e.g. 1,2,5-12,15
If a line range starts with -... | bigcode/self-oss-instruct-sc2-concepts |
def max_elements(seq):
"""Return list of position(s) of largest element"""
max_indices = []
if seq:
max_val = seq[0]
for i, val in ((i, val) for i, val in enumerate(seq) if val >= max_val):
if val == max_val:
max_indices.append(i)
else:
... | bigcode/self-oss-instruct-sc2-concepts |
import textwrap
def wrap_text(text, width):
"""
Wraps text to a maximum width, keeping newlines intact.
"""
lines = []
for line in text.split('\n'):
if line:
lines += textwrap.wrap(line, width)
else:
# textwrap ignores empty lines, we want to keep them
... | bigcode/self-oss-instruct-sc2-concepts |
def isreadable(f):
"""
Returns True if the file-like object can be read from. This is a common-
sense approximation of io.IOBase.readable.
"""
if hasattr(f, 'readable'):
return f.readable()
if hasattr(f, 'closed') and f.closed:
# This mimics the behavior of io.IOBase.readable
... | bigcode/self-oss-instruct-sc2-concepts |
def find_singleton(input_dict):
"""
Given an input dictionary of sequences, find a length 1 sequence and return its key and element
"""
for key, seq in input_dict.items():
if len(seq) == 1:
return key, seq.pop()
# No length 1 sequence (e.g. singleton set) found in the input dicti... | bigcode/self-oss-instruct-sc2-concepts |
def flat_list(l):
"""
Flattens an input list made by arbitrarily nested lists.
:param l: the input list
:return: the flattened list
"""
if not isinstance(l, list):
return [l]
else:
return [e for k in l for e in flat_list(k)] | bigcode/self-oss-instruct-sc2-concepts |
def get_output_size(height, width, filter_height, filter_width, padding, stride):
"""
return (output_height, output_width)
You can see below by drawing a figure.
height + 2 * padding = filter_height + (output_height - 1) * stride
width + 2 * padding = filter_width + (output_width - 1) * stride
... | bigcode/self-oss-instruct-sc2-concepts |
def get_image_value(x, y, img):
"""Get pixel value at specified x-y coordinate of image.
Args:
x (int): horizontal pixel coordinate
y (int): vertical pixel coordinate
img (numpy.ndarray): image from which to get get pixel value
Returns:
float: pixel value at specified coord... | bigcode/self-oss-instruct-sc2-concepts |
def str_to_dict(text):
"""
This function converts a string to a dictionary
:type text: string
:param text: string to be converted
String to be converted should be as follow :
string_to_convert="key1:value1,key2:value2..."
result={'key1':'value1', 'key2':'value2'}
:rtype: dic... | bigcode/self-oss-instruct-sc2-concepts |
def get_rectangle_point_intersect(rect, pt):
"""Returns the intersection of a rectangle and point.
Parameters
----------
rect : libpysal.cg.Rectangle
A rectangle to check for an intersection.
pt : libpysal.cg.Point
A point to check ``rect`` for an intersection.
Returns
----... | bigcode/self-oss-instruct-sc2-concepts |
import click
def trim_dependent_repos(repos):
"""Remove dependent repos (an obsolete feature of this program).
Repos with 'parent-repo' in their 'openedx-release' data are removed from
the `repos` dict. A new dict of repos is returned.
"""
trimmed = {}
for r, data in repos.items():
... | bigcode/self-oss-instruct-sc2-concepts |
def check_keys_exist(vglist,my_keys):
"""
Accepts a list of dicts and checks the specified keys exist in each list element.
"""
for d in vglist:
if not all(key in d for key in my_keys):
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
def has_resistance_heat(heat_type):
"""Determines if the heat type has resistance heating capability
Parameters
----------
heat_type : str
The name of the heating type
Returns
-------
boolean
"""
if heat_type == "heat_pump_electric_backup":
return True
return F... | bigcode/self-oss-instruct-sc2-concepts |
def aic(model):
"""Given a model, calculates an AIC score."""
k = model.num_of_params
L = model.lnlikelihood()
return 2*(k-L) | bigcode/self-oss-instruct-sc2-concepts |
def hex_color_for(rgb):
"""
Convert a 3-element rgb structure to a HTML color definition
"""
opacity_shade = 0.3
return "rgba(%d,%d,%d,%f)" % (rgb[0], rgb[1], rgb[2], opacity_shade) | bigcode/self-oss-instruct-sc2-concepts |
def input_data_job_id(conf):
# type: (dict) -> str
"""Retrieve input data job id
:param dict conf: configuration object
:rtype: str
:return: job id
"""
return conf['job_id'] | bigcode/self-oss-instruct-sc2-concepts |
def transpose_callable(f):
"""Returns a callable whose output is the transposed of the input callable."""
def transposed(x):
return f(x).T
return transposed | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def unsentencise(ts: List[str]) -> str:
"""Join a list of sentences into a string"""
return ". ".join(ts) | bigcode/self-oss-instruct-sc2-concepts |
import yaml
def load_yaml(config_path):
"""Tries to load a config file from YAML.
"""
with open(config_path) as f:
return yaml.load(f, Loader=yaml.FullLoader) | bigcode/self-oss-instruct-sc2-concepts |
def eval_median_spend(simulation):
"""median spend metric for current trial
Returns:
float: Median real spending for current trial
"""
return simulation.latest_trial.trial_df['spend'].median() | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
import json
def sfn_run(session, arn, input_={}):
"""Start executing a StepFunction
Args:
session (Session): Boto3 session
arn (str): ARN of the StepFunction to execute
input_ (Json): Json input data for the first state to process
Returns:
st... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Dict
from typing import Any
import itertools
def chain(*configs: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Chain given iterable config dictionaries."""
chained_configs: List[Dict[str, Any]] = list()
for instance in itertools.product(*configs):
mer... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def batch_randint(start, batch_end):
"""
Sample k from start to end (both inclusive)
Return the same shape as batch_end
"""
return start + (torch.rand_like(batch_end.float()) * (batch_end - start + 1).float()).long() | bigcode/self-oss-instruct-sc2-concepts |
def extract_email(msg):
"""Extract all the interesting fields from an email"""
msg_obj = {}
msg_obj["from"] = msg.getheaders('From')[0]
msg_obj["to"] = msg.getheaders('To')[0]
msg_obj["subject"] = msg.getheaders('Subject')[0]
msg_obj["date"] = msg.getheaders('Date')[0]
msg_obj["contents"] = ... | bigcode/self-oss-instruct-sc2-concepts |
import re
def has_timestamp(text):
"""Return True if text has a timestamp of this format:
2014-07-03T23:30:37"""
pattern = r'[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}'
find = re.findall(pattern, text)
return bool(find)
pass | bigcode/self-oss-instruct-sc2-concepts |
def get_words(message):
"""Get the normalized list of words from a message string.
This function should split a message into words, normalize them, and return
the resulting list. For simplicity, you should split on whitespace, not
punctuation or any other character. For normalization, you should conver... | bigcode/self-oss-instruct-sc2-concepts |
def book_name_strings(bk):
"""Returns a list of the named range names in
as workbook.
Arguments:
bk {xw.Book} -- Workbook to retrieve list from.
Returns:
list -- named range names.
"""
return [nm.name for nm in bk.names] | bigcode/self-oss-instruct-sc2-concepts |
def get_text(elem, name, default=None):
"""Retrieve text of an attribute or subelement.
Parameters
----------
elem : xml.etree.ElementTree.Element
Element from which to search
name : str
Name of attribute/subelement
default : object
A defult value to return if matching a... | bigcode/self-oss-instruct-sc2-concepts |
def harmonic_mapping(fg):
"""Get all peaks from a FOOOFGroup and compute harmonic mapping on the CFs."""
f_mapping = []
for f_res in fg:
cfs = f_res.peak_params[:, 0]
if len(cfs) > 0:
f_mapping.append(list(cfs / cfs[0]))
return f_mapping | bigcode/self-oss-instruct-sc2-concepts |
def intersect(a, b):
""" Return the intersection of two lists.
Args:
a (list): A list.
b (list): Another list.
Returns (list):
The intersection of the two lists.
"""
# NOTE: Binary operator '&' is built in and returns the intersection of 2 sets.
ret... | bigcode/self-oss-instruct-sc2-concepts |
def bgr_to_rgb(bgr):
"""Converts Blue, Green, Red to Red, Green, Blue."""
return bgr[..., [2, 1, 0]] | bigcode/self-oss-instruct-sc2-concepts |
def torchcrop(x, start_idx, crop_sz):
"""
Arguments
---------
x : Tensor to be cropped
Either of dim 2 or of 3
start_idx: tuple/list
Start indices to crop from in each axis
crop_sz: tuple/list
Crop size
Returns
-------
cropped tensor
"""
dim = len(x.s... | bigcode/self-oss-instruct-sc2-concepts |
def round_int(x, *, ndim=0):
""" 先四舍五入,再取整
:param x: 一个数值,或者多维数组
:param ndim: x是数值是默认0,否则指定数组维度,批量处理
比如ndim=1是一维数组
ndim=2是二维数组
>>> round_int(1.5)
2
>>> round_int(1.4)
1
>>> round_int([2.3, 1.42], ndim=1)
[2, 1]
>>> round_int([[2.3, 1.42], [3.6]], ndim=2)
[[2... | bigcode/self-oss-instruct-sc2-concepts |
def get_river_config(fileName, noisy=False):
"""
Parse the rivers namelist to extract the parameters and their values.
Returns a dict of the parameters with the associated values for all the
rivers defined in the namelist.
Parameters
----------
fileName : str
Full path to an FVCOM R... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
from typing import List
def list_over(obj: Union[list, str], n: int) -> List[str]:
"""
Return a list of strings of length greater than n in obj,
or sublists of obj, if obj is a list.
If obj is a string of length greater than n, return a list
containing obj. Otherwise retu... | bigcode/self-oss-instruct-sc2-concepts |
def prune(d):
"""If possible, make the multi-valued mapping `d` single-valued.
If all value sets of `d` have exactly one member, remove the set layer,
and return the single-valued dictionary.
Else return `d` as-is.
"""
if all(len(v) == 1 for v in d.values()):
return {k: next(iter(v)) f... | bigcode/self-oss-instruct-sc2-concepts |
def fn_check_missing_data(df):
"""check for any missing data in the df (display in descending order)"""
return df.isnull().sum().sort_values(ascending=False) | bigcode/self-oss-instruct-sc2-concepts |
def rotate_square_counter(block, count):
"""
Return a square block after rotating counterclockwise 90° count times
"""
for _ in range(count):
block = [[block[j][i] for j in range(len(block))] for i in list(reversed(range(len(block))))]
block = [''.join(i) for i in block]
return block | bigcode/self-oss-instruct-sc2-concepts |
def Finish_to_c(self):
"""Syntax conversion for breaking a loop."""
return f"goto break_{self.targetID};" | bigcode/self-oss-instruct-sc2-concepts |
def key_by_id(mapping):
"""
Converts arrays to hashes keyed by the id attribute for easier lookup. So
[{'id': 'one', 'foo': 'bar'}, {'id': 'two', 'foo': 'baz'}]
becomes
{'one': {'id': 'one', 'foo': 'bar'}, 'two': {'id': 'two', 'foo': 'baz'}}
"""
if isinstance(mapping, list) and isins... | bigcode/self-oss-instruct-sc2-concepts |
def _match_tags(repex_tags, path_tags):
"""Check for matching tags between what the user provided
and the tags set in the config.
If `any` is chosen, match.
If no tags are chosen and none are configured, match.
If the user provided tags match any of the configured tags, match.
"""
if 'any' ... | bigcode/self-oss-instruct-sc2-concepts |
import string
def isalphanum(word):
"""
This function returns true if a word contains letters or digits
:param word: A string token to check
:return: True if the word contains letters or digits
"""
for char in word:
if char not in string.ascii_letters and char not in string.digits:
... | bigcode/self-oss-instruct-sc2-concepts |
def read_fp(filename, dtype=int):
""" read fingerprint from file
Args:
filename: <type 'str'>
Return:
chembl_id_list: <type 'list'>, a list of str
fps_list: <type 'list'>, a list of dict.
"""
chembl_id_list = []
fps_list = []
infile = open(filename, "r")
line_num = 0
for line in infile:
... | bigcode/self-oss-instruct-sc2-concepts |
def stmt_from_rule(rule_name, model, stmts):
"""Return the source INDRA Statement corresponding to a rule in a model.
Parameters
----------
rule_name : str
The name of a rule in the given PySB model.
model : pysb.core.Model
A PySB model which contains the given rule.
stmts : lis... | bigcode/self-oss-instruct-sc2-concepts |
import string
import random
def get_alphanumeric_string(str_length, **kwargs):
"""Get random alpha numeric string, default is lowercase ascii chars
Available kwargs (in order of precedence*):
uppercase_only = default is False
mixed_case = default is False
digits_only = default is Fals... | 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.