content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def convert(tree,fileName=None):
"""
Converts input files to be compatible with merge request ???.
Changes the <OutStreamManager> nodes to <OutStreams> nodes.
Changes class="OutStreamManager" to class="OutStreams".
@ In, tree, xml.etree.ElementTree.ElementTree object, the contents of a
RAVEN inp... | 8ad7c10b0fab5d35f7217567330038b1b5ed988f | 93,610 |
def keymap_replace_substrings(target_str,
mappings={"<": "left_angle_bracket",
">": "right_angle_bracket",
"[": "left_square_bracket",
"]": "right_square_bracket",
... | b63d8aa46a1b610ab20792f6afaf967a0ddd5c9c | 93,615 |
import math
def NIST_helper(L, N=None, p=None):
"""
Computes percentile p of sorted list L of length N using definition in NIST handbook Sec 7.2.5.2.
:param L: sorted list of values
:param N: length of list
:param p: percentile desired, in the interval [0,1], or None for median
:return: comput... | 7edd970f29718ca75814b2bfd8bef6981049ee6c | 93,617 |
def time_distributed(inputs, op, activation=None, **kwargs):
"""
apply op on both the batch (B) and time (T) dimension
args:
inputs: [B, T, ...]
op: a layer op that accepts [B, ...]
reshape: if reshape to [B, T, newshape]
return:
outputs: [B, T, ...]
"""
batch_si... | 762eb8bdd8dcaba90e3f1580a57d76c583b3a0da | 93,618 |
def electric_humidification_unit(g_hu, m_ve_mech):
"""
Refactored from Legacy
Central AC can have a humidification unit.
If humidification load is present, only the mass flow of outdoor air to be humidified is relevant
:param g_hu: humidification load, water to be evaporated (kg/s)
:type g_hu: ... | a3c48f4b7376ac13c02690b8ddc62d8ff887b4d4 | 93,620 |
def change_first_appearance(cur_str, target_char, new_char):
"""
changes the first appearance of a char to a new char
:param cur_str: the input string
:param target_char: the char we search for
:param new_char: the char we insert instead of the target char
:return: a new string with the new cha... | 342878ee2507bb2be735a19788da5136fb9556d7 | 93,627 |
def get_best_rssi_per_location(sensors):
"""Find the strongest signal in each location."""
best_rssi = {}
for sensor in sensors.values():
location = sensor["location"]
rssi = sensor["rssi"]
if rssi and (location not in best_rssi or rssi > best_rssi[location]):
best_rssi[l... | 0d4a51efe0468251aa47b0cd551c35c88e7f62b0 | 93,632 |
def max_len(iterable, minimum=0):
"""Return the len() of the longest item in ``iterable`` or ``minimum``.
>>> max_len(['spam', 'ham'])
4
>>> max_len([])
0
>>> max_len(['ham'], 4)
4
"""
try:
result = max(map(len, iterable))
except ValueError:
return minimum
... | 448f4f96e11c48ee19734907489df2a4ead82241 | 93,638 |
def promptYesOrNo(prompt):
"""
Prompts the user via the command line for a yes or a no input.
Will only take the letters y (yes) and n (no) as input. (case-insensitive)
No is the default option if an invalid input is given.
:param prompt: the text prompt given to the user before a decision
:retu... | 330a9883f5b555597bc8da1af5346ae3aecbbc0e | 93,643 |
def initializeGsheet(gc, key):
"""
Initialize the Google Sheet.
Inputs:
googleAPI_key [path] - path to the google API JSON file
sheetCode [string] - code to identify the sheet you want to access
Outputs:
Sheet [object] - google sheet that has been accessed
"""
Sheet = gc.open_by_key(key).sheet1
return ... | 9813c58bf6aeadcb2ed88937c7eb6fe8302112e8 | 93,647 |
import inspect
def _is_method_of(func_name, class_object):
"""Check if a given class object has a method of a given name.
:param func_name: the name of the method to be checked for
:param class_object: the instance of the class
:rtype: bool
"""
attr = getattr(class_object, func_name, None)
if attr is None:
... | 8ad0d4e13a284e3730ad1dddaa17bd940c5ad988 | 93,651 |
def _DisplayValue(info, field, padding):
"""Gets the value of field from the dict info for display.
Args:
info: The dict with information about the component.
field: The field to access for display.
padding: Number of spaces to indent text to line up with first-line text.
Returns:
The value of th... | 652d4eb9b32e29b9b695ff046d14e5f36c1075d1 | 93,652 |
import re
def extract_pattern(text, term_pattern):
"""Returns a list all terms found extracted
--------
text: string
term_pattern: pattern or term to extract(you can also use r'' for raw regex pattern)
"""
result = re.findall(term_pattern, text)
return result | a0830d74d1893c3effbf89aadbaa3adeb30534ab | 93,653 |
def clamp(value, _min, _max):
"""
Returns a value clamped between two bounds (inclusive)
>>> clamp(17, 0, 100)
17
>>> clamp(-89, 0, 100)
0
>>> clamp(65635, 0, 100)
100
"""
return max(_min, min(value, _max)) | 9e52d1a5fc86be1ddedb4ceca99dd188c213b36c | 93,654 |
def is_effective(x, y, eff_list):
"""
Function: Is there a valid path at the location.
:param x: (int) x coordinate
:param y: (int) y coordinate
:param eff_list: (list) effective_list
:return: (bool) Is there a valid path
"""
for check_x in (x-1, x, x+1):
for check_y in (y-1, y, y+1):
if check_x == x and... | a9a5b6c98141217e79ff84b9174f4fe4a9117f95 | 93,655 |
import re
def remove_empty_lines_starting_cell(text: str) -> str:
"""Remove empty lines from start of cell.
--- before ---
# %% comment
first_code = 'here'
--- after ---
# %% comment
first_code = 'here'
"""
# (?:\n\s*){2,} = non-capturing group for two or more new lines containin... | f542f43c5a0525b4ce1c3a87a56fd2e0fe2e5024 | 93,657 |
def one_hot_encode(integer_encoding, num_classes):
""" One hot encode.
"""
onehot_encoded = [0 for _ in range(num_classes)]
onehot_encoded[integer_encoding] = 1
return onehot_encoded | 026470df6ca9e533086b0471482ceb301e49ae93 | 93,661 |
import types
import logging
import importlib
def recursive_reload(module: types.ModuleType, package_restrict: str):
"""Recursively reload a module and the modules it imports.
Args:
module: The module to reload.
package_restrict: Only modules with this prefix will be reloaded. For
example, if packa... | 9da6e363e8c17a820fd57df2cc76d1a4f111beb5 | 93,664 |
def attribute_values(class_input):
"""Turn class attribute values into a list."""
return [m for v, m in vars(class_input).items() if not (v.startswith('_') or callable(m))] | 6d2d9744bed7a243fc27cc2d1b768e0a7a59fdff | 93,669 |
def is_word_end(s):
"""
Checks if a sign finishes a word
:param s: the sign to check
:return: true if the sign finishes the word
"""
if s[-1] in "-.":
return False
return True | 16c18d3b67a096979b917c94a103de0ca456e569 | 93,673 |
def merge(list1,list2):
"""
Takes two lists and merge them in a sorted list
"""
# Initialie the empty list
result=[]
i=0
j=0
# This loop runs till both input lists have non-zero elements in them
# That means this loop stops when either of the input list runs out of element
while ... | c18beb1e79700940c4e7b42ebc986ab016a64f9c | 93,675 |
def int_to_hex(value):
"""Convert integer to two digit hex."""
hex = '{0:02x}'.format(int(value))
return hex | 4bdbf6427a65f1b74076ad02a08d012331c9c405 | 93,676 |
def to_int(answer):
""" Converts user input to integer if conversion is not possible None is returned. """
try:
answer = int(answer)
except ValueError:
return None
return answer | d0705c326d062e7208745bda54d86516ff2706f4 | 93,677 |
def calculate_wave_height(outside_wave_height, max_surge):
"""
Calculates the wave height. Waves are assumed to break at 0.45 the water level
:param outside_wave_height: maximum wave height during event far of the coast [m]
:param max_surge: maximum water level at the location where the wave height is ... | 7d9dda905be91e9c3930fc082317f4b789c57154 | 93,678 |
import torch
def mul(x, y):
"""
Multiplies two complex-valued tensors x and y.
i.e. z = (a + ib) * (c + id)
"""
assert x.size(-1) == 2
assert y.size(-1) == 2
a = x[..., 0]
b = x[..., 1]
c = y[..., 0]
d = y[..., 1]
real = a * c - b * d
imag = a * d + b * c
return... | cf85458b2793974ce6873479a0d6fa5fd5a8a214 | 93,684 |
def floatN(x):
"""
Convert the input to a floating point number if possible, but return NaN if it's not
:param x: Value to convert
:return: floating-point value of input, or NaN if conversion fails
"""
try:
return float(x)
except ValueError:
return float('NaN') | 58013fc6e79ca3294981cb79e4dfc844ed00df9e | 93,685 |
from typing import Counter
from warnings import warn
def check_duplication(x: list) -> bool:
"""
Internal method. Given a list check for duplicates. Warning generated for duplicates.
Parameters
----------
x: list
Returns
--------
bool
True if duplicates are found, else False
... | 2138bab4b4f1455dfe388f5cdd7b4b9b9fb7766c | 93,688 |
def get_new_placeholder_name(node_id: str, is_out_port: bool = False, port: int = 0):
"""
Forms a name of new placeholder created by cutting a graph
:param node_id: a node name that is cut
:param is_out_port: it is True iff output port is cut
:param port: a port number
:return: a name of new pla... | 611ccb415d1f7cc2b857d7c1a522d6ea37fa2525 | 93,692 |
def find_host_for_osd(osd, osd_status):
""" find host for a given osd """
for obj in osd_status['nodes']:
if obj['type'] == 'host':
if osd in obj['children']:
return obj['name']
return 'unknown' | 7491493e635742aa29027c475762aaa7aa5f7ceb | 93,694 |
import re
from datetime import datetime
def timestampedFilename(baseFileName):
"""Return the .txt filename timestamped as <baseFileName>_<timestamp>.txt.
The 'baseFileName' is cleansed to have only [-a-zA-Z0-9_] characters.
"""
return "%s_%s.txt" % (
re.sub(r'[^-a-zA-Z0-9_\.]+', '', baseFileN... | be937ff80f3866d859ed3a1b0aa1405d57c25101 | 93,698 |
def find_image(glance, filters):
"""Find most recent image based on filters and ``version_name``.
:param filters: Dictionary with Glance image properties to filter on
:type filters: dict
:returns: Glance image object
"""
candidate = None
for image in glance.images.list(filters=filters,
... | e8100d0ec0f6ce1ef51b289a837c7746df0b804f | 93,699 |
def frame_rti(detectorrows, ampcolumns, colstart, colstop, rowstart, rowstop,
sampleskip, refpixsampleskip, samplesum, resetwidth,
resetoverhead, burst_mode):
"""
Helper function which calculates the number of clock cycles, or RTI,
needed to read out the detector with a give... | 07388d58bc1a8ddc2bc7df79266df264e36d3bd2 | 93,700 |
import torch
def log(x):
""" Log func to prevent nans """
return torch.log(x + 1e-8) | 4fc2c2940cb73d44cc0042cb49b15fc82972b6ed | 93,702 |
def indent(text, indent=" "):
"""
Indent text by the given indentation string.
"""
return "\n".join(indent + line for line in text.splitlines()) | 056fc62d9123f4259490fa7c80b4c5009e6a6167 | 93,703 |
def get_cache_key(key):
"""
Generates a prefixed cache-key for ultimatethumb.
"""
return 'ultimatethumb:{0}'.format(key) | 43d82dced6371742a58d18b1cbc1f3a9a48aae5c | 93,706 |
import tempfile
def create_symbol_redefinition_file(rename_symbols):
"""Create a helper file that will be used to redefine symbols.
Args:
rename_symbols: Dictionary of symbols to rename.
Returns:
NamedTemporaryFile object containing the helper data for redefining symbols,
or None if there are no sy... | cf60ed3001b22b4defa74b59a18105a7616d9140 | 93,710 |
import torch
def get_top_n_boxes(box_list, num):
"""
Args:
box_list: ([N_i,5],[N_,],[N, C]) x T*1
num: number of box for each in T*1
Returns:
1. [[N_j, 5] x T*1]
2. [[N_j, C] x T*1]
3. [[N_j,] x T*1]
where N_j <= num
"""
good_box_list = []
feat... | 93e6627b3d452a081c005d24dba00c851644133a | 93,713 |
def NOT(expression):
"""
Evaluates a boolean and returns the opposite boolean value.
See https://docs.mongodb.com/manual/reference/operator/aggregation/not/
for more details
:param expression: An array of expressions
:return: Aggregation operator
"""
return {'$not': [expression]} | 2eda757f3f63d1b1bdcb99a4c5358945ad4f49ef | 93,716 |
def blocks_to_seconds(blocks):
"""
Return the estimated number of seconds which will transpire for a given
number of blocks.
"""
return blocks * 2.12 * 60 | 259b5b5c8ce467b98bdb349e723d62f2b44736d6 | 93,717 |
from typing import List
def get_last_cursor(edges: List[dict]):
"""
Function to get the last cursor of the edges in a response
"""
if len(edges) > 0:
return edges[-1].get("cursor")
return None | 52b35af547f5a46b687053c7805fd796ab9185a5 | 93,721 |
def pontos_jogador(num_jogadores):
"""
Inicializa os pontos dos jogadores
:param num_jogadores: número de jogadores
:return: retorna os pontos do jogadores no início da partida
"""
pontos = []
for i in range(num_jogadores):
pontos.append([0, 0])
return pontos | 11c506667c6eafdb36b1dd20d76cd5c3cef3285c | 93,725 |
from typing import Dict
from typing import Union
def get_default_chassis_section() -> Dict[str, Union[int, str, list]]:
"""Create an empty chassis section with default values."""
return {
'format_version': 1,
'type': 0,
'part_number': '',
'serial_number': '',
'custom_f... | 9f00027ded6881a36f58073d937d4dc9f87247b7 | 93,726 |
def _cid2c(cid):
"""Gets just the component portion of a cid string
e.g. main_page/axis_controls|x_column.value => x_column
"""
return cid.split("|")[-1].split(".")[0] | 409f0ed212ae0453363618d684a07011ff5f9589 | 93,727 |
import json
def _json_normalize(x: dict) -> dict:
"""Normalize given graph to be JSON compatible (e.g. use lists instead of tuples)"""
return json.loads(json.dumps(x)) | 9ea4c49e8fd413ef4fb72c3175f577fcc8bf4d77 | 93,729 |
import pytz
from datetime import datetime
def timestamp_to_iso(timestamp, tz=pytz.UTC):
"""
Convert timestamp to ISO time (UTC only)
"""
return datetime.fromtimestamp(timestamp, tz=tz).replace(microsecond=0).isoformat() | 846ad0ad59fa76b5adc292ae7649de4ff3e0d116 | 93,730 |
def indexp(predicate, items):
"""Return the first index into items that satisfies predicate(item)."""
for i, item in enumerate(items):
if predicate(item):
return i
return -1 | f754ea9ae04c4b3a73c23aa325ed71dff0e52bc5 | 93,743 |
def checkInput(var, arr):
"""
check if input is a number and is in range of array's length
"""
# check whether the input is a number
while (not var.isnumeric()):
var = input(f"Wrong input, choose a number 1-{len(arr)}: ")
var = int(var)
# check if the inpunt is correct
while (v... | 5d26f14e045ecc31936037d95ce8a2e3fff29b33 | 93,746 |
def find_text_in_element(element, tag: str) -> str:
"""
Find a text in an XML element.
Args:
element (Element): XML element.
tag (str): the XML tag to search for.
Returns:
str: the text of the tag that was searched.
"""
result = element.find(tag)
# This has to be an... | 2de6408580c95b428977fdda52b5e1edd46a127c | 93,748 |
def _romberg_diff(b, c, k):
"""Compute the differences for the Romberg quadrature corrections.
See Forman Acton's "Real Computing Made Real," p 143.
:param b: R(n-1, m-1) of Rombergs method.
:param c: R(n, m-1) of Rombergs method.
:param k: The parameter m of Rombergs method.
:type b: float or... | 22649fa829eb90597f029ed823a6e5f5d72c6ecd | 93,752 |
def sec_to_min_pretty(time_secs: int) -> str:
"""
Returns formatted string for converting secs to mins.
"""
if time_secs % 60 == 0:
return f'{time_secs // 60}'
m = time_secs / 60
return f'{m:.2g}' | 32ee50794293a332ae753e5c99e5bf18681eb9c4 | 93,755 |
import re
def is_email(value):
"""Check if given value looks like an email address."""
email_regex = r"[^@]+@[^@]+\.[^@]+"
return re.match(email_regex, value) | 1f2d0cc59d96791c90f42c748012536f2865a99d | 93,759 |
import random
def get_choice(choices=None, **kwargs):
""" Get a random element from collection.
:param choices: A collection
:return value: A random element
::
print get_choice([1, 2, 3]) # -> 1 or 2 or 3
"""
if not choices:
return None
return random.choice(choices) | 22e7b4e91deee5b808d356b9cc2fe613c977572b | 93,762 |
def helper_time_percent_complete(inf, percent_complete=0.25):
"""Helper function to calculate when the infection is percent_complete.
Args:
inf: an xr.DataArray representing new_infections with
dimensions of (location, sample, time).
percent_complete: a float representing the percent of the epidemic ... | 0aaa4366eebb1ebf825f8eb2cdd7f46d1993b269 | 93,766 |
def get_bound_cond(ti_mps):
"""
Gets the boundary condition defining our TI-MPS
Args:
ti_mps: TI-MPS language model
Returns:
bound_cond: A string from one of the following options:
'positive' -> Trainable positive mats at edges
'open' ... | 6a999fac8a1624a7f298883f50df4b57969a2f52 | 93,767 |
def _list_remove_duplicates(list_with_dup):
"""
Return a copy of a list without duplicated items.
:param list_with_dup: Input list that may contain duplicates
:return: List that does not contain duplicates
"""
set_no_dup = set(list_with_dup)
list_no_dup = list(set_no_dup)
return list_no... | fcc0ce688a0a201adba3fa706b13452383d5b58e | 93,768 |
from typing import Tuple
def span_intersect_span(span1: Tuple[int, int], span2: Tuple[int, int]):
"""Returns True if the given spans intersect"""
return (span1[0] <= span2[0] < span1[1]) or (span2[0] <= span1[0] < span2[1]) | b9e087d3a73136b32dad8dbc757860ccb0815227 | 93,770 |
def solve_new_captcha(line):
"""
>>> solve_new_captcha('1212')
6
>>> solve_new_captcha('1221')
0
>>> solve_new_captcha('123425')
4
>>> solve_new_captcha('123123')
12
>>> solve_new_captcha('12131415')
4
"""
return sum(int(x) for x, y in zip(line, line[len(line) // 2 :]... | b4e9d117006b6f9d9d45e78bfd4bed196e62e882 | 93,773 |
import re
def is_valid_email(email):
"""
return True if email is a valid email and
False if email is not a valid email.
email - (str) an email to be validated
"""
regex = '^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$'
if (re.search(regex,email)):
return True
else:
return False | 04a5cdb4a82e1d71f28d15ed7b40a64919b758d0 | 93,774 |
from functools import reduce
def get_num_divisors(factorization):
"""
Determine the number of different divisors given a factorization.
"""
powers = list(factorization.values())
num_divisors = reduce(lambda x, y: x * y, [_p + 1 for _p in powers])
return num_divisors | 252af7dad1250a105e665ccdd153fe8e9d9ae988 | 93,784 |
def _make_snippet_bidi_safe(snippet):
"""Place "directional isolate" characters around text that might be RTL.
U+2068 "FIRST STRONG ISOLATE" tells the receiving client's text renderer
to choose directionality of this segment based on the first strongly
directional character it finds *after* this mark.
... | 71941b6e3c95881ac73ab55ef18871d7a3ca561e | 93,789 |
import re
def does_text_contain_section(pagetext: str, section: str) -> bool:
"""
Determine whether the page text contains the given section title.
It does not care whether a section string may contain spaces or
underlines. Both will match.
If a section parameter contains an internal link, it wi... | fd46b7f57d060aebcc141b7f306140ebec7b36e8 | 93,795 |
def merge_flags(cfg1, cfg2):
"""Merge values from cffi config flags cfg2 to cf1
Example:
merge_flags({"libraries": ["one"]}, {"libraries": ["two"]})
{"libraries": ["one", "two"]}
"""
for key, value in cfg2.items():
if key not in cfg1:
cfg1[key] = value
else:
... | 3d86249d0143a578ce221ed66bb7e4e67cd93a97 | 93,798 |
def egcd(a, b):
"""Return (s,t,d), such that d = gcd(a,b), and s*a + t*b = d."""
if b == 0:
return (1, 0, a)
else:
(s, t, d) = egcd(b, a % b)
return (t, s - t * (a / b), d) | db9d6257f1b99e48aa0584a3e700cc304c8ec025 | 93,806 |
def get_index_for_column(dataset, col_id):
"""Get index position for column with given id in dataset schema.
Raises ValueError if no column with col_id exists.
Parameters
----------
dataset: vizier.datastore.base.DatasetHandle
Handle for dataset
col_id: int
Unique column identi... | e2b3f4f48649d588a5d6a024b8f0d6fd72eeb305 | 93,808 |
def to_tf_matrix(expression_matrix,
gene_names,
tf_names):
"""
:param expression_matrix: numpy matrix. Rows are observations and columns are genes.
:param gene_names: a list of gene names. Each entry corresponds to the expression_matrix column with same index.
:param tf... | ee2214af5dd96454155e58761d69d35a4cf281b8 | 93,810 |
def validate_notification(notification, valid_events):
"""
Validate a notification
"""
for item in notification:
if item not in ('event', 'type'):
return (False, 'invalid item "%s" in notifications' % item)
if item == 'event':
if notification[item] not in valid_ev... | e65d49815b1e72d2428362957da0671d678e8352 | 93,811 |
def discount(rewards, impatience):
"""Sum the rewards, where far off rewards are devalued by impatience.
For example, if rewards were [1, 1, 1, 1] and impatience was 0.5,
returns: sum([1, 0.5, 0.25, 0.125])
Args:
rewards (list): list of rewards to accumulate
impatience (float): factor ... | bffd30a9133b2cb4b6a596fc060e01d7f0333efd | 93,813 |
def two_pt_parabola(pt1,pt2):
"""
Given two points, gives us the coefficients for a parabola.
args:
pt1: The first point.
pt2: The second point.
"""
[x1, y1] = pt1 * 1.0
[x2, y2] = pt2 * 1.0
a = (y2-y1)/(x2-x1)**2
c = y1 + a*x1*x1
b = -2*a*x1
return [a,b,c] | c8b10768f3d5c368da5d178e06c34a9fbcfc053f | 93,818 |
import json
def _load_configurations(filename):
"""
Load JSON configuration file in a dict.
:param filename: name of the JSON file containing the configuarions.
"""
return json.loads(open(filename).read()) | ce3d6aa8612149e4809df8c6375a0255c3eae5ed | 93,820 |
def contains_reserved_character(word):
"""Checks if a word contains a reserved Windows path character."""
reserved = set(["<", ">", ":", "/", "\\", "|", "?", "*"])
word_set = set(list(word))
return not reserved.isdisjoint(word_set) | 80a90efda3219348410b8ad72279218d79781c9c | 93,821 |
def show_hidden_word(secret_word, old_letters_guessed):
"""
this function shows the player his progress in the game
:param secret_word: the word the player has to guess
:param old_letters_guessed: all the characters the player has already guessed
:type secret_word: str
:type old_letters_guessed... | 32ae301bf70bde235642c34898e32b1e31f46992 | 93,824 |
import math
def cell_vol(lpa,lpb,lpc,lpal,lpbe,lpga):
"""Calculate cell volume from cell parameters: a,b,c,alpha,beta,gamma."""
tmp_V = lpa*lpb*lpc*math.sqrt(1-math.cos(lpal*math.pi/180.0)*math.cos(lpal*math.pi/180.0)\
-math.cos(lpbe*math.pi/180.0)*math.cos(lpbe*math.pi/180.0... | 91b0047c655493de09bb8e2581c9082becaeadcb | 93,825 |
def hinged_line(ecc, slope, hinge_ecc, intercept=0):
"""Hinged line with an optional intercept.
Parameters
----------
ecc : jnp.ndarray
Eccentricity of RGC cells.
slope : jnp.ndarray
The slope giving the relationship between eccentricity and diameter.
hinge_ecc : jnp.ndarray
... | 284405a6dbc79329097f59574ded3c7987aa58df | 93,828 |
from typing import Any
def is_non_seperable(mode: Any) -> bool:
"""Check if blend mode is non-separable."""
return mode in frozenset(['color', 'hue', 'saturation', 'luminosity']) | dc0f0fb0e46bf8cbeee4485648474d30df4c6dfc | 93,829 |
def powerstore_host_name(connector, protocol):
"""Generate PowerStore host name for connector.
:param connector: connection properties
:param protocol: storage protocol (FC or iSCSI)
:return: unique host name
"""
return ("%(host)s-%(protocol)s" %
{"host": connector["host"],
... | 804956f97274285e9a7fc6d8f798113319560e04 | 93,830 |
def wrap_class_methods(
_return_a_copy_of_the_class=True,
_raise_error_if_non_existent_method=True,
**wrapper_for_method,
):
"""
Make a decorator that wraps specific methods.
IMPORTANT: The decorator will by default return a copy of the class. This might incur some run time overhead.
If thi... | 6eae6fa3f5d2508a4ba785ed2b7ebd3c9f339e18 | 93,836 |
def get_roll_selection(prompt:str = '\nRoll again? (y/n): '):
"""Return the users character when prompted to continue (y/n)."""
return input(prompt) | f18203efa800da09c789e330625c4ba4c3d23ee6 | 93,837 |
import json
def le_arquivo_json(caminho):
"""
Dado o <caminho> do arquivo, tenta ler seu conteúdo como JSON.
Se conseguir, retorna o conteúdo em forma de dicionário.
"""
# Carrega o arquivo sons.json no modo leitura (r)
try:
with open(caminho, 'r') as f:
# Extrai o dicion... | 86b7811d9f1b07779d9d596691f255cc7561d983 | 93,839 |
def is_valid_firewall_setting(f, service_exploits):
"""
Check that a given firewall setting is valid given the list of service exploits available
"""
if type(f) != list:
return False
for service in f:
if service not in service_exploits:
return False
for i, x in enumer... | a00afc615d5d81b036404a473e9e4bcbdf6ae278 | 93,840 |
def _check_regular_chunks(chunkset):
"""Check if the chunks are regular
"Regular" in this context means that along every axis, the chunks all
have the same size, except the last one, which may be smaller
Parameters
----------
chunkset: tuple of tuples of ints
From the ``.chunks`` attri... | 4b9ff89bc7e54170b3f1ffb0779df92e52182699 | 93,845 |
import string
def tamper(payload, **kwargs):
"""
Double url-encodes all characters in a given payload (not processing
already encoded)
Notes:
* Useful to bypass some weak web application firewalls that do not
double url-decode the request before processing it through their
... | b3f45667898a23228492477247e27880b235aa3f | 93,849 |
import re
def extract_variables(content):
"""
从内容中提取所有变量名, 变量格式为$variable,返回变量名list
:param content: 要被提取变量的用例数据
:return: 所有要提取的变量
"""
variable_regexp = r"\$([\w_]+)"
if not isinstance(content, str):
content = str(content)
try:
return re.findall(variable_regexp, content)... | 1ce8d3a363c03bb518096c2f3b8d4fe100f793f4 | 93,854 |
def format_channel_name(channel_number: str, channel_name: str | None = None) -> str:
"""Format a Roku Channel name."""
if channel_name is not None and channel_name != "":
return f"{channel_name} ({channel_number})"
return channel_number | 036a3954f8ff7804b0538ab9ac1667fcf0653704 | 93,855 |
import types
from typing import Iterator
def html_table(dictset: Iterator[dict], limit: int = 5):
"""
Render the dictset as a HTML table.
NOTE:
This exhausts generators so is only recommended to be used on lists.
Parameters:
dictset: iterable of dictionaries
The dictset t... | e246c75dd30e5e37c8c4dfa7b60bb11b080dd7ba | 93,861 |
import requests
def request_inform(server, requester, player, id, colour=None, rank=None):
"""
Give a player information about a card.
"""
data = {'recipient': player}
if colour is None:
assert(rank is not None)
data['rank'] = rank
if rank is None:
assert(colour is not ... | ae38baab435fb153b1fcdaf1a48f66c89b30afbc | 93,862 |
def factorial(n: int) -> int:
"""Compute n! recursively.
:param n: an integer >= 0
:returns: n!
Because of Python's stack limitation, this won't
compute a value larger than about 1000!.
>>> factorial(5)
120
"""
if n == 0:
return 1
return n * factorial(n - 1) | e7c0e81938ea4f59d2b02a4f1440804d5c510340 | 93,864 |
def f_my2(n):
"""
Try to simplify the previous function f_my
"""
pre2, pre1 = 0, 1
if n == 0:
return 0
if n == 1:
return 1
for i in range(2, n+1):
pre2, pre1 =pre1, pre2+pre1 # for current state
return pre1 | c46decd2cafe7df30e07ee5757571bfb07a3ff5e | 93,869 |
def bases_overlap(frst, scnd):
"""
Get the number of overlapping bases.
:param frst: a tuple representing the first region
with chromosome, start, end as the first
3 columns
:param scnd: a tuple representing the second region
with chromosome, start, en... | bb730ce0462b4471de4252434cf453d50e4fdf2a | 93,872 |
def preprocess_config(parser):
""" Adds Command line arguments to an empty Argument Parser
Input
--------------
parser - argparse.ArgumentParser . An initialized empty Arg Parser
Output
--------------
parser - argparse.ArgumentParser. Returns the argument parser with added
a... | 2a39bc0de559ab4d52d781257420163db70bdc53 | 93,876 |
def find_DETECTOR(output_hdul):
"""
This function determines which detector was used
Args:
output_hdul: the HDU list of the output header keywords
Returns:
det: string, either NRS1 or NRS2
"""
if "DETECTOR" in output_hdul:
det = output_hdul["DETECTOR"]
return det | cc7953b5a69d76a6ee9d0fd746730e0e7f23f0d4 | 93,890 |
def get_repo_push_url(args):
"""Return the fully expanded push url for this repo or None.
:args: the namespace returned from the argparse parser
:returns: string url to push the repo, or None
"""
url = None
if args.repo_push_url_format:
url = args.repo_push_url_format.format(args.repo_... | 7dffb88c96663b3ab575767892b5ae6cbc43aee9 | 93,892 |
def _DecodeUTF8(pb_value):
"""Decodes a UTF-8 encoded string into unicode."""
if pb_value is not None:
return pb_value.decode('utf-8')
return None | 16c729de7be804b4751ca2c083a4878fdafd345e | 93,896 |
def _makeGetter(compiledName):
"""Return a method that gets compiledName's value."""
return lambda self: self.__dict__[compiledName] | 8e3c51f3ae4eddb6cf5d9356e0c9f0da77142291 | 93,908 |
import fnmatch
def get_re_from_single_line(line):
"""Get regular expression from a single line in `.gitignore`
The rules of `.gitingore` followed http://git-scm.com/docs/gitignore
:param line: str -- single line from `.gitignore`
:return: tuple
0, None -- noting to match
1, str -- has... | 9fc07c7b9a729dbed8e621689ba01150b64c31f3 | 93,914 |
def parse_env_urls(urls=None):
"""Parses a list of urls
>>> parse_env_urls(urls='https://kibana.energy.svc.dbg.com | https://grafana.energy.svc.dbg.com')
['https://kibana.energy.svc.dbg.com', 'https://grafana.energy.svc.dbg.com']
"""
urls_list = [] if urls == None else urls.split('|')
urls_... | 518a2ae449c037cc63697b492fcfbf4a35123bd6 | 93,919 |
import yaml
def load_config(config_file='/etc/thermopi.yaml'):
"""Load the configuration file.
Parameters
----------
config_file : str
Path to the configuration file to load.
Returns
-------
dict
Dict containing the configuration file.
"""
with open(config_file) ... | 9ead1e95de530f935971b34838a7ebc098ffecea | 93,921 |
def check_final_winner(result):
"""
check_final_winner(result) --> string
result : ex) ['player', 'player']
반환값 : 만약 result 안에 'player' 가 두 개 이상이면 : 'player'
'computer' 가 두 개 이상이면 : 'computer'
otherwise : none
"""
print(f"player: {result.count('player')}승, computer: {resu... | 5be931344cf36e71783a9c881405b04e6b1cda5e | 93,922 |
def make_values(params, point):
"""Return a dictionary with the values replaced by the values in point,
where point is a list of the values corresponding to the sorted params."""
values = {}
for i, k in (enumerate)((sorted)(params)):
values[k] = point[i]
return values | 0013380053c897f241752dc7a1bfbb3259d55822 | 93,924 |
def append_footer(cmd, marker):
"""
Append header/footer to `cmd`.
Returns:
str: new_command
"""
header = ""
footer = """
EXIT_CODE=$?
echo {marker}code: ${{EXIT_CODE}}{marker}
echo {marker}pwd: $(pwd){marker}
echo {marker}env: $(cat -v <(env -0)){marker}
""".format(
marker=mark... | f4db0be0a9a9b95915b21bcc07da2b253c027292 | 93,925 |
def capitalize(str):
"""Capitalize a string, not affecting any character after the first."""
return str[:1].upper() + str[1:] | 2c3230f825dd924fa3bc6e1b1aa7015b9d1a0ff1 | 93,930 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.