content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import argparse
def init_parser():
"""Initialize the argument parser."""
parser = argparse.ArgumentParser(description='Play 21 Marble game.')
parser.add_argument('-a', '--ai', action="store_true", default=False,
help="if you want to play against an AI")
parser.add_argument('pla... | 2ff6eba53264b012bbf483e318e1f5e175a037d7 | 661,852 |
def evalPoly(fit_param, Y):
"""
Evaluate X, based on Y of the polynomial
"""
return fit_param[0]*Y**2 + fit_param[1]*Y + fit_param[2] | c5ef1e7fe148579e826571896f0c8227b18f9631 | 661,853 |
from typing import Any
def is_sequence(val: Any) -> bool:
""" test whether or not val is a squence - list or tuple
input: val
output: True or False
"""
### old python2 version - didn't work with python3 since strings startd to support __iter__
###return (hasattr(val, "__iter_... | e900ec7a2aef121d79724eaccc2707b5e455660f | 661,855 |
def _handle_not_found_error(exc, context, response):
"""Generic error for 'get_object_or_404()' function."""
response.data = {
"error": "NotFound",
"message": "Запрошенный объект не найден",
}
return response | 82f9dc91f9484e9ae97ef35d99b398eb81044864 | 661,856 |
def neuroblastoma():
"""Create neuroblastoma fixture."""
return {
"label_and_type": "ncit:c3270##merger",
"concept_id": "ncit:C3270",
"item_type": "merger",
"xrefs": ["mondo:0005072", "oncotree:NBL", "DOID:769"],
"label": "Neuroblastoma",
"aliases": [
... | b4adb775c3cc4dfeda926a7b7b04016d245b8f74 | 661,857 |
import platform
def is_arm_mac():
"""Determines whether the system is an ARM-based Mac (Apple Silicon).
Returns:
True/False
"""
plat = platform.platform()
return platform.system() == "Darwin" and any(
proc in plat for proc in {"aarch64", "arm64"}
) | 17a9c180f73285bd2849afa259897bcbec6c6abd | 661,859 |
def signExtend(x, n=8):
"""
Returns signed integer that is the sign extention of n bit unsigned integer x
in twos complement form where x has n significant bits
This is useful when unpacking bit fields where the bit fields use two's complement
to represent signed numbers. Assumes the the upper bits... | f77ba0024568ebd6280fcfa5f48d3057109d8823 | 661,860 |
def ans_match_wh(wh_word, new_ans):
"""Returns a function that yields new_ans if the question starts with |wh_word|."""
def func(a, tokens, q, **kwargs):
if q.lower().startswith(wh_word + ' '):
return new_ans
return None
return func | e1ea32bd973ea37ccec4b28d8f491d7e8a2b6314 | 661,862 |
import inspect
def get_caller_name(steps=2):
"""
When called inside a function, it returns the name
of the caller of that function.
Keyword arguments:
steps - the number of steps up the stack the calling function is
"""
return inspect.stack()[steps][3] | 4c513f561872f80a878906bc384b1826142d9dfd | 661,863 |
def thermalConductivity(T, tCP):
"""
thermalConductivity(T, tCP)
thermalConductivity (W/m/K) = A + B*T + C*T^2
Parameters
T, temperature in Kelvin
tCP, A=tCP[0], B=tCP[1], C=tCP[2]
A, B, and C are regression coefficients
Returns
thermal conductivity in W/m/K at T
... | 348e52dc16a864e72dc56a15635d1e61c51eee37 | 661,864 |
from typing import Any
def ExtractPrefixedKeysFromNestedMap(node: Any, prefix: str = '') -> Any:
"""Extracts a NestedMap with the nested prefix keys from its NestedMap node."""
if isinstance(node, dict): # NestedMap inherits from dict.
result = {}
for key, value in node.items():
if prefix:
... | cf5c265e781d58ad589e9914ef89fe86932a09ba | 661,865 |
import fnmatch
def _is_owner_ignored(owner, name, ignored_classes, ignored_modules):
"""Check if the given owner should be ignored
This will verify if the owner's module is in *ignored_modules*
or the owner's module fully qualified name is in *ignored_modules*
or if the *ignored_modules* contains a p... | d967e2c98b37809e9581198d3f4d03d947f4d914 | 661,866 |
def map_centreline_features(data):
"""
Maps the centreline feature codes to their more like features.
"""
data_m = data.copy()
data_m['FEATURE_CODE_DESC'] = data_m['FEATURE_CODE_DESC'].replace({'Laneway':'Local',
'Minor Arterial'... | 4ff613aab510eb91628e203ff48a170a19f630a1 | 661,867 |
def inspect_post(get_response):
"""Sets the user object from a JWT header"""
def middleware(request):
if request.method == 'POST':
print(f"""*** *** ***
POST METHODS DETECTED:
{request.POST}
""")
response = get_response(request)
return re... | 9b1b569ee71bcc477961f8f59070386772305f81 | 661,868 |
def array_rearranger(x,y):
"""Rearrange x according to y"""
return [x[i] for i in y] | 715db868ef68d6bc5a47a60135b0705bc17d6b73 | 661,869 |
def chance(dice):
"""Score the given role in the 'Chance' category """
return sum(dice) | 9a895ff6759e3afd330b56db87e57575c34b630e | 661,870 |
def get_average_velocity(model):
"""
Gets the total average velocity over all the agents
:param model: The model (environment) where the agents exist
:return: The total average velocity over all the agents
"""
df = model.datacollector.get_agent_vars_dataframe()
df.reset_index(inplace=True)... | 1db399b1a431de715891c22d00f576c802d347d0 | 661,871 |
def inversion_defaults():
"""
Get defaults for EM1D inversions
"""
defaults = {
"units": {"EM1D": "S/m"},
"property": {
"EM1D": "conductivity",
},
"reference_value": {"EM1D": 1e-3},
"starting_value": {
"EM1D": 1e-3,
},
}
re... | 33f8ac9a27f69e82a5b65270e4cc61849625d4bb | 661,872 |
def xor(x, y):
"""Return truth value of ``x`` XOR ``y``."""
return bool(x) != bool(y) | 1eb05009886c677c4d514f2b80a0881766b54cbc | 661,873 |
def fetch_production_configuration(service):
"""Safely fetches production configuration from 3scale"""
return service.proxy.list().configs.list(env="production") | 5627a73ca3b13815221fc91f9c3a1adbbbc2b3a5 | 661,874 |
import base64
def binary_to_base64(path: str) -> str:
"""
Transforms a binary file to base64
:param path: file's path
:return: base code
"""
with open(path, 'rb') as binary_file:
binary_file_data = binary_file.read()
base64_encoded_data = base64.b64encode(binary_file_data)
... | 6ecaf93ca1f124566bdc672205797f89a832b6c4 | 661,875 |
def chan_list_to_mask(chan_list):
# type: (list[int]) -> int
"""
This function returns an integer representing a channel mask to be used
with the MCC daqhats library with all bit positions defined in the
provided list of channels to a logic 1 and all other bit positions set
to a logic 0.
Ar... | c64b10237a5407b6ad0e285dfccb7c73553ddc55 | 661,876 |
def greedy_cow_transport(cows,limit=10):
"""
Uses a greedy heuristic to determine an allocation of cows that attempts to
minimize the number of spaceship trips needed to transport all the cows. The
returned allocation of cows may or may not be optimal.
The greedy heuristic should follow the followin... | 0cc344ded49f80c3887504ca25d1f7afb42f6606 | 661,877 |
def learner_name(learner):
"""Return the value of `learner.name` if it exists, or the learner's type
name otherwise"""
return getattr(learner, "name", type(learner).__name__) | 1da28e9c918df8e3bdf994df3cf2b7bbd6146d76 | 661,879 |
def _version_info(v: str) -> tuple:
"""Un-format ``__version__``."""
return (*(int(x) for x in v[:5].split('.')), v[5:]) | fcd8941c8755efcaff1b6f70f6a50eb26ab52900 | 661,880 |
import time
import os
def exit_code(pid, timeout=5):
"""
Wait up to `timeout` seconds for `pid` to exit and return its exit code.
Returns -1 if the `pid` does not exit.
"""
start = time.time()
while True:
_, status = os.waitpid(pid, os.WNOHANG)
if os.WIFEXITED(status):
... | c05019b84d8bd574102c6a4c34ff947561662d66 | 661,881 |
def subset(pattern1: str, pattern2: str) -> bool:
"""
>>> subset('bc', 'cba')
True
>>> subset('cba', 'cad')
False
"""
return set(pattern1).issubset(set(pattern2)) | eeae138d43772e2d22191cb33fada63f044b95c1 | 661,882 |
import os
from pathlib import Path
def _patch_subprocess_environment(config):
"""Patch the environment of the subprocess.
The problem is that task files are rendered and, then, stored in the hidden build
directory. This would prohibit imports if we did not add the project root to the
`PYTHONPATH`.
... | 6a28ee9d0002698bce61ce966ec40ab769c6c0cc | 661,883 |
import subprocess
def gitGetLastCommitId(directory):
"""
Returns the SHA-1 id of the last commit.
"""
return subprocess.check_output(["git", "log", "-1", "--pretty=%H"]).strip() | 1269b2c17c5231e9f098f9964b627ad90a093c06 | 661,884 |
def is_skippable(string: str):
"""A string is skippable if it's empty or begins with a '#'"""
return not string or string[0] == "#" | 2fd9695c8118922ccd3d5b4d739e227b12e94b42 | 661,885 |
def change_color(ellipse, color, find="#FF7F7F"):
""" """
ellipse = ellipse.replace(find, color)
return ellipse | 3d4aee5d716c03926c529597dd9f35b656ad6c06 | 661,886 |
import re
def re_sub(string, args):
"""
Provide a full regular expression replace on strings in templates
Usage:
{{ my_variable|re_sub:"/(foo|bar)/baaz/" }}
"""
old = args.split(args[0])[1]
new = args.split(args[0])[2]
return re.sub(old, new, string) | d5fe239a74c5436e24bbd5972bace157fbb8a70f | 661,887 |
def get_24_bit_bg_color(r, g, b):
""""Returns the 24 bit color value for the provided RGB values. Note: not all terminals support this"""
return '48;2;%d;%d;%d' % (r, g, b) | a30a95acec239b878739710d895632ca50fb75ec | 661,888 |
def merge(left, right, lt):
"""Assumes left and right are sorted lists.
lt defines an ordering on the elements of the lists.
Returns a new sorted(by lt) list containing the same elements
as (left + right) would contain."""
result = []
i,j = 0, 0
while i < len(left) and j < len(right):
... | 00a212db74cb2abf62b30ff1c3a67e426718e126 | 661,889 |
def compPubKey(keyObj):
"""
get public key from python-bitcoin key object
:param keyObj: python-bitcoin key object
:return: public bytes
"""
keyObj._cec_key.set_compressed(True)
pubbits = keyObj._cec_key.get_pubkey()
return pubbits | 12eb5b1b59f76f80621067275bf93c73fccc4472 | 661,890 |
def make_backreference(namespace, elemid):
"""Create a backreference string.
namespace -- The OSM namespace for the element.
elemid -- Element ID in the namespace.
"""
return namespace[0].upper() + elemid | e8ac711b49a0b489e373ac691ddbaeef21d1787e | 661,891 |
def _get_default_slot_value(spellbook, level):
"""
Get the default value of a slot maximum capacity:
- the existing maximum capacity if the slot already exists
- 0 in other cases
"""
try:
return spellbook.slot_level(level).max_capacity
except AttributeError:
return 0 | 42175f6ce1bd2d36a419ee7c7516b495110ba7ae | 661,892 |
def pegar_link(navegador, link):
"""
navegador - instancia do navegador
link - link ou parte do link que deseja buscar
"""
main = navegador.find_element_by_id('main')
ancora = main.find_elements_by_tag_name('a')
for a in ancora:
if link in a.get_attribute('href'):
return... | 428a2b657966c8c3890e9765732cbbd228a104ad | 661,893 |
import os
def zipdir(path, ziph):
""" Function for putting everything under an existing folder into
a zip folder.
This function puts all the files in an existing folder into a zipped
folder and then removes it from the existing folder.
Args:
path (str): path to folder desired to be zippe... | cb6e59c501afb3c209d76590b4ffe616ae579f50 | 661,894 |
def new_patch_description(pattern: str) -> str:
"""
Wrap the pattern to conform to the new commit queue patch description format.
Add the commit queue prefix and suffix to the pattern. The format looks like:
Commit Queue Merge: '<commit message>' into '<owner>/<repo>:<branch>'
:param pattern: The... | 1589e7be04252f16aeff40e08757b49b555fecc3 | 661,895 |
def same_neighbourhood_size(atom_index_1, molecule_1, atom_index_2, molecule_2):
""" Checks whether the same atoms in two different molecules (e.g., reactant and product molecules) have the same
neighbourhood size. """
if len(molecule_1.GetAtomWithIdx(atom_index_1).GetNeighbors()) != \
len(... | c767c6930375cf916fbf279a903cfac48233d441 | 661,896 |
def _FilterFile(affected_file):
"""Return true if the file could contain code requiring a presubmit check."""
return affected_file.LocalPath().endswith(
('.h', '.cc', '.cpp', '.cxx', '.mm')) | afe7971484bb80ca9ce5fd276aa1cab7138b915f | 661,897 |
def enter_manually_paper(user, **kwargs):
"""helper to determine if we're in `enter manually - paper`
Looks for 'entry_method' in kwargs - returns true if it has value
'paper', false otherwise.
"""
return kwargs.get('entry_method') == 'paper' | 1b17f2fede92b0f6517024e7d271bb397ded31f4 | 661,898 |
import decimal
def prettyprint(x, baseunit):
"""
Just a function to round the printed units to nice amounts
:param x: Input value
:param baseunit: Units used
:return: rounded value with correct unit prefix
"""
prefix = 'yzafpnµm kMGTPEZY'
shift = decimal.Decimal('1E24')
d = (decim... | a3b8b1bcd59ae654c8c319117569c53f74a7b70d | 661,900 |
def get_prep_pobj_text(preps):
"""
Parameters
----------
preps : a list of spacy Tokens
Returns
-------
info : str
The text from preps with its immediate children - objects (pobj)
Raises
------
IndexError
if any of given preps doesn't have any children
"""
... | 17c92ed818f4c1a6b4bc284ed0684c36a80ba5c2 | 661,901 |
import requests
def api_retrieve_category_history(category_id):
"""
Allows the client to call "retrieve --all" method on the server side to
retrieve the historical states of category from the ledger.
Args:
category_id (str): The uuid of the category
Returns:
type: str
... | 6294e220edac1781764f547366ab36c8fef75f63 | 661,902 |
import os
def get_file_list(path, filter_fn=None):
"""Return a list of files in a directory.
If you can specify a predicate (a callable), only file names matching it
will be returned.
"""
return filter(filter_fn, os.listdir(path)) | 6530134c6a7fd65b45dc19dbff959200d031370b | 661,903 |
def is_in_roi(x, y, roi_x, roi_y, roi_width, roi_height):
"""
Returns true if in region of interest and false if not
"""
return ((x >= roi_x and x <= roi_x + roi_width) and (y >= roi_y and y <= roi_y + roi_height)) | 4aa89a2bed6ed79c0e6447d8f3c4a5d97c7e3a4d | 661,904 |
import optparse
def mock_options(filename,rescale_out,folder):
"""Make the options object with nice values for testing"""
return optparse.Values({
"filename":filename,
"rescale_out":rescale_out,
"verbose":True,
"folder":folder,
"quiet":True
}) | ffb1f2c344c0a58b961bc760dde419fd483c473c | 661,905 |
def get_percent_from_BED(bed, percentage, twoside=False):
"""Get the lower and upper bondaries of scores given a percentage
Parameters:
1. bed: a bed object
2. percentage: integer from 0 to 100
3. twosided: If True, get the middle part of scores within the percentage; otherwise, started with th... | 1adff8a191bf4ce387443cbf86e38ceb01d20f37 | 661,906 |
from typing import Union
def create_choice(value: Union[str, int], name: str):
"""
Creates choices used for creating command option.
:param value: Value of the choice.
:param name: Name of the choice.
:return: dict
"""
return {
"value": value,
"name": name
} | 7fba604f4bf5a5bbbf15a602c767f4973befc3c3 | 661,907 |
def UD(value):
"""
Tags the given value with User Data tags.
"""
return "<ud>{0}</ud>".format(value) | 472fc5b1390a292034c66bb6731cdbfb12b78041 | 661,908 |
import numpy
def calc_gl_velocity_block(astrometry, trajectory):
"""
Finds the best linear transformation that
aligns the theoretical trajectory to the proper radial velocity data
:param astrometry: Observational data (proper motion and radial velocity)
:param trajectory: Complete theoretical tr... | c407b7b51620945634d1d90c4243be03be4c0b77 | 661,909 |
def pickle_protocol(request):
"""
Fixture to run all the tests for protocols 0 and 1, and -1 (most advanced).
(Originally from astropy.table.tests.test_pickle)
"""
return request.param | 2ede5f0afccda3004b2452940156880712775907 | 661,910 |
def floatArguments(func):
""" A decorator that converts all function arguments to float. Keyword arguments are left untouched.
@param func: a function to be decorated
@return :[funtion object] the decorated function
"""
def inner_func(*args, **kwargs):
args = map(float, args)
... | ceddbbbfa1416babb0041cab4f92a3266663ff51 | 661,911 |
import re
def trim(string):
"""Long File Name -> Long File Name"""
return re.sub(r"\s+", " ", string).strip() | 5ec5f2f9359a8ffea1274edc61ebe9069efdad76 | 661,912 |
def get_tokens(line):
"""tokenize a line"""
return line.split() | 8045f0cfcaa58ef1c94fa08313990028c47db129 | 661,913 |
def next_tag(el):
"""
Return next tag, skipping <br>s.
"""
el = el.getnext()
while el.tag == 'br':
el = el.getnext()
return el | c58f65b109faad8595c0e920c117adebc0627df5 | 661,914 |
from typing import Optional
import os
import sys
import subprocess
import re
def _get_splice() -> Optional[str]:
""" returns the content if found """
for f in ["th/Main.hs", "th/data.json"]:
if not os.path.isfile(f):
print(f"{f} not found", file=sys.stderr)
return None
tou... | 4503e2d8177323ae930358d51a1ffb3538705de6 | 661,915 |
import random
def is_prime_fermat(number: int, k=20) -> bool:
"""
Testa se um número é primo utilizando o teste de primalidade de Fermat
number - numero a ser verificado
"""
# Implementation uses the Fermat Primality Test
if number == 2 or number == 3:
return True
if number % 2 ==... | 9c63d192e7e098050afaa1a14a231a6977b99648 | 661,916 |
def isCacheInitialized(addr):
"""
Cache address is initialized if the first bit is set
"""
return (int.from_bytes(addr, byteorder='little') & 0x80000000) != 0 | 57266dfc4ef6a2319df290c9ecdd198dc528637e | 661,917 |
def getIndex(model, field):
"""
用于数据创建时主键ID的获取及起始值设定
:param model: model类
:param field: 按照某个字段排序
:return: 返回计算后的index
"""
dataList = list(model.objects.values().order_by(field))
if len(dataList) <= 0:
index = 1000
else:
index = int(dataList[-1][field]) + 1
return ... | 72e05911e0dcbcd0d7465f819004324a56f25833 | 661,918 |
def infer_legend(unique_class_list, classes):
"""Infer text for legend entries."""
n_class = len(unique_class_list)
legend_entries = []
for i_class in range(n_class):
class_label = classes[unique_class_list[i_class]]
legend_entries.append(class_label)
return legend_entries | d739e5af49c87a8c1d682df4d95180341b4b160c | 661,919 |
def location_to_string(locationID):
"""
helper to calculate port and bus number from locationID
"""
loc = ['{}-'.format(locationID >> 24)]
while locationID & 0xf00000:
if len(loc) > 1:
loc.append('.')
loc.append('{}'.format((locationID >> 20) & 0xf))
locationID <<... | d921370eacc83da3a136c6f6c50e3b21f22301ae | 661,920 |
def func_reporter_bare(func,*args,**kwargs):
"""
This bare reporter function can be transformed into a decorator if you
decorate it with decorator.decorator so that the func signature is
preserved.
"""
# suppressing printing for now. this decorator is for demo only
if 0: print('status called "%s" with: args=%s,... | 00105d2e74a8f97dc7e1ad1d0e5de4495fb704f8 | 661,921 |
import torch
def aggregate(x, dim, aggr='add', mask=None, keepdim=False):
"""
Args:
x: (..., A, ..., F), Features to be aggregated.
mask: (..., A, ...)
Returns:
(..., , ..., F), if keepdim == False
(..., 1, ..., F), if keepdim == True
"""
assert aggr in ('add', ... | be68cfa119991a064b30c220fcbe1b672ed2f789 | 661,922 |
def get_artist_id(name, cursor, db):
"""Is a helper function for execute_artist_queries()
Gets artist id by searching for the artist name"""
cursor.execute("SELECT artist_id from artist WHERE artist_name = '{}'".format(name))
db.commit()
id = cursor.fetchone()
if id is not None:
return ... | b5bb30d4c2f316293c5409771408cbbd31d46996 | 661,923 |
def reverse2(snippet):
"""Reverse second sequence.
Change a + b to b - a and a - b or b - a to a + b.
"""
text = snippet
if '0123456789/' in text:
text = text.replace('0123456789/', '9876543210/')
else:
text = text.replace('9876543210/', '0123456789/')
return text | 11a68327841ad8a7c5de084dc5743be670785eb8 | 661,925 |
def update_stream_values_for_type(store_data, stream_event_data, uid_to_streams_for_type):
"""
Update the store with values of streams for a single type
Args:
store_data: Current store dictionary
stream_event_data: Potential stream data for current plotly event and
traces in fi... | 280052483ab08a8dfda1a407c6620bcd1e3bbffe | 661,927 |
def minkowski_params(n_samples):
"""Generate minkowski benchmarking parameters.
Parameters
----------
n_samples : int
Number of samples to be used.
Returns
-------
_ : list.
List of params.
"""
manifold = "Minkowski"
manifold_args = [(3,), (5,)]
module = "ge... | 9202e26b22a8f29ba460dfe4eeec5ec2f717dd72 | 661,928 |
import re
def get_chr(bam_alignment, canonical=False):
"""Helper function to return canonical chromosomes from SAM/BAM header
Arguments:
bam_alignment (pysam.AlignmentFile): SAM/BAM pysam object
canonical (boolean): Return only canonical chromosomes
Returns:
regions (list[str]): R... | f0c016d5f4f946b5553c3125a3e9fc8f0c7bf07b | 661,929 |
import six
def row_to_dict(row):
"""Convert a `pymssql` row object into a normal dictionary (removing integer keys).
>>> returned = row_to_dict({1: 'foo', 'one': 'foo', 2: 'bar', 'two': 'bar'})
>>> returned == {'one': 'foo', 'two': 'bar'}
True
"""
retval = dict()
for key, value in six.iteritems(row):
... | 5ef570e4b85a10bd4f4f9cfd2a78eba204360c03 | 661,930 |
def getPeopleData4():
"""
獲取人力 四阶段
---
tags:
- 人
responses:
500:
description: Error !
200:
description: Success!
"""
return "people data4" | 46d8689d1f7ef17fb2a5ea18fffdbe44d2b9b402 | 661,931 |
def get_matches_for_completion(text, candidates):
"""Create matches for readline completion for text.
candidates is a sequence of candidates to match. The returned list ends with
a None.
"""
return [w + ' ' for w in candidates if w.startswith(text)] + [None] | 9d120a889930d5ba305541cb3969bf3fb0c584d3 | 661,933 |
def cve_harvest(text):
"""
looks for anything with 'CVE' inside a text and returns a list of it
"""
array = []
#look inside split by whitespace
for word in text.split():
if 'CVE' in word:
array.append(word)
return array | b33e81d4be3ffd78f3962e7e78d796e79fa170c6 | 661,934 |
from datetime import datetime
def get_date_str():
"""
@return: A string representing the current date/time that can be used as a directory name.
"""
return str(datetime.now()).replace(' ', '_').replace(':', '.')[:-10] | 1dd4d5a8ad7beec9ab4ea6ea827b1c429c254ea5 | 661,935 |
def _is_tuple_of_dyads(states):
"""Check if the object is a tuple or list of dyads
"""
def _is_a_dyad(dd):
return len(dd) == 2
ret = False
for st in states:
if _is_a_dyad(st):
ret = True
else:
ret = False
break
r... | 100ff10fcc46134bfd25959eafc599da54a41ecf | 661,936 |
def calculate_fitness(reference, population):
"""
Calculate how many binary digits in each solution are the same as our
reference solution.
"""
# Create an array of True/False compared to reference
identical_to_reference = population == reference
# Sum number of genes that are identical to t... | cde3ba975d13e59e495240ce2dbb12b71b5706f2 | 661,937 |
def compliance_level(level):
"""
Property: PatchBaseline.ApprovedPatchesComplianceLevel
Property: Rule.ComplianceLevel
"""
valid_levels = ["CRITICAL", "HIGH", "MEDIUM", "LOW", "INFORMATIONAL", "UNSPECIFIED"]
if level not in valid_levels:
raise ValueError(
'ApprovedPatchesCom... | 01fb8f8475cba585620a896e5e09a0b239ed7a74 | 661,938 |
from typing import Callable
def binary_search(f: Callable, low: int, high: int) -> int:
""" Binary search """
hi, lo = f(high), f(low)
mid = (high + low) // 2
if hi and lo:
return high
if not hi and lo:
return binary_search(f, low, mid)
if hi and not lo:
return bina... | 8f77f2d3866ac77fef591156abfcbee3b3cc64f6 | 661,939 |
def restore_buffered_image(expanded_image, original_shape):
"""
Crop the buffer
:param expanded_image: Expanded image that is desired to be in the original shape.
:param original_shape: Original shape of the image.
:return: The input image cropped to the original shape. THe object is placed in the ... | be2a4eb260f137b6caa8bf1a69650d54d80c7bdb | 661,940 |
def delkey(value, key):
"""
:param value: dictionary
:param key: string - name of element to delete
"""
value.pop(key)
return "" | 18ce1c3b1798866caceccc174aea132403217a75 | 661,941 |
def is_valid_classification(classification):
""" Check if the classification is a MISRA defined classification """
allowed_classifications = ['Rule']
return classification in allowed_classifications | fb99b768bbf53efa8a9bc578da0284fb598d7c74 | 661,942 |
def coin_amount_for_usd(coin: str, usd: float, tickers: dict) -> float:
"""
Get amount of {coin} for {usd}
:param coin: coin symbol
:param usd: amount in USD
:param tickers: raw tickers fetched from binance
:return: amount of coin for usd value as float
"""
price_in_btc = float(tickers[f... | a18b930393fd6a7997e6f47bbf8c459d60528109 | 661,943 |
import click
def validate_user(context, param, value):
"""
Validates the existence of user by username.
"""
users = context.obj.api.users()
user = next((u for u in users if u["username"] == value), None)
if not user:
raise click.BadParameter("User \"%s\" was not found" % value)
re... | ab30ff53a83b8d6d9a5c5ab8b75e9121f58f5ed5 | 661,944 |
from functools import reduce
def valid(tuple_list):
"""Returns True if checksum is correct. Returns False otherwise."""
f = lambda x,y: x+y
byte_sum = reduce(f, reduce(f, tuple_list))
return ((byte_sum & 0xFF) == 0) | 5271bd1a6025093abe9e6a31e9c14277b79392a4 | 661,945 |
def read_input(fileName, vtype, *getlines):
"""
reads a shadow text input file (like ``start.NN``) which consists of lines
``field = value``.
Parameters:
*fileName*: str
*vtype*: {int|str|float}
Type of the returned value.
*getlines*: list of strings
Returns:
... | e3162fe835c1f9e36aa80f7fcec14b141a0f304a | 661,947 |
def top_screen_edge(desktop, rect):
""" Get the y-coordinate of the effective top screen edge.
Parameters
----------
desktop : QDesktopWidget
The desktop widget for the application.
rect : QRect
The rect of interest.
Returns
-------
result : int
the y-coordinat... | bbb97ac3bb75771376bb9645b7500dd69c0c80d7 | 661,949 |
import random
def quick_sort(array, start, end):
"""
Quick Sort
Complexity: O(N^2)
Most of the the times when using random pivot
the complexity is O(NlogN). That is why we use
the term "worst case complexity" O(N^2) and
"expected worst case complexity" O(NlogN). Amortized
and expected... | fea6cfe30bddc30e91588ff1b8af1552d6e9cb38 | 661,950 |
from typing import OrderedDict
def dicts_from_table(table, keys=None):
"""Returns a list of dict() objects, one for each row in a list of lists (table)"""
lod = []
for row in table:
if not keys:
keys = row
if not all((k not in (None, '') or bool(k.strip())) for k in keys):
... | 9b847b4674cbfe6f2c1943d30fbaf27ccdcc9459 | 661,951 |
def parse_odbc(url):
"""
Parse Redshift ODBC URL
-----------------------
:param url: Fully Qualified ODBC URL
:type url: str
:return parsed: ODBC fields parsed into respective fields.
:rtype parsed: dict
.. example::
Driver={Amazon Redshift (x64)};
Server=server_name... | cafabc765e1f0846d4f1f9ceca44d0d18bd95182 | 661,952 |
import yaml
def pdu():
""" read and yield pdu configuration """
with open('../ansible/group_vars/pdu/pdu.yml') as stream:
pdu = yaml.safe_load(stream)
return pdu | 487c4b79fa0f6f6c675fabf959caa8f944756cfe | 661,953 |
from typing import Union
from typing import Dict
from typing import List
import json
def read_json(filename: str) -> Union[Dict, List]:
"""Read a JSON object or list from the given output file. By convention,
the Java wrapper for Metanome algorithms stores all algorithm as JSON
seriaizations.
Paramet... | 0bddb80e047aca5b4bbbe955ac4b3b46f36beac3 | 661,954 |
import typing
import subprocess
def recover_container(container_id: str) -> typing.Optional[str]:
"""Detect/kill a dangling container from an earlier devcluster."""
cmd = [
"docker",
"ps",
"-a",
"--filter",
f"id={container_id}",
"--format",
"{{.State}},{... | 9a6fd7d2fae489feb8ed937db73a88a92ca1341e | 661,955 |
def quantize_vector(vector, left_bound, right_bound):
"""Modulo clipping of the provided vector."""
if left_bound > right_bound:
raise ValueError('Left bound is higher than the right bound.')
distance = (right_bound - left_bound)
scale = (vector - left_bound) // distance
vector -= distance ... | 9c7dd7932e915696da0e1aa7a165e7e467daa0d2 | 661,956 |
def _ImportPythonModule(module_name):
"""Imports a Python module.
Args:
module_name (str): name of the module.
Returns:
module: Python module or None if the module cannot be imported.
"""
try:
module_object = list(map(__import__, [module_name]))[0]
except ImportError:
return None
# If t... | 0288486bef88f028138f577e7561b2776b24d46f | 661,957 |
import json
def _construct_image_metadata(manifest):
"""Perform introspection and analysis of docker manifest."""
if manifest is None:
raise ValueError('Invalid manifest')
req_keys = ('schemaVersion', 'fsLayers', 'history', 'signatures')
if any([x for x in req_keys if x not in manifest]):
... | 902a1bf39b6264d1dfb10945f2cdd94b61c12d3c | 661,958 |
import argparse
from datetime import datetime
def parse_args():
"""
Configure default hyperparams and cli interface
"""
parser = argparse.ArgumentParser("Training script for Traffic Monitoring")
parser.add_argument('--batch_size', default=1, type=int,
help='Model batch siz... | 820ba50f1cc69793444f55b89b35d73be3165351 | 661,959 |
def construct_fail_jumps(pattern: str):
"""Get lengths of longest proper prefixes that are suffixes at every position."""
longest_substr = [0]
for i in range(1, len(pattern)):
len_substr = longest_substr[-1]
while len_substr > 0 and pattern[len_substr] != pattern[i]:
len_subs... | 7dbde5aba16566c57437708cd1ab7f363e608ab9 | 661,960 |
def asciilower(s):
"""convert a string to lowercase if ASCII
Raises UnicodeDecodeError if non-ASCII characters are found."""
s.decode('ascii')
return s.lower() | 49dbebfdc0af9b74095c6069d5c0f50f470b05de | 661,961 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.