content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import torch
def apply_background(I, background):
"""
Applies a background RGB image to the input image I.
Parameters
----------
I : Tensor
an image tensor in RGBDA format
background : Tensor
an image tensor in RGB format
Returns
-------
Tensor
an image te... | eb22e05a3d3cdf34de71cbb9147e04027ca10d84 | 605,138 |
def isName(string):
""" Checks to see if the string is an author name of an experiment rather than a sequence of NCBI codes. """
return '_' in string | 874526e8e2156d0dd096765132b4bfda319a9284 | 605,143 |
def htmlize_line_breaks(comment):
"""Formats comment to HTML by inserting <br/> tags at newlines.
Parameters
----------
comment : str
Comment to format
Returns
-------
comment : str
The HTMLized comment
"""
return comment.replace("\n", "\n<br/>\n") | 47d5427f0ccadfe83a8b961ed4c96ef7c2be0244 | 605,144 |
def is_sequence(item):
"""Returns True if an object is iterable."""
return hasattr(type(item), '__iter__') | 3e3d4b47993ae28e42bb1e496c8537d7bf5eb85c | 605,150 |
def process_what_to_run_randoms(pairs_to_test, random_counterpart):
"""Process concepts and pairs to test.
Args:
pairs_to_test: a list of concepts to be tested and a target (e.g,
[ ("target1", ["concept1", "concept2", "concept3"]),...])
random_counterpart: a random concept that will be compared to th... | 451727016284706a4ad07606f8e61ab75fb08ad6 | 605,152 |
from typing import Dict
from typing import Any
import torch
def release_gpu(
tensors_dict: Dict[str, Any]
) -> Dict[str, Any]:
"""Detach and move to cpu the tensors from the input dict.
The non-tensor elements are kept intact.
Parameters
----------
tensors_dict : Dict[str, Any]
A dic... | ac2a83d4d4f9d83037f779762e10db59f5722e05 | 605,154 |
def concat(datasets):
"""Merge dictionaries containing lists for each key"""
res = {}
for dataset in datasets:
for k, v in dataset.items():
res[k] = res.get(k, []) + v
return res | 314244dde631a5ff623d947bc4f640f86f6dca05 | 605,156 |
def generate_parameters_string(parameters):
"""Generates the parameters string from the parameters dictionary
Parameters
----------
parameters : dict
The parameter values, keyed by parameter name
Returns
-------
str
A string with the parameters to the CLI call
Raises
... | e7ba9c8f14ce8752bcea84370933cb29adea0345 | 605,158 |
def create_array(n) -> list:
"""This function create an array, populated with integers from 1 to n."""
res=[]
for i in range(1, n + 1):
res.append(i)
return res | d73fa64618b093652bb4db15ab0ae0fe341d4221 | 605,160 |
def simple_equality(v1, v2, read):
"""
Equality for simple fields where equality can be tested directly.
"""
return v1 == v2 | 055159309eb4885c1c8c3959c003f42e4926da3c | 605,161 |
from typing import Dict
from typing import Any
from typing import List
def _subnets_in_network_config(config: Dict[str, Any]) -> List[str]:
"""
Returns all subnet IDs found in the given node config's network interfaces.
Args:
config (Dict[str, Any]): node config
Returns:
subnet_ids (L... | db8bb13dc984fcf9c1b4d86ae85b663d47abbbb1 | 605,162 |
def get_business_obj_dict(business_obj_list):
""" Convert business_obj_list to business_obj_dict, with key: business_id, V: business_obj
"""
business_obj_dict = {}
for w in business_obj_list:
business_obj_dict[w['business_id']] = w
return business_obj_dict | 3bb83a47637d0ea88354395a885681b30eb07ee7 | 605,163 |
def _genetate_feature_list(channel_mappings: list):
"""
Generate a list of features from a list of ChannelMap objects (see data.panel.ChannelMap). By default
the ChannelMap marker value is used, but if missing will use channel value instead.
Parameters
----------
channel_mappings: list
... | 7a9e8e4e3aabafadc345d1dc209834e840efbcbc | 605,167 |
def get_db_key_for_interval(interval):
"""Calculate a database key for the given interval object."""
return '>>'.join(interval['range']) | 3553ef785281bd23759e6f24f3f75a3489180406 | 605,168 |
import random
def random_text() -> str:
"""
Generate a random text string.
"""
alphabet = "abcdefghijklmnopqrstuvwxyz"
words = []
for _ in range(random.randint(4, 10)):
words.append("".join(random.choice(alphabet) for _ in range(random.randrange(1, 6))))
return " ".join(words) | de5f40db1ed2fea648b4f2f7bc19bfc79d73c5fc | 605,169 |
def find_boolean_function(lib_json_data, port_name):
"""
Search for a boolean function for a certain port in a .lib.json file.
:param lib_json_data: json data of a .lib.json file
:param port_name: The port name
:returns: The boolean function as a string. Empty string if no boolean function was foun... | fac223dcc68bba04858018d190ea82e91ae79f66 | 605,176 |
import re
def snake_case(a_string):
"""
Returns a snake-cased version of a string.
:param a_string: any :class:`str` object.
Usage:
>>> snake_case('FooBar')
"foo_bar"
"""
partial = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', a_string)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2'... | 235b718a300e17de2b24fb5b5e97513b46abb0be | 605,177 |
def _get_value(f, i, values=False):
""" return the value for the location i """
# check agains values
if values:
return f.values[i]
# this is equiv of f[col][row].....
# v = f
# for a in reversed(i):
# v = v.__getitem__(a)
# return v
return f.ix[i] | fc07c9fbe8ec30ae6e983f8bb808744f3fb9d25d | 605,178 |
def get_dist(stroke_count, modes):
"""
Get the distance to the closest mode.
Parameters
----------
stroke_count : int
modes : list of int
"""
dist = float('inf')
for mode in modes:
dist = min(dist, abs(mode - stroke_count))
return dist | 0f8d02885ef8f48456d6039f0336a2a1e545cc22 | 605,181 |
import re
def condense_zero_units(css):
"""Replace `0(px, em, %, etc)` with `0`."""
return re.sub(r"([\s:])(0)(px|em|%|in|cm|mm|pc|pt|ex)", r"\1\2", css) | 93982e353c1fab75c4249efcfa7b0b526cf56d6c | 605,187 |
def update_string_by_indexes(string: str, content: str, start_pos: int, end_pos: int) -> str:
"""String içerisideki verilen konumdaki metni değiştirme
Arguments:
string {str} -- Eklenecek string
content {str} -- Asıl içerik
start_pos {int} -- Başlangıç indeksi
end_pos {int} -- B... | e18db824832afc7c0f220b9de7b4835d724fa2fd | 605,188 |
def condensed_coords(i, j, n):
"""Transform square distance matrix coordinates to the corresponding
index into a condensed, 1D form of the matrix.
Parameters
----------
i : int
Row index.
j : int
Column index.
n : int
Size of the square matrix (length of first or sec... | 5fcde38a52163cb0745f294814705cc3a3490786 | 605,189 |
def str_end_rev(input: str) -> str:
""" ABCD -> CDAB ; reverse order, but groupd by two """
return "".join([b + a for a, b in zip(input[::2], input[1::2])])[::-1] | 4ba780121876f3082528a3ebc3e87d41dd5d0a2b | 605,190 |
def remove_dup_list(seq,case=False): # Dave Kirby
"""Removes duplicates from a list. Order preserving"""
seen = set()
if case: return [x.lower() for x in seq if
x.lower() not in seen and not seen.add(x)]
return [x for x in seq if x not in seen and not seen.add(x)] | 30fa874a586b676811975d3f98978337b41e5d49 | 605,193 |
def month_string_to_int(solar_dataframe):
"""This function translates string values for months into their integer representations"""
#Use a dictionary to map text to integer values for the months - HDF5 needs no strings
month_change = {'January':1,'February':2,'March':3,'April':4, 'May':5,'June':6,'July':7,... | 44bf490327babf844a11caaa34356eff3b229fc2 | 605,196 |
def make_foot_pressure_indicator(sensor_number, value, previous_value=None) -> dict:
"""Create figure of analog meter displaying value of singe pressure sensor"""
return dict(
data=[
dict(
type='indicator',
mode='number+delta+gauge',
title=f'F... | db3cf7b09a9051f237919bcecb60ad14e8a91469 | 605,197 |
def is_collade(v1, v2):
"""
Input:
v1,v2: velocity of train one and train two respectively in km/h
Output:
True if trains collade under defined circumstates, False if not
"""
t1 = 4/v1
s1 = t1*v2
if s1 >= 6:
return True
else:
return False | b35a89c5971119f9ecefafe5d39258026c03fd13 | 605,212 |
def check_if_mutually_exclusive(possible_args: list, kwargs):
""" "
Checks if at most one of the allowed arguments has been used.
Returns False if more than one arg was used
Returns True if at most one arg was used
"""
count = 0
for arg in possible_args:
if type(arg) == str:
... | 62daeb578c045a2f735f48c3503cd348927a02bd | 605,213 |
def tensor_to_array(input_data):
""" torch.tensor -> np.array
Parameters
----------
input_data : torch.Tensor
torch.Tensor data
Returns
-------
output_data : np.ndarray
input_data converted to array type
"""
output_data = input_data.to('cpu').detach().numpy().copy()
... | ccef52510b54ef085a847cc834f7d255d7ce22cb | 605,217 |
def version_greater_or_equal_to(version, min_version):
"""Compares two version strings and returns True if version > min_version
>>> version_greater_or_equal_to('1.0', '0')
True
>>> version_greater_or_equal_to('1.0', '0.9.9.9')
True
>>> version_greater_or_equal_to('1.0', '2.0')
False
>>> version_greate... | b3050bd321374abb0d2e82b3080a4174644d20e9 | 605,226 |
import re
def _replace_shebang(contents: bytes, new_executable: bytes) -> bytes:
"""Replace the python executable from the shebeng line, which can be in two forms:
1. #!python_executable
2. #!/bin/sh
'''exec' '/path to/python' "$0" "$@"
' '''
"""
_complex_shebang_re = rb"^'''exec' (... | a5eb7e63f2a39911de3c4e8421e1005cbc7836ed | 605,229 |
def build_filters(gearman_worker, raw_filters):
"""
Replace any wildcards in the provided filters
"""
return_filters = raw_filters
return_filters['includeFilter'] = [include_filter.replace('{cruiseID}', gearman_worker.cruise_id) for include_filter in return_filters['includeFilter']]
return ret... | 0c8c447dbe8fdc2a226d05aafccde9656ae0b26d | 605,230 |
def find_area(coords):
"""Find area of a box when given the box corners in a tuple"""
return (coords[1] - coords[0]) * (coords[3] - coords[2]) | 63b39e3cd6ac67a0670ab3881e2bb19799e73a3c | 605,232 |
def get_key_val_of_max_key(dict_obj):
"""Returns the key-value pair with the largest key in the given dict.
Example:
--------
>>> dict_obj = {5: 'g', 3: 'z'}
>>> print(get_key_val_of_max_key(dict_obj))
(5, 'g')
"""
return max(dict_obj.items(), key=lambda item: item[0]) | d8d6a6836f0c8c0e8e914dd4cdd97f9bf703c5e4 | 605,233 |
def mem_add_payload(mem_default_payload):
"""Provide a membership payload for adding a member."""
add_payload = mem_default_payload
add_payload["action"] = "added"
return add_payload | dc55a2b707eb5f6fda0683fefbc3155f4fd27f5a | 605,235 |
def get_parent_index(child_index):
"""
Get the index of the given key's parent given the index
of the child key.
"""
# The root of the tree is at index position 1
# and can have no parent
if child_index == 1:
return 0
return child_index // 2 | 28cdc313ec03f520ccd81d8243cf4a3104a9237f | 605,236 |
def ipv6_link_eth_mcast(dst_ip):
"""Return an Ethernet multicast address from an IPv6 address.
See RFC 2464 section 7.
Args:
dst_ip (ipaddress.IPv6Address): IPv6 address.
Returns:
str: Ethernet multicast address.
"""
mcast_mac_bytes = b'\x33\x33\xff' + dst_ip.packed[-3:]
mc... | c264a3bed16d24daa01eb3bcc392f109de420bff | 605,240 |
import torch
def hunt_adjustment(img):
"""
Applies Hunt-adjustment to an image
:param img: image tensor to adjust (with NxCxHxW layout in the L*a*b* color space)
:return: Hunt-adjusted image tensor (with NxCxHxW layout in the Hunt-adjusted L*A*B* color space)
"""
device = img.device
# Extract luminance compo... | 3d9581abda7c135e788d356fda02eaefa2bd33d4 | 605,241 |
import json
import base64
def decode_environ_backup(encoded_environ_backup: str) -> dict:
"""
Decode environ backup from safe string.
"""
return json.loads(base64.b64decode(encoded_environ_backup).decode("utf-8")) | 1aa9f90bf9aa7f64c761a174e95394779534ad59 | 605,242 |
from typing import List
def add_me_to_the_queue(express_queue: List[str], normal_queue: List[str], ticket_type: int,
person_name: str) -> List[str]:
"""
:param express_queue: list - names in the Fast-track queue.
:param normal_queue: list - names in the normal queue.
:param t... | 4fc4e78d7dfc7b0855976fb1efcef03eddcc6573 | 605,243 |
from typing import Sized
def len_eq(a: Sized, b: int) -> bool:
"""Check if the length of **a** is equivalent to **b**: :code:`len(a) == b`."""
return len(a) == b | 9707cd814fa16e133fe520dd0579c2233046050a | 605,245 |
def last_digit_of(a,b):
""" Calculates the last digit of a^b
Args:
a (int): Base of a^b
b (int): Exponent of a^b
Returns:
(int): The last digit of a^b
"""
last_digit_a = int(str(a)[-1])
if b % 4 == 0:
exp = 4
else:
exp = b % 4
retur... | 9896eab66290650b9f76bc888c69020560c07039 | 605,246 |
import colorsys
def convert_hsv_to_rgb(hsv):
"""
Converts HSV (0-360, 0-1 ranges) values to RGB (0-1 range in SRGBFloats)
:param hsv: list, hue, saturation, value in 0-360 range, saturation, value in 0-1 range
:return: list, red, green, blue RGB values in 0-1 srgbFloat
"""
return list(colorsy... | a18e736d04cae454edd00f58ee7022f6050035d8 | 605,253 |
def is_armstrong(number: int) -> bool:
""" Returns `True` if `number` is Armstrong number else `False`."""
digits = str(number)
return sum(map(lambda digit: int(digit) ** len(digits), digits)) == number | 45765a9839593483545196f2868fcb61047ae504 | 605,254 |
def calcExpGrowth(mgr, asym):
"""Calculate exponential growth value 'r'"""
return 4 * mgr / asym | 4a13d27eb9b873e13ee1ff871d41b9d4e65d2cd0 | 605,257 |
import re
def part_one(data: str) -> int:
"""Sum all numbers present in data."""
# Pattern uses lookahead and lookbehind to make sure we get the full
# numbers. Simply including non-numbers outside the matching group causes
# problems if two numbers are separated by a single token, e.g. '1,2'.
pat... | fcf1c04cdc1b8790438e7ef80e840fbdc2012510 | 605,259 |
def nsplit(s, n):
"""Split a list into sublists of size "n", returns a generator."""
return (s[k: k + n] for k in range(0, len(s), n)) | 662456c785edfb5d7fe032e204385313cf078b01 | 605,261 |
def cigar_int_list(cig_list):
"""Convert int strings in the cigar_list to int and put them into a list"""
int_list = []
for x in cig_list[::2]:
int_list.append(int(x))
return int_list | 695dd3d220708118d376c693178b5aec4b75f873 | 605,262 |
import torch
def dummy_forward_pass(model: torch.nn.Module, forward_pass_callback_args) -> float:
"""
This is intended to be the user-defined model evaluation function.
AIMET requires the above signature. So if the user's eval function does not
match this signature, please create a simple wrapper.
... | e9e979bc965a4dd41bd9a68585ebd5a652b3aa95 | 605,264 |
def compare_to_zero(value: bytearray) -> bool:
"""Compare byte array with zero.
This function, in contrast to the simple comparison operation '==', is
performed in constant time to prevent timing attacks.
Args:
value: Array to compare.
Returns:
Comparison result (boolean).
"""... | e385c624f3d8f612266b60d3c5d1c4b3cca77932 | 605,266 |
def max_overlaps(classes):
"""
Encontra o número máximo de sobreposições (F) que uma classe pode ter. F = N * (N - 1) * X * T
:param classes: Classes de dados normalizadas.
:return: Quantidade máxima de sobreposições possíveis de todas as classes.
"""
number_classes = len(classes) # N
num... | 5dd8057b70c1df6f6e83fe64247c230dc6922841 | 605,269 |
def keyword_search(rows, **kwargs):
"""
Takes a list of dictionaries and finds all the dictionaries where the
keys and values match those found in the keyword arguments.
Keys in the row data have ' ' and '-' replaced with '_', so they can
match the keyword argument parsing. For example, the keywor... | e347c4f680a0e9af70d53c55d9fbcad5d314e06e | 605,271 |
def dot_product(vector_one, vector_two):
"""
Calculates the dot product of two vectors
"""
total = 0
for i in range(len(vector_one)):
total += vector_one[i] * vector_two[i]
return total | c18b97672e688bf338eeab1d83a10a1cb2c20977 | 605,274 |
import warnings
def _check_spec(spec, image_format):
"""Check that an InOutSpec is suitable for a CNNModule.
Args:
spec (garage.InOutSpec): Specification of inputs and outputs. The
input should be in 'NCHW' format: [batch_size, channel, height,
width]. Will print a warning i... | 173179bf7c112182a815d0ff453f79353ac86fea | 605,276 |
import json
def _load_file(filename):
"""
Open and read a JSON file containing Structured Data.
@param filename: the file to open
"""
with open(filename, 'r') as f:
return json.load(f) | 2ac55a3635b8528b554e83d93d7acf1027955fff | 605,281 |
def format_value_string(par_name: str, lmfit_par, end_char=''):
"""Format an lmfit par to a string of value with uncertainty."""
val_string = par_name
val_string += ': {:.4f}'.format(lmfit_par.value)
if lmfit_par.stderr is not None:
val_string += r'$\pm$' + '{:.4f}'.format(lmfit_par.stderr)
... | 7d6a988399ee2c501c80b3e486413e1521196c06 | 605,284 |
def SessionNum(session):
"""
:param session: String with number of session.
>>> SessionNum(session='Session: 9562D061; timeout=60')
9562D061
:return: Number of Session.
"""
num1 = session.find('Session:')
num1 += 9
SessiontTime = session[num1:]
num2 = SessiontTime.find(';')
... | 0f999c46f105a68aa36330d598826b05cf6026d6 | 605,287 |
import requests
def offline_token_using_password(token_endpoint, client_id, username,
password):
"""Get offine token using password."""
response = requests.post(
token_endpoint,
data={
'grant_type': 'password',
'scope': ['offline_access'... | db802596940a9d020bb13e93b0546ce9a48aea40 | 605,290 |
def fixed_asset_turnover(revenue, average_net_fixed_assets):
"""Computes fixed asset turnover.
Parameters
----------
revenue : int or float
Revenue
average_net_fixed_assets :
Average net fixed assets in period
Returns
-------
out : int or float
Fixed asset turno... | 715460872842f83a9ce998369263362d38f297db | 605,292 |
def tile_tensor(tensor, n, dim):
"""Replicate tensor n times along dim, without allocating memory (using torch.expand)"""
assert 0 <= dim < len(tensor.shape), "dim must be a dimension of the given tensor"
# this function works by unsqueezing tensor at dim (which will have size 1 and can therefore be expan... | 5bf4f42def8ec80f3e812f814278e8e5ba9c3fa9 | 605,293 |
import traceback
def render_plaintext(logger, level, event):
"""
Render a structlog event in plaintext.
"""
event = event.copy() # prevent mutation of dict from caller side
ret = "{timestamp} [{level:7}] [{logger}] {event}".format(
timestamp=event.pop("timestamp"),
logger=event.po... | 6a9817e3a807448e3a6e86380e6960a229490950 | 605,295 |
def _ros_group_rank(df, dl_idx, censorship):
"""
Ranks each result within the groups defined by the record's
detection limit index and censorship.
Parameters
----------
df : pandas.DataFrame
dl_idx : str
Name of the column in the dataframe the index of the result's
correspond... | abb7d6c2997e7c0f4fa30b3a3025d133ac798bdb | 605,301 |
def subsetBy(df, column, values):
"""
Subset by one or more values of different columns from data frame
:param df: data frame
:param column: column to subset by
:param values: values to subset by
:return: df subset by values and column
"""
if values is None:
return df
elif is... | c6f3898a3f3ccd1f472835bf9f2a7c2db1c0149a | 605,302 |
def test_model_finder_multiclass_create_scoring_multiclass(
model_finder_multiclass, input_func, expected_results
):
"""Testing if creating closures (and adding them to regular scorings) for multiclass scorings works correctly."""
y_actual = 1
y_predicted = 2
def plus_one(y_true, y_score):
... | 28e4f3f34b63c3f46cefb20de88c841de6738d76 | 605,303 |
import re
def is_valid_username(username):
"""
Validate username with provided requirements
:param username: username of user trying to login
:return: true if the username is acceptable, false otherwise
"""
return (
# r2.8 requirement
2 < len(username) < 20 and
# does n... | 8d1fc5ada18e05f53e7dfce0d182c8c0ae49b875 | 605,305 |
def dot_symbol(directory):
""" Check if given string is dot. """
return directory == '.' | e9bbc56eaa89a2f5c7bf664c42f7bc9d02c80c69 | 605,307 |
def get_root(tree):
"""Get the root node of the tree.
Parameters
----------
tree : dict
The tree.
Returns
----------
s : :py:class:`ast_toolbox.mcts.AdaptiveStressTesting.ASTState`
The root state.
"""
for s in tree.keys():
if s.parent is None:
re... | 4583ee1fa29816156f4b86a0b94fa688a25baf2b | 605,308 |
def port_ready(port, socket):
"""Checks if a given port is already binded"""
try:
socket.connect(('127.0.0.1', port))
except IOError:
return False
else:
socket.shutdown(2)
socket.close()
return True | 50eed8087c7ab6e80de03c1dfa6b4eaab17acd70 | 605,310 |
def finish_present_answer_feedback(question_id):
"""
Feedback when the user tries to answer another question, when he is in mid of answering a question.
:param question_id: Q-id of the question, you are currently answering
:return: Feedback text
"""
return "Please complete answering present que... | 49d330e2becdb85e616f0c7af8ce76e590a389e5 | 605,317 |
from typing import Tuple
def _calculate_splits(number_elements: int, ratio_split: float) -> Tuple[int, int]:
"""Calculates the size of the partitions when splitting a number of elements into two.
:param number_elements: the total number of elements to split.
:param ratio_split: a number between 0 and 1 d... | d93780504834001423c1a5da2ae8d64b5808a627 | 605,318 |
def convert_sky_code(sky_code):
"""
Convert sky code into the following code, handling only sunny and cloudy
SKY Code: refer to weather station API document
1: sunny,
2: partly cloudy,
3: mostly cloudy
4: cloudy
2,3,4 mapped to 2
Weather Code: Own implementation
... | 9a7188d972f911007b8c8cb51877802012ac069b | 605,320 |
def is_palindrome(num):
"""Return True if num is palindromic."""
num = str(num)
if num == '':
return False
return num == num[::-1] | 6077246ba2de1d8d1cadbd131be7f95c08692fb0 | 605,322 |
def has_duplicates(t):
# Old Code
# tmp = []
# for i in t:
# tmp.append(i)
# Worked solution this way because I didn't think to just use days 1-365 and instead
# chose to work with strings like 'mm-dd'. I think the nested conditional is
# particularly gross, especially given the knowledg... | e52cbd4ab5cffea73869d59c66c85d2af70e7be4 | 605,327 |
import importlib
def import_from_str(import_string):
"""
Import and return an object defined as import string in the form of
path.to.module.object_name
"""
path, field_name = import_string.rsplit('.', 1)
module = importlib.import_module(path)
return getattr(module, field_name) | f250639fc6fd376530f775094579ddec67aa5dea | 605,329 |
def is_int(str):
""" Checks if input string is a number rather than a letter
Parameters
----------
str: str
string to test
Returns
-------
answer: bool
returns True if string is a number; False if string is not
"""
answer = False
try:
int(str)
except... | aaaa1a7e97ba9e0021f975778bd8691402ee55aa | 605,331 |
def check_goal(state):
"""
Returns True if state is the goal state. Otherwise, returns False.
"""
n = len(state[0])
for i in range(0, n):
for j in range(0, n):
if state[i][j] != (j + 1) + (i * n):
if not(i == j == (n - 1) and state[i][j] == '*'):
... | ff0c28846db915023801e0c0c92d44c554d9f414 | 605,334 |
import requests
import json
def add_class_to_group(base_url, gid, classname, classparams=None):
"""
adds a class to a group in NodeMeister, returns True on success or False on failure
"""
payload = {'group': gid, 'classname': classname, 'classparams': classparams}
headers = {'content-type': 'appli... | 587fb2a745a1f6ae6ce8a7d0d124ee86e6e9e13f | 605,335 |
def mdlist(m, n):
"""Preallocate 2D list of size MxN"""
return [[None] * n for i in range(m)] | 9487057dfe12aff71ca68f22b46e5ce338cd334d | 605,336 |
def get_area_triangle(p1, p2, p3):
"""
Get the area of the triangle with vertices in p1, p2 and p3
Parameters
----------
p1 : np.array
point p1.
p2 : np.array
point p2.
p3 : np.array
point p3.
Returns
-------
float
area of triangle.
"""
... | 51eff193ecc555bf6c436588c637b71c4295fdf7 | 605,337 |
def getMiddleOfLengthInsert(length):
"""
Get the position for inserting an item in the middle the given length.
INPUT <= integer length
OUTPUT => integer position
"""
return (length + 1) // 2 | 7b1c5582f6af0884ea15486fd65a481b0c727b03 | 605,339 |
def get_touchdowns(df):
"""
Get the total number of touchdowns for a player in a given week.
Input:
- Dataframe
Output:
- Dataframe with a new column representing total touchdowns"""
TD_sum = df['ReceivingTouchdowns'] + df['RushingTouchdowns'] + df['PassingTouchdowns']... | 0a18e3a1a2888ce62d9476cd5b7bf869c28a87d9 | 605,342 |
import json
def lyr_color(js):
"""
Import JSON of .lyr file and extract dictionary of value/color.
Requires using arcpy in ArcMap console to first extract .lyr file as JSON.
See arc_scripts.py.
Parameters:
js: Path to json file
Returns:
d: dictionary of valu... | a18415aae9c51849a2a5d00f4fcd52fc3d0d69d5 | 605,343 |
def detect_image_mimetype(image):
"""
A method to detect image type. It checks image header from raw data,
returns content type.
It handles PNG, JPEG, GIF, returns null string in case type is unknown.
:param image: Image raw data to detect type.
"""
if image[1:4] == 'PNG': return 'image... | c44a46e4347a1256069832e1b09c67b94b0213e4 | 605,347 |
from typing import List
from typing import Callable
def add_to_partition(elem: str, partitions: List[List[str]],
is_equiv: Callable[[str, str], bool]):
"""Helper function to add an element to an appropriate equivalence class
Adds the element to an existing class if one is available or cr... | c6c7771794d9fdf90a72aa525195cab536d175e3 | 605,349 |
import hashlib
def checksum_file(f, blocksize: int = 2 << 15) -> str:
"""
Checksum a file-like object.
"""
hasher = hashlib.sha256()
for block in iter(lambda: f.read(blocksize), b""):
hasher.update(block)
f.seek(0)
return hasher.hexdigest() | c40f53bf03612564f5817c1a732e246dce330ed3 | 605,351 |
import hmac
import hashlib
def hmac_sha1(key, s):
"""
returns the hmac-sha1 signature of key and string s.
key: bytes or bytearray
s: any type supported by hashlib
"""
hmacsha1 = hmac.new(key, digestmod=hashlib.sha1)
hmacsha1.update(s)
return hmacsha1.hexdigest() | e0017d4c52781e2aac1bf7ec67741f5085f8a0e7 | 605,353 |
def hal_append_call_name(name):
""" map an event name to a hal append call name """
return 'hal_append_{}'.format(name) | 5a22abd2d814d7de455eb98dbd12e378209f1e6a | 605,354 |
def find_last_true(sorted_list, true_criterion):
"""Suppose we have a list of item [item1, item2, ..., itemN].
If we do a mapping::
>>> def true_criterion(item):
... return item <= 6
>>> [true_criterion(item) for item in sorted_list]
[True, True, ... True(last true), False,... | 6fde612f38b42859295c9ebc71e464d7cfbbafc0 | 605,356 |
import torch
def inverse_element_wise_affine(x, st, compute_jacobian=True):
"""Transform x element-wise through an affine function y = exp(-s)*(x - t)
where s = st[...,0] and t = st[...,1] with s.shape == x.shape == t.shape
This is the inverse of `element_wise_affine` above for the same set of parameters ... | cbe5455b1c608273b803ffff735ce7062658a993 | 605,357 |
def index_union(df_src, df_target, use_target_names=True):
"""
Create the union of the indices for the two Pandas DataFrames.
This combines the "rows" of the two indices, so the index-types
must be identical.
:param df_src: Pandas Series or DataFrame.
:param df_target: Pandas Series or DataFra... | d69e8714405a6ee55f5e5b14c5e4f069e67b7b87 | 605,358 |
import unicodedata
def encode_scroll(text):
"""Encode text in the valid scroll file utf32 encoding. Returns encoded bytes."""
text = unicodedata.normalize('NFC', text)
text = ''.join((char for char in text if not unicodedata.combining(char)))
return text.encode('utf-32-be') | a1bfb3dc2b80eb5057cde985f9eb2c2f1186c194 | 605,359 |
def streaming_response_type(response_type: str) -> str:
"""Wrap the given response type with a reader for streaming functions."""
return f"std::unique_ptr<grpc::ClientReader<{response_type}>>" | 09105144d23e95438cb7c863d6d6eb27a01dde9f | 605,360 |
from typing import Callable
def bisect(first: int, last: int, condition: Callable[[int], int]):
"""
Returns the largest integer i with first <= i <= last such that
condition(i-1) is True.
Requires truth of condition(first) and that condition(i+1)
implies condition(i).
"""
left, right = fi... | 1fd4bd3fafa7df649fc79d696c0f339927736806 | 605,362 |
def accuracy(y_predictions, y_true):
"""
Calculate the accuracy.
Input
y_predictions: a one-dimensional numpy array of predicted classes (0s and 1s).
y_true: a one-dimensional numpy array of true classes (0s and 1s).
Output
acc: accuracy, a float between 0 and 1
"""
t,... | ccb4bfca2ba75d61493dba3e579f60ec314dc810 | 605,364 |
import csv
def load_event_list(file):
"""Load event list from tab delimited text file (csv-formated)
Supported input formats:
- [event_onset (float)][tab][event_offset (float)]
- [event_onset (float)][tab][event_offset (float)][tab][event_label (string)]
- [file(string)[tab][scene_la... | cc15096592ca156f33482d8eb95c7e00c80b829f | 605,365 |
from typing import List
def list_intersect(list1: List, list2: List):
"""
Intersection of two lists
:param list1: the first list
:param list2: the second list
:return: intersection of lists
"""
assert len(list1) == len(list2)
try:
return list(set(list1) & set(list2))
excep... | 7624d2495d65d988fd86f7871e022c682e2eaf01 | 605,367 |
def convert_seq_to_codons(seq):
"""Convert a string (sequence) into a list of 3-letter strings (triplets)."""
seq_codons = [seq[i : i + 3] for i in range(0, len(seq), 3)]
return seq_codons | 61d0f9609212bdc22f357bf1a4c8ad64d4884358 | 605,369 |
def mean(values):
"""Computes the mean of a sequence of numeric values.
Args:
values: Sequence of numeric values.
Returns:
The mean (floating point).
"""
if len(values) == 0:
raise ValueError("Cannot determine the mode of an empty sequence")
return sum(values) / len(val... | bdbf7820b005d87cf34658b2c1c90ee5c619af28 | 605,373 |
import math
def area_poligono_regular(num_lados: int, longitud: float) -> float:
""" Área de un polígono regular
Parámetros:
num_lados (int): Número de lados del polígono
longitud (float): Longitud de uno de los lados del polígono
Retorno:
float: Área del polígono regular redondeada a do... | ad560874b083a321c0cda7e6a4860951f573e0d2 | 605,379 |
import cmath
import math
def line_details(Z1_polar=True, Z1=[]
, Z0_polar=True, Z0=[]
, length=1
, CT=[1,1], VT=[1,1]
, Prim=True):
"""This function returns the line details for a MiCOM P543 relay
Inputs:
Z1_polar: Set True if the inp... | 154720abeef715745ee2616e858c5f610bf2cccc | 605,381 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.