content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def ConvertContinueToBinary(signal, threshold = 0, maximize = True):
"""
It converts a continue signal (in pandas DataFrame format) into a binany signal according to a rule defined by a threshold and a type of filter.
:param signal:
input signal
:type signal: pd.DataFrame
:param t... | 0b9538f28ecc6d0967a30c55b2dc83987fc61902 | 600,219 |
from typing import Dict
def context() -> Dict[str, str]:
"""Cookiecutter context dictionary."""
return {"project_slug": "example"} | 872744a9cec88d2a1c4693a2296bca57ce9baa93 | 600,224 |
import torch
def select_top_predictions(predictions, confidence_threshold):
"""
Select only predictions which have a `score` > self.confidence_threshold,
and returns the predictions in descending order of score
Arguments:
predictions (BoxList): the result of the computation by the model.
... | cb843276bcc8487a267665caae20c8a6b8166d5c | 600,226 |
from typing import Dict
import logging
import csv
def read_index(pack_index_path: str) -> Dict[str, str]:
"""
Reads an index from the page name to the path of the stored pack.
Args:
pack_index_path: The path of this index file. The file should be a tab
separated file.
Returns:
... | 5b86ad60ea620c4eb10011c1bf611e891ae85462 | 600,227 |
def get_mdal_datetime_to_string(date_object):
"""Gets string from datetime object. In UTC Time.
:param date_object
:returns '%Y-%m-%d %H:%M:%S UTC' """
return date_object.strftime('%Y-%m-%d %H:%M:%S') + ' UTC' | c37a57ab603ace8f354f78cb7c234850862d5787 | 600,228 |
import re
def trim_spaces(string):
"""
Replace consecutive spaces with a single whitespace.
Args:
string (str): String
Returns:
str: Replaced string
"""
return re.sub(r'\s+', ' ', string).strip() | d026d0983b58934b6c406b077abce0beae973d4f | 600,229 |
from typing import List
from typing import Dict
import csv
def read_input_csv(path: str) -> List[Dict[str, str]]:
"""
Read the input CSV file and deserialize data.
:param str path: Path to input CSV file
:return: List of CSV rows
:rtype: List[Dict[str, str]]
"""
transactions = []
wit... | ba704387d3225322120694dcd8a7b56748226354 | 600,231 |
def roas(total_revenue, total_marketing_costs):
"""Return the Return on Advertising Spend or ROAS.
Args:
total_revenue (float): Total revenue generated.
total_marketing_costs (float): Total marketing costs
Returns:
Return on Advertising Spend or ROAS (float).
"""
return to... | 1e9bfcae1c2dcb8225fa742030fe8966efd253e3 | 600,232 |
def _time_multi_index_gr_seq(df, time_1, time_2):
"""
Extract frames with time index greater time_1 and smaller or equal time_2
"""
_s = (df.index.get_level_values('time') > time_1) & (df.index.get_level_values('time') <= time_2)
return _s | b7a158e9c672b763dc4d7b82365b9979bf6811d7 | 600,233 |
def load_source_code(source_filename=__file__):
"""
Open a script to parse.
:param source_filename: Full path to script to parse, if not provided,
this script will parse itself.
:return: Script content as a string
"""
return open(source_filename, 'r').read() | 8bb86855db489101f2d48d40cff3609f51ca50c8 | 600,234 |
def split_neo_dict(neo_dict: dict) -> list:
"""
Convert NEO dictionary into a list of NEOs
Args:
neo_dict (dict): NEO dictionary pulled from NEO feed
Returns:
[list]: List of NEOs
"""
return [i for v in neo_dict.items() for i in v] | 0e2948c2b4cc03abe292a7e67f6c8c4c691e0771 | 600,238 |
from typing import List
def ellipsize(elements: List) -> str:
"""Generate a short string representation of `elements`.
If the list has more than 5 elements, only the first two and last two are shown,
with "..." between.
"""
if len(elements) > 5:
return ", ".join(map(str, elements[:2] + ["... | 51f204af391ed38d2310fd20d6c9984576dcbe2c | 600,239 |
def _call_if_callable(f):
"""Call callables, or return value of non-callables."""
return f() if callable(f) else f | 463d6e5d22ac68649a340407d47afd1ddaf2b934 | 600,240 |
def leafLemmaMatches(src, tgt):
"""
Return true if both src and tgt are leaves, and the lemmas match
"""
if src.isLeaf() and tgt.isLeaf() and src.token().lemma == tgt.token().lemma:
return True
else:
return False | 81e4375d3f4f06b94a3c67ab278a111a7fd99e28 | 600,241 |
from typing import List
def find_multiples(dim1: int, dim2: int) -> List[int]:
"""
Helper to get different available patching sizes
by finding the common denominator.
"""
multiples = []
for i in range(1, min(dim1, dim2)):
if dim1 % i == dim2 % i == 0:
multiples.append(i)
... | 21b89cc8109924f2f17eca8d1d8d5bb8677d6578 | 600,242 |
from typing import List
def match_shape(tensor, *expected_shape):
"""Compare the given tensor's shape with what you expect it to be.
This function serves two goals: it can be used both to assert that the size
of a tensor (or part of it) is what it should be, and to query for the size
of the unknown d... | 2206343129ce9b1078bcab567f3a49a66b64ecde | 600,243 |
def reverse_transcribe(seq):
"""reverse transcribes a dna sequence (does not convert any non-atcg/ATCG characters)"""
watson_crick = {'A': 'T', 'T': 'A', 'G': 'C', 'C': 'G', 'a': 't', 't': 'a', 'g': 'c', 'c': 'g'}
return ''.join([watson_crick.setdefault(c, c) for c in seq[::-1]]) | bea09e9a19a300a1037ed16037ce0602cce34874 | 600,245 |
import json
def load_json_corpus(filepath='corpus.json'):
"""
Loads an existing corpus from a JSON file.
:param filepath: The location of the file to load.
:type filepath: str
:return: The list of all sentences from the dataset.
:rtype: list
"""
with open(filepath) as f:
retur... | 7df92531acdbc969e2598b29d85fde40266307e6 | 600,248 |
def colors(string, color):
"""To make things colorful
Arguments:
string {string} -- string to be colored.
color {integer} -- color
"""
return("\033[%sm%s\033[0m" % (color, string)) | f217f0612a92f5fce7873034e2112fe38b640550 | 600,251 |
def read_html_to_variable(file):
"""
Function to open savedfile and read lines into variable
:param file: string (path of file)
:return: string
"""
with open(file,'r') as f:
outvar = f.read()
return outvar | 6555e50d52b94790195d86bddb65a065f1118132 | 600,252 |
def add_ids_args(parser, required=True):
"""
Helper function. Adds arguments for ids to various subcommands.
:param parser: subcommand parser object
:return: parser (enhanced with new arguments!)
"""
ids = parser.add_mutually_exclusive_group(required=required)
ids.add_argument(
"--id... | d0d5804271da199f0cae8e7bf17d5d7e008db8e5 | 600,260 |
async def eval_issue_5(serialized_citation):
"""
Return 5 if 'doi' or ':' in DOI, else None
See: https://github.com/cverluise/SciCit/issues/5
:param serialized_citation: dict
:return: int or None
"""
if "DOI" in serialized_citation.keys():
doi = serialized_citation["DOI"].lower()
... | 8820b032a6e83ea7b65162c028ec9b6200ad1f52 | 600,261 |
def cuda_set_device(dev_id):
"""
Selects the CUDA device with the given ID.
"""
return 0 | 67cb8cd28b5479c9401106d29d85a08b5bb73a87 | 600,267 |
def get_parent_snap(f):
"""
Find the parent (last ancestor) of SubSnap f
"""
parent = f.ancestor
while parent != f:
f = parent
parent = f.ancestor
return parent | 0e7bd00b934009188adf935c8e4802eaff39ef51 | 600,268 |
def intervals_union(S):
"""Union of intervals
:param S: list of pairs (low, high) defining intervals [low, high)
:returns: ordered list of disjoint intervals with the same union as S
:complexity: O(n log n)
"""
E = [(low, -1) for (low, high) in S]
E += [(high, +1) for (low, high) in S]
... | 89d03eef9774ad469e1859f7513ebcffdf45f7be | 600,272 |
import warnings
def flatten(geoms):
"""Flatten a list of geometries into a single geometry object
Combine geometries by iteratively union-ing neighbors (according to index)
* example, given a list of geometries (A,B,C,D,E,F,G,H,I,J):
[ A B C D E F G H I J ]
[ AB CD EF... | c59db431a0711909668ded3e68018af11e014631 | 600,274 |
def fix_limit(limit):
"""
fix limit integer from user
Args:
limit: limit integer - default 10
Returns:
limit integer or 10
"""
if limit:
try:
if int(limit) > 10000:
return 10000
return int(limit)
except Exception:
... | d5b4f5f0656a7409256301240dac0d7759a930c2 | 600,277 |
import re
def score_simplicity(word):
"""Determine how simple the word is.
Simple is defined as the number of separate words.
In this case, higher is better, indicating a better score.
:param word (string): the name
:rtype score (int): the final simplicity score
>>> score_simplicity('the ca... | 1db1258e3a1cdddd122eb424377abad2c6280b87 | 600,278 |
def pathway_names(pathways):
""" Split the pathway names and descriptions
Args:
pathways (list): A list of pathway names and descriptions
(from a pathway abundance or coverage file)
Requires:
None
Returns:
(dic... | b1eb5e89c56827f32f18fab9edde7dc47334a326 | 600,286 |
import asyncio
async def run(cmd):
"""asynchronously run a subprocess, useful for running tncexporter in tests"""
proc = await asyncio.create_subprocess_shell(
cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE)
stdout, stderr = await proc.communicate()
if stdo... | 4aee14481d72445528694ac9bde69428f60dcf8e | 600,292 |
import ast
def check_locals(node):
"""
Checks if there is a call to `locals()`.
The check is not perfect has there might be local or global
variables with that name.
"""
class Visitor(ast.NodeVisitor):
def __init__(self):
self.found = False
... | 68a01f6ed294a9ea28db846ac4d2080ece2c7329 | 600,294 |
from typing import List
import abc
def _get_base_classes(cls: type) -> List[type]:
"""Get a list of all the base classes of a class.
This will exclude the base "object" class.
:param cls: The class to get the base classes for.
:return: A list of all the base classes.
"""
cls_bases = [base f... | eed58bdbc1a9857bdf502acbf7ee6374f1003e98 | 600,309 |
def _arg_names(f):
"""Return the argument names of a function."""
return f.__code__.co_varnames[:f.__code__.co_argcount] | d9df2b9ccf13b8c8fb7eeac27bcd496e59c013f1 | 600,310 |
import torch
def _q_bar_matrix(q):
"""Matrix representation of quaternion for multiplication purposes.
"""
return torch.cat((
torch.stack((q[0], -q[1], -q[2], -q[3]), 1),
torch.stack((q[1], q[0], q[3], -q[2]), 1),
torch.stack((q[2], -q[3], q[0], q[1]), 1),
torch.stack((... | f65e1c2b1604593eb1799a045318bf2a4dac8cec | 600,312 |
def prompt_continue(name):
"""Prompt for required user intervention."""
print(name + " already exists. " + "Data will be added to " + name + " if you continue. ")
prompt = "Do you want to continue? (y/n): "
inp = input(prompt).strip().lower()
if inp not in ['y', 'n']:
print(inp + " is not a... | ccf9d293ca077514ce0e4f0aacc5ffb89ef59815 | 600,317 |
import torch
def fill_tail_dims(
y: torch.Tensor,
y_like: torch.Tensor,
):
"""Fill in missing trailing dimensions for y according to y_like."""
return y[(...,) + (None,) * (y_like.dim() - y.dim())] | 5cadc0350b1a8aebec81189291b4c8ecf582ee58 | 600,320 |
from typing import Any
from typing import Callable
from typing import Dict
import functools
from typing import List
def singleton(cls: Any) -> Callable:
"""
Handy decorator for creating a singleton class
Description:
- Decorate your class with this decorator
- If you happen to create anoth... | 092fbb78aca58842070d68abcf729529aa9f8af8 | 600,322 |
from datetime import datetime
def is_aware_datetime(value: datetime) -> bool:
"""
:return: ``True`` if and only iff the given value is a timezone-aware
datetime instance.
"""
return isinstance(value, datetime) and value.tzinfo is not None | 913dd8348dcaba6025b9b704db791cf1fd66a55b | 600,324 |
def array_current_index(array):
"""
Return the current index (elementIndex()) of a MArrayDataHandle, or -1 if the
current index isn't valid, probably because the array is empty.
"""
try:
return array.elementIndex()
except RuntimeError as e:
# If the array is empty, elementIndex r... | 654173b806c921b7a0d4bce987fba71a8bc26bb5 | 600,326 |
def read_char(handle):
"""
Helper function to parse character from file handle
Args:
handle (file): File handle
Returns:
char
"""
return handle.read(1) | be765a3c461a3d02085915b24b40966958ea14b0 | 600,327 |
def transport_degree_factor(
temperature,
deadband_lower=15,
deadband_upper=20,
lower_degree_factor=0.5,
upper_degree_factor=1.6):
"""
Work out how much energy demand in vehicles increases due to heating and cooling.
There is a deadband where there is no increase.
Degree factors are ... | ea5d5128fa985ea566aefe8b0f7b5875878a9838 | 600,331 |
def get_site(nb, siteid):
""" For a given device, return site-specific information as a tuple.
@param nb: pynetbox api object
@param siteid: the ID of a site in netbox
@return: name and coordinates (latitude and longitude) of the site
"""
site = nb.dcim.sites.get(id=siteid)
ret... | 92d84b8084c2a0e1f45413048c86cc2588849175 | 600,332 |
def buffer_to_bytes(buf):
"""Cast a buffer object to bytes"""
if not isinstance(buf, bytes):
buf = bytes(buf)
return buf | 8f5837f4ae569d9a8c1942199fcf99d55b1e5582 | 600,337 |
def is_container(obj):
"""
Checks if the object is a container, that is, an iterable,
but not a string.
:param obj: Object to be tested.
:return: True if object is a container, False otherwise.
"""
if hasattr(obj, '__iter__') and not isinstance(obj, str):
return True
return Fals... | dda87ed2a9809040638991b56d4d239015fb6546 | 600,340 |
def bdev_opal_set_lock_state(client, bdev_name, user_id, password, lock_state):
"""set lock state for an opal bdev.
Args:
bdev_name: name of opal vbdev
user_id: ID of the user who will set lock state
password: password of the user
lock_state: lock state to set
"""
params... | aede67683040e11ec7076362f13f109e4e6120be | 600,341 |
import requests
import json
import time
def fetch_json(path, payload, call_count=1):
"""Send a request to the server and return the parsed JSON response."""
# it's polite to self-identify this "bot"
delphi_url = 'https://delphi.midas.cs.cmu.edu/index.html'
user_agent = 'Mozilla/5.0 (compatible; delphibot/1.0... | 5176d8bf6f107c67bf97bf46a05f4ce17278e21f | 600,342 |
def rule_110(a, b, c):
"""
Compute the value of a cell in the Rule 110 automata.
https://en.wikipedia.org/wiki/Rule_110
Let `n` be the current row and `i` be the current column. This function
computes the value of the cell (i, n).
Inputs:
a - The value of cell (i-1, n-1)
b - The value ... | 877e4e7dce044b45e86ab165bbce5eaea74ac5f0 | 600,346 |
def filter_queryset_metadata_uuid(queryset, uuid):
""" Filters a given REST framework queryset by a given uuid.
Only keeps the element which holds the uuid.
Args:
queryset: A queryset containing elements
uuid: A uuid
Returns:
queryset: The given queryset which only contains mat... | 7aa20a1677a9213f1115d6ca24df0755271f6f5b | 600,348 |
def trace_up(all_bags, bag):
"""
For the input bag "bag", trace the path upwards along all of its parents,
which are the bags that can hold it.
"""
parents = []
if len(bag.held_by) == 0:
return parents
for bag_type in bag.held_by:
parents.append(bag_type)
held_bag =... | 44950e8059c664ac97fc536622ddd9cd3224ce8c | 600,349 |
def get_difference_target_classification_proba(model, x, class_column,
method='predict_proba'):
"""Calculates the objective 1 (f1), where it attempts to maximize the
probability of the desired class. Valid only for classification problems
with methods returni... | 3603cac8c1dd3e9b79243e582178357ec1842155 | 600,350 |
def size_decode(src):
"""
Decodes a size (encoded with size_encode()) from the start of src.
Returns a tuple (size, len) where size is the size that was decoded,
and len is the number of bytes from src that were consumed.
"""
dstSize = 0
pos = 0
# Extract prefixed encoded size, if present.
val = 1
while True... | a3adf30c2c3a29a7b5e193a008195c0c9295eec2 | 600,352 |
def is_asexual(phylogeny):
"""Is this an asexual phylogeny?
A phylogeny is considered to be asexual if all taxa (nodes) have a single
direct ancestor (predecessor).
Args:
phylogeny (networkx.DiGraph): graph object that describes a phylogeny
Returns:
True if the phylogeny is asexua... | 40f8feffe3b681c7bb6e096d0b116b041e3f1434 | 600,356 |
def _std(var:list, mean:float, length:int):
"""
Compute the Standar Deviation of a point
Parameters:
------------
var: list
The variance between all points
mean: float
The mean of the point
lenght: int
The lenght of all routes
Return
-------
Return the standar deviation of a point
"""
summ... | 0c7c1ac57e32f434b9e2015e855e7fb74879bbbc | 600,357 |
def divisible_by(numbers: list, divisor: int) -> list:
"""This function returns all numbers which are divisible by the given divisor."""
if numbers is None:
return []
res = []
for item in numbers:
if item % divisor == 0:
res.append(item)
return res | f913e83ba3e6b053205a6de9b4069adf71fb4edd | 600,360 |
def squares_causing_max_conflicts(gv_init, gv_current, conflicts_grid_values):
"""Will receive a grid filled with values and a conflicts_grid_values and will return:
- a set of all squares having the maximum number of conflits
- the number of conflicts (int) for this maximum"""
maxconflicts = max(... | 0795d89ff991569010d1d48e83b1455aeeba85ff | 600,363 |
def distance(point1, point2):
"""L2 distance"""
return sum((point1[i]-point2[i])**2 for i in range(len(point1)))**0.5 | 2be6669689b3bde57542f8ac876228d064c9d694 | 600,375 |
def is_valid_name(f_name, cfg, log, **kwargs):
"""Function: is_valid_name
Description: Determine if the file name meets the search criteria. If the
file name has one of the items in the filter criteria, then it will be
processed. If the filter criteria is empty, then all files will be
... | 5990eb92d3a0a6c35af1645335224dbf6df8193f | 600,378 |
def detokenize(token_rules, words): # Deprecated?
"""
To align with treebanks, return a list of "chunks", where a chunk is a
sequence of tokens that are separated by whitespace in actual strings. Each
chunk should be a tuple of token indices, e.g.
>>> detokenize(["ca<SEP>n't", '<SEP>!'], ["I", "ca"... | de66eeb93e4f05e983c0f56023475d9ca4743e69 | 600,380 |
import base64
def get_b64_from_data(data):
""" Encode data to base64.
"""
b64_from_data = None
try:
b64_from_data = base64.b64encode(data)
except:
print("Could not read data to compute base64 string.")
return b64_from_data | e088ecd3130da8661e8cf79037c0bf56221e56ab | 600,381 |
def sig_dim(alphabet_size, depth):
"""Calculates the number of terms in a signature of depth :depth: over an alphabet of size :alphabet_size:."""
return int(alphabet_size * (1 - alphabet_size ** depth) / (1 - alphabet_size))
# == sum(alphabet_size ** i for i in range(1, depth + 1)) (geometric sum formula) | 3d76b9d3b87f6cffe518327f804cb903281b41b4 | 600,384 |
def area_def_to_dict(area_def):
"""
given an area_def, save it as a dictionary`
Parameters
----------
area_def: pyresample area_def object
Returns
-------
out_dict: dict containing
area_def dictionary
"""
keys = [
"area_id",
... | 64bc005bf9dda566acd84fd6c11406ae2781f862 | 600,389 |
import gzip
def compress_gzip(data: bytes) -> bytes:
"""compresses data via gzip
The current static settings may not be the best solution,
but they are the most commonly used values and should therefore be enough for the time being.
:param data: uncompressed data
:type data: bytes
:return: co... | d4f5eb67513536170627d1fdd71961b3b7c302ec | 600,394 |
import re
def remove_type_spaces(part):
"""
Trims whitespace from types that can have it. This will alter types, so the resulting strings shoudln't be used to deduce types. The results are intended to make it easier to parse out param names.
"""
ret = re.sub(r"func\(.*\)\s+", "func()_", part)
ret ... | 9cc1bfe97ab97432475ce37beec3cd0da8d9ba94 | 600,396 |
def add_docstring(value):
"""Decorator to add a docstring to a function."""
def _doc(func):
func.__doc__ = value
return func
return _doc | 7b2c882a37d1261d2b67698f21e8b3b2fd7a2dfa | 600,397 |
def format_hex(value, mask):
""" Format an integer as a hexadecimal string """
if mask is None:
return "0x{:x}".format(value)
return "0x{:x}/0x{:x}".format(value, mask) | 2948dbb754ef5856262a5befc00b52b40c72dcfc | 600,398 |
def _get_element_id(tag):
"""Extracts the id=* from the tag and returns that as a string
Args:
tag (str or bytes): Full valid html tag from < to >
Returns:
str or None: ID of the tag parameter, or None if one does not exist
"""
# decode tag parameter if its a bytes object
tag =... | 88f732aca1fe7f37c7de894cb54e573ad9d758b9 | 600,402 |
def spines(*, left=True, right=True, top=True, bottom=True):
"""Adjust the visibility of the axes' spines."""
return {
"axes.spines.left": left,
"axes.spines.right": right,
"axes.spines.top": top,
"axes.spines.bottom": bottom,
} | 2ab8e648804442aab7e4e8f5e08dcc954a0c8352 | 600,403 |
def listMinus(x, y, delete=False):
"""If delete = True, removes all things in y that are in x. e.g.
x = [1,2,3,4], y = [2,4] at the end x becomes [1,3], y remains the same.
If delete = False, returns what x would have been while preserving x."""
if delete == True:
to_be_diminished = x
else:
... | 6f584f60d64ddedc02516a83e4cc1a32f668a517 | 600,413 |
import pickle
def load_pickle(filename, channel=-1, verbose=0):
"""
Load Joerg's pickle files.
Parameters
----------
filepath: string
The full path and name of the file to load.
channel: int
The data channel. If negative all channels are selected.
verbose: int
if >... | 59c1b4f19149078cc43e6f0b171fb7e2c77013f4 | 600,419 |
def nothing(*args, **kwargs):
"""Constant function: False"""
return False | aba561fd347db9fed96fa360d3da7637fce68dfb | 600,424 |
def format_message(message: str) -> str:
"""Formats the Message to remove redundant Spaces and Newline chars"""
msg_l = message.split(" ")
new = []
for x in msg_l:
if "\n" in x:
x = x.replace("\n", "")
new.append(x) if not len(x) == 0 else None
elif len(x) != 0:
... | 98b0e7135ae01bdc6aaecdb2a40d474565e966bc | 600,429 |
import requests
def api_get_course(srcdb, crn, code):
"""
Given a CU Boulder course code and CRN, return the API response
for details on that course (including its sections).
"""
url = "https://classes.colorado.edu/api/?page=fose&route=details"
data = {
"group": "code:{}".format(code),... | e8260aefaa5e4f2dd4a919bbc3af6cdce675f8fb | 600,432 |
def ParseGTestListTests(raw_list):
"""Parses a raw test list as provided by --gtest_list_tests.
Args:
raw_list: The raw test listing with the following format:
IPCChannelTest.
SendMessageInChannelConnected
IPCSyncChannelTest.
Simple
DISABLED_SendWithTimeoutMixedOKAndTimeout
Return... | ec53e28fbf7b934fcfffa0d028cabb4c3bc120b3 | 600,439 |
def shingle(iterable, n):
"""
Shingle a list into tokens of length n
Eg. with n = 3
[1, 2, 3, 4, 5] => [[1,2,3], [2,3,4], [3,4,5]]
"""
num_shingles = max(1, len(iterable) - n + 1)
return [iterable[i:i + n] for i in range(num_shingles)] | 3aa5a5bce2e26a0a590fa408474b33e287b12909 | 600,443 |
def setOfAllCfgVal(pmgr, field, fcheck=None, fval=None):
"""
Returns a set of all configured values for field.
kwargs is a dict of field : value pairs that act as conditions for being
on this list. With no kwargs we return all of the values.
"""
vals = set()
pmgr.updateTables()
for cfg i... | 9ca03ac008b598bbf27f94aed4b31d1b331aea9c | 600,447 |
def has_active_network_in_vlan(vlan):
"""Check if there are any other active network in the vlan this is used
because some equipments remove all the L3 config when applying some
commands, so they can only be applyed at the first time or to remove
interface vlan configuration
:param vlan: vlan objec... | ab38e73ebbd402463d03b6f8d7ca3d918e970879 | 600,450 |
def _split_words(text):
"""
Splits a piece of text into words, separated by whitespace.
"""
return text.split() | 5d16efdac503684461fd8388027a7de0f7be27a4 | 600,451 |
def get_square(size=0):
"""
Returns a drawn square with '*' as the border and '-' on the inside of the square
:param size: The size of the square
:return: A ASCII square
"""
output = ''
for i in range(0, size):
# The first and the last row only contain '*'
if i == 0 or i ==... | a7cce7c275333cedeca960af233ebc7aae3016ab | 600,454 |
def read_name(ix):
"""Reads player name from CLI, returns string."""
return input( "What is your name (Player" + str(ix) + ")?\n\t") | 18a5f8b7b31e4dc364c63c7ca505a917cbfdbe15 | 600,455 |
from typing import Dict
from typing import Any
def parse_address_positionstack(place_info: Dict[str, Any]) -> Dict[str, Any]:
"""Parse Position Stack location info.
:param: place_info: address info.
:return: country and coordinates.
"""
if not place_info:
return {}
info = {
'... | 90281d87cf59124aadde4bf807326d69a3cbf148 | 600,456 |
def balanced(config, n):
"""
Slightly different version of Zeller's split. This version keeps the split
balanced by distributing the residuals of the integer division among all
chunks. This way, the size of the chunks in the resulting split is not
monotonous.
:param config: The configuration to... | 2d48ecb74ccb6b1bfe479dd02fe535e8c45de2e4 | 600,458 |
def energy_consumption(cpu_active_time, cpu_lpm_time, listen_time):
"""
Calculates the power consumption during a synchronization attempt.
Note that, in our experiments, we use Zolertia RE-Mote B devices (https://github.com/Zolertia/Resources/raw/master/RE-Mote/Hardware/Revision%20B/Datasheets/ZOL-RM0x-B%20... | b74a3b3333bd34b743035a92567af5ff6ad865c3 | 600,459 |
import time
def endless_poke(ts3conn, nickname, msg=None, num=100, delay=1):
"""
Pokes all clients where *nickname* matches *num* times with the message
*msg*. Sleeping *delay* seconds between the single pokes. If *num* is -1,
the client is poked forever.
"""
if msg is None:
msg = "Sto... | a66c12e3c658f81da3ba698b5a261628413ea172 | 600,461 |
def remove(text, exclude):
"""Remove ``exclude`` symbols from ``text``.
Example:
>>> remove("example text", string.whitespace)
'exampletext'
Args:
text (str): The text to modify
exclude (iterable): The symbols to exclude
Returns:
``text`` with ``exclude`` symbo... | a775980c02d77b211d6e6fbbc74e16417edfaade | 600,463 |
def make_multiprint(filelist):
"""Makes a function that prints its argument to all files in FILELIST."""
def multiprint(msg):
for f in filelist:
print(msg, file=f)
return multiprint | 250cf8387b6240c4b590f2b70b0ffcc0b4a80373 | 600,464 |
def _dup(x): # pylint: disable=invalid-name
"""Helper: copy the top element of a list or a tuple."""
if isinstance(x, list):
return [x[0]] + x
assert isinstance(x, tuple)
return tuple([x[0]] + list(x)) | c382c537f8d6d01a235ec4ff98aa902e446438f1 | 600,472 |
def datatype_to_bq(datatype):
"""
Simple attempt to do some basic datatypes.
Fallback to String for unknowns and then you can fix it later in bigquery.
"""
if "DATETIME" in datatype:
return "DATETIME"
if "DATE" in datatype:
return "DATE"
if "INT" in datatype:
return "... | 4a350f3c9416799f9d7f92e9d8412b411578e4bc | 600,477 |
from typing import Optional
from typing import Union
def type_union(*args: type) -> Optional[type]:
"""Finds the union of types, eliminating `None` where possible."""
union_t = None
for t in args:
if union_t is None:
union_t = t
elif t is not None:
union_t = Union[u... | 1de257308d037460a96d66df8f1daaeb19128fff | 600,478 |
def fib(n,dic= {0:0,1:1}):
"""
Fibonacci with Memoization
"""
if n in dic.keys():
return dic[n]
else:
dic[n] = fib(n-1) + fib(n-2)
return dic[n] | a730c94107b1c63c2e80d4830c7a90434065ef19 | 600,483 |
def getUserReponse(prompt):
""" Helper function to get a yes/no response from the user """
resp = input(prompt+'\n')
while resp.lower() not in ['y', 'n']:
print("Invalid option.")
resp = input(prompt+'\n')
return resp == 'y' | e077650975024106c91a5d35d966b3c8603c01e3 | 600,485 |
import time
def nanotime(s=None):
""" convert seconds to nanoseconds. If s is None, current time is
returned """
if s is not None:
return s * 1000000000
return time.time() * 1000000000 | 917699dbc0997d42efacfa01cdc83c9c15840646 | 600,486 |
def skip_blanks(lines):
"""Filter out blank lines."""
return (line for line in lines if line) | c707d03699ba6caa39a4b946ff2bc1e9e4ae109a | 600,487 |
from PIL import ImageDraw
def line(pos, image, data, scale=1, spacing=3, mode='dual'):
"""
Draw spectrum bars.
:param pos: (x, y) - position of spectrum on image
:param image: PIL.image - image to draw
:param data: 1D array - spectrum data
:param scale: number - scaling of bar lenght
:param spacing: int... | 61973a785fb25d37fb97c8be05ed6a43dfda7982 | 600,488 |
from typing import Any
import numbers
def _has_valid_value(key: str, value: Any) -> bool:
"""Checks if the field has a usable value.
A field should be ignored when the value has no actual data (e.g. numeric 0 is
meaningful data but None is not meaningful).
This method returns False if the given value is eit... | a0c4f1fc3776162ccc8ae9f927a4bfdaddc3f88a | 600,491 |
def meanflat(x):
"""Take the mean over all axes except the first batch dimension."""
return x.mean(axis=tuple(range(1, len(x.shape)))) | 8623dc141de7350629ae8ba762d80299a90cdb9a | 600,493 |
def str_cmp(s1, s2):
"""
Compute the Hamming distance between two strings of the same length.
"""
count = 0
for i in range(len(s1)):
if s1[i] != s2[i]:
count += 1
return count | 068be6f9f6f67787f77af765b7dc3686e4e87654 | 600,498 |
def get_base_name(path_name):
"""Extract the filename from the full path"""
path_parts = path_name.split("/")
return path_parts[-1] | 81530be11a48bd3d6107a9935bab1591d0fa56e9 | 600,500 |
async def get_current_doc_amount(TAGDB):
"""Get the current docs amount"""
return await TAGDB.count_documents({}) | 32632595083a6f0378178f668d8ddc51e966bc04 | 600,501 |
def bbox_for_points(points):
"""Finds bounding box for provided points.
:type points: list or tuple
:param points: sequince of coordinate points
:rtype: list
:return: bounding box
"""
xmin = xmax = points[0][0]
ymin = ymax = points[0][1]
for point in points:
xmin = min(xmin, point[0])
xmax =... | d49dbadc3294c5abaa8e0df11fed3f0d82c82842 | 600,502 |
import re
def _order_from_regexp(items, order_regexps):
"""Re-order list given regular expression listed by priorities
Example:
--------
>>> _order_from_regexp(["aA", "aZ", "bb", "bY", "cZ", "aY"], [".*Y", ".*Z"])
['bY', 'aY', 'aZ', 'cZ', 'aA', 'bb']
"""
ordered = list()
for order_reg... | 392f9460e22cce95fd7078966401a882610cc19a | 600,503 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.