seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def escape_characters(data: bytes) -> bytes:
"""
Characters that are used for telegram control are replaced with others
so that it easier to parse the message over the wire.
Final character is never replaced.
'\x0d' -> '\x1b\x0e'
'\x1b' -> '\x1b\x1b'
'\x8d' -> '\x1b\x0f'
"""
if not ... | bigcode/self-oss-instruct-sc2-concepts |
def from_pairs(pairs):
"""Creates a new object from a list key-value pairs. If a key appears in
multiple pairs, the rightmost pair is included in the object"""
out = {}
for (k, v) in pairs:
out[k] = v
return out | bigcode/self-oss-instruct-sc2-concepts |
def spmwrite(self, method="", nmode="", inputs="", inputlabels="",
outputs="", outputlabels="", nic="", velacckey="",
fileformat="", **kwargs):
"""Calculates the state-space matrices and writes them to the SPM file.
APDL Command: SPMWRITE
Parameters
----------
method
... | bigcode/self-oss-instruct-sc2-concepts |
def relocate_h2id(soup):
"""Moves the anchor ID to the H2 tag, from the wrapper DIV."""
for h2 in soup.find_all('h2'):
div = h2.find_parent('div')
if div.has_attr('id') and not h2.has_attr('id'):
# print('Move ID: ' + div['id'])
h2['id'] = div['id']
del div['id']
# Also delete embedded... | bigcode/self-oss-instruct-sc2-concepts |
import ast
def parse_string_value(str_value):
""" parse string to number if possible
e.g. "123" => 123
"12.2" => 12.3
"abc" => "abc"
"$var" => "$var"
"""
try:
return ast.literal_eval(str_value)
except ValueError:
return str_value
except SyntaxError:
... | bigcode/self-oss-instruct-sc2-concepts |
def SmiNetDateTime(python_date):
"""
Datetime as a string in the format `YYYY-MM-DD HH:MM:SS`
Original xsd documentation: SmiNetLabExporters datum- och tidformat (ÅÅÅÅ-MM-DD TT:MM:SS).
"""
return python_date.strftime("%Y-%m-%d %H:%M:%S") | bigcode/self-oss-instruct-sc2-concepts |
def dict_filter_keys_start_with(start, row):
"""
Given a dict, returns a new dict with key-value pairs
where the key of each pair starts with start.
"""
return {k[len(start)+1:]: v for k, v in row.items() if k.startswith(start)} | bigcode/self-oss-instruct-sc2-concepts |
def make_image_black_and_white(img, threshold=127):
"""Convert an image to a black and white image."""
#convert('1') converts to black and white;
# use a custom threshold via:
# https://stackoverflow.com/a/50090612/454773
fn = lambda x : 255 if x > threshold else 0
img = img.convert('L').p... | bigcode/self-oss-instruct-sc2-concepts |
def rectangles_collide(x1, y1, w1, h1, x2, y2, w2, h2):
"""
Return whether or not two rectangles collide.
Arguments:
- ``x1`` -- The horizontal position of the first rectangle.
- ``y1`` -- The vertical position of the first rectangle.
- ``w1`` -- The width of the first rectangle.
- ``h1`` ... | bigcode/self-oss-instruct-sc2-concepts |
def give_action_choose_probability_new(episodes, episode, model):
"""
This method gives probability of choosing action according to the episode number and total number of episode.
:param episodes: total number of episodes
:param episode: current running episode
:param model: model number
:return... | bigcode/self-oss-instruct-sc2-concepts |
async def startlist() -> dict:
"""Create a mock startlist object."""
return {
"id": "startlist_1",
"event_id": "event_1",
"no_of_contestants": 8,
"start_entries": ["11", "22", "33", "44", "55", "66", "77", "88"],
} | bigcode/self-oss-instruct-sc2-concepts |
def spancmb(class_=None, **kwargs):
""" span combinator
because class is a reserved keyword in python, class_ is the first arg
kwargs keys may be any html global attribute """
cdict = {'class': class_} # put class first (sign the siren song or python preserving key order)
cdict.update(kwarg... | bigcode/self-oss-instruct-sc2-concepts |
def node_below_adjacent_elements(node, surface):
"""
node_below_adjacent_elements determines if a node is below any element adjacent to it in the surface.
Consider the following layout:
*-*-*-* Here, the nodes are shown as * and node (0,0) as X. Elements are shown as o and neighboring
|O|O|o| ele... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def sample_pdf(rays, weights, N_importance, det=False, eps=1e-5):
"""
Sample @N_importance samples from @bins with distribution defined by @weights.
from https://github.com/sxyu/pixel-nerf/blob/master/src/render/nerf.py#L120
Inputs:
rays: (N_rays, N_samples_+1) where N_samples_ is... | bigcode/self-oss-instruct-sc2-concepts |
import string
def strip_punctuation(text):
"""
Remove all punctuation from text
:param text: raw headline
:return: parsed headline
"""
if text is None:
text = ""
return text.translate(str.maketrans('', '', string.punctuation)) | bigcode/self-oss-instruct-sc2-concepts |
import requests
def get_access_token(app_id, app_secret, redirect_uri, code):
"""
This method gets the access token that helps you get
user details from facebook. The code argument is
retrieved from the url after the user has accepted
the permissions of your app from facebook
:param app_id:
... | bigcode/self-oss-instruct-sc2-concepts |
import re
def remove_br_in_ul(content):
"""
Get rid of <br> inside <ul> lists
>>> remove_br_in_ul('<ul><li>abc<br></li></ul>')
'<ul><li>abc</li></ul>'
"""
_re_content_in_pre = re.compile(r"<ul>(.*?)</ul>", re.DOTALL)
return re.sub(_re_content_in_pre, lambda match: match.group().replace('<... | bigcode/self-oss-instruct-sc2-concepts |
def traditional_constants_basal_equation(tdd):
""" Traditional basal equation with constants from ACE consensus """
a = 0.5
return a * tdd | bigcode/self-oss-instruct-sc2-concepts |
import pathlib
from typing import Dict
def table_files(sql_file: pathlib.Path) -> Dict[str, str]:
"""
Associates the name of an output file to its SQL table, by reading the
snb-load.sql script
"""
results = {}
with open(sql_file, "r", encoding="utf-8") as in_fd:
for line in in_fd:
... | bigcode/self-oss-instruct-sc2-concepts |
def argToInt(value):
""" Given a size or addresse of the type passed in args (ie 512KB or 1MB) then return the value in bytes.
In case of neither KB or MB was specified, 0x prefix can be used.
"""
for letter, multiplier in [("k", 1024), ("m", 1024 * 1024), ("kb", 1024), ("mb", 1024 * 1024), ]:
i... | bigcode/self-oss-instruct-sc2-concepts |
def col_dict_to_set(df, col, key):
"""Create a set from the values of the dictionaries given a key
Args:
df(pd.Dataframe): dataframe
col(str): column containing list of dictionaries
key(str): key to extract from the dictionaries
Returns:
A pandas Dataf... | bigcode/self-oss-instruct-sc2-concepts |
def _tensor_name_base(full_tensor_name):
"""Removes the device assignment code from a tensor.
e.g. _tensor_name_base("foo:3") => "foo"
Args:
full_tensor_name: A tensor name that is annotated with a device placement
(this is what tensor flow introspection gives).
Returns:
A name without any devic... | bigcode/self-oss-instruct-sc2-concepts |
from typing import NamedTuple
def _to_dict(conf: NamedTuple):
"""Convert nested named tuple to dict."""
d = conf._asdict()
for k in conf._fields:
el = getattr(conf, k)
if hasattr(el, '_asdict'):
d[k] = _to_dict(el)
return d | bigcode/self-oss-instruct-sc2-concepts |
import requests
import json
def vaultPutBulk(url, params, body, sessionId):
"""
Make an HTTP PUT request to Vault.
:param url: the URL to PUT
:param params: query parameters
:param body: update body
:param sessionId: vault sessionId
:return: responseStr: JSON response string from Vault A... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def to_one_hot_vector(num_class, label):
""" Converts a label to a one hot vector
:param num_class: number of object classes
:param label: integer label values
:return: a vector of the length num_class containing a 1 at position label, and 0 otherwise
"""
return torch.nn.function... | bigcode/self-oss-instruct-sc2-concepts |
def bswsa_should_halt(_seq, _stream, values, _context, _loaded_fields):
"""Halting function for :attr:`BasicStructWithSentinelArray.numbers`."""
if values and values[-1] == 0:
# Hit sentinel, remove it from the end of the array.
del values[-1]
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
import torch
def get_R_torch(angles):
"""Get rotation matrix R along verticle axis from the angle
Args:
angles (tensor[N]): In radian
Returns:
Rs (tensor[N, 3, 3])
"""
cs, ss = torch.cos(angles), torch.sin(angles)
zeros = torch.zeros(len(cs), device=angles.device)
ones = ... | bigcode/self-oss-instruct-sc2-concepts |
def fancy_join(lst, sep=", ", final_sep=" and "):
"""
Join a list using a different separator for the final element
"""
if len(lst) > 2:
head, tail = lst[:-1], lst[-1]
lst = [sep.join(head), tail]
return final_sep.join(lst) | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def datetime_fromisoformat(dts):
"""
Take an ISO format datetime string and return a datetime type.
The datetime.fromisoformat method was new in Python 3.7. This replacement
works on 3.6.9, which the author is still has on some machines.
It may work on older versions,... | bigcode/self-oss-instruct-sc2-concepts |
import yaml
def load_yaml(file_path):
"""Load a yaml file as a Python dictionary.
Args:
file_path: the absolute or relative path to the yaml file.
Returns:
the contents of the yaml file, as a Python dictionary.
"""
return yaml.load(open(file_path, "r"), Loader=yaml.Loader) | bigcode/self-oss-instruct-sc2-concepts |
def capitalize(s):
"""
Capitalize the first char of a string, without
affecting the rest of the string.
This differs from `str.capitalize` since the latter
also lowercases the rest of the string.
"""
if not s:
return s
return ''.join([s[0].upper(), s[1:]]) | bigcode/self-oss-instruct-sc2-concepts |
def get_normalized_list(input_str):
""" Returns the comma-separated input string as a normalized list. """
items = input_str.split(",")
total = 0.0
for item in items:
total += float(item)
temp_total = 0
for index, item in enumerate(items):
temp_total += float(item)
items[... | bigcode/self-oss-instruct-sc2-concepts |
def cpf_is_digits(value):
"""
This function receives the Brazilian CPF and returns True if it contains only digits or False if not.
:param value: A string with the number of Brazilian CPF
:return: True or False
"""
if value.isdigit():
return True
else:
return False | bigcode/self-oss-instruct-sc2-concepts |
import six
def key_by_value_dict(in_dict, value):
""" Reverse dictionary lookup.
Args:
in_dict (dict): Input dict.
value: Lookup value.
Returns:
Key in ``in_dict`` containing ``value`` if found.
>>> key_by_value_dict({'key1': 42, 'key2': 'forty-two'},... | bigcode/self-oss-instruct-sc2-concepts |
def moyenne_trois_nb(a : float, b : float, c : float) -> float:
"""Retourne la moyenne arithmétique des trois nombres a, b et c.
"""
return (a + b + c) / 3.0 | bigcode/self-oss-instruct-sc2-concepts |
from functools import reduce
def solve(n, ar):
"""
Return the sum of the elements in array, ar of size n.
This is the same problem as "Simple Array Sum" but the twist is that the
elements of the array are in the order of 10^10. In python, however, values
are autocast to whatever type/size they nee... | bigcode/self-oss-instruct-sc2-concepts |
def bin_to_dec(bin_str):
"""Convert a string of bits to decimal."""
result = 0
for i, bit in enumerate(bin_str[::-1]):
result += int(bit) * 2**i
return result | bigcode/self-oss-instruct-sc2-concepts |
def purge_spikes_beyond_tracking(spike_train, tracking_ts, full_purge=True):
"""
Parameters
----------
spike_train : np.ndarray
Spike times in seconds.
tracking_ts : np.ndarray (2, )
The start and end of tracking relative to sessions start.
full_purge : bool
Remove spikes... | bigcode/self-oss-instruct-sc2-concepts |
def apply_antialiasing(kernel, kernel_width, scale_factor,
antialiasing):
"""
Antialiasing is "stretching" the field of view according to the scale
factor (only for downscaling). This is produces the low-pass filtering.
This requires modifying both the interpolation (st... | bigcode/self-oss-instruct-sc2-concepts |
def _iterateTrixelFinder(pt, parent, max_level):
"""
Method to iteratively find the htmid of the trixel containing
a point.
Parameters
----------
pt is a Cartesian point (not necessarily on the unit sphere)
parent is the largest trixel currently known to contain the point
max_level is... | bigcode/self-oss-instruct-sc2-concepts |
def netids_above_cutoff(grades, cutoff):
"""Returns list of netids with grades above or equal cutoff
Precondition: grades has netids as keys, ints as values.
cutoff is an int."""
netid = []
for key in grades.keys():
if grades[key] >= cutoff:
netid.append(key)
return netid | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def PBKDF2(self, mnemonic, salt=""):
"""
Uses the PBKDF2 key-stretching function to stretch the mnemonic to a 512-bit value. The use
of salt is optional
Parameters:
mnemonic (String): the mnemonic code words to stretch
salt (String): An addi... | bigcode/self-oss-instruct-sc2-concepts |
def update_store(coin_store1, coin_store2):
"""Updates the contents of a coin store with values from another store."""
for coin_type, coin_num in coin_store2.items():
coin_store1[coin_type] += coin_num
return coin_store1 | bigcode/self-oss-instruct-sc2-concepts |
def user_converts(predicted_value):
"""
Converts the predicted value into text and styles for easy visualization
:param predicted_value:
:return:
"""
style = {"border-radius": "20px", "padding": "10px", "vertical-align": "middle", "margin": "auto"}
if predicted_value == 'No Value':
... | bigcode/self-oss-instruct-sc2-concepts |
def tuples_to_dict(pairs, verbose=False):
"""
Take a list of paired tuples and convert to a dictionary
where the first element of each tuple is the key and the
second element is the value.
"""
d={}
for (k, v) in pairs:
d[k] = v
if verbose:
if isinstance(v,float):... | bigcode/self-oss-instruct-sc2-concepts |
def _append_docstring(func, supplement, insert_in="Parameters", at_end=True):
"""
Local helper to automate text insertions in docstrings
Parameters
----------
func : callable
Typically a (wrapped) Syncopy metafunction such as :func:`~syncopy.freqanalysis`
supplement : str
Te... | bigcode/self-oss-instruct-sc2-concepts |
def get_float(prompt, lower_bound, upper_bound):
"""Prompt the user for a number and return the number as a float.
Parameters
prompt: A string to display to the user.
lower_bound: The lowest (smallest) number that the user may enter.
upper_bound: The highest (largest) number that the us... | bigcode/self-oss-instruct-sc2-concepts |
import re
def parse_circle(msg):
"""Parse the message from CIRCLE and return the line numbers"""
matches = re.findall(r"LINE NO.=\s*(\d*)", msg)
if matches:
return [int(match) for match in matches] | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def _str2list(s: str) -> List[str]:
"""Converts str into list - use for list of OCLC numbers"""
return [n.strip() for n in s.split(",")] | bigcode/self-oss-instruct-sc2-concepts |
import re
def escape_name(name):
"""Escaped wheel name as specified in :pep:`427#escaping-and-unicode`."""
return re.sub(r"[^\w\d.]+", "_", name, flags=re.UNICODE) | bigcode/self-oss-instruct-sc2-concepts |
def StrNoneChk(fld):
""" Returns a blank string if none """
if fld is None:
return ""
return str(fld) | bigcode/self-oss-instruct-sc2-concepts |
def get_coordinates_here(response):
"""
Returns a tuple with the lat/long
:param response: dict - The here response object
:return: double, double
"""
try:
lat = response["Response"]["View"][0]["Result"][0]["Location"][
"NavigationPosition"
][0]["Latitude"]
lo... | bigcode/self-oss-instruct-sc2-concepts |
def add_residue_to_dfix(dfix_head, resinum):
"""
Add a residue to a list of DFIX/DANG restraints
DFIX 1.234 C1 C2 -> DFIX 1.234 C1_4 C2_4
>>> add_residue_to_dfix(['DFIX 1.456 C1 C2', 'DFIX 1.212 C3 C4'], 4)
['DFIX 1.456 C1_4 C2_4\\n', 'DFIX 1.212 C3_4 C4_4\\n']
>>> add_residue_to_dfix(['DF... | bigcode/self-oss-instruct-sc2-concepts |
def field_occurrence_predicate(field, args):
"""Return a function that checks for the occurrence of a field."""
newfield = field.lower() if args.ignore_case else field
def _field_occurrence(entry):
return bool(getattr(entry, newfield, None))
return _field_occurrence | bigcode/self-oss-instruct-sc2-concepts |
def _bit_is_set(bit_str: str, i: int) -> bool:
"""
Private helper function to check whether the i-th bit in the given bit
string is set.
:param bit_str: str
:param i: int
:return: bool
"""
return bit_str[i] == '1'
# Running time complexity: O(1) | bigcode/self-oss-instruct-sc2-concepts |
def S_ISDOOR(mode): # real signature unknown; restored from __doc__
"""
S_ISDOOR(mode) -> bool
Return True if mode is from a door.
"""
return False | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Any
def peek(array: List[Any]) -> Any:
"""
Returns the last element in the input array. Similar to the built-in
Array.pop method, except that it does not remove the last element.
This method is a convenient shorthand for array[array.length - 1].
"""
r... | bigcode/self-oss-instruct-sc2-concepts |
def _to_python_str(s):
""" Convert to Python string """
if isinstance(s, bytes):
return s.decode('utf-8')
else:
return s | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
def read_token() -> Union[str, None]:
"""
Reads token from the saved config file
Returns:
token string from file (or None if missing/invalid)
"""
try:
with open("config/token", "r") as file:
return file.readline().rstrip()
except Exception ... | bigcode/self-oss-instruct-sc2-concepts |
def add_user_to_groups(uname, grpstr, groups=["lsst_lcl", "jovyan"]):
"""Take a user name (a string) and a base group file (as a string) and
inject the user into the appropriate groups, given in the groups
parameter (defaults to 'lsst_lcl' and 'jovyan'). Returns a string."""
glines = grpstr.split("\n")... | bigcode/self-oss-instruct-sc2-concepts |
import re
def _replace_version(package_str, new_version):
"""
replaces the version tag in contents if there is only one instance
:param package_str: str contents of package.xml
:param new_version: str version number
:returns: str new package.xml
:raises RuntimeError:
"""
# try to repl... | bigcode/self-oss-instruct-sc2-concepts |
def tocreset(I, Ipickup, TD, curve="U1", CTR=1):
"""
Time OverCurrent Reset Time Function.
Function to calculate the time to reset for a TOC
(Time-OverCurrent, 51) element.
Parameters
----------
I: float
Measured Current in Amps
Ipickup: float
... | bigcode/self-oss-instruct-sc2-concepts |
def add_make_abundance_io_arguments(arg_parser):
"""Add io arguments to parser."""
helpstr = "Input group file which associates collapsed isoforms with reads."
arg_parser.add_argument("group_filename", type=str, help=helpstr)
helpstr = "Input pickle file (e.g., hq_lq_pre_dict.pickle) which maps HQ " + ... | bigcode/self-oss-instruct-sc2-concepts |
def remove_quotes(arg):
"""
This function returns two values:
- The treated string (i.e., without surrounding quotes)
- A boolean value informing whether it removed any quotes or not
Note that it will only remove anything if the quotes at each end match.
Therefore, strings like "foo' will be returned as they are... | bigcode/self-oss-instruct-sc2-concepts |
def is_video_file(filename):
""" Check if file is a video
:param filename: file name string
:return: Boolean toggle
"""
return any(filename.endswith(extension) for extension in ['.mp4', '.avi', '.mpg', '.mkv', '.wmv', '.flv']) | bigcode/self-oss-instruct-sc2-concepts |
import six
def convert_id36_to_numeric_id(id36):
"""Convert strings representing base36 numbers into an integer."""
if not isinstance(id36, six.string_types) or id36.count("_") > 0:
raise ValueError("must supply base36 string, not fullname (e.g. use "
"xxxxx, not t3_xxxxx)")
... | bigcode/self-oss-instruct-sc2-concepts |
def normalize_df(series):
"""convenience function to normalize a signal
(i.e., rescale to range from 0 to 1)
"""
series_norm = (series - series.min()) / (series.max() - series.min())
return series_norm | bigcode/self-oss-instruct-sc2-concepts |
def svid2gnssid(svid) -> int:
"""
Derive gnssId from svid numbering range.
:param int svid: space vehicle ID
:return: gnssId as integer
:rtype: int
"""
if 120 <= svid <= 158:
gnssId = 1 # SBAS
elif 211 <= svid <= 246:
gnssId = 2 # Galileo
elif (159 <= svid <= 163... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def compute_hash(filename):
"""Returns the MD5 hash of the specified file"""
with open(filename, 'r') as f:
contents = f.read().encode('utf-8')
return hashlib.md5(contents).digest() | bigcode/self-oss-instruct-sc2-concepts |
import json
import base64
def get_service_account_cred_from_key_response(key_response):
"""
Return the decoded private key given the response from
`create_service_account_key()`. This return from this function is the
JSON key file contents e.g. response can be placed directly in file
and be used a... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Tuple
def get_new_gatecharacterization_range(
current_valid_ranges: List[Tuple[float, float]],
safety_voltage_ranges: List[Tuple[float, float]],
range_update_directives: List[str],
) -> List[Tuple[float, float]]:
"""Determines new voltage range for a subseque... | bigcode/self-oss-instruct-sc2-concepts |
import torch
import math
def encode_μ_law(x: torch.Tensor, μ: int = 255, cast: bool = False)\
-> torch.Tensor:
"""
Encodes the input tensor element-wise with μ-law encoding
Args:
x: tensor
μ: the size of the encoding (number of possible classes)
cast: whether to cast to in... | bigcode/self-oss-instruct-sc2-concepts |
def to_minimal_df(df_in):
"""
Extracts a minimal df partof the given dataframe to be used with the
implemented machine learning workflow. Also ensures that the indices are
compareable
"""
df1 = df_in.copy().reset_index()
if "Modified sequence" in df_in.columns:
df2 = df_in[["Sequenc... | bigcode/self-oss-instruct-sc2-concepts |
def get_FTPdetect_coordinates(FTPdetect_file_content, ff_bin, meteor_no = 1):
""" Returns a list of FF*.bin coordinates of a specific bin file and a meteor on that image as a list of tuples e.g. [(15, 20), (16, 21), (17, 22)] and the rotation angle of the meteor.
"""
if int(FTPdetect_file_content[0].split(... | bigcode/self-oss-instruct-sc2-concepts |
def mirror(pt: float, delta: float):
"""Mirrors a value in a numberline
Args:
pt : real value in numberline
delta: value to mirror
Returns:
pt - delta, pt + delta
"""
return pt - delta, pt + delta | bigcode/self-oss-instruct-sc2-concepts |
def cw310_params(
tags = [],
timeout = "moderate",
local = True,
args = [
"--exec=\"console -q -t0\"",
"--exec=\"bootstrap $(location {test_bin})\"",
"console",
"--exit-failure=FAIL",
"--exit-success=PASS",
"--timeou... | bigcode/self-oss-instruct-sc2-concepts |
import importlib
def find_function(search_def):
"""
Dynamically load the function based on the search definition.
:param str search_def: A string to tell us the function to load, e.g.
module:funcname or module.path:class.staticmethod
:raises ValueError: In case configuratio... | bigcode/self-oss-instruct-sc2-concepts |
def generate_matrix(dim):
"""Generate the matrix with enumarated elements.
Args:
dim: Dimension of the matrix.
Returns:
Generated matrix as a nested list.
"""
matr = []
for i in range(dim):
# Start by 1 and increase the number for each new element by one.
matr.a... | bigcode/self-oss-instruct-sc2-concepts |
def pack(join, alist):
"""Interleave a list with a value
This function interleaves a list of values with the joining
element.
Params:
join -- The value to be interleaved within the list
alist -- The supplied list
Returns:
A new list
pack("a",[1,2,3,4]) ==> ["a",1... | bigcode/self-oss-instruct-sc2-concepts |
import re
def read_d1_letter(fin_txt):
"""Reads letter aliases from a text file created by GoDepth1LettersWr."""
go2letter = {}
re_goid = re.compile(r"(GO:\d{7})")
with open(fin_txt) as ifstrm:
for line in ifstrm:
mtch = re_goid.search(line)
if mtch and line[:1] != ' ':... | bigcode/self-oss-instruct-sc2-concepts |
def _has_numbers(text):
""" Checks if any characters in the input text contain numbers """
return any(char.isdigit() for char in text) | bigcode/self-oss-instruct-sc2-concepts |
def expect_lit(char, buf, pos):
"""Expect a literal character at the current buffer position."""
if pos >= len(buf) or buf[pos] != char:
return None, len(buf)
return char, pos+1 | bigcode/self-oss-instruct-sc2-concepts |
def exactly(length:int) -> str:
""" Match the previous pattern exactly `length` times.
>>> import superexpressive as se
>>> se.exactly(4)
'{4}'
>>> import superexpressive as se
>>> se.DIGIT + se.exactly(6)
'\\\\d{6}'
"""
return f"{{{length}}}" | bigcode/self-oss-instruct-sc2-concepts |
def make_save_folder(hyps):
"""
Creates the save name for the model.
hyps: dict
keys:
exp_name: str
exp_num: int
search_keys: str
"""
save_folder = "{}/{}_{}".format(hyps['exp_name'],
hyps['exp_name'],
... | bigcode/self-oss-instruct-sc2-concepts |
import textwrap
def format_helptext(text):
"""Format help text, including wrapping."""
return "\n".join(textwrap.wrap(text)) | bigcode/self-oss-instruct-sc2-concepts |
def _energy_test_statistic_coefficient(n, m):
"""Coefficient of the test statistic."""
return n * m / (n + m) | bigcode/self-oss-instruct-sc2-concepts |
def mul(c1, val):
"""Multiplies an encrypted counter by a public value"""
a1, b1 = c1
return (val*a1, val*b1) | bigcode/self-oss-instruct-sc2-concepts |
def FormatSubversionPropertyChanges(filename, props):
"""Returns Subversion's 'Property changes on ...' strings using given filename
and properties.
Args:
filename: filename
props: A list whose element is a (svn_prop_key, svn_prop_value) pair.
Returns:
A string which can be used in the patch file ... | bigcode/self-oss-instruct-sc2-concepts |
def try_attrs(obj, *attrs, **kwargs):
"""Try to find an available attribute.
Args:
obj (object): Object to get the attribute value for.
*attrs (tuple/str): Tuple of different string attribute names to try (These names may include '.' attributes).
default (object)[None]: Default Value to... | bigcode/self-oss-instruct-sc2-concepts |
def groupby(iterable, key=None):
"""
Group items from iterable by key and return a dictionary where values are
the lists of items from the iterable having the same key.
:param key: function to apply to each element of the iterable.
If not specified or is None key defaults to identity function and... | bigcode/self-oss-instruct-sc2-concepts |
def make_broadcastable(v, X):
"""Returns a view of `v` that can be broadcast with `X`.
If `v` is a one-dimensional tensor [N] and `X` is a tensor of shape
`[N, ..., ]`, returns a view of v with singleton dimensions appended.
Example:
`v` is a tensor of shape `[10]` and `X` is a tensor of shape... | bigcode/self-oss-instruct-sc2-concepts |
def point(value):
"""
Convert an integer to a string containing commas every three digits.
For example, 3000 becomes '3,000' and 45000 becomes '45,000'.
"""
return "{:20,.2f}".format(value) | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def multiindex_iterator (shape, *, melt_1_tuple=False):
"""
Provides a tuple-valued iterator to iterate over all multi-indices with given shape.
For example, if shape is (2,3), then the iterated sequence is:
(0,0), (0,1), (0,2), (1,0), (1,1), (1,2).
If len(shape) is 1 and me... | bigcode/self-oss-instruct-sc2-concepts |
def filter_and_sort(file_list):
""" Out of a list of file names, returns only the ones ending by
'.py', ordered with increasing file name length.
"""
file_list = [filename for filename in file_list
if filename.endswith('.py')]
def key(item):
return len(item)
... | bigcode/self-oss-instruct-sc2-concepts |
def getComboIndex(combo_box, label, ignore_casing=False):
"""
This will return the index of the first matching label within a combo
box qwidget.
If no label is found 0 is returned
:param combo_box: Widget to iterate through
:type combo_box: QComboBox
:param label: The combo label to match... | bigcode/self-oss-instruct-sc2-concepts |
def read_table (lines):
"""Reads to the next divider line.
Read lines are returned, 'lines' is reduced to everything remaining.
"""
table_lines = []
while len(lines):
popline = lines[0]
lines = lines[1:]
if popline[:6] == "======":
break
table_lines +... | bigcode/self-oss-instruct-sc2-concepts |
def arch_handler(value, **kwargs):
"""
Return a Package URL qualifier for the arch.
"""
return {'qualifiers': 'arch={}'.format(value)} | bigcode/self-oss-instruct-sc2-concepts |
def convert_tags(tags):
"""Will convert tags so the article can be uploaded to dev.to. This involves removing the `-` and making the tag
lowercase.
Args:
tags (list): The list of tags to convert.
Returns:
list: The list of converted tags
"""
new_tags = []
for tag in tags:
... | bigcode/self-oss-instruct-sc2-concepts |
def shall_exclude_diagnostic_message(message):
"""Exclude certain diagnostics messages"""
exclusion_list = [
"-fno-canonical-system-headers",
"-Wunused-but-set-parameter",
"-Wno-free-nonheap-object",
"-Werror=init-list-lifetime",
"-Werror=class-conversion",
]
retu... | bigcode/self-oss-instruct-sc2-concepts |
def slurp(f):
"""
Returns file content as string
"""
fd = open(f)
buf = fd.readlines()
fd.close()
return ''.join(buf) | 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.