seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
import random
from time import gmtime, strftime
def generate_DOB(age=65):
"""Randomly generate a month & date for DOB """
birth_month = random.randint(1,12)
if birth_month == "1" or "3" or "5" or "7" or "8" or "10" or "12":
birth_day = random.randint(1,31)
if birth_month == "2":
birth_day = random... | bigcode/self-oss-instruct-sc2-concepts |
def nts(s):
"""Convert a null-terminated string field to a python string.
"""
# Use the string up to the first null char.
p = s.find("\0")
if p == -1:
return s
return s[:p] | bigcode/self-oss-instruct-sc2-concepts |
def parse_csv_data(csv_filename: str) -> list:
"""Parses through a CSV file, reading and storing each line of the file.
Opens a csv file, assigning covid_csv_file to a list of all lines in the
file. For each line in the file, the newline character and the commas are
removed from the file, with each lin... | bigcode/self-oss-instruct-sc2-concepts |
def get_iscam_mws(intensities, mw_intensity_line_pars=None):
"""
Calculate the molecular weights of the intensities with the line parameters
`mw_intensity_line_pars`
Parameters
----------
intensities : np.ndarray
inensities of an iscam measurements
mw_intensity_line_pars : array lik... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def torch_dot(x: torch.Tensor, y: torch.Tensor):
"""
Dot product of two tensors.
"""
return (x * y).sum(-1) | bigcode/self-oss-instruct-sc2-concepts |
def _CheckTestDataReadmeUpdated(input_api, output_api):
"""
Checks to make sure the README.md file is updated when changing test files.
"""
test_data_dir = input_api.os_path.join('media', 'test', 'data')
readme_path = input_api.os_path.join('media', 'test', 'data', 'README.md')
test_files = []
readme_upda... | bigcode/self-oss-instruct-sc2-concepts |
def format_custom_attr(ddic):
"""
Format a dictionary of dictionaries in string format in the "custom attribute" syntax
e.g. custom="readingOrder {index:1;} structure {type:heading;}"
"""
s = ""
for k1, d2 in ddic.items():
if s:
s += " "
s += "%s" % k1
s2 = ""... | bigcode/self-oss-instruct-sc2-concepts |
import re
def mark_quoted_strings(sql):
"""Mark all quoted strings in the SOQL by '@' and get them as params,
with respect to all escaped backslashes and quotes.
"""
pm_pattern = re.compile(r"'[^\\']*(?:\\[\\'][^\\']*)*'")
bs_pattern = re.compile(r"\\([\\'])")
out_pattern = re.compile("^[-!()*... | bigcode/self-oss-instruct-sc2-concepts |
def eff_heat_pump(temp_diff, efficiency_intersect, m_slope=-.08, h_diff=10):
"""Calculate efficiency of heat pump
Parameters
----------
temp_diff: array
Temperature difference
efficiency_intersect : float,default=-0.08
Extrapolated intersect at temp diff of 10 degree (which is treat... | bigcode/self-oss-instruct-sc2-concepts |
def equally_sized_accessor(elements, n_variadic, n_preceding_simple,
n_preceding_variadic):
"""
Returns a starting position and a number of elements per variadic group
assuming equally-sized groups and the given numbers of preceding groups.
elements: a sequential container.
n_v... | bigcode/self-oss-instruct-sc2-concepts |
def _make_extra_string(s=''):
""" Create an extra function that just returns a constant string.
"""
def extra(attr, die, section_offset):
return s
return extra | bigcode/self-oss-instruct-sc2-concepts |
def previous(field):
"""Generates s-expression to access a `field` previous value.
"""
return ["f", field, -1] | bigcode/self-oss-instruct-sc2-concepts |
def is_inside(x, y, window):
"""
Check if (x, y) is a valid coordinate in input window
Args:
x (int): x-coordinate
y (int): y-coordinate
window (face_spinner.Window): Window
Returns:
bool -> True if valid, False otherwise
"""
if window.x <= x < (window.x + windo... | bigcode/self-oss-instruct-sc2-concepts |
def is_source_directory(src_count, files_count):
"""
Return True is this resource is a source directory with at least over 90% of
source code files at full depth.
"""
return src_count / files_count >= 0.9 | bigcode/self-oss-instruct-sc2-concepts |
def _prev_char(s: str, idx: int):
"""Returns the character from *s* at the position before *idx*
or None, if *idx* is zero.
"""
if idx <= 0:
return None
else:
return s[idx - 1] | bigcode/self-oss-instruct-sc2-concepts |
from typing import Sequence
from typing import Dict
from typing import Union
def get_instance_class_from_properties_seq(
instance_idx: Sequence, map_dict: Dict[str, Union[str, int]]) -> Sequence:
"""
Extract instance classes form mapping dict
Args:
instance_idx: instance ids present in se... | bigcode/self-oss-instruct-sc2-concepts |
def _item_to_value_identity(iterator, item):
"""An item to value transformer that returns the item un-changed."""
# pylint: disable=unused-argument
# We are conforming to the interface defined by Iterator.
return item | bigcode/self-oss-instruct-sc2-concepts |
def get_first_line(filename, nlines=1):
"""return the first line of a file.
Arguments
---------
filename : string
The name of the file to be opened.
nlines : int
Number of lines to return.
Returns
-------
string
The first line(s) of the file.
"""
# U is to... | bigcode/self-oss-instruct-sc2-concepts |
def _IsBuildRunning(build_data):
"""Checks whether the build is in progress on buildbot.
Presence of currentStep element in build JSON indicates build is in progress.
Args:
build_data: A dictionary with build data, loaded from buildbot JSON API.
Returns:
True if build is in progress, otherwise False.... | bigcode/self-oss-instruct-sc2-concepts |
import ipaddress
def search_prefix_list(ip, prefix_list):
"""
Check if IP address exists in some prefix which is part of `prefix_list`
`prefix_list` must be a list of tuples
Each tuple must be of form (ip_prefix_begin, ip_prefix_end) in int equivalent (check preparation step)
1. Convert IP to int ... | bigcode/self-oss-instruct-sc2-concepts |
def differ_in_at_most_one(first, second):
"""Check if two strings differ in at most one position."""
# Check if length differences make it possible
if abs(len(first) - len(second)) > 1:
return False
if len(first) > len(second):
longer, shorter = first, second
else:
longer, s... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def is_within(parent, child) -> bool:
"""
Check that a path is within another.
"""
return Path(parent).resolve() in Path(child).resolve().parents | bigcode/self-oss-instruct-sc2-concepts |
import torch
def rankdata_pt(b, tie_method='ordinal', dim=0):
"""
pytorch equivalent of scipy.stats.rankdata, GPU compatible.
:param b: torch.Tensor
The 1-D or 2-D tensor of values to be ranked. The tensor is first flattened
if tie_method is not 'ordinal'.
:param tie_method: s... | bigcode/self-oss-instruct-sc2-concepts |
def get_temp_var(used_vars):
"""get a temp variable name """
for i in range(0, 1000):
var_name = "t{}".format(i)
if var_name not in used_vars:
return var_name | bigcode/self-oss-instruct-sc2-concepts |
def getCoinbaseAddr (node, blockHash):
"""
Extract the coinbase tx' payout address for the given block.
"""
blockData = node.getblock (blockHash)
txn = blockData['tx']
assert len (txn) >= 1
txData = node.getrawtransaction (txn[0], True, blockHash)
assert len (txData['vout']) >= 1 and l... | bigcode/self-oss-instruct-sc2-concepts |
import time
def format_ampm(time_24hour) -> str:
"""Convert 24 hour to 12 hour system"""
t = time.strptime(time_24hour, "%H%M") # Create time object
timevalue_12hour = time.strftime("%-I:%M %p", t) # e.g. From 08:14 to 8:14 AM or 15:24 to 3:24 PM
return timevalue_12hour | bigcode/self-oss-instruct-sc2-concepts |
def all_filled(board):
"""
Returns True if all board is filled, False otherwise.
"""
for i in range(len(board)):
if board[i].count(None):
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
import struct
def decode_ieee(val_int):
"""Decode Python int (32 bits integer) as an IEEE single precision format
Support NaN.
:param val_int: a 32 bit integer as an int Python value
:type val_int: int
:returns: float result
:rtype: float
"""
return struct.unpack(... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def log1p_exp(input_tensor):
""" Computationally stable function for computing log(1+exp(x)).
"""
x = input_tensor * input_tensor.ge(0).to(torch.float32)
res = x + torch.log1p(torch.exp(-torch.abs(input_tensor)))
return res | bigcode/self-oss-instruct-sc2-concepts |
from typing import OrderedDict
def tuples_as_dict(_list):
"""Translate a list of tuples to OrderedDict with key and val as strings.
Parameters
----------
_list : list of tuples
Returns
-------
collections.OrderedDict
Example
-------
::
>>> tuples_as_dict([('cmd', 'v... | bigcode/self-oss-instruct-sc2-concepts |
def find_adjacent_segment_type(segments, time):
"""Find boundary type on left and right (NONSPEECH or SPEECH)"""
# find previous segment type
segments[0].append("NS")
prev = segments[0]
for i in range(1, len(segments)):
if (segments[i][0] - time) > prev[2]:
segments[i].append("NS... | bigcode/self-oss-instruct-sc2-concepts |
import math
def get_elapsed_time(start, end):
"""
Compute elapsed time.
@param start: start time
@param end: end time
@return: elapsed time (string)
"""
diff = end - start
days, hours, minutes = [0, 0, 0]
s_time = []
if diff > 86400: # day
days = math.floor(dif... | bigcode/self-oss-instruct-sc2-concepts |
import asyncio
def async_test(test):
"""
Decorator to run async test methods.
"""
def wrapper(*args, **kwargs):
asyncio.run(test(*args, **kwargs))
return wrapper | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def flatten(sequence_list, cls=list):
"""
Flatten one level of nesting
:param sequence_list: list of sequence
:param cls: create instance of cls by flatten_gen
:return: cls instance or generator
"""
flatten_gen = itertools.chain.from_iterable(sequence_list)
return cls(... | bigcode/self-oss-instruct-sc2-concepts |
def calculate_precision_recall_f1score(y_pred, y_true, entity_label=None):
""" Calculates precision recall and F1-score metrics.
Args:
y_pred (list(AnnotatedDocument)): The predictions of an NER
model in the form of a list of annotated documents.
y_true (list(Annotat... | bigcode/self-oss-instruct-sc2-concepts |
def get_func_and_args_from_str(call_str):
"""Parse call string to get function and argument names.
Args:
call_str: Call string must be in the form:
`tf.foo(arg1=val1, arg2=val2, ...)`.
Returns:
(function_name, list of arg names) tuple.
"""
open_paren_index = call_str.find("(")
close_... | bigcode/self-oss-instruct-sc2-concepts |
import json
def read_from_json(full_path_with_name):
"""Read from an arbitrary JSON and return the structure"""
with open(full_path_with_name, 'r') as mjson:
return json.load(mjson) | bigcode/self-oss-instruct-sc2-concepts |
def xml_tag_name(tag_name: str) -> str:
"""Cleans anonymous tag-names for serialization, so that the colon does not
lead to invalid XML::
>>> xml_tag_name(':Series')
'ANONYMOUS_Series__'
:param tag_name: the original tag name
:returns: the XML-conform tag_name
"""
if tag_name[:... | bigcode/self-oss-instruct-sc2-concepts |
import uuid
def default_test_msg(prefix='', suffix='', sep=' '):
"""Create a random test string"""
return sep.join([prefix, uuid.uuid4().hex, suffix]) | bigcode/self-oss-instruct-sc2-concepts |
import re
def polished(summary):
""" Polish summary, e.g. by cutting and trimming it.
Args:
summary: summary text to polish
Returns:
(part of) polished summary
"""
first_sentence = re.search('.*\.', summary)
if first_sentence:
return first_sentence.group().str... | bigcode/self-oss-instruct-sc2-concepts |
def sample_exposure(image, sample_indices):
"""
A helper function which samples the given image at the specified indices.
:param image: a single RGB image to be sampled from
:param sample_indices: an array of the length N with the indices to sample at. N is the number of pixels
:return: sampled_re... | bigcode/self-oss-instruct-sc2-concepts |
def triangular(n):
"""Gives the n-th triangle number."""
return n*(n+1)/2 | bigcode/self-oss-instruct-sc2-concepts |
def _get_command_prefix(properties):
"""
If multiple commands are registered with the same name, attempt to construct a unique
prefix from other information in the command's properties dictionary to distinguish one
command from another. Uses the properties' ``app`` and/or ``group`` keys to create the
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def extract_words(input_file_name: str) -> List[str]:
"""
Extracts a list of words from a word list. Expects one word per line.
:param input_file_name: the path of the file to extract the words from
:return: a list of words
"""
input_tokens = []
with open(input_file... | bigcode/self-oss-instruct-sc2-concepts |
def checkbox_result_to_bool(res):
"""
Takes in a checkbox result from a form and converts it to a bool
Params:
res (str): the result string from a checkbox
Returns:
bool: the boolean value of res
"""
if res == "on":
return True
elif res == "off" or res is None:
... | bigcode/self-oss-instruct-sc2-concepts |
def EQUAL(x, y):
"""checks if both given arguments are equal"""
return x == y | bigcode/self-oss-instruct-sc2-concepts |
def alphaB(T):
"""
Returns Case B recombination coefficient (Osterbrock 1989; Krumholz+07)
2.59e-13*(T/1e4)**(-0.7)
"""
return 2.59e-13*(T/1e4)**(-0.7) | bigcode/self-oss-instruct-sc2-concepts |
def first_non_repeating_letter(the_string):
"""
Find first non-repeating letter in a string.
Letters are to be treated case-insensitive,
which means 't' = 'T'. However, one must
return the first non-repeating letter as it
appears in the string, either in uppercase
or lowercase.
'sTress'... | bigcode/self-oss-instruct-sc2-concepts |
def weak_pareto_dominates(vec1, vec2):
"""
Returns whether vec1 weakly dominates vec2
"""
for i in range(len(vec1)):
if vec1[i] < vec2[i]:
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
def HtmlString_to_HtmlFile(html_string,file_name="test.html"):
"""Saves an html string as a file with the default name """
out_file=open(file_name,'w')
out_file.write(html_string)
out_file.close()
return file_name | bigcode/self-oss-instruct-sc2-concepts |
import requests
import tempfile
def download_file(url):
"""
Download and return temporary file
"""
print("url detected, downloading...")
response = requests.get(url)
# detect file type from MIME-TYPE of request
content_type = response.headers['content-type']
if content_type == 'application/pdf':
... | bigcode/self-oss-instruct-sc2-concepts |
def comma_list_to_shape(s):
"""Parse a string of comma-separated ints into a valid numpy shape.
Trailing commas will raise an error.
Parameters
----------
s : str
A string of comma-separated positive integers.
Returns
-------
tuple
"""
if not isinstance(s, str):
... | bigcode/self-oss-instruct-sc2-concepts |
def has_juniper_error(s):
"""Test whether a string seems to contain an Juniper error."""
tests = (
'unknown command.' in s,
'syntax error, ' in s,
'invalid value.' in s,
'missing argument.' in s,
)
return any(tests) | bigcode/self-oss-instruct-sc2-concepts |
def factorial(num):
"""
(int) -> int
Calcula el factorial de un número entero
>>> factorial(3)
6
>>> factorial(4)
24
:param num: int el numero a evaluar
:return: int el resultado del factorial
"""
if num == 1 or num == 0:
return 1
elif num < 0:
raise Va... | bigcode/self-oss-instruct-sc2-concepts |
def condition(cond, rule):
""" Only apply rule if condition is true """
def conditioned_rl(expr):
if cond(expr):
return rule(expr)
else:
return expr
return conditioned_rl | bigcode/self-oss-instruct-sc2-concepts |
import json
def to_json(obj):
"""
Converts the given object to a json string
:param obj: The input object
:type obj: object
:return: object as json string
:rtype: str
"""
return json.dumps(obj) | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def set_date_from_string(value: str, format_: str = "%Y-%m-%dT%H:%M:%S"):
"""Generic function to format a string to datetime
Args: value: The value to be validated.
format_: A regex pattern to validate if the string has a specific format
Returns:
A datetime obje... | bigcode/self-oss-instruct-sc2-concepts |
def ChkCTStarOnly(cron_time_field):
"""Checks if a crontab field is only a *.
Args:
cron_time_field: Parsed cron time field to check.
Returns:
True if there's only a * in this field.
"""
if not cron_time_field:
return True
if len(cron_time_field) == 1 and cron_time_field[0].Kind == 'star':
... | bigcode/self-oss-instruct-sc2-concepts |
def _stripBold(s):
"""Returns the string s, with bold removed."""
return s.replace('\x02', '') | bigcode/self-oss-instruct-sc2-concepts |
def capitalize_title(title):
"""Convert the first letter of each word in the title to uppercase if needed.
:param title: str - title string that needs title casing.
:return: str - title string in title case (first letters capitalized).
"""
return title.title() | bigcode/self-oss-instruct-sc2-concepts |
def perspectiveTransform(x, y, M):
""" Implementation of the perspective transform (homography) in 2D.
**Parameters**\n
x, y: numeric, numeric
Pixel coordinates of the original point.
M: 2d array
Perspective transform matrix.
**Return**\n
xtrans, ytrans: numeric, numeric
... | bigcode/self-oss-instruct-sc2-concepts |
def decode_time(value):
"""time decoder
Used for fields such as:
duration=1234.123s
"""
if value == "never":
return value
time_str = value.rstrip("s")
return float(time_str) | bigcode/self-oss-instruct-sc2-concepts |
def InstanceOverlap_OLD(instance1,instance2):
"""Returns True if given instances share a vertex."""
for vertex1 in instance1.vertices:
if vertex1 in instance2.vertices:
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
import numbers
import string
def build_coder(shift):
"""
Returns a dict that can apply a Caesar cipher to a letter.
The cipher is defined by the shift value. Ignores non-letter characters
like punctuation and numbers. The empty space counts as the 27th letter
of the alphabet, so spaces should be m... | bigcode/self-oss-instruct-sc2-concepts |
def apply_ucrow_aggregation(X):
"""
Given a tensor of activations, aggregate by sum-pooling without weighting.
:param ndarray X:
3d tensor of activations with dimensions (channels, height, width)
:returns ndarray:
unweighted global image feature
"""
return X.sum(axis=(1, 2)) | bigcode/self-oss-instruct-sc2-concepts |
def create_groupings_columns(groupings_params):
"""
Strips all other parameters from groupings except name and columns
"""
new_groupings={}
for grouping_name, grouping_values in groupings_params.items():
for values_name, values in grouping_values.items():
if values_name is 'colum... | bigcode/self-oss-instruct-sc2-concepts |
def _container_exists(blob_service_client, container):
"""Check if container exists"""
return next(blob_service_client.list_containers(container), None) is not None | bigcode/self-oss-instruct-sc2-concepts |
import re
def parse_doi(doi: str) -> str:
"""Parses a DOI from e.g. a URL.
Args:
doi: DOI string.
Returns:
The (possibly trimmed) DOI.
Raises:
ValueError: if the DOI cannot be parsed.
"""
# See https://www.doi.org/doi_handbook/2_Numbering.html#2.2.
match = re.sea... | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def four_body_sum(spins):
"""Calculate four body term in the periodic lattice
Input:
spins: spins configuration matrix.
Output:
sum of four body terms.
"""
size = len(spins)
Sum = 0
for i,j in itertools.product(range(size), repeat=2):
Sum += spins[i,j] * s... | bigcode/self-oss-instruct-sc2-concepts |
from hashlib import md5
def part2_adventcoin_miner(secret_key, match='000000'):
"""
--- Part Two ---
Now find one that starts with six zeroes.
"""
for x in range(99999999):
newkey = md5(secret_key + str(x)).hexdigest()
if newkey[:len(match)] == match:
return (x) | bigcode/self-oss-instruct-sc2-concepts |
def duration(duration_ms: float) -> str:
"""
Formats duration into a string logged in stats
:param duration_ms: Duration in milliseconds
:return: formatted duration
"""
return "{:.2f}ms".format(duration_ms) | bigcode/self-oss-instruct-sc2-concepts |
def compare_probs(post_a, post_b):
"""Compute P(A > B) probability."""
return (post_a > post_b).sum() / post_a.size | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
def getCosponsors(fileDict: Dict, includeFields = []) -> list:
"""
Gets Cosponsors from data.json Dict. `includeFields` is a list of keys to keep. The most useful are probably 'name' and 'bioguide_id'.
Args:
fileDict (Dict): the Dict created from data.json
includeFields (li... | bigcode/self-oss-instruct-sc2-concepts |
def ternary_search(f, xmin, xmax, epsilon=1e-6):
"""Ternary search.
Args:
f: An objective function. Must be convex downward.
xmin: The lower bound of the range to search.
xmax: The upper bound of the range to search.
epsilon: The epsilon value for judging convergence.
"""
l, r =... | bigcode/self-oss-instruct-sc2-concepts |
def build_response_body(sentiment_prediction, confidence):
"""
Returns a formatted dict containing sentiment prediction.
:param sentiment_prediction:
:param confidence:
:return:
"""
return dict(sentiment='{}'.format(sentiment_prediction),
confidence=confidence) | bigcode/self-oss-instruct-sc2-concepts |
def is_mapping_table(table_id):
"""
Return True if specified table is a mapping table
:param table_id: identifies the table
:return: True if specified table is an mapping table, False otherwise
"""
return table_id.startswith('_mapping_') | bigcode/self-oss-instruct-sc2-concepts |
def fsplit(pred, objs):
"""Split a list into two classes according to the predicate."""
t = []
f = []
for obj in objs:
if pred(obj):
t.append(obj)
else:
f.append(obj)
return (t, f) | bigcode/self-oss-instruct-sc2-concepts |
def _attr_key(attr):
"""Return an appropriate key for an attribute for sorting
Attributes have a namespace that can be either ``None`` or a string. We
can't compare the two because they're different types, so we convert
``None`` to an empty string first.
"""
return (attr[0][0] or ''), attr[0][... | bigcode/self-oss-instruct-sc2-concepts |
import bz2
def unpack(requests):
"""Unpack a list of requests compressed in bz2"""
return [bz2.decompress(request) for request in requests] | bigcode/self-oss-instruct-sc2-concepts |
import torch
def my_l1(x, x_recon):
"""Calculate l1 loss
Parameters
----------
x : torch.cuda.FloatTensor or torch.FloatTensor
Input data
x_recon : torch.cuda.FloatTensor or torch.FloatTensor
Reconstructed input
Returns
-------
torch.cuda.FloatTensor or torch.FloatTen... | bigcode/self-oss-instruct-sc2-concepts |
def step_lstm(lstm, input_, h_0_c_0=None):
"""LSTMCell-like API for LSTM.
Args:
lstm: nn.LSTM
input_: [batch_size, input_size]
h_0_c_0: None or
h_0: [num_layers, batch_size, hidden_size]
c_0: [num_layers, batch_size, hidden_size]
Returns:
output: [batc... | bigcode/self-oss-instruct-sc2-concepts |
import string
def title_to_url(title):
"""
Converts a title string to a valid string for a url. White space will be
replaced by dash, case will be set to lower and all punctuation marks will
be removed.
:param title: the title string.
:type title: str
:return: a valid url string.
:rty... | bigcode/self-oss-instruct-sc2-concepts |
def create_prediction_series(lis, predictor):
"""
this function returns a list, lets call it p, of the length of the given lis
such that p[i] = the prediction of the i'th element in lis given the first i-1 elements
to make things nice, p[0] would be equal to lis[0]
:param lis:
:param predictor:... | bigcode/self-oss-instruct-sc2-concepts |
def usable_class_name(node):
"""Make a reasonable class name for a class node."""
name = node.qname()
for prefix in ["__builtin__.", "builtins.", "."]:
if name.startswith(prefix):
name = name[len(prefix) :]
return name | bigcode/self-oss-instruct-sc2-concepts |
def is_pass_transistor(pip_json):
""" Returns boolean if pip JSON indicates pip is a pass transistor.
Always returns False if database lacks this information.
"""
if 'is_pass_transistor' in pip_json:
return bool(int(pip_json['is_pass_transistor']))
else:
return False | bigcode/self-oss-instruct-sc2-concepts |
def task10(number: int) -> None:
"""
Function that take an integer number as string and print the "It is an even number" if the number is even,
otherwise print "It is an odd number".
Input: number
Output: None
"""
if number % 2 == 0:
print("It is an even number")
else:
p... | bigcode/self-oss-instruct-sc2-concepts |
def has_method(obj, method_name: str) -> bool:
"""
Returns True if the provided object (`obj`) has the named method (`method_name`).
"""
return callable(getattr(obj, method_name, None)) | bigcode/self-oss-instruct-sc2-concepts |
def make_naive(value, timezone):
"""
Makes an aware datetime.datetime naive in a given time zone.
"""
# If `value` is naive, astimezone() will raise a ValueError,
# so we don't need to perform a redundant check.
value = value.astimezone(timezone)
if hasattr(timezone, 'normalize'):
# ... | bigcode/self-oss-instruct-sc2-concepts |
def ensure_other_is_scalar(matrix_method):
"""Simple decorator to check if second argument to a matrix method is a scalar."""
def wrapper(self, other, *args, **kwargs):
if not isinstance(other, (int, float, complex)):
raise ValueError(f"Cannot use {matrix_method} with 'other' of type {type(o... | bigcode/self-oss-instruct-sc2-concepts |
def get_extension(local_file: str) -> str:
"""Extract the file extension of a file."""
return local_file.rsplit(".", 1)[1].lower() | bigcode/self-oss-instruct-sc2-concepts |
def normalize(vector, size):
"""
Normalizes a vector given the vector and the corresponding document length
"""
for word in vector:
vector[word]=vector[word]/float(size)
return vector | bigcode/self-oss-instruct-sc2-concepts |
import pickle
def load_pkl(path: str, load_mode: str = 'rb'):
"""
Read a pickle file.
:param path: str, filepath to read
:param load_mode: str, read mode
:return: contents of the pickle file
"""
return pickle.load(open(path, load_mode)) | bigcode/self-oss-instruct-sc2-concepts |
def first_neighbours_last(batches, current_batch_idx, nb_left, nb_right):
"""Build a sublist from a large batch list.
This is used to display batch links for a large table.
arguments:
* :param batches: a large sequence (may be a batches as well)
* :param current_batch_idx: index of the current b... | bigcode/self-oss-instruct-sc2-concepts |
import csv
def fetch_education_urls(input_file):
"""
Given a local input file, parse it and return a list of GOV.UK URLs.
"""
documents = []
with open(input_file, 'r') as f:
reader = csv.reader(f)
# skip headers
next(reader, None)
documents = list(reader)
retur... | bigcode/self-oss-instruct-sc2-concepts |
def createPointWkt(coords):
"""Create WKT POINT string.
Args:
coords (list): Two item list representing single point coordinate.
Returns:
str: WKT POINT string.
"""
return 'POINT(' + str(coords[0]) + ' ' + str(coords[1]) + ')' | bigcode/self-oss-instruct-sc2-concepts |
def mu_lambda(E=None, nu=None, lam=None, mu=None):
"""Get lame's parameters.
Build the lame constants of a material using the elastic constants for
isotropic materials. You must specify exactly two of the four available
constants. For example, you can provide E and mu as arguments.
Args:
... | bigcode/self-oss-instruct-sc2-concepts |
import re
def _match_regex(pattern: str, path: str) -> bool:
"""True if `path` matches `pattern`."""
return re.match(pattern, path) is not None | bigcode/self-oss-instruct-sc2-concepts |
def clean_path(source):
"""
Replace backslashes from source.file_name with a slash
"""
source.file_name = source.file_name.replace('\\', '/')
return source | bigcode/self-oss-instruct-sc2-concepts |
import re
def remove_non_alphanumeric_symbols(s):
"""Make text usable for attribute name"""
return re.sub(r"\W", "_", s) | bigcode/self-oss-instruct-sc2-concepts |
def build_falloff(parameters, falloff_function):
"""Creates falloff reaction Troe parameter string
Parameters
----------
parameters : numpy.ndarray
Array of falloff parameters; length varies based on ``falloff_function``
falloff_function : {'Troe', 'SRI'}
Type of falloff function
... | 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.