content
stringlengths 35
416k
| sha1
stringlengths 40
40
| id
int64 0
710k
|
---|---|---|
def get_timepoint( data, tp=0 ):
"""Returns the timepoint (3D data volume, lowest is 0) from 4D input.
You can save memory by using [1]:
nifti.dataobj[..., tp]
instead: see get_nifti_timepoint()
Works with loop_and_save().
Call directly, or with niftify().
Ref:
[1]: http://nipy.org/nibabel/images_and_memory.html
"""
# Replicating seg_maths -tp
tp = int(tp)
if len(data.shape) < 4:
print("Data has fewer than 4 dimensions. Doing nothing...")
output = data
else:
if data.shape[3] < tp:
print("Data has fewer than {0} timepoints in its 4th dimension.".format(tp))
output = data
else:
output = data[:,:,:,tp]
return output
# elif len(data.shape) > 4:
# print("Data has more than 4 dimensions! Assuming the 4th is time ...")
# End get_timepoint() definition | f5a718e5d9f60d1b389839fc0c637bee32b500bf | 4,079 |
def method_from_name(klass, method_name: str):
"""
Given an imported class, return the given method pointer.
:param klass: An imported class containing the method.
:param method_name: The method name to find.
:return: The method pointer
"""
try:
return getattr(klass, method_name)
except AttributeError:
raise NotImplementedError() | 97274754bd89ede62ee5940fca6c4763efdbb95c | 4,080 |
import re
def parse_value(string: str) -> str:
"""Check if value is a normal string or an arrow function
Args:
string (str): Value
Returns:
str: Value if it's normal string else Function Content
"""
content, success = re.subn(r'^\(\s*\)\s*=>\s*{(.*)}$', r'\1', string)
if not success:
return string
return content | ead42d7f300c68b6978699473de8506794bb1ab4 | 4,081 |
import os
def file_exists(fpath: str):
"""Checks if file exists by the given path
:param str fpath:
A path to validate for being a file
:returns:
True, if fpath is a file
False, if fpath doesn't exists or isn't a file
"""
return os.path.isfile(fpath) | 7bc85a461d6928acddd15b3be1fa8fca028b015b | 4,082 |
def convert(origDict, initialSpecies):
"""
Convert the original dictionary with species labels as keys
into a new dictionary with species objects as keys,
using the given dictionary of species.
"""
new_dict = {}
for label, value in origDict.items():
new_dict[initialSpecies[label]] = value
return new_dict | 5143f31acd1efdf1790e68bade3a1f8d8977bcde | 4,083 |
def createGrid(nx, ny):
"""
Create a grid position array.
"""
direction = 0
positions = []
if (nx > 1) or (ny > 1):
half_x = int(nx/2)
half_y = int(ny/2)
for i in range(-half_y, half_y+1):
for j in range(-half_x, half_x+1):
if not ((i==0) and (j==0)):
if ((direction%2)==0):
positions.append([j,i])
else:
positions.append([-j,i])
direction += 1
return positions | fe74af508e1bc7185d21f9c86b4eab64a66a52f5 | 4,084 |
def command_ltc(bot, user, channel, args):
"""Display current LRC exchange rates from BTC-E"""
r = bot.get_url("https://btc-e.com/api/2/ltc_usd/ticker")
j = r.json()['ticker']
return bot.say(channel, "BTC-E: avg:$%s last:$%s low:$%s high:$%s vol:%s" % (j['avg'], j['last'], j['low'], j['high'], j['vol'])) | 7aa411b6708e54b09cf2b9aef9c8b01899b95298 | 4,085 |
def union_exprs(La, Lb):
"""
Union two lists of Exprs.
"""
b_strs = set([node.unique_str() for node in Lb])
a_extra_nodes = [node for node in La if node.unique_str() not in b_strs]
return a_extra_nodes + Lb | 2bd634a22b27314f6d03c8e52c0b09f7f4b692db | 4,087 |
import re
import itertools
def compile_read_regex(read_tags, file_extension):
"""Generate regular expressions to disern direction in paired-end reads."""
read_regex = [re.compile(r'{}\.{}$'.format(x, y))\
for x, y in itertools.product(read_tags, [file_extension])]
return read_regex | e677b8ff622eb31ea5f77bc662845ba0aef91770 | 4,088 |
from typing import List
def get_bank_sizes(num_constraints: int,
beam_size: int,
candidate_counts: List[int]) -> List[int]:
"""
Evenly distributes the beam across the banks, where each bank is a portion of the beam devoted
to hypotheses having met the same number of constraints, 0..num_constraints.
After the assignment, banks with more slots than candidates are adjusted.
:param num_constraints: The number of constraints.
:param beam_size: The beam size.
:param candidate_counts: The empirical counts of number of candidates in each bank.
:return: A distribution over banks.
"""
num_banks = num_constraints + 1
bank_size = beam_size // num_banks
remainder = beam_size - bank_size * num_banks
# Distribute any remainder to the end
assigned = [bank_size for x in range(num_banks)]
assigned[-1] += remainder
# Now, moving right to left, push extra allocation to earlier buckets.
# This encodes a bias for higher buckets, but if no candidates are found, space
# will be made in lower buckets. This may not be the best strategy, but it is important
# that you start pushing from the bucket that is assigned the remainder, for cases where
# num_constraints >= beam_size.
for i in reversed(range(num_banks)):
overfill = assigned[i] - candidate_counts[i]
if overfill > 0:
assigned[i] -= overfill
assigned[(i - 1) % num_banks] += overfill
return assigned | 7a515b1e7762d01b7f7a1405a943f03babe26520 | 4,091 |
import ast
def parse_data(data):
"""Takes a string from a repr(WSGIRequest) and transliterates it
This is incredibly gross "parsing" code that takes the WSGIRequest
string from an error email and turns it into something that
vaguely resembles the original WSGIRequest so that we can send
it through the system again.
"""
BEGIN = '<WSGIRequest'
data = data.strip()
data = data[data.find(BEGIN) + len(BEGIN):]
if data.endswith('>'):
data = data[:-1]
container = {}
key = ''
for line in data.splitlines():
# Lines that start with 'wsgi.' have values which are
# objects. E.g. a logger. This won't fly with ast.literal_eval
# so we just ignore all the wsgi. meta stuff.
if not line or line.startswith(' \'wsgi.'):
continue
if line.startswith(' '):
# If it starts with a space, then it's a continuation of
# the current dict.
container[key] += line
else:
key, val = line.split(':', 1)
container[key.strip()] = val.strip()
QUERYDICT = '<QueryDict: '
for key, val in container.items():
val = val.strip(',')
if val.startswith(QUERYDICT):
# GET and POST are both QueryDicts, so we nix the
# QueryDict part and pretend they're regular dicts.
#
# <QueryDict: {...}> -> {...}
val = val[len(QUERYDICT):-1]
elif val.startswith('{'):
# Regular dict that might be missing a } because we
# dropped it when we were weeding out wsgi. lines.
#
# {... -> {...}
val = val.strip()
if not val.endswith('}'):
val = val + '}'
else:
# This needs to have the string ornamentation added so it
# literal_evals into a string.
val = 'u"' + val + '"'
# Note: We use ast.literal_eval here so that we're guaranteed
# only to be getting out strings, lists, tuples, dicts,
# booleans or None and not executing arbitrary Python code.
val = ast.literal_eval(val)
container[key] = val
return container | 63470f1a935ef6218c239f99228eaf7919b9f09c | 4,092 |
def _is_ref_path(path_elements):
"""
Determine whether the given object path, expressed as an element list
(see _element_list_to_object_path()), ends with a reference and is
therefore eligible for continuation through the reference. The given
object path is assumed to be "completed" down to a single STIX property
value. This means that a *_ref property will be the last component, and
*_refs will be second-to-last, because it requires a subsequent index step.
:param path_elements: An object path, as a list
:return: True if a continuable reference path; False if not
"""
result = False
if path_elements:
last_elt = path_elements[-1]
if isinstance(last_elt, str) and last_elt.endswith("_ref"):
result = True
elif len(path_elements) > 1:
# for _refs properties, the ref property itself must be
# second-to-last, and the last path element must be an index step,
# either "*" or an int. Maybe not necessary to check the index
# step; all we need is to check the second-to-last property.
second_last_elt = path_elements[-2]
if isinstance(second_last_elt, str) \
and second_last_elt.endswith("_refs"):
result = True
return result | da8bc8eb7611ce7b5361209873e871f2a4656a03 | 4,093 |
def is_leap(year):
"""
Simply returns true or false depending on if it's leap or not.
"""
return not year%400 or not (year%4 and year%100) | 5cb40664b2e8aa9aea647a356b63708f00891a2c | 4,095 |
def knapsack_fractional(weights,values,capacity):
""" takes weights and values of items and capacity of knapsack as input
and returns the maximum profit possible for the given capacity of knapsack
using the fractional knapsack algorithm"""
#initialisaing the value of max_profit variable
max_profit=0
for pair in sorted(zip(weights,values),key=lambda x:-x[1]/x[0]): # sorting the pair of values in descending order
#if weight of highest pair is greater than capacity, the amount is added in fractions
if pair[0]>capacity:
# while((pair[1]/(pair[0]/capacity))!=0)
max_profit+=int(pair[1]/(pair[0]/capacity))
capacity=0
#if highest pair is lesser than capacity then the next pair is also added in fractions
elif pair[0]<= capacity:
max_profit+=pair[1]
capacity-=pair[0]
#returns nearest possible integer value of profit
return int(max_profit) | 8cb05c199baf65c24512fa97882085e7bb66a98d | 4,096 |
import os
from os.path import dirname, abspath, realpath
from platform import system
def get_libpath():
"""
Get the library path of the the distributed SSA library.
"""
root = dirname(abspath(realpath(__file__)))
if system() == 'Linux':
library = 'Linux-SSA.so'
elif system() == 'Darwin':
library = 'OSX-SSA.so'
elif system() == 'Windows':
library = "Win-SSA.so"
else:
raise RuntimeError("unsupported platform - \"{}\"".format(system()))
return os.path.join(root, 'clibs', library) | 0b23429796f00c56cba081e4f86420de7267135b | 4,097 |
def coord(row, col):
""" returns coordinate values of specific cell within Sudoku Puzzle"""
return row*9+col | 14cda1489215a2b36d61ac6eac56c14981290b16 | 4,098 |
def post_authn_parse(request, client_id, endpoint_context, **kwargs):
"""
:param request:
:param client_id:
:param endpoint_context:
:param kwargs:
:return:
"""
if endpoint_context.args["pkce"]["essential"] is True:
if not "code_challenge" in request:
raise ValueError("Missing required code_challenge")
if not "code_challenge_method" in request:
if "plain" not in endpoint_context.args["pkce"]["code_challenge_method"]:
raise ValueError("No support for code_challenge_method=plain")
request["code_challenge_method"] = "plain"
else: # May or may not
if "code_challenge" in request:
if not "code_challenge_method" in request:
if (
"plain"
not in endpoint_context.args["pkce"]["code_challenge_method"]
):
raise ValueError("No support for code_challenge_method=plain")
request["code_challenge_method"] = "plain"
return request | 6e9e00a5d073a57cf0245b2506abfd822b5f6ff5 | 4,099 |
def constructed(function):
"""A decorator function for calling when a class is constructed."""
def store_constructed(class_reference):
"""Store the key map."""
setattr(class_reference, "__deserialize_constructed__", function)
return class_reference
return store_constructed | 29101fe6deb1112b5e69291377a3d8ab12082268 | 4,101 |
def datetime_to_hours(dt):
"""Converts datetime.timedelta to hours
Parameters:
-----------
dt: datetime.timedelta
Returns:
--------
float
"""
return dt.days * 24 + dt.seconds / 3600 | e7373cbb49e21340fef1590a655059fd39c6ce88 | 4,104 |
def adjust_learning_rate(optimizer, step):
"""Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
if step == 500000:
for param_group in optimizer.param_groups:
param_group['lr'] = 0.0005
elif step == 1000000:
for param_group in optimizer.param_groups:
param_group['lr'] = 0.0003
elif step == 2000000:
for param_group in optimizer.param_groups:
param_group['lr'] = 0.0001
return optimizer | 729c6650eb9b88102b68ba5e8d356e1cfa8b6632 | 4,105 |
import os
def find_file(path, include_str='t1', exclude_str='lesion'):
"""finds all the files in the given path which include include_str in their
name and do not include exclude_str
----------
path: path to the directory
path where the files are stored
include_str: string
string which must be included in the name of the file
exclude_str: strin
string which may not be included in the name of the file
Returns
-------
files: list
list of filenames matching the given criteria
"""
files = os.listdir(path)
if include_str is not None:
files = [n_file for n_file in files if (include_str in n_file)]
if exclude_str is not None:
files = [n_file for n_file in files if (exclude_str not in n_file)]
return files | 32f3e373268f3cf310eebceb339c0c6cb9e34cb8 | 4,106 |
def remove_suffix(input_string, suffix):
"""From the python docs, earlier versions of python does not have this."""
if suffix and input_string.endswith(suffix):
return input_string[: -len(suffix)]
return input_string | af4af2442f42121540de00dfaece13831a27cc57 | 4,107 |
import requests
def get_bga_game_list():
"""Gets a geeklist containing all games currently on Board Game Arena."""
result = requests.get("https://www.boardgamegeek.com/xmlapi2/geeklist/252354")
return result.text | 61418d5c0e0ad12c3f7af8a7831d02f94153ac84 | 4,108 |
import http
def build_status(code: int) -> str:
"""
Builds a string with HTTP status code and reason for given code.
:param code: integer HTTP code
:return: string with code and reason
"""
status = http.HTTPStatus(code)
def _process_word(_word: str) -> str:
if _word == "OK":
return _word
return _word.capitalize()
reason = " ".join(_process_word(word) for word in status.name.split("_"))
text = f"{code} {reason}"
return text | 9730abf472ddc3d5e852181c9d60f8c42fee687d | 4,109 |
import time
def retry(func_name, max_retry, *args):
"""Retry a function if the output of the function is false
:param func_name: name of the function to retry
:type func_name: Object
:param max_retry: Maximum number of times to be retried
:type max_retry: Integer
:param args: Arguments passed to the function
:type args: args
:return: Output of the function if function is True
:rtype: Boolean (True/False) or None Type(None)
"""
output = None
for _ in range(max_retry):
output = func_name(*args)
if output and output != 'False':
return output
else:
time.sleep(5)
else:
return output | 29051605dbad65823c1ca99afb3237679a37a08c | 4,110 |
def benedict_bornder_constants(g, critical=False):
""" Computes the g,h constants for a Benedict-Bordner filter, which
minimizes transient errors for a g-h filter.
Returns the values g,h for a specified g. Strictly speaking, only h
is computed, g is returned unchanged.
The default formula for the Benedict-Bordner allows ringing. We can
"nearly" critically damp it; ringing will be reduced, but not entirely
eliminated at the cost of reduced performance.
Parameters
----------
g : float
scaling factor g for the filter
critical : boolean, default False
Attempts to critically damp the filter.
Returns
-------
g : float
scaling factor g (same as the g that was passed in)
h : float
scaling factor h that minimizes the transient errors
Examples
--------
.. code-block:: Python
from filterpy.gh import GHFilter, benedict_bornder_constants
g, h = benedict_bornder_constants(.855)
f = GHFilter(0, 0, 1, g, h)
References
----------
Brookner, "Tracking and Kalman Filters Made Easy". John Wiley and
Sons, 1998.
"""
g_sqr = g**2
if critical:
return (g, 0.8 * (2. - g_sqr - 2*(1-g_sqr)**.5) / g_sqr)
return (g, g_sqr / (2.-g)) | ca40941b4843b3d71030549da2810c9241ebdf72 | 4,111 |
def get_mode(elements):
"""The element(s) that occur most frequently in a data set."""
dictionary = {}
elements.sort()
for element in elements:
if element in dictionary:
dictionary[element] += 1
else:
dictionary[element] = 1
# Get the max value
max_value = max(dictionary.values())
highest_elements = [key for key, value in dictionary.items() if value == max_value]
modes = sorted(highest_elements)
return modes[0] | bc792ffe58ffb3b9368559fe45ec623fe8accff6 | 4,112 |
import re
def remove_special_message(section_content):
"""
Remove special message - "medicinal product no longer authorised"
e.g.
'me di cin al p ro du ct n o lo ng er a ut ho ris ed'
'me dic ina l p rod uc t n o l on ge r a uth ori se d'
:param section_content: content of a section
:return: content of a section without special message
"""
# string as it is present in the section content
SPECIAL_MESSAGE1 = 'me di cin al p ro du ct n o lo ng er a ut ho ris ed'
SPECIAL_MESSAGE2 = 'me dic ina l p ro du ct no lo ng er au th or ise d'
SPECIAL_MESSAGE3 = 'me dic ina l p rod uc t n o l on ge r a uth ori se d'
SPECIAL_MESSAGE4 = 'me dic ina l p ro du ct no lo ng er au tho ris ed'
SPECIAL_MESSAGE5 = 'me dic ina l p ro du ct no lo ng er a ut ho ris ed'
SPECIAL_MESSAGE6 = 'me dic ina l p rod uc t n o l on ge r a uth ori sed'
SPECIAL_MESSAGE7 = 'm ed ici na l p ro du ct no lo ng er a ut ho ris ed'
SPECIAL_MESSAGE8 = 'm ed ici na l p ro du ct no lo ng er au th or ise d'
SPECIAL_MESSAGE9 = 'med icin al pro du ct no lo ng er au tho ris ed'
SPECIAL_MESSAGE_ARRAY = [SPECIAL_MESSAGE1, SPECIAL_MESSAGE2, SPECIAL_MESSAGE3, SPECIAL_MESSAGE4,
SPECIAL_MESSAGE5, SPECIAL_MESSAGE6, SPECIAL_MESSAGE7, SPECIAL_MESSAGE8,
SPECIAL_MESSAGE9]
# in case message present in section content
for SPECIAL_MESSAGE in SPECIAL_MESSAGE_ARRAY:
section_content = section_content.replace(SPECIAL_MESSAGE, '')
# remove multiple consecutive spaces
section_content = re.sub(' +', ' ', section_content)
return section_content | 37d9cbd697a98891b3f19848c90cb17dafcd6345 | 4,114 |
def apply_function_elementwise_series(ser, func):
"""Apply a function on a row/column basis of a DataFrame.
Args:
ser (pd.Series): Series.
func (function): The function to apply.
Returns:
pd.Series: Series with the applied function.
Examples:
>>> df = pd.DataFrame(np.array(range(12)).reshape(4, 3), columns=list('abc'))
>>> ser = df['b']
>>> f = lambda x: '%.1f' % x
>>> apply_function_elementwise_series(ser, f)
0 1.0
1 4.0
2 7.0
3 10.0
Name: b, dtype: object
"""
return ser.map(func) | d2af0a9c7817c602b4621603a8f06283f34ae81a | 4,115 |
def BitWidth(n: int):
""" compute the minimum bitwidth needed to represent and integer """
if n == 0:
return 0
if n > 0:
return n.bit_length()
if n < 0:
# two's-complement WITHOUT sign
return (n + 1).bit_length() | 46dcdfb0987268133d606e609d39c641b9e6faab | 4,116 |
def fetch_last_posts(conn) -> list:
"""Fetch tooted posts from db"""
cur = conn.cursor()
cur.execute("select postid from posts")
last_posts = cur.fetchall()
return [e[0] for e in last_posts] | dd5addd1ba19ec2663a84617904f6754fe7fc1fc | 4,118 |
import socket
def tcp_port_open_locally(port):
"""
Returns True if the given TCP port is open on the local machine
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex(("127.0.0.1", port))
return result == 0 | f5c801a5016085eedbed953089742e184f514db5 | 4,120 |
def wrap(text, width=80):
"""
Wraps a string at a fixed width.
Arguments
---------
text : str
Text to be wrapped
width : int
Line width
Returns
-------
str
Wrapped string
"""
return "\n".join(
[text[i:i + width] for i in range(0, len(text), width)]
) | 793840a1cae51397de15dd16051c5dfffc211768 | 4,121 |
import socket
def get_ephemeral_port(sock_family=socket.AF_INET, sock_type=socket.SOCK_STREAM):
"""Return an ostensibly available ephemeral port number."""
# We expect that the operating system is polite enough to not hand out the
# same ephemeral port before we can explicitly bind it a second time.
s = socket.socket(sock_family, sock_type)
s.bind(('', 0))
port = s.getsockname()[1]
s.close()
return port | 37287b70e35b8aa7fbdb01ced1882fb3bbf38543 | 4,123 |
def lastmsg(self):
"""
Return last logged message if **_lastmsg** attribute is available.
Returns:
last massage or empty str
"""
return getattr(self, '_last_message', '') | ad080c05caadbb644914344145460db0164f017c | 4,124 |
def _callback_on_all_dict_keys(dt, callback_fn):
"""
Callback callback_fn on all dictionary keys recursively
"""
result = {}
for (key, val) in dt.items():
if type(val) == dict:
val = _callback_on_all_dict_keys(val, callback_fn)
result[callback_fn(key)] = val
return result | 3cab018413a7ba8a0e5bbae8574025253a2ea885 | 4,125 |
import os
def running_on_kaggle() -> bool:
"""Detect if the current environment is running on Kaggle.
Returns:
bool:
True if the current environment is on Kaggle, False
otherwise.
"""
return os.environ.get("KAGGLE_KERNEL_RUN_TYPE") == "Interactive" | ac1432666ccc8ca8e9d1d73938c5a1212f4fc429 | 4,126 |
def getCountdown(c):
"""
Parse into a Friendly Readable format for Humans
"""
days = c.days
c = c.total_seconds()
hours = round(c//3600)
minutes = round(c // 60 - hours * 60)
seconds = round(c - hours * 3600 - minutes * 60)
return days, hours, minutes, seconds | f49225ae2680192340720c8958aa19b9e9369f5f | 4,128 |
def get_list_channels(sc):
"""Get list of channels."""
# https://api.slack.com/methods/channels.list
response = sc.api_call(
"channels.list",
)
return response['channels'] | d31271bcc065b4a212e298c6283c4d658e5547da | 4,129 |
def construct_sru_query(keyword, keyword_type=None, mat_type=None, cat_source=None):
"""
Creates readable SRU/CQL query, does not encode white spaces or parenthesis -
this is handled by the session obj.
"""
query_elems = []
if keyword is None:
raise TypeError("query argument cannot be None.")
if keyword_type is None:
# take as straight sru query and pass to sru_query method
query_elems.append(keyword.strip())
elif keyword_type == "ISBN":
query_elems.append('srw.bn = "{}"'.format(keyword))
elif keyword_type == "UPC":
query_elems.append('srw.sn = "{}"'.format(keyword))
elif keyword_type == "ISSN":
query_elems.append('srw.in = "{}"'.format(keyword))
elif keyword_type == "OCLC #":
query_elems.append('srw.no = "{}"'.format(keyword))
elif keyword_type == "LCCN":
query_elems.append('srw.dn = "{}"'.format(keyword))
if mat_type is None or mat_type == "any":
pass
elif mat_type == "print":
query_elems.append('srw.mt = "bks"')
elif mat_type == "large print":
query_elems.append('srw.mt = "lpt"')
elif mat_type == "dvd":
query_elems.append('srw.mt = "dvv"')
elif mat_type == "bluray":
query_elems.append('srw.mt = "bta"')
if cat_source is None or cat_source == "any":
pass
elif cat_source == "DLC":
query_elems.append('srw.pc = "dlc"')
return " AND ".join(query_elems) | fbe28156beca73339fa88d200777e25172796864 | 4,130 |
import json
def json2dict(astr: str) -> dict:
"""将json字符串转为dict类型的数据对象
Args:
astr: json字符串转为dict类型的数据对象
Returns:
返回dict类型数据对象
"""
return json.loads(astr) | f13b698dcf7dda253fd872bb464594901280f03b | 4,132 |
import os
def add_service_context(_logger, _method, event_dict):
"""
Function intended as a processor for structlog. It adds information
about the service environment and reasonable defaults when not running in Lambda.
"""
event_dict['region'] = os.environ.get('REGION', os.uname().nodename)
event_dict['service'] = os.environ.get('SERVICE', os.path.abspath(__file__))
event_dict['stage'] = os.environ.get('STAGE', 'dev')
return event_dict | f5ea74b09ddd7024a04bc4f42bbd339b82adc9e3 | 4,133 |
import os
def get_drives():
"""A list of accessible drives"""
if os.name == "nt":
return _get_win_drives()
else:
return [] | f370697170d27600322d6b1eae1c6028e73dc5a6 | 4,134 |
def fibonacci(length=10):
"""Get fibonacci sequence given it length.
Parameters
----------
length : int
The length of the desired sequence.
Returns
-------
sequence : list of int
The desired Fibonacci sequence
"""
if length < 1:
raise ValueError("Sequence length must be > 0")
sequence = [0] * (length + 2)
sequence[0] = 0
sequence[1] = 1
for i in range(2, len(sequence)):
sequence[i] = sequence[i - 1] + sequence[i - 2]
return sequence[: -2] | afa3ef63a663b4e89e5c4a694315083debdbab59 | 4,135 |
def lowercase_words(words):
"""
Lowercases a list of words
Parameters
-----------
words: list of words to process
Returns
-------
Processed list of words where words are now all lowercase
"""
return [word.lower() for word in words] | b6e8658f35743f6729a9f8df229b382797b770f6 | 4,137 |
def _standardize_df(data_frame):
"""
Helper function which divides df by std and extracts mean.
:param data_frame: (pd.DataFrame): to standardize
:return: (pd.DataFrame): standardized data frame
"""
return data_frame.sub(data_frame.mean(), axis=1).div(data_frame.std(), axis=1) | cbe0e1f5c507181a63193a4e08f4ed8139d9e129 | 4,138 |
def isempty(s):
"""
return if input object(string) is empty
"""
if s in (None, "", "-", []):
return True
return False | 9c3ffd6ab818e803c1c0129588c345361c58807f | 4,139 |
def clamp(val, min_, max_):
"""clamp val to between min_ and max_ inclusive"""
if val < min_:
return min_
if val > max_:
return max_
return val | 31f2441ba03cf765138a7ba9b41acbfe21b7bda7 | 4,140 |
def get_ip(request):
"""Determines user IP address
Args:
request: resquest object
Return:
ip_address: requesting machine's ip address (PUBLIC)
"""
ip_address = request.remote_addr
return ip_address | 84e1540bc8b79fd2043a8fb6f107f7bcd8d7cc8c | 4,141 |
def _is_valid_new_style_arxiv_id(identifier):
"""Determine if the given identifier is a valid new style arXiv ID."""
split_identifier = identifier.split('v')
if len(split_identifier) > 2:
return False
elif len(split_identifier) == 2:
identifier, version = split_identifier
if not version.isnumeric():
return False
else:
identifier = split_identifier[0]
split_identifier = identifier.split('.')
if len(split_identifier) != 2:
return False
prefix, suffix = split_identifier
if not prefix.isnumeric() or not suffix.isnumeric():
return False
if len(prefix) != 4 or len(suffix) not in {4, 5}:
return False
month = prefix[2:4]
if int(month) > 12:
return False
return True | 71171984ad1497fa45e109b9657352c20bfe7682 | 4,142 |
def count_vowels(s):
"""Used to count the vowels in the sequence"""
s = s.lower()
counter=0
for x in s:
if(x in ['a','e','i','o','u']):
counter+=1
return counter | 236500c76b22510e6f0d97a4200865e2a18b47c3 | 4,144 |
def get_start_block(block):
"""
Gets the deepest block to use as the starting block.
"""
if not block.get('children'):
return block
first_child = block['children'][0]
return get_start_block(first_child) | e658954bb69f88f10c2f328c605d6da094ba065d | 4,146 |
def parse_worker_string(miner, worker):
"""
Parses a worker string and returns the coin address and worker ID
Returns:
String, String
"""
worker_part_count = worker.count(".") + 1
if worker_part_count > 1:
if worker_part_count == 2:
coin_address, worker = worker.split('.')
else:
worker_parts = worker.split('.')
coin_address = worker_parts[0]
worker = worker_parts[worker_part_count - 1]
else:
coin_address = worker
if coin_address is not None:
if miner.coin_address is None or len(miner.coin_address) == 0:
miner.coin_address = coin_address
elif miner.coin_address != coin_address:
miner.coin_address = coin_address
if worker is not None:
if miner.worker_name is None or len(miner.worker_name) == 0:
miner.worker_name = worker
elif miner.worker_name != worker:
miner.worker_name = worker
return coin_address, worker | 3492716fc9f5290a161de0b46e7af87afbe6b348 | 4,147 |
def str_view(request):
"""
A simple test view that returns a string.
"""
return '<Response><Message>Hi!</Message></Response>' | fd9d150afdf0589cdb4036bcb31243b2e22ef1e2 | 4,149 |
def get_mnsp_offer_index(data) -> list:
"""Get MNSP offer index"""
interconnectors = (data.get('NEMSPDCaseFile').get('NemSpdInputs')
.get('PeriodCollection').get('Period')
.get('InterconnectorPeriodCollection')
.get('InterconnectorPeriod'))
# Container for offer index
offer_index = []
for i in interconnectors:
# Non-MNSP interconnectors do not have an MNSPOfferCollection attribute
if i.get('MNSPOfferCollection') is None:
continue
# Extract InterconnectorID and RegionID for each offer entry
for j in i.get('MNSPOfferCollection').get('MNSPOffer'):
offer_index.append((i['@InterconnectorID'], j['@RegionID']))
return offer_index | 46211e9a29f1fd1fd3148deaaaa064b6d6b05ca7 | 4,150 |
from typing import Generator
import pkg_resources
def get_pip_package_list(path: str) -> Generator[pkg_resources.Distribution, None, None]:
"""Get the Pip package list of a Python virtual environment.
Must be a path like: /project/venv/lib/python3.9/site-packages
"""
packages = pkg_resources.find_distributions(path)
return packages | 9e73e27c2b50186dedeedd1240c28ef4f4d50e03 | 4,151 |
def _get_reverse_complement(seq):
"""
Get the reverse compliment of a DNA sequence.
Parameters:
-----------
seq
Returns:
--------
reverse_complement_seq
Notes:
------
(1) No dependencies required. Pure python.
"""
complement_seq = ""
for i in seq:
if i == "C":
complement_seq += "G"
elif i == "G":
complement_seq += "C"
elif i == "A":
complement_seq += "T"
elif i == "T":
complement_seq += "A"
elif i == "N":
complement_seq += "N"
reverse_complement_seq = complement_seq[::-1]
return reverse_complement_seq | 31408767c628ab7b0e6e63867e37f11eb6e19560 | 4,152 |
def check_table(conn, table, interconnect):
"""
searches if Interconnect exists in table in database
:param conn: connect instance for database
:param table: name of table you want to check
:param interconnect: name of the Interconnect you are looking for
:return: results of SQL query searching for table
"""
cur = conn.cursor()
sql_search = "SELECT * \
FROM %s \
WHERE Interconnect='%s'" % (table, interconnect)
found = cur.execute(sql_search).fetchone()
return found | 0888146d5dfe20e7bdfbfe078c58e86fda43d6a5 | 4,153 |
def xml_escape(x):
"""Paranoid XML escaping suitable for content and attributes."""
res = ''
for i in x:
o = ord(i)
if ((o >= ord('a')) and (o <= ord('z'))) or \
((o >= ord('A')) and (o <= ord('Z'))) or \
((o >= ord('0')) and (o <= ord('9'))) or \
i in ' !#$%()*+,-./:;=?@\^_`{|}~':
res += i
else:
res += '&#%d;' % o
return res | 018dc7d1ca050641b4dd7198e17911b8d17ce5fc | 4,154 |
def read_tab(filename):
"""Read information from a TAB file and return a list.
Parameters
----------
filename : str
Full path and name for the tab file.
Returns
-------
list
"""
with open(filename) as my_file:
lines = my_file.readlines()
return lines | 8a6a6b0ec693130da7f036f4673c89f786dfb230 | 4,155 |
def int2(c):
""" Parse a string as a binary number """
return int(c, 2) | dd1fb1f4c194e159b227c77c4246136863646707 | 4,156 |
def properties(classes):
"""get all property (p-*, u-*, e-*, dt-*) classnames
"""
return [c.partition("-")[2] for c in classes if c.startswith("p-")
or c.startswith("u-") or c.startswith("e-") or c.startswith("dt-")] | 417562d19043f4b98068ec38cc010061b612fef3 | 4,157 |
def _setter_name(getter_name):
""" Convert a getter name to a setter name.
"""
return 'set' + getter_name[0].upper() + getter_name[1:] | d4b55afc10c6d79a1432d2a8f3077eb308ab0f76 | 4,158 |
def thumbnail(img, size = (1000,1000)):
"""Converts Pillow images to a different size without modifying the original image
"""
img_thumbnail = img.copy()
img_thumbnail.thumbnail(size)
return img_thumbnail | 4eb49869a53d9ddd42ca8c184a12f0fedb8586a5 | 4,161 |
import os
def get_unique_dir(log_dir='', max_num=100, keep_original=False):
"""Get a unique dir name based on log_dir.
If keep_original is True, it checks the list
{log_dir, log_dir-0, log_dir-1, ..., log_dir-[max_num-1]}
and returns the first non-existing dir name. If keep_original is False
then log_dir is excluded from the list.
"""
if keep_original and not os.path.exists(log_dir):
if log_dir == '':
raise ValueError('log_dir cannot be empty with keep_original=True.')
return log_dir
else:
for i in range(max_num):
_dir = '{}-{}'.format(log_dir, i)
if not os.path.exists(_dir):
return _dir
raise ValueError('Too many dirs starting with {}.'.format(log_dir)) | 0cc517f67929fd29e1a38d0dc0aae73e3e4c9252 | 4,163 |
def create_contrasts(task):
"""
Create a contrasts list
"""
contrasts = []
contrasts += [('Go', 'T', ['GO'], [1])]
contrasts += [('GoRT', 'T', ['GO_rt'], [1])]
contrasts += [('StopSuccess', 'T', ['STOP_SUCCESS'], [1])]
contrasts += [('StopUnsuccess', 'T', ['STOP_UNSUCCESS'], [1])]
contrasts += [('StopUnsuccessRT', 'T', ['STOP_UNSUCCESS_rt'], [1])]
contrasts += [('Go-StopSuccess', 'T', ['GO', 'STOP_SUCCESS'], [1, -1])]
contrasts += [('Go-StopUnsuccess', 'T', ['GO', 'STOP_UNSUCCESS'], [1, -1])]
contrasts += [('StopSuccess-StopUnsuccess', 'T',
['STOP_SUCCESS', 'STOP_UNSUCCESS'], [1, -1])]
# add negative
repl_w_neg = []
for con in contrasts:
if '-' not in con[0]:
newname = 'neg_%s' % con[0]
else:
newname = "-".join(con[0].split("-")[::-1])
new = (newname, 'T', con[2], [-x for x in con[3]])
repl_w_neg.append(con)
repl_w_neg.append(new)
return repl_w_neg | 221b1b1ebcc6c8d0e2fcb32d004794d1b0a47522 | 4,167 |
from typing import List
import logging
def sort_by_fullname(data: List[dict]) -> List[dict]:
""" sort data by full name
:param data:
:return:
"""
logging.info("Sorting data by fullname...")
try:
data.sort(key=lambda info: info["FULL_NAME"], reverse=False)
except Exception as exception:
logging.exception(exception)
raise
logging.info("Sort data by fullname successfully!")
return data | 0b4ecf53893bda7d226b3c26fe51b9abc073294b | 4,168 |
def check_position(position):
"""Determines if the transform is valid. That is, not off-keypad."""
if position == (0, -3) or position == (4, -3):
return False
if (-1 < position[0] < 5) and (-4 < position[1] < 1):
return True
else:
return False | f95ab22ce8da386284040626ac90c908a17b53fa | 4,169 |
def split_kp(kp_joined, detach=False):
"""
Split the given keypoints into two sets(one for driving video frames, and the other for source image)
"""
if detach:
kp_video = {k: v[:, 1:].detach() for k, v in kp_joined.items()}
kp_appearance = {k: v[:, :1].detach() for k, v in kp_joined.items()}
else:
kp_video = {k: v[:, 1:] for k, v in kp_joined.items()}
kp_appearance = {k: v[:, :1] for k, v in kp_joined.items()}
return {'kp_driving': kp_video, 'kp_source': kp_appearance} | 0396003a17172a75b121ddb43c9b9cf14ee3e458 | 4,170 |
def extract_timestamp(line):
"""Extract timestamp and convert to a form that gives the
expected result in a comparison
"""
# return unixtime value
return line.split('\t')[6] | 84618f02e4116c70d9f6a1518aafb0691a29ef07 | 4,171 |
def plot_histogram(ax,values,bins,colors='r',log=False,xminmax=None):
"""
plot 1 histogram
"""
#print (type(values))
ax.hist(values, histtype="bar", bins=bins,color=colors,log=log,
alpha=0.8, density=False, range=xminmax)
# Add a small annotation.
# ax.annotate('Annotation', xy=(0.25, 4.25),
# xytext=(0.9, 0.9), textcoords=ax.transAxes,
# va="top", ha="right",
# bbox=dict(boxstyle="round", alpha=0.2),
# arrowprops=dict(
# arrowstyle="->",
# connectionstyle="angle,angleA=-95,angleB=35,rad=10"),
# )
return ax | d11e89c005275a176fd00d0e2ac5173ee8f490b1 | 4,172 |
from operator import and_
def get_repository_metadata_by_changeset_revision( trans, id, changeset_revision ):
"""Get metadata for a specified repository change set from the database."""
# Make sure there are no duplicate records, and return the single unique record for the changeset_revision. Duplicate records were somehow
# created in the past. The cause of this issue has been resolved, but we'll leave this method as is for a while longer to ensure all duplicate
# records are removed.
all_metadata_records = trans.sa_session.query( trans.model.RepositoryMetadata ) \
.filter( and_( trans.model.RepositoryMetadata.table.c.repository_id == trans.security.decode_id( id ),
trans.model.RepositoryMetadata.table.c.changeset_revision == changeset_revision ) ) \
.order_by( trans.model.RepositoryMetadata.table.c.update_time.desc() ) \
.all()
if len( all_metadata_records ) > 1:
# Delete all recrds older than the last one updated.
for repository_metadata in all_metadata_records[ 1: ]:
trans.sa_session.delete( repository_metadata )
trans.sa_session.flush()
return all_metadata_records[ 0 ]
elif all_metadata_records:
return all_metadata_records[ 0 ]
return None | 33f5da869f8fde08e2f83d7a60a708e4848664a1 | 4,175 |
def repetitions(seq: str) -> int:
"""
[Easy] https://cses.fi/problemset/task/1069/
[Solution] https://cses.fi/paste/659d805082c50ec1219667/
You are given a DNA sequence: a string consisting of characters A, C, G,
and T. Your task is to find the longest repetition in the sequence. This is
a maximum-length substring containing only one type of character.
The only input line contains a string of n characters.
Print one integer, the length of the longest repetition.
Constraints: 1 ≤ n ≤ 10^6
Example
Input: ATTCGGGA
Output: 3
"""
res, cur = 0, 0
fir = ''
for ch in seq:
if ch == fir:
cur += 1
else:
res = max(res, cur)
fir = ch
cur = 1
return max(res, cur) | 4dde2ec4a6cd6b13a54c2eafe4e8db0d87381faa | 4,177 |
def parse_headers(headers, data):
"""
Given a header structure and some data, parse the data as headers.
"""
return {k: f(v) for (k, (f, _), _), v in zip(headers, data)} | 456c2ab2d2f7832076a7263be8815b9abeec56dd | 4,178 |
def dataset_parser(value, A):
"""Parse an ImageNet record from a serialized string Tensor."""
# return value[:A.shape[0]], value[A.shape[0]:]
return value[:A.shape[0]], value | 0b07b6eec9e3e23f470970c489ad83c416d650e7 | 4,179 |
def check_rule(body, obj, obj_string, rule, only_body):
"""
Compare the argument with a rule.
"""
if only_body: # Compare only the body of the rule to the argument
retval = (body == rule[2:])
else:
retval = ((body == rule[2:]) and (obj == obj_string))
return retval | 9237da310ebcc30f623211e659ac2247efb36f69 | 4,181 |
def get_lines(filename):
"""
Returns a list of lines of a file.
Parameters
filename : str, name of control file
"""
with open(filename, "r") as f:
lines = f.readlines()
return lines | 1307b169733b50517b26ecbf0414ca3396475360 | 4,182 |
def normalize_type(type: str) -> str:
"""Normalize DataTransfer's type strings.
https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransfer-getdata
'text' -> 'text/plain'
'url' -> 'text/uri-list'
"""
if type == 'text':
return 'text/plain'
elif type == 'url':
return 'text/uri-list'
return type | 887c532218a7775ea55c6a39953ec244183af455 | 4,183 |
def filterLinesByCommentStr(lines, comment_str='#'):
"""
Filter all lines from a file.readlines output which begins with one of the
symbols in the comment_str.
"""
comment_line_idx = []
for i, line in enumerate(lines):
if line[0] in comment_str:
comment_line_idx.append(i)
for j in comment_line_idx[::-1]:
del lines[j]
return lines | 8a6ce56187afc2368ec81d11c38fe7af2eacb14f | 4,184 |
def search_trie(result, trie):
""" trie search """
if result.is_null():
return []
# output
ret_vals = []
for token_str in result:
ret_vals += trie.find(token_str)
if result.has_memory():
ret_vals = [
one_string for one_string in ret_vals
if result.is_memorized(one_string) == False
]
return ret_vals | 75ad08db7962b47ea6402e866cf4a7a9861037c9 | 4,185 |
def GetFlagFromDest(dest):
"""Returns a conventional flag name given a dest name."""
return '--' + dest.replace('_', '-') | 021ab8bca05afbb2325d865a299a2af7c3b939c9 | 4,187 |
def ganache_url(host='127.0.0.1', port='7445'):
"""Return URL for Ganache test server."""
return f"http://{host}:{port}" | 9de6e2c26c0e1235a14c8dd28040fcdfb8a36a7f | 4,188 |
def unwrap(func):
"""
Returns the object wrapped by decorators.
"""
def _is_wrapped(f):
return hasattr(f, '__wrapped__')
unwrapped_f = func
while (_is_wrapped(unwrapped_f)):
unwrapped_f = unwrapped_f.__wrapped__
return unwrapped_f | 17aa0c8cc91578fd1187784ad0396ed91c5ec9b8 | 4,189 |
from typing import Dict
def missing_keys_4(data: Dict, lprint=print, eprint=print):
""" Add keys: _max_eval_all_epoch, _max_seen_train, _max_seen_eval, _finished_experiment """
if "_finished_experiment" not in data:
lprint(f"Add keys _finished_experiment ...")
max_eval = -1
for k1, v1 in data["_eval_trace"].items():
for k2, v2 in v1.items():
max_eval += len(v2)
max_train = -1
for k1, v1 in data["_train_trace"].items():
for k2, v2 in v1.items():
max_train += len(v2)
data["_max_eval_all_epoch"] = max_eval
data["_max_train_all_epoch"] = max_train
data["_max_seen_train"] = max_seen_train = max(data["_train_trace"].keys())
data["_max_seen_eval"] = max_seen_eval = max(data["_eval_trace"].keys())
# Check if finished or no
no_tasks = len(data["_task_info"])
epochs_per_task = data["_args"]["train"]["epochs_per_task"]
should_train = no_tasks * epochs_per_task
reached_max_train = should_train == max_train + 1
same_seen = data["_max_seen_train"] == data["_max_seen_eval"]
all_final_tasks_evaluated = len(data["_eval_trace"][max_seen_eval]) == no_tasks
data["_finished_experiment"] = reached_max_train \
and same_seen and all_final_tasks_evaluated
return 1
return 0 | ad8d3f7c19dd4eefa0db465dd52b5e8dc8f0bd1e | 4,190 |
def tlam(func, tup):
"""Split tuple into arguments
"""
return func(*tup) | 0e3a9b93b36795e6c11631f8c8852aba59724f88 | 4,191 |
def priority(floors, elevator):
"""Priority for a State."""
priority = 3 - elevator
for i, floor in enumerate(floors):
priority += (3 - i) * len(floor)
return priority | b65abac24fb85f50425f2adfd4d98786b41c9a2d | 4,192 |
import re
def modify_list(result, guess, answer):
"""
Print all the key in dict.
Arguments:
result -- a list of the show pattern word.
guess -- the letter of user's guess.
answer -- the answer of word
Returns:
result -- the list of word after modified.
"""
guess = guess.lower()
answer = answer.lower()
if guess in answer:
index_list = [x.start() for x in re.finditer(guess, answer)]
for i in index_list:
result[i] = guess.upper()
else:
print("Letter '{}' is not in the word".format(guess.upper()))
print(' '.join(result))
return result | 9384ecd09659c55808a859dd613641ccac46c760 | 4,194 |
def get_N_intransit(tdur, cadence):
"""Estimates number of in-transit points for transits in a light curve.
Parameters
----------
tdur: float
Full transit duration
cadence: float
Cadence/integration time for light curve
Returns
-------
n_intransit: int
Number of flux points in each transit
"""
n_intransit = tdur//cadence
return n_intransit | d126b5590a8997b8695c1a86360421f2bf4b8357 | 4,195 |
def extract_keys(keys, dic, drop=True):
"""
Extract keys from dictionary and return a dictionary with the extracted
values.
If key is not included in the dictionary, it will also be absent from the
output.
"""
out = {}
for k in keys:
try:
if drop:
out[k] = dic.pop(k)
else:
out[k] = dic[k]
except KeyError:
pass
return out | 15a66fff5207df18d8ece4959e485068f1bd3c9c | 4,196 |
import sqlite3
def getStations(options, type):
"""Query stations by specific type ('GHCND', 'ASOS', 'COOP', 'USAF-WBAN')
"""
conn = sqlite3.connect(options.database)
c = conn.cursor()
if type == "ALL":
c.execute("select rowid, id, name, lat, lon from stations")
else:
c.execute("select rowid, id, name, lat, lon from stations where type = ?",(type,))
stations = []
for r in c:
stations.append(r)
conn.close()
return stations | 59d45a79542e68cd691cf848f3d4fe250389732c | 4,197 |
import textwrap
def inputwrap(x, ARG_indented: bool=False, ARG_end_with: str=" "):
"""Textwrapping for regular 'input' commands.
Parameters
----------
x
The text to be wrapped.
ARG_indented : bool (default is 'False')
Whether or not the textwrapped string should be indented.
ARG_end_with : str (default is ' ')
The string that the textwrapped string will end with.
Returns
-------
str
User input.
"""
if ARG_indented is True:
_input = input (textwrap.fill (x, width=70, subsequent_indent=" ") + ARG_end_with)
return _input
else:
_input = input (textwrap.fill (x, width=70) + ARG_end_with)
return _input | af0ab3b69205965b40d3e03bdcfe3148889f7080 | 4,199 |
import random
import string
def random_string_fx() -> str:
"""
Creates a 16 digit alphanumeric string. For use
with logging tests.
Returns:
16 digit alphanumeric string.
"""
result = "".join(random.sample(string.ascii_letters, 16))
return result | 835c2dc2716c6ef0ad37f5ae03cfc9dbe2e16725 | 4,200 |
def parse_date(td):
"""helper function to parse time"""
resYear = float(td.days)/364.0 # get the number of years including the the numbers after the dot
resMonth = int((resYear - int(resYear))*364/30) # get the number of months, by multiply the number after the dot by 364 and divide by 30.
resYear = int(resYear)
return str(resYear) + "y" + str(resMonth) + "m" | bda78b0968b59c13f763e51f5f15340a377eeb35 | 4,202 |
def report_cots_cv2x_bsm(bsm: dict) -> str:
"""A function to report the BSM information contained in an SPDU from a COTS C-V2X device
:param bsm: a dictionary containing BSM fields from a C-V2X SPDU
:type bsm: dict
:return: a string representation of the BSM fields
:rtype: str
"""
report = ""
for key in bsm.keys():
report += key + "\t\t\t" + str(bsm[key]) + "\n"
report += "\n"
return report | df0aa5ae4b50980088fe69cb0b776abbf0b0998d | 4,203 |
def perdict_raw(model, *args, **kwargs):
"""
Tries to call model.predict(*args, **kwargs, prediction_type="RawFormulaVal"). If that fail,
calls model.predict(*args, **kwargs)
"""
try:
return model.predict(*args, **kwargs, prediction_type="RawFormulaVal")
except TypeError:
return model.predict(*args, **kwargs) | 2ab7790c0cd48cc9b26f6e7888dd61436cb728b4 | 4,204 |
import random
def random_function(*args):
"""Picks one of its arguments uniformly at random, calls it, and returns the result.
Example usage:
>>> random_function(lambda: numpy.uniform(-2, -1), lambda: numpy.uniform(1, 2))
"""
choice = random.randint(0, len(args) - 1)
return args[choice]() | 3f8d11becc52fde5752671e3045a9c64ddfeec97 | 4,205 |
def biweekly_test_data():
""" Provides test data for the full system test when using "biweekly" time_scale."""
time_scale = "biweekly"
time_per_task = {
"Free" : 480 * 9 * 2,
"Work" : 480 * 5 * 2,
"Sleep" : 480 * 7 * 2
}
min_task_time = 60
preferences = {
"Free" : {
"avoid" : [ "Monday1,09:00AM-Monday1,05:00PM",
"Tuesday1,09:00AM-Tuesday1,05:00PM",
"Wednesday1,09:00AM-Wednesday1,05:00PM",
"Thursday1,09:00AM-Thursday1,05:00PM",
"Friday1,09:00AM-Friday1,05:00PM",
"Monday2,09:00AM-Monday2,05:00PM",
"Tuesday2,09:00AM-Tuesday2,05:00PM",
"Wednesday2,09:00AM-Wednesday2,05:00PM",
"Thursday2,09:00AM-Thursday2,05:00PM",
"Friday2,09:00AM-Friday2,05:00PM"],
"inconvenient" : [],
"neutral" : [],
"convenient" :[ "Monday1,06:00PM-Monday1,08:00PM",
"Tuesday1,06:00PM-Tuesday1,08:00PM",
"Wednesday1,06:00PM-Wednesday1,08:00PM",
"Thursday1,06:00PM-Thursday1,08:00PM",
"Friday1,06:00PM-Friday1,08:00PM",
"Monday2,06:00PM-Monday2,08:00PM",
"Tuesday2,06:00PM-Tuesday2,08:00PM",
"Wednesday2,06:00PM-Wednesday2,08:00PM",
"Thursday2,06:00PM-Thursday2,08:00PM",
"Friday2,06:00PM-Friday2,08:00PM"],
"preferred" : [],
"required" : []
},
"Work" : {
"avoid" : [],
"inconvenient" : [],
"neutral" : [],
"convenient" : [],
"preferred" : [],
"required" : [ "Monday1,09:00AM-Monday1,05:00PM",
"Tuesday1,09:00AM-Tuesday1,05:00PM",
"Wednesday1,09:00AM-Wednesday1,05:00PM",
"Thursday1,09:00AM-Thursday1,05:00PM",
"Friday1,09:00AM-Friday1,05:00PM",
"Monday2,09:00AM-Monday2,05:00PM",
"Tuesday2,09:00AM-Tuesday2,05:00PM",
"Wednesday2,09:00AM-Wednesday2,05:00PM",
"Thursday2,09:00AM-Thursday2,05:00PM",
"Friday2,09:00AM-Friday2,05:00PM"],
},
"Sleep" : {
"avoid" : [ "Monday1,09:00AM-Monday1,05:00PM",
"Tuesday1,09:00AM-Tuesday1,05:00PM",
"Wednesday1,09:00AM-Wednesday1,05:00PM",
"Thursday1,09:00AM-Thursday1,05:00PM",
"Friday1,09:00AM-Friday1,05:00PM",
"Monday2,09:00AM-Monday2,05:00PM",
"Tuesday2,09:00AM-Tuesday2,05:00PM",
"Wednesday2,09:00AM-Wednesday2,05:00PM",
"Thursday2,09:00AM-Thursday2,05:00PM",
"Friday2,09:00AM-Friday2,05:00PM"],
"inconvenient" : [],
"neutral" : [],
"convenient" : [],
"preferred" : [ "Monday1,10:00PM-Tuesday1,06:00AM",
"Tuesday1,10:00PM-Wednesday1,06:00AM",
"Wednesday1,10:00PM-Thursday1,06:00AM",
"Thursday1,10:00PM-Friday1,06:00AM",
"Friday1,10:00PM-Saturday1,06:00AM",
"Saturday1,10:00PM-Sunday1,06:00AM",
"Sunday1,10:00PM-Monday2,06:00AM",
"Monday2,10:00PM-Tuesday2,06:00AM",
"Tuesday2,10:00PM-Wednesday2,06:00AM",
"Wednesday2,10:00PM-Thursday2,06:00AM",
"Thursday2,10:00PM-Friday2,06:00AM",
"Friday2,10:00PM-Saturday2,06:00AM",
"Saturday2,10:00PM-Sunday2,06:00AM",
"Sunday2,10:00PM-Monday1,06:00AM"],
"required" : []
}
}
return time_scale, time_per_task, min_task_time, preferences | b5f354a17819133c3c29e7652f6b1132599e89b6 | 4,207 |
def is_rescue_entry(boot_entry):
"""
Determines whether the given boot entry is rescue.
:param BootEntry boot_entry: Boot entry to assess
:return: True is the entry is rescue
:rtype: bool
"""
return 'rescue' in boot_entry.kernel_image.lower() | ba456c2724c3ad4e35bef110ed8c4cc08147b42c | 4,208 |
import math
def rad_to_gon(angle: float) -> float:
"""Converts from radiant to gon (grad).
Args:
angle: Angle in rad.
Returns:
Converted angle in gon.
"""
return angle * 200 / math.pi | cbf7070a9c3a9796dfe4bffe39fdf2421f7279ed | 4,210 |
def detected(numbers, mode):
"""
Returns a Boolean result indicating whether the last member in a numeric array is the max or
min, depending on the setting.
Arguments
- numbers: an array of numbers
- mode: 'max' or 'min'
"""
call_dict = {'min': min, 'max': max}
if mode not in call_dict.keys():
print('Must specify either max or min')
return
return numbers[-1] == call_dict[mode](numbers) | b0a5b19e7d97db99769f28c4b8ce998dbe318c5b | 4,211 |