seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def c_to_f(temp):
"""
Convert celcius temperature to fahrenheit.
"""
return temp * 1.8 + 32 | bigcode/self-oss-instruct-sc2-concepts |
import string
import secrets
def generate_password(length=12):
"""Generates a random password
Args:
length (int, optional): Length of the generated password. Defaults to 12.
Returns:
str: The output generated password
"""
req_str = string.ascii_letters + string.digits
secure... | bigcode/self-oss-instruct-sc2-concepts |
def max_run(_b, _x):
"""Determine the length of the maximum run of b's in vector x.
Parameters
----------
b: int
Integer for counting.
x: array
Vector of integers.
Returns
-------
max: int
Length of maximum run of b's.
"""
# Initialize counter
_max ... | bigcode/self-oss-instruct-sc2-concepts |
def ssh_cmd_container_instance(detail) -> str:
"""SSH command to access a ecs2 instance by id."""
return f"TERM=xterm ssh {detail['ec2InstanceId']}" | bigcode/self-oss-instruct-sc2-concepts |
def get_tmin_tmax(ct_idx, chop_times, sfreq):
"""
Get tmin and tmax for the chop interval based on the
time points given by chop_times.
Parameters:
-----------
ct_idx : int
Index corresponding to chop_times.
chop_times : list of float
List with the time points of when to cho... | bigcode/self-oss-instruct-sc2-concepts |
import time
def datetime2ts(dt):
""" Convert a `datetime` object to unix timestamp (seconds since epoch).
"""
return int(time.mktime(dt.timetuple())) | bigcode/self-oss-instruct-sc2-concepts |
def sreprlow(s):
"""Squash unicode and return the repr() of string `s` as lower case."""
return repr(str(s)).lower() | bigcode/self-oss-instruct-sc2-concepts |
def FormatThousands(value):
"""Format a numerical value, inserting commas as thousands separators.
Args:
value: An integer, float, or string representation thereof.
If the argument is a float, it is converted to a string using '%.2f'.
Returns:
A string with groups of 3 digits before the decimal po... | bigcode/self-oss-instruct-sc2-concepts |
def get_ligand_filetype(ligand_filename):
"""Returns the filetype of ligand."""
if ".mol2" in ligand_filename:
return "mol2"
elif ".sdf" in ligand_filename:
return "sdf"
elif ".pdbqt" in ligand_filename:
return "pdbqt"
elif ".pdb" in ligand_filename:
return "pdb"
else:
raise ValueError("... | bigcode/self-oss-instruct-sc2-concepts |
def _check_value(value):
"""Convert the provided value into a boolean, an int or leave it as it."""
if str(value).lower() in ["true"]:
value = True
elif str(value).lower() in ["false"]:
value = False
elif str(value).isdigit():
value = int(value)
return value | bigcode/self-oss-instruct-sc2-concepts |
def getdiffmeta(diff):
"""get commit metadata (date, node, user, p1) from a diff object
The metadata could be "hg:meta", sent by phabsend, like:
"properties": {
"hg:meta": {
"date": "1499571514 25200",
"node": "98c08acae292b2faf60a279b4189beb6cff1414d",
"u... | bigcode/self-oss-instruct-sc2-concepts |
import re
from datetime import datetime
def clean_title_input(title, draft=False):
"""Convert a string into a valide Jekyll filename.
Remove non-word characters, replace spaces and underscores with dashes,
and add a date stamp if the file is marked as a Post, not a Draft.
Args:
title (string... | bigcode/self-oss-instruct-sc2-concepts |
def _find_node(state, node_id_or_label):
""" Finds a node according to its ID (if integer is
provided) or label (if string is provided).
:param node_id_or_label Node ID (if int) or label (if str)
:return A nodes.Node object
"""
if isinstance(node_id_or_label, str):
for n i... | bigcode/self-oss-instruct-sc2-concepts |
def _subsample( X, ind):
""" like X[ind,:] but works in case X has size (n,) """
if X.ndim == 1:
y = X[ind]
elif X.ndim == 2:
y = X[ind,:]
else:
raise ValueError("Expected 1D or 2D array")
return y | bigcode/self-oss-instruct-sc2-concepts |
def _make_task_name(cls, addons=None):
"""Makes a pretty name for a task class."""
base_name = ".".join([cls.__module__, cls.__name__])
extra = ''
if addons:
extra = ';%s' % (", ".join([str(a) for a in addons]))
return base_name + extra | bigcode/self-oss-instruct-sc2-concepts |
def _test2(num1, num2):
"""Sample function for TestCase.
Returns the supplied values.
Args:
num1: number 1
num2: number 2
Returns:
float: sum of number 1 and 2
"""
return float(num1) + float(num2) | bigcode/self-oss-instruct-sc2-concepts |
import six
def collect_namespaces(root_spec):
"""Constructs a set of namespaces in a given ElementSpec.
Args:
root_spec: An `ElementSpec` for the root element in the schema.
Returns:
A set of strings specifying the names of all the namespaces that are present
in the spec.
"""
findable_namespac... | bigcode/self-oss-instruct-sc2-concepts |
def school2nation(id_num):
"""
Takes school id, returns nation id of the school.
"""
if id_num < 97100000:
return id_num // 100000 * 10000
if id_num < 97200000:
return 7240000
if id_num < 97400000:
return 8400000
return 320100 | bigcode/self-oss-instruct-sc2-concepts |
def pybb_posted_by(post, user):
"""
Check if the post is writed by the user.
"""
return post.user == user | bigcode/self-oss-instruct-sc2-concepts |
import torch
def shearx_grid(output_size, ulim=(-1, 1), vlim=(-5, 5), out=None, device=None):
"""Horizontal shear coordinate system.
Args:
output_size: (int, int), number of sampled values for the v-coordinate and u-coordinate respectively
ulim: (float, float), Cartesian y-coordinate limi... | bigcode/self-oss-instruct-sc2-concepts |
import pickle
def get_ibc_data(use_neutral=False,
use_subsampling=False,
return_subsampling_depths=False,
labels=(0, 1, 2)):
"""
Samples the annotated IBC data. This dataset can be described
more here. http://www.cs.umd.edu/~miyyer/ibc/.
This dataset... | bigcode/self-oss-instruct-sc2-concepts |
def tokens2options(tokens):
"""Split the list of tokens into the options it specifies, even if
there is a single option.
Arguments:
`tokens` -- the list of tokens to split, as provided by the tokenizer.
Returns:
A list of options, suitable for parsing.
"""
options = []
option = []
... | bigcode/self-oss-instruct-sc2-concepts |
def threshold_RMSE(upper_bound, lower_bound, q=3):
"""Compute threshold for RMSE metric.
Args:
upper_bound (int): Upper bound of regression outputs
lower_bound (int): lower bound of regression outputs
q (int): Quantification parameter
Returns:
threshold (float): The minimal... | bigcode/self-oss-instruct-sc2-concepts |
def capitalize_correct(phrase):
"""
Capitalizes words in a string, avoiding possessives being capitalized
"""
phrase = phrase.strip()
return " ".join(w.capitalize() for w in phrase.split()) | bigcode/self-oss-instruct-sc2-concepts |
def parseSecondsIntoReadableTime(seconds):
"""Generate a string based on seconds having the format "m:s:cs"."""
minutes = seconds / 60
absoluteMinutes = int(minutes)
seconds = (minutes - absoluteMinutes) * 60
absoluteSeconds = int(seconds)
m = str(absoluteMinutes)
if absoluteMinutes <= 9:
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Any
from warnings import warn
def has_license_and_update(data: Dict[str, Any]) -> bool:
"""Check if license header exists anywhere in notebook and format.
Args:
data: object representing a parsed JSON notebook.
Returns:
Boolean: True if notebook contains the ... | bigcode/self-oss-instruct-sc2-concepts |
from pkg_resources import get_distribution, DistributionNotFound
def distribution_version(name):
"""try to get the version of the named distribution,
returs None on failure"""
try:
dist = get_distribution(name)
except DistributionNotFound:
pass
else:
return dist.version | bigcode/self-oss-instruct-sc2-concepts |
def nD0_active(N, vzero, dr, L):
"""
Returns product of particle density n = N/L^2 and active diffusion constant
D_0 = vzero^2/2*dr.
Parameters
----------
N : int or float
Number of particles.
vzero : float
Self-propelling velocity.
dr : float
Rotation diffusion ... | bigcode/self-oss-instruct-sc2-concepts |
def _val_to_bool(val):
"""Convert a text representation to a bool."""
if val == 'true':
return True
else:
return False | bigcode/self-oss-instruct-sc2-concepts |
import torch
def getTheLargestComponent(affinity_mat: torch.Tensor, seg_index: int, device: torch.device):
"""
Find the largest affinity_mat connected components for each given node.
This is for checking whether the affinity_mat is fully connected.
Args:
affinity_mat: (torch.tensor)
... | bigcode/self-oss-instruct-sc2-concepts |
def rgb_from_int(val):
"""Return an RGB tuple converted from an int in the range [0, 0xffffff]."""
return tuple([
((val >> 16) & 0xff) / 0xff,
((val >> 8) & 0xff) / 0xff,
(val & 0xff) / 0xff]) | bigcode/self-oss-instruct-sc2-concepts |
import requests
def exchange_token(refresh_token, token_endpoint, client_id):
"""Exchange token for access token."""
response = requests.post(
token_endpoint,
data={
'grant_type': 'refresh_token',
'client_id': client_id,
'refresh_token': refresh_token,
... | bigcode/self-oss-instruct-sc2-concepts |
from bs4 import BeautifulSoup
import requests
def get_soup(url: str) -> BeautifulSoup:
"""
Generic BeautifulSoup page scraping starter code
:param url: String, the url of the page to scrape
:return: BeautifulSoup object
"""
try:
page: requests.Response = requests.get(url)
soup:... | bigcode/self-oss-instruct-sc2-concepts |
import re
def detect_file_content(content: str, f: str="/etc/passwd") -> bool:
""" Detect specific file content in content
:param str content: file content that should be analyzed
:param str f: file that the content should be compared with
:return bool: True if the content was recognized, False other... | bigcode/self-oss-instruct-sc2-concepts |
def should_be_zipped(input_file, input_files):
"""
Determine whether a given input file should be included in the zip.
Compiler includes and target files should only be included if there is
no compiler info file present.
"""
return (input_file in ['metadata.json', 'compiler_info.json']
... | bigcode/self-oss-instruct-sc2-concepts |
def get_idx_via_binary_search(nums: list[int], target: int) -> int:
"""Returns the index of target if it exists, otherwise -1
Complexity:
n = len(nums)
Time: O(logn)
Space: O(1)
Args:
nums: array of integers sorted in ascending order
target: element for which to sea... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def gaussian_sample(mu, sigma):
""" Sample a gaussian variable using the reparametrization trick.
Arguments:
mu (torch.Tensor): Mean.
sigma (torch.Tensor): Standard deviation. Same size as mu.
Returns:
z (torch.Tensor): Samples. Same size as mean.
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def compare_digest(a, b):
"""
** From Django source **
Run a constant time comparison against two strings
Returns true if a and b are equal.
a and b must both be the same length, or False is
returned immediately
"""
if len(a) != len(b):
return False
result = 0
for ch_a, ... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
import time
import requests
def stock_js_weibo_nlp_time() -> Dict:
"""
https://datacenter.jin10.com/market
:return: 特定时间表示的字典
:rtype: dict
"""
url = "https://datacenter-api.jin10.com/weibo/config"
payload = {"_": int(time.time() * 1000)}
headers = {
"aut... | bigcode/self-oss-instruct-sc2-concepts |
def square_this(x):
"""Return the square of a number."""
return x**2 | bigcode/self-oss-instruct-sc2-concepts |
async def assert_reply_matches(self, contents: str, regex):
""" Send a message and wait for a response. If the response does not match a regex, fail the test.
Requires a properly formatted Python regex ready to be used in the ``re`` functions.
:param str contents: The content of the trigger message. (A co... | bigcode/self-oss-instruct-sc2-concepts |
def list_apim_api(client, resource_group_name, service_name):
"""List all APIs of an API Management instance. """
return client.api.list_by_service(resource_group_name, service_name) | bigcode/self-oss-instruct-sc2-concepts |
def remote_bazel_options(crosstool_top):
"""Returns bazel options for the "remote" execution strategy."""
k8 = [
"--cpu=k8",
"--host_cpu=k8",
"--crosstool_top=" + crosstool_top,
"--define=EXECUTOR=remote",
]
return k8 + [
"--spawn_strategy=remote",
"--genrule_strategy=remote"... | bigcode/self-oss-instruct-sc2-concepts |
def get_mode_H_array(mode_H, mode_MR, mode_OR):
"""暖房の運転モードを取得する
Args:
mode_H(str): 暖房方式
mode_MR(str): 主たる居室の運転方法 (連続運転|間歇運転)
mode_OR(str): その他の居室の運転方法 (連続運転|間歇運転)
Returns:
tuple: 暖房の運転モード
"""
# 運転モード(暖房)
if mode_H == '住戸全体を連続的に暖房する方式':
# 全館連続
return tu... | bigcode/self-oss-instruct-sc2-concepts |
def is_short_info(obj):
"""Return whether the object is a short representation of a dataset"""
fields = ['bodySize', 'bodyRows', 'bodyFormat', 'numErrors', 'metaTitle',
'commitTime']
return bool(set(obj) & set(fields)) | bigcode/self-oss-instruct-sc2-concepts |
def compute_average_bits(encodings, frequency):
"""
Compute the average storage bits of the current layer after Huffman Coding.
:param 'encodings': Encoding map mapping each weight parameter to its Huffman coding.
:param 'frequency': Frequency map mapping each weight parameter to the total number of its... | bigcode/self-oss-instruct-sc2-concepts |
def split_list(ls, sep):
"""
Split list similarly to split string, according to some separator
"""
ret = []
cur = []
for x in ls:
if (x != sep):
cur.append(x)
elif cur:
ret.append(cur)
cur = []
if cur:
ret.append(cur)
return ret | bigcode/self-oss-instruct-sc2-concepts |
def get_function_indent(line: str) -> int:
"""
Get function indents from begging of the file.
"""
first_function_entrance = line.index('def')
indents = line[:first_function_entrance]
indents_space_count = len(indents)
return indents_space_count | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def existing_git_submodule(path: Path) -> bool:
"""Check if a git submodule exists
:param Path path: Submodule path
:return: True, if .git file exists inside path
"""
return Path(path / '.git').is_file() | bigcode/self-oss-instruct-sc2-concepts |
def round_odd(x):
"""Round X to nearest odd integer."""
return int(x + 1 - x % 2) | bigcode/self-oss-instruct-sc2-concepts |
def consensus_decision(consensus):
""" Given a consensus dict, return list of candidates to delete/archive.
"""
delete = []
archive = []
for k, v in consensus.items():
tags = v['tags']
if 'delete' in tags or 'rfi' in tags:
delete.append(k)
elif 'archive' in tags ... | bigcode/self-oss-instruct-sc2-concepts |
def _input_wrap(prompt, default=None):
"""
Run input() with formatted prompt, and return
The while loop can be used to ensure correct output
"""
understood = False
while not understood:
result = input(prompt.format(default=default)).lower().strip()
if result in {"y", "yes"}:
... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def hash_file(file_path):
"""
Return the hash of a file.
"""
md5 = hashlib.md5()
with open(file_path, 'rb') as file:
md5.update(file.read())
return md5.hexdigest() | bigcode/self-oss-instruct-sc2-concepts |
def getmAxId(root):
"""Returns the highest id number from the xml """
a=0
for face in root.iter('Face'):
id = int(face.attrib.get('id'))
if(id>a):
a=id
return(a) | bigcode/self-oss-instruct-sc2-concepts |
def cer(e):
"""
Canonicalize the representation of an undirected edge.
Works by returning a sorted tuple.
"""
return tuple(sorted(e)) | bigcode/self-oss-instruct-sc2-concepts |
def delete_migration(connection, basename):
"""
Delete a migration in `migrations_applied` table
"""
# Prepare query
sql = "DELETE FROM migrations_applied WHERE name = %s"
# Run
with connection.cursor() as cursor:
cursor.execute(sql, (basename,))
connection.commit()
... | bigcode/self-oss-instruct-sc2-concepts |
def build_slack_message(integration, title, title_link, fallback_text, fields,
pre_text, body, color, thumb_url, image_url):
"""Build message using Slack webhook format.
This will build the payload data for HTTP requests to services such as
Slack, Mattermost and Discord.
Args:
... | bigcode/self-oss-instruct-sc2-concepts |
def iface_definition(iface, ssid, psk):
"""Returns the corresponding iface definition as a string,
formatted for inclusion in /etc/network/interfaces.d/"""
return \
"""iface {} inet dhcp
wpa-ssid "{}"
wpa-psk {}
""".format(iface, ssid, psk) | bigcode/self-oss-instruct-sc2-concepts |
def get_walk_data(walk, data):
"""Retrieve data specific to a given walk.
Args:
walk (str): walk identifier.
data (dict): holds all data matrices/lists, including unique
walk identifiers in 'subject_walk_IDs'.
Returns:
walk_data (dict): all data matrices/lists for a sin... | bigcode/self-oss-instruct-sc2-concepts |
def degrees(graph):
"""Returns a list of node degrees in a ProgramGraph.
Args:
graph: A ProgramGraph.
Returns:
An (unsorted) list of node degrees (in-degree plus out-degree).
"""
return [len(graph.neighbors(node)) for node in graph.all_nodes()] | bigcode/self-oss-instruct-sc2-concepts |
import math
def haversine(origin, destination):
"""
Returns the distance between two points using the haversine formula
http://www.platoscave.net/blog/2009/oct/5/calculate-distance-latitude-longitude-python/
>>> int(haversine((-1.31017, 51.7459), (-1.199226, 51.749327)))
7647
"""
... | bigcode/self-oss-instruct-sc2-concepts |
import requests
import time
def request_url_json(url: str) -> dict:
"""Get JSON object version of reponse to GET request to given URL.
Args:
url: URL to make the GET request.
Returns:
JSON decoded response from the GET call.
Empty dict is returned in case the call fails.
"""
print(url)
try... | bigcode/self-oss-instruct-sc2-concepts |
def kmer_count(k, rc=False):
"""
Counts the number of possible k-mers
Args:
k (int): kmer size
rc (bool): Use canonical k-mers
Returns:
int: number of possible kmers
"""
if not rc:
return 4**k
n_palindromes = 0
if k % 2 == 0:
n_palindromes = 4**(... | bigcode/self-oss-instruct-sc2-concepts |
def long_repeat(line):
"""
length the longest substring that consists of the same char
"""
line_length = len(line)
if line_length <= 1:
return line_length
count_list = [0]
current_count = 1
current_ch = ''
for i in range(0,line_length):
ch = line[i]
if ch... | bigcode/self-oss-instruct-sc2-concepts |
def get_initial_cholcovs_index_tuples(n_mixtures, factors):
"""Index tuples for initial_cov.
Args:
n_mixtures (int): Number of elements in the mixture distribution of the factors.
factors (list): The latent factors of the model
Returns:
ind_tups (list)
"""
ind_tups = []
... | bigcode/self-oss-instruct-sc2-concepts |
def parametrizeTimeoutMixin(protocol, reactor):
"""
Parametrizes the L{TimeoutMixin} so that it works with whatever reactor is
being used by the test.
@param protocol: A L{_GenericHTTPChannel} or something implementing a
similar interface.
@type protocol: L{_GenericHTTPChannel}
@param ... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def checksum_file(path):
"""Compute the sha256 checksum of a path"""
hasher = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hasher.update(chunk)
return hasher.hexdigest() | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
import torch
import itertools
def unit_box(n: int, scale: Optional[torch.Tensor] = None) -> torch.Tensor:
"""
Create a (scaled) version of a unit box
Args:
n: number of dimensions
scale: scaling of each dimension
Returns:
torch.Tensor: scaled unit ... | bigcode/self-oss-instruct-sc2-concepts |
def get_p2p_ssqr_diff_over_var(model):
"""
Get sum of squared differences of consecutive values as a fraction of the
variance of the data.
"""
return model['ssqr_diff_over_var'] | bigcode/self-oss-instruct-sc2-concepts |
def SetPageSize(unused_ref, args, request):
"""Set page size to request.pageSize.
Args:
unused_ref: unused.
args: The argparse namespace.
request: The request to modify.
Returns:
The updated request.
"""
if hasattr(args, 'page-size') and args.IsSpecified('page_size'):
request.pageSize = ... | bigcode/self-oss-instruct-sc2-concepts |
def reverse_y_mapper(height, mapper):
"""
Returns a coordinate mapper function for grids with reversed Y coordinates.
:param height: width of strip
:param mapper: grid mapper to wrap
:return: mapper(x, y)
"""
max_y = height - 1
def y_mapper(x, y):
return mapper(x, max_y - y)
... | bigcode/self-oss-instruct-sc2-concepts |
def ip_version(vnum):
"""String version of ip version"""
return 'ipv4' if vnum == 4 else 'ipv6' | bigcode/self-oss-instruct-sc2-concepts |
def create_padding_mask(seq):
"""
Mask all the pad tokens in the batch of sequence. It ensures that the model does not treat padding
as the input.
The mask indicates where pad value 0 is present: it outputs a 1 at those locations, and a 0 otherwise.
The input shape is [batch, seq_len], the output sh... | bigcode/self-oss-instruct-sc2-concepts |
def ns_between(l, r, ns):
"""Checks if all ns are between l and r (inclusive)."""
return all(l <= n <= r for n in ns) | bigcode/self-oss-instruct-sc2-concepts |
def dom2dict(element):
"""Converts DOM elements to dictionaries of attributes."""
keys = list(element.attributes.keys())
values = [val.value for val in list(element.attributes.values())]
return dict(list(zip(keys, values))) | bigcode/self-oss-instruct-sc2-concepts |
def split(text):
"""
Convenience function to parse a string into a list using two or more spaces
as the delimiter.
Parameters
----------
text : string
Contains text to be parsed
Returns
-------
textout : list
list of strings containing the parsed input text
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def format_time(t, format_spec='dhms'):
"""
Return a formatted time string describing the duration of
the input in seconds in terms of days,hours,minutes and seconds.
"""
if format_spec == '':
sb, mb, hb, db = True, True, True, True
else:
sb = 's' in format_spec
mb = 'm' in format_spec
hb = 'h' in format... | bigcode/self-oss-instruct-sc2-concepts |
def scale_for_curses(rgb_value: int) -> int:
"""Scale a single RGB value for curses.
:param rgb_value: One RGB value
:returns: The value scaled for curses
"""
curses_ceiling = 1000
rgb_ceiling = 255
return int(rgb_value * curses_ceiling / rgb_ceiling) | bigcode/self-oss-instruct-sc2-concepts |
import requests
def minify(file_content:str) -> str:
"""Access Toptal's CSS Minifier API.
Parameters
----------
file_content : str
CSS file content in str format.
Returns
-------
str
Minifier CSS in str format.
"""
payload = {'input': file_content}
url =... | bigcode/self-oss-instruct-sc2-concepts |
def simple_wsgi(_, start_response):
"""A simple wsgi app that always returns an empty response."""
start_response("200 OK", [("Content-Type", "text/html")])
return [b""] | bigcode/self-oss-instruct-sc2-concepts |
def count_consecutives(tosses):
"""
Counts the number of consecutive heads or tails.
"""
consecutive_tosses = 1
max_consecutive_tosses = 1
for i in range(0, len(tosses) - 1):
if tosses[i] == tosses[i + 1]:
consecutive_tosses += 1
max_consecutive_tosses = max(max_c... | bigcode/self-oss-instruct-sc2-concepts |
def get_target_for_label(label):
"""Convert a label to `0` or `1`.
Args:
label(string) - Either "POSITIVE" or "NEGATIVE".
Returns:
`0` or `1`.
"""
if(label == 'POSITIVE'):
return 1
else:
return 0 | bigcode/self-oss-instruct-sc2-concepts |
def custom_format(template, **kwargs):
"""
Custom format of strings for only those that we provide
:param template: str - string to format
:param kwargs: dict - dictionary of strings to replace
:return: str - formatted string
"""
for k, v in kwargs.items():
template = template.replac... | bigcode/self-oss-instruct-sc2-concepts |
def invert(dct):
""" Transposes the keys and values in a dictionary
:param dct: dictionary to transpose
:tupe dct: dict
:rtype: dict
"""
return {val: key for key, val in dct.items()} | bigcode/self-oss-instruct-sc2-concepts |
def comp_stacked_rating_hist_allbrands(review_item):
"""
Compute rating distributions for all brands
:param review_item: a merged data frame containing item and review info
:return: brands: an ascending list containing names of all brands
scores: an ascending list containing all possible ra... | bigcode/self-oss-instruct-sc2-concepts |
def is_number(term):
"""check if term is a number. Returns bool"""
if isinstance(term, int) or term.isdigit():
return True | bigcode/self-oss-instruct-sc2-concepts |
def compact(inDict, keep_if=lambda k, v: v is not None):
"""
Takes a dictionary and returns a copy with elements matching a given lambda removed. The
default behavior will remove any values that are `None`.
Args:
inDict (dict): The dictionary to operate on.
keep_if (lambda(k,v), option... | bigcode/self-oss-instruct-sc2-concepts |
def simple_filter(**kwargs):
"""Return a simple filter that requires all keyword arguments to be equal
to their specified value."""
criteria = []
for key, value in kwargs.items():
criteria.append({'type': 'SIMPLE', 'propertyName': key,
'operator': 'Equals', 'operand': va... | bigcode/self-oss-instruct-sc2-concepts |
def fixture_repo_id() -> int:
"""Return a repository ID."""
return 102909380 | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def disable_for_loaddata(signal_handler):
"""The signals to update denormalized data should not be called
during loaddata management command (can raise an IntegrityError)"""
def wrapper(*args, **kwargs):
for fr in inspect.stack():
if inspect.getmodulename(fr[1]) == 'load... | bigcode/self-oss-instruct-sc2-concepts |
def remove_short_segments(
lbl_tb, segment_inds_list, timebin_dur, min_segment_dur, unlabeled_label=0
):
"""remove segments from vector of labeled timebins
that are shorter than specified duration
Parameters
----------
lbl_tb : numpy.ndarray
vector of labeled spectrogram time bins, i.e.... | bigcode/self-oss-instruct-sc2-concepts |
def simple_decorator(pattern=None):
"""Build a simple decorator function from the given pattern.
The decorator will prefix each line with the given pattern. If the given
pattern contains a '{}' placeholder, it will be used as a separator
between the prefix and suffix. In other words, this:
simpl... | bigcode/self-oss-instruct-sc2-concepts |
def parse_tf_ids(target_tfs_filename):
"""
If user has provided a file with Ensembl transcript ids, parse these to a list.
"""
with open(target_tfs_filename, 'r') as target_tfs_file:
target_tfs_list = target_tfs_file.read().splitlines()
target_tfs_list = [x.upper() for x in target_tfs_l... | bigcode/self-oss-instruct-sc2-concepts |
def strfdelta(tdelta, fmt):
"""Utility function. Formats a `timedelta` into human readable string."""
d = {"days": tdelta.days}
d["hours"], rem = divmod(tdelta.seconds, 3600)
d["minutes"], d["seconds"] = divmod(rem, 60)
return fmt.format(**d) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
import functools
import inspect
def is_coroutine_function(obj: Any) -> bool:
"""
Correctly determines if an object is a coroutine function,
including those wrapped in functools.partial objects.
"""
while isinstance(obj, functools.partial):
obj = obj.func
return i... | bigcode/self-oss-instruct-sc2-concepts |
def is_kernel_module_loaded(module_name):
"""
Checks whether the kernel module with the specified name is loaded.
Args:
module_name (str) : Name of the module to check.
Returns:
True, if the module is loaded; otherwise False.
"""
with open("/proc/modules") as file:
lin... | bigcode/self-oss-instruct-sc2-concepts |
def GenerateAnnulusRZPhiToNode(nRCoords, nZCoords, phiPoints):
"""
Generate the map from r, z phi IDs to node IDs for a structured 3D linear
tet annulus mesh
"""
rzphiToNode = []
index = 0
for i in range(nRCoords):
rzphiToNode.append([])
for j in range(nZCoords):
rzphiToNode[i].append([]... | bigcode/self-oss-instruct-sc2-concepts |
def clip_command(command):
"""Is this a clip command?
:param command: string
"""
# It is possible to have `\clip` or `SELECT * FROM \clip`. So we check
# for both conditions.
return command.strip().endswith('\\clip') or command.strip().startswith('\\clip') | bigcode/self-oss-instruct-sc2-concepts |
def sum_digits(n):
"""Calculate the sum of digits.
Parameters:
n (int): Number.
Returns:
int: Sum of digitis of n.
Examples:
>>> sum_digits(42)
6
"""
s = 0
while n:
s += n % 10
n //= 10
return s | bigcode/self-oss-instruct-sc2-concepts |
def Pad(ids, pad_id, length):
"""Pad or trim list to len length.
Args:
ids: list of ints to pad
pad_id: what to pad with
length: length to pad or trim to
Returns:
ids trimmed or padded with pad_id
"""
assert pad_id is not None
assert length is not None
if len(ids) < length:
a = [pad... | 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.