content
stringlengths 7
1.05M
|
---|
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
# Runtime: 20 ms
# Memory: 13.7 MB
if needle in haystack:
return haystack.index(needle)
else:
return -1
# One thing to take note here is if needle="" the condition will be True and str.index() will return 0
|
{
"targets": [
{
"target_name": "mtrace",
"sources": [ "mtrace.cc" ],
"include_dirs" : [
"<!(node -e \"require('nan')\")"
]
}
]
}
|
class TCPServer(object):
def process_request(self, request, client_address):
self.do_work(request, client_address)
self.shutdown_request(request)
class ThreadingMixIn:
"""Mix-in class to handle each request in a new thread."""
def process_request(self, request, client_address):
"""Start a new thread to process the request."""
t = threading.Thread(target = self.do_work, args = (request, client_address))
t.daemon = self.daemon_threads
t.start()
class ThreadingTCPServer(ThreadingMixIn, TCPServer): pass
|
class Node:
def __init__(self, data, parent=None):
self.parent = parent
self.data = data
self.left = None
self.right = None
def leftChild(self, left):
self.left = Node(left, self)
def rightChild(self, right):
self.right = Node(right, self)
def __str__(self):
return self.data
def ask(node):
ans = input(str(node.data) + " Y/N ")
if ans.upper() == 'Y':
return node.left
else:
return node.right
root = Node("Does it bark?")
root.leftChild("Dog")
root.rightChild("Cat")
response = root
while True:
response = ask(response)
if response.left == None:
new = input("Is it a " + str(response.data) + "? Y/N ")
if new.upper() == 'y':
print('Thanks for playing!')
quit()
else:
# TODO make the user ask a question to differaniate their animal to the guess
# Then add that to database for the binary tree
print("FAILURE!")
quit()
|
class Solution:
def isPalindrome(self, s: str) -> bool:
formattedString = ''.join([c.lower() for c in s if c.isalnum()])
if formattedString == formattedString[::-1]:
return True
return False
|
VERSION = (0, 0, 2, 3)
__version__ = '.'.join(map(str, VERSION))
default_app_config = 'django.chatbot.apps.DjangoChatBotConfig'
|
# Use right join to merge the movie_to_genres and pop_movies tables
genres_movies = movie_to_genres.merge(pop_movies, how='right',
left_on='movie_id',
right_on='id')
# Count the number of genres
genre_count = genres_movies.groupby('genre').agg({'id':'count'})
# Plot a bar chart of the genre_count
genre_count.plot(kind='bar')
plt.show()
|
counter = 10
sums = 1
k = 2
currLast = 1
while counter > 0:
k += 1
while sums < (k + 1) ** 2:
currLast += 1
sums += currLast
if sums == (k + 1) ** 2:
counter -= 1
print (k + 1), currLast
|
# IMPORTS
# DATA
data = []
with open("Data - Day11.txt") as file:
for line in file:
for direction in line.strip().split(","):
data.append(direction)
# GOAL 1
"""
The hexagons ("hexes") in this grid are aligned such that adjacent hexes can be found to the north,
northeast, southeast, south, southwest, and northwest:
You have the path the child process took.
Starting where he started, you need to determine the
fewest number of steps required to reach him.
(A "step" means to move from the hex you are in to any adjacent hex.)
"""
# ANSWER 1
def find_kid(data):
y = 0 # North - South
x = 0 # North West - South East
for direction in data:
if direction == "n":
y += 1
elif direction == "s":
y -= 1
elif direction == "nw":
x += 1
elif direction == "se":
x -= 1
elif direction == "ne":
x -= 1
y += 1
elif direction == "sw":
x += 1
y -= 1
return abs(y), abs(x), abs(-x-y)
location = find_kid(data)
print(f"Distance to kid: {sum(location) / 2} tiles")
# Goal 2
"""
How many steps away is the furthest he ever got from his starting position?
"""
def max_dist(data):
y = 0 # North - South
x = 0 # North West - South East
max_loc = 0
for direction in data:
if direction == "n":
y += 1
elif direction == "s":
y -= 1
elif direction == "nw":
x += 1
elif direction == "se":
x -= 1
elif direction == "ne":
x -= 1
y += 1
elif direction == "sw":
x += 1
y -= 1
max_loc = max(abs(y), abs(x), abs(-x-y), max_loc)
return max_loc
print(f"Max distance kid: {max_dist(data)}")
|
class Solution(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
lo = 0
hi = len(nums) - 1
while (lo < hi):
if nums[lo] == 0:
lo += 1
elif nums[hi] == 2:
hi -= 1
elif nums[lo] == 1 and nums[hi] == 1:
mi = lo + 1
while (mi < hi):
if nums[mi] == 2 or nums[mi] == 0:
nums[mi], nums[hi] = nums[hi], nums[mi]
break
else:
mi += 1
if mi == hi:
return
else:
nums[lo], nums[hi] = nums[hi], nums[lo]
class Solution(object):
def sortColors(self, nums):
lo, mi, hi = 0, 0, len(nums) - 1
while mi <= hi: # Nottice!: here has to be <=
if nums[mi] == 0:
nums[mi], nums[lo] = nums[lo], nums[mi]
lo += 1
mi += 1
elif nums[mi] == 2:
nums[mi], nums[hi] = nums[hi], nums[mi]
hi -= 1
else:
mi += 1
|
CONVERT_JSON_TO_YAML = {
"type": "post",
"endpoint": "/convertJSONtoYAML",
"call_message": "{type} {endpoint}",
"error_message": "{type} {endpoint} {response_code}"
}
CONVERT_RANGE_FROM_TO = {
"type": "get",
"endpoint": "/convertRangeFromTo",
"call_message": "{type} {endpoint}",
"error_message": "{type} {endpoint} {response_code}"
}
CONVERT_TEXT_FILE_FROM_TO = {
"type": "get",
"endpoint": "/convertTextFileFromTo",
"call_message": "{type} {endpoint}",
"error_message": "{type} {endpoint} {response_code}"
}
CONVERT_YAML_TO_JSON = {
"type": "post",
"endpoint": "/convertYAMLtoJSON",
"call_message": "{type} {endpoint}",
"error_message": "{type} {endpoint} {response_code}"
}
COPY_FILE = {
"type": "get",
"endpoint": "/copyFile",
"call_message": "{type} {endpoint}",
"error_message": "{type} {endpoint} {response_code}"
}
GET_FILE = {
"type": "get",
"endpoint": "/getFile",
"call_message": "{type} {endpoint}",
"error_message": "{type} {endpoint} {response_code}"
}
|
number = 0
total = 0
while number != -1:
total += number
number = float(input("Please enter a positive number (-1 to stop):"))
print(total)
|
"""
This module contains several parsers. This includes utilities for reading and converting molecular
dynamics input files to instructions for the :obj:`schnetpack.md.simulator.Simulator`. In addition, there is
a full package for parsing ORCA output files.
"""
|
def fatorial(n, show=True):
'''
Calcula o fatorial de um número.
:param n: Numero a ser calculado.
:param show: Exibe ou não o calculo. True para exibir, false para não exibir.
:return: O fatorial do número informado.
'''
print(f'O fatorial de {n} é: {n}', end=' ')
for c in range(n - 1, 0, -1):
if show == True:
print(f'x {c}', end=' ')
n = n * c
print(f'= {n}')
fatorial(5, show=True)
help(fatorial)
|
# Define your handoff handlers here
# for more information, see:
# http://docs.tethysplatform.org/en/dev/tethys_sdk/handoff.html
def csv(request, csv_url):
"""
Test Handoff handler.
"""
return 'test_app:home'
|
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# author: bigfoolliu
"""
python装饰器的使用
https://blog.csdn.net/chenhanxuan1999/article/details/103771009
http://c.biancheng.net/view/2270.html
https://www.jb51.net/article/168276.htm
"""
"""
闭包的概念:
1)函数嵌套
2)内部函数使用外部函数的变量
3)外部函数的返回值为内部函数
"""
def closure_func(name):
def func_in():
print(name)
return func_in
def closure_demo():
"""闭包示例"""
func1 = closure_func(name='hey')
func1()
"""
1.装饰器无参数的装饰器
"""
def decorator1(func):
def wrapped_func(*args, **kwargs):
"""func为被装饰的函数"""
print('begin decorate')
func()
print('end decorate')
return True
return wrapped_func
def func():
print('this is func')
@decorator1
def func1():
print('this is func1')
def decorator1_demo():
# wrapped_func = decorator1(func)
# wrapped_func()
func1()
"""
2.装饰器带参数用法
装饰器本身是一个函数,不能携带函数则功能就很受限,装饰器实现传参需要两层嵌套。
"""
def decorator2(name): # 装饰器的参数
print(f'name is: {name}')
def wrapper(func): # 传入的被装饰函数
def wrapped_func(*args, **kwargs): # 被装饰函数的参数
print('begin decorate')
func()
print('end decorate')
return wrapped_func
return wrapper
def func2():
print('this is func2')
@decorator2(name='james')
def func22():
print('this is func22')
def decorator2_demo():
# wrapper = decorator2(name='jane')
# wrapped_func = wrapper(func2)
# wrapped_func()
# 等价写法
func22()
def main():
# closure_demo()
# decorator1_demo()
decorator2_demo()
if __name__ == '__main__':
main()
|
# -*— coding: utf-8 -*-
class ServerCC:
DEV = 2
TEST = 3
RASDEV = 4
RASTEST = 5
def __rasdev(self):
url = 'https://rasdev9.zhixueyun.com'
auth_url = 'https://rasdev9.zhixueyun.com/oauth/api/v1/auth'
return (url, auth_url)
def __rastest(self):
url = 'https://rastest9.zhixueyun.com'
auth_url = 'https://rastest9.zhixueyun.com/oauth/api/v1/auth'
return (url, auth_url)
def __dev(self):
url = 'https://dev9.zhixueyun.com'
auth_url = 'https://dev9.zhixueyun.com/oauth/api/v1/auth'
return (url, auth_url)
def __test(self):
url = 'https://test9.zhixueyun.com'
auth_url = 'https://test9.zhixueyun.com/oauth/api/v1/auth'
return (url, auth_url)
def getEnv(self, env=1):
if env == self.DEV:
return self.__dev()
elif env == self.TEST:
return self.__test()
elif env == self.RASDEV:
return self.__rasdev()
elif env == self.RASTEST:
return self.__rastest()
|
#
# PySNMP MIB module ZHONE-CARD-DIAGNOSTICS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZHONE-CARD-DIAGNOSTICS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:46:50 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint", "ConstraintsIntersection")
InterfaceIndexOrZero, = mibBuilder.importSymbols("IF-MIB", "InterfaceIndexOrZero")
NotificationGroup, ObjectGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ObjectGroup", "ModuleCompliance")
ModuleIdentity, MibIdentifier, TimeTicks, iso, Unsigned32, ObjectIdentity, Integer32, NotificationType, Bits, Counter64, IpAddress, MibScalar, MibTable, MibTableRow, MibTableColumn, Gauge32, Counter32 = mibBuilder.importSymbols("SNMPv2-SMI", "ModuleIdentity", "MibIdentifier", "TimeTicks", "iso", "Unsigned32", "ObjectIdentity", "Integer32", "NotificationType", "Bits", "Counter64", "IpAddress", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Gauge32", "Counter32")
DateAndTime, DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DateAndTime", "DisplayString", "TextualConvention")
zhoneSlotIndex, zhoneCard, zhoneModules, zhoneShelfIndex = mibBuilder.importSymbols("Zhone", "zhoneSlotIndex", "zhoneCard", "zhoneModules", "zhoneShelfIndex")
ZhoneDiagAction, ZhoneDiagResult, ZhoneRowStatus = mibBuilder.importSymbols("Zhone-TC", "ZhoneDiagAction", "ZhoneDiagResult", "ZhoneRowStatus")
zhoneCardDiagnosticsModule = ModuleIdentity((1, 3, 6, 1, 4, 1, 5504, 6, 11))
zhoneCardDiagnosticsModule.setRevisions(('2010-03-05 14:05', '2009-05-14 09:39', '2009-05-07 22:37', '2009-01-12 15:36', '2008-10-22 05:28', '2006-07-24 11:28', '2001-11-14 15:28', '2001-08-30 11:21', '2001-08-27 18:14', '2001-06-28 12:01', '2001-06-26 12:40', '2000-12-12 16:30', '2000-10-19 19:45', '2000-10-17 10:32', '2000-09-12 11:07',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: zhoneCardDiagnosticsModule.setRevisionsDescriptions(('V01.00.14 change tactestresults to persistent', 'V01.00.13 add optional parameters for line test', 'V01.00.12 mtac name changes', 'add trap for mtac ringer power bus fault alarm', 'Changing the mtac name into tac and removing the name metallic.', 'V01.00.09 - Add new Mtac test controls for the Legerity Test Suite.', 'V01.00.08. Added comments for mtactestmode', 'V01.00.07 - Modify description of zhoneCardDiagType to include specific diagnostics for T3TDM card', 'V01.00.06 - Modify description of zhoneCardDiagType to include specific diagnostics for VASP card - Add DEFVAL for zhoneCardDiagType - Modify DEFVAL for zhoneCardDiagRepetition, zhoneCardDiagDuration', 'V01.00.05 - fix the 17 slot problem', 'V01.00.04 - Added zhoneMetallicTest Table entry,and also added the markups. Removed zhoneCardDiagIndex field from zhoneCardDiagObjects. ', 'V01.00.03 - move zhoneCardDiagNextIndex into table.', 'V01.00.02 - Corrected revision information.', 'VO1.00.01 - Added ZHONE_KEYWORD markup.', 'V01.00.00 - Initial Release',))
if mibBuilder.loadTexts: zhoneCardDiagnosticsModule.setLastUpdated('201003030930Z')
if mibBuilder.loadTexts: zhoneCardDiagnosticsModule.setOrganization('Zhone Technologies, Inc.')
if mibBuilder.loadTexts: zhoneCardDiagnosticsModule.setContactInfo(' Postal: Zhone Technologies, Inc. @ Zhone Way 7001 Oakport Street Oakland, CA 94621 USA Toll-Free: +1 877-ZHONE20 (+1 877-946-6320) Tel: +1-510-777-7000 Fax: +1-510-777-7001 E-mail: [email protected]')
if mibBuilder.loadTexts: zhoneCardDiagnosticsModule.setDescription('Contains the diagnostics and results available on a per card or resource basis.')
zhoneCardDiagNextTable = MibTable((1, 3, 6, 1, 4, 1, 5504, 3, 3, 5), )
if mibBuilder.loadTexts: zhoneCardDiagNextTable.setStatus('current')
if mibBuilder.loadTexts: zhoneCardDiagNextTable.setDescription('Augment table of the unit/card resource but specific to the diagnostic results information. This card contains the index to create diagnostics table entries (zhoneCardDiagEntry) which contains all the data for executing and obtaining diagnostic results.')
zhoneCardDiagNextEntry = MibTableRow((1, 3, 6, 1, 4, 1, 5504, 3, 3, 5, 1), ).setIndexNames((0, "Zhone", "zhoneShelfIndex"), (0, "Zhone", "zhoneSlotIndex"))
if mibBuilder.loadTexts: zhoneCardDiagNextEntry.setStatus('current')
if mibBuilder.loadTexts: zhoneCardDiagNextEntry.setDescription('This is the card diagnostics next index table which contains all the data for: - index for creating next zhoneCardDiagEntry.')
zhoneCardDiagNextIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 3, 3, 5, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 10))).setMaxAccess("readonly")
if mibBuilder.loadTexts: zhoneCardDiagNextIndex.setStatus('current')
if mibBuilder.loadTexts: zhoneCardDiagNextIndex.setDescription('We allow ten diagnostic requests from multiple interfaces. The diagNextIndex represents the next available diagnostic request handle for requesting a diagnostic. NOTE: this operates as a wrap-around counter starting at 1 and wrapping around to 1 after reaching 10.')
zhoneCardDiagTable = MibTable((1, 3, 6, 1, 4, 1, 5504, 3, 3, 6), )
if mibBuilder.loadTexts: zhoneCardDiagTable.setStatus('current')
if mibBuilder.loadTexts: zhoneCardDiagTable.setDescription('Augment table of the unit/card resource but specific to the diagnostic results information. This is the card diagnostics table which contains all the data for executing and obtaining diagnostic results.')
zhoneCardDiagEntry = MibTableRow((1, 3, 6, 1, 4, 1, 5504, 3, 3, 6, 1), ).setIndexNames((0, "Zhone", "zhoneShelfIndex"), (0, "Zhone", "zhoneSlotIndex"), (0, "ZHONE-CARD-DIAGNOSTICS-MIB", "zhoneCardDiagIndex"))
if mibBuilder.loadTexts: zhoneCardDiagEntry.setStatus('current')
if mibBuilder.loadTexts: zhoneCardDiagEntry.setDescription('This is the card diagnostics table which contains all the data for: - invoking diagnostics, - obtaining diagnostic results.')
zhoneCardDiagIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 3, 3, 6, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 10)))
if mibBuilder.loadTexts: zhoneCardDiagIndex.setStatus('current')
if mibBuilder.loadTexts: zhoneCardDiagIndex.setDescription('We allow ten diagnostic requests from multiple interfaces. The diagIndex represents the diagnostic request to start a diagnostic or obtain test results for a completed diagnostic. NOTE: this operates as a wrap-around counter starting at 1 and wrapping around to 1 after reaching 10.')
zhoneCardDiagType = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 3, 3, 6, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13))).clone(namedValues=NamedValues(("selftest", 1), ("supvBus", 2), ("cardEEprom", 3), ("frbus", 4), ("pcmcia", 5), ("shelfLamp", 6), ("realTimeClock", 7), ("fanTray", 8), ("shelfMonitor", 9), ("ioCard", 10), ("mezzanineCard", 11), ("backPlane", 12), ("midPlane", 13))).clone('selftest')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: zhoneCardDiagType.setStatus('current')
if mibBuilder.loadTexts: zhoneCardDiagType.setDescription("This field specifies the diagnostic to execute. The default value is 'selftest'. NOTE: not all of the individual diagnostics are available on every Zhone card type. NOTE: Zhone card types (cardZhoneType) are defined in the genCardResources.mib List of possible diagnostics: ============================ Common to all PLS cards ----------------------- selftest(1) - this diagnostic will execute all of the individual tests available on this card. Supports: diagStart, diagStop, diagRepetition. cardEEprom(3) - this diagnostic will verify the main card EEPROM checksum. Supports: diagStart, diagStop, diagRepetition. frbus(4) - this diagnostic will verify that the BAN slot card can access the Fhrame Bus by doing a loopback with 10 message of 100 bytes. Supports: diagStart, diagStop, diagRepetition. backPlane(12) - this diagnostic will verify that the BAN slot card can access the back plane by verifying the back plane EEPROM checksum. Supports: diagStart, diagStop, diagRepetition. cardZhoneType::infoServices(3) specific --------------------------------------- supvBus(2) - this diagnostic will verify that the BAN slot card can access the supervisory Bus by doing a loopback of 20 bytes. Supports: diagStart, diagStop, diagRepetition. pcmcia(5) - this diagnostic will verify that the InfoServ card can access the PCMCIA flash card I/O by doing a file create, write, and read of length 4000 bytes. Supports: diagStart, diagStop, diagRepetition. shelfLamp(6) - this diagnostic will illuminate the shelf alarm indicators for a period of 1.5 seconds. The indicators will return to their original settings after the diagnostic completes. Supports: diagStart, diagStop, diagRepetition. realTimeClk(7) - this diagnostic will verify that the real time clock increments. Supports: diagStart, diagStop, diagRepetition. fanTray(8) - this diagnostic tests that the fan tray is operational by verifying the fan tray EEPROM checksum. Supports: diagStart, diagStop, diagRepetition. shelfMonitor(9) - this diagnostic tests the shelf monitor board is operational by checking the POST status register and verifying the shelf monitor board EEPROM checksum. Supports: diagStart, diagStop, diagRepetition. midPlane(13) - this diagnostic will verify that the mid plane card is present by verifying the mid plane card EEPROM checksum. Supports: diagStart, diagStop, diagRepetition. cardZhoneType::vasp(5) specific --------------------------------- ioCard(10) - this diagnostic will verify that the I/O card is present by verifying the I/O card EEPROM checksum. Supports: diagStart, diagStop, diagRepetition. mezzanineCard(11) - this diagnostic will test that the mezzanine card is operational by verifying the mezzanine card EEPROM checksum. Supports: diagStart, diagStop, diagRepetition. cardZhoneType::t3Tdm(6) specific --------------------------------- ioCard(10) - this diagnostic will verify that the I/O card is present by verifying the I/O card EEPROM checksum. Supports: diagStart, diagStop, diagRepetition. midPlane(13) - this diagnostic will verify that the mid plane card is present by verifying the mid plane card EEPROM checksum. Supports: diagStart, diagStop, diagRepetition. cardZhoneType::ethernet(9) specific ----------------------------------- midPlane(13) - this diagnostic will verify that the mid plane card is present by verifying the mid plane card EEPROM checksum. Supports: diagStart, diagStop, diagRepetition. cardZhoneType::hdsl2(10) specific --------------------------------- ioCard(10) - this diagnostic will verify that the I/O card is present by verifying the I/O card EEPROM checksum. Supports: diagStart, diagStop, diagRepetition. mezzanineCard(11) - this diagnostic will test that the mezzanine card is operational by verifying the mezzanine card EEPROM checksum. Supports: diagStart, diagStop, diagRepetition.")
zhoneCardDiagAction = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 3, 3, 6, 1, 3), ZhoneDiagAction().clone('diagStart')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: zhoneCardDiagAction.setStatus('current')
if mibBuilder.loadTexts: zhoneCardDiagAction.setDescription('The diagAction field represents the diagnostic operation to execute. Current supported actions are as follows: diagStart : begin diagnostics and initialize results. diagStop : stop diagnostics if not yet complete. diagSuspend: suspend diagnostics at current point. diagResume : resume diagnostics from point of suspension.')
zhoneCardDiagRepetition = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 3, 3, 6, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 10)).clone(1)).setMaxAccess("readcreate")
if mibBuilder.loadTexts: zhoneCardDiagRepetition.setStatus('current')
if mibBuilder.loadTexts: zhoneCardDiagRepetition.setDescription('This field specifies the number of repetitions of diagnostics to execute. The default value is 1. NOTE: this field operates as an OR with the diagDuration field. If this field is set to non-zero then the diagnostics will be executed that amount of repetitions.')
zhoneCardDiagDuration = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 3, 3, 6, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 600)).clone(60)).setUnits('seconds').setMaxAccess("readcreate")
if mibBuilder.loadTexts: zhoneCardDiagDuration.setStatus('current')
if mibBuilder.loadTexts: zhoneCardDiagDuration.setDescription('This field specifies the duration of diagnostics to execute. The default value is 60 seconds. NOTE: this field operates as an OR with the diagRepetition field. If this field is set to non-zero then the diagnostics will be executed that amount of time.')
zhoneCardDiagResult = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 3, 3, 6, 1, 6), ZhoneDiagResult()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zhoneCardDiagResult.setStatus('current')
if mibBuilder.loadTexts: zhoneCardDiagResult.setDescription('This represents the overall diagnostic result.')
zhoneCardDiagPassCount = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 3, 3, 6, 1, 7), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zhoneCardDiagPassCount.setStatus('current')
if mibBuilder.loadTexts: zhoneCardDiagPassCount.setDescription('The number of diagnostics that executed successfully.')
zhoneCardDiagFailCount = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 3, 3, 6, 1, 8), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zhoneCardDiagFailCount.setStatus('current')
if mibBuilder.loadTexts: zhoneCardDiagFailCount.setDescription('The number of diagnostics that have failed.')
zhoneCardDiagDetails = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 3, 3, 6, 1, 9), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readonly")
if mibBuilder.loadTexts: zhoneCardDiagDetails.setStatus('current')
if mibBuilder.loadTexts: zhoneCardDiagDetails.setDescription('The failure reason, if any, for the last diagnostic which has executed. NOTE: An empty string indicates that no additional information is available.')
zhoneCardDiagStartTime = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 3, 3, 6, 1, 10), DateAndTime()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zhoneCardDiagStartTime.setStatus('current')
if mibBuilder.loadTexts: zhoneCardDiagStartTime.setDescription('Starting date and time of last selftest execution.')
zhoneCardDiagEndTime = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 3, 3, 6, 1, 11), DateAndTime()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zhoneCardDiagEndTime.setStatus('current')
if mibBuilder.loadTexts: zhoneCardDiagEndTime.setDescription('Ending date and time of last selftest execution.')
zhoneCardDiagRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 3, 3, 6, 1, 12), ZhoneRowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: zhoneCardDiagRowStatus.setStatus('current')
if mibBuilder.loadTexts: zhoneCardDiagRowStatus.setDescription('In any case where a new row can be created either via the cli or zms there will always be a proprietary mib entity of type ZhoneRowStatus which has the basic equivalence of the standard rowstatus object_id.')
zhoneTacTestTable = MibTable((1, 3, 6, 1, 4, 1, 5504, 3, 3, 7), )
if mibBuilder.loadTexts: zhoneTacTestTable.setStatus('current')
if mibBuilder.loadTexts: zhoneTacTestTable.setDescription('This table contains one entry for each tac test channel available on Zhone devices. In the initial release only the primary channel (1) is supported. Future line cards may support the second channel. If the second channel is supported the row will be populated, if the second channel is not supported a get will return no such instance. ')
zhoneTacTestEntry = MibTableRow((1, 3, 6, 1, 4, 1, 5504, 3, 3, 7, 1), ).setIndexNames((0, "ZHONE-CARD-DIAGNOSTICS-MIB", "zhoneTacIndex"))
if mibBuilder.loadTexts: zhoneTacTestEntry.setStatus('current')
if mibBuilder.loadTexts: zhoneTacTestEntry.setDescription('One row per tac test channel.')
zhoneTacIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 3, 3, 7, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2)))
if mibBuilder.loadTexts: zhoneTacIndex.setStatus('current')
if mibBuilder.loadTexts: zhoneTacIndex.setDescription('This field is the index field for the tac test channel which will be connected on the external port. This device supports a maximum of two channels, one or both channels may be supported by a device depending on which lines cards are installed.')
zhoneTacInterfaceIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 3, 3, 7, 1, 2), InterfaceIndexOrZero()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: zhoneTacInterfaceIndex.setStatus('current')
if mibBuilder.loadTexts: zhoneTacInterfaceIndex.setDescription('This field contains the InterfaceIndex of the physical line to be tested. If no line is currently being tested this value is 0. The ability of a physical line type to support tac test may vary depending on the line cards installed and the external test equipment. This field may not be modified when an tac test is in progress as indicated by a non-zero value in this field and the test mode set to one of tacModeLookIn, tacModeLookOut or tacModeBridge')
zhoneTacTestMode = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 3, 3, 7, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("mtacModeBridge", 1), ("mtacModeLookIn", 2), ("mtacModeLookOut", 3), ("mtacModeNone", 4))).clone('mtacModeNone')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: zhoneTacTestMode.setStatus('current')
if mibBuilder.loadTexts: zhoneTacTestMode.setDescription('This field is used to set the mtac test mode for a given line. The options are: mtacModeBridge - All traffic on the given line is bridged across the mtac lines mtacModeLookIn - All outbound traffic on the given line originates exclusively to the mtac lines mtacModeLookIn - All inbound traffic on the given line originates exclusively to the mtac lines mtacModeNone - No mtac test is in progress. The mtac test mode may be changed only if the zhoneInterfaceIndex is set, Otherwise it defaults to mtacModeNone. And can be changed again by setting InterfaceIndex to non-zero values. ')
zhoneTacTestId = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 3, 3, 7, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32))).clone(namedValues=NamedValues(("none", 1), ("runAllTests", 2), ("abortTest", 3), ("calibration", 4), ("foreignDCVoltage", 5), ("foreignACVoltage", 6), ("dcLoopResistance", 7), ("threeElementInsulationResistance", 8), ("fiveElementInsulationResistance", 9), ("threeElementCapacitance", 10), ("receiverOffHook", 11), ("distanceToOpen", 12), ("foreignACCurrents", 13), ("ringerEquivalencyNumber", 14), ("dtmfAndPulseDigitMeasurement", 15), ("noiseMeasurement", 16), ("signalToNoiseRatio", 17), ("arbitrarySignalToneMeasurement", 18), ("toneGeneration", 19), ("transHybridLoss", 20), ("drawAndBreakDialTone", 21), ("inwardCurrent", 22), ("dcFeedSelf", 23), ("onAndOffHookSelfTest", 24), ("ringingSelfTest", 25), ("ringingMonitor", 26), ("meteringSelfTest", 27), ("transmissionSelfTest", 28), ("dialingSelfTest", 29), ("howlerTest", 30), ("fuseTest", 31), ("readLoopAndBatteryConditions", 32))).clone('none')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: zhoneTacTestId.setStatus('current')
if mibBuilder.loadTexts: zhoneTacTestId.setDescription('This object is only valid for Tac Cards which support the new Legerity Suite of tests. This object identifies which test is to be run, or can be set to abort the current test. Test results are sent to the zhoneTacTestResultsTable. There are 3 Legerity software packages: Basic Test (VCP-BT), Advanced Test (VCP-AT), and Advanced Test Plus (VCP-ATP). We currently support Basic Test package. The following lists which tests are supported in each software package. Calibration VCP-ATP Foreign DC Voltage Test VCP-BT, VCP-AT, VCP-ATP Foreign AC VoltageTest VCP-BT, VCP-AT, VCP-ATP DC Loop Resistance Test VCP-BT, VCP-AT, VCP-ATP Three-Element Insulation Resistance Test VCP-BT, VCP-AT, VCP-ATP Five-Element Insulation Resistance Test VCP-ATP Three-Element Capacitance Test VCP-BT, VCP-AT Receiver Off-Hook Test VCP-BT, VCP-AT, VCP-ATP Distance to Open Test VCP-BT, VCP-AT Foreign AC Currents Test VCP-BT, VCP-AT Ringer Equivalency Number Test VCP-BT, VCP-AT, VCP-ATP DTMF and Pulse Digit Measurement Test VCP-BT, VCP-AT Noise Measurement Test VCP-BT, VCP-AT, VCP-ATP Signal to Noise Ratio Test VCP-ATP Arbitrary Single Tone Measurement Test VCP-ATP Tone Generation Test VCP-BT, VCP-AT Trans-Hybrid Loss Test VCP-BT, VCP-AT, VCP-ATP Draw and Break Dial Tone Test VCP-BT, VCP-AT Inward Current Test VCP-ATP DC Feed Self-Test VCP-BT, VCP-AT, VCP-ATP On/Off Hook Self-Test VCP-BT, VCP-AT, VCP-ATP Ringing Self-Test VCP-BT, VCP-AT, VCP-ATP Ringing Monitor Test VCP-BT, VCP-AT, VCP-ATP Metering Self-Test VCP-BT, VCP-AT Transmission Self-Test VCP-BT, VCP-AT, VCP-ATP Dialing Sef Test VCP-BT, VCP-AT Howler Test VCP-BT, VCP-AT Fuse Test VCP-ATP Read Loop and Battery Conditions VCP-BT, VCP-AT, VCP-ATP ')
zhoneTacTestParam1 = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 3, 3, 7, 1, 5), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: zhoneTacTestParam1.setStatus('current')
if mibBuilder.loadTexts: zhoneTacTestParam1.setDescription('Optional Test Parameter #1')
zhoneTacTestParam2 = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 3, 3, 7, 1, 6), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: zhoneTacTestParam2.setStatus('current')
if mibBuilder.loadTexts: zhoneTacTestParam2.setDescription('Optional Test Paramerter #2')
zhoneTacTestParam3 = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 3, 3, 7, 1, 7), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: zhoneTacTestParam3.setStatus('current')
if mibBuilder.loadTexts: zhoneTacTestParam3.setDescription('Optional Test Parameter #3')
zhoneTacTestParam4 = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 3, 3, 7, 1, 8), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: zhoneTacTestParam4.setStatus('current')
if mibBuilder.loadTexts: zhoneTacTestParam4.setDescription('Optional Test Parameter #4')
zhoneTacTestParam5 = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 3, 3, 7, 1, 9), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: zhoneTacTestParam5.setStatus('current')
if mibBuilder.loadTexts: zhoneTacTestParam5.setDescription('Optional Test Parameter #5 Value: 0x00000001 Force Line-Test mode')
zhoneTacTestResultsTable = MibTable((1, 3, 6, 1, 4, 1, 5504, 3, 3, 12), )
if mibBuilder.loadTexts: zhoneTacTestResultsTable.setStatus('current')
if mibBuilder.loadTexts: zhoneTacTestResultsTable.setDescription('Table of Tac Test Results objects. Indexed by same index as zhoneTacTestTable. This table is only valid for Tac cards which support the Legerity Suite of tests.')
zhoneTacTestResultsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 5504, 3, 3, 12, 1), ).setIndexNames((0, "ZHONE-CARD-DIAGNOSTICS-MIB", "zhoneTacIndex"))
if mibBuilder.loadTexts: zhoneTacTestResultsEntry.setStatus('current')
if mibBuilder.loadTexts: zhoneTacTestResultsEntry.setDescription('Entry of Test Results objects. Indexed by same index as zhoneTacTestEntry. This entry is only valid for Tac cards which support the Legerity Suite of tests.')
zhoneTacTestResultsTimeStarted = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 3, 3, 12, 1, 1), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zhoneTacTestResultsTimeStarted.setStatus('current')
if mibBuilder.loadTexts: zhoneTacTestResultsTimeStarted.setDescription('Description.')
zhoneTacTestResultsTimeEnded = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 3, 3, 12, 1, 2), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zhoneTacTestResultsTimeEnded.setStatus('current')
if mibBuilder.loadTexts: zhoneTacTestResultsTimeEnded.setDescription('Description.')
zhoneTacTestResultStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 3, 3, 12, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("testNotStarted", 1), ("testInProgress", 2), ("testCompleted", 3), ("testAborted", 4), ("testNotSupported", 5)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: zhoneTacTestResultStatus.setReference('Contains the test status.')
if mibBuilder.loadTexts: zhoneTacTestResultStatus.setStatus('current')
if mibBuilder.loadTexts: zhoneTacTestResultStatus.setDescription('Contains test results.')
zhoneTacTestResultsOutput = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 3, 3, 12, 1, 4), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 8000))).setMaxAccess("readonly")
if mibBuilder.loadTexts: zhoneTacTestResultsOutput.setStatus('current')
if mibBuilder.loadTexts: zhoneTacTestResultsOutput.setDescription("For Legerity Test Suite, results of test(s) are output to this object as one string, separated by UNIX '/n' for newline characters and terminated by the NULL character. This test results will persist until the next test is run or until tac card reboot.")
zhoneTacTestTraps = ObjectIdentity((1, 3, 6, 1, 4, 1, 5504, 3, 3, 13))
if mibBuilder.loadTexts: zhoneTacTestTraps.setStatus('current')
if mibBuilder.loadTexts: zhoneTacTestTraps.setDescription('Traps for the tac system.')
zhoneRingerTraps = ObjectIdentity((1, 3, 6, 1, 4, 1, 5504, 3, 3, 13, 0))
if mibBuilder.loadTexts: zhoneRingerTraps.setStatus('current')
if mibBuilder.loadTexts: zhoneRingerTraps.setDescription('Traps associated with ring generator. Traps should be added below - the .0 on this entry is required.')
zhoneRingerStatusAlarm = NotificationType((1, 3, 6, 1, 4, 1, 5504, 3, 3, 13, 0, 1))
if mibBuilder.loadTexts: zhoneRingerStatusAlarm.setStatus('current')
if mibBuilder.loadTexts: zhoneRingerStatusAlarm.setDescription('This trap occurs when a ring signal fails to be detected, or when it re-starts after failure.')
zhoneRingerBusFaultAlarm = NotificationType((1, 3, 6, 1, 4, 1, 5504, 3, 3, 13, 0, 2))
if mibBuilder.loadTexts: zhoneRingerBusFaultAlarm.setStatus('current')
if mibBuilder.loadTexts: zhoneRingerBusFaultAlarm.setDescription('This trap occurs when a fault in the ringer power bus is detected. Such fault may be caused by the possible shortage in the POTS or DSL line.')
zhoneCardDiagObjects = ObjectGroup((1, 3, 6, 1, 4, 1, 5504, 6, 11, 1)).setObjects(("ZHONE-CARD-DIAGNOSTICS-MIB", "zhoneCardDiagNextIndex"), ("ZHONE-CARD-DIAGNOSTICS-MIB", "zhoneCardDiagType"), ("ZHONE-CARD-DIAGNOSTICS-MIB", "zhoneCardDiagAction"), ("ZHONE-CARD-DIAGNOSTICS-MIB", "zhoneCardDiagRepetition"), ("ZHONE-CARD-DIAGNOSTICS-MIB", "zhoneCardDiagDuration"), ("ZHONE-CARD-DIAGNOSTICS-MIB", "zhoneCardDiagResult"), ("ZHONE-CARD-DIAGNOSTICS-MIB", "zhoneCardDiagPassCount"), ("ZHONE-CARD-DIAGNOSTICS-MIB", "zhoneCardDiagFailCount"), ("ZHONE-CARD-DIAGNOSTICS-MIB", "zhoneCardDiagDetails"), ("ZHONE-CARD-DIAGNOSTICS-MIB", "zhoneCardDiagStartTime"), ("ZHONE-CARD-DIAGNOSTICS-MIB", "zhoneCardDiagEndTime"), ("ZHONE-CARD-DIAGNOSTICS-MIB", "zhoneCardDiagRowStatus"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
zhoneCardDiagObjects = zhoneCardDiagObjects.setStatus('current')
if mibBuilder.loadTexts: zhoneCardDiagObjects.setDescription('This group contains objects associated with Zhone Card Diagnostics')
zhoneTacTestObjects = ObjectGroup((1, 3, 6, 1, 4, 1, 5504, 6, 11, 2)).setObjects(("ZHONE-CARD-DIAGNOSTICS-MIB", "zhoneTacInterfaceIndex"), ("ZHONE-CARD-DIAGNOSTICS-MIB", "zhoneTacTestMode"), ("ZHONE-CARD-DIAGNOSTICS-MIB", "zhoneTacTestId"), ("ZHONE-CARD-DIAGNOSTICS-MIB", "zhoneTacTestResultsTimeStarted"), ("ZHONE-CARD-DIAGNOSTICS-MIB", "zhoneTacTestResultsTimeEnded"), ("ZHONE-CARD-DIAGNOSTICS-MIB", "zhoneTacTestResultStatus"), ("ZHONE-CARD-DIAGNOSTICS-MIB", "zhoneTacTestResultsOutput"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
zhoneTacTestObjects = zhoneTacTestObjects.setStatus('current')
if mibBuilder.loadTexts: zhoneTacTestObjects.setDescription('This group contains objects associated with initiating tac tests')
mibBuilder.exportSymbols("ZHONE-CARD-DIAGNOSTICS-MIB", zhoneCardDiagDetails=zhoneCardDiagDetails, zhoneTacTestMode=zhoneTacTestMode, zhoneRingerBusFaultAlarm=zhoneRingerBusFaultAlarm, zhoneCardDiagNextIndex=zhoneCardDiagNextIndex, zhoneTacTestResultsTimeEnded=zhoneTacTestResultsTimeEnded, zhoneCardDiagEntry=zhoneCardDiagEntry, zhoneTacTestParam4=zhoneTacTestParam4, zhoneCardDiagRowStatus=zhoneCardDiagRowStatus, zhoneTacIndex=zhoneTacIndex, zhoneTacTestParam1=zhoneTacTestParam1, zhoneTacInterfaceIndex=zhoneTacInterfaceIndex, zhoneTacTestTable=zhoneTacTestTable, zhoneRingerTraps=zhoneRingerTraps, zhoneCardDiagStartTime=zhoneCardDiagStartTime, zhoneTacTestResultsOutput=zhoneTacTestResultsOutput, zhoneTacTestResultsTimeStarted=zhoneTacTestResultsTimeStarted, zhoneCardDiagResult=zhoneCardDiagResult, zhoneCardDiagPassCount=zhoneCardDiagPassCount, zhoneTacTestTraps=zhoneTacTestTraps, zhoneCardDiagTable=zhoneCardDiagTable, zhoneCardDiagObjects=zhoneCardDiagObjects, zhoneCardDiagnosticsModule=zhoneCardDiagnosticsModule, zhoneTacTestParam2=zhoneTacTestParam2, zhoneTacTestParam5=zhoneTacTestParam5, zhoneCardDiagNextTable=zhoneCardDiagNextTable, zhoneCardDiagEndTime=zhoneCardDiagEndTime, zhoneTacTestEntry=zhoneTacTestEntry, zhoneTacTestResultStatus=zhoneTacTestResultStatus, zhoneTacTestId=zhoneTacTestId, zhoneTacTestResultsEntry=zhoneTacTestResultsEntry, zhoneCardDiagDuration=zhoneCardDiagDuration, zhoneTacTestObjects=zhoneTacTestObjects, zhoneCardDiagNextEntry=zhoneCardDiagNextEntry, zhoneTacTestParam3=zhoneTacTestParam3, zhoneCardDiagFailCount=zhoneCardDiagFailCount, zhoneCardDiagIndex=zhoneCardDiagIndex, zhoneCardDiagAction=zhoneCardDiagAction, zhoneTacTestResultsTable=zhoneTacTestResultsTable, zhoneCardDiagRepetition=zhoneCardDiagRepetition, zhoneRingerStatusAlarm=zhoneRingerStatusAlarm, zhoneCardDiagType=zhoneCardDiagType, PYSNMP_MODULE_ID=zhoneCardDiagnosticsModule)
|
line = input()
party = {}
unlikes = 0
while line != "Stop":
act, guest, meal = line.split("-")
if act == "Like":
if guest in party.keys():
if meal in party[guest]:
line = input()
continue
party[guest].append(meal)
line = input()
continue
party[guest] = [meal]
elif act == "Unlike":
if guest not in party.keys():
print(f"{guest} is not at the party.")
line = input()
continue
elif meal not in party[guest]:
print(f"{guest} doesn't have the {meal} in his/her collection.")
line = input()
continue
else:
party[guest].remove(meal)
print(f"{guest} doesn't like the {meal}.")
unlikes += 1
line = input()
continue
line = input()
for member, foods in sorted(party.items(), key=lambda x: (-len(x[1]), x[0])):
if len(foods) == 0:
print(f"{member}:")
else:
print(f"{member}: {', '.join(foods)}")
print(f"Unliked meals: {unlikes}")
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__project__ = 'leetcode'
__file__ = '__init__.py'
__author__ = 'king'
__time__ = '2020/3/6 22:12'
_ooOoo_
o8888888o
88" . "88
(| -_- |)
O\ = /O
____/`---'\____
.' \\| |// `.
/ \\||| : |||// \
/ _||||| -:- |||||- \
| | \\\ - /// | |
| \_| ''\---/'' | |
\ .-\__ `-` ___/-. /
___`. .' /--.--\ `. . __
."" '< `.___\_<|>_/___.' >'"".
| | : `- \`.;`\ _ /`;.`/ - ` : | |
\ \ `-. \_ __\ /__ _/ .-` / /
======`-.____`-.___\_____/___.-`____.-'======
`=---='
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
佛祖保佑 永无BUG
"""
"""
难度:简单
输入一个正整数 target ,输出所有和为 target 的连续正整数序列(至少含有两个数)。
序列内的数字由小到大排列,不同序列按照首个数字从小到大排列。
示例 1:
输入:target = 9
输出:[[2,3,4],[4,5]]
示例 2:
输入:target = 15
输出:[[1,2,3,4,5],[4,5,6],[7,8]]
限制:
1 <= target <= 10^5
"""
class Solution(object):
def findContinuousSequence(self, target):
"""
:type target: int
:rtype: List[List[int]]
"""
l = []
ll = [i for i in range(int((target + 1) / 2))]
s = 0
for i in ll:
if sum(ll[s:s + 1]) == target:
temp = []
print(Solution().findContinuousSequence(15))
|
L=raw_input("Please Enter the length of the layer (in m): ")
A=raw_input("Please Enter the area of the wall (in m2): ")
material=raw_input("Please Enter the material of the layer: ")
if material=="glass":
type_glas=raw_input("which type of glass do you mean:window=1, wool insulation=2 ")
if int(type_glas)==1:
k=str(0.96) #W/mK
elif int(type_glas)==2:
k= str(0.04) #W/mK
else:
print("The selected glass type is not acceptable")
elif material=="brick":
k=str(0.8) #W/mK
else:
print("I do not have the properties of this material")
k=(raw_input("Please Enter the conductivity off the layer(in W/(m K): "))
print("\n you just said "+ "L= " + L+ " m "+ "A= " + A+ " m2 "+ "k= "+ k +" W/(m*K) \n")
R=float(L)/(float(k)*float(A))
print("Well the Thermal Resistnace is "+ str(R)+ " degC/W")
|
def test_user_create_public_group( # noqa
user, public_group,
):
accessible = public_group.is_accessible_by(user, mode="create")
assert accessible
def test_user_create_public_groupuser(
user, public_groupuser,
):
accessible = public_groupuser.is_accessible_by(user, mode="create")
assert not accessible # needs GroupAdmin
def test_user_create_public_stream(
user, public_stream,
):
accessible = public_stream.is_accessible_by(user, mode="create")
assert not accessible # needs system admin
def test_user_create_public_groupstream(
user, public_groupstream,
):
accessible = public_groupstream.is_accessible_by(user, mode="create")
assert not accessible # needs system admin
def test_user_create_public_streamuser(
user, public_streamuser,
):
accessible = public_streamuser.is_accessible_by(user, mode="create")
assert not accessible # needs system admin
def test_user_create_public_filter(
user, public_filter,
):
accessible = public_filter.is_accessible_by(user, mode="create")
assert accessible
def test_user_create_public_candidate_object(
user, public_candidate_object,
):
accessible = public_candidate_object.is_accessible_by(user, mode="create")
assert accessible
def test_user_create_public_source_object(
user, public_source_object,
):
accessible = public_source_object.is_accessible_by(user, mode="create")
assert accessible
def test_user_create_keck1_telescope(
user, keck1_telescope,
):
accessible = keck1_telescope.is_accessible_by(user, mode="create")
assert accessible
def test_user_create_sedm(
user, sedm,
):
accessible = sedm.is_accessible_by(user, mode="create")
assert accessible
def test_user_create_public_group_sedm_allocation(
user, public_group_sedm_allocation,
):
accessible = public_group_sedm_allocation.is_accessible_by(user, mode="create")
assert accessible
def test_user_read_public_group(
user, public_group,
):
accessible = public_group.is_accessible_by(user, mode="read")
assert accessible
def test_user_read_public_groupuser(
user, public_groupuser,
):
accessible = public_groupuser.is_accessible_by(user, mode="read")
assert accessible
def test_user_read_public_stream(
user, public_stream,
):
accessible = public_stream.is_accessible_by(user, mode="read")
assert accessible
def test_user_read_public_groupstream(
user, public_groupstream,
):
accessible = public_groupstream.is_accessible_by(user, mode="read")
assert accessible
def test_user_read_public_streamuser(
user, public_streamuser,
):
accessible = public_streamuser.is_accessible_by(user, mode="read")
assert accessible
def test_user_read_public_filter(
user, public_filter,
):
accessible = public_filter.is_accessible_by(user, mode="read")
assert accessible
def test_user_read_public_candidate_object(
user, public_candidate_object,
):
accessible = public_candidate_object.is_accessible_by(user, mode="read")
assert accessible
def test_user_read_public_source_object(
user, public_source_object,
):
accessible = public_source_object.is_accessible_by(user, mode="read")
assert accessible
def test_user_read_keck1_telescope(
user, keck1_telescope,
):
accessible = keck1_telescope.is_accessible_by(user, mode="read")
assert accessible
def test_user_read_sedm(
user, sedm,
):
accessible = sedm.is_accessible_by(user, mode="read")
assert accessible
def test_user_read_public_group_sedm_allocation(
user, public_group_sedm_allocation,
):
accessible = public_group_sedm_allocation.is_accessible_by(user, mode="read")
assert accessible
def test_user_update_public_group(
user, public_group,
):
accessible = public_group.is_accessible_by(user, mode="update")
assert not accessible # needs groupadmin
def test_user_update_public_groupuser(
user, public_groupuser,
):
accessible = public_groupuser.is_accessible_by(user, mode="update")
assert not accessible # needs groupadmin
def test_user_update_public_stream(
user, public_stream,
):
accessible = public_stream.is_accessible_by(user, mode="update")
assert not accessible # needs systemadmin
def test_user_update_public_groupstream(
user, public_groupstream,
):
accessible = public_groupstream.is_accessible_by(user, mode="update")
assert not accessible # needs systemadmin
def test_user_update_public_streamuser(
user, public_streamuser,
):
accessible = public_streamuser.is_accessible_by(user, mode="update")
assert not accessible # needs systemadmin
def test_user_update_public_filter(
user, public_filter,
):
accessible = public_filter.is_accessible_by(user, mode="update")
assert accessible
def test_user_update_public_candidate_object(
user, public_candidate_object,
):
accessible = public_candidate_object.is_accessible_by(user, mode="update")
assert accessible
def test_user_update_public_source_object(
user, public_source_object,
):
accessible = public_source_object.is_accessible_by(user, mode="update")
assert accessible
def test_user_update_keck1_telescope(
user, keck1_telescope,
):
accessible = keck1_telescope.is_accessible_by(user, mode="update")
assert not accessible # needs system admin
def test_user_update_sedm(
user, sedm,
):
accessible = sedm.is_accessible_by(user, mode="update")
assert not accessible # needs system admin
def test_user_update_public_group_sedm_allocation(
user, public_group_sedm_allocation,
):
accessible = public_group_sedm_allocation.is_accessible_by(user, mode="update")
assert accessible
def test_user_delete_public_group(
user, public_group,
):
accessible = public_group.is_accessible_by(user, mode="delete")
assert not accessible # needs group admin
def test_user_delete_public_groupuser(
user, public_groupuser,
):
accessible = public_groupuser.is_accessible_by(user, mode="delete")
assert not accessible # needs group admin
def test_user_delete_public_stream(
user, public_stream,
):
accessible = public_stream.is_accessible_by(user, mode="delete")
assert not accessible # needs system admin
def test_user_delete_public_groupstream(
user, public_groupstream,
):
accessible = public_groupstream.is_accessible_by(user, mode="delete")
assert not accessible # needs system admin
def test_user_delete_public_streamuser(
user, public_streamuser,
):
accessible = public_streamuser.is_accessible_by(user, mode="delete")
assert not accessible # needs system admin
def test_user_delete_public_filter(
user, public_filter,
):
accessible = public_filter.is_accessible_by(user, mode="delete")
assert accessible # any group member can delete a group filter for now
def test_user_delete_public_candidate_object(
user, public_candidate_object,
):
accessible = public_candidate_object.is_accessible_by(user, mode="delete")
assert accessible
def test_user_delete_public_source_object(
user, public_source_object,
):
accessible = public_source_object.is_accessible_by(user, mode="delete")
assert accessible
def test_user_delete_keck1_telescope(
user, keck1_telescope,
):
accessible = keck1_telescope.is_accessible_by(user, mode="delete")
assert not accessible # needs sysadmin
def test_user_delete_sedm(
user, sedm,
):
accessible = sedm.is_accessible_by(user, mode="delete")
assert not accessible # needs sysadmin
def test_user_delete_public_group_sedm_allocation(
user, public_group_sedm_allocation,
):
accessible = public_group_sedm_allocation.is_accessible_by(user, mode="delete")
assert accessible
def test_user_group2_create_public_group(
user_group2, public_group,
):
accessible = public_group.is_accessible_by(user_group2, mode="create")
assert accessible
def test_user_group2_create_public_groupuser(
user_group2, public_groupuser,
):
accessible = public_groupuser.is_accessible_by(user_group2, mode="create")
assert not accessible # must be in the group and be a group admin
def test_user_group2_create_public_stream(
user_group2, public_stream,
):
accessible = public_stream.is_accessible_by(user_group2, mode="create")
assert not accessible # needs sys admin
def test_user_group2_create_public_groupstream(
user_group2, public_groupstream,
):
accessible = public_groupstream.is_accessible_by(user_group2, mode="create")
assert not accessible # needs sys admin
def test_user_group2_create_public_streamuser(
user_group2, public_streamuser,
):
accessible = public_streamuser.is_accessible_by(user_group2, mode="create")
assert not accessible # needs system admin
def test_user_group2_create_public_filter(
user_group2, public_filter,
):
accessible = public_filter.is_accessible_by(user_group2, mode="create")
assert not accessible # must be in the filter's group
def test_user_group2_create_public_candidate_object(
user_group2, public_candidate_object,
):
accessible = public_candidate_object.is_accessible_by(user_group2, mode="create")
assert not accessible # must be in the filter's group
def test_user_group2_create_public_source_object(
user_group2, public_source_object,
):
accessible = public_source_object.is_accessible_by(user_group2, mode="create")
assert not accessible # must be in the source's group
def test_user_group2_create_keck1_telescope(
user_group2, keck1_telescope,
):
accessible = keck1_telescope.is_accessible_by(user_group2, mode="create")
assert accessible
def test_user_group2_create_sedm(
user_group2, sedm,
):
accessible = sedm.is_accessible_by(user_group2, mode="create")
assert accessible
def test_user_group2_create_public_group_sedm_allocation(
user_group2, public_group_sedm_allocation,
):
accessible = public_group_sedm_allocation.is_accessible_by(
user_group2, mode="create"
)
assert not accessible # must be in the allocation's group
def test_user_group2_read_public_group(
user_group2, public_group,
):
accessible = public_group.is_accessible_by(user_group2, mode="read")
assert accessible
def test_user_group2_read_public_groupuser(
user_group2, public_groupuser,
):
accessible = public_groupuser.is_accessible_by(user_group2, mode="read")
assert accessible
def test_user_group2_read_public_stream(
user_group2, public_stream,
):
accessible = public_stream.is_accessible_by(user_group2, mode="read")
assert accessible
def test_user_group2_read_public_groupstream(
user_group2, public_groupstream,
):
accessible = public_groupstream.is_accessible_by(user_group2, mode="read")
assert accessible
def test_user_group2_read_public_streamuser(
user_group2, public_streamuser,
):
accessible = public_streamuser.is_accessible_by(user_group2, mode="read")
assert accessible == public_streamuser.user.is_accessible_by(
user_group2, mode="read"
) and public_streamuser.stream.is_accessible_by(user_group2, mode="read")
def test_user_group2_read_public_filter(
user_group2, public_filter,
):
accessible = public_filter.is_accessible_by(user_group2, mode="read")
assert not accessible # must be a member of the group
def test_user_group2_read_public_candidate_object(
user_group2, public_candidate_object,
):
accessible = public_candidate_object.is_accessible_by(user_group2, mode="read")
assert not accessible # must be a member of the filter's group
def test_user_group2_read_public_source_object(
user_group2, public_source_object,
):
accessible = public_source_object.is_accessible_by(user_group2, mode="read")
assert not accessible # must be a member of the source's group
def test_user_group2_read_keck1_telescope(
user_group2, keck1_telescope,
):
accessible = keck1_telescope.is_accessible_by(user_group2, mode="read")
assert accessible
def test_user_group2_read_sedm(
user_group2, sedm,
):
accessible = sedm.is_accessible_by(user_group2, mode="read")
assert accessible
def test_user_group2_read_public_group_sedm_allocation(
user_group2, public_group_sedm_allocation,
):
accessible = public_group_sedm_allocation.is_accessible_by(user_group2, mode="read")
assert not accessible # must be a member of the allocation's group
def test_user_group2_update_public_group(
user_group2, public_group,
):
accessible = public_group.is_accessible_by(user_group2, mode="update")
assert not accessible # must be an admin of the group
def test_user_group2_update_public_groupuser(
user_group2, public_groupuser,
):
accessible = public_groupuser.is_accessible_by(user_group2, mode="update")
assert not accessible # must be an admin of the group
def test_user_group2_update_public_stream(
user_group2, public_stream,
):
accessible = public_stream.is_accessible_by(user_group2, mode="update")
assert not accessible # must be a system admin
def test_user_group2_update_public_groupstream(
user_group2, public_groupstream,
):
accessible = public_groupstream.is_accessible_by(user_group2, mode="update")
assert not accessible # must be a system admin
def test_user_group2_update_public_streamuser(
user_group2, public_streamuser,
):
accessible = public_streamuser.is_accessible_by(user_group2, mode="update")
assert not accessible # must be a system admin
def test_user_group2_update_public_filter(
user_group2, public_filter,
):
accessible = public_filter.is_accessible_by(user_group2, mode="update")
assert not accessible # must be an admin of the filter's group
def test_user_group2_update_public_candidate_object(
user_group2, public_candidate_object,
):
accessible = public_candidate_object.is_accessible_by(user_group2, mode="update")
assert not accessible # must be a member of the candidate's filter's group
def test_user_group2_update_public_source_object(
user_group2, public_source_object,
):
accessible = public_source_object.is_accessible_by(user_group2, mode="update")
assert not accessible # must be a member of the source's group
def test_user_group2_update_keck1_telescope(
user_group2, keck1_telescope,
):
accessible = keck1_telescope.is_accessible_by(user_group2, mode="update")
assert not accessible # must be system admin
def test_user_group2_update_sedm(
user_group2, sedm,
):
accessible = sedm.is_accessible_by(user_group2, mode="update")
assert not accessible # must be system admin
def test_user_group2_update_public_group_sedm_allocation(
user_group2, public_group_sedm_allocation,
):
accessible = public_group_sedm_allocation.is_accessible_by(
user_group2, mode="update"
)
assert not accessible # must be a member of the group
def test_user_group2_delete_public_group(
user_group2, public_group,
):
accessible = public_group.is_accessible_by(user_group2, mode="delete")
assert not accessible # must be a group admin
def test_user_group2_delete_public_groupuser(
user_group2, public_groupuser,
):
accessible = public_groupuser.is_accessible_by(user_group2, mode="delete")
assert not accessible # must be a group admin of the target group
def test_user_group2_delete_public_stream(
user_group2, public_stream,
):
accessible = public_stream.is_accessible_by(user_group2, mode="delete")
assert not accessible # must be a system admin
def test_user_group2_delete_public_groupstream(
user_group2, public_groupstream,
):
accessible = public_groupstream.is_accessible_by(user_group2, mode="delete")
assert not accessible # must be a system admin
def test_user_group2_delete_public_streamuser(
user_group2, public_streamuser,
):
accessible = public_streamuser.is_accessible_by(user_group2, mode="delete")
assert not accessible # must be a system admin
def test_user_group2_delete_public_filter(
user_group2, public_filter,
):
accessible = public_filter.is_accessible_by(user_group2, mode="delete")
assert not accessible # must be a group member of target group
def test_user_group2_delete_public_candidate_object(
user_group2, public_candidate_object,
):
accessible = public_candidate_object.is_accessible_by(user_group2, mode="delete")
assert not accessible # must be a member of target group
def test_user_group2_delete_public_source_object(
user_group2, public_source_object,
):
accessible = public_source_object.is_accessible_by(user_group2, mode="delete")
assert not accessible # must be a member of target group
def test_user_group2_delete_keck1_telescope(
user_group2, keck1_telescope,
):
accessible = keck1_telescope.is_accessible_by(user_group2, mode="delete")
assert not accessible # must be a system admin
def test_user_group2_delete_sedm(
user_group2, sedm,
):
accessible = sedm.is_accessible_by(user_group2, mode="delete")
assert not accessible # must be a system admin
def test_user_group2_delete_public_group_sedm_allocation(
user_group2, public_group_sedm_allocation,
):
accessible = public_group_sedm_allocation.is_accessible_by(
user_group2, mode="delete"
)
assert not accessible # must be a member of target group
def test_super_admin_user_create_public_group(
super_admin_user, public_group,
):
accessible = public_group.is_accessible_by(super_admin_user, mode="create")
assert accessible
def test_super_admin_user_create_public_groupuser(
super_admin_user, public_groupuser,
):
accessible = public_groupuser.is_accessible_by(super_admin_user, mode="create")
assert accessible
def test_super_admin_user_create_public_stream(
super_admin_user, public_stream,
):
accessible = public_stream.is_accessible_by(super_admin_user, mode="create")
assert accessible
def test_super_admin_user_create_public_groupstream(
super_admin_user, public_groupstream,
):
accessible = public_groupstream.is_accessible_by(super_admin_user, mode="create")
assert accessible
def test_super_admin_user_create_public_streamuser(
super_admin_user, public_streamuser,
):
accessible = public_streamuser.is_accessible_by(super_admin_user, mode="create")
assert accessible
def test_super_admin_user_create_public_filter(
super_admin_user, public_filter,
):
accessible = public_filter.is_accessible_by(super_admin_user, mode="create")
assert accessible
def test_super_admin_user_create_public_candidate_object(
super_admin_user, public_candidate_object,
):
accessible = public_candidate_object.is_accessible_by(
super_admin_user, mode="create"
)
assert accessible
def test_super_admin_user_create_public_source_object(
super_admin_user, public_source_object,
):
accessible = public_source_object.is_accessible_by(super_admin_user, mode="create")
assert accessible
def test_super_admin_user_create_keck1_telescope(
super_admin_user, keck1_telescope,
):
accessible = keck1_telescope.is_accessible_by(super_admin_user, mode="create")
assert accessible
def test_super_admin_user_create_sedm(
super_admin_user, sedm,
):
accessible = sedm.is_accessible_by(super_admin_user, mode="create")
assert accessible
def test_super_admin_user_create_public_group_sedm_allocation(
super_admin_user, public_group_sedm_allocation,
):
accessible = public_group_sedm_allocation.is_accessible_by(
super_admin_user, mode="create"
)
assert accessible
def test_super_admin_user_read_public_group(
super_admin_user, public_group,
):
accessible = public_group.is_accessible_by(super_admin_user, mode="read")
assert accessible
def test_super_admin_user_read_public_groupuser(
super_admin_user, public_groupuser,
):
accessible = public_groupuser.is_accessible_by(super_admin_user, mode="read")
assert accessible
def test_super_admin_user_read_public_stream(
super_admin_user, public_stream,
):
accessible = public_stream.is_accessible_by(super_admin_user, mode="read")
assert accessible
def test_super_admin_user_read_public_groupstream(
super_admin_user, public_groupstream,
):
accessible = public_groupstream.is_accessible_by(super_admin_user, mode="read")
assert accessible
def test_super_admin_user_read_public_streamuser(
super_admin_user, public_streamuser,
):
accessible = public_streamuser.is_accessible_by(super_admin_user, mode="read")
assert accessible
def test_super_admin_user_read_public_filter(
super_admin_user, public_filter,
):
accessible = public_filter.is_accessible_by(super_admin_user, mode="read")
assert accessible
def test_super_admin_user_read_public_candidate_object(
super_admin_user, public_candidate_object,
):
accessible = public_candidate_object.is_accessible_by(super_admin_user, mode="read")
assert accessible
def test_super_admin_user_read_public_source_object(
super_admin_user, public_source_object,
):
accessible = public_source_object.is_accessible_by(super_admin_user, mode="read")
assert accessible
def test_super_admin_user_read_keck1_telescope(
super_admin_user, keck1_telescope,
):
accessible = keck1_telescope.is_accessible_by(super_admin_user, mode="read")
assert accessible
def test_super_admin_user_read_sedm(
super_admin_user, sedm,
):
accessible = sedm.is_accessible_by(super_admin_user, mode="read")
assert accessible
def test_super_admin_user_read_public_group_sedm_allocation(
super_admin_user, public_group_sedm_allocation,
):
accessible = public_group_sedm_allocation.is_accessible_by(
super_admin_user, mode="read"
)
assert accessible
def test_super_admin_user_update_public_group(
super_admin_user, public_group,
):
accessible = public_group.is_accessible_by(super_admin_user, mode="update")
assert accessible
def test_super_admin_user_update_public_groupuser(
super_admin_user, public_groupuser,
):
accessible = public_groupuser.is_accessible_by(super_admin_user, mode="update")
assert accessible
def test_super_admin_user_update_public_stream(
super_admin_user, public_stream,
):
accessible = public_stream.is_accessible_by(super_admin_user, mode="update")
assert accessible
def test_super_admin_user_update_public_groupstream(
super_admin_user, public_groupstream,
):
accessible = public_groupstream.is_accessible_by(super_admin_user, mode="update")
assert accessible
def test_super_admin_user_update_public_streamuser(
super_admin_user, public_streamuser,
):
accessible = public_streamuser.is_accessible_by(super_admin_user, mode="update")
assert accessible
def test_super_admin_user_update_public_filter(
super_admin_user, public_filter,
):
accessible = public_filter.is_accessible_by(super_admin_user, mode="update")
assert accessible
def test_super_admin_user_update_public_candidate_object(
super_admin_user, public_candidate_object,
):
accessible = public_candidate_object.is_accessible_by(
super_admin_user, mode="update"
)
assert accessible
def test_super_admin_user_update_public_source_object(
super_admin_user, public_source_object,
):
accessible = public_source_object.is_accessible_by(super_admin_user, mode="update")
assert accessible
def test_super_admin_user_update_keck1_telescope(
super_admin_user, keck1_telescope,
):
accessible = keck1_telescope.is_accessible_by(super_admin_user, mode="update")
assert accessible
def test_super_admin_user_update_sedm(
super_admin_user, sedm,
):
accessible = sedm.is_accessible_by(super_admin_user, mode="update")
assert accessible
def test_super_admin_user_update_public_group_sedm_allocation(
super_admin_user, public_group_sedm_allocation,
):
accessible = public_group_sedm_allocation.is_accessible_by(
super_admin_user, mode="update"
)
assert accessible
def test_super_admin_user_delete_public_group(
super_admin_user, public_group,
):
accessible = public_group.is_accessible_by(super_admin_user, mode="delete")
assert accessible
def test_super_admin_user_delete_public_groupuser(
super_admin_user, public_groupuser,
):
accessible = public_groupuser.is_accessible_by(super_admin_user, mode="delete")
assert accessible
def test_super_admin_user_delete_public_stream(
super_admin_user, public_stream,
):
accessible = public_stream.is_accessible_by(super_admin_user, mode="delete")
assert accessible
def test_super_admin_user_delete_public_groupstream(
super_admin_user, public_groupstream,
):
accessible = public_groupstream.is_accessible_by(super_admin_user, mode="delete")
assert accessible
def test_super_admin_user_delete_public_streamuser(
super_admin_user, public_streamuser,
):
accessible = public_streamuser.is_accessible_by(super_admin_user, mode="delete")
assert accessible
def test_super_admin_user_delete_public_filter(
super_admin_user, public_filter,
):
accessible = public_filter.is_accessible_by(super_admin_user, mode="delete")
assert accessible
def test_super_admin_user_delete_public_candidate_object(
super_admin_user, public_candidate_object,
):
accessible = public_candidate_object.is_accessible_by(
super_admin_user, mode="delete"
)
assert accessible
def test_super_admin_user_delete_public_source_object(
super_admin_user, public_source_object,
):
accessible = public_source_object.is_accessible_by(super_admin_user, mode="delete")
assert accessible
def test_super_admin_user_delete_keck1_telescope(
super_admin_user, keck1_telescope,
):
accessible = keck1_telescope.is_accessible_by(super_admin_user, mode="delete")
assert accessible
def test_super_admin_user_delete_sedm(
super_admin_user, sedm,
):
accessible = sedm.is_accessible_by(super_admin_user, mode="delete")
assert accessible
def test_super_admin_user_delete_public_group_sedm_allocation(
super_admin_user, public_group_sedm_allocation,
):
accessible = public_group_sedm_allocation.is_accessible_by(
super_admin_user, mode="delete"
)
assert accessible
def test_group_admin_user_create_public_group(
group_admin_user, public_group,
):
accessible = public_group.is_accessible_by(group_admin_user, mode="create")
assert accessible
def test_group_admin_user_create_public_groupuser(
group_admin_user, public_groupuser,
):
accessible = public_groupuser.is_accessible_by(group_admin_user, mode="create")
assert accessible
def test_group_admin_user_create_public_stream(
group_admin_user, public_stream,
):
accessible = public_stream.is_accessible_by(group_admin_user, mode="create")
assert not accessible # must be system admin
def test_group_admin_user_create_public_groupstream(
group_admin_user, public_groupstream,
):
accessible = public_groupstream.is_accessible_by(group_admin_user, mode="create")
assert accessible
def test_group_admin_user_create_public_streamuser(
group_admin_user, public_streamuser,
):
accessible = public_streamuser.is_accessible_by(group_admin_user, mode="create")
assert not accessible # must be system admin
def test_group_admin_user_create_public_filter(
group_admin_user, public_filter,
):
accessible = public_filter.is_accessible_by(group_admin_user, mode="create")
assert accessible
def test_group_admin_user_create_public_candidate_object(
group_admin_user, public_candidate_object,
):
accessible = public_candidate_object.is_accessible_by(
group_admin_user, mode="create"
)
assert accessible
def test_group_admin_user_create_public_source_object(
group_admin_user, public_source_object,
):
accessible = public_source_object.is_accessible_by(group_admin_user, mode="create")
assert accessible
def test_group_admin_user_create_keck1_telescope(
group_admin_user, keck1_telescope,
):
accessible = keck1_telescope.is_accessible_by(group_admin_user, mode="create")
assert accessible
def test_group_admin_user_create_sedm(
group_admin_user, sedm,
):
accessible = sedm.is_accessible_by(group_admin_user, mode="create")
assert accessible
def test_group_admin_user_create_public_group_sedm_allocation(
group_admin_user, public_group_sedm_allocation,
):
accessible = public_group_sedm_allocation.is_accessible_by(
group_admin_user, mode="create"
)
assert accessible
def test_group_admin_user_read_public_group(
group_admin_user, public_group,
):
accessible = public_group.is_accessible_by(group_admin_user, mode="read")
assert accessible
def test_group_admin_user_read_public_groupuser(
group_admin_user, public_groupuser,
):
accessible = public_groupuser.is_accessible_by(group_admin_user, mode="read")
assert accessible
def test_group_admin_user_read_public_stream(
group_admin_user, public_stream,
):
accessible = public_stream.is_accessible_by(group_admin_user, mode="read")
assert accessible
def test_group_admin_user_read_public_groupstream(
group_admin_user, public_groupstream,
):
accessible = public_groupstream.is_accessible_by(group_admin_user, mode="read")
assert accessible
def test_group_admin_user_read_public_streamuser(
group_admin_user, public_streamuser,
):
accessible = public_streamuser.is_accessible_by(group_admin_user, mode="read")
assert accessible
def test_group_admin_user_read_public_filter(
group_admin_user, public_filter,
):
accessible = public_filter.is_accessible_by(group_admin_user, mode="read")
assert accessible
def test_group_admin_user_read_public_candidate_object(
group_admin_user, public_candidate_object,
):
accessible = public_candidate_object.is_accessible_by(group_admin_user, mode="read")
assert accessible
def test_group_admin_user_read_public_source_object(
group_admin_user, public_source_object,
):
accessible = public_source_object.is_accessible_by(group_admin_user, mode="read")
assert accessible
def test_group_admin_user_read_keck1_telescope(
group_admin_user, keck1_telescope,
):
accessible = keck1_telescope.is_accessible_by(group_admin_user, mode="read")
assert accessible
def test_group_admin_user_read_sedm(
group_admin_user, sedm,
):
accessible = sedm.is_accessible_by(group_admin_user, mode="read")
assert accessible
def test_group_admin_user_read_public_group_sedm_allocation(
group_admin_user, public_group_sedm_allocation,
):
accessible = public_group_sedm_allocation.is_accessible_by(
group_admin_user, mode="read"
)
assert accessible
def test_group_admin_user_update_public_group(
group_admin_user, public_group,
):
accessible = public_group.is_accessible_by(group_admin_user, mode="update")
assert accessible
def test_group_admin_user_update_public_groupuser(
group_admin_user, public_groupuser,
):
accessible = public_groupuser.is_accessible_by(group_admin_user, mode="update")
assert accessible
def test_group_admin_user_update_public_stream(
group_admin_user, public_stream,
):
accessible = public_stream.is_accessible_by(group_admin_user, mode="update")
assert not accessible # needs system admin
def test_group_admin_user_update_public_groupstream(
group_admin_user, public_groupstream,
):
accessible = public_groupstream.is_accessible_by(group_admin_user, mode="update")
assert accessible
def test_group_admin_user_update_public_streamuser(
group_admin_user, public_streamuser,
):
accessible = public_streamuser.is_accessible_by(group_admin_user, mode="update")
assert not accessible # needs system admin
def test_group_admin_user_update_public_filter(
group_admin_user, public_filter,
):
accessible = public_filter.is_accessible_by(group_admin_user, mode="update")
assert accessible
def test_group_admin_user_update_public_candidate_object(
group_admin_user, public_candidate_object,
):
accessible = public_candidate_object.is_accessible_by(
group_admin_user, mode="update"
)
assert accessible
def test_group_admin_user_update_public_source_object(
group_admin_user, public_source_object,
):
accessible = public_source_object.is_accessible_by(group_admin_user, mode="update")
assert accessible
def test_group_admin_user_update_keck1_telescope(
group_admin_user, keck1_telescope,
):
accessible = keck1_telescope.is_accessible_by(group_admin_user, mode="update")
assert not accessible # system admin
def test_group_admin_user_update_sedm(
group_admin_user, sedm,
):
accessible = sedm.is_accessible_by(group_admin_user, mode="update")
assert not accessible # sysadmin
def test_group_admin_user_update_public_group_sedm_allocation(
group_admin_user, public_group_sedm_allocation,
):
accessible = public_group_sedm_allocation.is_accessible_by(
group_admin_user, mode="update"
)
assert accessible
def test_group_admin_user_delete_public_group(
group_admin_user, public_group,
):
accessible = public_group.is_accessible_by(group_admin_user, mode="delete")
assert accessible
def test_group_admin_user_delete_public_groupuser(
group_admin_user, public_groupuser,
):
accessible = public_groupuser.is_accessible_by(group_admin_user, mode="delete")
assert accessible
def test_group_admin_user_delete_public_stream(
group_admin_user, public_stream,
):
accessible = public_stream.is_accessible_by(group_admin_user, mode="delete")
assert not accessible # sys admin
def test_group_admin_user_delete_public_groupstream(
group_admin_user, public_groupstream,
):
accessible = public_groupstream.is_accessible_by(group_admin_user, mode="delete")
assert accessible
def test_group_admin_user_delete_public_streamuser(
group_admin_user, public_streamuser,
):
accessible = public_streamuser.is_accessible_by(group_admin_user, mode="delete")
assert not accessible # sysadmin
def test_group_admin_user_delete_public_filter(
group_admin_user, public_filter,
):
accessible = public_filter.is_accessible_by(group_admin_user, mode="delete")
assert accessible
def test_group_admin_user_delete_public_candidate_object(
group_admin_user, public_candidate_object,
):
accessible = public_candidate_object.is_accessible_by(
group_admin_user, mode="delete"
)
assert accessible
def test_group_admin_user_delete_public_source_object(
group_admin_user, public_source_object,
):
accessible = public_source_object.is_accessible_by(group_admin_user, mode="delete")
assert accessible
def test_group_admin_user_delete_keck1_telescope(
group_admin_user, keck1_telescope,
):
accessible = keck1_telescope.is_accessible_by(group_admin_user, mode="delete")
assert not accessible # sysadmin
def test_group_admin_user_delete_sedm(
group_admin_user, sedm,
):
accessible = sedm.is_accessible_by(group_admin_user, mode="delete")
assert not accessible # sysadmin
def test_group_admin_user_delete_public_group_sedm_allocation(
group_admin_user, public_group_sedm_allocation,
):
accessible = public_group_sedm_allocation.is_accessible_by(
group_admin_user, mode="delete"
)
assert accessible
def test_user_create_public_group_taxonomy(user, public_group_taxonomy):
accessible = public_group_taxonomy.is_accessible_by(user, mode="create")
assert accessible
def test_user_create_public_taxonomy(user, public_taxonomy):
accessible = public_taxonomy.is_accessible_by(user, mode="create")
assert accessible
def test_user_read_public_group_taxonomy(user, public_group_taxonomy):
accessible = public_group_taxonomy.is_accessible_by(user, mode="read")
assert accessible
def test_user_read_public_taxonomy(user, public_taxonomy):
accessible = public_taxonomy.is_accessible_by(user, mode="read")
assert accessible
def test_user_update_public_group_taxonomy(user, public_group_taxonomy):
accessible = public_group_taxonomy.is_accessible_by(user, mode="update")
assert not accessible # must be super admin
def test_user_update_public_taxonomy(user, public_taxonomy):
accessible = public_taxonomy.is_accessible_by(user, mode="update")
assert not accessible # must be super admin
def test_user_delete_public_group_taxonomy(user, public_group_taxonomy):
accessible = public_group_taxonomy.is_accessible_by(user, mode="delete")
assert not accessible # must be group admin
def test_user_delete_public_taxonomy(user, public_taxonomy):
accessible = public_taxonomy.is_accessible_by(user, mode="delete")
assert not accessible # must be super admin
def test_user_group2_create_public_group_taxonomy(user_group2, public_group_taxonomy):
accessible = public_group_taxonomy.is_accessible_by(user_group2, mode="create")
assert (
not accessible
) # need read access on taxonomy, which is only visible to group 1
def test_user_group2_create_public_taxonomy(user_group2, public_taxonomy):
accessible = public_taxonomy.is_accessible_by(user_group2, mode="create")
assert accessible
def test_user_group2_read_public_group_taxonomy(user_group2, public_group_taxonomy):
accessible = public_group_taxonomy.is_accessible_by(user_group2, mode="read")
assert (
not accessible
) # need read access on taxonomy, which is only visible to group 1
def test_user_group2_read_public_taxonomy(user_group2, public_taxonomy):
accessible = public_taxonomy.is_accessible_by(user_group2, mode="read")
assert not accessible # need to be in group 1
def test_user_group2_update_public_group_taxonomy(user_group2, public_group_taxonomy):
accessible = public_group_taxonomy.is_accessible_by(user_group2, mode="update")
assert (
not accessible
) # user must be in one of public_taxonomy's groups and must be a group admin
def test_user_group2_update_public_taxonomy(user_group2, public_taxonomy):
accessible = public_taxonomy.is_accessible_by(user_group2, mode="update")
assert not accessible # must be a group admin of one of taxonomy's groups
def test_user_group2_delete_public_group_taxonomy(user_group2, public_group_taxonomy):
accessible = public_group_taxonomy.is_accessible_by(user_group2, mode="delete")
assert (
not accessible
) # need read access to taxonomy and must be a group admin of target group
def test_user_group2_delete_public_taxonomy(user_group2, public_taxonomy):
accessible = public_taxonomy.is_accessible_by(user_group2, mode="delete")
assert not accessible # must be sysadmin
def test_super_admin_user_create_public_group_taxonomy(
super_admin_user, public_group_taxonomy
):
accessible = public_group_taxonomy.is_accessible_by(super_admin_user, mode="create")
assert accessible
def test_super_admin_user_create_public_taxonomy(super_admin_user, public_taxonomy):
accessible = public_taxonomy.is_accessible_by(super_admin_user, mode="create")
assert accessible
def test_super_admin_user_read_public_group_taxonomy(
super_admin_user, public_group_taxonomy
):
accessible = public_group_taxonomy.is_accessible_by(super_admin_user, mode="read")
assert accessible
def test_super_admin_user_read_public_taxonomy(super_admin_user, public_taxonomy):
accessible = public_taxonomy.is_accessible_by(super_admin_user, mode="read")
assert accessible
def test_super_admin_user_update_public_group_taxonomy(
super_admin_user, public_group_taxonomy
):
accessible = public_group_taxonomy.is_accessible_by(super_admin_user, mode="update")
assert accessible
def test_super_admin_user_update_public_taxonomy(super_admin_user, public_taxonomy):
accessible = public_taxonomy.is_accessible_by(super_admin_user, mode="update")
assert accessible
def test_super_admin_user_delete_public_group_taxonomy(
super_admin_user, public_group_taxonomy
):
accessible = public_group_taxonomy.is_accessible_by(super_admin_user, mode="delete")
assert accessible
def test_super_admin_user_delete_public_taxonomy(super_admin_user, public_taxonomy):
accessible = public_taxonomy.is_accessible_by(super_admin_user, mode="delete")
assert accessible
def test_group_admin_user_create_public_group_taxonomy(
group_admin_user, public_group_taxonomy
):
accessible = public_group_taxonomy.is_accessible_by(group_admin_user, mode="create")
assert accessible
def test_group_admin_user_create_public_taxonomy(group_admin_user, public_taxonomy):
accessible = public_taxonomy.is_accessible_by(group_admin_user, mode="create")
assert accessible
def test_group_admin_user_read_public_group_taxonomy(
group_admin_user, public_group_taxonomy
):
accessible = public_group_taxonomy.is_accessible_by(group_admin_user, mode="read")
assert accessible
def test_group_admin_user_read_public_taxonomy(group_admin_user, public_taxonomy):
accessible = public_taxonomy.is_accessible_by(group_admin_user, mode="read")
assert accessible
def test_group_admin_user_update_public_group_taxonomy(
group_admin_user, public_group_taxonomy
):
accessible = public_group_taxonomy.is_accessible_by(group_admin_user, mode="update")
assert accessible
def test_group_admin_user_update_public_taxonomy(group_admin_user, public_taxonomy):
accessible = public_taxonomy.is_accessible_by(group_admin_user, mode="update")
assert not accessible # need sysadmin
def test_group_admin_user_delete_public_group_taxonomy(
group_admin_user, public_group_taxonomy
):
accessible = public_group_taxonomy.is_accessible_by(group_admin_user, mode="delete")
assert accessible
def test_group_admin_user_delete_public_taxonomy(group_admin_user, public_taxonomy):
accessible = public_taxonomy.is_accessible_by(group_admin_user, mode="delete")
assert not accessible # need sysadmin
def test_user_create_public_comment(user, public_comment):
accessible = public_comment.is_accessible_by(user, mode="create")
assert accessible
def test_user_read_public_comment(user, public_comment):
accessible = public_comment.is_accessible_by(user, mode="read")
assert accessible
def test_user_update_public_comment(user, public_comment):
accessible = public_comment.is_accessible_by(user, mode="update")
assert not accessible # must be comment author
def test_user_delete_public_comment(user, public_comment):
accessible = public_comment.is_accessible_by(user, mode="delete")
assert not accessible # must be comment author
def test_user_group2_create_public_comment(user_group2, public_comment):
accessible = public_comment.is_accessible_by(user_group2, mode="create")
assert accessible
def test_user_group2_read_public_comment(user_group2, public_comment):
accessible = public_comment.is_accessible_by(user_group2, mode="read")
assert not accessible # must be a member of the comment's target groups
def test_user_group2_update_public_comment(user_group2, public_comment):
accessible = public_comment.is_accessible_by(user_group2, mode="update")
assert not accessible # must be comment author
def test_user_group2_delete_public_comment(user_group2, public_comment):
accessible = public_comment.is_accessible_by(user_group2, mode="delete")
assert not accessible # must be comment author
def test_super_admin_user_create_public_comment(super_admin_user, public_comment):
accessible = public_comment.is_accessible_by(super_admin_user, mode="create")
assert accessible
def test_super_admin_user_read_public_comment(super_admin_user, public_comment):
accessible = public_comment.is_accessible_by(super_admin_user, mode="read")
assert accessible
def test_super_admin_user_update_public_comment(super_admin_user, public_comment):
accessible = public_comment.is_accessible_by(super_admin_user, mode="update")
assert accessible
def test_super_admin_user_delete_public_comment(super_admin_user, public_comment):
accessible = public_comment.is_accessible_by(super_admin_user, mode="delete")
assert accessible
def test_group_admin_user_create_public_comment(group_admin_user, public_comment):
accessible = public_comment.is_accessible_by(group_admin_user, mode="create")
assert accessible
def test_group_admin_user_read_public_comment(group_admin_user, public_comment):
accessible = public_comment.is_accessible_by(group_admin_user, mode="read")
assert accessible
def test_group_admin_user_update_public_comment(group_admin_user, public_comment):
accessible = public_comment.is_accessible_by(group_admin_user, mode="update")
assert not accessible # must be comment author
def test_group_admin_user_delete_public_comment(group_admin_user, public_comment):
accessible = public_comment.is_accessible_by(group_admin_user, mode="delete")
assert not accessible # must be comment author
def test_user_create_public_groupcomment(user, public_groupcomment):
accessible = public_groupcomment.is_accessible_by(user, mode="create")
assert accessible
def test_user_read_public_groupcomment(user, public_groupcomment):
accessible = public_groupcomment.is_accessible_by(user, mode="read")
assert accessible
def test_user_update_public_groupcomment(user, public_groupcomment):
accessible = public_groupcomment.is_accessible_by(user, mode="update")
assert not accessible # must be group admin
def test_user_delete_public_groupcomment(user, public_groupcomment):
accessible = public_groupcomment.is_accessible_by(user, mode="delete")
assert not accessible # must be group admin
def test_user_group2_create_public_groupcomment(user_group2, public_groupcomment):
accessible = public_groupcomment.is_accessible_by(user_group2, mode="create")
assert not accessible # must be able ot read the comment
def test_user_group2_read_public_groupcomment(user_group2, public_groupcomment):
accessible = public_groupcomment.is_accessible_by(user_group2, mode="read")
assert not accessible # must be able to read the comment
def test_user_group2_update_public_groupcomment(user_group2, public_groupcomment):
accessible = public_groupcomment.is_accessible_by(user_group2, mode="update")
assert not accessible # must be able to read the comment and be a group admin
def test_user_group2_delete_public_groupcomment(user_group2, public_groupcomment):
accessible = public_groupcomment.is_accessible_by(user_group2, mode="delete")
assert not accessible # must be able ot read the comment and be a group admin
def test_super_admin_user_create_public_groupcomment(
super_admin_user, public_groupcomment
):
accessible = public_groupcomment.is_accessible_by(super_admin_user, mode="create")
assert accessible
def test_super_admin_user_read_public_groupcomment(
super_admin_user, public_groupcomment
):
accessible = public_groupcomment.is_accessible_by(super_admin_user, mode="read")
assert accessible
def test_super_admin_user_update_public_groupcomment(
super_admin_user, public_groupcomment
):
accessible = public_groupcomment.is_accessible_by(super_admin_user, mode="update")
assert accessible
def test_super_admin_user_delete_public_groupcomment(
super_admin_user, public_groupcomment
):
accessible = public_groupcomment.is_accessible_by(super_admin_user, mode="delete")
assert accessible
def test_group_admin_user_create_public_groupcomment(
group_admin_user, public_groupcomment
):
accessible = public_groupcomment.is_accessible_by(group_admin_user, mode="create")
assert accessible
def test_group_admin_user_read_public_groupcomment(
group_admin_user, public_groupcomment
):
accessible = public_groupcomment.is_accessible_by(group_admin_user, mode="read")
assert accessible
def test_group_admin_user_update_public_groupcomment(
group_admin_user, public_groupcomment
):
accessible = public_groupcomment.is_accessible_by(group_admin_user, mode="update")
assert accessible
def test_group_admin_user_delete_public_groupcomment(
group_admin_user, public_groupcomment
):
accessible = public_groupcomment.is_accessible_by(group_admin_user, mode="delete")
assert accessible
def test_user_create_public_annotation(user, public_annotation):
accessible = public_annotation.is_accessible_by(user, mode="create")
assert accessible
def test_user_read_public_annotation(user, public_annotation):
accessible = public_annotation.is_accessible_by(user, mode="read")
assert accessible
def test_user_update_public_annotation(user, public_annotation):
accessible = public_annotation.is_accessible_by(user, mode="update")
assert not accessible # must be annotation author
def test_user_delete_public_annotation(user, public_annotation):
accessible = public_annotation.is_accessible_by(user, mode="delete")
assert not accessible # must be annotation author
def test_user_group2_create_public_annotation(user_group2, public_annotation):
accessible = public_annotation.is_accessible_by(user_group2, mode="create")
assert accessible
def test_user_group2_read_public_annotation(user_group2, public_annotation):
accessible = public_annotation.is_accessible_by(user_group2, mode="read")
assert not accessible # must be a member of the annotation's target groups
def test_user_group2_update_public_annotation(user_group2, public_annotation):
accessible = public_annotation.is_accessible_by(user_group2, mode="update")
assert not accessible # must be annotation author
def test_user_group2_delete_public_annotation(user_group2, public_annotation):
accessible = public_annotation.is_accessible_by(user_group2, mode="delete")
assert not accessible # must be annotation author
def test_super_admin_user_create_public_annotation(super_admin_user, public_annotation):
accessible = public_annotation.is_accessible_by(super_admin_user, mode="create")
assert accessible
def test_super_admin_user_read_public_annotation(super_admin_user, public_annotation):
accessible = public_annotation.is_accessible_by(super_admin_user, mode="read")
assert accessible
def test_super_admin_user_update_public_annotation(super_admin_user, public_annotation):
accessible = public_annotation.is_accessible_by(super_admin_user, mode="update")
assert accessible
def test_super_admin_user_delete_public_annotation(super_admin_user, public_annotation):
accessible = public_annotation.is_accessible_by(super_admin_user, mode="delete")
assert accessible
def test_group_admin_user_create_public_annotation(group_admin_user, public_annotation):
accessible = public_annotation.is_accessible_by(group_admin_user, mode="create")
assert accessible
def test_group_admin_user_read_public_annotation(group_admin_user, public_annotation):
accessible = public_annotation.is_accessible_by(group_admin_user, mode="read")
assert accessible
def test_group_admin_user_update_public_annotation(group_admin_user, public_annotation):
accessible = public_annotation.is_accessible_by(group_admin_user, mode="update")
assert not accessible # must be annotation author
def test_group_admin_user_delete_public_annotation(group_admin_user, public_annotation):
accessible = public_annotation.is_accessible_by(group_admin_user, mode="delete")
assert not accessible # must be annotation author
def test_user_create_public_groupannotation(user, public_groupannotation):
accessible = public_groupannotation.is_accessible_by(user, mode="create")
assert accessible
def test_user_read_public_groupannotation(user, public_groupannotation):
accessible = public_groupannotation.is_accessible_by(user, mode="read")
assert accessible
def test_user_update_public_groupannotation(user, public_groupannotation):
accessible = public_groupannotation.is_accessible_by(user, mode="update")
assert not accessible # must be group admin
def test_user_delete_public_groupannotation(user, public_groupannotation):
accessible = public_groupannotation.is_accessible_by(user, mode="delete")
assert not accessible # must be group admin
def test_user_group2_create_public_groupannotation(user_group2, public_groupannotation):
accessible = public_groupannotation.is_accessible_by(user_group2, mode="create")
assert not accessible # must be able ot read the annotation
def test_user_group2_read_public_groupannotation(user_group2, public_groupannotation):
accessible = public_groupannotation.is_accessible_by(user_group2, mode="read")
assert not accessible # must be able to read the annotation
def test_user_group2_update_public_groupannotation(user_group2, public_groupannotation):
accessible = public_groupannotation.is_accessible_by(user_group2, mode="update")
assert not accessible # must be able to read the annotation and be a group admin
def test_user_group2_delete_public_groupannotation(user_group2, public_groupannotation):
accessible = public_groupannotation.is_accessible_by(user_group2, mode="delete")
assert not accessible # must be able ot read the annotation and be a group admin
def test_super_admin_user_create_public_groupannotation(
super_admin_user, public_groupannotation
):
accessible = public_groupannotation.is_accessible_by(
super_admin_user, mode="create"
)
assert accessible
def test_super_admin_user_read_public_groupannotation(
super_admin_user, public_groupannotation
):
accessible = public_groupannotation.is_accessible_by(super_admin_user, mode="read")
assert accessible
def test_super_admin_user_update_public_groupannotation(
super_admin_user, public_groupannotation
):
accessible = public_groupannotation.is_accessible_by(
super_admin_user, mode="update"
)
assert accessible
def test_super_admin_user_delete_public_groupannotation(
super_admin_user, public_groupannotation
):
accessible = public_groupannotation.is_accessible_by(
super_admin_user, mode="delete"
)
assert accessible
def test_group_admin_user_create_public_groupannotation(
group_admin_user, public_groupannotation
):
accessible = public_groupannotation.is_accessible_by(
group_admin_user, mode="create"
)
assert accessible
def test_group_admin_user_read_public_groupannotation(
group_admin_user, public_groupannotation
):
accessible = public_groupannotation.is_accessible_by(group_admin_user, mode="read")
assert accessible
def test_group_admin_user_update_public_groupannotation(
group_admin_user, public_groupannotation
):
accessible = public_groupannotation.is_accessible_by(
group_admin_user, mode="update"
)
assert accessible
def test_group_admin_user_delete_public_groupannotation(
group_admin_user, public_groupannotation
):
accessible = public_groupannotation.is_accessible_by(
group_admin_user, mode="delete"
)
assert accessible
def test_user_create_public_classification(user, public_classification):
accessible = public_classification.is_accessible_by(user, mode="create")
assert accessible
def test_user_read_public_classification(user, public_classification):
accessible = public_classification.is_accessible_by(user, mode="read")
assert accessible
def test_user_update_public_classification(user, public_classification):
accessible = public_classification.is_accessible_by(user, mode="update")
assert not accessible # must be classification author
def test_user_delete_public_classification(user, public_classification):
accessible = public_classification.is_accessible_by(user, mode="delete")
assert not accessible # must be classification author
def test_user_group2_create_public_classification(user_group2, public_classification):
accessible = public_classification.is_accessible_by(user_group2, mode="create")
assert not accessible # need read access to underlying taxonomy
def test_user_group2_read_public_classification(user_group2, public_classification):
accessible = public_classification.is_accessible_by(user_group2, mode="read")
assert not accessible # must be a member of the classification's target groups
def test_user_group2_update_public_classification(user_group2, public_classification):
accessible = public_classification.is_accessible_by(user_group2, mode="update")
assert not accessible # must be classification author
def test_user_group2_delete_public_classification(user_group2, public_classification):
accessible = public_classification.is_accessible_by(user_group2, mode="delete")
assert not accessible # must be classification author
def test_super_admin_user_create_public_classification(
super_admin_user, public_classification
):
accessible = public_classification.is_accessible_by(super_admin_user, mode="create")
assert accessible
def test_super_admin_user_read_public_classification(
super_admin_user, public_classification
):
accessible = public_classification.is_accessible_by(super_admin_user, mode="read")
assert accessible
def test_super_admin_user_update_public_classification(
super_admin_user, public_classification
):
accessible = public_classification.is_accessible_by(super_admin_user, mode="update")
assert accessible
def test_super_admin_user_delete_public_classification(
super_admin_user, public_classification
):
accessible = public_classification.is_accessible_by(super_admin_user, mode="delete")
assert accessible
def test_group_admin_user_create_public_classification(
group_admin_user, public_classification
):
accessible = public_classification.is_accessible_by(group_admin_user, mode="create")
assert accessible
def test_group_admin_user_read_public_classification(
group_admin_user, public_classification
):
accessible = public_classification.is_accessible_by(group_admin_user, mode="read")
assert accessible
def test_group_admin_user_update_public_classification(
group_admin_user, public_classification
):
accessible = public_classification.is_accessible_by(group_admin_user, mode="update")
assert not accessible # must be classification author
def test_group_admin_user_delete_public_classification(
group_admin_user, public_classification
):
accessible = public_classification.is_accessible_by(group_admin_user, mode="delete")
assert not accessible # must be classification author
def test_user_create_public_groupclassification(user, public_groupclassification):
accessible = public_groupclassification.is_accessible_by(user, mode="create")
assert accessible
def test_user_read_public_groupclassification(user, public_groupclassification):
accessible = public_groupclassification.is_accessible_by(user, mode="read")
assert accessible
def test_user_update_public_groupclassification(user, public_groupclassification):
accessible = public_groupclassification.is_accessible_by(user, mode="update")
assert not accessible # must be group admin
def test_user_delete_public_groupclassification(user, public_groupclassification):
accessible = public_groupclassification.is_accessible_by(user, mode="delete")
assert not accessible # must be group admin
def test_user_group2_create_public_groupclassification(
user_group2, public_groupclassification
):
accessible = public_groupclassification.is_accessible_by(user_group2, mode="create")
assert not accessible # must be able ot read the classification
def test_user_group2_read_public_groupclassification(
user_group2, public_groupclassification
):
accessible = public_groupclassification.is_accessible_by(user_group2, mode="read")
assert not accessible # must be able to read the classification
def test_user_group2_update_public_groupclassification(
user_group2, public_groupclassification
):
accessible = public_groupclassification.is_accessible_by(user_group2, mode="update")
assert (
not accessible
) # must be able to read the classification and be a group admin
def test_user_group2_delete_public_groupclassification(
user_group2, public_groupclassification
):
accessible = public_groupclassification.is_accessible_by(user_group2, mode="delete")
assert (
not accessible
) # must be able ot read the classification and be a group admin
def test_super_admin_user_create_public_groupclassification(
super_admin_user, public_groupclassification
):
accessible = public_groupclassification.is_accessible_by(
super_admin_user, mode="create"
)
assert accessible
def test_super_admin_user_read_public_groupclassification(
super_admin_user, public_groupclassification
):
accessible = public_groupclassification.is_accessible_by(
super_admin_user, mode="read"
)
assert accessible
def test_super_admin_user_update_public_groupclassification(
super_admin_user, public_groupclassification
):
accessible = public_groupclassification.is_accessible_by(
super_admin_user, mode="update"
)
assert accessible
def test_super_admin_user_delete_public_groupclassification(
super_admin_user, public_groupclassification
):
accessible = public_groupclassification.is_accessible_by(
super_admin_user, mode="delete"
)
assert accessible
def test_group_admin_user_create_public_groupclassification(
group_admin_user, public_groupclassification
):
accessible = public_groupclassification.is_accessible_by(
group_admin_user, mode="create"
)
assert accessible
def test_group_admin_user_read_public_groupclassification(
group_admin_user, public_groupclassification
):
accessible = public_groupclassification.is_accessible_by(
group_admin_user, mode="read"
)
assert accessible
def test_group_admin_user_update_public_groupclassification(
group_admin_user, public_groupclassification
):
accessible = public_groupclassification.is_accessible_by(
group_admin_user, mode="update"
)
assert accessible
def test_group_admin_user_delete_public_groupclassification(
group_admin_user, public_groupclassification
):
accessible = public_groupclassification.is_accessible_by(
group_admin_user, mode="delete"
)
assert accessible
def test_user_create_public_source_photometry_point(
user, public_source_photometry_point
):
accessible = public_source_photometry_point.is_accessible_by(user, mode="create")
assert accessible
def test_user_create_public_source_groupphotometry(user, public_source_groupphotometry):
accessible = public_source_groupphotometry.is_accessible_by(user, mode="create")
assert accessible
def test_user_read_public_source_photometry_point(user, public_source_photometry_point):
accessible = public_source_photometry_point.is_accessible_by(user, mode="read")
assert accessible
def test_user_read_public_source_groupphotometry(user, public_source_groupphotometry):
accessible = public_source_groupphotometry.is_accessible_by(user, mode="read")
assert accessible
def test_user_update_public_source_photometry_point(
user, public_source_photometry_point
):
accessible = public_source_photometry_point.is_accessible_by(user, mode="update")
assert not accessible # only owner can update
def test_user_update_public_source_groupphotometry(user, public_source_groupphotometry):
accessible = public_source_groupphotometry.is_accessible_by(user, mode="update")
assert not accessible # only accessible by group admin
def test_user_delete_public_source_photometry_point(
user, public_source_photometry_point
):
accessible = public_source_photometry_point.is_accessible_by(user, mode="delete")
assert not accessible # only accessible by owner
def test_user_delete_public_source_groupphotometry(user, public_source_groupphotometry):
accessible = public_source_groupphotometry.is_accessible_by(user, mode="delete")
assert not accessible # only accessible by group admin
def test_user_group2_create_public_source_photometry_point(
user_group2, public_source_photometry_point
):
accessible = public_source_photometry_point.is_accessible_by(
user_group2, mode="create"
)
assert accessible
def test_user_group2_create_public_source_groupphotometry(
user_group2, public_source_groupphotometry
):
accessible = public_source_groupphotometry.is_accessible_by(
user_group2, mode="create"
)
assert not accessible # need read access to the underlying photometry
def test_user_group2_read_public_source_photometry_point(
user_group2, public_source_photometry_point
):
accessible = public_source_photometry_point.is_accessible_by(
user_group2, mode="read"
)
assert not accessible # must be a member of one of the photometry's groups
def test_user_group2_read_public_source_groupphotometry(
user_group2, public_source_groupphotometry
):
accessible = public_source_groupphotometry.is_accessible_by(
user_group2, mode="read"
)
assert not accessible # must be a member of one of the photometry's groups
def test_user_group2_update_public_source_photometry_point(
user_group2, public_source_photometry_point
):
accessible = public_source_photometry_point.is_accessible_by(
user_group2, mode="update"
)
assert not accessible # must be photometry owner
def test_user_group2_update_public_source_groupphotometry(
user_group2, public_source_groupphotometry
):
accessible = public_source_groupphotometry.is_accessible_by(
user_group2, mode="update"
)
assert not accessible # must be group admin
def test_user_group2_delete_public_source_photometry_point(
user_group2, public_source_photometry_point
):
accessible = public_source_photometry_point.is_accessible_by(
user_group2, mode="delete"
)
assert not accessible # must be photometry owner
def test_user_group2_delete_public_source_groupphotometry(
user_group2, public_source_groupphotometry
):
accessible = public_source_groupphotometry.is_accessible_by(
user_group2, mode="delete"
)
assert not accessible # must be group admin
def test_super_admin_user_create_public_source_photometry_point(
super_admin_user, public_source_photometry_point
):
accessible = public_source_photometry_point.is_accessible_by(
super_admin_user, mode="create"
)
assert accessible
def test_super_admin_user_create_public_source_groupphotometry(
super_admin_user, public_source_groupphotometry
):
accessible = public_source_groupphotometry.is_accessible_by(
super_admin_user, mode="create"
)
assert accessible
def test_super_admin_user_read_public_source_photometry_point(
super_admin_user, public_source_photometry_point
):
accessible = public_source_photometry_point.is_accessible_by(
super_admin_user, mode="read"
)
assert accessible
def test_super_admin_user_read_public_source_groupphotometry(
super_admin_user, public_source_groupphotometry
):
accessible = public_source_groupphotometry.is_accessible_by(
super_admin_user, mode="read"
)
assert accessible
def test_super_admin_user_update_public_source_photometry_point(
super_admin_user, public_source_photometry_point
):
accessible = public_source_photometry_point.is_accessible_by(
super_admin_user, mode="update"
)
assert accessible
def test_super_admin_user_update_public_source_groupphotometry(
super_admin_user, public_source_groupphotometry
):
accessible = public_source_groupphotometry.is_accessible_by(
super_admin_user, mode="update"
)
assert accessible
def test_super_admin_user_delete_public_source_photometry_point(
super_admin_user, public_source_photometry_point
):
accessible = public_source_photometry_point.is_accessible_by(
super_admin_user, mode="delete"
)
assert accessible
def test_super_admin_user_delete_public_source_groupphotometry(
super_admin_user, public_source_groupphotometry
):
accessible = public_source_groupphotometry.is_accessible_by(
super_admin_user, mode="delete"
)
assert accessible
def test_group_admin_user_create_public_source_photometry_point(
group_admin_user, public_source_photometry_point
):
accessible = public_source_photometry_point.is_accessible_by(
group_admin_user, mode="create"
)
assert accessible
def test_group_admin_user_create_public_source_groupphotometry(
group_admin_user, public_source_groupphotometry
):
accessible = public_source_groupphotometry.is_accessible_by(
group_admin_user, mode="create"
)
assert accessible
def test_group_admin_user_read_public_source_photometry_point(
group_admin_user, public_source_photometry_point
):
accessible = public_source_photometry_point.is_accessible_by(
group_admin_user, mode="read"
)
assert accessible
def test_group_admin_user_read_public_source_groupphotometry(
group_admin_user, public_source_groupphotometry
):
accessible = public_source_groupphotometry.is_accessible_by(
group_admin_user, mode="read"
)
assert accessible
def test_group_admin_user_update_public_source_photometry_point(
group_admin_user, public_source_photometry_point
):
accessible = public_source_photometry_point.is_accessible_by(
group_admin_user, mode="update"
)
assert not accessible # must be photometry owner
def test_group_admin_user_update_public_source_groupphotometry(
group_admin_user, public_source_groupphotometry
):
accessible = public_source_groupphotometry.is_accessible_by(
group_admin_user, mode="update"
)
assert accessible
def test_group_admin_user_delete_public_source_photometry_point(
group_admin_user, public_source_photometry_point
):
accessible = public_source_photometry_point.is_accessible_by(
group_admin_user, mode="delete"
)
assert not accessible # must be photometry owner
def test_group_admin_user_delete_public_source_groupphotometry(
group_admin_user, public_source_groupphotometry
):
accessible = public_source_groupphotometry.is_accessible_by(
group_admin_user, mode="delete"
)
assert accessible
def test_user_create_public_source_spectrum(user, public_source_spectrum):
accessible = public_source_spectrum.is_accessible_by(user, mode="create")
assert accessible
def test_user_create_public_source_groupspectrum(user, public_source_groupspectrum):
accessible = public_source_groupspectrum.is_accessible_by(user, mode="create")
assert accessible
def test_user_read_public_source_spectrum(user, public_source_spectrum):
accessible = public_source_spectrum.is_accessible_by(user, mode="read")
assert accessible
def test_user_read_public_source_groupspectrum(user, public_source_groupspectrum):
accessible = public_source_groupspectrum.is_accessible_by(user, mode="read")
assert accessible
def test_user_update_public_source_spectrum(user, public_source_spectrum):
accessible = public_source_spectrum.is_accessible_by(user, mode="update")
assert not accessible # only owner can update
def test_user_update_public_source_groupspectrum(user, public_source_groupspectrum):
accessible = public_source_groupspectrum.is_accessible_by(user, mode="update")
assert not accessible # only accessible by group admin
def test_user_delete_public_source_spectrum(user, public_source_spectrum):
accessible = public_source_spectrum.is_accessible_by(user, mode="delete")
assert not accessible # only accessible by owner
def test_user_delete_public_source_groupspectrum(user, public_source_groupspectrum):
accessible = public_source_groupspectrum.is_accessible_by(user, mode="delete")
assert not accessible # only accessible by group admin
def test_user_group2_create_public_source_spectrum(user_group2, public_source_spectrum):
accessible = public_source_spectrum.is_accessible_by(user_group2, mode="create")
assert accessible
def test_user_group2_create_public_source_groupspectrum(
user_group2, public_source_groupspectrum
):
accessible = public_source_groupspectrum.is_accessible_by(
user_group2, mode="create"
)
assert not accessible # need read access to the underlying spectrum
def test_user_group2_read_public_source_spectrum(user_group2, public_source_spectrum):
accessible = public_source_spectrum.is_accessible_by(user_group2, mode="read")
assert not accessible # must be a member of one of the spectrum's groups
def test_user_group2_read_public_source_groupspectrum(
user_group2, public_source_groupspectrum
):
accessible = public_source_groupspectrum.is_accessible_by(user_group2, mode="read")
assert not accessible # must be a member of one of the spectrum's groups
def test_user_group2_update_public_source_spectrum(user_group2, public_source_spectrum):
accessible = public_source_spectrum.is_accessible_by(user_group2, mode="update")
assert not accessible # must be spectrum owner
def test_user_group2_update_public_source_groupspectrum(
user_group2, public_source_groupspectrum
):
accessible = public_source_groupspectrum.is_accessible_by(
user_group2, mode="update"
)
assert not accessible # must be group admin
def test_user_group2_delete_public_source_spectrum(user_group2, public_source_spectrum):
accessible = public_source_spectrum.is_accessible_by(user_group2, mode="delete")
assert not accessible # must be spectrum owner
def test_user_group2_delete_public_source_groupspectrum(
user_group2, public_source_groupspectrum
):
accessible = public_source_groupspectrum.is_accessible_by(
user_group2, mode="delete"
)
assert not accessible # must be group admin
def test_super_admin_user_create_public_source_spectrum(
super_admin_user, public_source_spectrum
):
accessible = public_source_spectrum.is_accessible_by(
super_admin_user, mode="create"
)
assert accessible
def test_super_admin_user_create_public_source_groupspectrum(
super_admin_user, public_source_groupspectrum
):
accessible = public_source_groupspectrum.is_accessible_by(
super_admin_user, mode="create"
)
assert accessible
def test_super_admin_user_read_public_source_spectrum(
super_admin_user, public_source_spectrum
):
accessible = public_source_spectrum.is_accessible_by(super_admin_user, mode="read")
assert accessible
def test_super_admin_user_read_public_source_groupspectrum(
super_admin_user, public_source_groupspectrum
):
accessible = public_source_groupspectrum.is_accessible_by(
super_admin_user, mode="read"
)
assert accessible
def test_super_admin_user_update_public_source_spectrum(
super_admin_user, public_source_spectrum
):
accessible = public_source_spectrum.is_accessible_by(
super_admin_user, mode="update"
)
assert accessible
def test_super_admin_user_update_public_source_groupspectrum(
super_admin_user, public_source_groupspectrum
):
accessible = public_source_groupspectrum.is_accessible_by(
super_admin_user, mode="update"
)
assert accessible
def test_super_admin_user_delete_public_source_spectrum(
super_admin_user, public_source_spectrum
):
accessible = public_source_spectrum.is_accessible_by(
super_admin_user, mode="delete"
)
assert accessible
def test_super_admin_user_delete_public_source_groupspectrum(
super_admin_user, public_source_groupspectrum
):
accessible = public_source_groupspectrum.is_accessible_by(
super_admin_user, mode="delete"
)
assert accessible
def test_group_admin_user_create_public_source_spectrum(
group_admin_user, public_source_spectrum
):
accessible = public_source_spectrum.is_accessible_by(
group_admin_user, mode="create"
)
assert accessible
def test_group_admin_user_create_public_source_groupspectrum(
group_admin_user, public_source_groupspectrum
):
accessible = public_source_groupspectrum.is_accessible_by(
group_admin_user, mode="create"
)
assert accessible
def test_group_admin_user_read_public_source_spectrum(
group_admin_user, public_source_spectrum
):
accessible = public_source_spectrum.is_accessible_by(group_admin_user, mode="read")
assert accessible
def test_group_admin_user_read_public_source_groupspectrum(
group_admin_user, public_source_groupspectrum
):
accessible = public_source_groupspectrum.is_accessible_by(
group_admin_user, mode="read"
)
assert accessible
def test_group_admin_user_update_public_source_spectrum(
group_admin_user, public_source_spectrum
):
accessible = public_source_spectrum.is_accessible_by(
group_admin_user, mode="update"
)
assert not accessible # must be spectrum owner
def test_group_admin_user_update_public_source_groupspectrum(
group_admin_user, public_source_groupspectrum
):
accessible = public_source_groupspectrum.is_accessible_by(
group_admin_user, mode="update"
)
assert accessible
def test_group_admin_user_delete_public_source_spectrum(
group_admin_user, public_source_spectrum
):
accessible = public_source_spectrum.is_accessible_by(
group_admin_user, mode="delete"
)
assert not accessible # must be spectrum owner
def test_group_admin_user_delete_public_source_groupspectrum(
group_admin_user, public_source_groupspectrum
):
accessible = public_source_groupspectrum.is_accessible_by(
group_admin_user, mode="delete"
)
assert accessible
def test_user_create_public_source_followup_request(
user, public_source_followup_request
):
accessible = public_source_followup_request.is_accessible_by(user, mode="create")
assert accessible
def test_user_create_public_source_followup_request_target_group(
user, public_source_followup_request_target_group
):
accessible = public_source_followup_request_target_group.is_accessible_by(
user, mode="create"
)
assert accessible
def test_user_read_public_source_followup_request(user, public_source_followup_request):
accessible = public_source_followup_request.is_accessible_by(user, mode="read")
assert accessible
def test_user_read_public_source_followup_request_target_group(
user, public_source_followup_request_target_group
):
accessible = public_source_followup_request_target_group.is_accessible_by(
user, mode="read"
)
assert accessible
def test_user_update_public_source_followup_request(
user, public_source_followup_request
):
accessible = public_source_followup_request.is_accessible_by(user, mode="update")
assert accessible
def test_user_update_public_source_followup_request_target_group(
user, public_source_followup_request_target_group
):
accessible = public_source_followup_request_target_group.is_accessible_by(
user, mode="update"
)
assert (
accessible
# since this is the user that authored the request, otherwise false
)
def test_user_delete_public_source_followup_request(
user, public_source_followup_request
):
accessible = public_source_followup_request.is_accessible_by(user, mode="delete")
assert accessible
def test_user_delete_public_source_followup_request_target_group(
user, public_source_followup_request_target_group
):
accessible = public_source_followup_request_target_group.is_accessible_by(
user, mode="delete"
)
assert accessible
def test_user_group2_create_public_source_followup_request(
user_group2, public_source_followup_request
):
accessible = public_source_followup_request.is_accessible_by(
user_group2, mode="create"
)
assert not accessible # need access to the allocation
def test_user_group2_create_public_source_followup_request_target_group(
user_group2, public_source_followup_request_target_group
):
accessible = public_source_followup_request_target_group.is_accessible_by(
user_group2, mode="create"
)
assert not accessible # need read access to target group
def test_user_group2_read_public_source_followup_request(
user_group2, public_source_followup_request
):
accessible = public_source_followup_request.is_accessible_by(
user_group2, mode="read"
)
assert not accessible # not in the allocation's group
def test_user_group2_read_public_source_followup_request_target_group(
user_group2, public_source_followup_request_target_group
):
accessible = public_source_followup_request_target_group.is_accessible_by(
user_group2, mode="read"
)
assert not accessible # need to be able to read the followup request
def test_user_group2_update_public_source_followup_request(
user_group2, public_source_followup_request
):
accessible = public_source_followup_request.is_accessible_by(
user_group2, mode="update"
)
assert not accessible # must be in allocation group
def test_user_group2_update_public_source_followup_request_target_group(
user_group2, public_source_followup_request_target_group
):
accessible = public_source_followup_request_target_group.is_accessible_by(
user_group2, mode="update"
)
assert not accessible # must be followup request requester
def test_user_group2_delete_public_source_followup_request(
user_group2, public_source_followup_request
):
accessible = public_source_followup_request.is_accessible_by(
user_group2, mode="delete"
)
assert not accessible # must be in allocation group
def test_user_group2_delete_public_source_followup_request_target_group(
user_group2, public_source_followup_request_target_group
):
accessible = public_source_followup_request_target_group.is_accessible_by(
user_group2, mode="delete"
)
assert not accessible # must be followup request requester
def test_super_admin_user_create_public_source_followup_request(
super_admin_user, public_source_followup_request
):
accessible = public_source_followup_request.is_accessible_by(
super_admin_user, mode="create"
)
assert accessible
def test_super_admin_user_create_public_source_followup_request_target_group(
super_admin_user, public_source_followup_request_target_group
):
accessible = public_source_followup_request_target_group.is_accessible_by(
super_admin_user, mode="create"
)
assert accessible
def test_super_admin_user_read_public_source_followup_request(
super_admin_user, public_source_followup_request
):
accessible = public_source_followup_request.is_accessible_by(
super_admin_user, mode="read"
)
assert accessible
def test_super_admin_user_read_public_source_followup_request_target_group(
super_admin_user, public_source_followup_request_target_group
):
accessible = public_source_followup_request_target_group.is_accessible_by(
super_admin_user, mode="read"
)
assert accessible
def test_super_admin_user_update_public_source_followup_request(
super_admin_user, public_source_followup_request
):
accessible = public_source_followup_request.is_accessible_by(
super_admin_user, mode="update"
)
assert accessible
def test_super_admin_user_update_public_source_followup_request_target_group(
super_admin_user, public_source_followup_request_target_group
):
accessible = public_source_followup_request_target_group.is_accessible_by(
super_admin_user, mode="update"
)
assert accessible
def test_super_admin_user_delete_public_source_followup_request(
super_admin_user, public_source_followup_request
):
accessible = public_source_followup_request.is_accessible_by(
super_admin_user, mode="delete"
)
assert accessible
def test_super_admin_user_delete_public_source_followup_request_target_group(
super_admin_user, public_source_followup_request_target_group
):
accessible = public_source_followup_request_target_group.is_accessible_by(
super_admin_user, mode="delete"
)
assert accessible
def test_group_admin_user_create_public_source_followup_request(
group_admin_user, public_source_followup_request
):
accessible = public_source_followup_request.is_accessible_by(
group_admin_user, mode="create"
)
assert accessible
def test_group_admin_user_create_public_source_followup_request_target_group(
group_admin_user, public_source_followup_request_target_group
):
accessible = public_source_followup_request_target_group.is_accessible_by(
group_admin_user, mode="create"
)
assert not accessible # must be followup request requester
def test_group_admin_user_read_public_source_followup_request(
group_admin_user, public_source_followup_request
):
accessible = public_source_followup_request.is_accessible_by(
group_admin_user, mode="read"
)
assert accessible
def test_group_admin_user_read_public_source_followup_request_target_group(
group_admin_user, public_source_followup_request_target_group
):
accessible = public_source_followup_request_target_group.is_accessible_by(
group_admin_user, mode="read"
)
assert accessible
def test_group_admin_user_update_public_source_followup_request(
group_admin_user, public_source_followup_request
):
accessible = public_source_followup_request.is_accessible_by(
group_admin_user, mode="update"
)
assert accessible
def test_group_admin_user_update_public_source_followup_request_target_group(
group_admin_user, public_source_followup_request_target_group
):
accessible = public_source_followup_request_target_group.is_accessible_by(
group_admin_user, mode="update"
)
assert not accessible # must be requester
def test_group_admin_user_delete_public_source_followup_request(
group_admin_user, public_source_followup_request
):
accessible = public_source_followup_request.is_accessible_by(
group_admin_user, mode="delete"
)
assert accessible
def test_group_admin_user_delete_public_source_followup_request_target_group(
group_admin_user, public_source_followup_request_target_group
):
accessible = public_source_followup_request_target_group.is_accessible_by(
group_admin_user, mode="delete"
)
assert not accessible # must be requester
def test_user_create_public_thumbnail(user, public_thumbnail):
accessible = public_thumbnail.is_accessible_by(user, mode="create")
assert accessible
def test_user_read_public_thumbnail(user, public_thumbnail):
accessible = public_thumbnail.is_accessible_by(user, mode="read")
assert accessible
def test_user_update_public_thumbnail(user, public_thumbnail):
accessible = public_thumbnail.is_accessible_by(user, mode="update")
assert not accessible # restricted
def test_user_delete_public_thumbnail(user, public_thumbnail):
accessible = public_thumbnail.is_accessible_by(user, mode="delete")
assert not accessible # restricted
def test_user_group2_create_public_thumbnail(user_group2, public_thumbnail):
accessible = public_thumbnail.is_accessible_by(user_group2, mode="create")
assert accessible
def test_user_group2_read_public_thumbnail(user_group2, public_thumbnail):
accessible = public_thumbnail.is_accessible_by(user_group2, mode="read")
assert accessible
def test_user_group2_update_public_thumbnail(user_group2, public_thumbnail):
accessible = public_thumbnail.is_accessible_by(user_group2, mode="update")
assert not accessible # restricted
def test_user_group2_delete_public_thumbnail(user_group2, public_thumbnail):
accessible = public_thumbnail.is_accessible_by(user_group2, mode="delete")
assert not accessible
def test_super_admin_user_create_public_thumbnail(super_admin_user, public_thumbnail):
accessible = public_thumbnail.is_accessible_by(super_admin_user, mode="create")
assert accessible
def test_super_admin_user_read_public_thumbnail(super_admin_user, public_thumbnail):
accessible = public_thumbnail.is_accessible_by(super_admin_user, mode="read")
assert accessible
def test_super_admin_user_update_public_thumbnail(super_admin_user, public_thumbnail):
accessible = public_thumbnail.is_accessible_by(super_admin_user, mode="update")
assert accessible
def test_super_admin_user_delete_public_thumbnail(super_admin_user, public_thumbnail):
accessible = public_thumbnail.is_accessible_by(super_admin_user, mode="delete")
assert accessible
def test_group_admin_user_create_public_thumbnail(group_admin_user, public_thumbnail):
accessible = public_thumbnail.is_accessible_by(group_admin_user, mode="create")
assert accessible
def test_group_admin_user_read_public_thumbnail(group_admin_user, public_thumbnail):
accessible = public_thumbnail.is_accessible_by(group_admin_user, mode="read")
assert accessible
def test_group_admin_user_update_public_thumbnail(group_admin_user, public_thumbnail):
accessible = public_thumbnail.is_accessible_by(group_admin_user, mode="update")
assert not accessible # need sysadmin
def test_group_admin_user_delete_public_thumbnail(group_admin_user, public_thumbnail):
accessible = public_thumbnail.is_accessible_by(group_admin_user, mode="delete")
assert not accessible # need sysadmin
def test_user_create_red_transients_run(user, red_transients_run):
accessible = red_transients_run.is_accessible_by(user, mode="create")
assert accessible
def test_user_read_red_transients_run(user, red_transients_run):
accessible = red_transients_run.is_accessible_by(user, mode="read")
assert accessible
def test_user_update_red_transients_run(user, red_transients_run):
accessible = red_transients_run.is_accessible_by(user, mode="update")
assert accessible
def test_user_delete_red_transients_run(user, red_transients_run):
accessible = red_transients_run.is_accessible_by(user, mode="delete")
assert accessible
def test_user_group2_create_red_transients_run(user_group2, red_transients_run):
accessible = red_transients_run.is_accessible_by(user_group2, mode="create")
assert accessible
def test_user_group2_read_red_transients_run(user_group2, red_transients_run):
accessible = red_transients_run.is_accessible_by(user_group2, mode="read")
assert accessible
def test_user_group2_update_red_transients_run(user_group2, red_transients_run):
accessible = red_transients_run.is_accessible_by(user_group2, mode="update")
assert not accessible # must be owner
def test_user_group2_delete_red_transients_run(user_group2, red_transients_run):
accessible = red_transients_run.is_accessible_by(user_group2, mode="delete")
assert not accessible # must be owner
def test_super_admin_user_create_red_transients_run(
super_admin_user, red_transients_run
):
accessible = red_transients_run.is_accessible_by(super_admin_user, mode="create")
assert accessible
def test_super_admin_user_read_red_transients_run(super_admin_user, red_transients_run):
accessible = red_transients_run.is_accessible_by(super_admin_user, mode="read")
assert accessible
def test_super_admin_user_update_red_transients_run(
super_admin_user, red_transients_run
):
accessible = red_transients_run.is_accessible_by(super_admin_user, mode="update")
assert accessible
def test_super_admin_user_delete_red_transients_run(
super_admin_user, red_transients_run
):
accessible = red_transients_run.is_accessible_by(super_admin_user, mode="delete")
assert accessible
def test_group_admin_user_create_red_transients_run(
group_admin_user, red_transients_run
):
accessible = red_transients_run.is_accessible_by(group_admin_user, mode="create")
assert accessible
def test_group_admin_user_read_red_transients_run(group_admin_user, red_transients_run):
accessible = red_transients_run.is_accessible_by(group_admin_user, mode="read")
assert accessible
def test_group_admin_user_update_red_transients_run(
group_admin_user, red_transients_run
):
accessible = red_transients_run.is_accessible_by(group_admin_user, mode="update")
assert not accessible # must be owner
def test_group_admin_user_delete_red_transients_run(
group_admin_user, red_transients_run
):
accessible = red_transients_run.is_accessible_by(group_admin_user, mode="delete")
assert not accessible # must be owner
def test_user_create_problematic_assignment(user, problematic_assignment):
accessible = problematic_assignment.is_accessible_by(user, mode="create")
assert accessible
def test_user_read_problematic_assignment(user, problematic_assignment):
accessible = problematic_assignment.is_accessible_by(user, mode="read")
assert accessible
def test_user_update_problematic_assignment(user, problematic_assignment):
accessible = problematic_assignment.is_accessible_by(user, mode="update")
assert accessible
def test_user_delete_problematic_assignment(user, problematic_assignment):
accessible = problematic_assignment.is_accessible_by(user, mode="delete")
assert accessible
def test_user_group2_create_problematic_assignment(user_group2, problematic_assignment):
accessible = problematic_assignment.is_accessible_by(user_group2, mode="create")
assert accessible
def test_user_group2_read_problematic_assignment(user_group2, problematic_assignment):
accessible = problematic_assignment.is_accessible_by(user_group2, mode="read")
assert accessible
def test_user_group2_update_problematic_assignment(user_group2, problematic_assignment):
accessible = problematic_assignment.is_accessible_by(user_group2, mode="update")
assert accessible
def test_user_group2_delete_problematic_assignment(user_group2, problematic_assignment):
accessible = problematic_assignment.is_accessible_by(user_group2, mode="delete")
assert accessible
def test_super_admin_user_create_problematic_assignment(
super_admin_user, problematic_assignment
):
accessible = problematic_assignment.is_accessible_by(
super_admin_user, mode="create"
)
assert accessible
def test_super_admin_user_read_problematic_assignment(
super_admin_user, problematic_assignment
):
accessible = problematic_assignment.is_accessible_by(super_admin_user, mode="read")
assert accessible
def test_super_admin_user_update_problematic_assignment(
super_admin_user, problematic_assignment
):
accessible = problematic_assignment.is_accessible_by(
super_admin_user, mode="update"
)
assert accessible
def test_super_admin_user_delete_problematic_assignment(
super_admin_user, problematic_assignment
):
accessible = problematic_assignment.is_accessible_by(
super_admin_user, mode="delete"
)
assert accessible
def test_group_admin_user_create_problematic_assignment(
group_admin_user, problematic_assignment
):
accessible = problematic_assignment.is_accessible_by(
group_admin_user, mode="create"
)
assert accessible
def test_group_admin_user_read_problematic_assignment(
group_admin_user, problematic_assignment
):
accessible = problematic_assignment.is_accessible_by(group_admin_user, mode="read")
assert accessible
def test_group_admin_user_update_problematic_assignment(
group_admin_user, problematic_assignment
):
accessible = problematic_assignment.is_accessible_by(
group_admin_user, mode="update"
)
assert accessible
def test_group_admin_user_delete_problematic_assignment(
group_admin_user, problematic_assignment
):
accessible = problematic_assignment.is_accessible_by(
group_admin_user, mode="delete"
)
assert accessible
# These tests are commented out because they require email / twilio clients
# to be set up, which is not done by default.
"""
def test_user_create_invitation(user, invitation):
accessible = invitation.is_accessible_by(user, mode="create")
assert accessible
def test_user_read_invitation(user, invitation):
accessible = invitation.is_accessible_by(user, mode="read")
assert accessible
def test_user_update_invitation(user, invitation):
accessible = invitation.is_accessible_by(user, mode="update")
assert accessible
def test_user_delete_invitation(user, invitation):
accessible = invitation.is_accessible_by(user, mode="delete")
assert accessible
def test_user_group2_create_invitation(user_group2, invitation):
accessible = invitation.is_accessible_by(user_group2, mode="create")
assert accessible
def test_user_group2_read_invitation(user_group2, invitation):
accessible = invitation.is_accessible_by(user_group2, mode="read")
assert not accessible # must be the inviter
def test_user_group2_update_invitation(user_group2, invitation):
accessible = invitation.is_accessible_by(user_group2, mode="update")
assert not accessible # must be the inviter
def test_user_group2_delete_invitation(user_group2, invitation):
accessible = invitation.is_accessible_by(user_group2, mode="delete")
assert not accessible # must be the inviter
def test_super_admin_user_create_invitation(super_admin_user, invitation):
accessible = invitation.is_accessible_by(super_admin_user, mode="create")
assert accessible
def test_super_admin_user_read_invitation(super_admin_user, invitation):
accessible = invitation.is_accessible_by(super_admin_user, mode="read")
assert accessible
def test_super_admin_user_update_invitation(super_admin_user, invitation):
accessible = invitation.is_accessible_by(super_admin_user, mode="update")
assert accessible
def test_super_admin_user_delete_invitation(super_admin_user, invitation):
accessible = invitation.is_accessible_by(super_admin_user, mode="delete")
assert accessible
def test_group_admin_user_create_invitation(group_admin_user, invitation):
accessible = invitation.is_accessible_by(group_admin_user, mode="create")
assert accessible
def test_group_admin_user_read_invitation(group_admin_user, invitation):
accessible = invitation.is_accessible_by(group_admin_user, mode="read")
assert not accessible # must be the inviter
def test_group_admin_user_update_invitation(group_admin_user, invitation):
accessible = invitation.is_accessible_by(group_admin_user, mode="update")
assert not accessible # must be the inviter
def test_group_admin_user_delete_invitation(group_admin_user, invitation):
accessible = invitation.is_accessible_by(group_admin_user, mode="delete")
assert not accessible # must be the inviter
def test_user_create_public_source_notification(user, public_source_notification):
accessible = public_source_notification.is_accessible_by(user, mode="create")
assert accessible
def test_user_read_public_source_notification(user, public_source_notification):
accessible = public_source_notification.is_accessible_by(user, mode="read")
assert accessible
def test_user_update_public_source_notification(user, public_source_notification):
accessible = public_source_notification.is_accessible_by(user, mode="update")
assert not accessible # must be sender
def test_user_delete_public_source_notification(user, public_source_notification):
accessible = public_source_notification.is_accessible_by(user, mode="delete")
assert not accessible # must be sender
def test_user_group2_create_public_source_notification(user_group2, public_source_notification):
accessible = public_source_notification.is_accessible_by(user_group2, mode="create")
assert not accessible # must be member of all target groups
def test_user_group2_read_public_source_notification(user_group2, public_source_notification):
accessible = public_source_notification.is_accessible_by(user_group2, mode="read")
assert not accessible # must be a member of at least one target group
def test_user_group2_update_public_source_notification(user_group2, public_source_notification):
accessible = public_source_notification.is_accessible_by(user_group2, mode="update")
assert not accessible # must be notification sender
def test_user_group2_delete_public_source_notification(user_group2, public_source_notification):
accessible = public_source_notification.is_accessible_by(user_group2, mode="delete")
assert not accessible # must be notification sender
def test_super_admin_user_create_public_source_notification(super_admin_user, public_source_notification):
accessible = public_source_notification.is_accessible_by(super_admin_user, mode="create")
assert accessible
def test_super_admin_user_read_public_source_notification(super_admin_user, public_source_notification):
accessible = public_source_notification.is_accessible_by(super_admin_user, mode="read")
assert accessible
def test_super_admin_user_update_public_source_notification(super_admin_user, public_source_notification):
accessible = public_source_notification.is_accessible_by(super_admin_user, mode="update")
assert accessible
def test_super_admin_user_delete_public_source_notification(super_admin_user, public_source_notification):
accessible = public_source_notification.is_accessible_by(super_admin_user, mode="delete")
assert accessible
def test_group_admin_user_create_public_source_notification(group_admin_user, public_source_notification):
accessible = public_source_notification.is_accessible_by(group_admin_user, mode="create")
assert accessible
def test_group_admin_user_read_public_source_notification(group_admin_user, public_source_notification):
accessible = public_source_notification.is_accessible_by(group_admin_user, mode="read")
assert accessible
def test_group_admin_user_update_public_source_notification(group_admin_user, public_source_notification):
accessible = public_source_notification.is_accessible_by(group_admin_user, mode="update")
assert accessible # must be notification sender
def test_group_admin_user_delete_public_source_notification(group_admin_user, public_source_notification):
accessible = public_source_notification.is_accessible_by(group_admin_user, mode="delete")
assert accessible # must be notification sender
"""
def test_user_create_user_notification(user, user_notification):
accessible = user_notification.is_accessible_by(user, mode="create")
assert accessible
def test_user_read_user_notification(user, user_notification):
accessible = user_notification.is_accessible_by(user, mode="read")
assert accessible
def test_user_update_user_notification(user, user_notification):
accessible = user_notification.is_accessible_by(user, mode="update")
assert accessible
def test_user_delete_user_notification(user, user_notification):
accessible = user_notification.is_accessible_by(user, mode="delete")
assert accessible
def test_user_group2_create_user_notification(user_group2, user_notification):
accessible = user_notification.is_accessible_by(user_group2, mode="create")
assert accessible
def test_user_group2_read_user_notification(user_group2, user_notification):
accessible = user_notification.is_accessible_by(user_group2, mode="read")
assert not accessible # must be target user
def test_user_group2_update_user_notification(user_group2, user_notification):
accessible = user_notification.is_accessible_by(user_group2, mode="update")
assert not accessible # must be target user
def test_user_group2_delete_user_notification(user_group2, user_notification):
accessible = user_notification.is_accessible_by(user_group2, mode="delete")
assert not accessible # must be target user
def test_super_admin_user_create_user_notification(super_admin_user, user_notification):
accessible = user_notification.is_accessible_by(super_admin_user, mode="create")
assert accessible
def test_super_admin_user_read_user_notification(super_admin_user, user_notification):
accessible = user_notification.is_accessible_by(super_admin_user, mode="read")
assert accessible
def test_super_admin_user_update_user_notification(super_admin_user, user_notification):
accessible = user_notification.is_accessible_by(super_admin_user, mode="update")
assert accessible
def test_super_admin_user_delete_user_notification(super_admin_user, user_notification):
accessible = user_notification.is_accessible_by(super_admin_user, mode="delete")
assert accessible
def test_group_admin_user_create_user_notification(group_admin_user, user_notification):
accessible = user_notification.is_accessible_by(group_admin_user, mode="create")
assert accessible
def test_group_admin_user_read_user_notification(group_admin_user, user_notification):
accessible = user_notification.is_accessible_by(group_admin_user, mode="read")
assert not accessible # must be target user
def test_group_admin_user_update_user_notification(group_admin_user, user_notification):
accessible = user_notification.is_accessible_by(group_admin_user, mode="update")
assert not accessible # must be target user
def test_group_admin_user_delete_user_notification(group_admin_user, user_notification):
accessible = user_notification.is_accessible_by(group_admin_user, mode="delete")
assert not accessible # must be target user
|
#define a value holder function
# => True
def switch(value):
switch.value=value
return True
#define matching case function
# => True or False
def case(*args):
return any((arg == switch.value for arg in args))
# Switch example:
print("Describe a number from range:")
for n in range(0,10):
print(n, end=" ", flush=True)
print()
# Ask for a number and analyze
x=input("n:")
n=int(x)
while switch(n):
if case(0):
print ("n is zero;")
break
if case(1, 4, 9):
print ("n is a perfect square;")
break
if case(2):
print ("n is an even number;")
if case(2, 3, 5, 7):
print ("n is a prime number;")
break
if case(6, 8):
print ("n is an even number;")
break
print ("Only single-digit numbers are allowed.")
|
# Recursive solution (TLE)
class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
def util(s, wordDict):
if s == "":
return True
for i in range(1, len(s)+1):
if str(s[:i]) in wordDict and util(s[i:], wordDict):
# print(s[:i], s[i:])
return True
return False
d = {}
for word in wordDict:
if word not in d:
d[word] = 1
return util(s, d)
# Memoization (Accepted, 14%)
class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
def util(s, wordDict, wordbreaks):
if s == "":
return True
if s in wordbreaks:
return wordbreaks[str(s)]
for i in range(1, len(s)+1):
if str(s[:i]) in wordDict and util(s[i:], wordDict, wordbreaks):
# print(s[:i], s[i:])
wordbreaks[str(s[i:])] = True
return True
wordbreaks[str(s)] = False
return False
d = {}
wordbreaks = {}
for word in wordDict:
if word not in d:
d[word] = 1
return util(s, d, wordbreaks)
# DP (80%)
class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
n = len(s)
dp = [False]*(n+1)
dp[0] = True
for i in range(1, n+1):
for w in wordDict:
if dp[i-len(w)] and s[i-len(w):i] == w:
dp[i] = True
return dp[-1]
|
# Copyright 2019 AUI, Inc. Washington DC, USA
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#####################################################
def uvmodelfit(xds, field=None, spw=None, timerange=None, uvrange=None, antenna=None, scan=None, niter=5, comptype='p', sourcepar=[1, 0, 0],
varypar=[]):
"""
.. todo::
This function is not yet implemented
Fit simple analytic source component models directly to visibility data
Parameters
----------
xds : xarray.core.dataset.Dataset
input Visibility Dataset
field : int
field selection. If None, use all fields
spw : int
spw selection. If None, use all spws
timerange : int
time selection. If None, use all times
uvrange : int
uvrange selection. If None, use all uvranges
antenna : int
antenna selection. If None, use all antennas
scan : int
scan selection. If None, use all scans
niter : int
number of fitting iteractions to execute
comptype : str
component type (p=point source, g=ell. gauss. d=ell. disk)
sourcepar : list
starting fuess (flux, xoff, yoff, bmajaxrat, bpa)
varypar : list
parameters that may vary in the fit
Returns
-------
xarray.core.dataset.Dataset
New Visibility Dataset with updated data
"""
return {}
|
#Tendo NElem como uma Lista de 25 elementos do tipo Inteiro, desenvolva um
#programa que faça a leitura de N elementos para essa Lista sendo pedido ao
#utilizador o valor de N (num máximo de 25). De seguida desenvolva:
#a) Uma função para fazer a apresentação dos elementos dessa lista.
#b) uma função que calcule o menor elemento.
#c) uma função para calcular a média dos elementos da lista.
#d) uma função que devolva o somatório de todos os números positivos da lista.
#e) uma função que devolva o somatório de todos os números negativos da lista.
#f) uma função que receba como argumento, para além da lista, um inteiro e
#devolva quantas vezes é que esse número aparece na lista.
#g) uma função que devolva o somatório de todos os números pares da lista.
def criarLista():
lista=[None]*10
for i in range(0,10):
try:
lista[i]=int(input('Indique o %dº número: ' %(i+1)))
except ValueError:
print('Não foi inserido um número.')
return lista
def menorElem(lista):
men=lista[2]
for i in range(0,10):
if lista[i]<men:
men=lista[i]
print('O menor número é %d.' %men)
def media(lista):
med=0
for i in range(0,10):
med+=lista[i]
med=med/10
print('A média é %.2f.' %med)
def somaPOS(lista):
soma=0
for i in range(0,10):
if i>0:
soma+=lista[i]
print('A soma de todos os números positivos deu %d.' %soma)
def somaNEG(lista):
soma=0
for i in range(0,10):
if i<0:
soma+=lista[i]
print('A soma de todos os números negativos deu %d.' %soma)
def search(lista):
try:
num=int(input('Indique pelo número que quer procurar: '))
except ValueError:
print('Não foi inserido um número.')
cont=0
for i in range(0,10):
if lista[i] == num:
cont+=1
print('A todo foram encontrados %d \'%d\'.' %(cont, num))
def somaPARES(lista):
soma=0
for i in range(0,10):
if lista[i]%2==0:
soma+=lista[i]
print('A soma de todos os números pares deu %d.' %soma)
def menu():
opc=str(input('Indique a opção que deseja:\n'
'a) Uma função para fazer a apresentação dos elementos dessa lista.\n'
'b) uma função que calcule o menor elemento.\n'
'c) uma função para calcular a média dos elementos da lista.\n'
'd) uma função que devolva o somatório de todos os números positivos da lista.\n'
'e) uma função que devolva o somatório de todos os números negativos da lista.\n'
'f) uma função que receba como argumento, para além da lista, um inteiro e\n'
' devolva quantas vezes é que esse número aparece na lista.\n'
'g) uma função que devolva o somatório de todos os números pares da lista.\n'
'Opção: '))
while opc not in 'AaBbCcDdEeFfGg':
opc=str(input('Opção Inválida!\nOpção: '))
if opc in 'Aa':
print(lista)
print('-' * 80)
menu()
elif opc in 'Bb':
menorElem(lista)
print('-' * 80)
menu()
elif opc in 'Cc':
media(lista)
print('-' * 80)
menu()
elif opc in 'Dd':
somaPOS(lista)
print('-' * 80)
menu()
elif opc in 'Ee':
somaNEG(lista)
print('-' * 80)
menu()
elif opc in 'Ff':
search(lista)
print('-' * 80)
menu()
elif opc in 'Gg':
somaPARES(lista)
print('-' * 80)
menu()
print('-'*80)
lista=criarLista()
print('-'*80)
menu()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2013, 2014, 2016, 2017 Guenter Bartsch
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
# big phoneme table
#
# entries:
# ( IPA, XSAMPA, MARY, ESPEAK )
#
MAX_PHONEME_LENGTH = 2
big_phoneme_table = [
#
# stop
#
( u'p' , 'p' , 'p', 'p' ),
( u'b' , 'b' , 'b', 'b' ),
( u't' , 't' , 't', 't' ),
( u'd' , 'd' , 'd', 'd' ),
( u'k' , 'k' , 'k', 'k' ),
( u'g' , 'g' , 'g', 'g' ),
( u'ʔ' , '?' , '?', '?' ),
#
# 2 consonants
#
( u'pf' , 'pf' , 'pf' , 'pf' ),
( u'ts' , 'ts' , 'ts' , 'ts' ),
( u'tʃ' , 'tS' , 'tS' , 'tS' ),
( u'dʒ' , 'dZ' , 'dZ' , 'dZ' ),
#
# fricative
#
( u'f' , 'f' , 'f' , 'f' ),
( u'v' , 'v' , 'v' , 'v' ),
( u'θ' , 'T' , 'T' , 'T' ),
( u'ð' , 'D' , 'D' , 'D' ),
( u's' , 's' , 's' , 's' ),
( u'z' , 'z' , 'z' , 'z' ),
( u'ʃ' , 'S' , 'S' , 'S' ),
( u'ʒ' , 'Z' , 'Z' , 'Z' ),
( u'ç' , 'C' , 'C' , 'C' ),
( u'j' , 'j' , 'j' , 'j' ),
( u'x' , 'x' , 'x' , 'x' ),
( u'ʁ' , 'R' , 'R' , 'R' ),
( u'h' , 'h' , 'h' , 'h' ),
( u'ɥ' , 'H' , 'H' , 'H' ),
#
# nasal
#
( u'm' , 'm' , 'm' , 'm' ),
( u'n' , 'n' , 'n' , 'n' ),
( u'ɳ' , 'N' , 'N' , 'N' ),
( u'ɲ' , 'J' , 'J' , 'J' ),
#
# liquid
#
( u'l' , 'l' , 'l' , 'l' ),
( u'r' , 'r' , 'r' , 'r' ),
#
# glide
#
( u'w' , 'w' , 'w', 'w' ),
# see above ( u'j' , 'j' , 'j' ),
#
# vowels: monophongs
#
# front
( u'i' , 'i' , 'i' , 'i' ),
( u'ɪ' , 'I' , 'I' , 'I' ),
( u'y' , 'y' , 'y' , 'y' ),
( u'ʏ' , 'Y' , 'Y' , 'y' ),
( u'e' , 'e' , 'e' , 'e' ),
( u'ø' , '2' , '2' , 'W' ),
( u'œ' , '9' , '9' , 'W' ),
( u'œ̃' , '9~' , '9~' , 'W~' ),
( u'ɛ' , 'E' , 'E' , 'E' ),
( u'ɛ̃' , 'E~' , 'E~' , 'E~' ),
( u'æ' , '{' , '{' , 'a' ),
( u'a' , 'a' , 'a' , 'a' ),
# central
( u'ʌ' , 'V' , 'V' , 'A' ),
( u'ə' , '@' , '@' , '@' ),
( u'ɐ' , '6' , '6' , '@' ),
( u'ɜ' , '3' , 'r=', '3' ),
# back
( u'u' , 'u' , 'u' , 'u' ),
( u'ʊ' , 'U' , 'U' , 'U' ),
( u'o' , 'o' , 'o' , 'o' ),
( u'ɔ' , 'O' , 'O' , 'O' ),
( u'ɔ̃' , 'O~' , 'O~' , 'O~' ),
( u'ɑ' , 'A' , 'A' , 'A' ),
( u'ɑ̃' , 'A~' , 'A~' , 'A~' ),
( u'ɒ' , 'Q' , 'Q' , 'Q' ),
# diphtongs
( u'aɪ' , 'aI' , 'aI' , 'aI' ),
( u'ɔɪ' , 'OI' , 'OI' , 'OI' ),
( u'aʊ' , 'aU' , 'aU' , 'aU' ),
( u'ɔʏ' , 'OY' , 'OY' , 'OY' ),
#
# misc
#
( u'ː' , ':' , ':' , ':' ),
( u'-' , '-' , '-' , '-' ),
( u'\'' , '\'' , '\'' , '\'' ),
#
# noise
#
( u'#' , '#' , '#' ),
]
IPA_normalization = {
u':' : u'ː',
u'?' : u'ʔ',
u'ɾ' : u'ʁ',
u'ɡ' : u'g',
u'ŋ' : u'ɳ',
u' ' : None,
u'(' : None,
u')' : None,
u'\u02c8' : u'\'',
u'\u032f' : None,
u'\u0329' : None,
u'\u02cc' : None,
u'\u200d' : None,
u'\u0279' : None,
u'\u0361' : None,
}
IPA_vowels = set([
u'i' ,
u'ɪ' ,
u'y' ,
u'ʏ' ,
u'e' ,
u'ø' ,
u'œ' ,
u'ɛ' ,
u'æ' ,
u'a' ,
# central
u'ʌ' ,
u'ə' ,
u'ɐ' ,
u'ɜ' ,
# back
u'u' ,
u'ʊ' ,
u'o' ,
u'ɔ' ,
u'ɑ' ,
u'ɒ' ,
# diphtongs
u'aɪ' ,
u'ɔɪ' ,
u'aʊ' ,
u'ɔʏ' ])
XSAMPA_normalization = {
' ': None,
'0': 'O',
',': None,
}
def _normalize (s, norm_table):
buf = ""
for c in s:
if c in norm_table:
x = norm_table[c]
if x:
buf += x
else:
buf += c
return buf
def _translate (graph, s, f_idx, t_idx, spaces=False):
buf = ""
i = 0
l = len(s)
while i < l:
found = False
for pl in range(MAX_PHONEME_LENGTH, 0, -1):
if i + pl > l:
continue
substr = s[i : i+pl ]
#print u"i: %s, pl: %d, substr: '%s'" % (i, pl, substr)
for pe in big_phoneme_table:
p_f = pe[f_idx]
p_t = pe[t_idx]
if substr == p_f:
buf += p_t
i += pl
if i<l and s[i] != u'ː' and spaces:
buf += ' '
found = True
break
if found:
break
if not found:
p = s[i]
msg = (u"_translate: %s: %s Phoneme not found: %s (%s)" % (graph, s, p, repr(p))).encode('UTF8')
raise Exception (msg)
return buf
def ipa_move_stress_to_vowels(ipa):
stress = False
res = u''
for c in ipa:
if c == '\'':
stress = True
continue
if stress and c in IPA_vowels:
res += '\''
stress = False
res += c
return res
def ipa2xsampa (graph, ipas, spaces=False, stress_to_vowels=True):
ipas = _normalize (ipas, IPA_normalization)
if stress_to_vowels:
ipas = ipa_move_stress_to_vowels(ipas)
return _translate (graph, ipas, 0, 1, spaces)
def ipa2mary (graph, ipas):
ipas = _normalize (ipas, IPA_normalization)
return _translate (graph, ipas, 0, 2)
def xsampa2ipa (graph, xs):
xs = _normalize (xs, XSAMPA_normalization)
return _translate (graph, xs, 1, 0)
def mary2ipa (graph, ms):
ms = _normalize (ms, XSAMPA_normalization)
return _translate (graph, ms, 2, 0)
ESPEAK_normalization = {
' ' : '',
';' : '',
'~' : '',
'0' : 'O',
',' : '',
# '3' : '@',
't#' : 't',
'E2' : 'E',
'I#' : 'I',
'L' : 'l',
'_!' : '',
'_::': '',
'_;_': '',
'_!' : '',
'_|' : '',
'_:' : '',
'_' : '',
'!' : '',
'(' : '',
')' : '',
'Y' : 'y',
'pF' : 'pf',
}
def espeak2ipa (graph, ms):
for c in ESPEAK_normalization:
ms = ms.replace(c, ESPEAK_normalization[c])
return _translate (graph, ms, 3, 0)
def ipa2espeak (graph, ipas, spaces=False, stress_to_vowels=True):
ipas = _normalize (ipas, IPA_normalization)
if stress_to_vowels:
ipas = ipa_move_stress_to_vowels(ipas)
return _translate (graph, ipas, 0, 3, spaces)
#
# X-ARPABET is my own creation - similar to arpabet plus
# some of my own creating for those phones defined in
#
# http://www.dev.voxforge.org/projects/de/wiki/PhoneSet
#
# uses only latin alpha chars
#
xs2xa_table = [
#
# stop
#
('p' , 'P'),
('b' , 'B'),
('t' , 'T'),
('d' , 'D'),
('k' , 'K'),
('g' , 'G'),
('?' , 'Q'),
#
# 2 consonants
#
('pf' , 'PF'),
('ts' , 'TS'),
('tS' , 'CH'),
('dZ' , 'JH'),
#
# fricative
#
('f' , 'F'),
('v' , 'V'),
('T' , 'TH'),
('D' , 'DH'),
('s' , 'S'),
('z' , 'Z'),
('S' , 'SH'),
('Z' , 'ZH'),
('C' , 'CC'),
('j' , 'Y'),
('x' , 'X'),
('R' , 'RR'),
('h' , 'HH'),
('H' , 'HHH'),
#
# nasal
#
('m' , 'M'),
('n' , 'N'),
('N' , 'NG'),
('J' , 'NJ'),
#
# liquid
#
('l' , 'L'),
('r' , 'R'),
#
# glide
#
('w' , 'W'),
#
# vowels, monophongs
#
# front
('i' , 'IY'),
('i:' , 'IIH'),
('I' , 'IH'),
('y' , 'UE'),
('y:' , 'YYH'),
('Y' , 'YY'),
('e' , 'EE'),
('e:' , 'EEH'),
('2' , 'OH'),
('2:' , 'OHH'),
('9' , 'OE'),
('9~' , 'OEN'),
('E' , 'EH'),
('E:' , 'EHH'),
('E~' , 'EN'),
('{' , 'AE'),
('{:' , 'AEH'),
('a' , 'AH'),
('a:' , 'AAH'),
('3' , 'ER'),
('3:' , 'ERH'),
# central
('V' , 'VV'),
('@' , 'AX'),
('6' , 'EX'),
#('3' , 'AOR'),
# back
('u' , 'UH'),
('u:' , 'UUH'),
('U' , 'UU'),
('o' , 'AO'),
('o:' , 'OOH'),
('O' , 'OO'),
('O:' , 'OOOH'),
('O~' , 'ON'),
('A' , 'AA'),
('A:' , 'AAAH'),
('A~' , 'AN'),
('Q' , 'QQ'),
# diphtongs
('aI' , 'AY'),
('OI' , 'OI'),
('aU' , 'AW'),
('OY' , 'OY'),
# misc (noise)
('#' , 'NSPC'),
]
XARPABET_normalization = {
'-': None,
'\'': None,
}
def xsampa2xarpabet (graph, s):
s = _normalize (s, XARPABET_normalization)
buf = ""
i = 0
l = len(s)
while i < l:
found = False
for pl in range(MAX_PHONEME_LENGTH, 0, -1):
if i + pl > l:
continue
substr = s[i : i+pl ]
#print u"i: %s, pl: %d, substr: '%s'" % (i, pl, substr)
for pe in xs2xa_table:
p_f = pe[0]
p_t = pe[1]
if substr == p_f:
if len(buf)>0:
buf += ' '
buf += p_t
i += pl
found = True
break
if found:
break
if not found:
p = s[i]
msg = u"xsampa2xarpabet: graph:'%s' - s:'%s' Phoneme not found: '%s' (%d) '%s'" % (graph, s, p, ord(p), s[i:])
raise Exception (msg.encode('UTF8'))
return buf
|
#!/usr/bin/python3
"""
This is a simple implementation of BST
binary search tree
"""
class Node(object):
def __init__(self, value=None, left=None, right=None, parent=None):
self.value = value
self.left = left
self.right = right
self.parent = parent
def __str__(self):
"""
String representation of the TreeNode
"""
return str(self.value)
def isLeaf(self):
"""
Check whether the node is leaf node or not
:return: True or False depend on whether a leaf node
"""
return not (self.right or self.left)
def isRoot(self):
"""
Check whether the node has a parent or not
:return: return True if there is no parent, False if there is a parent
"""
return not self.parent
def hasLeftChild(self):
"""
Check whether the node has a left child or not
"""
return self.left
def hasRightChild(self):
"""
Check whether the node has a right child or not
"""
return self.right
def hasAnyChildren(self):
"""
Check whether the node has any child nodes
similar to the isLeaf
"""
return self.right or self.left
|
pessoas = list()
dados = list()
maior = menor = 0
while True:
dados.append(str(input('Digite seu nome: ').strip().capitalize()))
dados.append(int(input('Digite seu peso: ')))
if not pessoas:
maior = menor = dados[1]
pessoas.append(dados[:])
for valor in pessoas:
if valor[1] > maior:
maior = valor[1]
elif valor[1] < menor:
menor = valor[1]
dados.clear()
resp = ''
while not resp or resp not in 'SsNn':
resp = str(input('Deseja continuar? [S/N]: ')).strip().upper()
if not resp or resp not in 'SsNn':
print('Opção inválida!')
else:
break
if resp in 'Nn':
break
print(f'Foram cadastradas {len(pessoas)} pessoas.')
print(f'O maior peso registrado foi: {maior}Kg.')
print(f'As pessoas mais pesadas foram:', end=' ')
for valor in pessoas:
if valor[1] >= maior:
print(valor[0], end='. ')
print(f'\nO menor peso registrado foi: {menor}Kg.')
print(f'As pessoas mais leves foram:', end=' ')
for valor in pessoas:
if valor[1] <= menor:
print(valor[0], end='. ')
|
#!/usr/bin/python3
# Guilhem Mizrahi 09/2019
def first():
var1=input("Enter the first number: ")
var2=input("Enter the second number: ")
print(var1/var2)
def second():
var1=int(input("Enter the first number: "))
var2=int(input("Enter the second number: "))
print(var1/var2)
def third():
retvalue1=""
while(not retvalue1.isnumeric()):
retvalue1=input("Type in first a number: ")
retvalue2=""
while(not retvalue2.isnumeric()):
retvalue2=input("Type in a second number: ")
retvalue1=int(retvalue1)
retvalue2=int(retvalue2)
print(retvalue1/retvalue2)
def fourth():
while True:
try:
val1 = int(input("Enter the first number: "))
val2 = int(input("Enter the second number: "))
break
except:
print("You did not enter a number")
continue
print(val1/val2)
def fith():
mylist = ["obj1","obj2","obj3"]
myvar1 = 32
myvar2 = "Something else"
print('{} {}'.format(myvar1,myvar2))
print('{1} {0}'.format(myvar1,myvar2))
print('{} {}'.format(mylist[1],mylist[2]))
def sixth():
for i in range(1,13):
print("{:3d} {:4d} {:5d}".format(i, i**2, i**3))
if __name__=="__main__":
# first()
# second()
# third()
# fourth()
# fith()
sixth()
|
PROG = 'censor'
fin = open(PROG + '.in', 'r')
fout = open(PROG + '.out', 'w')
def main():
s = fin.readline()
s = s[:len(s) - 1]
t = fin.readline()
t = t[:len(t) - 1]
while True:
i = s.find(t)
if i == -1:
break
s = s[0:i] + s[i + len(t):]
fout.write(s + '\n')
main()
fin.close()
fout.close()
|
# tests.py
# Run `conda install pytest`
# Run `pytest test_main.py` from the speech2phone/ directory.
"""
To use pytest, the file must be named "test***.py". For example, `tests.py` or `test_pca.py`.
Test functions must be prefixed with `test_`. So `multiply()` is not a test function, but `test_numbers_3_4()` is.
We use simple assert statements for our testing. No assertThis() or assertThat().
https://docs.pytest.org/en/latest/usage.html
http://pythontesting.net/framework/pytest/pytest-introduction/#running_pytest
pytest fixtures could be useful later, but don't worry about them for now.
"""
def multiply(a, b):
return a * b
def test_numbers_3_4():
assert multiply(3,4) == 12
def test_strings_a_3():
assert multiply('a',3) == 'aaa'
|
class IncorrectInputVectorLength(Exception):
pass
class NetIsNotInitialized(Exception):
pass
class IncorrectFactorValue(Exception):
pass
class NetIsNotCalculated(Exception):
pass
class IncorrectExpectedOutputVectorLength(Exception):
pass
class NetConfigIndefined(Exception):
pass
class NetConfigIncorrect(Exception):
pass
class JsonFileNotFound(Exception):
pass
class JsonFileStructureIncorrect(Exception):
pass
|
# The rand7() API is already defined for you.
# def rand7():
# @return a random integer in the range 1 to 7
class Solution:
def rand10(self):
"""
:rtype: int
"""
v = (rand7()-1)*7 + rand7()-1
while v >= 40: v = (rand7()-1)*7 + rand7()-1
return v%10 + 1
|
class BingoBoard:
def __init__(self, numbers):
self.numbers = [int(n) for n in numbers.replace("\n", " ").split()]
self.marked = set()
def mark(self, n):
if n in self.numbers:
self.marked.add(n)
return self.check_win()
return False
def get_score(self):
return sum(set(self.numbers).difference(self.marked))
def check_win(self):
return self.check_rows() or self.check_columns()
def check_rows(self):
for i in range(0, 21, 5):
if self.marked.issuperset(self.numbers[i:i+5]):
return True
return False
def check_columns(self):
for i in range(5):
if self.marked.issuperset(self.numbers[i::5]):
return True
return False
def get_data(filename):
with open(filename) as file:
numbers, *boards = file.read().split("\n\n")
numbers = [int(n) for n in numbers.split(",")]
boards = [BingoBoard(board) for board in boards]
return numbers, boards
def play(numbers, boards):
winning_score = None
for n in numbers:
boards_to_remove = set()
for board in boards:
if board.mark(n):
boards_to_remove.add(board)
if winning_score is None:
winning_score = board.get_score() * n
elif len(boards) == 1:
losing_score = board.get_score() * n
return winning_score, losing_score
boards = [board for board in boards if board not in boards_to_remove]
# sample_data = get_data("day_04_sample.txt")
challenge_data = get_data("input.txt")
if __name__ == "__main__":
# sample_part_1, sample_part_2 = play(*sample_data)
# assert sample_part_1 == 4512
# assert sample_part_2 == 1924
challenge_part_1, challenge_part_2 = play(*challenge_data)
print(challenge_part_1) # 23177
print(challenge_part_2) # 6804
|
#from http://rosettacode.org/wiki/Greatest_common_divisor#Python
#pythran export gcd_iter(int, int)
#pythran export gcd(int, int)
#pythran export gcd_bin(int, int)
#runas gcd_iter(40902, 24140)
#runas gcd(40902, 24140)
#runas gcd_bin(40902, 24140)
def gcd_iter(u, v):
while v:
u, v = v, u % v
return abs(u)
def gcd(u, v):
return gcd(v, u % v) if v else abs(u)
def gcd_bin(u, v):
u, v = abs(u), abs(v) # u >= 0, v >= 0
if u < v:
u, v = v, u # u >= v >= 0
if v == 0:
return u
# u >= v > 0
k = 1
while u & 1 == 0 and v & 1 == 0: # u, v - even
u >>= 1; v >>= 1
k <<= 1
t = -v if u & 1 else u
while t:
while t & 1 == 0:
t >>= 1
if t > 0:
u = t
else:
v = -t
t = u - v
return u * k
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 10 21:24:01 2019
@author: li-ming-fan
"""
#
def segment_sentences(text, delimiters = None):
"""
"""
if delimiters is None:
delimiters = ['?', '!', ';', '?', '!', '。', ';', '…', '\n']
#
text = text.replace('...', '。。。').replace('..', '。。')
#
# 引用(“ ”)中有句子的情况
# text = text.replace('"', '').replace('“', '').replace('”', '')
#
len_text = len(text)
sep_posi = []
for item in delimiters:
posi_start = 0
while posi_start < len_text:
try:
posi = posi_start + text[posi_start:].index(item) #
sep_posi.append(posi)
posi_start = posi + 1
except BaseException:
break # while
#
#
sep_posi.sort()
num_sep = len(sep_posi)
#
#
list_sent = []
#
if num_sep == 0: return [ text ]
#
posi_last = 0
for idx in range(0, num_sep - 1):
posi_curr = sep_posi[idx] + 1
posi_next = sep_posi[idx + 1]
if posi_next > posi_curr:
list_sent.append( text[posi_last:posi_curr] )
posi_last = posi_curr
#
posi_curr = sep_posi[-1] + 1
if posi_curr == len_text:
list_sent.append( text[posi_last:] )
else:
list_sent.extend( [text[posi_last:posi_curr], text[posi_curr:]] )
#
return list_sent
#
# chars
def convert_quan_to_ban(str_quan):
"""全角转半角"""
str_ban = ""
for uchar in str_quan:
inside_code = ord(uchar)
if inside_code == 12288: #全角空格直接转换
inside_code = 32
elif (inside_code >= 65281 and inside_code <= 65374): #全角字符(除空格)根据关系转化
inside_code -= 65248
#
str_ban += chr(inside_code)
return str_ban
def convert_ban_to_quan(str_ban):
"""半角转全角"""
str_quan = ""
for uchar in str_ban:
inside_code = ord(uchar)
if inside_code == 32: #半角空格直接转化
inside_code = 12288
elif inside_code >= 32 and inside_code <= 126: #半角字符(除空格)根据关系转化
inside_code += 65248
#
str_quan += chr(inside_code)
return str_quan
|
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
class JobMode:
COLLECTIVE = 'collective'
PS = 'ps'
HETER = 'heter'
class Job(object):
def __init__(self, jid='default', mode=JobMode.COLLECTIVE, nnodes="1"):
self._mode = mode
self._id = jid
self._replicas = 0
self._replicas_min = self._replicas
self._replicas_max = self._replicas
self._elastic = False
self.set_replicas(str(nnodes))
def __str__(self):
return "Job: {}, mode {}, replicas {}[{}:{}], elastic {}".format(
self.id, self.mode, self._replicas, self._replicas_min,
self._replicas_max, self.elastic)
@property
def mode(self):
return self._mode
@property
def id(self):
return self._id
@property
def elastic(self):
return self._elastic
@property
def replicas(self):
return self._replicas
@property
def replicas_min(self):
return self._replicas_min
@property
def replicas_max(self):
return self._replicas_max
@replicas.setter
def replicas(self, replicas):
self._replicas = replicas
def set_replicas(self, nnodes: str):
np = str(nnodes) if nnodes else '1'
if ':' in np:
nps = np.split(':')
self._replicas_min, self._replicas_max = int(nps[0]), int(nps[1])
self._replicas = self._replicas_max # default to max
self._elastic = True
else:
self._replicas = int(np)
self._replicas_min, self._replicas_max = self._replicas, self._replicas
self._elastic = False
|
def Menunggu(n,des):
#basis
if n == 0:
return 0
#rekuren
print(des)
return Menunggu(n-1,des)
def MySum(n):
#basis
if n == 0:
return 0
#rekuren
return n+MySum(n-1)
def main():
# solusi iteratif/pengulangan dengan teknik for loop
#n = 10
#for i in range(n):
# print("Menunggu si dia.")
# solusi rekursif
Menunggu(10,"Menunggu si dia.")
# solusi iteratif penjumlahan
# sum = 0
# n = 10
# for i in range(n+1):
# sum+=i
# print(sum) #55
# solusi rekursif
print(MySum(10)) #55?
if __name__=="__main__":
main()
|
i = input().split()
N,Q = int(i[0]),int(i[1])
AI = input().split()
ai = []
for n in AI:
ai.append(int(n))
QI = input().split()
qi = []
for n in QI:
qi.append(int(n))
for q in qi:
ai_aux = ai.copy()
count = 0
p = 0
while(p<len(ai_aux)-1):
if q in ai_aux:
count += 1
i = ai_aux.index(q)
ai_aux[i] = 0
elif (q-ai_aux[p]) in ai_aux:
count += 1
i1 = ai_aux.index(q-ai_aux[p])
ai_aux[i1] = 0
i2 = ai_aux.index(ai_aux[p])
ai_aux[i2] = 0
p += 1
p += 1
print(count)
|
class hparams:
train_or_test = 'train'
output_dir = 'logs/your_program_name'
aug = False
latest_checkpoint_file = 'checkpoint_latest.pt'
total_epochs = 100
epochs_per_checkpoint = 10
batch_size = 2
ckpt = None
init_lr = 0.0002
scheduer_step_size = 20
scheduer_gamma = 0.8
debug = False
mode = '2d' # '2d or '3d'
in_class = 1
out_class = 2
crop_or_pad_size = 224,224,1 # if 3D: 256,256,256
fold_arch = '*.png'
source_train_0_dir = 'train/0'
source_train_1_dir = 'train/1'
source_test_0_dir = 'test/0'
source_test_1_dir = 'test/1'
|
'''
--- Day 1: The Tyranny of the Rocket Equation ---
-- Part 1 --
The Elves quickly load you into a spacecraft and prepare to launch.
At the first Go / No Go poll, every Elf is Go until the Fuel Counter-Upper.
They haven't determined the amount of fuel required yet.
Fuel required to launch a given module is based on its mass. Specifically,
to find the fuel required for a module, take its mass, divide by three,
round down, and subtract 2. What is the sum of the fuel requirements for all
of the modules on your spacecraft?
-- Part 2 --
During the second Go / No Go poll, the Elf in charge of the Rocket Equation
Double-Checker stops the launch sequence. Apparently, you forgot to include
additional fuel for the fuel you just added.
Fuel itself requires fuel just like a module - take its mass, divide by three,
round down, and subtract 2. However, that fuel also requires fuel, and that
fuel requires fuel, and so on. Any mass that would require negative fuel should
instead be treated as if it requires zero fuel; the remaining mass, if any, is
instead handled by wishing really hard, which has no mass and is outside the
scope of this calculation.
So, for each module mass, calculate its fuel and add it to the total. Then,
treat the fuel amount you just calculated as the input mass and repeat the
process, continuing until a fuel requirement is zero or negative.
What is the sum of the fuel requirements for all of the modules on your
spacecraft when also taking into account the mass of the added fuel?
'''
def get_fuel(mass):
return int(mass/3)-2
def fuel_sum():
sum = [0,0]
m = open("modules.txt", "r")
for x in m:
add_fuel = get_fuel(int(x))
sum[0] += add_fuel
while get_fuel(add_fuel) > 0:
add_fuel = get_fuel(add_fuel)
sum[1] += add_fuel
return sum
if __name__ == '__main__':
result = fuel_sum()
print("Part 1:", result[0])
print("Part 2:", result[0]+result[1])
|
"""
exceptions/__init__.py
Comments:
Author: Dennis Whitney
Email: [email protected]
Copyright (c) 2021, iRunAsRoot
"""
class ValueReadOnly(Exception):
pass
class ValueNotAllowed(Exception):
pass
class UnauthorizedAccess(Exception):
pass
class UnknownEndpoint(Exception):
pass
|
def test_create(app):
wd = app.wd
assert app.soap.can_login(username="administrator", password="admin")
app.session.login(user_name="administrator", user_pass="admin")
assert app.session.is_logged_in_as("administrator")
#open create page
app.open_create_page()
# fill form
pn = "name0"
pd = "desc0"
app.fill_form(pname=pn, pdesc=pd)
# check creation
wd.find_element_by_xpath("//a[@href='/mantisbt-2.25.2/manage_overview_page.php']").click()
wd.find_element_by_link_text(u"Управление проектами").click()
tab = wd.find_element_by_css_selector("table")
hrefs = tab.find_elements_by_css_selector("a")
flag = 0
for i in hrefs:
if i.text == pn:
flag = 1
assert flag == 1
app.soap.get_projects(username="administrator", password="admin", pname=pn)
|
# Redis数据库地址
REDIS_HOST = 'localhost'
# Redis端口
REDIS_PORT = 6379
# Redis密码,如无填None
REDIS_PASSWORD = 'foobared'
# 产生器使用的浏览器
BROWSER_TYPE = 'Chrome'
# 产生器类,如扩展其他站点,请在此配置
GENERATOR_MAP = {
'weibo': 'WeiboCookiesGenerator'
}
# 测试类,如扩展其他站点,请在此配置
TESTER_MAP = {
'weibo': 'WeiboValidTester'
}
TEST_URL_MAP = {
'weibo': 'https://m.weibo.cn/'
}
# 产生器和验证器循环周期
CYCLE = 120
# API地址和端口
API_HOST = '0.0.0.0'
API_PORT = 5000
# 产生器开关,模拟登录添加Cookies
GENERATOR_PROCESS = False
# 验证器开关,循环检测数据库中Cookies是否可用,不可用删除
VALID_PROCESS = False
# API接口服务
API_PROCESS = True
|
"""
map data could be a 2D grid with data for each cell as N, S, E, W. A special data
set would highlight "here" information, like if there's a pit, item, encounter or
teleportation.
w - wall
d - door
o - open
s - secret door (shows as 'w' on other side)
A box with a door leading east from the NE quadrant would look like:
woowwodoowowowwo
"""
|
#This is a simple inventory program for a small car dealership.
print('Automotive Inventory')
class Automobile:
def __init__(self):
self._make = ''
self._model = ''
self._year = 0
self._color = ''
self._mileage = 0
def addVehicle(self):
try:
self._make = input('Enter vehicle make: ')
self._model = input('Enter vehicle model: ')
self._year = int(input('Enter vehicle year: '))
self._color = input('Enter vehicle color: ')
self._mileage = int(input('Enter vehicle mileage: '))
return True
except ValueError:
print('Please try entering vehicle information again using only whole numbers for mileage and year')
return False
def __str__(self):
return '\t'.join(str(x) for x in [self._make, self._model, self._year, self._color, self._mileage])
class Inventory:
def __init__(self):
self.vehicles = []
def addVehicle(self):
vehicle = Automobile()
if vehicle.addVehicle() == True:
self.vehicles.append(vehicle)
print ()
print('This vehicle has been added, Thank you')
def viewInventory(self):
print('\t'.join(['','Make', 'Model','Year', 'Color', 'Mileage']))
for idx, vehicle in enumerate(self.vehicles) :
print(idx + 1, end='\t')
print(vehicle)
inventory = Inventory()
while True:
print('')
print('#1 Add Vehicle to Inventory')
print('#2 Delete Vehicle from Inventory')
print('#3 View Current Inventory')
print('#4 Update Vehicle in Inventory')
print('#5 Export Current Inventory')
print('#6 Quit')
print('--------------------------------------------')
userInput=input('Please choose from one of the above options: ')
if userInput=="1":
#add a vehicle
inventory.addVehicle()
elif userInput=='2':
#delete a vehicle
if len(inventory.vehicles) < 1:
print('Sorry there are no vehicles currently in inventory')
continue
inventory.viewInventory()
item = int(input('Please enter the number associated with the vehicle to be removed: '))
if item - 1 > len(inventory.vehicles):
print('This is an invalid number')
else:
inventory.vehicles.remove(inventory.vehicles[item - 1])
print ()
print('This vehicle has been removed')
elif userInput == '3':
#list all the vehicles
if len(inventory.vehicles) < 1:
print('Sorry there are no vehicles currently in inventory')
continue
inventory.viewInventory()
elif userInput == '4':
#edit vehicle
if len(inventory.vehicles) < 1:
print('Sorry there are no vehicles currently in inventory')
continue
inventory.viewInventory()
item = int(input('Please enter the number associated with the vehicle to be updated: '))
if item - 1 > len(inventory.vehicles):
print('This is an invalid number')
else:
automobile = Automobile()
if automobile.addVehicle() == True :
inventory.vehicles.remove(inventory.vehicles[item - 1])
inventory.vehicles.insert(item - 1, automobile)
print ()
print('This vehicle has been updated')
elif userInput == '5':
#export inventory to file
if len(inventory.vehicles) < 1:
print('Sorry there are no vehicles currently in inventory')
continue
f = open('vehicle_inventory.txt', 'w')
f.write('\t'.join(['Make', 'Model','Year', 'Color', 'Mileage']))
f.write('\n')
for vechicle in inventory.vehicles:
f.write('%s\n' %vechicle)
f.close()
print('The vehicle inventory has been exported to a file')
elif userInput == '6':
#exit the loop
print('Goodbye')
break
else:
#invalid user input
print('This is an invalid input. Please try again.')
|
class Registry:
def __init__(self):
self.addr = ["134.209.83.144"]
self._config = None
self._executor = None
@property
def executor(self):
if not self._executor:
self._executor = ExecutorSSH(self.addr[0], 22)
return self._executor
@property
def myname(self):
"""
is the main config
"""
myname = j.core.myenv.sshagent.key_default_name
c = self.config["clients"]
if myname not in c:
y = j.core.tools.logask_yes_no(
"is our unique login name:%s\nif not please say no and define new name." % myname
)
if not y:
myname2 = j.core.tools.ask_string("give your unique loginname")
msg = "careful: your sshkeyname will be changed accordingly on your system to:%s, ok?" % myname2
if j.core.tools.ask_yes_no(msg):
src = j.core.myenv.sshagent.key_path_get()
dest = "%s/%s" % (os.path.dirname(src), myname2)
shutil.copyfile(src, dest)
shutil.copyfile(src + ".pub", dest + ".pub")
j.core.myenv.config["SSH_KEY_DEFAULT"] = myname2
j.core.myenv.config_save()
j.core.tools.delete(src)
j.core.tools.delete(src + ".pub")
j.core.myenv.sshagent.keys_unload()
j.core.myenv.sshagent.key_load(dest)
myname = myname2
else:
raise j.exceptions.Input("cannot continue need unique login name which corresponds to your sshkey")
c[myname] = {}
c = c[myname]
keypub = j.core.myenv.sshagent.keypub
def showdetails(c):
print(json.dumps(c))
def askdetails(c):
organizations = ["codescalers", "freeflow", "frequencyvillage", "threefold", "incubaid", "bettertoken"]
organizations2 = ", ".join(organizations)
if "email" not in c:
c["email"] = j.core.tools.ask_string("please provide your main email addr")
if "organizations" not in c:
print("valid organizations: '%s'" % organizations2)
c["organizations"] = j.core.tools.ask_string("please provide your organizations (comma separated)")
if "remark" not in c:
c["remark"] = j.core.tools.ask_string("any remark?")
if "telegram" not in c:
c["telegram"] = j.core.tools.ask_string("please provide your main telegram handle")
if "mobile" not in c:
c["mobile"] = j.core.tools.ask_string("please provide your mobile nr's (if more than one use ,)")
showdetails(c)
y = j.core.tools.ask_yes_no("is above all correct !!!")
if not y:
c["email"] = j.core.tools.ask_string("please provide your main email addr", default=c["email"])
print("valid organizations: '%s'" % organizations2)
c["organizations"] = j.core.tools.ask_string(
"please provide your organizations (comma separated)", default=c["organizations"]
)
c["remark"] = j.core.tools.ask_string("any remark?", default=c["remark"])
c["telegram"] = j.core.tools.ask_string(
"please provide your main telegram handle", default=c["telegram"]
)
c["mobile"] = j.core.tools.ask_string(
"please provide your mobile nr's (if more than one use ,)", default=c["mobile"]
)
self.executor.save()
o = c["organizations"]
o2 = []
for oname in o.lower().split(","):
oname = oname.strip().lower()
if oname == "":
continue
if oname not in organizations:
raise j.exceptions.Input(
"please choose valid organizations (notok:%s): %s" % (oname, organizations2)
)
o2.append(oname)
c["organizations"] = ",".join(o2)
if "keypub" not in c:
c["keypub"] = keypub
askdetails()
self.executor.save()
else:
if not c["keypub"].strip() == keypub.strip():
showdetails(c)
y = j.core.tools.ask_yes_no("Are you sure your are above?")
raise j.exceptions.Input(
"keypub does not correspond, your name:%s, is this a unique name, comes from your main sshkey, change if needed"
% myname
)
return myname
def load(self):
self._config = None
@property
def config_mine(self):
return self.config["clients"][self.myname]
@property
def myid(self):
if "myid" not in self.config_mine:
if "lastmyid" not in self.config:
self.config["lastmyid"] = 1
else:
self.config["lastmyid"] += 1
self.config_mine["myid"] = self.config["lastmyid"]
self.executor.save()
return self.config_mine["myid"]
# @iterator
# def users(self):
# for name, data in self.config["clients"].items():
# yield data
@property
def config(self):
"""
is the main config
"""
if not self._config:
c = self.executor.config
if not "registry" in c:
c["registry"] = {}
config = self.executor.config["registry"]
if "clients" not in config:
config["clients"] = {}
self._config = config
return self._config
|
# Copyright (c) 2012-2018 SoftBank Robotics. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the COPYING file.
""" qisrc actcions """
|
__author__ = 'ian.collins'
currentcolor = True # true=day, false=night
lightthreshold = 50
lightchecktime = 10.0
gpsrefreshtime = 15.0
netrefreshtime = 30.0
crvincidentmain = None
# The actualt status bar
statusbar = None
# Where the statusbar fields are kept
statusbarbox = None
# An alternate statusbar - primarily for drop down hints (first char of dropdown list)
altstatusbarbox = None # used by dropdown for hints
# When button in alstatusbarbox is clicked, value it put here.
alstatusbarclick = ''
# The altstatusbarbox parent (used to test if caller is still active)
alstatusbarparent = None
quickpopup = None # to try and stop too many error popups
data = None
msgbox = None
mycurl = None
tmpxloc = None
gridheight = 40
default_font_size = '20sp'
default_large_font_size = '30sp'
default_medium_font_size = '15sp'
default_small_font_size = '14sp'
default_tiny_font_size = '10sp'
default_menu_font_size = '18sp'
temptidestations = []
|
#########################################################################################################################################################################
# Author : Remi Monthiller, [email protected]
# Adapted from the code of Raphael Maurin, [email protected]
# 30/10/2018
#
# Incline plane simulations
#
#########################################################################################################################################################################
def lengthVector3(vect):
return (vect[0] ** 2.0 + vect[1] ** 2.0 + vect[2] ** 2.0) ** (1.0/2.0)
|
class Solution(object):
def wordsAbbreviation(self, dict):
"""
:type dict: List[str]
:rtype: List[str]
"""
res = []
countMap = {}
prefix = [1] * len(dict)
for word in dict:
abbr = self.abbreviateWord(word, 1)
res.append(abbr)
countMap[abbr] = countMap.get(abbr, 0) + 1
while(True):
unique = True
for i in range(len(res)):
if countMap.get(res[i], 0) > 1:
unique = False
prefix[i] += 1
abbr = self.abbreviateWord(dict[i], prefix[i])
res[i] = abbr
countMap[abbr] = countMap.get(abbr, 0) + 1
if unique:
break
return res
def abbreviateWord(self, word, pos):
if pos + 2 >= len(word):
return word
return word[:pos] + str(len(word) - pos - 1) + word[-1]
|
DRIVERS = {
"default": "cookie",
"cookie": {},
}
|
string = "resource"
if len(string) < 2:
print("--")
else:
print(string[0:2] + string[-2:])
|
def run_tests(tests, function):
"""
Runs provided test cases and reports failure or success
:param tests: list of tests in (dict, expected value) format
:param function: function to run the tests against
:return: None
"""
success = 0
for test, expected in tests:
actual = function(**test)
if actual == expected:
success += 1
else:
error_message = x = """
error in : {}
expected : {}
actual : {}
""".format(test, expected, actual)
print(error_message)
if success == len(tests):
print('✓ All tests successful')
|
def increment_id(tag):
if tag == "error":
filename = "errorarena"
elif tag == "valid":
filename = "validarena"
elif tag == "gif":
filename = "gif"
file = open(f"./results/id/{filename}.txt","r")
id_line = file.readline()
file.close()
curr_id = int(id_line.strip())
file = open(f"./results/id/{filename}.txt","w")
file.write(f"{curr_id+1}")
file.close()
return curr_id
|
for char in 'One':
print (char)
'''
O
n
e
'''
|
# program to convert degrees f to degrees c
# need to use (degF - 32) * 5/9
user = input('Hello, what is your name? ')
print('Hello', user)
degF = int(input('Enter a temperature in degrees F: '))
degC = (degF -32) * 5/9
print('{} ,degrees F converts to , {} ,degrees C'.format(degF, (degC)))
|
num =10
num2= 20
num3=30
num4=40
|
class A(object):
x:int = 1
class B(A):
def __init__(self: "B"):
pass
class C(B):
z:bool = True
a:A = None
b:B = None
c:C = None
a = A()
b = B()
c = C()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 21 20:55:21 2017
@author: Lama Hamadeh
"""
'''
Case Study about DNA translation
'''
'''
NCBI is the United States' main public repository of DNA and related information
We will download two files from NCBI: the first is a strand of DNA and the second
is the protein sequence of amino acids translated from this DNA.
'''
#Downloading DNA Data
#---------------------
#read in the NCBI DNA sequence with the accession number NM_207618.2
#we have downloaded two files from the website:
#DNA.txt
#protein.text
#Importing DNA Data Into Python
#-------------------------------
#we can/need enter the studying folder through 'cd' and display the current folder using 'pwd'
print("\nThe DNA Sequence From the NCBI Website (Accession Number NM_207618.2) Is....\n")
inputfile = "DNA.txt"
f = open (inputfile, "r") #"r" here refers to reading command
seq = f.read()
seq = seq.replace("\n", "")
seq = seq.replace("\r", "")#As strings are immutable, this method return a new string
#so in order for us to use a new string, we have to assign it to a variable
#in this case, we will reassign it to the same variable as before.
print(seq) #we can even slice up the sequence to see specific part of the DNA file
#for example: print(seq[40:50]). In this case the output would be: CCTGAAAACC.
#Another way of opening the DNA.txt file:
#inputfile = "DNA.txt"
#with open(inutfile, "r") as f: #we need to put the colon at the end since with
#is a compound statement
#seq = f.read()
# We also can create a function that reads the file:
'''
def read_seq(inputfile):
"""This function reads and returns the input sequence with special characters removed"""
with open(inputfile, "r") as f:
seq = f.read()
seq = seq.replace("\n", "")
seq = seq.replace("\r", "")
return seq
'''
#Translating the DNA Sequence
#-----------------------------
#the translation process is essentially a table lookup operation.
#Python provides a very natural object for dealing with these types of situations.
#The object is a dictionary.
#In this case, the key objects are strings, each consisting of three letters,
#i.e., condons or nucleotide triples, drawn
#from the four letter alphabet (A,G,C,T).
#The value object is also a string but a string consisting of just one-letter symbol
#used for different amino acids.
#Defining a dictionary called 'table':
table = {'ATA':'I', 'ATC':'I', 'ATT':'I', 'ATG':'M',
'ACA':'T', 'ACC':'T', 'ACG':'T', 'ACT':'T',
'AAC':'N', 'AAt':'N', 'AAA':'K', 'AAG':'K',
'AGC':'S', 'AGT':'S', 'AGA':'R', 'AGG':'R',
'CTA':'L', 'CTC':'L', 'CTG':'L', 'CTT':'L',
'CCA':'P', 'CCC':'P', 'CCG':'P', 'CCT':'P',
'CAC':'H', 'CAT':'H', 'CAA':'Q', 'CAG':'Q',
'CGA':'R', 'CGC':'R', 'CGG':'R', 'CGT':'R',
'GTA':'V', 'GTC':'V', 'GTG':'V', 'GTT':'V',
'GCA':'A', 'GCC':'A', 'GCG':'A', 'GCT':'A',
'GAC':'D', 'GAT':'D', 'GAA':'E', 'GAG':'E',
'GGA':'G', 'GGC':'G', 'GGG':'G', 'GGT':'G',
'TCA':'S', 'TCC':'S', 'TCG':'S', 'TCT':'S',
'TTC':'F', 'TTT':'F', 'TTA':'L', 'TTG':'L',
'TAC':'Y', 'TAT':'Y', 'TAA':'_', 'TAG':'_',
'TGC':'C', 'TGT':'C', 'TGA':'_', 'TGG':'W'}
print (table['ATC']) #to see what is the corresponding value for the key ATC.
#STEP1: Check that length of sequence is divisible by 3
#STEP2: Look up each 3-letter string in table and store result.
#STEP3: Continue lookups until reaching end of sequence.
#Define a function that describes the translating process.
def translate(seq):
'''DOCSTRING: Translate a string containing a nucleotide sequence into a string containing the corresponding
sequence of amino acids. Nucleotides are translated in triplets using the table dictionary; each
amino acid is encoded with a string of length 1.'''
table = {'ATA':'I', 'ATC':'I', 'ATT':'I', 'ATG':'M',
'ACA':'T', 'ACC':'T', 'ACG':'T', 'ACT':'T',
'AAC':'N', 'AAt':'N', 'AAA':'K', 'AAG':'K',
'AGC':'S', 'AGT':'S', 'AGA':'R', 'AGG':'R',
'CTA':'L', 'CTC':'L', 'CTG':'L', 'CTT':'L',
'CCA':'P', 'CCC':'P', 'CCG':'P', 'CCT':'P',
'CAC':'H', 'CAT':'H', 'CAA':'Q', 'CAG':'Q',
'CGA':'R', 'CGC':'R', 'CGG':'R', 'CGT':'R',
'GTA':'V', 'GTC':'V', 'GTG':'V', 'GTT':'V',
'GCA':'A', 'GCC':'A', 'GCG':'A', 'GCT':'A',
'GAC':'D', 'GAT':'D', 'GAA':'E', 'GAG':'E',
'GGA':'G', 'GGC':'G', 'GGG':'G', 'GGT':'G',
'TCA':'S', 'TCC':'S', 'TCG':'S', 'TCT':'S',
'TTC':'F', 'TTT':'F', 'TTA':'L', 'TTG':'L',
'TAC':'Y', 'TAT':'Y', 'TAA':'_', 'TAG':'_',
'TGC':'C', 'TGT':'C', 'TGA':'_', 'TGG':'W'}
protein = ''
if len(seq) % 3 == 0: # Check that length of sequence is divisible by 3
for i in range(0, len(seq), 3): #Look up each 3-letter string in table and store result.
condon = seq[i : i+3]
protein += table[condon]
return protein
#check the function
print(translate("ATG"))
print(help (translate))#This print the docstring that is included inside the function
|
class Solution:
def findKthPositive(self, arr: List[int], k: int) -> int:
'''
Number of missing element at index i =
= arr[0] - 1 + arr[idx] - arr[0] - idx =
= arr[idx] - idx - 1
For more description, see: 1060 Missing Element in Sorted Array
T: O(log n) and O(1)
'''
def countMissing(idx):
return arr[idx] - idx - 1
if k < arr[0]: return k
lo, hi = 0, len(arr)
while lo < hi:
mid = lo + (hi - lo) // 2
if countMissing(mid) >= k:
hi = mid
else:
lo = mid + 1
return arr[lo - 1] + k - countMissing(lo - 1)
|
z = "Tests were ran for service: matchService \n" \
"Passed: \n" \
"Failed: \n" \
"Error: \n" \
"Skipped: \n"
|
ip_addr1="192.168.1.1"
ip_addr2="10.1.1.1"
ip_addr3="172.16.1.1"
print ("\n")
print ("-" * 80)
print ("{my_ip:^20}{ip:^20}{ip_alt:^20}".format(ip_alt=ip_addr1, ip=ip_addr2, my_ip=ip_addr3))
print ("-" * 80)
print ("\n")
octets = ip_addr1.split('.')
|
"""
find the last item in a singly linked list
"""
#keep checking list until there is node has no next
def lastnode(linked_list, k):
if k <= 0:
return None
pointer2 = linkedlist.head
for i in range(k-1):
if pointer2.next != None:
pointer2 = pointer2.next
else:
return "loop"
pointer1 = linkedlist.head
while pointer2.next != None:
pointer2 = pointer2.next
pointer1 = pointer1.next
return pointer1
|
"""Define module exceptions."""
class SeventeenTrackError(Exception):
"""Define a base error."""
pass
class InvalidTrackingNumberError(SeventeenTrackError):
"""Define an error for an invalid tracking number."""
pass
class RequestError(SeventeenTrackError):
"""Define an error for HTTP request errors."""
pass
|
class Registers(object):
def __eq__(self, other) :
return self.__dict__ == other.__dict__
def __init__(self):
self.accumulator = 0
self.x_index = 0
self.y_index = 0
self.sp = 0xFD
self.pc = 0
self.carry_flag = False
self.zero_flag = False
self.interrupt_disable_flag = True
self.decimal_mode_flag = False
self.sw_interrupt = False
self.overflow_flag = False
self.negative_flag = False
def set_NZ(self, value):
self.negative_flag = (value & 0x80)
self.zero_flag = (value == 0)
def set_NZV(self, operand, result):
signbits_differ = (operand ^ self.accumulator) & 0x80
resultsign_differs = (operand ^ result) & 0x80
#print("a: {2} o:{0} r:{1}".format(operand, result, self.accumulator))
#print("rd:{0} sd:{1}".format(resultsign_differs, signbits_differ))
self.overflow_flag = resultsign_differs and not signbits_differ
self.set_NZ(result)
def status_register(self):
bits = 1 if self.overflow_flag else 0
bits |= 0x20 if self.decimal_mode_flag else 0
bits |= 0x40 if self.interrupt_disable_flag else 0
bits |= 0x10 if self.carry_flag else 0
bits |= 0x20 if self.zero_flag else 0
bits |= 0x40 if self.negative_flag else 0
return bits
|
def take_input():
"""Helper function to take input for a user"""
name_marks = input().split()
name = name_marks[0]
marks = [float(x) for x in name_marks[1:]]
return name, marks
def rank_user(users_name_list, users_score_lst):
"""Returns a dictionary. Key is user_name and values is rank"""
user_score = dict(zip(users_name_list, users_score_lst))
user_score = sorted(user_score.items(), key=lambda x: x[1], reverse=True)
rank_dict = {}
rank = 0
prev = float('-inf')
for idx, (key, val) in enumerate(user_score):
if prev == val:
rank_dict[key] = rank
else:
rank_dict[key] = rank+1
rank += 1
prev = val
return rank_dict
def find_topper():
"""Rank users based on mean score."""
# your code starts here.
print("Enter user_name and marks (space seperated)")
users_1, marks_1 = take_input()
users_2, marks_2 = take_input()
users_3, marks_3 = take_input()
users_1_mean_score = sum(marks_1)/len(marks_1)
users_2_mean_score = sum(marks_2)/len(marks_2)
users_3_mean_score = sum(marks_3)/len(marks_3)
user_lst = [users_1, users_2, users_3]
score_lst = [users_1_mean_score, users_2_mean_score, users_3_mean_score]
user_ranks = rank_user(user_lst, score_lst)
for name, rank in user_ranks.items():
print("{}: {}".format(name, rank))
if __name__ == '__main__':
find_topper()
|
class Solution:
def anagrams(self, strs):
key = lambda s: ''.join(sorted(s))
strs = sorted(strs, key=key)
strs = itertools.groupby(strs, key=key)
result = []
for k, g in strs:
l = list(g)
if len(l) == 1:
continue
result.extend(l)
return result
|
"""
파일 이름 : 11656.py
제작자 : 정지운
제작 날짜 : 2017년 7월 31일
"""
# 입력
s = input()
# 모든 접미사 리스트에 등록
lst = []
for i in range(len(s)):
lst.append(s[i:len(s)])
# 정렬 후 출력
lst.sort()
for i in range(len(lst)):
print(lst[i])
|
# Databricks notebook source
# MAGIC %md-sandbox
# MAGIC
# MAGIC <div style="text-align: center; line-height: 0; padding-top: 9px;">
# MAGIC <img src="https://databricks.com/wp-content/uploads/2018/03/db-academy-rgb-1200px.png" alt="Databricks Learning" style="width: 600px">
# MAGIC </div>
# COMMAND ----------
# MAGIC %md
# MAGIC
# MAGIC ## End-to-End ETL in the Lakehouse
# MAGIC
# MAGIC In this notebook, you will pull together concepts learned throughout the course to complete an example data pipeline.
# MAGIC
# MAGIC The following is a non-exhaustive list of skills and tasks necessary to successfully complete this exercise:
# MAGIC * Using Databricks notebooks to write queries in SQL and Python
# MAGIC * Creating and modifying databases, tables, and views
# MAGIC * Using Auto Loader and Spark Structured Streaming for incremental data processing in a multi-hop architecture
# MAGIC * Using Delta Live Table SQL syntax
# MAGIC * Configuring a Delta Live Table pipeline for continuous processing
# MAGIC * Using Databricks Jobs to orchestrate tasks from notebooks stored in Repos
# MAGIC * Setting chronological scheduling for Databricks Jobs
# MAGIC * Defining queries in Databricks SQL
# MAGIC * Creating visualizations in Databricks SQL
# MAGIC * Defining Databricks SQL dashboards to review metrics and results
# COMMAND ----------
# MAGIC %md
# MAGIC ## Run Setup
# MAGIC Run the following cell to reset all the databases and directories associated with this lab.
# COMMAND ----------
# MAGIC %run ../../Includes/classroom-setup-dlt-lab
# COMMAND ----------
# MAGIC %md
# MAGIC ## Land Initial Data
# MAGIC Seed the landing zone with some data before proceeding.
# COMMAND ----------
DA.data_factory.load()
# COMMAND ----------
# MAGIC %md
# MAGIC ## Create and Configure a DLT Pipeline
# MAGIC **NOTE**: The main difference between the instructions here and in previous labs with DLT is that in this instance, we will be setting up our pipeline for **Continuous** execution in **Production** mode.
# MAGIC
# MAGIC Steps:
# MAGIC 1. Click the **Jobs** button on the sidebar, then select the **Delta Live Tables** tab.
# MAGIC 1. Click **Create Pipeline**.
# MAGIC 1. Fill in a **Pipeline Name** of your choosing.
# MAGIC 1. For **Notebook Libraries**, use the navigator to locate and select the notebook **1 - DLT Task**.
# MAGIC 1. Run the cell below to generate values for **source**, **Target** and **Storage Location**. (All of these will include your current username).
# MAGIC * Click **Add configuration**; enter the word **source** in the **Key** field and the output printed next to **source** below in the value field.
# MAGIC * Enter the database name printed next to **Target** below in the **Target** field.
# MAGIC * Enter the location printed next to **Storage Location** below in the **Storage Location** field.
# MAGIC 1. Set **Pipeline Mode** to **Continuous**.
# MAGIC 1. Disable autoscaling.
# MAGIC 1. Set the number of workers to 1.
# MAGIC 1. Click **Create**.
# MAGIC
# MAGIC In the UI that populates, change from **Development** to **Production** mode. This should begin the deployment of infrastructure.
# COMMAND ----------
print(f"source: {DA.paths.data_landing_location}")
print(f"Target: {DA.db_name}")
print(f"Storage Location: {DA.paths.storage_location}")
# COMMAND ----------
# MAGIC %md
# MAGIC ## Schedule a Notebook Job
# MAGIC
# MAGIC Our DLT pipeline is setup to process data as soon as it arrives. We'll schedule a notebook to land a new batch of data each minute so we can see this functionality in action.
# MAGIC
# MAGIC Steps:
# MAGIC 1. Navigate to the Jobs UI using the Databricks left side navigation bar.
# MAGIC 1. Click the blue **Create Job** button
# MAGIC 1. Configure the task:
# MAGIC 1. Enter **Land-Data** for the task name
# MAGIC 1. Select the notebook **2 - Land New Data** using the notebook picker
# MAGIC 1. Select an Existing All Purpose Cluster from the **Cluster** dropdown
# MAGIC 1. Click **Create**
# MAGIC
# MAGIC **Note**: When selecting your all purpose cluster, you will get a warning about how this will be billed as all purpose compute. Production jobs should always be scheduled against new job clusters appropriately sized for the workload, as this is billed at a much lower rate.
# MAGIC
# MAGIC ## Set a Chronological Schedule for your Job
# MAGIC Steps:
# MAGIC * On the right hand side of the Jobs UI, locate **Schedule** section.
# MAGIC * Click on the **Edit schedule** button to explore scheduling options.
# MAGIC * Change **Schedule type** field from **Manual** to **Scheduled** will bring up a chron scheduling UI.
# MAGIC * Set the schedule to update every **2 minutes**
# MAGIC * Click **Save**
# MAGIC
# MAGIC **NOTE**: If you wish, you can click **Run now** to trigger the first run, or wait until the top of the next minute to make sure your scheduling has worked successfully.
# COMMAND ----------
# MAGIC %md
# MAGIC ## Register DLT Event Metrics for Querying with DBSQL
# MAGIC
# MAGIC The following cell prints out SQL statements to register the DLT event logs to your target database for querying in DBSQL.
# MAGIC
# MAGIC Execute the output code with the DBSQL Query Editor to register these tables and views.
# MAGIC
# MAGIC Explore each and make note of the logged event metrics.
# COMMAND ----------
DA.generate_register_dlt_event_metrics_sql()
# COMMAND ----------
# SOURCE-ONLY
# Will use this later to refactor in testing
for command in generate_register_dlt_event_metrics_sql_string.split(";"):
if len(command) > 0:
print(command)
print("-"*80)
# COMMAND ----------
# MAGIC %md
# MAGIC ## Define a Query on the Gold Table
# MAGIC
# MAGIC The **daily_patient_avg** table is automatically updated each time a new batch of data is processed through the DLT pipeline. Each time a query is executed against this table, DBSQL will confirm if there is a newer version and then materialize results from the newest available version.
# MAGIC
# MAGIC Run the following cell to print out a query with your database name. Save this as a DBSQL query.
# COMMAND ----------
DA.generate_daily_patient_avg()
# COMMAND ----------
# MAGIC %md
# MAGIC ## Add a Line Plot Visualization
# MAGIC
# MAGIC To track trends in patient averages over time, create a line plot and add it to a new dashboard.
# MAGIC
# MAGIC Create a line plot with the following settings:
# MAGIC * **X Column**: **`date`**
# MAGIC * **Y Columns**: **`avg_heartrate`**
# MAGIC * **Group By**: **`name`**
# MAGIC
# MAGIC Add this visualization to a dashboard.
# COMMAND ----------
# MAGIC %md
# MAGIC ## Track Data Processing Progress
# MAGIC
# MAGIC The code below extracts the **`flow_name`**, **`timestamp`**, and **`num_output_rows`** from the DLT event logs.
# MAGIC
# MAGIC Save this query in DBSQL, then define a bar plot visualization that shows:
# MAGIC * **X Column**: **`timestamp`**
# MAGIC * **Y Columns**: **`num_output_rows`**
# MAGIC * **Group By**: **`flow_name`**
# MAGIC
# MAGIC Add your visualization to your dashboard.
# COMMAND ----------
DA.generate_visualization_query()
# COMMAND ----------
# MAGIC %md
# MAGIC ## Refresh your Dashboard and Track Results
# MAGIC
# MAGIC The **Land-Data** notebook scheduled with Jobs above has 12 batches of data, each representing a month of recordings for our small sampling of patients. As configured per our instructions, it should take just over 20 minutes for all of these batches of data to be triggered and processed (we scheduled the Databricks Job to run every 2 minutes, and batches of data will process through our pipeline very quickly after initial ingestion).
# MAGIC
# MAGIC Refresh your dashboard and review your visualizations to see how many batches of data have been processed. (If you followed the instructions as outlined here, there should be 12 distinct flow updates tracked by your DLT metrics.) If all source data has not yet been processed, you can go back to the Databricks Jobs UI and manually trigger additional batches.
# COMMAND ----------
# MAGIC %md
# MAGIC ## Execute a Query to Repair Broken Data
# MAGIC
# MAGIC Review the code that defined the **`recordings_enriched`** table to identify the filter applied for the quality check.
# MAGIC
# MAGIC In the cell below, write a query that returns all the records from the **`recordings_bronze`** table that were refused by this quality check.
# COMMAND ----------
# MAGIC %sql
# MAGIC -- ANSWER
# MAGIC SELECT * FROM ${da.db_name}.recordings_bronze WHERE heartrate <= 0
# COMMAND ----------
# MAGIC %md
# MAGIC For the purposes of our demo, let's assume that thorough manual review of our data and systems has demonstrated that occasionally otherwise valid heartrate recordings are returned as negative values.
# MAGIC
# MAGIC Run the following query to examine these same rows with the negative sign removed.
# COMMAND ----------
# MAGIC %sql
# MAGIC SELECT abs(heartrate), * FROM ${da.db_name}.recordings_bronze WHERE heartrate <= 0
# COMMAND ----------
# MAGIC %md
# MAGIC To complete our dataset, we wish to insert these fixed records into the silver **`recordings_enriched`** table.
# MAGIC
# MAGIC Use the cell below to update the query used in the DLT pipeline to execute this repair.
# MAGIC
# MAGIC **NOTE**: Make sure you update the code to only process those records that were previously rejected due to the quality check.
# COMMAND ----------
# MAGIC %sql
# MAGIC -- ANSWER
# MAGIC -- The difference between this ANSWER cell and the TODO cell,
# MAGIC -- where it appears to not be the same code, is intentional per Douglas Strodtman
# MAGIC
# MAGIC MERGE INTO ${da.db_name}.recordings_enriched t
# MAGIC USING (SELECT
# MAGIC CAST(a.device_id AS INTEGER) device_id,
# MAGIC CAST(a.mrn AS LONG) mrn,
# MAGIC abs(CAST(a.heartrate AS DOUBLE)) heartrate,
# MAGIC CAST(from_unixtime(a.time, 'yyyy-MM-dd HH:mm:ss') AS TIMESTAMP) time,
# MAGIC b.name
# MAGIC FROM ${da.db_name}.recordings_bronze a
# MAGIC INNER JOIN ${da.db_name}.pii b
# MAGIC ON a.mrn = b.mrn
# MAGIC WHERE heartrate <= 0) v
# MAGIC ON t.mrn=v.mrn AND t.time=v.time
# MAGIC WHEN NOT MATCHED THEN INSERT *
# COMMAND ----------
# MAGIC %md
# MAGIC Use the cell below to manually or programmatically confirm that this update has been successful.
# MAGIC
# MAGIC (The total number of records in the **`recordings_bronze`** should now be equal to the total records in **`recordings_enriched`**).
# COMMAND ----------
# ANSWER
assert spark.table(f"{DA.db_name}.recordings_bronze").count() == spark.table(f"{DA.db_name}.recordings_enriched").count()
# COMMAND ----------
# MAGIC %md
# MAGIC ## Consider Production Data Permissions
# MAGIC
# MAGIC Note that while our manual repair of the data was successful, as the owner of these datasets, by default we have permissions to modify or delete these data from any location we're executing code.
# MAGIC
# MAGIC To put this another way: our current permissions would allow us to change or drop our production tables permanently if an errant SQL query is accidentally executed with the current user's permissions (or if other users are granted similar permissions).
# MAGIC
# MAGIC While for the purposes of this lab, we desired to have full permissions on our data, as we move code from development to production, it is safer to leverage <a href="https://docs.databricks.com/administration-guide/users-groups/service-principals.html" target="_blank">service principals</a> when scheduling Jobs and DLT Pipelines to avoid accidental data modifications.
# COMMAND ----------
# MAGIC %md
# MAGIC ## Shut Down Production Infrastructure
# MAGIC
# MAGIC Note that Databricks Jobs, DLT Pipelines, and scheduled DBSQL queries and dashboards are all designed to provide sustained execution of production code. In this end-to-end demo, you were instructed to configure a Job and Pipeline for continuous data processing. To prevent these workloads from continuing to execute, you should **Pause** your Databricks Job and **Stop** your DLT pipeline. Deleting these assets will also ensure that production infrastructure is terminated.
# MAGIC
# MAGIC **NOTE**: All instructions for DBSQL asset scheduling in previous lessons instructed users to set the update schedule to end tomorrow. You may choose to go back and also cancel these updates to prevent DBSQL endpoints from staying on until that time.
# COMMAND ----------
DA.cleanup()
# COMMAND ----------
# MAGIC %md-sandbox
# MAGIC © 2022 Databricks, Inc. All rights reserved.<br/>
# MAGIC Apache, Apache Spark, Spark and the Spark logo are trademarks of the <a href="https://www.apache.org/">Apache Software Foundation</a>.<br/>
# MAGIC <br/>
# MAGIC <a href="https://databricks.com/privacy-policy">Privacy Policy</a> | <a href="https://databricks.com/terms-of-use">Terms of Use</a> | <a href="https://help.databricks.com/">Support</a>
|
class RebarContainerParameterManager(object,IDisposable):
""" Provides implementation of RebarContainer parameters overrides. """
def AddOverride(self,paramId,value):
"""
AddOverride(self: RebarContainerParameterManager,paramId: ElementId,value: int)
Adds an override for the given parameter as its value will be displayed for the
Rebar Container element.
paramId: The id of the parameter
value: The override value of the parameter.
AddOverride(self: RebarContainerParameterManager,paramId: ElementId,value: float)
Adds an override for the given parameter as its value will be displayed for the
Rebar Container element.
paramId: The id of the parameter
value: The override value of the parameter.
AddOverride(self: RebarContainerParameterManager,paramId: ElementId,value: ElementId)
Adds an override for the given parameter as its value will be displayed for the
Rebar Container element.
paramId: The id of the parameter
value: The override value of the parameter.
AddOverride(self: RebarContainerParameterManager,paramId: ElementId,value: str)
Adds an override for the given parameter as its value will be displayed for the
Rebar Container element.
paramId: The id of the parameter
value: The override value of the parameter.
"""
pass
def AddSharedParameterAsOverride(self,paramId):
"""
AddSharedParameterAsOverride(self: RebarContainerParameterManager,paramId: ElementId)
Adds a shared parameter as one of the parameter overrides stored by this Rebar
Container element.
paramId: The id of the shared parameter element
"""
pass
def ClearOverrides(self):
"""
ClearOverrides(self: RebarContainerParameterManager)
Clears any overridden values from all parameters of the associated
RebarContainer element.
"""
pass
def Dispose(self):
""" Dispose(self: RebarContainerParameterManager) """
pass
def IsOverriddenParameterModifiable(self,paramId):
"""
IsOverriddenParameterModifiable(self: RebarContainerParameterManager,paramId: ElementId) -> bool
Checks if overridden parameter is modifiable.
paramId: Overridden parameter id
Returns: True if the parameter is modifiable,false if the parameter is readonly.
"""
pass
def IsParameterOverridden(self,paramId):
"""
IsParameterOverridden(self: RebarContainerParameterManager,paramId: ElementId) -> bool
Checks if the parameter has an override
paramId: The id of the parameter element
Returns: True if the parameter has an override
"""
pass
def IsRebarContainerParameter(self,paramId):
"""
IsRebarContainerParameter(self: RebarContainerParameterManager,paramId: ElementId) -> bool
Checks if the parameter is a Rebar Container parameter
paramId: The id of the parameter element
Returns: True if the parameter is a Rebar Container parameter
"""
pass
def ReleaseUnmanagedResources(self,*args):
""" ReleaseUnmanagedResources(self: RebarContainerParameterManager,disposing: bool) """
pass
def RemoveOverride(self,paramId):
"""
RemoveOverride(self: RebarContainerParameterManager,paramId: ElementId)
Removes an overridden value from the given parameter.
paramId: The id of the parameter
"""
pass
def SetOverriddenParameterModifiable(self,paramId):
"""
SetOverriddenParameterModifiable(self: RebarContainerParameterManager,paramId: ElementId)
Sets this overridden parameter to be modifiable.
paramId: Overridden parameter id
"""
pass
def SetOverriddenParameterReadonly(self,paramId):
"""
SetOverriddenParameterReadonly(self: RebarContainerParameterManager,paramId: ElementId)
Sets this overridden parameter to be readonly.
paramId: Overridden parameter id
"""
pass
def __enter__(self,*args):
""" __enter__(self: IDisposable) -> object """
pass
def __exit__(self,*args):
""" __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
def __repr__(self,*args):
""" __repr__(self: object) -> str """
pass
IsValidObject=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Specifies whether the .NET object represents a valid Revit entity.
Get: IsValidObject(self: RebarContainerParameterManager) -> bool
"""
|
# MIT License
#
# Copyright (c) 2019 Michael J Simms. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
def is_point_in_polygon(point, poly):
"""Implements the ray casting/crossing number algorithm. Returns TRUE if the point is within the bounds of the points that specify the polygon (poly is a list of points)."""
# Sanity checks.
if not isinstance(poly, list):
return False
num_crossings = 0
num_vertices = len(poly)
if num_vertices < 3: # Need at least three points to make a polygon
return False
test_x = point['x']
test_y = point['y']
for i in range(0, num_vertices):
# Cache the y coordinate for the first point on the edge.
poly_pt = poly[i]
poly_pt1_y = poly_pt['y']
# Cache the second point on the edge, handling the wrap around that happens when we close the polygon.
if i == num_vertices - 1:
poly_pt = poly[0]
poly_pt2_x = poly_pt['x']
poly_pt2_y = poly_pt['y']
else:
poly_pt = poly[i + 1]
poly_pt2_x = poly_pt['x']
poly_pt2_y = poly_pt['y']
# Test if the point is within the y limits of the edge.
crosses_y = ((poly_pt1_y <= test_y) and (poly_pt2_y > test_y)) or ((poly_pt1_y > test_y) and (poly_pt2_y <= test_y))
if crosses_y:
# Test if the ray extending to the right of the point crosses the edge.
poly_pt1_x = (poly[i])['x']
if test_x < poly_pt1_x + ((test_y - poly_pt1_y) / (poly_pt2_y - poly_pt1_y)) * (poly_pt2_x - poly_pt1_x):
num_crossings = num_crossings + 1
return num_crossings & 1
def is_point_in_poly_array(test_x, test_y, poly):
"""Implements the ray casting/crossing number algorithm. Returns TRUE if the point is within the bounds of the points that specify the polygon (poly is a list of points)."""
# Sanity checks.
if not isinstance(poly, list):
return False
num_crossings = 0
num_vertices = len(poly)
if num_vertices < 3: # Need at least three points to make a polygon
return False
for i in range(0, num_vertices):
# Cache the y coordinate for the first point on the edge.
poly_pt = poly[i]
if len(poly_pt) != 2:
return False
poly_pt1_y = poly_pt[1]
# Cache the second point on the edge, handling the wrap around that happens when we close the polygon.
if i == num_vertices - 1:
poly_pt = poly[0]
poly_pt2_x = poly_pt[0]
poly_pt2_y = poly_pt[1]
else:
poly_pt = poly[i + 1]
poly_pt2_x = poly_pt[0]
poly_pt2_y = poly_pt[1]
# Test if the point is within the y limits of the edge.
crosses_y = ((poly_pt1_y <= test_y) and (poly_pt2_y > test_y)) or ((poly_pt1_y > test_y) and (poly_pt2_y <= test_y))
if crosses_y:
# Test if the ray extending to the right of the point crosses the edge.
poly_pt1_x = (poly[i])[0]
if test_x < poly_pt1_x + ((test_y - poly_pt1_y) / (poly_pt2_y - poly_pt1_y)) * (poly_pt2_x - poly_pt1_x):
num_crossings = num_crossings + 1
return num_crossings & 1
|
# Meta classes
class Meta(type):
def __new__(self, class_name, bases, attrs):
print(attrs)
a = {}
for name, val in attrs.items():
if name.startswith("__"):
a[name] = val
else:
a[name.upper()] = val
return type(class_name, bases, a)
class Dog(metaclass=Meta):
x = 5
y = 8
def hello(self):
print("hi")
d = Dog()
print(d.HELLO())
|
def listifyer(word):
listify = list(word)
return listify
def rearrPL(word):
seperator = ','
del word[-1]
del word[-1]
last_element = word[(len(word) - 1)]
word.insert(0, last_element)
del word[-1]
new_word = seperator.join(word)
return new_word
def rearrE(word):
first_letter = word[0]
seperator = ','
word.remove(word[0])
word.append(first_letter)
word.append("a")
word.append("y")
new_word = seperator.join(word)
return new_word
def PL2E():
theWord = input("What word are we translating?: ")
listified_word = listifyer(theWord)
rearranged_word = rearrPL(listified_word)
translated_word1 = rearranged_word.replace(",", "")
translated_word2 = translated_word1.lower()
translated_word3 = translated_word2.capitalize()
print(theWord + " ----> " + translated_word3)
def E2PL():
theWord = input("What word are we translating?: ")
listified_word = listifyer(theWord)
rearranged_word = rearrE(listified_word)
translated_word1 = rearranged_word.replace(",", "")
translated_word2 = translated_word1.lower()
translated_word3 = translated_word2.capitalize()
print(theWord + " ----> " + translated_word3)
def choose():
usrint = input(
"What are we translating to?: \npig latin or english(p/e): ")
if usrint == "p":
E2PL()
elif usrint == 'e':
PL2E()
else:
print("That's not an option choose (p/e)")
choose()
choose()
|
# -*- coding: utf-8 -*-
# cython:language_level=3
"""
-------------------------------------------------
File Name: surfExpression
Description :
Author : liaozhaoyan
date: 2021/12/24
-------------------------------------------------
Change Activity:
2021/12/24:
-------------------------------------------------
"""
__author__ = 'liaozhaoyan'
probeReserveVars = ('common_pid', 'common_preempt_count', 'common_flags', 'common_type')
archRegd = {'x86_64': ('di', 'si', 'dx', 'cx', 'r8', 'r9', 'ax', 'bx',
'sp', 'bp', 'r10', 'r11', 'r12', 'r13', 'r14', 'r15',),
'x86': ('di', 'si', 'dx', 'cx'),
'aarch64': ('x0', 'x1', 'x2', 'x3', 'x4', 'x5', 'x6', 'x7', 'x8', 'x9',
'x10', 'x11', 'x12', 'x13', 'x14', 'x15', 'x16', 'x17', 'x18', 'x19',
'x20', 'x21', 'x22', 'x23', 'x24', 'x25', 'x26', 'x27', 'x28', 'x29',
'x30', 'x31'),}
class ExprException(Exception):
def __init__(self, message):
super(ExprException, self).__init__(message)
self.message = message
def maxNameString(cells, t):
rs = cells[0][t]
ret = ""
for i, r in enumerate(rs):
for f in cells[1:]:
sFunc = f[t]
if len(sFunc) < i or sFunc[i] != r:
return ret
ret += r
return ret
def isStruct(text):
strips = ("const ", "volatile ")
for s in strips:
text = text.replace(s, "")
text = text.strip()
if text.startswith("struct ") or text.startswith("union "):
return text
return None
def splitExpr(text):
es = []
e = ""
count = 0
for c in text:
if c == '(':
count += 1
elif c == ")":
count -= 1
if count < 0:
return None
elif count == 0 and c == " ":
if e != "": es.append(e)
e = ""
continue
e += c
if e != "": es.append(e)
return es
def spiltInputLine(line):
res = {}
es = splitExpr(line)
esLen = len(es)
if esLen < 2:
raise ExprException("%s is a single expression" % line)
if es[0] not in ('p', 'r', 'e'):
raise ExprException("not support %s event." % es[0])
res['type'] = es[0]
res['symbol'] = es[1]
if esLen >= 3:
if es[-1].startswith("f:"):
res['filter'] = es[-1][2:]
res['args'] = " ".join(es[2:-1])
else:
res['filter'] = ""
res['args'] = " ".join(es[2:])
else:
res['filter'] = ""; res['args'] = ""
return res
def unpackRes(res):
s = "%s %s" % (res['type'], res['symbol'])
if res['filter'] == "":
if res['args'] == "":
return s
else:
return s + " %s" % res['args']
else:
if res['args'] == "":
return s + " f:%s" % res['filter']
else:
return s + " %s f:%s" % (res['args'], res['filter'])
def stripPoint(sStruct):
return sStruct.strip("*").strip()
def regIndex(reg, arch='x86'):
regs = archRegd[arch]
try:
return regs.index(reg)
except ValueError:
raise ExprException('%s is not a %s register.' % (reg, arch))
def transReg(i, arch='x86'):
try:
return archRegd[arch][i]
except IndexError:
raise ExprException('reg index %d overflow.' % i)
if __name__ == "__main__":
s = "p __netif_receive_skb_core proto=%0~$(struct iphdr)l3->protocol ip_src=%0~$(struct iphdr)l3->saddr ip_dst=%0~$(struct iphdr)->daddr type=%0~$(struct icmphdr)l3->type data=%0~$(struct icmphdr)l3->sdata[1] f:proto==1&&ip_src==127.0.0.1"
print(spiltInputLine(s))
pass
|
mortgage = 366323
agent_fee = .06
prorated_property_taxes = 400
prorated_mortgage_interest = 1500
other_fees = 2500
closing_costs = prorated_property_taxes + prorated_mortgage_interest + other_fees
sale_price = input('What is the sale price of your home? ')
agent_cost = agent_fee * float(sale_price)
price_per_sqft = (float(sale_price) / 3160)
proceeds = (float(sale_price) - mortgage - closing_costs - agent_cost)
print('Your closing costs will be $' + str(closing_costs))
print()
print('Your agent cost is ${:,.2f}'.format(agent_cost))
print()
print('Your price per sqft is ${:,.2f}'.format(price_per_sqft))
print()
print('Your proceeds from the sale will be ${:,.2f}'.format(proceeds))
|
"""
ipcai2016
Copyright (c) German Cancer Research Center,
Computer Assisted Interventions.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE for details
"""
|
# -*- coding: utf-8 -*-
"""Top-level package for Django CMS export page."""
__author__ = """Maykin Media"""
__email__ = '[email protected]'
__version__ = '0.1.0'
|
_base_ = './mask_rcnn_r50_fpn_gn_ws-all_2x_coco.py'
model = dict(
backbone=dict(
depth=101,
init_cfg=dict(
type='Pretrained', checkpoint='open-mmlab://jhu/resnet101_gn_ws')))
|
"""Sample package."""
MORSE_MAPPING = {
"A": ".-",
"B": "-...",
"C": "-.-.",
"D": "-..",
"E": ".",
"F": "..-.",
"G": "--.",
"H": "....",
"I": "..",
"J": ".---",
"K": "-.-",
"L": ".-..",
"M": "--",
"N": "-.",
"O": "---",
"P": ".--.",
"Q": "--.-",
"R": ".-.",
"S": "...",
"T": "-",
"U": "..-",
"V": "...-",
"W": ".--",
"X": "-..-",
"Y": "-.--",
"Z": "--..",
"1": ".----",
"2": "..---",
"3": "...--",
"4": "....-",
"5": ".....",
"6": "-....",
"7": "--...",
"8": "---..",
"9": "----.",
"0": "-----",
".": ".-.-.-",
",": "--..--",
"?": "..--..",
":": "---...",
";": "_._._.",
"'": ".----.",
'"': ".-..-.",
"(": "-.--.",
")": "-.--.-",
"/": "-..-.",
"-": "-....-",
"=": "-...-",
"+": ".-.-.",
"!": "-.-.--",
"&": ".-...",
"_": "..--.-",
"$": "...-..-",
"¿": "..-.-",
"¡": "--...-",
"@": ".--.-.",
" ": "/",
}
REVERSE_MAPPING = {value: key for key, value in MORSE_MAPPING.items()}
def encode(string: str) -> str:
"""Convert a string to morse code."""
string = string.upper()
return " ".join(MORSE_MAPPING[char] for char in string if char in MORSE_MAPPING)
def decode(string: str) -> str:
"""Convert morse code to string."""
return "".join(REVERSE_MAPPING.get(code, "") for code in string.split())
|
'''
Author : MiKueen
Level : Medium
Problem Statement : Find First and Last Position of Elements in Sorted Array
Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
Example 1:
Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
Example 2:
Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]
'''
class Solution:
def searchLeft(self, nums, target):
low, high = 0, len(nums) - 1
while low <= high:
mid = (low + high) // 2
if target > nums[mid]:
low = mid + 1
else:
high = mid - 1
return low
def searchRight(self, nums, target):
low, high = 0, len(nums) - 1
while low <= high:
mid = (low + high) // 2
if target >= nums[mid]:
low = mid + 1
else:
high = mid - 1
return high
def searchRange(self, nums: List[int], target: int) -> List[int]:
left_res = self.searchLeft(nums, target)
right_res = self.searchRight(nums, target)
if left_res <= right_res:
return (left_res, right_res)
else:
return [-1, -1]
|
###########################################
# EXERCICIO 055 #
###########################################
'''FAÇA UM PROGRAMA QUE LEIA O PESO DE 5
PESSOAS. NO FINAL MOSTRE QUAL FOI O MAIOR
E O MENOR PESO'''
maior = 0
menor = 0
for c in range(1,6):
peso = float(input('PESO DA {}ª PESSOA: '.format(c)))
if c == 1:
maior = peso
menor = peso
else:
if peso > maior:
maior = peso
if peso < menor:
menor = peso
print('{} KG foi o menor peso e {} KG foi o maior'.format(menor,maior))
|
totidade = homens = mulheresmenores = 0
while True:
print('-'*20)
print('Cadastre uma pessoa')
print('-'*20)
idade = int(input('Idade: '))
sexo = ' '
while sexo not in 'MF':
sexo = str(input('Sexo: [M/F]')).strip().upper()[0]
cont = ' '
while cont not in 'SN':
cont = str(input('Quer continuar? [S/N]: ')).upper().strip()[0]
if cont == 'S':
if idade > 18:
totidade += 1
if sexo == 'M':
homens += 1
if sexo == 'F' and idade < 20:
mulheresmenores += 1
else:
print(f'Total de pessoas com mais de 18 anos: {totidade}')
print(f'Ao todo temos {homens} homens cadastrados')
print(f'E temos {mulheresmenores} mulheres com menos de 20 anos!')
break
|
def get_build_tool(name):
tools = {
"cmake": CMakeBuildTool,
"colcon": ColconBuildTool,
"catkin": CatkinBuildTool
}
if name not in tools:
raise Exception("Unknown build tool: {}".format(name))
return tools[name]
class BuildTool():
@staticmethod
def getCommands():
return [k for k in self.commands.keys()]
def executeCommand(self, command, args):
if command in self.commands:
return self.commands[command](args)
raise Exception("BuildEnv [{}] from [{}] does not have command [{}]".format(type(self), self.root_dir, command))
def __init__(self, config):
self.commands = {}
def getBuildCommand(self, args):
raise Exception("getBuildCommand() not implemented in {}".format(type(self)))
class CMakeBuildTool(BuildTool):
def getBuildCommand(self, args):
return "mkdir -p build/ && cd build/ && cmake .. && make {}".format(args)
class ColconBuildTool(BuildTool):
def getBuildCommand(self, args):
return "colcon build {}".format(args)
class CatkinBuildTool(BuildTool):
def getBuildCommand(self, args):
return "catkin build {}".format(args)
|
number = input('Enter a number: ')
number = int(number)
if number % 2 == 0:
print('The number is even')
else:
print('The number is odd')
|
print("input 5 decimals")
values = []
for i in range(5):
values.append(float(input("demical #"+str(i+1)+": ")))
cnt = 0
for i in values:
if i >= 10 and i <= 100:
cnt += 1
print(cnt)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on 2018-11-11
@author: marcel-odya
'''
base = [
["właśnie teraz", "za chwilę"],
["%s sekund temu", "za %s sekund", "%s sekundy temu", "za %s sekundy"],
["minutę temu", "za minutę"],
["%s minut temu", "za %s minut", "%s minuty temu", "za %s minuty"],
["godzinę temu", "za godzinę"],
["%s godzin temu", "za %s godzin", "%s godziny temu", "za %s godziny"],
["1 dzień temu", "za 1 dzień"],
["%s dni temu", "za %s dni", "%s dni temu", "za %s dni"],
["tydzień temu", "za tydzień"],
["%s tygodni temu", "za %s tygodni", "%s tygodnie temu", "za %s tygodnie"],
["miesiąc temu", "za miesiąc"],
["%s miesięcy temu", "za %s miesięcy", "%s miesiące temu", "za %s miesiące"],
["rok temu", "za rok"],
["%s lat temu", "za %s lat", "%s lata temu", "za %s lata"]
]
def generate(row, y):
def formatting(time):
'''
Uses the 3rd and 4th field of the list in every 2 entries -
the ones containing %s, if the diff ends with 2, 3 or 4 but
not with 12, 13 or 14.
'''
if row % 2 == 0:
return base[row][y]
last_number = time % 10
last_two_numbers = time % 100
if last_number in range(2, 5) and last_two_numbers not in range(12, 15):
return base[row][y + 2]
return base[row][y]
return formatting
LOCALE = generate
|
# 3. n children have got m pieces of candy. They want to eat as much candy as they can, but each child must eat exactly the same amount of candy as any other child. Determine how many pieces of candy will be eaten by all the children together. Individual pieces of candy cannot be split.
# Example
# For n = 3 and m = 10, the output should be
# candies(n, m) = 9.
# Each child will eat 3 pieces. So the answer is 9.
def candies(n, m):
result = m - (m % n)
return result
print(candies(4, 25))
|
def install_file(name, src, out):
"""
Install a single file, using `install`. Returns out, so that it can be easily
embedded into a filegroup rule.
"""
native.genrule(
name = name,
srcs = [src],
outs = [out],
cmd = "install -c -m 644 $(location {}) $(location {})".format(src, out),
)
return out
def _validate_prefix(prefix, avoid):
"""
Validate an install prefix.
"""
if prefix.startswith(avoid):
rest = prefix[0:len(avoid)]
return rest != "/" and rest != ""
return True
def install_dir(src_prefix, out_prefix):
"""
Copy all files under `src_prefix` to `out_prefix`. Returns the list of out
files, for use in a `filegroup` rule.
"""
if not _validate_prefix(src_prefix, out_prefix):
fail(msg = "invalid src_prefix")
if not _validate_prefix(out_prefix, src_prefix):
fail(msg = "invalid out_prefix")
# normalize src_prefix to end with a trailing slash
prefix_len = len(src_prefix)
if src_prefix != "" and src_prefix[-1] != "/":
prefix_len += 1
# normalize out_prefix to end with a trailing slash
if out_prefix != "" and out_prefix[-1] != "/":
out_prefix += "/"
outs = []
for src in native.glob(["{}/**/*".format(src_prefix)]):
out_name = "install_{}".format(src)
base = src[prefix_len:]
out = out_prefix + base
outs.append(out)
install_file(name = out_name, src = src, out = out)
return outs
|
test = {
'name': 'lab1_p1',
'suites': [
{
'cases': [
{
'code': r"""
>>> # It looks like your variable is not named correctly.
>>> # Please check for a typo. The variable name should be
>>> # my_favorite_things_lst
>>> 'my_favorite_things_lst' in vars()
True
"""
},
{
'code': r"""
>>> # The variable name is good you need to have at least three values.
>>> len(my_favorite_things_lst) >= 3
True
"""
}
]
}
]
}
|
"""Cascade Mask RCNN with ResNet101-FPN, 3x schedule, MS training."""
_base_ = "./cascade_mask_rcnn_r50_fpn_3x_ins_seg_bdd100k.py"
model = dict(
backbone=dict(
depth=101,
init_cfg=dict(type="Pretrained", checkpoint="torchvision://resnet101"),
)
)
load_from = "https://dl.cv.ethz.ch/bdd100k/ins_seg/models/cascade_mask_rcnn_r101_fpn_3x_ins_seg_bdd100k.pth"
|
'''error pattern'''
class A:
def __init__(self, text):
print('a')
print(text)
class B(A):
def __init__(self, text):
print('b')
super(B, self).__init__(text)
class C:
def __init__(self, **kwargs):
print('c')
super(C, self).__init__()
class D(C, B):
def __init__(self, text):
print('d')
super(D, self).__init__(text=text)
D('aaa')
|
def test_restart_opencart_mysql_service(restart_mysql):
assert "active (running)" in restart_mysql
print(restart_mysql)
def test_restart_opencart_apache_service(restart_apache):
assert "active (running)" in restart_apache
print(restart_apache)
def test_opencart_is_active(request_opencart):
print(request_opencart.status_code)
assert request_opencart.status_code == 200
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
List Comprehensions 列表推导式
对序列或可迭代对象中的每个元素应用某种操作,用生成的结果创建新的列表;或用满足特定条件的元素创建子序列。
"""
squares = [x * x for x in range(1, 5)]
print(squares)
even_l = [x ** 2 for x in range(1, 11) if x % 2 == 0]
print(even_l)
num_l = [x if x % 2 == 1 else -x for x in range(1, 11)]
print(num_l)
combs = [x + y for x in 'ABC' for y in '12']
print(combs)
d = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}
d1 = [k + '=' + v for k, v in d.items()]
print(d1)
|
def fatorial(n):
nFatorial=n
for i in range(1,n):
nFatorial=nFatorial*(n-i)
return nFatorial
|
class Solution:
def dayOfTheWeek(self, day: int, month: int, year: int) -> str:
num2day = ['Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday']
mon2num = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
count = 0
for i in range(1971, year):
if i % 400 == 0 or (i % 4 == 0 and i % 100 != 0):
count += 366
else:
count += 365
if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0): mon2num[2] += 1
return num2day[(count + sum(mon2num[:month]) + day) % 7]
|
def preenchimento_de_vetor_iv():
n = 0
par = list()
impar = list()
while n < 15:
numero = int(input())
if numero % 2 == 0:
par.append(numero)
else:
impar.append(numero)
if len(par) == 5:
for i in range(5):
print(f'par[{i}] = {par[i]}')
par = list()
elif len(impar) == 5:
for j in range(5):
print(f'impar[{j}] = {impar[j]}')
impar = list()
n += 1
for k in range(len(impar)):
print(f'impar[{k}] = {impar[k]}')
for t in range(len(par)):
print(f'par[{t}] = {par[t]}')
preenchimento_de_vetor_iv()
|
# -*- coding: utf-8 -*-
# @Time : 2018/4/12 20:16
# @Author : ddvv
# @Site : http://ddvv.life
# @File : __init__.py.py
# @Software: PyCharm
def main():
pass
if __name__ == "__main__":
main()
|
n= int(input())
alfabeto = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i in range(n):
letras=input()
pulos=int(input())
novaPalavra=""
for j in range(len(letras)):
posicao=alfabeto.find(letras[j])
numeroPosicao=posicao-pulos
if numeroPosicao<0:
novaPosicao=len(alfabeto)+numeroPosicao
novaPalavra = novaPalavra + alfabeto[novaPosicao]
else:
novaPosicao=numeroPosicao
novaPalavra=novaPalavra+alfabeto[novaPosicao]
print(novaPalavra)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.