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 input file
@ In, fileName, the name for the raven input file
@Out, tree, xml.etree.ElementTree.ElementTree object, the modified RAVEN
input file
"""
rootNode = tree.getroot()
if rootNode.tag not in ['Simulation', 'OutStreamManager', 'Steps']:
## This is not a valid input file, or at least not one we care about for
## this conversion
return tree
osmNode = None
stepsNode = None
if rootNode.tag == 'Simulation':
osmNode = rootNode.find('OutStreamManager')
stepsNode = rootNode.find('Steps')
elif rootNode.tag == 'outstreamManager':
## Case for when the OutStreamManager node is specified in an external file.
## (Steps should not be in this file?)
osmNode = rootNode
elif rootNode.tag == 'Steps':
## Case for when the Steps node is specified in an external file.
## (OutStreamManager should not be in this file?)
stepsNode = rootNode
if osmNode is not None:
osmNode.tag = 'OutStreams'
if stepsNode is not None:
for outputNode in stepsNode.iter('Output'):
if 'class' in outputNode.attrib and outputNode.attrib['class'] == 'OutStreamManager':
outputNode.attrib['class'] = 'OutStreams'
return tree | 8ad7c10b0fab5d35f7217567330038b1b5ed988f | 93,610 |
def keymap_replace_substrings(target_str,
mappings={"<": "left_angle_bracket",
">": "right_angle_bracket",
"[": "left_square_bracket",
"]": "right_square_bracket",
"{": "left_curly_bracket",
"}": "right_curly_bracket",
"\n": "newline"}):
"""Replace parts of a string based on a dictionary.
This function takes a dictionary of
replacement mappings. For example, if I supplied
the string "Hello world.", and the mappings
{"H": "J", ".": "!"}, it would return "Jello world!".
Warning: replacements are made iteratively,
meaning multiple replacements could occur.
:param target_str: (str)
The string to replace characters in.
:param mappings: (str)
A dictionary of replacement mappings.
:return: (str)
String with values replaced
"""
for substring, replacement in mappings.items():
target_str = target_str.replace(substring, replacement)
return target_str | 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: computer percentile p of sorted list L
"""
if N is None: N = len(L)
if N < 1:
return None
elif N < 2:
return L[0]
if p is None:
p = 0.5
weight, base = math.modf(float(p) * (N + 1))
base = int(base) - 1
if base < 0:
return L[0]
elif base >= N - 1:
return L[-1]
else:
return float(L[base]) + weight * (float(L[base + 1]) - float(L[base])) | 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_size = inputs.size(0)
seq_len = inputs.size(1)
p_dim = inputs.size()[2:]
outputs = op(inputs.view(-1, *p_dim), **kwargs)
out_dim = outputs.size()[1:]
if activation is not None:
outputs = activation(outputs)
outputs = outputs.view(batch_size, seq_len, *out_dim)
return outputs | 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: double
:param m_ve_mech: mechanical ventilation air flow, outdoor air (kg/s)
:type m_ve_mech: double
:return: e_hs_lat_aux, electric load of humidification (W)
:rtype: double
"""
if g_hu > 0.0:
# Adiabatic humidifier - computation of electrical auxiliary loads
e_hs_lat_aux = 15.0 * m_ve_mech * 3600.0 # assuming a performance of 15 W por Kg/h of humidified air source: bertagnolo 2012
else:
e_hs_lat_aux = 0.0
return e_hs_lat_aux | 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 char instead of the first appearance of the target char
"""
first_appearance = cur_str.find(target_char)
return cur_str[:first_appearance] + new_char + cur_str[first_appearance + 1:] | 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[location] = rssi
return best_rssi | 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
return max(result, 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
:return: True is the choice was a 'yes' and False in all other circumstances
"""
choice = input(prompt + " [y/N]: ")[0].capitalize()
return choice == "Y" | 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 Sheet | 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:
return False
else:
return inspect.ismethod(attr) | 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 the field for display, or None if no value should be displayed.
"""
value = info.get(field)
if value is None:
return None
skip_doc_types = ('dict', 'list', 'unicode', 'int', 'float', 'bool')
if field == 'docstring':
if info.get('type_name') in skip_doc_types:
# Don't show the boring default docstrings for these types.
return None
elif value == '<no docstring>':
return None
elif field == 'usage':
lines = []
for index, line in enumerate(value.split('\n')):
if index > 0:
line = ' ' * padding + line
lines.append(line)
return '\n'.join(lines)
return value | 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 check_y == y:
pass
else:
if eff_list[check_x][check_y] == 1:
return True
return False | 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 containing
# only optional white space
return re.sub(r"(?m)^(# %%[^\n]*)(?:\n\s*){2,}", r"\g<1>\n", text) | 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 package_restrict is "scenic.projects", only modules under
scenic.projects will be reloaded. package_restrict must always be set to
avoid reloading of built-in or unrelated packages that should not be
reloaded (e.g. Numpy).
Returns:
The reloaded module object.
Raises:
ValueError if package_restrict is empyt.
"""
reloaded = set()
if not package_restrict:
raise ValueError('package_restrict must be non-empty.')
def reload(m):
if m in reloaded:
return m
reloaded.add(m)
for attribute_name in dir(m):
attribute = getattr(m, attribute_name)
if (isinstance(attribute, types.ModuleType) and
attribute.__name__.startswith(package_restrict)):
reload(attribute)
logging.info('Reloading %s', m.__name__)
return importlib.reload(m)
return reload(module) | 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 (len(list1)>0 and len(list2)>0):
if list1[0]<=list2[0]:
# Append to the result list
result.append(list1[0])
#print("Result:",result)
# Pop the first element of the list
list1.pop(0)
i=i+1
else:
# Append to the result list
result.append(list2[0])
#print("Result:",result)
# Pop the first element of the list
list2.pop(0)
j+=1
# Now checking which input list has run out of element.
# Whichever list still has element left, append all of them to the result array
# Note, only one of these if-loops will be executed
if(len(list1)>0):
result=result+list1
if(len(list2)>0):
result=result+list2
#print(f"i:{i},j:{j}")
return (result) | 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 calculated [m+MSL]
:return wave_height: wave height at the location [m]
"""
wave_height = min(outside_wave_height, 0.45*max_surge)
return wave_height | 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 torch.stack((real, imag), dim=-1) | 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
"""
x = [i if i else None for i in x]
duplicates = [item for item, count in Counter(x).items() if count > 1 and item is not None]
if duplicates:
warn(f'Duplicate channel/markers identified: {duplicates}')
return True
return 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 placeholder created by cutting a graph
"""
port_type = '_out' if is_out_port else ''
return '{}/placeholder{}_port_{}'.format(node_id, port_type, port) | 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_\.]+', '', baseFileName),
datetime.now().strftime('%Y%m%d_%H%M%S')) | 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,
sort_key='created_at',
sort_dir='desc'):
# glance does not offer ``version_name`` as a sort key.
# iterate over result to make sure we get the most recent image.
if not candidate or candidate.version_name < image.version_name:
candidate = image
return candidate | 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 given a list of FPGA parameters.
This function can be used to test the frame time calculation over a
wide range of scenarios.
:Reference:
JPL MIRI DFM 478 04.02, MIRI FPS Exposure Time Calculations,
M. E. Ressler, October 2014
:Parameters:
detectorrows:
Total number of detector rows.
ampcolumns
Total number of amplifier columns (including reference columns).
= Total number of detector columns / Number of amplifiers.
colstart: int
Amplifier column at which readout starts.
Derived from the subarray mode.
colstop: int
Amplifier column at which readout stops.
Derived from the subarray mode.
rowstart: int
Detector row at which readout starts.
Derived from the subarray mode.
rowstop: int
Detector row at which readout stops.
Derived from the subarray mode.
sampleskip: int
Number of clock cycles to dwell on a pixel before reading it.
Derived from the readout mode.
refpixsampleskip: int
Number of clock cycles to dwell on a reference pixel before reading it.
Derived from the readout mode.
samplesum: int
Number of clock cycles to sample a pixel during readout.
resetwidth: int
Width of the reset pulse in clock cycles.
Derived from the readout mode.
resetoverhead: int
The overhead, in clock cycles, associated with setting shift
registers back to zero.
burst_mode: boolean, optional, default is False
True if a subarray is being read out in burst mode,
which skips quickly over unwanted columns.
:Returns:
frame_rti: float
Number of clock cycles (RTI) for readout.
"""
# The time taken to skip a row not contained in a subarray is the
# row reset overhead, which is the reset pulse width plus the overhead
# to reset the shift registers.
row_reset = resetwidth + resetoverhead
rti_row_non_roi = row_reset
# The number of clock cycles needed to read a pixel is the
pix_clocks = sampleskip + samplesum
refpix_clocks = refpixsampleskip + samplesum
if (colstart == 1) or (not burst_mode):
# For a row within a subarray (if burst_mode is False or the subarray
# begins at column 1), we start with the row reset overheads, then add
# the reference pixel time, refpix_clocks, then add the science pixel
# time, n * pix_clocks.
rti_row_roi = row_reset
# strg = "rti_row_roi=%d " % row_reset
if colstart == 1:
rti_row_roi += refpix_clocks
# strg += " + %d " % refpix_clocks
else:
rti_row_roi += resetwidth
if colstop == ampcolumns:
rti_row_roi += (colstop-2) * pix_clocks
# strg += " + (%d * %d) " % ((colstop-2), pix_clocks)
rti_row_roi += refpix_clocks
# strg += " + %d " % refpix_clocks
else:
rti_row_roi += (colstop-1) * pix_clocks
# strg += " + (%d * %d) " % ((colstop-1), pix_clocks)
# print(strg)
else:
# In burst_mode, when a subarray does not touch the left hand edge,
# each row begins with the same reset overhead, then the left hand
# pixels are clocked at 5 times the normal rate until the subarray
# is reached. If the number of burst columns is not an even multiple
# of 5, the readout is paused until a normal clock boundary.
rti_row_roi = row_reset
# strg = "rti_row_roi=%d " % row_reset
if colstart == 1:
rti_row_roi += refpix_clocks
# strg += " + %d " % refpix_clocks
else:
rti_row_roi += refpix_clocks + ((colstart-2)*pix_clocks+4)//5
# strg += " + %d + %d " % (refpix_clocks,
# ((colstart-2)*pix_clocks+4)//5)
if colstop == ampcolumns:
rti_row_roi += ((colstop-2)-colstart+1) * pix_clocks
# strg += " + (%d * %d) " % (((colstop-2)-colstart+1), pix_clocks)
rti_row_roi += refpix_clocks
# strg += " + %d " % refpix_clocks
else:
rti_row_roi += (colstop-colstart+1) * pix_clocks
# strg += " + (%d * %d) " % ((colstop-colstart+1), pix_clocks)
# print(strg)
# The total number of clock cycles to read the frame is the sum
# of the portion before the ROI, after the ROI and during the ROI.
# print("rti_row_non_roi=", rti_row_non_roi, "rti_row_roi=", rti_row_roi)
frame_rti = (rowstart-1) * rti_row_non_roi + \
(rowstop-rowstart+1) * rti_row_roi + \
(detectorrows-rowstop) * rti_row_non_roi
return frame_rti | 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 symbols to rename.
"""
if not rename_symbols:
return None
# Write the symbol redefinition file. It will be cleaned up when the program
# exits.
redefinition_file = tempfile.NamedTemporaryFile()
redefinition_data = open(redefinition_file.name, "w")
any_written = False
for key, val in rename_symbols.items():
if key != val:
any_written = True
redefinition_data.write("%s %s\n" % (key, val))
redefinition_data.close()
return redefinition_file if any_written else None | 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_seq = []
ind_list = []
for boxes, labels, feat in box_list:
num_boxes = min(num, len(boxes))
_, ind = boxes[:, -1].topk(num_boxes)
good_box_list.append(boxes[ind])
feat_seq.append(feat[ind])
ind_list.append(ind)
feat_seq = torch.cat(feat_seq, 0)
return good_box_list, feat_seq, ind_list | 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_fields': [],
} | 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 (var < 1 or var > len(arr)):
var = int(input(f"Wrong input, number in range 1-{len(arr)}: "))
return var | 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 exact check, as an element that has no text will evaluate to none.
if result is None:
raise LookupError(f"Tag {tag} not found in element.")
if not hasattr(result, "text"):
raise LookupError(f"Tag {tag} has no text.")
return result.text if result.text else "" | 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 array[float]
:type c: float or array[float]
:type k: int
:returns: R(n, m) of Rombergs method.
:rtype: float or array[float]
"""
tmp = 4.0**k
diff = (tmp * c - b) / (tmp - 1.0)
return diff | 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 that we
want to see completed.
Returns:
true_time: an xr.DataArray containing the ground truth time of
the percent complete. Has dims (location, sample).
"""
# Calculate the total epidemic size
total_size = inf.sum('time')
target_size = percent_complete * total_size
cumulative_infections = inf.cumsum('time')
target_time = cumulative_infections.where(
cumulative_infections <= target_size).argmax('time')
return target_time | 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' -> Trainable rank-1 mats at edges
'white_noise' -> Identity matrices at edges
'infinite' -> Transfer op fixed-points at edges
"""
shape_len = len(ti_mps.bound_obj.shape)
if shape_len == 3:
return 'positive'
elif shape_len == 2:
return 'open'
elif shape_len == 1:
return 'infinite'
elif shape_len == 0:
return 'white_noise' | 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_dup | 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 :] + line[: len(line) // 2]) if x == y) | 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.
U+2069 is POP DIRECTIONAL ISOLATE, which tells the receiving client's text
renderer that this segment has ended, and it should go back to using the
directionality of the parent text segment.
Marking strings from the YouTube API that might contain RTL or
bidirectional text in this way minimizes the possibility of weird text
rendering/ordering in IRC clients' output due to renderers' incorrect
guesses about the directionality or flow of weakly directional or neutral
characters like digits, punctuation, and whitespace.
Weird text wrapping in lines with long opposite-direction phrases that
cross visual line breaks may still occur, and any values that *contain*
both RTL and LTR text might still render funny in other ways—but that's
really much farther into the weeds than we need to go. This should be
enough of a hint to clients' text rendering that the results won't
*completely* suck.
See https://github.com/sopel-irc/sopel-youtube/issues/30
"""
keys = ['title', 'channelTitle']
for key in keys:
try:
snippet[key] = "\u2068" + snippet[key] + "\u2069"
except KeyError:
# no need to safeguard something that doesn't exist
pass
return snippet | 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 will match the
section with or without a preceding colon which is required for a
text link e.g. for categories and files.
:param pagetext: The wikitext of a page
:param section: a section of a page including wikitext markups
"""
# match preceding colon for text links
section = re.sub(r'\\\[\\\[(\\?:)?', r'\[\[\:?', re.escape(section))
# match underscores and white spaces
section = re.sub(r'\\?[ _]', '[ _]', section)
m = re.search("=+[ ']*{}[ ']*=+".format(section), pagetext)
return bool(m) | 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:
if not isinstance(cfg1[key], list):
raise TypeError("cfg1[%r] should be a list of strings" % (key,))
if not isinstance(value, list):
raise TypeError("cfg2[%r] should be a list of strings" % (key,))
cfg1[key].extend(value)
return cfg1 | 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 identifier
Returns
-------
int
"""
for i in range(len(dataset.columns)):
if dataset.columns[i].identifier == col_id:
return i
# Raise ValueError if no column was found
raise ValueError('unknown column identifier \'' + str(col_id) + '\'') | 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_names: a list of transcription factor names. Should be a subset of gene_names.
:return: tuple of:
0: A numpy matrix representing the predictor matrix for the regressions.
1: The gene names corresponding to the columns in the predictor matrix.
"""
tuples = [(index, gene) for index, gene in enumerate(gene_names) if gene in tf_names]
tf_indices = [t[0] for t in tuples]
tf_matrix_names = [t[1] for t in tuples]
return expression_matrix[:, tf_indices], tf_matrix_names | 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_events:
return (False, 'invalid notification event "%s"' % notification[item])
if item == 'type':
if notification[item] != 'email':
return (False, 'invalid notification type "%s"' % notification[item])
return (True, '') | 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 to discount the rewards at
"""
total, factor = 0, 1.0
for r in rewards:
total += r * factor
factor *= impatience
return total | 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: list
:return: a string which consists of letters and underlines
the string displays the letters from the old_letters_guessed list that
are in the secret_word string in their appropriate position,
and the rest of the letters in the string (which the player has not yet guessed) as underlines
:rtype: str
"""
returned_string = ""
for char in secret_word:
if char in old_letters_guessed:
returned_string += char
else:
returned_string += "_"
return " ".join(returned_string) | 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) \
-math.cos(lpga*math.pi/180.0)*math.cos(lpga*math.pi/180.0)\
+2*math.cos(lpal*math.pi/180.0)*math.cos(lpbe*math.pi/180.0)*math.cos(lpga*math.pi/180.0))
return tmp_V | 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
Eccentricity at which the line hinges.
intercept : jnp.ndarray, optional
The intercept for the line.
Returns
-------
diameter_mean : jnp.ndarray
The mean diameter at each location.
"""
diam = intercept + ecc * slope
return diam.clip(intercept + hinge_ecc * slope) | 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"],
"protocol": protocol, }) | 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 this is desirable, for example, when you want to create several decorations of a same class.
If you want to change the class itself (e.g. you're only loading it once in a module, and decorating it), then
specify _return_a_copy_of_the_class=False
Note that _return_a_copy_of_the_class=True has a side effect of building russian dolls of essentially subclasses
of the class, which may have some undesirable results if repeated too many times.
:param _return_a_copy_of_the_class: Specifies whether to
return a copy of the class (_return_a_copy_of_the_class=True, the default),
or change the actual loaded class itself (_return_a_copy_of_the_class=False)
:param wrapper_for_method: method_name=wrapper_function pairs.
:return: A class wrapper. That is, a decorator that takes a class and returns a decorated version of it
(or decaorates "in-place" if _return_a_copy_of_the_class=False
SEE ALSO:
* wrap_method_output: The function that is called for every method we wrap.
* transform_class_method_input_and_output: A wrap_class_methods that is specialized for input arg and output
transformation.
>>> from functools import wraps
>>> class A:
... def __init__(self, a=10):
... self.a = a
... def add(self, x):
... return self.a + x
... def multiply(self, x):
... return self.a * x
...
>>> a = A()
>>> a.add(2)
12
>>> a.multiply(2)
20
>>>
>>> def log_calls(func):
... name = func.__name__
... @wraps(func)
... def _func(self, *args, **kwargs):
... print("Calling {} with\\n args={}\\n kwargs={}".format(name, args, kwargs))
... return func(self, *args, **kwargs)
... return _func
...
>>> AA = wrap_class_methods(**{k: log_calls for k in ['add', 'multiply']})(A)
>>> a = AA()
>>> a.add(x=3)
Calling add with
args=()
kwargs={'x': 3}
13
>>> a.multiply(3)
Calling multiply with
args=(3,)
kwargs={}
30
"""
def class_wrapper(cls):
if _return_a_copy_of_the_class:
_cls = type('_' + cls.__name__, cls.__bases__, dict(cls.__dict__))
# class _cls(cls):
# pass
else:
_cls = cls
for method, wrapper in wrapper_for_method.items():
if hasattr(_cls, method):
setattr(_cls, method, wrapper(getattr(_cls, method)))
elif _raise_error_if_non_existent_method:
raise ValueError(
f"{getattr(_cls, '__name__', str(cls))} has no '{method}' method!"
)
return _cls
return class_wrapper | 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áro do arquivo sons.json
dados_json = json.load(f)
# Retorna os dados
return dados_json
# Caso o arquivo não seja encontrado
except FileNotFoundError as e:
print('[ERRO] Util: le_arquivo_json(): Arquivo não encontrado:', e)
return None | 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 enumerate(f):
for j, y in enumerate(f):
if i != j and x == y:
return False
return True | 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`` attribute of an ``Array``
Returns
-------
True if chunkset passes, else False
Examples
--------
>>> import dask.array as da
>>> arr = da.zeros(10, chunks=(5, ))
>>> _check_regular_chunks(arr.chunks)
True
>>> arr = da.zeros(10, chunks=((3, 3, 3, 1), ))
>>> _check_regular_chunks(arr.chunks)
True
>>> arr = da.zeros(10, chunks=((3, 1, 3, 3), ))
>>> _check_regular_chunks(arr.chunks)
False
"""
for chunks in chunkset:
if len(chunks) == 1:
continue
if len(set(chunks[:-1])) > 1:
return False
if chunks[-1] > chunks[0]:
return False
return True | 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
ruleset
>>> tamper('SELECT FIELD FROM%20TABLE')
'%2553%2545%254C%2545%2543%2554%2520%2546%2549%2545%254C%2544%2520%2546%2552%254F%254D%2520%2554%2541%2542%254C%2545'
"""
retVal = payload
if payload:
retVal = ""
i = 0
while i < len(payload):
if payload[i] == '%' and (i < len(payload) - 2) and payload[i + 1:i + 2] in string.hexdigits and payload[i + 2:i + 3] in string.hexdigits:
retVal += '%%25%s' % payload[i + 1:i + 3]
i += 3
else:
retVal += '%%25%.2X' % ord(payload[i])
i += 1
return retVal | 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)
except TypeError:
return [] | 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 to render
limit: integer (optional)
The maximum number of record to show in the table, defaults to 5
Returns:
string (HTML table)
"""
def _to_html_table(data, columns):
yield '<table class="table table-sm">'
for counter, record in enumerate(data):
if counter == 0:
yield '<thead class="thead-light"><tr>'
for column in columns:
yield "<th>" + column + "<th>\n"
yield "</tr></thead><tbody>"
if (counter % 2) == 0:
yield '<tr style="background-color:#F4F4F4">'
else:
yield "<tr>"
for column in columns:
yield "<td>" + str(record.get(column)) + "<td>\n"
yield "</tr>"
yield "</tbody></table>"
rows = []
columns = [] # type:ignore
for i, row in enumerate(dictset):
rows.append(row)
columns = columns + list(row.keys())
if (i + 1) == limit:
break
columns = set(columns) # type:ignore
footer = ""
if isinstance(dictset, types.GeneratorType):
footer = f"\n<p>top {limit} rows x {len(columns)} columns</p>"
footer += "\nNOTE: the displayed records have been spent"
if isinstance(dictset, list):
footer = f"\n<p>{len(dictset)} rows x {len(columns)} columns</p>"
return "".join(_to_html_table(rows, columns)) + footer | 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 None)
data['colour'] = colour.lower().capitalize()
url = server + '/inform/{id}/{player}'.format(id=id, player=requester)
r = requests.post('http://' + url, data=data)
return r.text | 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, end as the first
3 columns
:return: the number of overlapping bases
"""
if frst[0] != scnd[0]:
return 0
rstart = max(frst[1], scnd[1])
rend = min(frst[2], scnd[2])
if rend < rstart:
return 0
return rend - rstart | 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
arguments
"""
parser.add_argument('--max_len', default= 512, type=int)
parser.add_argument('--data_dir', default="./../../temp/data/", type=str)
parser.add_argument('--in_dir', default="parapremise",type=str)
parser.add_argument('--out_dir',default="../processed/parapremise",type=str)
parser.add_argument('--single_sentence', default=0,type=int)
parser.add_argument('--splits',default=["train","dev","test_alpha1","test_alpha2","test_alpha3"], action='store', type=str, nargs='*')
parser.add_argument('--tokenizer_type',default="roberta-base", type=str, help='Value should be from the HuggingFace Transformers model classes - https://huggingface.co/transformers/pretrained_models.html')
return parser | 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_url)
return url | 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 -- hash to match
2, str -- negate ignore path to match
3, str -- ignore path to match
"""
_line = line.strip()
# Deal with file name end with ` `
line = (
_line + " " if _line.endswith("\\") and (
line.endswith(" \r\n") or line.endswith("\n")
) else _line
)
line = line.replace("\\ ", " ")
# Deal with `**` in folder path
line = line.replace("**", "*")
if line.endswith("/"):
line += "*"
if line == "":
# A blank line matches no files
return 0, None
elif line.startswith("#"):
# A line starting with `#` serves as a comment
return 0, None
elif line.startswith("\\#"):
# A line starting with `\#` serves as a pattern for hash
return 1, line.split("#")[-1].strip()
else:
if line.startswith("!"):
# A line starting with `!` negates the pattern
re_type = 2
line = line[1:]
else:
re_type = 3
# Deal with escape string
line = line.replace("\\", "")
if line.startswith("./"):
# Dealing with line start with `./`, just remove the head
return re_type, fnmatch.translate(line[2:])
else:
return re_type, fnmatch.translate(line) | 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_list_stripped = list(map(str.strip, urls_list))
return urls_list_stripped | 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) as in_file:
return yaml.load(in_file, Loader=yaml.FullLoader) | 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: {result.count('computer')}승")
if result.count('player') >= 2:
return "player"
elif result.count('computer') >= 2:
return "computer"
else:
None | 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=marker
)
full_command = "\n".join([header, cmd, footer])
return full_command | 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.