content stringlengths 42 6.51k |
|---|
def has_duplicate_values(tmp_list):
"""
Checks to see if a given list has any duplicate value.
:returns: False if tmp_list has no duplicate values.
:returns: True if tmp_list has duplicate values.
"""
set_of_elements = set()
for elem in tmp_list:
if elem in set_of_elements:
... |
def encode_text(text):
"""Encode data to help prevent XSS attacks from text in article"""
#Most efficient way is to chain these together ( https://stackoverflow.com/questions/3411771/best-way-to-replace-multiple-characters-in-a-string )
text = text.replace('&','&').replace('<','<').replace('>','>').r... |
def ComputePrecisionAndRecall(events, interpolate = False):
"""
Given a sorted list of events, compute teh Precision and Recall of each
of the events.
Events are tuples (tp, fp, fn) of float numbers in the range [0, 1], which
indicate whether the given event is a hit (or true positive), a false
... |
def extract_env_version(release_version):
"""Returns environment version based on release version.
A release version consists of 'OSt' and 'MOS' versions: '2014.1.1-5.0.2'
so we need to extract 'MOS' version and returns it as result.
.. todo:: [ikalnitsky] think about introducing a special field in re... |
def ts_fromdebris_func(h, a, b, c):
""" estimate surface temperature from debris thickness (h is debris thickness, a and k are coefficients)
Hill Equation"""
return a * h**c / (b**c + h**c) |
def inverse_mod(k, p):
"""Returns the inverse of k modulo p.
This function returns the only integer x such that (x * k) % p == 1.
k must be non-zero and p must be a prime.
"""
if k == 0:
raise ZeroDivisionError("division by zero")
if k < 0:
# k ** -1 = p - (-k) ** -1 (mod p)
... |
def is_instance_or_subclass(val, class_):
"""Return True if ``val`` is either a subclass or instance of ``class_``."""
try:
return issubclass(val, class_)
except TypeError:
return isinstance(val, class_) |
def l2_loss(y_true, y_pred):
"""Implements L2 loss.
y_true and y_pred are typically: [N, 4], but could be any shape.
"""
loss = (y_true - y_pred) ** 2
return loss |
def get_value(map, key):
"""Returns the value part from the dict, ignoring shorthand variants.
"""
if map[key].__class__ == "".__class__:
return map[key]
else:
return map[key][0] |
def const(f, *args, **kwargs):
"""
Decorator to maintain constness of parameters.
This should be used on any function that takes ndarrays as parameters.
This helps protect against potential subtle bugs caused by the pass by
reference nature of python arguments.
``copy`` is assumed to a shallow... |
def read_img_string(img_str):
"""
:param img_str: a string describing an image, like '4_3_3'
:return: integer array of this list. e.g: [4,3,3]
"""
img_array = img_str.split('_')
img_array = list(map(int, img_array))
return img_array |
def parse_slack_output(slack_client, slack_rtm_output, config, bot_id):
"""
The Slack Real Time Messaging API is an events firehose.
this parsing function returns None unless a message is
directed at the Bot, based on its ID.
"""
at_bot = "<@{0}>".format(bot_id)
output_list = sl... |
def L1(v, dfs_data):
"""The L1 lowpoint of the node."""
return dfs_data['lowpoint_1_lookup'][v] |
def parse_byte_size_string(string):
"""
Attempts to guess the string format based on default symbols
set and return the corresponding bytes as an integer.
When unable to recognize the format ValueError is raised.
>>> parse_byte_size_string('1 KB')
1024
>>> parse_byte_size_string('2.2 ... |
def get_tracked_zone(name, zones):
"""
What is the tracked zone for the provided hostname?
"""
for zone in zones:
if name.endswith("." + zone) or name == zone:
return zone
return None |
def remove_links_with_no_month_reference(all_links: list) -> list:
"""
function to remove all links that don't have an association with a month. All entries with None or '\xa0' instead
of month name.
args:
all_links: list -> List of tuples where the first index is the link, second index is the... |
def MangleModuleIfNeeded(module_id):
"""Convert module ID to the format breakpad uses.
See TracingSamplerProfiler::MangleModuleIDIfNeeded().
Warning: this is only relevant in Android, Linux and CrOS.
Linux ELF module IDs are 160bit integers, which we need to mangle
down to 128bit integers to match the id tha... |
def isInCategory(category, categoryData):
"""Check if the event enters category X, given the tuple computed by eventCategory."""
if category==0:
return (categoryData[0]>0 or categoryData[1]>0) and categoryData[2]>=4
elif category==1:
return isInCategory(0,categoryData) and (categoryData[3]>15 or categoryD... |
def get_export_from_line(line):
"""Get export name from import statements"""
if not line.startswith("export * from"):
return None
start = line.find("\"")
if start > 0:
return line[start+1:-3] # remove ";\n
return None |
def seconds_to_string(seconds):
"""
Convert run seconds into string representation
:param seconds: Number of seconds
:type seconds: int
:return: String in the format of 'Xd Xh Xm Xs' based on the provided elapsed time
:rtype: string
"""
day = int(seconds // (24 * 3600))
time_mod = se... |
def bytes_(s, encoding='utf-8', errors='strict'):
"""
If ``s`` is an instance of ``text_type``, return
``s.encode(encoding, errors)``, otherwise return ``s``
"""
if not isinstance(s, bytes) and s is not None:
s = s.encode(encoding, errors)
return s |
def edges_path_to(edge_to, src, target):
"""Recover path from src to target."""
if not target in edge_to:
raise ValueError('{} is unreachable from {}'.format(target, src))
path = []
v = target
while v != src:
path.append(v)
v = edge_to[v][0]
# last one to push is the so... |
def get_nterm_mod(seq, mod):
"""Check for a given nterminal mod.
If the sequences contains the mod a 1 is returned, else 0.
"""
if seq.startswith(mod):
return 1
else:
return 0 |
def filter_coefficients(position):
"""
15 quarter-pixel interpolation filters, with coefficients taken directly from VVC implementation
:param position: 1 indicates (0,4) fractional shift, ..., 4 is (4,0), ... 9 is (8,4), ...
:return: 8 filter coefficients for the specified fractional shift
"""
... |
def transformArrYXToXY(arrYX):
""" transformArrYXToXY(arrYX)
Getting a array of positions invert order.
Parameters
----------
arrYX : Array
List of positions to invert
Returns
-------
List
Returns list with all coordinates inverted inside
a tuple.
"""
... |
def check_5_characters_functions(strings):
"""
This function checks to see if the user's input has more than, or equal to 5 characters, or not.
:param strings: This variable "strings" saves the user's input
:return: True if the user's input has more than, or equal to 5 characters
return False if the... |
def integrate_curve(curve_points):
"""
Integrates the curve using the trapezoid method.
:param curve_points: the list of point of the curve
:type curve_points: List[Tuple[float, float]]
:return: the integration of the curve
:rtype: float
"""
area = 0.0
for i in range(1, len(curve_po... |
def prefix_sum_n_mean(A, n_values):
"""
Calculates the average of the n_values ahead of each position of list A
:param A: list
:param n_means: number of values to use for each average
:return: list of averages
"""
n = len(A) - (n_values - 1)
P = [10000] * n
for k in range(n):
... |
def create_pinhole_camera(height, width):
"""
Creates a pinhole camera according to height and width, assuming the principal point is in the center of the image
"""
cx = (width - 1) / 2
cy = (height - 1) / 2
f = max(cx, cy)
return f, cx, cy |
def dotted_prefixes(dotted_name, reverse=False):
"""
Return the prefixes of a dotted name.
>>> dotted_prefixes("aa.bb.cc")
['aa', 'aa.bb', 'aa.bb.cc']
>>> dotted_prefixes("aa.bb.cc", reverse=True)
['aa.bb.cc', 'aa.bb', 'aa']
:type dotted_name:
``str``
:param reverse:
... |
def SegmentsIntersect(l1, r1, l2, r2):
"""Returns true if [l1, r1) intersects with [l2, r2).
Args:
l1: int. Left border of the first segment.
r1: int. Right border (exclusive) of the second segment.
l2: int. Left border of the second segment.
r2: int. Right border (exclusive) of the second segment.... |
def hex_to_number(hex_string):
"""
Return a int representation of the encoding code.
:param hex_string: Hex string to convert
:type hex_string: str
:return: The hex string as a number
:type: int
>>> hex_to_number('00F00D') == 0xF00D
True
"""
return int(hex_string, 16) |
def power(x, y):
"""Power with stricter evaluation rules"""
if x == 0:
if y == 0: raise ValueError("0^0")
elif x < 0:
if y != int(y): raise ValueError("non-integer power of negative")
return x ** y |
def count(func, lst):
"""
Counts the number of times func(x) is True for x in list 'lst'
See also:
counteq(a, lst) count items equal to a
countneq(a, lst) count items not equal to a
countle(a, lst) count items less than or equal to a
countlt(a, lst) count items less t... |
def mergeRegisters(*qregs):
"""
Returns a single register containing all the qubits (or cbits) from multiple registers
"""
bigReg = []
for qreg in qregs:
bigReg += [q for q in qreg]
return bigReg |
def update_dictionary(a_dictionary, key, value):
"""
updates a dictionary and returns a new copy
original is affected
"""
a_dictionary.update({key: value})
return (a_dictionary.copy()) |
def mysqrt(x, steps=10):
"""Calculate sqrt by Newton's method."""
# Initial guess (guess number 1 of <steps>)
guess = x/2
for i in range(steps-1):
# Next guess given by Newton's formula
guess = (guess + x/guess) / 2
# Result after <steps> iteration
mysqrt = guess
return... |
def get_output(values, puzzle_input):
"""returns the value for output
"""
return puzzle_input[values[0]] |
def pedigree_to_qc_pedigree(samples_pedigree):
"""
extract pedigree for qc for every family member
- input samples accession list
- qc pedigree
"""
qc_pedigree = []
# get samples
for sample in samples_pedigree:
member_qc_pedigree = {
'gender': samp... |
def PNT2Tidal_Pv14(XA,chiA=0,chiB=0,AqmA=0,AqmB=0,alpha2PNT=0):
""" TaylorT2 2PN Quadrupolar Tidal Coefficient, v^14 Phasing Term.
XA = mass fraction of object
chiA = aligned spin-orbit component of object
chiB = aligned spin-orbit component of companion object
AqmA = dimensionless spin-induced quadrupo... |
def compute_tally(vec):
"""
Here vec is an iterable of hashable elements.
Return dict giving tally of elements.
"""
tally = {}
for x in vec:
tally[x] = tally.get(x, 0) + 1
return tally |
def scale(mylist, zero_vals=None, one_vals=None):
""" Scales a 2D list by attribute from 0 to 1
Args:
mylist (list of list of obj): The lists to scale
zero_vals (list of numbers): The override of the minimum values to scale to zero with.
one_vals (list of numbers): See zero_vals. Bo... |
def unqualify(name: str) -> str:
"""
Return an unqualified name given a qualified module/package ``name``.
Args:
name: The module name to unqualify.
Returns:
The unqualified module name.
"""
return name.rsplit(".", maxsplit=1)[-1] |
def sort_all(batch, lens):
""" Sort all fields by descending order of lens, and return the original indices. """
if batch == [[]]:
return [[]], []
unsorted_all = [lens] + [range(len(lens))] + list(batch)
sorted_all = [list(t) for t in zip(*sorted(zip(*unsorted_all), reverse=True))]
return so... |
def print_color(text):
"""
Print text in yellow :)
:param text: String to be colored
:return: Colored text
"""
return '\033[0;33m' + text + '\033[0m' |
def rosenbrock(args):
"""
Name: Rosenbrock
Global minimum: f(1,...,1) = 0.0
Search domain: -inf <= xi <= inf, 1 <= i <= n
"""
rosen = 0
for i in range(len(args ) -1):
rosen += 10.0 *((args[i]**2 ) -args[ i +1] )** 2 +( 1 -args[i] )**2
return rosen |
def stripline(line, stripboth=False):
"""
Default line transformer.
Returns the supplied line after calling rstrip
:param line: string representing a file line
:param stripboth: Optional boolean flag indicating both l and r strip should be applied
:return: The trimmed line
"""
if stripbo... |
def get_wildcard_mask(mask):
""" convert mask length to ip address wildcard mask, i.e. 24 to 0.0.0.255 """
mask_int = ["255"] * 4
value = int(mask)
if value > 32:
return None
if value < 8:
mask_int[0] = str(int(~(0xFF << (8 - value % 8)) & 0xFF))
if value >= 8:
mask_int... |
def svg_color_tuple(rgb_floats):
"""
Turn an rgb tuple (0-255, 0-255, 0-255) into an svg color definition.
:param rgb_floats: (0-255, 0-255, 0-255)
:return: "rgb(128,128,128)"
"""
r, g, b = (round(x) for x in rgb_floats)
return f"rgb({r},{g},{b})" |
def sum(val):
"""
>>> sum((1.0, 2.0))
3.0
>>> sum((2.0*meter, 3.0*meter))
Quantity(value=5.0, unit=meter)
>>> sum((2.0*meter, 30.0*centimeter))
Quantity(value=2.3, unit=meter)
"""
if len(val) == 0:
return 0
result = val[0]
for i in range(1, len(val)):
result +... |
def unique_subjects_sessions_to_subjects_sessions(
unique_subject_list, per_subject_session_list
):
"""Do reverse operation of get_unique_subjects function.
Example:
>>> from clinicaml.utils.participant import unique_subjects_sessions_to_subjects_sessions
>>> unique_subjects_sessions_to_sub... |
def gcd(*args):
"""Calculate the greatest common divisor (GCD) of the arguments."""
L = len(args)
if L == 0: return 0
if L == 1: return args[0]
if L == 2:
a, b = args
while b:
a, b = b, a % b
return a
return gcd(gcd(args[0], args[1]), *args[2:]) |
def sameThreeCharStartPredicate(field):
"""return first three characters"""
if len(field) < 3:
return ()
return (field[:3], ) |
def balance_tasks_among_levels(max_workers: int, tasks: dict, levels: dict):
"""Rearrange tasks across levels to optimize execution regarding the maximum workers.
The constraint between tasks of same level (no relationship) must be conserved
:param tasks:
:param max_workers:
:param levels:
:retu... |
def is_valid_bio(entity):
""" check if the entity sequence is valid,
'I-' should not at the beginning, and should never follow 'O' neither.
"""
for j, e in enumerate(entity):
if e.startswith('I-') and ( j == 0 or e[2:] != entity[j - 1][2:]):
print(j, entity[j-1], e,)
re... |
def sat_to_btc(amount_sat: float) -> float:
"""
The value is given in satoshi.
"""
smallest_sat = 1
largest_sat = 99999999
#
if not (smallest_sat <= amount_sat <= largest_sat):
raise ValueError
# else
btc = amount_sat * 1e-8
return btc |
def go_next(i, z_result, s):
"""
Check if we have to move forward to the next characters or not
"""
return i + z_result[i] < len(s) and s[z_result[i]] == s[i + z_result[i]] |
def handle_port_probe_action(action):
"""
Handle the PORT_PROBE action type from the
guard duty finding.
:param data:
:return:
"""
portProbeAction = action.get("portProbeAction")
print("Port Probe action: {}".format(portProbeAction))
portProbeDetails = portProbeAction.get("portPro... |
def bring_contact_bonus_list(pb_client, obj_pb_ids, arm_pb_id, table_pb_id):
""" For some bring goals, may be useful to also satisfy an object touching table and
not touching arm condition. """
correct_contacts = []
for o in obj_pb_ids:
o2ee_contact = len(pb_client.getContactPoints(o, arm_pb_id)... |
def isPrime(n: int)->bool:
"""
Give an Integer 'n'. Check if 'n' is Prime or Not
:param n:
:return: bool - True or False
We will use Naive approach.
Check Divisibility of n with all numbers smaller than n.
If any one of the smaller number is able to divide n, then n is instantly identified ... |
def calldict2txt(inputDict):
"""
Convert all keys in dict to a string txt, txt file is:
chr1 123 123 . . +
:param inputDict:
:return:
"""
text = ""
for key in inputDict:
text += f'{key[0]}\t{key[1]}\t{key[1]}\t.\t.\t{key[2]}\n'
return text |
def calculate_colorscale(n_values):
"""
Split the colorscale into n_values + 1 values. The first is black for
points representing pairs of variables not in the same cluster.
:param n_values:
:return:
"""
# First 2 entries define a black colour for the "none" category
colorscale = [[0, "r... |
def kelvin_to_fahrenheit(kelvin: float, ndigits: int = 2) -> float:
"""
Convert a given value from Kelvin to Fahrenheit and round it to 2 decimal places.
Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin
Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit
"""
return round((kelv... |
def wordFinder(string):
"""Takes a string and returns the number of times a word is repeated"""
#begin init of function variables
stringLower=string.lower()
stringList=list(stringLower)
stringList.insert(0,' ')
stringList.append(' ')
spaceList=[]
wordList=[]
charList=[]
repeat=0
... |
def getMessageIfFalse(condition, msg):
"""If condition is False, then returns msg, otherwise returns empty string.
:param bool condition: Condition paramater.
:param str msg: Message returned if condition is False.
:return: msg or empty string.
:rtype: str
>>> getMessageIfFalse(False, "Condit... |
def all_validator(value):
"""No validation for value insertion. Returns True always. """
# pylint: disable=unused-argument
return True |
def parse_short_time_label(label):
"""
Provides the number of seconds corresponding to the formatting used for the
cputime and etime fields of ps:
[[dd-]hh:]mm:ss or mm:ss.ss
::
>>> parse_short_time_label('01:51')
111
>>> parse_short_time_label('6-07:08:20')
544100
:param str label: time... |
def generate_triangle(n, left="/", right="\\"):
"""This function generates a list of strings which
when printed resembles a triangle
"""
if type(n) is not int:
raise TypeError("Input an integer only")
result = []
for i in range(1, n+1):
line = ' '*(n-i) + left*i + right*... |
def parseCheckOutput(install):
"""Parses the preparsed solver output with respect to fakevariables"""
retstr = '### Keep the following dependencies:\n'
inconStr = ''
consistent = True
for item in install:
if item[1] != '0.0-fake':
retstr += item[0]+' version '+item[1]+'\n'
... |
def pointsToCoordinatesAndProperties(points):
"""Converts points in various formats to a (coordinates, properties) tuple
Arguments:
points (array or tuple): point data to be converted to (coordinates, properties) tuple
Returns:
tuple: (coordinates, properties) tuple
No... |
def _get_components(env, *args):
"""Get the objects of the given component(s)
:param env: the SCons environment
:param args: the names of the components
"""
variant_dir = env['COMPONENTS_VARIANT_DIR']
objects = set()
for name in args:
[objects.add(obj) for obj in env['CO... |
def find(array, key): # O(N)
"""
Find an element in an array of tuples
>>> find([('human', 42), ('cat', 22)], 'cat')
1
>>> find([('human', 42), ('cat', 22)], 'dog')
-1
"""
length = len(array) # O(1... |
def InvertNaiveSConsQuoting(s):
"""SCons tries to "help" with quoting by naively putting double-quotes around
command-line arguments containing space or tab, which is broken for all
but trivial cases, so we undo it. (See quote_spaces() in Subst.py)"""
if ' ' in s or '\t' in s:
# Then SCons will p... |
def setup_dict(data, required=None, defaults=None):
"""Setup and validate dict scenario_base. on mandatory keys and default data.
This function reduces code that constructs dict objects
with specific schema (e.g. for API data).
:param data: dict, input data
:param required: list, mandatory keys to... |
def hex_to_rgb(hex_string):
"""
Convert a hexadecimal string with leading hash into a three item list of values between [0, 1].
E.g. #00ff00 --> [0, 1, 0]
:return: The value of the hexadecimal string as a three element list with values in the range [0. 1].
"""
hex_string = hex_string.lstrip(... |
def _import(name):
"""Return module from a package.
These two are equivalent:
> from package import module as bar
> bar = _import('package.module')
"""
mod = __import__(name)
components = name.split('.')
for comp in components[1:]:
try:
mod = getattr(mo... |
def mapfmt_str(fmt: str, size: int) -> str:
"""Same as mapfmt, but works on strings instead of bytes."""
if size == 4:
return fmt
return fmt.replace('i', 'q').replace('f', 'd') |
def add_to_list(items,new_item):
""" Add the value to the list/tuple. If the item is not a list, create a new
list from the item and the value
Args:
items (list, string or tuple): Single or multiple items
new_item (string): The new value
Returns:
(list): A lis... |
def escape_jsonpointer_part(part: str) -> str:
"""convert path-part according to the json-pointer standard"""
return str(part).replace("~", "~0").replace("/", "~1") |
def htTitle(name):
"""Format a `name` as a section title."""
return f'<h2 class="section">{name}</h2>' |
def prune_pout(pout, in_names):
"""Removes entries marked for deletion in a BigMultiPipe.pipeline() output
Parameters
----------
pout : list of tuples (str or ``None``, dict)
Output of a :meth:`BigMultiPipe.pipeline()
<bigmultipipe.BigMultiPipe.pipeline>` run. The `str` are
pip... |
def _AddDataTableSeries(channel_data, output_data):
"""Adds series to the DataTable inputs.
Args:
channel_data: A dictionary of channel names to their data. Each value in
the dictionary has the same sampling frequency and the same time slice.
output_data: Current graph data for DataTable API.
Return... |
def reverse_strand(strand):
"""Given a strand
:return the opposite strand: if is specify
:return None: if strand is not defined
"""
dict_inverted = dict([('+', '-'), ('-', '+'), (None, None)])
return dict_inverted[strand] |
def fix_path(path_in: str, path_type='dir') -> str:
"""
Fix path, including slashes.
:param path_in: Path to be fixed.
:param path_type: 'file' or 'dir'
:return: Path with forward slashes.
"""
path = str(path_in).replace('\\', '/')
if not path.endswith("/") and path_type != "file":
... |
def dict_to_formula(material_dict):
"""Input a material in element dict form
Returns formula of element (arbitrary order)
"""
formula = ""
for element, val in material_dict.items():
if val != 0:
formula = formula + f'{element}{val}'
return formula |
def results_to_dict(results):
"""convert result arrays into dict used by json files"""
# video ids and allocate the dict
vidxs = sorted(list(set(results['video-id'])))
results_dict = {}
for vidx in vidxs:
results_dict[vidx] = []
# fill in the dict
for vidx, start, end, label, score ... |
def _testRGBW(R, G, B, W):
""" RGBW coherence color test
:param R: red value (0;255)
:param G: green value (0;255)
:param B: blue value (0;255)
:param W: white value (0;255)
:return: True if coherent / False otherwise """
try:
if (R != 0) and (G != 0) and (B != 0):
raise ... |
def factorial(n):
""" defined as n * n-1"""
if n <= 1:
return 1
else:
return n * factorial(n-1) |
def get_magic(name):
"""Get a magic function by name or None if not exists."""
return globals().get("do_" + name) |
def relative_angle(x, y):
"""Assuming y is clockwise from x, increment y by 360 until it's not less
than x.
Parameters:
x (float): start angle in degrees.
y (float): end angle in degrees.
Returns:
float: y shifted such that it represents the same angle but is greater
th... |
def get_user_host(user_host):
""" Returns a tuple (user, host) from the user_host string. """
if "@" in user_host:
return tuple(user_host.split("@"))
return None, user_host |
def check_suffix(x, suffixes):
"""check whether string x ends with one of the suffixes in suffixes"""
for suffix in suffixes:
if x.endswith(suffix):
return True
return False |
def minusX10(a,b):
"""subtracts b from a, multiplies by 10 and retuns the answer"""
c = (a-b)*10
return c |
def exp_gradients(x, y, a, mu, eta):
"""KL loss gradients of neurons with sigmoid activation
(~ Exponential(lambda=1/mu))."""
delta_b = eta * (1 - (2 + (1 / mu)) * y + (y**2) / mu)
delta_a = (eta / a) + delta_b * x
return delta_a, delta_b |
def sanitize(val):
"""Escape latex specical characters in string values."""
if isinstance(val, str):
val = val.replace('_', r'\_').replace('%', r'\%')
return val |
def get_accuracy(y_pred, y_test):
"""
Get the prediction accuracy, which is number of correct predictions / number of all predictions.
:param y_pred:
:param y_test:
:return: prediction accuracy
"""
good = 0
for i, pred in enumerate(y_pred):
if pred == y_test[i]:
good ... |
def process_single_service_request_definition_output(res) -> dict:
"""
Process single service request definition response object for output
:param res: service request definition object
:return: processed object for output
"""
service_request_definition_name = ''
for field in res.get('Fields... |
def decode_labelme_shape(encoded_shape):
"""
Decode the cnn json shape (usually encoded from labelme format)
Return a list of points that are used in labelme
"""
assert isinstance(encoded_shape, str)
points = encoded_shape.split(',')
shape = list()
for point in points:
x, y = poi... |
def new_network(address, ssid, frequency, encrypted, encryption_type, mode, bit_rates, channel):
"""{ address, ssid, frequency, encrypted, encryption_type, mode, bit_rates, channel }"""
network = {
'address' : address
,'ssid' : ssid
,'frequency' : frequency
,'encrypted' : encrypted
,'encryption_type': encr... |
def single_letter_count(word, letter):
"""How many times does letter appear in word (case-insensitively)?"""
return word.lower().count(letter.lower()) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.