content
stringlengths 35
416k
| sha1
stringlengths 40
40
| id
int64 0
710k
|
---|---|---|
def is_within_boundary(boundary_right_most_x, boundary_top_most_y,
boundary_left_most_x, boundary_bottom_most_y,
cursor):
"""
Checks if cursor is within given boundary
:param boundary_right_most_x:
:param boundary_top_most_y:
:param boundary_left_most_x:
:param boundary_bottom_most_y:
:param cursor:
:return: boolean
"""
if cursor.y < boundary_top_most_y:
return False
elif cursor.y > boundary_bottom_most_y:
return False
elif cursor.x < boundary_left_most_x:
return False
elif cursor.x > boundary_right_most_x:
return False
return True | d53106c9d525eb1bb51cfe4c30bc7e143ac6a517 | 707,332 |
import requests
from bs4 import BeautifulSoup
def get_game_page(url):
"""
Get the HTML for a given URL, where the URL is a game's page in the Xbox
Store
"""
try:
response = requests.get(url)
except (requests.exceptions.MissingSchema, ConnectionError):
return None
game_page = BeautifulSoup(response.content, "html.parser")
return game_page | 40d578ce8cda0b5139515e03f8308911169e0442 | 707,333 |
import math
def normalise_angle(angle: float) -> float:
"""Normalises the angle in the range (-pi, pi].
args:
angle (rad): The angle to normalise.
return:
angle (rad): The normalised angle.
"""
while angle > math.pi:
angle -= 2 * math.pi
while angle <= -math.pi:
angle += 2 * math.pi
return angle | 0a4cfa6e9da58bfdbb6cd4a04e7a742e8c432002 | 707,334 |
import re
def normalize_url(url):
"""Function to normalize the url. It will be used as document id value.
Returns:
the normalized url string.
"""
norm_url = re.sub(r'http://', '', url)
norm_url = re.sub(r'https://', '', norm_url)
norm_url = re.sub(r'/', '__', norm_url)
return norm_url | 79197b9fa1c47da601bdb9c34d626d236b649173 | 707,335 |
import fsspec
def is_remote_filesystem(fs: fsspec.AbstractFileSystem) -> bool:
"""
Validates if filesystem has remote protocol.
Args:
fs (``fsspec.spec.AbstractFileSystem``): An abstract super-class for pythonic file-systems, e.g. :code:`fsspec.filesystem(\'file\')` or :class:`datasets.filesystems.S3FileSystem`
"""
if fs is not None and fs.protocol != "file":
return True
else:
return False | c40f9bb4845bbd1fc1a4cf9fce2c1b366cd22354 | 707,336 |
def get_element_attribute_or_empty(element, attribute_name):
"""
Args:
element (element): The xib's element.
attribute_name (str): The desired attribute's name.
Returns:
The attribute's value, or an empty str if none exists.
"""
return element.attributes[attribute_name].value if element.hasAttribute(attribute_name) else "" | dbc7f5c24d321c40b46f1c78950d7cf254719b5c | 707,337 |
def substitute_word(text):
"""
word subsitution to make it consistent
"""
words = text.split(" ")
preprocessed = []
for w in words:
substitution = ""
if w == "mister":
substitution = "mr"
elif w == "missus":
substitution = "mrs"
else:
substitution = w
preprocessed.append(substitution)
return " ".join(preprocessed) | 0709f4223cb06ddfdc5e9704048f418f275429d1 | 707,338 |
def escape(line, chars):
"""Escapes characters 'chars' with '\\' in 'line'."""
def esc_one_char(ch):
if ch in chars:
return "\\" + ch
else:
return ch
return u"".join([esc_one_char(ch) for ch in line]) | f69409c92eacbbcab4232f7bb0ee244c77a4f219 | 707,339 |
def polinomsuzIntegralHesapla(veriler):
"""
Gelen verileri kullanarak integral hesaplar.
:param veriler: İntegrali hesaplanacak veriler. Liste tipinde olmalı.
"""
a,b=5,len(veriler)
deltax = 1
integral = 0
n = int((b - a) / deltax)
for i in range(n-1):
integral += deltax * (veriler[a] + veriler[a+deltax]) / 2
a += deltax
return integral | 468e02da8ff077b04456f71f0af6d77bf5a47d68 | 707,340 |
def _keep_extensions(files, extension):
""" Filters by file extension, this can be more than the extension!
E.g. .png is the extension, gray.png is a possible extension"""
if isinstance(extension, str):
extension = [extension]
def one_equal_extension(some_string, extension_list):
return any([some_string.endswith(one_extension) for one_extension in extension_list])
return list(filter(lambda x: one_equal_extension(x, extension), files)) | 009233e381e2015ff4d919338225057d94d40a82 | 707,341 |
import os
def check_racs_exists(base_dir: str) -> bool:
"""
Check if RACS directory exists
Args:
base_dir: Path to base directory
Returns:
True if exists, False otherwise.
"""
return os.path.isdir(os.path.join(base_dir, "EPOCH00")) | efad779a5310b10b2eeefdc10e90f0b78d428bf4 | 707,342 |
import os
def keypair_to_file(keypair):
"""Looks for the SSH private key for keypair under ~/.ssh/
Prints an error if the file doesn't exist.
Args:
keypair (string) : AWS keypair to locate a private key for
Returns:
(string|None) : SSH private key file path or None is the private key doesn't exist.
"""
file = os.path.expanduser("~/.ssh/{}.pem".format(keypair))
if not os.path.exists(file):
print("Error: SSH Key '{}' does not exist".format(file))
return None
return file | 0f544fd7d67530853bc4d8a91df01458d6408255 | 707,344 |
def hex2int(s: str):
"""Convert a hex-octets (a sequence of octets) to an integer"""
return int(s, 16) | ecdb3152f8c661c944edd2811d016fce225c3d51 | 707,345 |
def get_selection(selection):
"""Return a valid model selection."""
if not isinstance(selection, str) and not isinstance(selection, list):
raise TypeError('The selection setting must be a string or a list.')
if isinstance(selection, str):
if selection.lower() == 'all' or selection == '':
selection = None
elif selection.startswith('topics'):
selection = [selection]
return selection | 996d0af844e7c1660bcc67e24b33c31861296d93 | 707,346 |
def calc_hebrew_bias(probs):
"""
:param probs: list of negative log likelihoods for a Hebrew corpus
:return: gender bias in corpus
"""
bias = 0
for idx in range(0, len(probs), 16):
bias -= probs[idx + 1] + probs[idx + 5] + probs[idx + 9] + probs[idx + 13]
bias += probs[idx + 2] + probs[idx + 6] + probs[idx + 10] + probs[idx + 14]
return bias / 4 | 565be51b51d857c671ee44e090c5243e4d207942 | 707,347 |
from datetime import datetime
import sys
import glob
import os
def get_log_name(GLASNOST_ROOT, start_time, client_ip, mlab_server):
"""Helper method that given a test key, finds the logfile"""
log_glob = "%s/%s.measurement-lab.org/%s_%s_*" % (start_time.strftime('%Y/%m/%d'), mlab_server, start_time.strftime('%Y-%m-%dT%H:%M:%S'), client_ip)
if start_time < datetime(2010,1,8,5,7,0):
# before this time, the days are +1 in the filenames
dy = start_time.day + 1
log_glob = log_glob[:8] + '%02d'%dy + log_glob[10:]
log_glob = log_glob[:51] + '%02d'%dy + log_glob[53:]
if not sys.platform.startswith("linux"):
log_glob = log_glob.replace(':','_')
logs = glob.glob(os.path.join(GLASNOST_ROOT, log_glob))
if not logs:
# sometimes filename seconds differs by +/-1! change to wildcard
log_glob = log_glob[:61] + '?' + log_glob[62:]
logs = glob.glob(os.path.join(GLASNOST_ROOT, log_glob))
if not logs:
log_glob = log_glob[:60] + '?' + log_glob[61:]
logs = glob.glob(os.path.join(GLASNOST_ROOT, log_glob))
#endif
if len(logs)!=1:
raise Exception('!! log file not found (=%d): %s' % (len(logs),log_glob))
return logs[0] | 2492ad96563a7a93a9b00d9e5e20742b7f645ec3 | 707,348 |
import sys
import os
def caller_path(steps=1, names=None):
"""Return the path to the file of the current frames' caller."""
frame = sys._getframe(steps + 1)
try:
path = os.path.dirname(frame.f_code.co_filename)
finally:
del frame
if not path:
path = os.getcwd()
if names is not None:
path = os.path.join(path, *names)
return os.path.realpath(path) | 74d617d970df49854e98c7147d7b830e2dc230cf | 707,349 |
def is_hitachi(dicom_input):
"""
Use this function to detect if a dicom series is a hitachi dataset
:param dicom_input: directory with dicom files for 1 scan of a dicom_header
"""
# read dicom header
header = dicom_input[0]
if 'Manufacturer' not in header or 'Modality' not in header:
return False # we try generic conversion in these cases
# check if Modality is mr
if header.Modality.upper() != 'MR':
return False
# check if manufacturer is hitachi
if 'HITACHI' not in header.Manufacturer.upper():
return False
return True | c039c0535823edda2f66c3e445a5800a9890f155 | 707,350 |
import numpy
def readcrd(filename, REAL):
"""
It reads the crd file, file that contains the charges information.
Arguments
----------
filename : name of the file that contains the surface information.
REAL : data type.
Returns
-------
pos : (Nqx3) array, positions of the charges.
q : (Nqx1) array, value of the charges.
Nq : int, number of charges.
"""
pos = []
q = []
start = 0
with open(filename, 'r') as f:
lines = f.readlines()
for line in lines:
line = line.split()
if len(line) > 8 and line[0] != '*': # and start==2:
x = line[4]
y = line[5]
z = line[6]
q.append(REAL(line[9]))
pos.append([REAL(x), REAL(y), REAL(z)])
pos = numpy.array(pos)
q = numpy.array(q)
return pos, q | efafc2e53eebeacbe6a1a5b1e346d0e121fa7a62 | 707,351 |
def get_mention_token_dist(m1, m2):
""" Returns distance in tokens between two mentions """
succ = m1.tokens[0].doc_index < m2.tokens[0].doc_index
first = m1 if succ else m2
second = m2 if succ else m1
return max(0, second.tokens[0].doc_index - first.tokens[-1].doc_index) | 84052f805193b1d653bf8cc22f5d37b6f8de66f4 | 707,352 |
def FindDescendantComponents(config, component_def):
"""Return a list of all nested components under the given component."""
path_plus_delim = component_def.path.lower() + '>'
return [cd for cd in config.component_defs
if cd.path.lower().startswith(path_plus_delim)] | f9734442bbe3a01460970b3521827dda4846f448 | 707,353 |
def _get_source(loader, fullname):
"""
This method is here as a replacement for SourceLoader.get_source. That
method returns unicode, but we prefer bytes.
"""
path = loader.get_filename(fullname)
try:
return loader.get_data(path)
except OSError:
raise ImportError('source not available through get_data()',
name=fullname) | af43b79fa1d90abbbdb66d7d1e3ead480e27cdd1 | 707,354 |
from bs4 import BeautifulSoup
def create_bs4_obj(connection):
"""Creates a beautiful Soup object"""
soup = BeautifulSoup(connection, 'html.parser')
return soup | b3956b13756e29cd57a0e12457a2d665959fb03d | 707,355 |
import toml
def parse_config_file(path):
"""Parse TOML config file and return dictionary"""
try:
with open(path, 'r') as f:
return toml.loads(f.read())
except:
open(path,'a').close()
return {} | 599164f023c0db5bffa0b6c4de07654daae1b995 | 707,356 |
def courses_to_take(input):
"""
Time complexity: O(n) (we process each course only once)
Space complexity: O(n) (array to store the result)
"""
# Normalize the dependencies, using a set to track the
# dependencies more efficiently
course_with_deps = {}
to_take = []
for course, deps in input.items():
if not deps:
# Course with no dependencies:
# candidate to start the search
to_take.append(course)
else:
course_with_deps[course] = set(deps)
result = []
while to_take:
course = to_take.pop()
# Add course to journey
result.append(course)
# Iterate through courses and remove this course from
# dependencies
for prereq_course, prereq_deps in course_with_deps.items():
if course in prereq_deps:
prereq_deps.remove(course)
if not prereq_deps:
# Course has all the dependencies solved:
# add to the "to_take" queue
to_take.append(prereq_course)
del course_with_deps[prereq_course]
return result if len(result) == len(input) else None | eb0fe7271497fb8c5429360d37741d20f691ff3c | 707,357 |
def base_round(x, base):
"""
This function takes in a value 'x' and rounds it to the nearest multiple
of the value 'base'.
Parameters
----------
x : int
Value to be rounded
base : int
Tase for x to be rounded to
Returns
-------
int
The rounded value
"""
return base*round(x/base) | e5b1a1b81c7baf990b7921fe27a20075c0305935 | 707,358 |
def _update_schema_1_to_2(table_metadata, table_path):
"""
Given a `table_metadata` of version 1, update it to version 2.
:param table_metadata: Table Metadata
:param table_path: [String, ...]
:return: Table Metadata
"""
table_metadata['path'] = tuple(table_path)
table_metadata['schema_version'] = 2
table_metadata.pop('table_mappings', None)
return table_metadata | 6b0c8bc72100cceeb1b9da5552e53bc3c9bad3fa | 707,359 |
def encode_integer_leb128(value: int) -> bytes:
"""Encode an integer with signed LEB128 encoding.
:param int value: The value to encode.
:return: ``value`` encoded as a variable-length integer in LEB128 format.
:rtype: bytes
"""
if value == 0:
return b"\0"
# Calculate the number of bits in the integer and round up to the nearest multiple
# of 7. We need to add 1 bit because bit_length() only returns the number of bits
# required to encode the magnitude, but not the sign.
n_bits = value.bit_length() + 1
if n_bits % 7:
n_bits += 7 - (n_bits % 7)
# Bit operations force a negative integer to its unsigned two's-complement
# representation, e.g. -127 & 0xff = 0x80, -10 & 0xfff = 0xff6, etc. We use this to
# sign-extend the number *and* make it unsigned. Once it's unsigned, we can use
# ULEB128.
mask = (1 << n_bits) - 1
value &= mask
output = bytearray(n_bits // 7)
for i in range(n_bits // 7):
output[i] = 0x80 | (value & 0x7F)
value >>= 7
# Last byte shouldn't have the high bit set.
output[-1] &= 0x7F
return bytes(output) | b74832115a58248f4a45a880f657de6dd38b0d8d | 707,360 |
def process_name(i: int, of: int) -> str:
"""Return e.g. '| | 2 |': an n-track name with track `i` (here i=2) marked.
This makes it easy to follow each process's log messages, because you just
go down the line until you encounter the same number again.
Example: The interleaved log of four processes that each simulate a car
visiting a charging station. The processes have been named with
`process_name()`, and their log messages start with their `self.name`.
(Car #2 does not turn up in this snippet.)
| | | 3 arriving at 6
| 1 | | starting to charge at 7
0 | | | starting to charge at 7
| 1 | | leaving the bcs at 9
"""
lines = ["|"] * of
lines[i] = str(i)
return " ".join(lines) | bc3e0d06544b61249a583b6fa0a010ec917c0428 | 707,361 |
def cards_db(db):
"""
CardsDB object that's empty.
"""
db.delete_all()
return db | 9649b309990325eca38ed89c6e9d499b41786dab | 707,362 |
def get_best_trial(trial_list, metric):
"""Retrieve the best trial."""
return max(trial_list, key=lambda trial: trial.last_result.get(metric, 0)) | c5ddbb9ad00cddaba857d0d0233f6452e6702552 | 707,363 |
def convert_to_clocks(duration, f_sampling=200e6, rounding_period=None):
"""
convert a duration in seconds to an integer number of clocks
f_sampling: 200e6 is the CBox sampling frequency
"""
if rounding_period is not None:
duration = max(duration//rounding_period, 1)*rounding_period
clock_duration = int(duration*f_sampling)
return clock_duration | 602b00af689cc25374b7debd39264b438de44baa | 707,364 |
def multiply(x):
"""Multiply operator.
>>> multiply(2)(1)
2
"""
def multiply(y):
return y * x
return multiply | 77d983090e03820d03777f1f69cfc7b0ef6d88a2 | 707,365 |
def expose(policy):
"""
Annotate a method to permit access to contexts matching an authorization
policy. The annotation may be specified multiple times. Methods lacking any
authorization policy are not accessible.
::
@mitogen.service.expose(policy=mitogen.service.AllowParents())
def unsafe_operation(self):
...
:param mitogen.service.Policy policy:
The policy to require.
"""
def wrapper(func):
func.mitogen_service__policies = [policy] + getattr(
func, "mitogen_service__policies", []
)
return func
return wrapper | 74caed36885e5ea947a2ecdac9a2cddf2f5f51b0 | 707,366 |
import base64
def didGen(vk, method="dad"):
"""
didGen accepts an EdDSA (Ed25519) key in the form of a byte string and returns a DID.
:param vk: 32 byte verifier/public key from EdDSA (Ed25519) key
:param method: W3C did method string. Defaults to "dad".
:return: W3C DID string
"""
if vk is None:
return None
# convert verkey to jsonable unicode string of base64 url-file safe
vk64u = base64.urlsafe_b64encode(vk).decode("utf-8")
return "did:{0}:{1}".format(method, vk64u) | 9991491ab486d8960633190e3d3baa9058f0da50 | 707,367 |
import pickle
def load_dataset(datapath):
"""Extract class label info """
with open(datapath + "/experiment_dataset.dat", "rb") as f:
data_dict = pickle.load(f)
return data_dict | 3a0d8ef9c48036879b32ab0e74e52429418297c0 | 707,368 |
from typing import Dict
from pathlib import Path
import json
def load_json(filename: str) -> Dict:
"""Read JSON file from metadata folder
Args:
filename: Name of metadata file
Returns:
dict: Dictionary of data
"""
filepath = (
Path(__file__).resolve().parent.parent.joinpath("metadata").joinpath(filename)
)
metadata: Dict = json.loads(filepath.read_text())
return metadata | 37d9f08344cf2a544c12fef58992d781556a9efd | 707,369 |
def get_short_size(size_bytes):
"""
Get a file size string in short format.
This function returns:
"B" size (e.g. 2) when size_bytes < 1KiB
"KiB" size (e.g. 345.6K) when size_bytes >= 1KiB and size_bytes < 1MiB
"MiB" size (e.g. 7.8M) when size_bytes >= 1MiB
size_bytes: File size in bytes
"""
if size_bytes < 1024:
return str(size_bytes)
if size_bytes < 1048576:
return f"{size_bytes / 1024:.1f}K"
return f"{size_bytes / 1048576:.1f}M" | ebc9ba25c01dedf0d15b9e2a21b67989763bc8c8 | 707,370 |
import argparse
def get_arguments():
"""parse provided command line arguments"""
parser = argparse.ArgumentParser()
parser.add_argument(
"--server",
help="Where to send the output - use https URL to POST "
"to the dognews server API, or a file name to save locally as json",
required=True)
parser.add_argument(
"--imagefolder",
help="Where to save the thumbnails",
required=True)
parser.add_argument(
"--token",
help="Authentication token associated with the submit-bot user, generated in the dognews server app",
required=True)
return parser.parse_args() | bc7aa7fefda65ade99820e786a460e07a5037f46 | 707,371 |
def summed_timeseries(timeseries):
"""
Give sum of value series against timestamps for given timeseries containing several values per one timestamp
:param timeseries:
:return:
"""
sum_timeseries = []
for i in range(len(timeseries)):
if len(timeseries[i])>1:
sum_timeseries.append([timeseries[i][0], '%.3f' % (sum(timeseries[i][1:]))])
return sum_timeseries | 618505f8f0960900a993bb6d9196d17bf31d02a6 | 707,372 |
import pathlib
def path_check(path_to_check):
"""
Check that the path given as a parameter is an valid absolute path.
:param path_to_check: string which as to be checked
:type path_to_check: str
:return: True if it is a valid absolute path, False otherwise
:rtype: boolean
"""
path = pathlib.Path(path_to_check)
if not path.is_absolute():
return False
return True | 41b3537b0be2c729ba993a49863df4a15119db8b | 707,373 |
import time
def timefunc(f):
"""Simple timer function to identify slow spots in algorithm.
Just import function and put decorator @timefunc on top of definition of any
function that you want to time.
"""
def f_timer(*args, **kwargs):
start = time.time()
result = f(*args, **kwargs)
end = time.time()
print(f.__name__, 'took {:.2f} seconds'.format(end - start))
return result, (end - start)
return f_timer | 56d5d052fa559e1b7c797ed00ee1b82c8e2126d6 | 707,374 |
def gen_endpoint(endpoint_name, endpoint_config_name):
"""
Generate the endpoint resource
"""
endpoint = {
"SagemakerEndpoint": {
"Type": "AWS::SageMaker::Endpoint",
"DependsOn": "SagemakerEndpointConfig",
"Properties": {
"EndpointConfigName": {
"Fn::GetAtt": ["SagemakerEndpointConfig", "EndpointConfigName"]
},
"EndpointName": endpoint_name,
"RetainAllVariantProperties": False,
},
},
}
return endpoint | bc658e6aebc41cfddefe0e77b2d65748a84789c5 | 707,375 |
def float_or_none(val, default=None):
"""
Arguments:
- `x`:
"""
if val is None:
return default
else:
try:
ret = float(val)
except ValueError:
ret = default
return ret | 00beabbd2fe4633e6738fea2220d55d096bfa91e | 707,376 |
from typing import List
async def get_sinks_metadata(sinkId: str) -> List: # pylint: disable=unused-argument
"""Get metadata attached to sinks
This adapter does not implement metadata. Therefore this will always result
in an empty list!
"""
return [] | 458b674cc59a80572fd9676aec81d0a7c353a8f3 | 707,377 |
def fn_lin(x_np, *, multiplier=3.1416):
""" Linear function """
return x_np * multiplier | e64f112b486ea6a0bdf877d67c98417ae90f03b3 | 707,378 |
def get_MACD(df, column='Close'):
"""Function to get the EMA of 12 and 26"""
df['EMA-12'] = df[column].ewm(span=12, adjust=False).mean()
df['EMA-26'] = df[column].ewm(span=26, adjust=False).mean()
df['MACD'] = df['EMA-12'] - df['EMA-26']
df['Signal'] = df['MACD'].ewm(span=9, adjust=False).mean()
df['Histogram'] = df['MACD'] - df['Signal']
return df | b5eb25c9a5097fb2a0d874d62b6ab1957bbe3f11 | 707,379 |
import random
def summary_selector(summary_models=None):
"""
Will create a function that take as input a dict of summaries :
{'T5': [str] summary_generated_by_T5, ..., 'KW': [str] summary_generted_by_KW}
and randomly return a summary that has been generated by one of the summary_model in summary_model
if summary_models is none, will not use summaru
:param summary_models: list of str(SummarizerModel)
:return: function [dict] -> [str]
"""
if summary_models is None or len(summary_models) == 0 or \
(len(summary_models) == 1 and summary_models[0] == ""):
return lambda x: ""
summary_model = random.choice(summary_models)
return lambda summaries_dict: summaries_dict[summary_model] | b8a2336546324d39ff87ff5b59f4f1174e5dd54c | 707,380 |
from typing import Match
def _replace_fun_unescape(m: Match[str]) -> str:
""" Decode single hex/unicode escapes found in regex matches.
Supports single hex/unicode escapes of the form ``'\\xYY'``,
``'\\uYYYY'``, and ``'\\UYYYYYYYY'`` where Y is a hex digit. Only
decodes if there is an odd number of backslashes.
.. versionadded:: 0.2
Parameters
----------
m : regex match
Returns
-------
c : str
The unescaped character.
"""
slsh = b'\\'.decode('ascii')
s = m.group(0)
count = s.count(slsh)
if count % 2 == 0:
return s
else:
c = chr(int(s[(count + 1):], base=16))
return slsh * (count - 1) + c | 3fdb275e3c15697e5302a6576b4d7149016299c0 | 707,382 |
from pathlib import Path
import os
def get_absolute_filename(user_inputted_filename: str) -> Path:
"""Clean up user inputted filename path, wraps os.path.abspath, returns Path object"""
filename_location = Path(os.path.abspath(user_inputted_filename))
return filename_location | d8d704f4adcaa443658789c6d178b3ddb05552d0 | 707,383 |
def check_answer(guess, a_follower, b_follower):
"""Chcek if the user guessed the correct option"""
if a_follower > b_follower:
return guess == "a"
else:
return guess == "b" | acd1e78026f89dd1482f4471916472d35edf68a7 | 707,384 |
import argparse
def command_line_arg_parser():
"""
Command line argument parser. Encrypts by default. Decrypts when --decrypt flag is passed in.
"""
parser = argparse.ArgumentParser(description='Parses input args')
parser.add_argument('input_file', type=str,
help='Path to input file location')
parser.add_argument('output_file', type=str, default='./output_data',
help='Path to output file location')
parser.add_argument('key_file', type=str,
help='Path to public or private key file')
parser.add_argument('--decrypt', dest='decrypt', action='store_true',
help='Private key file (for decryption)')
return parser | c1e9305e2967368fb36ad8fcdbb654ef04f8d3bf | 707,385 |
from typing import Dict
def canonical_for_code_system(jcs: Dict) -> str:
"""get the canonical URL for a code system entry from the art decor json. Prefer FHIR URIs over the generic OID URI.
Args:
jcs (Dict): the dictionary describing the code system
Returns:
str: the canonical URL
"""
if "canonicalUriR4" in jcs:
return jcs["canonicalUriR4"]
else:
return jcs["canonicalUri"] | f111a4cb65fa75799e799f0b088180ef94b71cc8 | 707,386 |
from typing import List
def create_unique_views(rows: list, fields: List[str]):
"""Create views for each class objects, default id should be a whole row"""
views = {}
for r in rows:
values = [r[cname] for cname in fields]
if any(isinstance(x, list) for x in values):
if all(isinstance(x, list) for x in values) and len({len(x) for x in values}) == 1:
# all its value is in a list
for j in range(len(values[0])):
key = ",".join(str(values[i][j]) for i in range(len(values)))
views[key] = [values[i][j] for i in range(len(values))]
else:
# assert False
key = ",".join((str(x) for x in values))
views[key] = values
else:
key = ",".join((str(x) for x in values))
views[key] = values
views = [{cname: r[i] for i, cname in enumerate(fields)} for r in views.values()]
return views | 24b311c8b013f742e69e7067c1f1bafe0044c940 | 707,387 |
def add_merge_variants_arguments(parser):
"""
Add arguments to a parser for sub-command "stitch"
:param parser: argeparse object
:return:
"""
parser.add_argument(
"-vp",
"--vcf_pepper",
type=str,
required=True,
help="Path to VCF file from PEPPER SNP."
)
parser.add_argument(
"-vd",
"--vcf_deepvariant",
type=str,
required=True,
help="Path to VCF file from DeepVariant."
)
parser.add_argument(
"-o",
"--output_dir",
type=str,
required=True,
help="Path to output directory."
)
return parser | 5fd6bc936ba1d17ea86a49499e1f6b816fb0a389 | 707,389 |
def escape_html(text: str) -> str:
"""Replaces all angle brackets with HTML entities."""
return text.replace('<', '<').replace('>', '>') | f853bcb3a69b8c87eb3d4bcea5bbca66376c7db4 | 707,390 |
import torch
def calc_driver_mask(n_nodes, driver_nodes: set, device='cpu', dtype=torch.float):
"""
Calculates a binary vector mask over graph nodes with unit value on the drive indeces.
:param n_nodes: numeber of driver nodes in graph
:param driver_nodes: driver node indeces.
:param device: the device of the `torch.Tensor`
:param dtype: the data type of the `torch.Tensor`
:return: the driver mask vector.
"""
driver_mask = torch.zeros(n_nodes, device=device, dtype=dtype)
driver_mask[list(driver_nodes)] = 1
return driver_mask | 2d2a08a86629ece190062f68dd25fc450d0fd84e | 707,391 |
def open_file(name):
"""
Return an open file object.
"""
return open(name, 'r') | 8921ee51e31ac6c64d9d9094cedf57502a2aa436 | 707,392 |
import math
def _bit_length(n):
"""Return the number of bits necessary to store the number in binary."""
try:
return n.bit_length()
except AttributeError: # pragma: no cover (Python 2.6 only)
return int(math.log(n, 2)) + 1 | bea6cb359c7b5454bdbb1a6c29396689035592d7 | 707,393 |
def solution(n):
"""
Return the product of a,b,c which are Pythagorean Triplet that satisfies
the following:
1. a < b < c
2. a**2 + b**2 = c**2
3. a + b + c = 1000
>>> solution(1000)
31875000
"""
product = -1
d = 0
for a in range(1, n // 3):
"""Solving the two equations a**2+b**2=c**2 and a+b+c=N eliminating c
"""
b = (n * n - 2 * a * n) // (2 * n - 2 * a)
c = n - a - b
if c * c == (a * a + b * b):
d = a * b * c
if d >= product:
product = d
return product | a0bf0f0bde50f536f6c91f2b52571be38e494cea | 707,394 |
import sys
def python2_binary():
"""Tries to find a python 2 executable."""
# Using [0] instead of .major here to support Python 2.6.
if sys.version_info[0] == 2:
return sys.executable or "python"
else:
return "python2" | 054870972e68aa5b9e8609d93b8a82ad5e95d634 | 707,395 |
def with_metaclass(meta, *bases):
"""A Python 2/3 compatible way of declaring a metaclass.
Taken from `Jinja 2 <https://github.com/mitsuhiko/jinja2/blob/master/jinja2
/_compat.py>`_ via `python-future <http://python-future.org>`_. License:
BSD.
Use it like this::
class MyClass(with_metaclass(MyMetaClass, BaseClass)):
pass
"""
class _Metaclass(meta):
"""Inner class"""
__call__ = type.__call__
__init__ = type.__init__
def __new__(cls, name, this_bases, attrs):
if this_bases is None:
return type.__new__(cls, name, (), attrs)
return meta(name, bases, attrs)
return _Metaclass(str('temporary_class'), None, {}) | 0fe8e95fe29821e4cda8b66ff54ddd1b73e51243 | 707,396 |
from typing import List
def join_with_and(words: List[str]) -> str:
"""Joins list of strings with "and" between the last two."""
if len(words) > 2:
return ", ".join(words[:-1]) + ", and " + words[-1]
elif len(words) == 2:
return " and ".join(words)
elif len(words) == 1:
return words[0]
else:
return "" | ecb2c1fa060657f2ea4173c4382a81c9b42beeb9 | 707,397 |
def is_url_relative(url):
"""
True if a URL is relative, False otherwise.
"""
return url[0] == "/" and url[1] != "/" | 91e1cb756a4554973e53fd1f607515577bc63294 | 707,398 |
from heapq import heappop, heappush
def dijkstra(vertex_count: int, source: int, edges):
"""Uses Dijkstra's algorithm to find the shortest path in a graph.
Args:
vertex_count: The number of vertices.
source : Vertex number (0-indexed).
edges : List of (cost, edge) (0-indexed).
Returns:
costs : List of the shortest distance.
parents: List of parent vertices.
Landau notation: O(|Edges|log|Vertices|).
See:
https://atcoder.jp/contests/abc191/submissions/19964078
https://atcoder.jp/contests/abc191/submissions/19966232
"""
hq = [(0, source)] # weight, vertex number (0-indexed)
costs = [float("inf") for _ in range(vertex_count)]
costs[source] = 0
pending = -1
parents = [pending for _ in range(vertex_count)]
while hq:
cost, vertex = heappop(hq)
if cost > costs[vertex]:
continue
for weight, edge in edges[vertex]:
new_cost = cost + weight
if new_cost < costs[edge]:
costs[edge] = new_cost
parents[edge] = vertex
heappush(hq, (new_cost, edge))
return costs, parents | d33f8dc28bf07154ffd7582a5bdd7161e195f331 | 707,399 |
def contains(poly0, poly1):
""" Does poly0 contain poly1?
As an initial implementation, returns True if any vertex of poly1 is within
poly0.
"""
# check for bounding box overlap
bb0 = (min(p[0] for p in poly0), min(p[1] for p in poly0),
max(p[0] for p in poly0), max(p[1] for p in poly0))
bb1 = (min(p[0] for p in poly1), min(p[1] for p in poly1),
max(p[0] for p in poly1), max(p[1] for p in poly1))
if ((bb0[0] > bb1[2])
or (bb0[2] < bb1[0])
or (bb0[1] > bb1[3])
or (bb0[3] < bb1[1])):
return False
# check each vertex
def _isleft(p, p0, p1):
return ((p1[0]-p0[0])*(p[1]-p0[1]) - (p[0]-p0[0])*(p1[1]-p0[1])) > 0
for p in poly1:
wn = 0
for i in range(len(poly0)-1):
p0 = poly0[i]
p1 = poly0[i+1]
if p0[1] <= p[1] < p1[1]: # upward crossing
if _isleft(p, p0, p1):
wn += 1
elif p0[1] >= p[1] > p1[1]:
if not _isleft(p, p0, p1):
wn -= 1
if wn != 0:
return True
return False | 26ea4bd17a55ed05afa049a9aaab5237f0965674 | 707,400 |
import os
import json
def get_ids_in_annotations(scene, frame, quality):
"""
Returns a set of all ids found in annotations.
"""
annotations_path = os.path.join(scene, '%sPose3d_stage1' % quality,
'body3DScene_%s.json' % frame)
if not os.path.exists(annotations_path):
return set()
with open(annotations_path, 'r') as f:
annots = json.load(f)
return set([b['id'] for b in annots['bodies']]) | 9e754af7ec397e9a36151b7f49f69d2de6ca0128 | 707,401 |
import os
import errno
def _ReapUntilProcessExits(monitored_pid):
"""Reap processes until |monitored_pid| exits, then return its exit status.
This will also reap any other processes ready to be reaped immediately after
|monitored_pid| is reaped.
"""
pid_status = None
options = 0
while True:
try:
(pid, status, _) = os.wait3(options)
# Capture status of monitored_pid so we can return it.
if pid == monitored_pid:
pid_status = status
# Switch to nohang so we can churn through the zombies w/out getting
# stuck on live orphaned processes.
options = os.WNOHANG
# There may be some more child processes still running, but none of them
# have exited/finished. Don't wait for those as we'll throw an error in
# the caller.
if pid_status is not None and pid == 0 and status == 0:
break
except OSError as e:
if e.errno == errno.ECHILD:
break
elif e.errno != errno.EINTR:
raise
return pid_status | ef540cc60634fe13ddc58b434f7fabe01109ddda | 707,402 |
def compute_wolfe_gap(point_x, objective_function, feasible_region):
"""Compute the Wolfe gap given a point."""
grad = objective_function.evaluate_grad(point_x.cartesian_coordinates)
v = feasible_region.lp_oracle(grad)
wolfe_gap = grad.dot(point_x.cartesian_coordinates - v)
return wolfe_gap | f2b09a232063599aa7525a70e6d3a0d8bafb57e7 | 707,403 |
import numpy
def ifft(a, axis):
"""
Fourier transformation from grid to image space, along a given axis.
(inverse Fourier transform)
:param a: numpy array, 1D or 2D (`uv` grid to transform)
:param axis: int; axes over which to calculate
:return: numpy array (an image in `lm` coordinate space)
"""
return numpy.fft.fftshift(
numpy.fft.ifft(numpy.fft.ifftshift(a, axis), axis=axis), axis
) | 3a96d6b615c8da63deaeca5e98a4f82f18fec8dd | 707,404 |
from typing import Dict
from typing import Any
def addon_config() -> Dict[str, Any]:
"""Sample addon config."""
return {
"package-name": "djangocms-blog",
"installed-apps": [
"filer",
"easy_thumbnails",
"aldryn_apphooks_config",
"parler",
"taggit",
"taggit_autosuggest",
"meta",
"djangocms_blog",
"sortedm2m",
],
"settings": {
"META_SITE_PROTOCOL": "https",
"META_USE_SITES": True,
"MIDDLEWARE": ["django.middleware.gzip.GZipMiddleware"],
},
"urls": [["", "djangocms_blog.taggit_urls"]],
"message": "Please check documentation to complete the setup",
} | f4266735ef2f0809e5802abed54dfde4c1cbd708 | 707,406 |
import math
def to_half_life(days):
"""
Return the constant [1/s] from the half life length [day]
"""
s= days * 3600*24
return -math.log(1/2)/s | af7724dfb9442bf1f5e931df5dd39b31d0e78091 | 707,407 |
import numpy
def TransformInversePoints(T,points):
"""Transforms a Nxk array of points by the inverse of an affine matrix"""
kminus = T.shape[1]-1
return numpy.dot(points-numpy.tile(T[0:kminus,kminus],(len(points),1)),T[0:kminus,0:kminus]) | 7e04a741c6ad0ec08e40ab393a703a1878ef784a | 707,408 |
import inspect
def get_default_args(func):
"""
Return dict for parameter name and default value.
Parameters
----------
func : Callable
A function to get parameter name and default value.
Returns
-------
Dict
Parameter name and default value.
Examples
--------
>>> def test_func(a: int, b: str = "c") -> int:
... return a+1
>>> get_default_args(test_func)
{'b': 'c'}
>>> def test_func2(a: int = 1, b="c") -> int:
... return a+1
>>> get_default_args(test_func2)
{'a': 1, 'b': 'c'}
"""
signature = inspect.signature(func)
return {
k: v.default
for k, v in signature.parameters.items()
if v.default is not inspect.Parameter.empty
} | dcc75dceae1385868866d668aa021584547190df | 707,409 |
def sec_to_time(seconds):
"""Transform seconds into a formatted time string.
Parameters
-----------
seconds : int
Seconds to be transformed.
Returns
-----------
time : string
A well formatted time string.
"""
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
return "%02d:%02d:%02d" % (h, m, s) | 59fcfe2f53d11ea7daac736b59b5eaeb72172dba | 707,410 |
import logging
def getLog():
"""simple wrapper around basic logger"""
return logging | b51942d2ed02f9ea7faf0a626715ec07e1677c88 | 707,411 |
from datetime import datetime
def _date(defval, t):
"""
支持的格式:
unix 时间戳
yyyy-mm-dd 格式的日期字符串
yyyy/mm/dd 格式的日期字符串
yyyymmdd 格式的日期字符串
如果年月日其中有一项是0,将被转换成 1
"""
if t is None:
return defval
if isinstance(t, (int, float)):
return datetime.fromtimestamp(t).strftime('%Y-%m-%d %H:%M:%S')
lt = len(t)
if lt < 8:
return defval
if lt == 8:
format_str = '%Y%m%d'
else:
t = t.replace('/', '-')
format_str = '%Y-%m-%d %H:%M:%S'
if lt > 19:
format_str += '.%f'
try:
return str(datetime.strptime(t, format_str))
except:
return defval | e8a1121da89d9dc46bdce5d1b8c70ec973909abb | 707,412 |
import re
def get_requirements(filename):
"""
Helper function to read the list of requirements from a file
"""
dependency_links = []
with open(filename) as requirements_file:
requirements = requirements_file.read().strip('\n').splitlines()
requirements = [req for req in requirements if not req.startswith('#')]
for i, req in enumerate(requirements):
if ':' in req:
match_obj = re.match(r"git\+(?:https|ssh|http):.*#egg=(.*)-(.*)", req)
assert match_obj, "Cannot make sense of url {}".format(req)
requirements[i] = "{req}=={ver}".format(req=match_obj.group(1), ver=match_obj.group(2))
dependency_links.append(req)
return requirements, dependency_links | 292d45ab8e7f8523734326869bb1dd05c6f395f1 | 707,413 |
import os
def normalise_dir_pattern(repo_dir, d):
"""
if d is a relative path, prepend the repo_dir to it
"""
if not d.startswith(repo_dir):
return os.path.join(repo_dir, d)
else:
return d | ea240eda35f7c85e652f78f5e80eb3ac16ce4e98 | 707,414 |
import subprocess
def get_disk_usage():
"""
Handle determining disk usage on this VM
"""
disk = {}
# Get the amount of general disk space used
cmd_out = subprocess.getstatusoutput('df -h | grep "/dev/xvda1"')[1]
cmd_parts = cmd_out.split()
disk["gen_disk_used"] = cmd_parts[2]
disk["gen_disk_total"] = cmd_parts[3]
disk["gen_disk_percent"] = cmd_parts[4]
# Get the amount of Docker disk space used
cmd_out = subprocess.getstatusoutput('df -h | grep "tmpfs"')[1]
cmd_parts = cmd_out.split()
disk["docker_disk_used"] = cmd_parts[2]
disk["docker_disk_total"] = cmd_parts[3]
disk["docker_disk_percent"] = cmd_parts[4]
return disk | e4f65e1c652a74086c111a3c80d5f6c9db94a66e | 707,415 |
from typing import OrderedDict
def _find_in_iterable_case_insensitive(iterable, name):
"""
Return the value matching ``name``, case insensitive, from an iterable.
"""
iterable = list(OrderedDict.fromkeys([k for k in iterable]))
iterupper = [k.upper() for k in iterable]
try:
match = iterable[iterupper.index(name.upper())]
except (ValueError, AttributeError):
match = None
return match | 548c951b08fb07251fda1b8918282462c8d0351a | 707,416 |
def _amplify_ep(text):
"""
check for added emphasis resulting from exclamation points (up to 4 of them)
"""
ep_count = text.count("!")
if ep_count > 4:
ep_count = 4
# (empirically derived mean sentiment intensity rating increase for
# exclamation points)
ep_amplifier = ep_count * 0.292
return ep_amplifier | 8f78a5f24aa22b5f2b4927131bfccf22ccc69ff3 | 707,417 |
import argparse
def options_handler():
"""Validates and parses script arguments.
Returns:
Namespace: Parsed arguments object.
"""
parser = argparse.ArgumentParser(description="Downloads XSOAR packs as zip and their latest docker images as tar.")
parser.add_argument('-p', '--packs',
help="A list of pack names as they appear in https://xsoar.pan.dev/marketplaceEither provided "
"via a path to a file that contains the packs list (separated by new lines) or "
"a string of comma separated packs (e.g. Base,AutoFocus)",
required=False)
parser.add_argument('-o', '--output_path',
help="The path where the files will be saved to.",
required=False, default=".")
parser.add_argument('-sp', '--skip_packs',
help="Don't download packs.",
required=False, action='store_true')
parser.add_argument('-sd', '--skip_docker',
help="Don't download docker images.",
required=False, action='store_true')
parser.add_argument('--insecure',
help="Skip certificate validation.", dest='feature', action='store_true')
parser.set_defaults(skip_packs=False, skip_docker=False, insecure=False)
return parser.parse_args() | d3a650d58d0444981b010e230cb5111245a00bc7 | 707,418 |
import os
def get_prefix_by_xml_filename(xml_filename):
"""
Obtém o prefixo associado a um arquivo xml
Parameters
----------
xml_filename : str
Nome de arquivo xml
Returns
-------
str
Prefixo associado ao arquivo xml
"""
file, ext = os.path.splitext(xml_filename)
return file | 169b5571ae0bfca2a923c4030325002503790f6e | 707,419 |
import base64
def create_api_headers(token):
"""
Create the API header.
This is going to be sent along with the request for verification.
"""
auth_type = 'Basic ' + base64.b64encode(bytes(token + ":")).decode('ascii')
return {
'Authorization': auth_type,
'Accept': 'application/json',
'Content-Type': 'application/json'
} | 41ba1e22898dab2d42dde52e4458abc40640e957 | 707,420 |
def counting_sort(array, low, high):
"""Razeni pocitanim (CountingSort). Seradte zadane pole 'array'
pricemz o poli vite, ze se v nem nachazeji pouze hodnoty v intervalu
od 'low' po 'high' (vcetne okraju intervalu). Vratte serazene pole.
"""
counts = [0 for i in range(high - low + 1)]
for elem in array:
counts[elem - low] += 1
current = 0
for i in range(high - low + 1):
for j in range(current, current + counts[i]):
array[j] = i + low
current += counts[i]
return array | bd4ccccdb24786ec3f3d867afe1adf340c9e53b5 | 707,421 |
import re
def normalize_archives_url(url):
"""
Normalize url.
will try to infer, find or guess the most useful archives URL, given a URL.
Return normalized URL, or the original URL if no improvement is found.
"""
# change new IETF mailarchive URLs to older, still available text .mail archives
new_ietf_exp = re.compile(
"https://mailarchive\\.ietf\\.org/arch/search/"
"\\?email_list=(?P<list_name>[\\w-]+)"
)
ietf_text_archives = (
r"https://www.ietf.org/mail-archive/text/\g<list_name>/"
)
new_ietf_browse_exp = re.compile(
r"https://mailarchive.ietf.org/arch/browse/(?P<list_name>[\w-]+)/?"
)
match = new_ietf_exp.match(url)
if match:
return re.sub(new_ietf_exp, ietf_text_archives, url)
match = new_ietf_browse_exp.match(url)
if match:
return re.sub(new_ietf_browse_exp, ietf_text_archives, url)
return url | e8a5351af28338c77c3e94fdf2b81e22c7a6edfd | 707,422 |
def getIsolatesFromIndices(indices):
"""
Extracts the isolates from the indices of a df_X.
:param pandas.index indices:
cn.KEY_ISOLATE_DVH, cn.KEY_ISOLATE_MMP
:return dict: keyed by cn.KEY_ISOLATE_DVH, cn.KEY_ISOLATE_MMP
values correspond to rows element in the index
"""
keys = [n for n in indices.names]
result = {}
for idx, key in enumerate(keys):
result[key] = [v[idx] for v in indices.values]
return result | 4e9200c722ce0c478d13eddcc799f4a8f7cab6db | 707,423 |
import os
def ensuredir(dirpath):
"""
ensure @dirpath exists and return it again
raises OSError on other error than EEXIST
"""
try:
os.makedirs(dirpath, 0o700)
except FileExistsError:
pass
return dirpath | 447f4542faa00e8928e30f0a9793436b8377964a | 707,424 |
import ast
from typing import Optional
def get_qualname(node: ast.AST) -> Optional[str]:
"""
If node represents a chain of attribute accesses, return is qualified name.
"""
parts = []
while True:
if isinstance(node, ast.Name):
parts.append(node.id)
break
elif isinstance(node, ast.Attribute):
parts.append(node.attr)
node = node.value
else:
return None
return '.'.join(reversed(parts)) | 0d08b25a50b7d159f5df3b0b17282725eb748f38 | 707,425 |
import re
def d(vars):
"""List of variables starting with string "df" in reverse order. Usage: d(dir())
@vars list of variables output by dir() command
"""
list_of_dfs = [item for item in vars if (item.find('df') == 0 and item.find('_') == -1 and item != 'dfs')]
list_of_dfs.sort(key=lambda x:int(re.sub("[^0-9]", "", x.replace('df',''))) if len(x) > 2 else 0, reverse=True)
return list_of_dfs | 4961ae70a61e45b81e06e55ee9553ff61fd45d18 | 707,426 |
def get_reset_state_name(t_fsm):
"""
Returns the name of the reset state.
If an .r keyword is specified, that is the name of the reset state.
If the .r keyword is not present, the first state defined
in the transition table is the reset state.
:param t_fsm: blifparser.BlifParser().blif.fsm object
:return str reset_state: name of the reset state
"""
reset_state = None
if t_fsm.r is None:
if len(t_fsm.transtable) > 0:
reset_state = t_fsm.transtable[0][1]
else:
reset_state = t_fsm.r.name
return reset_state | c65ea80f94f91b31a179faebc60a97f7260675c4 | 707,427 |
def border_msg(msg: str):
"""
This function creates boarders in the top and bottom of text
"""
row = len(msg)
h = ''.join(['+'] + ['-' * row] + ['+'])
return h + "\n" + msg + "\n" + h | cdd9d17ba76014f4c80b9c429aebbc4ca6f959c3 | 707,428 |
def _qual_arg(user_value,
python_arg_name,
gblock_arg_name,
allowable):
"""
Construct and sanity check a qualitative argument to
send to gblocks.
user_value: value to try to send to gblocks
python_arg_name: name of python argument (for error string)
gblock_arg_name: name of argument in gblocks
allowable: dictionary of allowable values mapping python to
whatever should be jammed into gblocks
"""
if user_value in allowable.keys():
return "-{}={}".format(gblock_arg_name,allowable[user_value])
else:
err = "\n\n{} '{}' not recognized\n".format(python_arg_name,
user_value)
err += "must be one of:\n"
allowed = list(allowable)
allowed.sort()
for a in allowed:
err += " {}\n".format(a)
raise ValueError(err) | 7bf6717ee3dbeb533902773c86316d2bbdcd59a9 | 707,430 |
def is_valid_ip(ip_addr):
"""
:param ip_addr:
:return:
"""
octet_ip = ip_addr.split(".")
int_octet_ip = [int(i) for i in octet_ip]
if (len(int_octet_ip) == 4) and \
(0 <= int_octet_ip[0] <= 255) and \
(0 <= int_octet_ip[1] <= 255) and \
(0 <= int_octet_ip[2] <= 255) and \
(0 <= int_octet_ip[3] <= 255):
return True
else:
print("Invalid IP, closing program... \n")
exit(0) | 7d776107f54e3c27a2a918570cbb267b0e9f419e | 707,431 |
def overlapping_community(G, community):
"""Return True if community partitions G into overlapping sets.
"""
community_size = sum(len(c) for c in community)
# community size must be larger to be overlapping
if not len(G) < community_size:
return False
# check that the set of nodes in the communities is the same as G
if not set(G) == set.union(*community):
return False
return True | da9e3465c6351df0efd19863e579c49bbc6b9d67 | 707,432 |
from typing import Any
def linear_search(lst: list, x: Any) -> int:
"""Return the index of the first element of `lst` equal to `x`, or -1 if no
elements of `lst` are equal to `x`.
Design idea: Scan the list from start to finish.
Complexity: O(n) time, O(1) space.
For an improvement on linear search for sorted lists, see the binary search
function in the decrease_and_conquer module.
"""
for i, y in enumerate(lst):
if x == y:
return i
return -1 | 47e73d53ff68954aadc6d0e9e293643717a807d8 | 707,434 |
def checksum(number):
"""Calculate the checksum. A valid number should have a checksum of 1."""
check = 0
for n in number:
check = (2 * check + int(10 if n == 'X' else n)) % 11
return check | 8ada40ca46bc62bbe8f96d69528f2cd88021ad6a | 707,437 |
def instanceof(value, type_):
"""Check if `value` is an instance of `type_`.
:param value: an object
:param type_: a type
"""
return isinstance(value, type_) | 3de366c64cd2b4fe065f15de10b1e6ac9132468e | 707,438 |
import torch
def SPTU(input_a, input_b, n_channels: int):
"""Softplus Tanh Unit (SPTU)"""
in_act = input_a+input_b
t_act = torch.tanh(in_act[:, :n_channels, :])
s_act = torch.nn.functional.softplus(in_act[:, n_channels:, :])
acts = t_act * s_act
return acts | a03cc114cf960af750b13cd61db8f4d2e6c064ad | 707,439 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.