content stringlengths 42 6.51k |
|---|
def date_range_frequency(filename):# {{{
"""Get the frequency of date range"""
if filename.find('day') != -1:
freq = 'D'
elif filename.find('week') != -1:
freq = 'W-MON'
elif filename.find('month') != -1:
freq = 'MS'
elif filename.find('year') != -1:
freq = 'AS-JAN'
... |
def page_count(n, p):
"""Hackerrank Problem: https://www.hackerrank.com/challenges/drawing-book/problem
Brie's Drawing teacher asks her class to open their books to a page number. Brie can either start turning pages from
the front of the book or from the back of the book. She always turns pages one at a ti... |
def concatenateDates(fullDates, yearMonthDates, years):
"""This function combines several dates in a human readable fashion.
>>> concatenateDates(set(['1988-04-25']), set(['1988-05']), set())
'1988-04-25 or 1988-05'
>>> concatenateDates(set(['1988-04-25', '1988-04-24']), set(['1988-05']), set())
'1988-04-24... |
def parse_kv_string_to_dict(kvs_string, inter_kv_sep, intra_kv_sep):
"""Parse a kv string to a dict. For example,
"key1:value1,key2:value2" => {key1: value1, key2: value2}
"""
kv_dict = {}
kv_pairs = kvs_string.split(inter_kv_sep)
for kv in kv_pairs:
key_and_value = kv.split(intra_kv_sep... |
def guess_cloudwatch_log_group(alarm_name):
"""
Guess the name of the CloudWatch log group most likely to contain
logs about the error.
"""
if alarm_name.startswith("loris-"):
return "platform/loris"
if alarm_name.startswith("catalogue-api-romulus"):
return "ecs/catalogue_api_gw... |
def multiply(intf, ints):
"""
overpython.multiply(intf, ints)
Multiply intf by ints. Raises ValueError if intf/ints is a string.
"""
try:
return float(intf) * float(ints)
except ValueError:
raise ValueError("%s/%s is not a number" % (intf, ints)) |
def RGBtoHSV(rgbcol):
""" Convert color data from RGB to HSV.
may be wrong some where (10Nov.2012)
"""
H=0; S=1.0; V=1.0
frgb=255; fhsv=60; eps=0.000001
R=rgbcol[0]/frgb; G=rgbcol[1]/frgb; B=rgbcol[2]/frgb
rgblst=[R,G,B]
maxrgb=max(rgblst); minrgb=min(rgblst); delta=maxrgb-minrgb... |
def last_n_lines(the_string, n_lines, truncation_message=None):
"""Returns the last n lines of the given string
Args:
the_string: str
n_lines: int
truncation_message: str, optional
Returns a string containing the last n lines of the_string
If truncation_message is provided, th... |
def remove_from_list(element,
iterable):
"""
Return list without given element from that list. Conversely to built-in
methods it is fruitful function.
Parameters
-------
element: object
Element to be removed from the list.
iterable: list, tuple, set
Iter... |
def wxyz_to_xyzw(arr):
"""
Convert quaternions from numpy to pyBullet.
"""
return [arr[1], arr[2], arr[3], arr[0]] |
def adjust_matrix(matrix):
"""
Given a matrix of size MxN, if an element is zero, set it's row and
column to zeros.
"""
zero_rows = {}
zero_columns = {}
# Get location of all the zeros.
for i, row in enumerate(matrix):
for j, num in enumerate(row):
if num is 0:
... |
def blend_lighten(cb: float, cs: float) -> float:
"""Blend mode 'lighten'."""
return max(cb, cs) |
def post(user, post_id):
"""User's post.
.. :quickref: User; Save user id
:param user: user login name
:param post_id: post unique id
:status 200: when user and post exists
:status 404: when user and post doesn't exist
"""
return str(post_id), 'by', user |
def is_int(text):
"""Tests if the specified string represents an integer number.
Args:
text(str): text to check
Returns:
: bool -- True if the text can be parsed to an int, False if not.
"""
try:
int(text)
return True
except ValueError:
return False |
def last_added_term_is_concatenation(query_list):
"""
Takes the under-construction query string and determines whether the
last added element is "and", "or", or "not"
"""
if len(query_list) <= 0:
return False
last_query_element = query_list[-1].lower()
return last_query_element in ('... |
def sdof_modal_peak(w, wn, zn, an, phi):
"""Return a modal peak generated from the given parameters.
Parameters
----------
w : ndarray
An array of omega (angular frequency) values.
wn : float
The resonant angular frequency.
zn : float
The damping factor.
an : float
... |
def bubbleSort(l):
"""
Needs to be implemented
"""
for i in range(1, len(l)-1):
for j in range(1, len(l)-i):
if l[j] > l[j+1]:
l[j], l[j+1] = l[j+1], l[j]
return l |
def merge_rec(left, right):
"""Merge sort merging function."""
left_index, right_index = 0, 0
result = []
while left_index < len(left) and right_index < len(right):
if left[left_index] < right[right_index]:
result.append(left[left_index])
left_index += 1
else:
... |
def dollars_to_cents(dollars):
"""
Convert dollars to cents.
:param dollars: Amount in dollars
:type dollars: float
:return: int
"""
return int(dollars * 100) |
def parse_bool(bool_arg):
"""
Parse a string representing a boolean.
:param bool_arg: The string to be parsed
:return: The corresponding boolean
"""
if bool_arg.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif bool_arg.lower() in ('no', 'false', 'f', 'n', '0'):
ret... |
def convert_to_bool(data):
"""
convert_to_bool converts input to bool type in python.
The following values are converted to True:
1. 'true'
2. 'yes'
3. '1'
4. 'y'
5. 1
The following values are converted to False:
1. 'false'
2. 'no'
3. '0'
4. 'n'
5. 0
:par... |
def _rounder(*args, dec=0):
""" Round each element of a list. """
# return [round(float(arg), dec) for arg in args]
return [round(float(a), dec) if abs(float(a)) < 10e3 else format(a, "5.1e") for a in args] |
def reverse_toss(choice):
""" Reverse the toss """
if choice == "bat":
choice_new = "field"
elif choice == "field":
choice_new = "bat"
else:
choice_new = choice
return choice_new |
def wrap_by_word(s, n):
"""
Returns a string where \n is inserted between every n words
:param s: string
:param n: integer, number of words
:return:
"""
a = s.split()
ret = ''
for i in range(0, len(a),... |
def count_smileys(arr):
"""
Given an array (arr) as an argument complete the function countSmileys that should return the total number of smiling faces.
Rules for a smiling face:
-Each smiley face must contain a valid pair of eyes. Eyes can be marked as : or ;
-A smiley face can have a nose but it d... |
def format_stackdriver(_, __, ed):
"""Stackdriver uses `message` and `severity` keys to display logs"""
ed["message"] = ed.pop("event")
ed["severity"] = ed.pop("level", "info").upper()
return ed |
def is_scope_type(node_type):
"""Judge whether the type is scope type."""
return node_type.endswith('scope') |
def __getRanks(dataColumn, descending=False):
"""
([List], Boolean) -> [List]
Determines the indexes(ranks) of data stored in the given list after getting sorted. Has an option to
make it a descending ranking.
"""
items = [item for item in dataColumn]
itemsSorted = sorted(items, reverse=... |
def getLemma(line):
"""
retreves the second word in a line in the coha corpus, or nothing if
given an empty line
"""
if line == "":
return ""
s = line.split("\t")
return s[1] |
def extract_keywords(group_nouns_list: list) -> list:
"""Extract keywords from the list of nouns from news groups.
:param group_nouns_list: list of results of extract_nouns(). [{keyword: count, },]
:return: list of extracted keywords. [str, ]
"""
# Merge nouns list
nouns_dict = dict()
nouns... |
def boom(iterable, target: int) -> str:
"""Find the target in iterable.
Return 'Boom!' if found.
Return f"there is no {target} in the list"
"""
for number in iterable:
if str(target) in str(number):
return "Boom!"
return f"there is no {target} in the list" |
def parse_namespace(publicDeclarations):
"""
from . import util
import json
namespace_json = util.parse_namespace(publicDeclarations["publicDeclarations"])
json.dump(namespace_json, open("c:/namespace.json",'w'))
"""
namespaces_dict = {}
for namespace in publicDeclarations:
name... |
def misencode(text):
"""Take a properly represented text, encode into win1250 and decode
back into latin2 (iso-8859-2) so it could be encoded back as such over the wire.
Has to be used when querying database for data stored by original application,
represented by MisencodedChar/TextField.
"""
r... |
def _drop_nones(d: dict) -> dict:
"""Recursively drop Nones in dict d and return a new dict"""
dd = {}
for k, v in d.items():
if isinstance(v, dict):
dd[k] = _drop_nones(v)
elif isinstance(v, (list, set, tuple)):
# note: Nones in lists are not dropped
dd[k... |
def capitalize(name):
"""Capitalize"""
return name[0].upper() + name[1:] |
def __transit(partition,rawnodepart):
"""Map partition of partition to the partition of original nodes
"""
res = dict()
for n,mn in rawnodepart.items():
res[n] = partition[mn]
return res |
def iterative_factorial(number : int) -> int :
"""
Computes factorial using loops
"""
factorial = 1
for i in range(1,number+1):
factorial *= i
return factorial |
def build_css_tag(url: str, defer: bool) -> str:
"""
Make ``link`` element from URL and donload-rule.
:param url: Target URL
:param defer: Flag to donload defer
"""
attrs = {
"href": url,
"rel": "stylesheet",
}
if defer:
attrs["rel"] = "preload"
attrs["as... |
def records_needed(pulse_length, samples_per_record):
"""Return records needed to store pulse_length samples"""
return 1 + (pulse_length - 1) // samples_per_record |
def p2p_worlds(worlds: list):
"""
Filters a list of worlds to a list only containing p2p worlds
"""
return [world for world in worlds if not world['f2p'] and not world['vip']] |
def _parse_string(value):
"""Coerce value into a string.
This is usually a no-op, but if value is a unicode string, it will be
encoded as UTF-8 before returning.
:param str value: Value to parse.
:returns: str
"""
if not isinstance(value, str):
return value.decode('utf-8')
retu... |
def _find_absmax(values):
"""find the absolute maximum values
Parameters
----------
values : List
A list of numerical values
"""
vmax = 0
for i in values:
if abs(i) > vmax:
vmax = abs(i)
return vmax |
def getFilteredMapName(name):
""" filters a map name to account for name changes, etc
so old configs still work """
# some legacy name fallbacks... can remove these eventually
if name == 'AlwaysLand' or name == 'Happy Land': name = u'Happy Thoughts'
if name == 'Hockey Arena': name = u'Hockey Stadium... |
def _to_iterable(maybe_iterable):
"""
_to_iterable(maybe_iterable)
Ensure the result is iterable. If the input is not iterable, it is wrapped into a tuple.
"""
if hasattr(maybe_iterable, "__iter__"):
surely_iterable = maybe_iterable
else:
surely_iterable = (maybe_iterable,)
... |
def _chao1_var_bias_corrected(s, d):
"""Calculates chao1 variance, bias-corrected.
`s` is the number of singletons and `d` is the number of doubletons.
From EstimateS manual, equation 6.
"""
return (s * (s - 1) / (2 * (d + 1)) + (s * (2 * s - 1) ** 2) /
(4 * (d + 1) ** 2) + (s ** 2 * ... |
def _is_used_without_argument(args):
"""Tests if a decorator invocation is without () or (args).
:param args: arguments
:return: True if it's an invocation without args
"""
return len(args) == 1 |
def parse_parameters(param_str):
"""
Parse parameter string return by librenderman into a dictionary keyed on parameter
index with values being the name / short descriptions for the parameter at that index.
:param param_str: A parameter decription string returned by librenderman
:type param_str: st... |
def CentralDiff(f, x, dx):
"""
Computes the 1st derivative of a function of a single variable f(x)
by central differencing:
\begin{equation}
f'(x) \approx \frac{f(x + dx) - f(x - dx)}{2 * dx}
\end{equation}
Input:
f: function
Function of a single variable that returns a... |
def is_unique(x):
"""[summary]
Args:
x ([type]): [description]
Returns:
[type]: [description]
"""
if len(x) == len(set(x)):
return True
else:
return False |
def simple(expr: str) -> int:
"""Evaluate a simple expression with no parens.
>>> simple("3 + 4 * 5")
35
>>> simple("1 + 2 * 3 + 4 * 5 + 6")
71
"""
# Split into bits then get out if we're done.
bits = expr.split()
if len(bits) == 1:
return int(expr)
# Evaluate the first... |
def force_to_float(a_potential_float):
"""Given arbitrary data, returns a float, always. If a_potential_float
cannot be made into a float, returns NaN (i.e. float("nan")) which is
a float that's not equal to anything.
"""
try:
the_float = float(a_potential_float)
except ValueError:
... |
def product(l):
"""Multiply together the elements of a list."""
prod = 1
for x in l:
prod *= x
return prod |
def _convert_ddb_list_to_list(conversion_list):
"""Return a python list without the DynamoDB datatypes.
Args:
conversion_list (Dict[str, Any]): A DynamoDB list which includes the
datatypes.
Returns:
List[Any]: Returns A sanitized list without the datatypes.
"""
ret_lis... |
def maxx(x, y):
"""Get the maximum of two items"""
if x >= y:
return x
else:
return y |
def sort_diffs(diff):
""" Sort diffs so we delete first and create later """
if diff['action'] == 'delete':
return 1
else:
return 2 |
def sort_tors_names(tors_names):
""" sort torsional names so that Dn where n is ascending order
"""
tors_names = list(tors_names)
tors_names.sort(key=lambda x: int(x.split('D')[1]))
return tors_names |
def object_at_end_of_path(path):
"""Attempt to return the Python object at the end of the dotted
path by repeated imports and attribute access.
"""
access_path = path.split(".")
module = None
for index in range(1, len(access_path)):
try:
# import top level module
... |
def missing(*module_names):
"""
Check if modules can be imported.
Return a string containing the missing modules.
"""
missing_modules = []
for module in module_names:
try:
exec("import " + module)
except:
missing_modules.append(module)
s = ", ".join(mi... |
def get_valid_pbc(inputpbc):
"""
Return a list of three booleans for the periodic boundary conditions,
in a valid format from a generic input.
Raise ValueError if the format is not valid.
"""
if isinstance(inputpbc,bool):
the_pbc = (inputpbc,inputpbc,inputpbc)
elif (hasattr(inputpbc... |
def format_args(args):
"""Formats the args with escaped " """
comma = "," if args else ""
return comma + ",".join(['\\\"' + a + '\\\"' for a in args]) |
def to_domain(pre, org):
"""Appends pre to org to create a domain name"""
return pre + "." + org["Domain"] |
def strip_quotes(s, qchar='"'):
"""Return string s with any enclosing quotes removed.
They are only removed if both are present."""
if len(s) > 1:
if s[0] == qchar and s[-1] == qchar:
s = s[1:-1]
return s |
def not_none(value):
"""
Returns value iff value is not none.
:param value: string
"""
if not value:
raise ValueError("Empty Value")
return value |
def UpperCamelCase(value):
"""Turns some_string or SOME_STRING into SomeString."""
split_value = value.lower().split('_')
return ''.join([part.capitalize() for part in split_value]) |
def diff(before, after):
"""
Return a dictionary with the difference between 'before' and 'after',
for items which are present in 'after' dictionary
"""
diff = dict((k,v) for (k,v) in after.items() if before.get(k, None) != v)
return diff |
def is_sent_by(author, authors):
"""Check if the email have been sent by one of the authors in the list.
if authors is empty true will be returned by default.
"""
if not authors:
return True
if author.lower() in [auth.lower() for auth in authors]:
return True
return False |
def get_children(nodeData, wsChildrenDic=dict(), firstChild=None, word2ballDic=None):
"""
get all children of a node
if firstChild is given, order the children list
:param nodeData:
:param wsChildrenDic:
:param firstChild:
:return:
"""
if word2ballDic:
chlst = [ch for ch in ... |
def peca_para_str(peca):
"""
peca_para_str: peca -> str
Devolve a cadeira de caracteres que representa o jogador dono da peca.
"""
return '[{}]'.format(peca['peca']) |
def parse_salt(trials: str, prob: str) -> tuple:
"""
Return the number of trials and the probaility from the user intput
arguments.
:param trials: the number of trials
:param prob: the probability of the event happeneing
:return: (trials, prob, is_percent) if the numbers are valid
"""
if... |
def _check_key_type(key, superclass):
"""
Check that scalar, list or slice is of a certain type.
This is only used in _get_column and _get_column_indices to check
if the `key` (column specification) is fully integer or fully string-like.
Parameters
----------
key : scalar, list, slice, arr... |
def min_ge(seq, val):
"""
Same as min_gt() except items equal to val are accepted as well.
>>> min_ge([1, 3, 6, 7], 6)
6
>>> min_ge([2, 3, 4, 8], 8)
8
"""
for v in seq:
if v >= val:
return v
return None |
def _diff_env(a, b):
"""Return difference of two environments dict"""
seta = set([(k, a[k]) for k in a])
setb = set([(k, b[k]) for k in b])
return (dict(seta - setb), dict(setb - seta)) |
def overflow(val):
""" Check Overflow for 32-bit values:
- result > 0x7FFFFFFF or result < -0x80000000
"""
return (val >> 32) != 0 |
def match_rules(txt, rules):
"""Find rule that first matches in txt"""
# Find first begin tag
first_begin_loc = 10e100
matching_rule = None
for rule in rules:
begin_tag, end_tag, func = rule
loc = txt.find(begin_tag)
if loc > -1 and loc < first_begin_loc:
first_be... |
def convert_rain_code(rain_code):
"""
Convert rain code into the following code
SKY Code: refer to weather station API document
0: No rain
1: Rainy
2: Rainy and Snowy
3: Snowy
Weather Code: Own implementation
1: sunny (not handled by this function)
2: ra... |
def get_content_dict(page, code):
"""
Generate the content dictionary used inside the template.
The key id the name label, and the value is get by the language code
used in that moment on the page.
"""
content = { x[0]["name"]: x[1]["value"].get(code, '') for x in zip(page['labels'], page['conte... |
def all_orig(f,c):
"""
Do all members of c satisfy f?
"""
for i in c:
if not f(i): return False
return True |
def make_description(comment):
"""Construct a single comment string from a fancy object."""
ret = '\n\n'.join(text for text in [comment.get('shortText'),
comment.get('text')]
if text)
return ret.strip() |
def save_variable(variable, path):
"""
:param variable:
:param path:
:return:
"""
import pickle
return pickle.dump(variable, open(path, 'wb')) |
def solution(arrays, k): # O(N^2)
"""
Given an array of arrays, find the intersecting values in k number of arrays
>>> solution([ \
[2, 5, 3, 2, 8, 1, 1, 2, 2], \
[7, 9, 5, 2, 4, 10, 10], \
[6, 7, 5, 5, 3, 7] \
], 2)
[2, 3, 5, 7]
... |
def expandtabs(s, tabstop=8, ignoring=None):
"""Expand tab characters `'\\\\t'` into spaces.
:param tabstop: number of space characters per tab
(defaults to the canonical 8)
:param ignoring: if not `None`, the expansion will be "smart" and
go from one tabsto... |
def read_db_properties_format(raw_db_properties):
"""Helper to read non-standard db properties format.
Note:
Spark/Hive doesn't provide a way to read separate key/values for database properties.
They provide a custom format like: ((key_a,value_a), (key_b,value_b))
Neither keys nor value... |
def extract_id(object_or_id):
"""Return an id given either an object with an id or an id."""
try:
id = object_or_id.id
except AttributeError:
id = object_or_id
return id |
def _normalize_validate(validate):
"""
Coerces the validate attribute on a Marshmallow field to a consistent type.
The validate attribute on a Marshmallow field can either be a single
Validator or a collection of Validators.
:param Validator|list[Validator] validate:
:rtype: list[Validator]
... |
def unsorted_unique(lista):
"""Removes duplicates from lista neglecting its initial ordering"""
return list(set(lista)) |
def namespaceDetect(title, site):
""" Detect the namespace of a given title
title - the page title
site - the wiki object the page is on
"""
bits = title.split(':', 1)
if len(bits) == 1 or bits[0] == '':
return 0
else:
nsprefix = bits[0].lower() # wp:Foo and caTEGory:Foo are normalized by MediaWiki
for ns ... |
def condition(cond, fn, x):
""" Only apply fn if condition is true """
if cond(x):
return fn(x)
else:
return x |
def last_name_first(n):
"""
Returns: copy of n but in the form 'last-name, first-name'
We assume that n is just two names (first and last). Middle names are
not supported.
Example:
last_name_first('Walker White') returns 'White, Walker'
Parameter n: the person's name
... |
def int_to_bits_indexes(n):
"""Return the list of bits indexes set to 1.
:param n: the int to convert
:type n: int
:return: a list of the indexes of bites sets to 1
:rtype: list
"""
L = []
i = 0
while n:
if n % 2:
L.append(i)
n //= 2
i += 1
... |
def part2(data):
"""Return x*y where (x, y) is the final submarine position.
The submarine starts at (0, 0).
Up/down decreases/increases the aim, which starts at 0.
The forward n command increases x by n and y by aim * n.
"""
x = y = aim = 0
for command in data.splitlines():
instruc... |
def intersects(p1, p2, p3, p4):
"""
Checks if the lines [p1, p2] and [p3, p4] intersect.
:param p1, p2: line
:param p3, p4: line
:return: lines intersect
"""
p0x, p0y = p1
p1x, p1y = p2
p2x, p2y = p3
p3x, p3y = p4
s10x = p1x - p0x
s10y = p1y - p0y
s32x = p3x - p2x
... |
def get_parse_dates(file):
"""Return a list of columns for which dates have to be parsed."""
parse_dates = [
'click_time',
'attributed_time'
]
if 'test' in file:
parse_dates.remove('attributed_time')
return parse_dates |
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 |
def is_two_pair(hand):
"""
This functions takes the hand (list) and returns true if the hand has two pair
"""
pair_count = 0
for card in hand:
if hand.count(card) is 2:
pair_count = pair_count + 1
if pair_count == 4:
return True |
def dpid_log(dpid):
"""Log a DP ID as hex/decimal."""
return 'DPID %u (0x%x)' % (dpid, dpid) |
def linear_interpolation(x, y, t):
"""
Function to do Linear interpolation with nearest neighbor extrapolation
Args:
x: Inlet and Outlet Temperature values
y: 0 and Heat value
t: Unique inlet and outlet temperatures
Returns:
Qstar: New array of Q Values
"""
# Set ... |
def ffs(c, s):
"""
first from second
goes through the first list, looking for items in the second, returns the first one
"""
for i in c:
if i in s: return i |
def format_timezone(offset, unnecessary_negative_timezone=False):
"""Format a timezone for Git serialization.
Args:
offset: Timezone offset as seconds difference to UTC
unnecessary_negative_timezone: Whether to use a minus sign for
UTC or positive timezones (-0000 and --700 rather than +000... |
def _get_incoming_value(incoming, key, default):
"""
Fetch value from incoming dict directly or check special nginx upload
created variants of this key.
"""
if '__' + key + '__is_composite' in incoming:
composite_keys = incoming['__' + key + '__keys'].split()
value = dict()
f... |
def serialize_forma_adquisicion(forma_adquisicion):
"""
# $ref: '#/components/schemas/formaAdquisicion'
"""
if forma_adquisicion:
return {
"clave": forma_adquisicion.codigo,
"valor": forma_adquisicion.forma_adquisicion
}
return {"clave":"RST","valor":"RIFA ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.