content stringlengths 42 6.51k |
|---|
def forward(facing, x_axis, y_axis):
"""Returns the X and Y axis after stepping forward"""
if facing == "N":
x_axis += 1
if facing == "S":
x_axis -= 1
if facing == "E":
y_axis += 1
if facing == "W":
y_axis -= 1
return x_axis, y_axis |
def _update_set(index, n_qubits):
"""The bits that need to be updated upon flipping the occupancy
of a mode."""
indices = set()
# For bit manipulation we need to count from 1 rather than 0
index += 1
# Ensure index is not a member of the set
index += index & -index
while index <= n_qub... |
def first_of(iterable, function):
"""
Return the first matching element of an iterable
This function is useful if you already know there is at most one matching
element.
"""
for item in iterable:
if function(item):
return item
return None |
def mean(values):
""" Returns the mean of values """
return sum(values) / len(values) |
def get_cities(src):
"""Return list of cities."""
cities = []
for city in src.get("city", []):
cities.append("%s, %s" % (city.get("name", ""), city.get("admin1_name", "")))
return cities |
def square_of_sum(n):
""" Calculate the square of the sum of the first n natural numbers """
return sum(i for i in range(1, n + 1)) ** 2 |
def dict_merge(d1, d2):
"""
Merge two dictionaries recursively. Merge the lists embedded within
dictionary at the same positions too (with caveats).
"""
result = dict(d2)
for k1, v1 in d1.items():
if k1 not in result:
result[k1] = v1
elif isinstance(v1, list):
... |
def wherechanged(arr):
"""
Returns the indices where a list changes values
Parameters
----------
arr : array or list
the array or list that may contain changes
Returns
------
where :
a list of indices that changes occur
"""
where = []
for i in range(len(arr)... |
def plusOneSum(arr):
"""returns the sum of the integers after adding 1 to each element"""
return sum(arr)+len(arr) |
def _next_power_two(x):
""" given a number, returns the next power of two
"""
x = int(x)
n = 1
while n < x:
n = n << 1
return n |
def test_exif_jfif(h, f):
"""JPEG data in JFIF or Exif format"""
if h[6:10] in (b'JFIF', b'Exif') or b'JFIF' in h[:23] or h[:2] == b'\xff\xd8':
return 'jpeg' |
def matches_rule(column, rule):
"""
Check if a list of numbers all match a particular rule.
:param column: list of numbers to check, this can be a column or a row of numbers
:param rule: a list with two tuples, each containing a low and high range number
:return: True if the list of numbers all matc... |
def avg_calc(times):
"""Calculate average of 5 for a given list of times
Args:
times (list): List of times, in seconds
Returns:
float or str: AO5 score or DNF
"""
dnf_counter = 0
conv_times = []
for i in times:
if i.upper() == "DNF":
dnf_counter += 1
continue
elif i == "":
dnf_counter += 1
... |
def _create_fake_operation(resource_link, verb, name):
"""Creates a fake operation resource dictionary for dry run.
Args:
resource_link (str): The full URL to the resource the operation would
have modified.
verb (str): The API method the operation would have been for.
name (... |
def to_float(s_val):
"""
Converts s to a float if possible.
@ In, s_val, any, value to convert
@ Out, s_val, float or any
"""
try:
return float(s_val)
except ValueError:
return s_val |
def get_item(dictionary, key_id):
"""Returns value in dictionary from the key_id.
Used when you want to get a value from a dictionary key using a variable
:param dictionary: dict
:param key_id: string
:return: value in the dictionary[key_id]
How to use:
{{ mydict|get_item:i... |
def urljoin(*parts: str) -> str:
"""Take as input an unpacked list of strings and joins them to form an URL"""
return "/".join(part.strip("/") for part in parts) |
def _call_string(*args, **kwargs):
"""Return format of args and kwargs as viewed when typed out"""
arg_strings = []
for arg in args:
arg_strings.append(repr(arg))
for key, arg in kwargs.items():
arg_strings.append(key+'='+repr(arg))
return "(%s)" % ', '.join(arg_strings) |
def collect(spotify, results, page_operation=None):
"""
:param spotify: Spotify
:param results: API response as Dictionary
:param page_operation: Function that has items from API response as parameter
:return:
"""
collection = []
if page_operation:
page_operation(results['items']... |
def before_send(event, hint):
"""Don't log django.DisallowedHost errors in Sentry."""
if "log_record" in hint:
if hint["log_record"].name == "django.security.DisallowedHost":
return None
return event |
def kalkulasi_kecepatan_akhir(
kecepatan_awal: float, percepatan: float, waktu: float
) -> float:
"""
Menghitung kecepatan akhir dari suatu pergerakan
dengan percepatan yang berbeda
>>> kalkulasi_kecepatan_akhir(10, 2.4, 5)
22.0
>>> kalkulasi_kecepatan_akhir(10, 7.2, 1)
17.2
"""
... |
def pam4_decision(x,l,m,h):
"""produces pam4 symbol from analog voltage
Parameters
----------
x : float
the analog voltage
l: float
voltage threshold between 0 and 1 symbol
m: float
voltage threshold between 1 and 2 symbol
h: float
volt... |
def expand_float(data):
"""helper method for ``expand_thru_case_control``"""
out = []
for datai in data:
out.append(float(datai))
out.sort()
return out |
def _line_reformat(line, width=70, firstlinewidth=0):
"""Takes line string and inserts newlines
and spaces on following continuation lines
so it all fits in width characters
@param width: how many characters to fit it in
@param firstlinewidth: if >0 then first line is this width.
if equal ... |
def format_data(mapping):
"""Format given mapping as HTML "data" attributes
"-data" prefix is not required for given mapping keys
"""
return ' '.join(('data-{}="{}"'.format(k, v) for k, v in mapping.items())) |
def _check_extension(filename):
""" check file type
Arguments:
----------
filename {str} -- file name
Returns:
--------
{str} -- file extension
Examples:
---------
>>> _check_extension("hoge")
None
>>> _check_extension("hoge.png")
'png'
... |
def _compute_annot_reliability_score(tf_row, entities, freq_matrix):
"""
Compute likelihood of neg samples belonging to pos space based on onto annotation freqs
:return:
"""
# Score is the sum of (freq in pos)-(freqs in neg) of the entities occurring in that text
n_ent_found = sum(tf_row)
if... |
def extract_pipeline_config(pipeline):
"""Extracts the configuration entities of a pipeline
:param pipeline: Pipeline configuration entity
:type pipeline: dict
:returns: The configuration entities of pipeline
:rtype: dict
"""
return list(pipeline.values())[0] |
def check(program_out,expected_out):
"""
User can edit this function for check if the output is correct. By default this function will return
"PASSED" if program output exactly matches to expected output.
User needs to edit this function for problems where Multiple Correct Outputs are accepted.
"""
if(progr... |
def times(number):
"""provides a range() like template filter to iterate over integer
values.
from :https://stackoverflow.com/questions/1107737
"""
return range(1, number + 1) |
def solution(A):
"""Count the number of pairs of cars that pass each other.
Each element in A[k] represents a car at position k moving in direction:
(1) right-bound if A[k] = 0
(2) left-bound if A[k] = 1
Args:
A (list): A list of cars at positions k moving in directions A[k].
... |
def toSignature(s):
""" transform wsdl address to valid package signature """
# cannot have ':' in package name
return 'SUDS#' + s.replace(':', '$') |
def extract_evidence_id(condition):
"""Extracts the id of the evidence resource linked to the Condition.
In this demo, the evidence is always a QuestionnaireResponse, which is the
only evidence and set on the detail field.
Example resource:
{
...
"evidence":[
{
"detail":[
{"r... |
def check_palindrome(string):
"""
Question 7.5: Check palindromicity of string
"""
begin = 0
end = len(string) - 1
while begin < end:
while not string[begin].isalnum() and begin < end:
begin += 1
while not string[end].isalnum() and begin < end:
end -= 1
... |
def reduceCategories(events):
""":Description: Legacy Facebook events have old categories that are consolidated, OTHER will be discarded from the training data"""
categoryMapping = {
u'BOOK': u'LITERATURE',
u'COMEDY': u'COMEDY_PERFORMANCE',
u'CLASS': u'OTHER',
u'DINING': u'FOOD',... |
def create_html_email_template(data):
""" Creates the HTML Email Template"""
return f"""
<p><strong>Company</strong>: {data.get('company')}</p>
<p><strong>Contact Name</strong>: {data.get('contact_name')}</p>
<p><strong>Email</strong>: {data.get('email')}</p>
<p><strong>Phone</strong>: {data.get... |
def trial_success(boutlist):
"""Takes list of times of bouts in seconds,
returns bool of whether the mouse managed to get the tape off in time.
"""
if boutlist[-1] == 300:
success = False
else:
success = True
return success |
def toggles_block_quote(line):
"""Returns true if line toggles block quotes on or off
(i.e. finds odd number of ```)"""
n_block_quote = line.count("```")
return n_block_quote > 0 and line.count("```") % 2 != 0 |
def root_of_closest_perfect_square(n):
""" http://stackoverflow.com/questions/15390807/integer-square-root-in-python """
x = n
y = (x + 1) // 2
while y < x:
x = y
y = (x + n // x) // 2
return x |
def cfact(n: int) -> int:
"""
>>> cfact(5)
120
"""
if n == 0: return 1
return n*cfact(n-1) |
def combine_lines(lines):
"""
Combines the stings contained in a list into a single string.
"""
new = ''
for each in lines:
new = new + each
return new |
def get_cred_fh(library: str) -> str:
"""
Determines correct SimplyE credential file
"""
if library == "BPL":
return ".simplyE/bpl_simply_e.yaml"
elif library == "NYPL":
return ".simplyE/nyp_simply_e.yaml"
else:
raise ValueError("Invalid library code passsed") |
def is_proper(str):
"""Tests if a set of parentheses are properly closed.
>>> is_proper('()(())') # regular doctests
True
>>> is_proper('(()()') # too many open parens
False
>>> is_proper('())') # too many close parens
False
>>> is_proper('())(') # parens don't match
False
"... |
def get_mse_sorted_norm(series1, series2):
"""
sorted and normalized
series length has to be equal
"""
assert len(series1) == len(series2)
mse = 0.0
max_v = max(series1)
if max_v == 0.0:
# difference is equa series2
return sum((value * value for value in series2))/len(ser... |
def clean_pci_read_output(output: str):
"""
Cleans the output from the "pci_read" function.
This essentially only means, that all the newlines and the leading whitespaces are being removed.
:param output: The output message of the "pci_read" function
:type output: str
:return:
"""
# R... |
def tokenize(lines, token='word'): #@save
"""Split sentences into word or char tokens."""
if token == 'word':
return [line.split(' ') for line in lines]
elif token == 'char':
return [list(line) for line in lines]
else:
print('ERROR: unknown token type '+token) |
def quote_identifier(identifier, sql_mode=""):
"""Quote the given identifier with backticks, converting backticks (`) in
the identifier name with the correct escape sequence (``).
Args:
identifier (string): Identifier to quote.
sql_mode (Optional[string]): SQL mode.
Returns:
A ... |
def updatedf(x,setval):
"""
update the negative values to requested value
:param name: each row of the column
setval: value to be set
:return:
updated value of the row for the column
"""
if x < 0 :
x=setval
return x |
def tostr(st):
"""Return normal quoted string."""
if not st:
return None
try:
st = str(st)
except UnicodeEncodeError:
st = st.encode("utf-8")
return st |
def expand_position(position, length=4):
"""Take a tuple with length <= 4 and pad it with ``None``'s up to
length.
Example, if ``length=4`` and ``position=(1, 0)``, then the output
is ``(1, 0, None, None)``.
"""
new_position = tuple(position) + (None,) * (length-len(position))
retu... |
def get_straights(edge):
""" Get vectors representing straight edges """
return [v for v in edge if v[0] == 0 or v[1] == 0] |
def fstatus(plus, minus, lines):
"""
returns git file change status in three digit string
"""
status = []
if plus == 0:
status.append('0')
else:
status.append('1')
if minus == 0:
status.append('0')
else:
status.append('1')
if lines == 0:
status... |
def _messageForError(status: int):
"""
Return a description string for an HTTP error code
"""
errors = {
500: 'Internal server error',
503: 'Service temporarily unavailable',
598: 'Network read timeout error'
}
return errors[status] |
def construct_conn_msg(stream, lines=None, protocol_opts=None):
"""Return a connnection message
:param stream: stream name
:param lines: number of messages to consume
:param protocol_opts: optional arguments
"""
connection_msg = stream
if lines:
connection_msg += ' {0}'.format(lines... |
def readme_name(repo):
"""Given a repo, return the name of the readme file."""
if repo == "libcxx":
return "LICENSE.TXT"
return "README.txt" |
def initial_velocity(final_velocity, acceleration, time):
"""
Calculates the initial_velocity when given final_velocity, acceleration and time
Parameters
----------
final_velocity : float
acceleration : float
time : float
Returns
-------
floa... |
def last_base_slope(c0, c1, a0, a1):
"""Calculate slope of line"""
dy = c1 - c0
dx = a1 - a0
return dy / dx |
def get_counties_with_deaths_today(counties_list, date):
"""
:param counties_list:
:return:
"""
# counties with deaths today
today_list = []
for county in counties_list:
if county[0] == date:
today_list.append(county)
return today_list |
def int2padstr(int_val):
"""
:param int_val:
:return:
"""
if int_val < 10:
return str(int_val).zfill(2)
else:
return str(int_val) |
def positive_response_id(service_id: int) -> int:
"""Given a service ID of a request, return the corresponding SID for a positive response"""
assert service_id != 0x7f - 0x40
return service_id + 0x40 |
def _drop_keys_with_none_values(main_dict: dict):
"""
Drop keys with None values to parse safe dictionary config
"""
return {k: v for k, v in main_dict.items() if v is not None} |
def format_response(code = 0, data = {}, info = 'ok'):
"""
format response
:param code: return status code
:param data: return data
:param info: return hint message
:return :class:`dict`
:rtype: dict
"""
return {
"code": code,
"data": data,
"info": info
} |
def reverseString(s):
"""reverse string
>>> reverseString('abc')
'cba'
"""
return s[::-1] |
def convert_kv_to_dict(data):
"""
convert text values in format:
key1=value1
key2=value2
to dict {'key1':'value1', 'key2':'value2'}
:param data: string containing lines with these values
:return: dict
"""
output = {}
for line in data.split("\n"):
stripped = line.strip()
... |
def robot_tidy_one(angents, self_state, self_name, cube):
"""
@param angents:
@param self_state:
@param self_name:
@param cube:
@return:
@ontology_type cube: Cube
"""
return [("robot_tell_human_to_tidy", "human", cube), ("robot_wait_for_human_to_tidy", "human", cube)] |
def calculate(not_to_exceed):
"""Returns the sum of the even-valued terms in the Fibonacci sequence
whose values do not exceed the specified number"""
answer = 0
term_one = 1
term_two = 2
while term_two < not_to_exceed:
if not term_two % 2:
answer += term_two
next_ter... |
def _format(payload):
"""Format the payload (variables) as a string.
When logging to the terminal or a file, only the string message is logged.
This converts the payload into a string, which can then be appended to the
log message itself.
:param dict payload: The variable payload.
:returns str... |
def kwargsGet(kwargs, key, replacement):
"""As kwargs.get but uses replacement if the value is None."""
if key not in kwargs:
return replacement
elif key in kwargs and kwargs[key] is None:
return replacement
else:
return kwargs[key] |
def _middle(values):
"""Lower bound of median, without using numpy (heavy reqs)"""
n = len(values)
is_odd = n % 2
middle_idx = int((n + is_odd) / 2) - 1
return sorted(values)[middle_idx] |
def add_friend(person, person2) -> None:
"""
Adds a person to this functional persons friends list
"""
person['friends'].append(person2)
return person |
def trim_url(url):
"""Removes extra punctuation from URLs found in text.
:param str url: the raw URL match
:return str: the cleaned URL
This function removes trailing punctuation that looks like it was not
intended to be part of the URL:
* trailing sentence- or clause-ending marks like ``.``,... |
def format_imm(raw):
"""Format one of the singleton immediate values."""
tag = (raw >> 3) & 0x3
if tag == 0:
return "True" if raw & 0x20 else "False"
return ("NotImplemented", "Unbound", "None")[tag - 1] |
def getSlice(m,wdcad):
"""
Get slice
Parameters
----------
m : middle index (center of the slice).
wdcad : width of slice list (units of cadence).
"""
return slice( m-wdcad/2 , m+wdcad/2 ) |
def fromHex(data,offset=0,step=2):
"""
Utility function to convert a hexadecimal string to buffer
"""
return bytearray([ int(data[x:x+2],16) for x in range(offset,len(data),step) ]) |
def _matches_version(actual_version, required_version):
"""Checks whether some version meets the requirements.
All elements of the required_version need to be present in the
actual_version.
required_version actual_version result
-----------------------------------------
1 ... |
def win_safe_name(cityname):
"""Edit the string so that it can be used as a valid file name in
Windows.
"""
cityname = cityname.strip()
if cityname.endswith("."):
cityname = cityname[:-1] + "_"
for chr in cityname:
if chr in ("<", ">", ":", "/", "\\", "|", "?", "*", "\"")... |
def pad_or_trim_sentence(sentence, max_sentence_length, padding_word="<PAD/>"):
"""
Pads all sentences to the same length. The length is defined by the longest sentence.
Returns padded sentences.
Credits: Ana Marasovic (marasovic@cl.uni-heidelberg.de)
"""
if len(sentence)>max_sentence_length:
... |
def compute_loss_packet_count(overall_packets, lost_packets):
"""
Compute loss percentage based on the number of lost packets and the number of overal packets.
"""
if overall_packets != 0:
loss = (lost_packets / overall_packets)*100
else:
return 100
return loss if loss >=0 else... |
def no_parens(s):
"""Delete parenteses from a string
Args:
s (str): String to delete parentheses from
Returns:
str: Input without any opening or closing parentheses.
"""
return s.replace('(','').replace(')','') |
def digits_are_unique(n):
"""Returns whether digits in n are unique (and no 0)"""
digits = set([int(d) for d in str(n)])
if 0 in digits:
return False
return len(str(n)) == len(digits) |
def password(password_str):
"""Checks if password length is greater than 4, else raises error"""
if len(password_str) > 4:
return password_str
else:
raise ValueError('Invalid password') |
def getUrlWithoutScheme(url: str):
"""Get the target url without scheme
@type url: str
@param url: The target URL
@returns str: The url without scheme
"""
return url[(url.index('://')+3):] |
def lr_schedule(epoch):
"""Learning Rate Schedule
Learning rate is scheduled to be reduced after 80, 120, 160, 180 epochs.
Called automatically every epoch as part of callbacks during training.
:param epoch (int): The number of epochs
:return lr (float32): learning rate
"""
lr = 1e-3
if ... |
def reverse(s):
"""
:param s:
:return:
"""
return s[::-1] |
def threept_center(x1, x2, x3, y1, y2, y3):
"""
Calculates center coordinate of a circle circumscribing three points
Parameters
--------------
x1: `double`
First x-coordinate
x2: `double`
Second x-coordinate
x3: `double`
Third y-coordinate
y1: `double`
... |
def zip_tuple(a_tuple):
"""Zip a tuple of tuple pairs into a tuple (cached)
>>> zip_tuple((('hi', 123), ('hello', 321)))
(('hi', 'hello'), (123, 321))
"""
tuple1, tuple2 = zip(*a_tuple)
return tuple1, tuple2 |
def _cons_trits(left: int, right: int) -> int:
"""
Compares two trits. If they have the same value, returns that
value. Otherwise, returns 0.
"""
return left if left == right else 0 |
def bin2int(arr):
"""Convert binary array to integer.
For example ``arr`` = `[1, 0, 1]` is converted to `5`.
Input
-----
arr: int or float
An iterable that yields 0's and 1's.
Output
-----
: int
Integer representation of ``arr``.
"""
if len(arr... |
def create_logdir(model_name, dataset, K, v, KNN, l1, l2, l3):
""" Directory to save training logs, weights, biases, etc."""
return "train_logs/{}/{}_KNN{}_K{}_v{}_l1{}_l2{}_l3{}".format(model_name, dataset, KNN, K, v, l1, l2, l3) |
def member_name(n):
"""
Formats a version of the name for use as a C# member variable.
@param n: The attribute name to format in variable style.
@type n: string
@return The resulting valid C# variable name
@rtype: string
"""
if n == None: return None
if n == 'ARG': return 'A... |
def ansible_stdout_to_str(ansible_stdout):
"""
The stdout of Ansible host is essentially a list of unicode characters.
This function converts it to a string.
Args:
ansible_stdout: stdout of Ansible
Returns:
Return a string
"""
result = ""
for x in ansible_stdout:
... |
def normalize(block):
""" Normalize a block of text to perform comparison.
Strip newlines from the very beginning and very end Then split into separate lines and strip trailing whitespace
from each line.
"""
assert isinstance(block, str)
block = block.strip('\n')
return [line.rstrip() for ... |
def clean_field(value):
"""
Strip whitespace, cast empty -> None.
Args:
value (str): The field value.
Returns:
list: The cleaned tokens.
"""
return (value.strip() or None) if value else None |
def repeated(f, n, x):
"""Returns the result of composing f n times on x.
>>> def square(x):
... return x * x
...
>>> repeated(square, 2, 3) # square(square(3)), or 3 ** 4
81
>>> repeated(square, 1, 4) # square(4)
16
>>> repeated(square, 6, 2) # big number
184467440737095... |
def to_camel_case(source: str) -> str:
"""Converts kebab-case or snake_case to camelCase."""
parts = source.replace("-", "_").split("_")
return "".join([parts[0], *[p.capitalize() for p in parts[1:]]]) |
def paths(m, n):
"""Return the number of paths from one corner of an
M by N grid to the opposite corner.
>>> paths(2, 2)
2
>>> paths(5, 7)
210
>>> paths(117, 1)
1
>>> paths(1, 157)
1
"""
"*** YOUR CODE HERE ***"
if m is 1: # if m is 1 then we have a grid the size of... |
def _path_to_name(path):
"""
Internal function to turn a path into an endpoint name
"""
return " > ".join(elem.title().replace("-", " ").replace("_", " ") for elem in str(path).split("/")) |
def toHours(spec):
"""spec is of the form '08:00-10:00' """
return (int(spec[0:2])+int(spec[3:5])/60.0, int(spec[6:8])+int(spec[9:11])/60.0) |
def create_help(header, options):
"""Create formated help
Args:
header (str): The header for the help
options (list[str]): The options that are available for argument
Returns:
str: Formated argument help
"""
return "\n" + header + "\n" + \
"\n".join(map(lambda x:... |
def parse_num(n):
"""
:param n: str
Number to parse
:return: float
Parses numbers written like 123,949.99
"""
m = str(n).strip().replace(".", "").replace(",", ".")
return float(m) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.