content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
#!/usr/bin/env python3
#
# util/generate_small_constants_test.py
#
# Copyright (c) 2018 David Creswick
#
# Licensed under the Apache License, Version 2.0
# <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
# license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
# option. All files in the project carrying such notice may not be copied,
# modified, or distributed except according to those terms.
# simple sieve of Eratosthenes
N = 1024
is_prime = [True]*(N+1)
is_prime[0] = False
is_prime[1] = False
for n in range(2, N+1):
if is_prime[n]:
for m in range(2*n, N+1, n):
is_prime[m] = False
print("// src/test_small_constants.rs")
print("//")
print("// Copyright (c) 2018 David Creswick")
print("//")
print("// Licensed under the Apache License, Version 2.0")
print("// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT")
print("// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your")
print("// option. All files in the project carrying such notice may not be copied,")
print("// modified, or distributed except according to those terms.")
print()
print("// DO NOT EDIT THIS FILE DIRECTLY!");
print("// This file is the output of util/generate_small_constant_test.py");
print("use typenum::*;")
print("use super::*;")
print()
for (test_name, b) in [("prime", True),
("composite", False)]:
print()
print("#[test]")
print("fn test_%s() {"%test_name)
for n in range(N+1):
if is_prime[n] == b:
#print(" assert!(%s<U%d as IsPrime>::Output::to_bool());"%(s,n))
print(" assert_type_eq!(<U%d as IsPrime>::Output, %s);"%(n,b))
print("}")
| n = 1024
is_prime = [True] * (N + 1)
is_prime[0] = False
is_prime[1] = False
for n in range(2, N + 1):
if is_prime[n]:
for m in range(2 * n, N + 1, n):
is_prime[m] = False
print('// src/test_small_constants.rs')
print('//')
print('// Copyright (c) 2018 David Creswick')
print('//')
print('// Licensed under the Apache License, Version 2.0')
print('// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT')
print('// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your')
print('// option. All files in the project carrying such notice may not be copied,')
print('// modified, or distributed except according to those terms.')
print()
print('// DO NOT EDIT THIS FILE DIRECTLY!')
print('// This file is the output of util/generate_small_constant_test.py')
print('use typenum::*;')
print('use super::*;')
print()
for (test_name, b) in [('prime', True), ('composite', False)]:
print()
print('#[test]')
print('fn test_%s() {' % test_name)
for n in range(N + 1):
if is_prime[n] == b:
print(' assert_type_eq!(<U%d as IsPrime>::Output, %s);' % (n, b))
print('}') |
# https://www.codechef.com/START11C/problems/FACEDIR
n = int(input())
for _ in range(n):
v = int(input())
v %= 4
if v == 0:
print("North")
elif v==1:
print("East")
elif v==2:
print("South")
else:
print("West") | n = int(input())
for _ in range(n):
v = int(input())
v %= 4
if v == 0:
print('North')
elif v == 1:
print('East')
elif v == 2:
print('South')
else:
print('West') |
DATA = [ '123.108.237.112/28',
'123.108.239.224/28',
'202.253.96.144/28',
'202.253.99.144/28',
'210.228.189.188/30']
| data = ['123.108.237.112/28', '123.108.239.224/28', '202.253.96.144/28', '202.253.99.144/28', '210.228.189.188/30'] |
# the print keyword is used to display a message
print('Hello world!')
# Strings can be enclosed in single quotes
print('Hello world single quotes')
# Strings can also be enclosed in double quotes
print("Hello world - double quotes")
# using print to display integer / whole numbers
print(188)
# using print to display float number / real number
print(99.9)
| print('Hello world!')
print('Hello world single quotes')
print('Hello world - double quotes')
print(188)
print(99.9) |
# -*- coding: utf-8 -*-
#Using Python3
#Drowing dynamic table
rows = input("Enter the number of rows: ")
columns = input("Enter the number of columns: ")
celNum = input("Enter number in cells: ")
rows = int(rows)
columns = int(columns)
celNum = int(celNum)
#Labels
print("Table", end = " ") #print on the same line
for i in range(0,columns):
print("T", end = " ")
print("Total")
#Body
for j in range(0, rows, 1 ):
print(" row" + str(j+1).zfill(1), end = " ") #formats int to string
for j in range(0, columns,1):
print(celNum, end = " ")
print("Suma")
#Totals
print("Total", end = " ") #print on the same line
for i in range(0,columns):
print("S", end = " ")
print("Vsi4ko")
| rows = input('Enter the number of rows: ')
columns = input('Enter the number of columns: ')
cel_num = input('Enter number in cells: ')
rows = int(rows)
columns = int(columns)
cel_num = int(celNum)
print('Table', end=' ')
for i in range(0, columns):
print('T', end=' ')
print('Total')
for j in range(0, rows, 1):
print(' row' + str(j + 1).zfill(1), end=' ')
for j in range(0, columns, 1):
print(celNum, end=' ')
print('Suma')
print('Total', end=' ')
for i in range(0, columns):
print('S', end=' ')
print('Vsi4ko') |
# DROP TABLES
airport_codes_table_drop = "DROP TABLE IF EXISTS airport_codes"
immigration_table_drop = "DROP TABLE IF EXISTS immigration"
state_codes_table_drop = "DROP TABLE IF EXISTS state_codes"
# user_table_drop = "DROP TABLE IF EXISTS users"
# song_table_drop = "DROP TABLE IF EXISTS songs"
# artist_table_drop = "DROP TABLE IF EXISTS artists"
# time_table_drop = "DROP TABLE IF EXISTS time"
# # CREATE TABLES
#
# songplay_table_create = ("CREATE TABLE songplays ( \
# songplay_id serial PRIMARY KEY, \
# start_time timestamp NOT NULL, \
# user_id int NOT NULL, \
# level varchar NOT NULL, \
# song_id varchar, \
# artist_id varchar, \
# session_id int NOT NULL, \
# location varchar NOT NULL, \
# user_agent varchar NOT NULL \
# )")
#
# user_table_create = ("CREATE TABLE users ( \
# user_id int PRIMARY KEY, \
# first_name varchar NOT NULL, \
# last_name varchar NOT NULL, \
# gender char(1) NOT NULL, \
# level varchar NOT NULL \
# )")
#
# song_table_create = ("CREATE TABLE songs ( \
# song_id varchar PRIMARY KEY, \
# title varchar NOT NULL, \
# artist_id varchar NOT NULL, \
# year int NOT NULL, \
# duration numeric NOT NULL \
# )")
#
# artist_table_create = ("CREATE TABLE artists ( \
# artist_id varchar PRIMARY KEY, \
# name varchar NOT NULL, \
# location varchar NOT NULL, \
# latitude numeric, \
# longitude numeric \
# )")
#
# time_table_create = ("CREATE TABLE time ( \
# start_time timestamp PRIMARY KEY, \
# hour int NOT NULL, \
# day int NOT NULL, \
# week int NOT NULL, \
# month int NOT NULL, \
# year int NOT NULL, \
# weekday int NOT NULL \
# )")
#
# # INSERT RECORDS
#
# songplay_table_insert = ("INSERT INTO songplays (start_time, user_id, level, song_id, artist_id, session_id, location, user_agent) \
# VALUES(%s, %s, %s, %s, %s, %s, %s, %s) ON CONFLICT DO NOTHING")
#
# user_table_insert = ("INSERT INTO users (user_id, first_name, last_name, gender, level) VALUES(%s, %s, %s, %s, %s) \
# ON CONFLICT (user_id) DO UPDATE SET level = EXCLUDED.level")
#
# song_table_insert = "INSERT INTO songs (song_id, title, artist_id, year, duration) VALUES(%s, %s, %s, %s, %s) ON CONFLICT DO NOTHING"
#
# artist_table_insert = ("INSERT INTO artists (artist_id, name, location, latitude, longitude) VALUES(%s, %s, %s, %s, %s) ON CONFLICT DO NOTHING")
#
#
# time_table_insert = ("INSERT INTO time (start_time, hour, day, week, month, year, weekday) VALUES(%s, %s, %s, %s, %s, %s, %s) ON CONFLICT DO NOTHING")
#
# # FIND SONGS
#
# song_select = ("SELECT songs.song_id, artists.artist_id FROM songs \
# JOIN artists ON songs.artist_id = artists.artist_id \
# WHERE songs.title = %s AND artists.name = %s AND songs.duration = %s")
#
# # QUERY LISTS
#
# create_table_queries = [songplay_table_create, user_table_create, song_table_create, artist_table_create, time_table_create]
drop_table_queries = [airport_codes_table_drop, immigration_table_drop, state_codes_table_drop] | airport_codes_table_drop = 'DROP TABLE IF EXISTS airport_codes'
immigration_table_drop = 'DROP TABLE IF EXISTS immigration'
state_codes_table_drop = 'DROP TABLE IF EXISTS state_codes'
drop_table_queries = [airport_codes_table_drop, immigration_table_drop, state_codes_table_drop] |
def MergeSort(A):
if len(A) > 1:
mid = len(A) // 2
lefthalf = A[:mid]
righthalf = A[mid:]
print(lefthalf, " ", righthalf)
MergeSort(lefthalf)
MergeSort(righthalf)
i = j = k = 0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
A[k] = lefthalf[i]
i = i + 1
else:
A[k] = righthalf[j]
j = j + 1
k = k + 1
while i < len(lefthalf):
A[k] = lefthalf[i]
i = i + 1
k = k + 1
while j < len(righthalf):
A[k] = righthalf[j]
j = j + 1
k = k + 1
A = [534, 246, 933, 127, 277, 321, 454, 565, 220]
MergeSort(A)
print(A)
#PRINT | def merge_sort(A):
if len(A) > 1:
mid = len(A) // 2
lefthalf = A[:mid]
righthalf = A[mid:]
print(lefthalf, ' ', righthalf)
merge_sort(lefthalf)
merge_sort(righthalf)
i = j = k = 0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
A[k] = lefthalf[i]
i = i + 1
else:
A[k] = righthalf[j]
j = j + 1
k = k + 1
while i < len(lefthalf):
A[k] = lefthalf[i]
i = i + 1
k = k + 1
while j < len(righthalf):
A[k] = righthalf[j]
j = j + 1
k = k + 1
a = [534, 246, 933, 127, 277, 321, 454, 565, 220]
merge_sort(A)
print(A) |
print("Program to find the sum of two binary numbers \n\n")
a=input("Enter binary number ")
b=int(a,2)
print (b)
c=int(input("Enter numerical natural number"))
d=bin(c)[2:]
print (d)
input()
| print('Program to find the sum of two binary numbers \n\n')
a = input('Enter binary number ')
b = int(a, 2)
print(b)
c = int(input('Enter numerical natural number'))
d = bin(c)[2:]
print(d)
input() |
#
# PySNMP MIB module XEDIA-L2DIAL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/XEDIA-L2DIAL-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:36:26 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)
#
Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueSizeConstraint, ConstraintsUnion, ValueRangeConstraint, ConstraintsIntersection, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ConstraintsUnion", "ValueRangeConstraint", "ConstraintsIntersection", "SingleValueConstraint")
ModuleCompliance, ObjectGroup, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "ObjectGroup", "NotificationGroup")
Counter32, ObjectIdentity, TimeTicks, IpAddress, Counter64, Integer32, Gauge32, iso, Unsigned32, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType, Bits, ModuleIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "Counter32", "ObjectIdentity", "TimeTicks", "IpAddress", "Counter64", "Integer32", "Gauge32", "iso", "Unsigned32", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType", "Bits", "ModuleIdentity")
TextualConvention, DisplayString, RowStatus = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString", "RowStatus")
xediaMibs, = mibBuilder.importSymbols("XEDIA-REG", "xediaMibs")
xediaL2DialMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 838, 3, 30))
if mibBuilder.loadTexts: xediaL2DialMIB.setLastUpdated('9902272155Z')
if mibBuilder.loadTexts: xediaL2DialMIB.setOrganization('Xedia Corp.')
l2DialObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 838, 3, 30, 1))
l2DialConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 838, 3, 30, 2))
l2DialStatusTable = MibTable((1, 3, 6, 1, 4, 1, 838, 3, 30, 1, 1), )
if mibBuilder.loadTexts: l2DialStatusTable.setStatus('current')
l2DialStatusEntry = MibTableRow((1, 3, 6, 1, 4, 1, 838, 3, 30, 1, 1, 1), ).setIndexNames((0, "XEDIA-L2DIAL-MIB", "l2DialStatusIpAddress"))
if mibBuilder.loadTexts: l2DialStatusEntry.setStatus('current')
l2DialStatusIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 838, 3, 30, 1, 1, 1, 1), IpAddress())
if mibBuilder.loadTexts: l2DialStatusIpAddress.setStatus('current')
l2DialStatusSublayer = MibTableColumn((1, 3, 6, 1, 4, 1, 838, 3, 30, 1, 1, 1, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: l2DialStatusSublayer.setStatus('current')
l2DialCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 838, 3, 30, 2, 1))
l2DialGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 838, 3, 30, 2, 2))
l2DialCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 838, 3, 30, 2, 1, 1)).setObjects(("XEDIA-L2DIAL-MIB", "l2DialStatusGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
l2DialCompliance = l2DialCompliance.setStatus('current')
l2DialStatusGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 838, 3, 30, 2, 2, 1)).setObjects(("XEDIA-L2DIAL-MIB", "l2DialStatusSublayer"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
l2DialStatusGroup = l2DialStatusGroup.setStatus('current')
mibBuilder.exportSymbols("XEDIA-L2DIAL-MIB", l2DialGroups=l2DialGroups, l2DialStatusIpAddress=l2DialStatusIpAddress, l2DialObjects=l2DialObjects, PYSNMP_MODULE_ID=xediaL2DialMIB, xediaL2DialMIB=xediaL2DialMIB, l2DialConformance=l2DialConformance, l2DialStatusEntry=l2DialStatusEntry, l2DialStatusSublayer=l2DialStatusSublayer, l2DialStatusTable=l2DialStatusTable, l2DialCompliance=l2DialCompliance, l2DialCompliances=l2DialCompliances, l2DialStatusGroup=l2DialStatusGroup)
| (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_union, value_range_constraint, constraints_intersection, single_value_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueSizeConstraint', 'ConstraintsUnion', 'ValueRangeConstraint', 'ConstraintsIntersection', 'SingleValueConstraint')
(module_compliance, object_group, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'ObjectGroup', 'NotificationGroup')
(counter32, object_identity, time_ticks, ip_address, counter64, integer32, gauge32, iso, unsigned32, mib_identifier, mib_scalar, mib_table, mib_table_row, mib_table_column, notification_type, bits, module_identity) = mibBuilder.importSymbols('SNMPv2-SMI', 'Counter32', 'ObjectIdentity', 'TimeTicks', 'IpAddress', 'Counter64', 'Integer32', 'Gauge32', 'iso', 'Unsigned32', 'MibIdentifier', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'NotificationType', 'Bits', 'ModuleIdentity')
(textual_convention, display_string, row_status) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString', 'RowStatus')
(xedia_mibs,) = mibBuilder.importSymbols('XEDIA-REG', 'xediaMibs')
xedia_l2_dial_mib = module_identity((1, 3, 6, 1, 4, 1, 838, 3, 30))
if mibBuilder.loadTexts:
xediaL2DialMIB.setLastUpdated('9902272155Z')
if mibBuilder.loadTexts:
xediaL2DialMIB.setOrganization('Xedia Corp.')
l2_dial_objects = mib_identifier((1, 3, 6, 1, 4, 1, 838, 3, 30, 1))
l2_dial_conformance = mib_identifier((1, 3, 6, 1, 4, 1, 838, 3, 30, 2))
l2_dial_status_table = mib_table((1, 3, 6, 1, 4, 1, 838, 3, 30, 1, 1))
if mibBuilder.loadTexts:
l2DialStatusTable.setStatus('current')
l2_dial_status_entry = mib_table_row((1, 3, 6, 1, 4, 1, 838, 3, 30, 1, 1, 1)).setIndexNames((0, 'XEDIA-L2DIAL-MIB', 'l2DialStatusIpAddress'))
if mibBuilder.loadTexts:
l2DialStatusEntry.setStatus('current')
l2_dial_status_ip_address = mib_table_column((1, 3, 6, 1, 4, 1, 838, 3, 30, 1, 1, 1, 1), ip_address())
if mibBuilder.loadTexts:
l2DialStatusIpAddress.setStatus('current')
l2_dial_status_sublayer = mib_table_column((1, 3, 6, 1, 4, 1, 838, 3, 30, 1, 1, 1, 2), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
l2DialStatusSublayer.setStatus('current')
l2_dial_compliances = mib_identifier((1, 3, 6, 1, 4, 1, 838, 3, 30, 2, 1))
l2_dial_groups = mib_identifier((1, 3, 6, 1, 4, 1, 838, 3, 30, 2, 2))
l2_dial_compliance = module_compliance((1, 3, 6, 1, 4, 1, 838, 3, 30, 2, 1, 1)).setObjects(('XEDIA-L2DIAL-MIB', 'l2DialStatusGroup'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
l2_dial_compliance = l2DialCompliance.setStatus('current')
l2_dial_status_group = object_group((1, 3, 6, 1, 4, 1, 838, 3, 30, 2, 2, 1)).setObjects(('XEDIA-L2DIAL-MIB', 'l2DialStatusSublayer'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
l2_dial_status_group = l2DialStatusGroup.setStatus('current')
mibBuilder.exportSymbols('XEDIA-L2DIAL-MIB', l2DialGroups=l2DialGroups, l2DialStatusIpAddress=l2DialStatusIpAddress, l2DialObjects=l2DialObjects, PYSNMP_MODULE_ID=xediaL2DialMIB, xediaL2DialMIB=xediaL2DialMIB, l2DialConformance=l2DialConformance, l2DialStatusEntry=l2DialStatusEntry, l2DialStatusSublayer=l2DialStatusSublayer, l2DialStatusTable=l2DialStatusTable, l2DialCompliance=l2DialCompliance, l2DialCompliances=l2DialCompliances, l2DialStatusGroup=l2DialStatusGroup) |
class Variable(object):
def __init__(self, identity, constraints = None):
self.identity = identity
self.constraints = constraints or set()
def __eq__(self, other):
return self.identity == (other.identity if other is Variable else other)
def __hash__(self):
return hash(self.identity)
def __str__(self):
return "Variable({0})".format(self.identity)
| class Variable(object):
def __init__(self, identity, constraints=None):
self.identity = identity
self.constraints = constraints or set()
def __eq__(self, other):
return self.identity == (other.identity if other is Variable else other)
def __hash__(self):
return hash(self.identity)
def __str__(self):
return 'Variable({0})'.format(self.identity) |
class ChromosomeConfig:
def __init__(self, cross_type, mut_type, cross_prob, mut_prob):
self.__cross_type = cross_type
self.__mut_type = mut_type
self.__cross_prob = cross_prob
self.__mut_prob = mut_prob
@property
def cross_type(self):
return self.__cross_type
@property
def mut_type(self):
return self.__mut_type
@property
def cross_prob(self):
return self.__cross_prob
@property
def mut_prob(self):
return self.__mut_prob
| class Chromosomeconfig:
def __init__(self, cross_type, mut_type, cross_prob, mut_prob):
self.__cross_type = cross_type
self.__mut_type = mut_type
self.__cross_prob = cross_prob
self.__mut_prob = mut_prob
@property
def cross_type(self):
return self.__cross_type
@property
def mut_type(self):
return self.__mut_type
@property
def cross_prob(self):
return self.__cross_prob
@property
def mut_prob(self):
return self.__mut_prob |
def pytest_generate_tests(metafunc):
for scenario in metafunc.cls.scenarios:
metafunc.addcall(id=scenario[0], funcargs=scenario[1])
scenario1 = ('basic', {'attribute': 'value'})
scenario2 = ('advanced', {'attribute': 'value2'})
class Foo(object):
pass
class TestSampleWithScenarios(Foo):
scenarios = [scenario1, scenario2]
def test_demo(self, attribute):
assert isinstance(attribute, str)
| def pytest_generate_tests(metafunc):
for scenario in metafunc.cls.scenarios:
metafunc.addcall(id=scenario[0], funcargs=scenario[1])
scenario1 = ('basic', {'attribute': 'value'})
scenario2 = ('advanced', {'attribute': 'value2'})
class Foo(object):
pass
class Testsamplewithscenarios(Foo):
scenarios = [scenario1, scenario2]
def test_demo(self, attribute):
assert isinstance(attribute, str) |
def mensaje():
print("Estoy aprendiendo python")
print("Estoy aprendiendo python")
print("Estoy aprendiendo python")
mensaje()
mensaje()
mensaje()
print("Ejecutando codigo fuera del cuerpo de la funcion")
mensaje()
| def mensaje():
print('Estoy aprendiendo python')
print('Estoy aprendiendo python')
print('Estoy aprendiendo python')
mensaje()
mensaje()
mensaje()
print('Ejecutando codigo fuera del cuerpo de la funcion')
mensaje() |
# Visitor Permissions -
ORDER = 0x000000001
PAY = 0x000000002
# Customer Permissions - Can order, Pay, and comment on food
COMMENT = 0x000000004
# Delivery Person Permissions - Bid, choose routes, comment on customer
BID = 0x000000008
ROUTES = 0x000000010
CUSTOMER_COMMENT = 0x000000020
# Cook Permissions - food quality, menu, prices
FOOD_QUALITY = 0x000000040
MENU = 0x000000080
PRICES = 0x000000100
# Salesperson Permissions - Nagotiate with Supplier
SUPPLIER = 0x000000200
# Manager Permissions - commissions for sales, pay for cooks, complaints, management of customers
COMMISSIONS = 0x000000400
PAY = 0x000000800
COMPLAINTS = 0x000000800
MANAGEMENT = 0x000001000
| order = 1
pay = 2
comment = 4
bid = 8
routes = 16
customer_comment = 32
food_quality = 64
menu = 128
prices = 256
supplier = 512
commissions = 1024
pay = 2048
complaints = 2048
management = 4096 |
# Crie um programa onde o usuario possa
# digitar varios valores numericos e cadastre-os
# em uma lista. Caso o numero ja exista la dentro,
# ele nao sera adicionado.
# No final, serao exibidos todos os valores
# unicos digitados, em ordem crescente
listagem = list()
r = 'S'
while True:
while r == 'S':
n = int(input('Digite um valor: '))
if n not in listagem:
listagem.append(n)
print('Valor adicionado com sucesso...')
else:
print('Valor duplicado! Nao vou adicionar...')
r = str(input('Quer continuar? [S/N] ')).strip().upper()[0]
while r != 'S' and r != 'N':
r = str(input('Quer continuar? [S/N] ')).strip().upper()[0]
if r == 'N':
break
listagem.sort()
print(listagem)
| listagem = list()
r = 'S'
while True:
while r == 'S':
n = int(input('Digite um valor: '))
if n not in listagem:
listagem.append(n)
print('Valor adicionado com sucesso...')
else:
print('Valor duplicado! Nao vou adicionar...')
r = str(input('Quer continuar? [S/N] ')).strip().upper()[0]
while r != 'S' and r != 'N':
r = str(input('Quer continuar? [S/N] ')).strip().upper()[0]
if r == 'N':
break
listagem.sort()
print(listagem) |
def is_even(number):
number = int (number)
return number % 2 == 0
number = input('add number: ')
print(is_even(number))
| def is_even(number):
number = int(number)
return number % 2 == 0
number = input('add number: ')
print(is_even(number)) |
class credit_card(object):
def __init__(self, name, sec_code, code):
credit = 0
self.name = name
self.sec_code = sec_code
self.code = code
self.credit = float(credit)
def add_credi(self, credit):
self.credit += float(credit)
def remove_credi(self, credit):
self.credit -= float(credit)
def print_credit(self):
return self.credit
| class Credit_Card(object):
def __init__(self, name, sec_code, code):
credit = 0
self.name = name
self.sec_code = sec_code
self.code = code
self.credit = float(credit)
def add_credi(self, credit):
self.credit += float(credit)
def remove_credi(self, credit):
self.credit -= float(credit)
def print_credit(self):
return self.credit |
# SPDX-License-Identifier: MIT
# Copyright (c) 2020 Akumatic
#
#https://adventofcode.com/2020/day/11
def readFile() -> list:
with open(f"{__file__.rstrip('code.py')}input.txt", "r") as f:
return [list(line.strip()) for line in f.readlines()]
def get_positions(seats: list, cache: dict, x: int, y: int):
idx = (x, y)
cache[idx] = {"adjacent": [], "next_seat": []}
for dx in range(-1, 2):
for dy in range(-1, 2):
if dx == 0 and dy == 0:
continue
# adjacent tiles
cache[idx]["adjacent"].append((x + dx, y + dy))
# next available seat
i, j = x, y
while i + dx in cache["rx"] and j + dy in cache["ry"]:
i += dx
j += dy
if seats[i][j] in ("L", "#"):
cache[idx]["next_seat"].append((i, j))
break
def count(seats: list, cache: dict, x: int, y: int, seat: str, selection: str) -> int:
return sum(1 for pos in cache[(x, y)][selection] if pos[0] in cache["rx"] and \
pos[1] in cache["ry"] and seats[pos[0]][pos[1]] == seat)
def create_cache(seats: list) -> dict:
cache = {"rx": range(len(seats)), "ry": range(len(seats[0]))}
for x in cache["rx"]:
for y in cache["ry"]:
get_positions(seats, cache, x, y)
return cache
def iterate(seats: list, cache: dict, adjacent: bool = True) -> list:
selection = "adjacent" if adjacent else "next_seat"
tolerance = 4 if adjacent else 5
while True:
tmp = [s[:] for s in seats]
for x in cache["rx"]:
for y in cache["ry"]:
if seats[x][y] == ".":
continue
elif seats[x][y] == "L":
if count(seats, cache, x, y, "#", selection) == 0:
tmp[x][y] = "#"
else: # seats[x][y] == "#":
if count(seats, cache, x, y, "#", selection) >= tolerance:
tmp[x][y] = "L"
if seats == tmp:
return seats
else:
seats = tmp
def part1(input: list, cache) -> int:
seats = iterate(input, cache)
return sum([row.count("#") for row in seats])
def part2(input: list, cache) -> int:
seats = iterate(input, cache, adjacent=False)
return sum([row.count("#") for row in seats])
if __name__ == "__main__":
input = readFile()
cache = create_cache(input)
print(f"Part 1: {part1(input, cache)}")
print(f"Part 2: {part2(input, cache)}") | def read_file() -> list:
with open(f"{__file__.rstrip('code.py')}input.txt", 'r') as f:
return [list(line.strip()) for line in f.readlines()]
def get_positions(seats: list, cache: dict, x: int, y: int):
idx = (x, y)
cache[idx] = {'adjacent': [], 'next_seat': []}
for dx in range(-1, 2):
for dy in range(-1, 2):
if dx == 0 and dy == 0:
continue
cache[idx]['adjacent'].append((x + dx, y + dy))
(i, j) = (x, y)
while i + dx in cache['rx'] and j + dy in cache['ry']:
i += dx
j += dy
if seats[i][j] in ('L', '#'):
cache[idx]['next_seat'].append((i, j))
break
def count(seats: list, cache: dict, x: int, y: int, seat: str, selection: str) -> int:
return sum((1 for pos in cache[x, y][selection] if pos[0] in cache['rx'] and pos[1] in cache['ry'] and (seats[pos[0]][pos[1]] == seat)))
def create_cache(seats: list) -> dict:
cache = {'rx': range(len(seats)), 'ry': range(len(seats[0]))}
for x in cache['rx']:
for y in cache['ry']:
get_positions(seats, cache, x, y)
return cache
def iterate(seats: list, cache: dict, adjacent: bool=True) -> list:
selection = 'adjacent' if adjacent else 'next_seat'
tolerance = 4 if adjacent else 5
while True:
tmp = [s[:] for s in seats]
for x in cache['rx']:
for y in cache['ry']:
if seats[x][y] == '.':
continue
elif seats[x][y] == 'L':
if count(seats, cache, x, y, '#', selection) == 0:
tmp[x][y] = '#'
elif count(seats, cache, x, y, '#', selection) >= tolerance:
tmp[x][y] = 'L'
if seats == tmp:
return seats
else:
seats = tmp
def part1(input: list, cache) -> int:
seats = iterate(input, cache)
return sum([row.count('#') for row in seats])
def part2(input: list, cache) -> int:
seats = iterate(input, cache, adjacent=False)
return sum([row.count('#') for row in seats])
if __name__ == '__main__':
input = read_file()
cache = create_cache(input)
print(f'Part 1: {part1(input, cache)}')
print(f'Part 2: {part2(input, cache)}') |
# Created by MechAviv
# Map ID :: 402000620
# Sandstorm Zone : Refuge Border
if sm.hasQuest(34929):
sm.spawnNpc(3001509, 298, 200)
sm.showNpcSpecialActionByTemplateId(3001509, "summon", 0)
sm.spawnNpc(3001512, 374, 200)
sm.showNpcSpecialActionByTemplateId(3001512, "summon", 0)
sm.spawnNpc(3001513, 431, 200)
sm.showNpcSpecialActionByTemplateId(3001513, "summon", 0)
sm.spawnNpc(3001510, 550, 200)
sm.showNpcSpecialActionByTemplateId(3001510, "summon", 0)
sm.spawnNpc(3001514, -181, 200)
sm.showNpcSpecialActionByTemplateId(3001514, "summon", 0)
sm.spawnNpc(3001515, -330, 200)
sm.showNpcSpecialActionByTemplateId(3001515, "summon", 0)
sm.spawnNpc(3001516, -275, 200)
sm.showNpcSpecialActionByTemplateId(3001516, "summon", 0)
sm.spawnNpc(3001517, -487, -5)
sm.showNpcSpecialActionByTemplateId(3001517, "summon", 0)
sm.spawnNpc(3001518, -330, -5)
sm.showNpcSpecialActionByTemplateId(3001518, "summon", 0)
sm.spawnNpc(3001519, -435, -5)
sm.showNpcSpecialActionByTemplateId(3001519, "summon", 0)
sm.spawnNpc(3001520, -380, -5)
sm.showNpcSpecialActionByTemplateId(3001520, "summon", 0)
sm.spawnNpc(3001521, -331, 132)
sm.showNpcSpecialActionByTemplateId(3001521, "summon", 0)
sm.spawnNpc(3001522, -439, 93)
sm.showNpcSpecialActionByTemplateId(3001522, "summon", 0)
sm.spawnNpc(3001511, -439, 200)
sm.showNpcSpecialActionByTemplateId(3001511, "summon", 0) | if sm.hasQuest(34929):
sm.spawnNpc(3001509, 298, 200)
sm.showNpcSpecialActionByTemplateId(3001509, 'summon', 0)
sm.spawnNpc(3001512, 374, 200)
sm.showNpcSpecialActionByTemplateId(3001512, 'summon', 0)
sm.spawnNpc(3001513, 431, 200)
sm.showNpcSpecialActionByTemplateId(3001513, 'summon', 0)
sm.spawnNpc(3001510, 550, 200)
sm.showNpcSpecialActionByTemplateId(3001510, 'summon', 0)
sm.spawnNpc(3001514, -181, 200)
sm.showNpcSpecialActionByTemplateId(3001514, 'summon', 0)
sm.spawnNpc(3001515, -330, 200)
sm.showNpcSpecialActionByTemplateId(3001515, 'summon', 0)
sm.spawnNpc(3001516, -275, 200)
sm.showNpcSpecialActionByTemplateId(3001516, 'summon', 0)
sm.spawnNpc(3001517, -487, -5)
sm.showNpcSpecialActionByTemplateId(3001517, 'summon', 0)
sm.spawnNpc(3001518, -330, -5)
sm.showNpcSpecialActionByTemplateId(3001518, 'summon', 0)
sm.spawnNpc(3001519, -435, -5)
sm.showNpcSpecialActionByTemplateId(3001519, 'summon', 0)
sm.spawnNpc(3001520, -380, -5)
sm.showNpcSpecialActionByTemplateId(3001520, 'summon', 0)
sm.spawnNpc(3001521, -331, 132)
sm.showNpcSpecialActionByTemplateId(3001521, 'summon', 0)
sm.spawnNpc(3001522, -439, 93)
sm.showNpcSpecialActionByTemplateId(3001522, 'summon', 0)
sm.spawnNpc(3001511, -439, 200)
sm.showNpcSpecialActionByTemplateId(3001511, 'summon', 0) |
def line_0(kwargs):
kwargs['a'] = 1
kwargs['b'] = kwargs['a'] + 1
kwargs['c'] = kwargs['b'] * kwargs['b']
if kwargs['a'] == 1:
kwargs['d'] = 1
else:
kwargs['d'] = 0
return kwargs
| def line_0(kwargs):
kwargs['a'] = 1
kwargs['b'] = kwargs['a'] + 1
kwargs['c'] = kwargs['b'] * kwargs['b']
if kwargs['a'] == 1:
kwargs['d'] = 1
else:
kwargs['d'] = 0
return kwargs |
# --------------
##File path for the file
file_path
#Code starts here
def read_file(path):
file = open(path,"r")
sentence = file.readline()
file.close()
return sentence
sample_message = read_file(file_path)
print(sample_message)
# --------------
#Code starts here
def read_file(file_path_1,file_path_2):
file_path_1 = open(file_path_1,"r")
file_path_2 = open(file_path_2,"r")
message_1 = file_path_1.readline()
message_2 = file_path_2.readline()
return message_1,message_2
def fuse_msg(message_a,message_b):
quotient = int(message_b)//int(message_a)
return str(quotient)
messages = read_file(file_path_1,file_path_2)
print(messages)
message_1 = messages[0]
print(message_1)
message_2 = messages[1]
print(message_2)
secret_msg_1 = fuse_msg(message_1,message_2)
print(secret_msg_1)
# --------------
#Code starts here
def read_file(file_path_3):
file = open(file_path_3,"r")
message_3 = file.readlines()
return message_3
def substitute_msg(message_c):
sub = ''
if message_c == 'Red':
sub = 'Army General'
elif message_c == 'Green':
sub = 'Data Scientist'
else:
sub = 'Marine Biologist'
return sub
messages = read_file(file_path_3)
print(messages)
message_3 = messages[0]
print(message_3)
secret_msg_2 = substitute_msg(message_3)
print(secret_msg_2)
# --------------
# File path for message 4 and message 5
file_path_4
file_path_5
#Code starts here
def read_file(file_path_4,file_path_5):
file1 = open(file_path_4,"r")
file2 = open(file_path_5,"r")
message_4 = file1.readline()
message_5 = file2.readline()
return message_4,message_5
#Function to compare message
def compare_msg(message_d,message_e):
#Splitting the message into a list
a_list=message_d.split()
#Splitting the message into a list
b_list=message_e.split()
#Comparing the elements from both the lists
c_list = [i for i in a_list if i not in b_list]
#Combining the words of a list back to a single string sentence
final_msg=" ".join(c_list)
#Returning the sentence
return final_msg
#Calling the function to read file
messages=read_file(file_path_4,file_path_5)
print(messages)
message_4 = messages[0]
message_5 = messages[1]
#Calling the function to read file
#message_5=read_file(file_path_5)
#Calling the function 'compare messages'
secret_msg_3=compare_msg(message_4,message_5)
#Printing the secret message
print(secret_msg_3)
#Code ends here
# --------------
#Code starts here
def read_file(file_path_6):
file = open(file_path_6,"r")
message_6 = file.readline()
return message_6
# Function to filter message
def extract_msg(message_f):
# Splitting the message into a list
a_list = message_f.split()
# Creating the lambda function to identify even length words
even_word = lambda x: (len(x) % 2 == 0)
# Splitting the message into a list
b_list = (filter(even_word, a_list))
# Combining the words of a list back to a single string sentence
final_msg = " ".join(b_list)
# Returning the sentence
return final_msg
# Calling the function to read file
message_6 = read_file(file_path_6)
print(message_6)
# Calling the function 'filter_msg'
secret_msg_4 = extract_msg(message_6)
# Printing the secret message
print(secret_msg_4)
# Code ends here
# --------------
#Secret message parts in the correct order
message_parts=[secret_msg_3, secret_msg_1, secret_msg_4, secret_msg_2]
final_path= user_data_dir + '/secret_message.txt'
#Code starts here
def write_file(path,secret_msg):
file = open(path,"a+")
file.write(secret_msg)
file.close()
secret_msg = " ".join(message_parts)
write_file(final_path,secret_msg)
print(secret_msg)
| file_path
def read_file(path):
file = open(path, 'r')
sentence = file.readline()
file.close()
return sentence
sample_message = read_file(file_path)
print(sample_message)
def read_file(file_path_1, file_path_2):
file_path_1 = open(file_path_1, 'r')
file_path_2 = open(file_path_2, 'r')
message_1 = file_path_1.readline()
message_2 = file_path_2.readline()
return (message_1, message_2)
def fuse_msg(message_a, message_b):
quotient = int(message_b) // int(message_a)
return str(quotient)
messages = read_file(file_path_1, file_path_2)
print(messages)
message_1 = messages[0]
print(message_1)
message_2 = messages[1]
print(message_2)
secret_msg_1 = fuse_msg(message_1, message_2)
print(secret_msg_1)
def read_file(file_path_3):
file = open(file_path_3, 'r')
message_3 = file.readlines()
return message_3
def substitute_msg(message_c):
sub = ''
if message_c == 'Red':
sub = 'Army General'
elif message_c == 'Green':
sub = 'Data Scientist'
else:
sub = 'Marine Biologist'
return sub
messages = read_file(file_path_3)
print(messages)
message_3 = messages[0]
print(message_3)
secret_msg_2 = substitute_msg(message_3)
print(secret_msg_2)
file_path_4
file_path_5
def read_file(file_path_4, file_path_5):
file1 = open(file_path_4, 'r')
file2 = open(file_path_5, 'r')
message_4 = file1.readline()
message_5 = file2.readline()
return (message_4, message_5)
def compare_msg(message_d, message_e):
a_list = message_d.split()
b_list = message_e.split()
c_list = [i for i in a_list if i not in b_list]
final_msg = ' '.join(c_list)
return final_msg
messages = read_file(file_path_4, file_path_5)
print(messages)
message_4 = messages[0]
message_5 = messages[1]
secret_msg_3 = compare_msg(message_4, message_5)
print(secret_msg_3)
def read_file(file_path_6):
file = open(file_path_6, 'r')
message_6 = file.readline()
return message_6
def extract_msg(message_f):
a_list = message_f.split()
even_word = lambda x: len(x) % 2 == 0
b_list = filter(even_word, a_list)
final_msg = ' '.join(b_list)
return final_msg
message_6 = read_file(file_path_6)
print(message_6)
secret_msg_4 = extract_msg(message_6)
print(secret_msg_4)
message_parts = [secret_msg_3, secret_msg_1, secret_msg_4, secret_msg_2]
final_path = user_data_dir + '/secret_message.txt'
def write_file(path, secret_msg):
file = open(path, 'a+')
file.write(secret_msg)
file.close()
secret_msg = ' '.join(message_parts)
write_file(final_path, secret_msg)
print(secret_msg) |
# -*- encoding: utf-8 -*-
bind = 'unix:mta-system.sock'
workers = 2
timeout = 300
loglevel = 'debug'
capture_output = True
accesslog = 'gunicorn-access.log'
errorlog = 'gunicorn-error.log'
enable_stdio_inheritance = True
| bind = 'unix:mta-system.sock'
workers = 2
timeout = 300
loglevel = 'debug'
capture_output = True
accesslog = 'gunicorn-access.log'
errorlog = 'gunicorn-error.log'
enable_stdio_inheritance = True |
# THIS FILE IS AUTO-GENERATED, DO NOT EDIT
config = {'all': {'comment': 'Entry point', 'type': 'nested', 'lists': ['2', '3', '4'], 'ensure_unique': True, 'ensure_unique_prefix': 4, 'max_slug_length': 50}, '2': {'comment': 'Two words (may also contain prepositions)', 'type': 'nested', 'lists': ['an']}, '3': {'comment': 'Three words (may also contain prepositions)', 'type': 'nested', 'lists': ['aan', 'ano', 'anl', 'nuo', 'as2', 's2o', 's2l', 'sl2']}, '4': {'comment': 'Four words (may also contain prepositions)', 'type': 'nested', 'lists': ['aano', 'aanl', 'anuo', 'as2o', 's2uo', 'as2l', 'asl2']}, 'an': {'comment': 'adjective-noun', 'type': 'cartesian', 'lists': ['adj_any', 'subj']}, 'aan': {'comment': 'adjective-adjective-noun', 'type': 'cartesian', 'lists': ['adj_far', 'adj_near', 'subj']}, 'ano': {'comment': 'adjective-noun-of-noun', 'type': 'cartesian', 'lists': ['adj_any', 'subj', 'of', 'of_noun_any']}, 'anl': {'comment': 'adjective-noun-from-location', 'type': 'cartesian', 'lists': ['adj_any', 'subj', 'from', 'from_noun_no_mod']}, 'nuo': {'comment': 'noun-of-adjective-noun', 'type': 'cartesian', 'lists': ['subj', 'of', 'of_modifier', 'of_noun']}, 'as2': {'comment': 'adjective-2word-subject', 'type': 'cartesian', 'lists': ['adj_far', 'subj2']}, 's2o': {'comment': '2word-subject-of-noun', 'type': 'cartesian', 'lists': ['subj2', 'of', 'of_noun_any']}, 's2l': {'comment': '2word-subject-from-location', 'type': 'cartesian', 'lists': ['subj2', 'from', 'from_noun_no_mod']}, 'sl2': {'comment': 'subject-from-some-location', 'type': 'cartesian', 'lists': ['subj', 'from', 'from2']}, 'aano': {'comment': 'adjective-adjective-noun-of-noun', 'type': 'cartesian', 'lists': ['adj_far', 'adj_near', 'subj', 'of', 'of_noun_any']}, 'aanl': {'comment': 'adjective-adjective-noun-from-location', 'type': 'cartesian', 'lists': ['adj_far', 'adj_near', 'subj', 'from', 'from_noun_no_mod']}, 'anuo': {'comment': 'adjective-noun-of-adjective-noun', 'type': 'cartesian', 'lists': ['adj_any', 'subj', 'of', 'of_modifier', 'of_noun']}, 'as2o': {'comment': 'adjective-2word-subject-of-noun', 'type': 'cartesian', 'lists': ['adj_far', 'subj2', 'of', 'of_noun_any']}, 's2uo': {'comment': 'adjective-2word-subject-of-adjective-noun', 'type': 'cartesian', 'lists': ['subj2', 'of', 'of_modifier', 'of_noun']}, 'as2l': {'comment': 'adjective-2word-subject-from-location', 'type': 'cartesian', 'lists': ['adj_far', 'subj2', 'from', 'from_noun_no_mod']}, 'asl2': {'comment': 'adjective-subject-from-some-location', 'type': 'cartesian', 'lists': ['adj_any', 'subj', 'from', 'from2']}, 'adj_far': {'comment': 'First adjective (with more following)', 'type': 'nested', 'lists': ['adjective', 'adjective_first', 'noun_adjective', 'size']}, 'adj_near': {'comment': 'Last adjective (closest to the subject)', 'type': 'nested', 'lists': ['adjective', 'color', 'noun_adjective', 'prefix']}, 'adj_any': {'comment': 'The only adjective (includes everything)', 'type': 'nested', 'lists': ['adjective', 'color', 'noun_adjective', 'prefix', 'size']}, 'subj': {'comment': 'The subject (animal)', 'type': 'nested', 'lists': ['animal', 'animal_breed', 'animal_legendary']}, 'of': {'type': 'const', 'value': 'of'}, 'of_noun_any': {'type': 'nested', 'lists': ['of_noun', 'of_noun_no_mod']}, 'from': {'type': 'const', 'value': 'from'}, 'from_noun_no_mod': {'type': 'words', 'words': ['venus', 'mars', 'jupiter', 'ganymede', 'saturn', 'uranus', 'neptune', 'pluto', 'betelgeuse', 'sirius', 'vega', 'arcadia', 'asgard', 'atlantis', 'avalon', 'camelot', 'eldorado', 'heaven', 'hell', 'hyperborea', 'lemuria', 'nibiru', 'shambhala', 'tartarus', 'valhalla', 'wonderland']}, 'prefix': {'type': 'words', 'words': ['giga', 'mega', 'micro', 'mini', 'nano', 'pygmy', 'super', 'uber', 'ultra', 'cyber', 'mutant', 'ninja', 'space'], 'max_length': 13}, 'of_modifier': {'type': 'words', 'words': ['absolute', 'abstract', 'algebraic', 'amazing', 'amusing', 'ancient', 'angelic', 'astonishing', 'authentic', 'awesome', 'beautiful', 'classic', 'delightful', 'demonic', 'eminent', 'enjoyable', 'eternal', 'excellent', 'exotic', 'extreme', 'fabulous', 'famous', 'fantastic', 'fascinating', 'flawless', 'fortunate', 'glorious', 'great', 'heavenly', 'holistic', 'hypothetical', 'ideal', 'illegal', 'imaginary', 'immense', 'imminent', 'immortal', 'impossible', 'impressive', 'improbable', 'incredible', 'inescapable', 'inevitable', 'infinite', 'inspiring', 'interesting', 'legal', 'magic', 'majestic', 'major', 'marvelous', 'massive', 'mysterious', 'nonconcrete', 'nonstop', 'luxurious', 'optimal', 'original', 'pastoral', 'perfect', 'perpetual', 'phenomenal', 'pleasurable', 'pragmatic', 'premium', 'radical', 'rampant', 'regular', 'remarkable', 'satisfying', 'serious', 'scientific', 'sexy', 'sheer', 'simple', 'silent', 'spectacular', 'splendid', 'stereotyped', 'stimulating', 'strange', 'striking', 'strongest', 'sublime', 'sudden', 'terrific', 'therapeutic', 'total', 'ultimate', 'uncanny', 'undeniable', 'unearthly', 'unexpected', 'unknown', 'unmatched', 'unnatural', 'unreal', 'unusual', 'utter', 'weird', 'wonderful', 'wondrous'], 'max_length': 13}, 'animal_breed': {'type': 'words', 'words': ['longhorn', 'akita', 'beagle', 'bloodhound', 'bulldog', 'chihuahua', 'collie', 'corgi', 'dalmatian', 'doberman', 'husky', 'labradoodle', 'labrador', 'mastiff', 'malamute', 'mongrel', 'poodle', 'rottweiler', 'spaniel', 'terrier', 'mule', 'mustang', 'pony', 'angora'], 'max_length': 13}, 'size': {'type': 'words', 'words': ['big', 'colossal', 'enormous', 'gigantic', 'great', 'huge', 'hulking', 'humongous', 'large', 'little', 'massive', 'miniature', 'petite', 'portable', 'small', 'tiny', 'towering'], 'max_length': 13}, 'from2': {'type': 'phrases', 'phrases': [('fancy', 'cafe'), ('prestigious', 'college'), ('prestigious', 'university'), ('big', 'city'), ('foreign', 'country'), ('small', 'town'), ('wild', 'west'), ('ancient', 'ruins'), ('another', 'dimension'), ('another', 'planet'), ('flying', 'circus'), ('secret', 'laboratory'), ('the', 'government'), ('the', 'future'), ('the', 'past'), ('the', 'stars')], 'number_of_words': 2, 'max_length': 24}, 'of_noun_no_mod': {'type': 'words', 'words': ['chemistry', 'education', 'experiment', 'mathematics', 'psychology', 'reading', 'cubism', 'painting', 'advertising', 'agreement', 'climate', 'competition', 'effort', 'emphasis', 'foundation', 'judgment', 'memory', 'opportunity', 'perspective', 'priority', 'promise', 'teaching'], 'max_length': 13}, 'of_noun': {'type': 'words', 'words': ['anger', 'bliss', 'contentment', 'courage', 'ecstasy', 'excitement', 'faith', 'felicity', 'fury', 'gaiety', 'glee', 'glory', 'greatness', 'inspiration', 'jest', 'joy', 'happiness', 'holiness', 'love', 'merriment', 'passion', 'patience', 'peace', 'persistence', 'pleasure', 'pride', 'recreation', 'relaxation', 'romance', 'serenity', 'tranquility', 'apotheosis', 'chaos', 'energy', 'essence', 'eternity', 'excellence', 'experience', 'freedom', 'nirvana', 'order', 'perfection', 'spirit', 'variation', 'acceptance', 'brotherhood', 'criticism', 'culture', 'discourse', 'discussion', 'justice', 'piety', 'respect', 'security', 'support', 'tolerance', 'trust', 'warranty', 'abundance', 'admiration', 'assurance', 'authority', 'awe', 'certainty', 'control', 'domination', 'enterprise', 'fame', 'grandeur', 'influence', 'luxury', 'management', 'opposition', 'plenty', 'popularity', 'prestige', 'prosperity', 'reputation', 'reverence', 'reward', 'superiority', 'triumph', 'wealth', 'acumen', 'aptitude', 'art', 'artistry', 'competence', 'efficiency', 'expertise', 'finesse', 'genius', 'leadership', 'perception', 'skill', 'virtuosity', 'argument', 'debate', 'action', 'agility', 'amplitude', 'attack', 'charisma', 'chivalry', 'defense', 'defiance', 'devotion', 'dignity', 'endurance', 'exercise', 'force', 'fortitude', 'gallantry', 'health', 'honor', 'infinity', 'inquire', 'intensity', 'luck', 'mastery', 'might', 'opportunity', 'penetration', 'performance', 'pluck', 'potency', 'protection', 'prowess', 'resistance', 'serendipity', 'speed', 'stamina', 'strength', 'swiftness', 'temperance', 'tenacity', 'valor', 'vigor', 'vitality', 'will', 'advance', 'conversion', 'correction', 'development', 'diversity', 'elevation', 'enhancement', 'enrichment', 'enthusiasm', 'focus', 'fruition', 'growth', 'improvement', 'innovation', 'modernism', 'novelty', 'proficiency', 'progress', 'promotion', 'realization', 'refinement', 'renovation', 'revolution', 'success', 'tempering', 'upgrade', 'ampleness', 'completion', 'satiation', 'saturation', 'sufficiency', 'vastness', 'wholeness', 'attraction', 'beauty', 'bloom', 'cleaning', 'courtesy', 'glamour', 'elegance', 'fascination', 'kindness', 'joviality', 'politeness', 'refinement', 'symmetry', 'sympathy', 'tact', 'calibration', 'drama', 'economy', 'engineering', 'examination', 'philosophy', 'poetry', 'research', 'science', 'democracy', 'election', 'feminism', 'champagne', 'coffee', 'cookies', 'flowers', 'fragrance', 'honeydew', 'music', 'pizza', 'aurora', 'blizzard', 'current', 'dew', 'downpour', 'drizzle', 'hail', 'hurricane', 'lightning', 'rain', 'snow', 'storm', 'sunshine', 'tempest', 'thunder', 'tornado', 'typhoon', 'weather', 'wind', 'whirlwind', 'abracadabra', 'adventure', 'atheism', 'camouflage', 'destiny', 'endeavor', 'expression', 'fantasy', 'fertility', 'imagination', 'karma', 'masquerade', 'maturity', 'radiance', 'shopping', 'sorcery', 'unity', 'witchcraft', 'wizardry', 'wonder', 'youth', 'purring'], 'max_length': 13}, 'subj2': {'type': 'phrases', 'phrases': [('atlantic', 'puffin'), ('bank', 'swallow'), ('barn', 'owl'), ('barn', 'swallow'), ('barred', 'owl'), ('chimney', 'swift'), ('cliff', 'swallow'), ('emperor', 'goose'), ('harlequin', 'duck'), ('himalayan', 'snowcock'), ('hyacinth', 'macaw'), ('mangrove', 'cuckoo'), ('mute', 'swan'), ('northern', 'cardinal'), ('peregrine', 'falcon'), ('prairie', 'falcon'), ('red', 'cardinal'), ('snow', 'goose'), ('snowy', 'owl'), ('trumpeter', 'swan'), ('tufted', 'puffin'), ('whooper', 'swan'), ('whooping', 'crane'), ('fire', 'ant'), ('alpine', 'chipmunk'), ('beaked', 'whale'), ('bottlenose', 'dolphin'), ('clouded', 'leopard'), ('eared', 'seal'), ('elephant', 'seal'), ('feral', 'cat'), ('feral', 'dog'), ('feral', 'donkey'), ('feral', 'goat'), ('feral', 'horse'), ('feral', 'pig'), ('fur', 'seal'), ('grizzly', 'bear'), ('harbor', 'porpoise'), ('honey', 'badger'), ('humpback', 'whale'), ('killer', 'whale'), ('mountain', 'deer'), ('mountain', 'goat'), ('mountain', 'lion'), ('olympic', 'marmot'), ('pampas', 'deer'), ('pine', 'marten'), ('polynesian', 'rat'), ('rhesus', 'macaque'), ('river', 'dolphin'), ('sea', 'lion'), ('sea', 'otter'), ('snow', 'leopard'), ('sperm', 'whale'), ('spinner', 'dolphin'), ('vampire', 'bat'), ('gila', 'monster'), ('freshwater', 'crocodile'), ('saltwater', 'crocodile'), ('snapping', 'turtle'), ('walking', 'mushroom')], 'number_of_words': 2, 'max_length': 22}, 'adjective': {'type': 'words', 'words': ['acrid', 'ambrosial', 'amorphous', 'armored', 'aromatic', 'bald', 'blazing', 'boisterous', 'bouncy', 'brawny', 'bulky', 'camouflaged', 'caped', 'chubby', 'curvy', 'elastic', 'ethereal', 'fat', 'feathered', 'fiery', 'flashy', 'flat', 'fluffy', 'foamy', 'fragrant', 'furry', 'fuzzy', 'glaring', 'hairy', 'heavy', 'hissing', 'horned', 'icy', 'imaginary', 'invisible', 'lean', 'loud', 'loutish', 'lumpy', 'lush', 'masked', 'meaty', 'messy', 'misty', 'nebulous', 'noisy', 'nondescript', 'organic', 'purring', 'quiet', 'quirky', 'radiant', 'roaring', 'ruddy', 'rustling', 'screeching', 'shaggy', 'shapeless', 'shiny', 'silent', 'silky', 'singing', 'skinny', 'smooth', 'soft', 'spicy', 'spiked', 'statuesque', 'sticky', 'tacky', 'tall', 'tangible', 'tentacled', 'thick', 'thundering', 'venomous', 'warm', 'weightless', 'whispering', 'winged', 'wooden', 'adorable', 'affable', 'amazing', 'amiable', 'attractive', 'beautiful', 'calm', 'charming', 'cherubic', 'classic', 'classy', 'convivial', 'cordial', 'cuddly', 'curly', 'cute', 'debonair', 'elegant', 'famous', 'fresh', 'friendly', 'funny', 'gorgeous', 'graceful', 'gregarious', 'grinning', 'handsome', 'hilarious', 'hot', 'interesting', 'kind', 'laughing', 'lovely', 'meek', 'mellow', 'merciful', 'neat', 'nifty', 'notorious', 'poetic', 'pretty', 'refined', 'refreshing', 'sexy', 'smiling', 'sociable', 'spiffy', 'stylish', 'sweet', 'tactful', 'whimsical', 'abiding', 'accurate', 'adamant', 'adaptable', 'adventurous', 'alluring', 'aloof', 'ambitious', 'amusing', 'annoying', 'arrogant', 'aspiring', 'belligerent', 'benign', 'berserk', 'benevolent', 'bold', 'brave', 'cheerful', 'chirpy', 'cocky', 'congenial', 'courageous', 'cryptic', 'curious', 'daft', 'dainty', 'daring', 'defiant', 'delicate', 'delightful', 'determined', 'devout', 'didactic', 'diligent', 'discreet', 'dramatic', 'dynamic', 'eager', 'eccentric', 'elated', 'encouraging', 'enigmatic', 'enthusiastic', 'evasive', 'faithful', 'fair', 'fanatic', 'fearless', 'fervent', 'festive', 'fierce', 'fine', 'free', 'gabby', 'garrulous', 'gay', 'gentle', 'glistening', 'greedy', 'grumpy', 'happy', 'honest', 'hopeful', 'hospitable', 'impetuous', 'independent', 'industrious', 'innocent', 'intrepid', 'jolly', 'jovial', 'just', 'lively', 'loose', 'loyal', 'merry', 'modest', 'mysterious', 'nice', 'obedient', 'optimistic', 'orthodox', 'outgoing', 'outrageous', 'overjoyed', 'passionate', 'perky', 'placid', 'polite', 'positive', 'proud', 'prudent', 'puzzling', 'quixotic', 'quizzical', 'rebel', 'resolute', 'rampant', 'righteous', 'romantic', 'rough', 'rousing', 'sassy', 'satisfied', 'sly', 'sincere', 'snobbish', 'spirited', 'spry', 'stalwart', 'stirring', 'swinging', 'tasteful', 'thankful', 'tidy', 'tremendous', 'truthful', 'unselfish', 'upbeat', 'uppish', 'valiant', 'vehement', 'vengeful', 'vigorous', 'vivacious', 'zealous', 'zippy', 'able', 'adept', 'analytic', 'astute', 'attentive', 'brainy', 'busy', 'calculating', 'capable', 'careful', 'cautious', 'certain', 'clever', 'competent', 'conscious', 'cooperative', 'crafty', 'crazy', 'cunning', 'daffy', 'devious', 'discerning', 'efficient', 'expert', 'functional', 'gifted', 'helpful', 'enlightened', 'idealistic', 'impartial', 'industrious', 'ingenious', 'inquisitive', 'intelligent', 'inventive', 'judicious', 'keen', 'knowing', 'literate', 'logical', 'masterful', 'mindful', 'nonchalant', 'observant', 'omniscient', 'poised', 'practical', 'pragmatic', 'proficient', 'provocative', 'qualified', 'radical', 'rational', 'realistic', 'resourceful', 'savvy', 'sceptical', 'sensible', 'serious', 'shrewd', 'skilled', 'slick', 'slim', 'sloppy', 'smart', 'sophisticated', 'stoic', 'succinct', 'talented', 'thoughtful', 'tricky', 'unbiased', 'uptight', 'versatile', 'versed', 'visionary', 'wise', 'witty', 'accelerated', 'active', 'agile', 'athletic', 'dashing', 'deft', 'dexterous', 'energetic', 'fast', 'frisky', 'hasty', 'hypersonic', 'meteoric', 'mighty', 'muscular', 'nimble', 'nippy', 'powerful', 'prompt', 'quick', 'rapid', 'resilient', 'robust', 'rugged', 'solid', 'speedy', 'steadfast', 'steady', 'strong', 'sturdy', 'tireless', 'tough', 'unyielding', 'rich', 'wealthy', 'meticulous', 'precise', 'rigorous', 'scrupulous', 'strict', 'airborne', 'burrowing', 'crouching', 'flying', 'hidden', 'hopping', 'jumping', 'lurking', 'tunneling', 'warping', 'aboriginal', 'amphibian', 'aquatic', 'arboreal', 'polar', 'terrestrial', 'urban', 'accomplished', 'astonishing', 'authentic', 'awesome', 'delectable', 'excellent', 'exotic', 'exuberant', 'fabulous', 'fantastic', 'fascinating', 'flawless', 'fortunate', 'funky', 'godlike', 'glorious', 'groovy', 'honored', 'illustrious', 'imposing', 'important', 'impressive', 'incredible', 'invaluable', 'kickass', 'majestic', 'magnificent', 'marvellous', 'monumental', 'perfect', 'phenomenal', 'pompous', 'precious', 'premium', 'private', 'remarkable', 'spectacular', 'splendid', 'successful', 'wonderful', 'wondrous', 'offbeat', 'original', 'outstanding', 'quaint', 'unique', 'ancient', 'antique', 'prehistoric', 'primitive', 'abstract', 'acoustic', 'angelic', 'arcane', 'archetypal', 'augmented', 'auspicious', 'axiomatic', 'beneficial', 'bipedal', 'bizarre', 'complex', 'dancing', 'dangerous', 'demonic', 'divergent', 'economic', 'electric', 'elite', 'eminent', 'enchanted', 'esoteric', 'finicky', 'fractal', 'futuristic', 'gainful', 'hallowed', 'heavenly', 'heretic', 'holistic', 'hungry', 'hypnotic', 'hysterical', 'illegal', 'imperial', 'imported', 'impossible', 'inescapable', 'juicy', 'liberal', 'ludicrous', 'lyrical', 'magnetic', 'manipulative', 'mature', 'military', 'macho', 'married', 'melodic', 'natural', 'naughty', 'nocturnal', 'nostalgic', 'optimal', 'pastoral', 'peculiar', 'piquant', 'pristine', 'prophetic', 'psychedelic', 'quantum', 'rare', 'real', 'secret', 'simple', 'spectral', 'spiritual', 'stereotyped', 'stimulating', 'straight', 'strange', 'tested', 'therapeutic', 'true', 'ubiquitous', 'uncovered', 'unnatural', 'utopian', 'vagabond', 'vague', 'vegan', 'victorious', 'vigilant', 'voracious', 'wakeful', 'wandering', 'watchful', 'wild', 'bright', 'brilliant', 'colorful', 'crystal', 'dark', 'dazzling', 'fluorescent', 'glittering', 'glossy', 'gleaming', 'light', 'mottled', 'neon', 'opalescent', 'pastel', 'smoky', 'sparkling', 'spotted', 'striped', 'translucent', 'transparent', 'vivid'], 'max_length': 13}, 'animal': {'type': 'words', 'words': ['earthworm', 'leech', 'worm', 'scorpion', 'spider', 'tarantula', 'barnacle', 'crab', 'crayfish', 'lobster', 'pillbug', 'prawn', 'shrimp', 'ant', 'bee', 'beetle', 'bug', 'bumblebee', 'butterfly', 'caterpillar', 'cicada', 'cricket', 'dragonfly', 'earwig', 'firefly', 'grasshopper', 'honeybee', 'hornet', 'inchworm', 'ladybug', 'locust', 'mantis', 'mayfly', 'mosquito', 'moth', 'sawfly', 'silkworm', 'termite', 'wasp', 'woodlouse', 'centipede', 'millipede', 'pronghorn', 'antelope', 'bison', 'buffalo', 'bull', 'chamois', 'cow', 'gazelle', 'gaur', 'goat', 'ibex', 'impala', 'kudu', 'markhor', 'mouflon', 'muskox', 'nyala', 'sheep', 'wildebeest', 'yak', 'zebu', 'alpaca', 'camel', 'llama', 'vicugna', 'caribou', 'chital', 'deer', 'elk', 'moose', 'pudu', 'reindeer', 'sambar', 'wapiti', 'beluga', 'dolphin', 'narwhal', 'orca', 'porpoise', 'whale', 'donkey', 'horse', 'stallion', 'zebra', 'giraffe', 'okapi', 'hippo', 'rhino', 'boar', 'hog', 'pig', 'swine', 'warthog', 'peccary', 'buzzard', 'eagle', 'goshawk', 'harrier', 'hawk', 'vulture', 'duck', 'goose', 'swan', 'teal', 'bird', 'hummingbird', 'swift', 'kiwi', 'potoo', 'seriema', 'cassowary', 'emu', 'condor', 'auk', 'avocet', 'guillemot', 'kittiwake', 'puffin', 'seagull', 'skua', 'stork', 'dodo', 'dove', 'pigeon', 'kingfisher', 'tody', 'bustard', 'coua', 'coucal', 'cuckoo', 'koel', 'malkoha', 'roadrunner', 'kagu', 'caracara', 'falcon', 'kestrel', 'chachalaca', 'chicken', 'curassow', 'grouse', 'guan', 'junglefowl', 'partridge', 'peacock', 'pheasant', 'quail', 'rooster', 'turkey', 'loon', 'coot', 'crane', 'turaco', 'hoatzin', 'bullfinch', 'crow', 'jackdaw', 'jaybird', 'finch', 'lyrebird', 'magpie', 'myna', 'nightingale', 'nuthatch', 'oriole', 'oxpecker', 'raven', 'robin', 'rook', 'skylark', 'sparrow', 'starling', 'swallow', 'waxbill', 'wren', 'heron', 'ibis', 'jacamar', 'piculet', 'toucan', 'toucanet', 'woodpecker', 'flamingo', 'grebe', 'albatross', 'fulmar', 'petrel', 'spoonbill', 'ara', 'cockatoo', 'kakapo', 'lorikeet', 'macaw', 'parakeet', 'parrot', 'penguin', 'ostrich', 'boobook', 'owl', 'booby', 'cormorant', 'frigatebird', 'pelican', 'quetzal', 'trogon', 'axolotl', 'bullfrog', 'frog', 'newt', 'salamander', 'toad', 'angelfish', 'barracuda', 'carp', 'catfish', 'dogfish', 'goldfish', 'guppy', 'eel', 'flounder', 'herring', 'lionfish', 'mackerel', 'oarfish', 'perch', 'salmon', 'seahorse', 'sturgeon', 'sunfish', 'tench', 'trout', 'tuna', 'wrasse', 'sawfish', 'shark', 'stingray', 'jellyfish', 'alligator', 'caiman', 'crocodile', 'gharial', 'starfish', 'urchin', 'hedgehog', 'coyote', 'dingo', 'dog', 'fennec', 'fox', 'hound', 'jackal', 'tanuki', 'wolf', 'bobcat', 'caracal', 'cat', 'cougar', 'jaguar', 'jaguarundi', 'leopard', 'lion', 'lynx', 'manul', 'ocelot', 'panther', 'puma', 'serval', 'smilodon', 'tiger', 'wildcat', 'aardwolf', 'binturong', 'cheetah', 'civet', 'fossa', 'hyena', 'meerkat', 'mongoose', 'badger', 'coati', 'ermine', 'ferret', 'marten', 'mink', 'otter', 'polecat', 'skunk', 'stoat', 'weasel', 'wolverine', 'seal', 'walrus', 'raccoon', 'ringtail', 'bear', 'panda', 'bat', 'armadillo', 'elephant', 'mammoth', 'mastodon', 'mole', 'hyrax', 'bandicoot', 'bettong', 'cuscus', 'kangaroo', 'koala', 'numbat', 'quokka', 'quoll', 'wallaby', 'wombat', 'echidna', 'platypus', 'tapir', 'anteater', 'sloth', 'agouti', 'beaver', 'capybara', 'chinchilla', 'chipmunk', 'degu', 'dormouse', 'gerbil', 'gopher', 'groundhog', 'jackrabbit', 'jerboa', 'hamster', 'hare', 'lemming', 'marmot', 'mouse', 'muskrat', 'porcupine', 'rabbit', 'rat', 'squirrel', 'vole', 'ape', 'baboon', 'bonobo', 'capuchin', 'chimpanzee', 'galago', 'gibbon', 'gorilla', 'lemur', 'lori', 'macaque', 'mandrill', 'marmoset', 'monkey', 'orangutan', 'tamarin', 'tarsier', 'uakari', 'dugong', 'manatee', 'shrew', 'aardwark', 'clam', 'cockle', 'mussel', 'oyster', 'scallop', 'shellfish', 'ammonite', 'cuttlefish', 'nautilus', 'octopus', 'squid', 'limpet', 'slug', 'snail', 'sponge', 'tuatara', 'agama', 'chameleon', 'dragon', 'gecko', 'iguana', 'lizard', 'pogona', 'skink', 'adder', 'anaconda', 'asp', 'boa', 'cobra', 'copperhead', 'mamba', 'python', 'rattlesnake', 'sidewinder', 'snake', 'taipan', 'viper', 'tortoise', 'turtle', 'dinosaur', 'raptor', 'mushroom'], 'max_length': 13}, 'color': {'type': 'words', 'words': ['almond', 'amaranth', 'apricot', 'artichoke', 'auburn', 'azure', 'banana', 'beige', 'black', 'blond', 'blue', 'brown', 'burgundy', 'carmine', 'carrot', 'celadon', 'cerise', 'cerulean', 'charcoal', 'cherry', 'chestnut', 'chocolate', 'cinnamon', 'copper', 'cream', 'crimson', 'cyan', 'daffodil', 'dandelion', 'denim', 'ebony', 'eggplant', 'gray', 'ginger', 'green', 'indigo', 'infrared', 'jasmine', 'khaki', 'lavender', 'lilac', 'mauve', 'magenta', 'mahogany', 'maize', 'marigold', 'mustard', 'ochre', 'orange', 'papaya', 'peach', 'persimmon', 'pink', 'pistachio', 'pumpkin', 'purple', 'raspberry', 'red', 'rose', 'russet', 'saffron', 'sage', 'scarlet', 'sepia', 'silver', 'tan', 'tangerine', 'taupe', 'teal', 'tomato', 'turquoise', 'tuscan', 'ultramarine', 'ultraviolet', 'umber', 'vanilla', 'vermilion', 'violet', 'viridian', 'white', 'wine', 'wisteria', 'yellow', 'agate', 'amber', 'amethyst', 'aquamarine', 'asparagus', 'beryl', 'brass', 'bronze', 'cobalt', 'coral', 'cornflower', 'diamond', 'emerald', 'garnet', 'golden', 'granite', 'ivory', 'jade', 'jasper', 'lemon', 'lime', 'malachite', 'maroon', 'myrtle', 'nickel', 'olive', 'olivine', 'onyx', 'opal', 'orchid', 'pearl', 'peridot', 'platinum', 'quartz', 'ruby', 'sandy', 'sapphire', 'steel', 'thistle', 'topaz', 'tourmaline', 'tungsten', 'xanthic', 'zircon'], 'max_length': 13}, 'noun_adjective': {'type': 'words', 'words': ['fancy', 'magic', 'rainbow', 'woodoo'], 'max_length': 13}, 'animal_legendary': {'type': 'words', 'words': ['basilisk', 'chupacabra', 'dragon', 'griffin', 'pegasus', 'unicorn'], 'max_length': 13}, 'adjective_first': {'type': 'words', 'words': ['first', 'new'], 'max_length': 13}}
# Python 2 compatibility - all words must be unicode
# (this is to make Python 2 and 3 both work from the same __init__.py code)
try:
for listdef in config.values():
if listdef['type'] == 'words':
listdef['words'] = [unicode(x) for x in listdef['words']]
elif listdef['type'] == 'phrases':
listdef['phrases'] = [tuple(unicode(y) for y in x) for x in listdef['phrases']]
elif listdef['type'] == 'const':
listdef['value'] = unicode(listdef['value'])
except NameError:
pass
| config = {'all': {'comment': 'Entry point', 'type': 'nested', 'lists': ['2', '3', '4'], 'ensure_unique': True, 'ensure_unique_prefix': 4, 'max_slug_length': 50}, '2': {'comment': 'Two words (may also contain prepositions)', 'type': 'nested', 'lists': ['an']}, '3': {'comment': 'Three words (may also contain prepositions)', 'type': 'nested', 'lists': ['aan', 'ano', 'anl', 'nuo', 'as2', 's2o', 's2l', 'sl2']}, '4': {'comment': 'Four words (may also contain prepositions)', 'type': 'nested', 'lists': ['aano', 'aanl', 'anuo', 'as2o', 's2uo', 'as2l', 'asl2']}, 'an': {'comment': 'adjective-noun', 'type': 'cartesian', 'lists': ['adj_any', 'subj']}, 'aan': {'comment': 'adjective-adjective-noun', 'type': 'cartesian', 'lists': ['adj_far', 'adj_near', 'subj']}, 'ano': {'comment': 'adjective-noun-of-noun', 'type': 'cartesian', 'lists': ['adj_any', 'subj', 'of', 'of_noun_any']}, 'anl': {'comment': 'adjective-noun-from-location', 'type': 'cartesian', 'lists': ['adj_any', 'subj', 'from', 'from_noun_no_mod']}, 'nuo': {'comment': 'noun-of-adjective-noun', 'type': 'cartesian', 'lists': ['subj', 'of', 'of_modifier', 'of_noun']}, 'as2': {'comment': 'adjective-2word-subject', 'type': 'cartesian', 'lists': ['adj_far', 'subj2']}, 's2o': {'comment': '2word-subject-of-noun', 'type': 'cartesian', 'lists': ['subj2', 'of', 'of_noun_any']}, 's2l': {'comment': '2word-subject-from-location', 'type': 'cartesian', 'lists': ['subj2', 'from', 'from_noun_no_mod']}, 'sl2': {'comment': 'subject-from-some-location', 'type': 'cartesian', 'lists': ['subj', 'from', 'from2']}, 'aano': {'comment': 'adjective-adjective-noun-of-noun', 'type': 'cartesian', 'lists': ['adj_far', 'adj_near', 'subj', 'of', 'of_noun_any']}, 'aanl': {'comment': 'adjective-adjective-noun-from-location', 'type': 'cartesian', 'lists': ['adj_far', 'adj_near', 'subj', 'from', 'from_noun_no_mod']}, 'anuo': {'comment': 'adjective-noun-of-adjective-noun', 'type': 'cartesian', 'lists': ['adj_any', 'subj', 'of', 'of_modifier', 'of_noun']}, 'as2o': {'comment': 'adjective-2word-subject-of-noun', 'type': 'cartesian', 'lists': ['adj_far', 'subj2', 'of', 'of_noun_any']}, 's2uo': {'comment': 'adjective-2word-subject-of-adjective-noun', 'type': 'cartesian', 'lists': ['subj2', 'of', 'of_modifier', 'of_noun']}, 'as2l': {'comment': 'adjective-2word-subject-from-location', 'type': 'cartesian', 'lists': ['adj_far', 'subj2', 'from', 'from_noun_no_mod']}, 'asl2': {'comment': 'adjective-subject-from-some-location', 'type': 'cartesian', 'lists': ['adj_any', 'subj', 'from', 'from2']}, 'adj_far': {'comment': 'First adjective (with more following)', 'type': 'nested', 'lists': ['adjective', 'adjective_first', 'noun_adjective', 'size']}, 'adj_near': {'comment': 'Last adjective (closest to the subject)', 'type': 'nested', 'lists': ['adjective', 'color', 'noun_adjective', 'prefix']}, 'adj_any': {'comment': 'The only adjective (includes everything)', 'type': 'nested', 'lists': ['adjective', 'color', 'noun_adjective', 'prefix', 'size']}, 'subj': {'comment': 'The subject (animal)', 'type': 'nested', 'lists': ['animal', 'animal_breed', 'animal_legendary']}, 'of': {'type': 'const', 'value': 'of'}, 'of_noun_any': {'type': 'nested', 'lists': ['of_noun', 'of_noun_no_mod']}, 'from': {'type': 'const', 'value': 'from'}, 'from_noun_no_mod': {'type': 'words', 'words': ['venus', 'mars', 'jupiter', 'ganymede', 'saturn', 'uranus', 'neptune', 'pluto', 'betelgeuse', 'sirius', 'vega', 'arcadia', 'asgard', 'atlantis', 'avalon', 'camelot', 'eldorado', 'heaven', 'hell', 'hyperborea', 'lemuria', 'nibiru', 'shambhala', 'tartarus', 'valhalla', 'wonderland']}, 'prefix': {'type': 'words', 'words': ['giga', 'mega', 'micro', 'mini', 'nano', 'pygmy', 'super', 'uber', 'ultra', 'cyber', 'mutant', 'ninja', 'space'], 'max_length': 13}, 'of_modifier': {'type': 'words', 'words': ['absolute', 'abstract', 'algebraic', 'amazing', 'amusing', 'ancient', 'angelic', 'astonishing', 'authentic', 'awesome', 'beautiful', 'classic', 'delightful', 'demonic', 'eminent', 'enjoyable', 'eternal', 'excellent', 'exotic', 'extreme', 'fabulous', 'famous', 'fantastic', 'fascinating', 'flawless', 'fortunate', 'glorious', 'great', 'heavenly', 'holistic', 'hypothetical', 'ideal', 'illegal', 'imaginary', 'immense', 'imminent', 'immortal', 'impossible', 'impressive', 'improbable', 'incredible', 'inescapable', 'inevitable', 'infinite', 'inspiring', 'interesting', 'legal', 'magic', 'majestic', 'major', 'marvelous', 'massive', 'mysterious', 'nonconcrete', 'nonstop', 'luxurious', 'optimal', 'original', 'pastoral', 'perfect', 'perpetual', 'phenomenal', 'pleasurable', 'pragmatic', 'premium', 'radical', 'rampant', 'regular', 'remarkable', 'satisfying', 'serious', 'scientific', 'sexy', 'sheer', 'simple', 'silent', 'spectacular', 'splendid', 'stereotyped', 'stimulating', 'strange', 'striking', 'strongest', 'sublime', 'sudden', 'terrific', 'therapeutic', 'total', 'ultimate', 'uncanny', 'undeniable', 'unearthly', 'unexpected', 'unknown', 'unmatched', 'unnatural', 'unreal', 'unusual', 'utter', 'weird', 'wonderful', 'wondrous'], 'max_length': 13}, 'animal_breed': {'type': 'words', 'words': ['longhorn', 'akita', 'beagle', 'bloodhound', 'bulldog', 'chihuahua', 'collie', 'corgi', 'dalmatian', 'doberman', 'husky', 'labradoodle', 'labrador', 'mastiff', 'malamute', 'mongrel', 'poodle', 'rottweiler', 'spaniel', 'terrier', 'mule', 'mustang', 'pony', 'angora'], 'max_length': 13}, 'size': {'type': 'words', 'words': ['big', 'colossal', 'enormous', 'gigantic', 'great', 'huge', 'hulking', 'humongous', 'large', 'little', 'massive', 'miniature', 'petite', 'portable', 'small', 'tiny', 'towering'], 'max_length': 13}, 'from2': {'type': 'phrases', 'phrases': [('fancy', 'cafe'), ('prestigious', 'college'), ('prestigious', 'university'), ('big', 'city'), ('foreign', 'country'), ('small', 'town'), ('wild', 'west'), ('ancient', 'ruins'), ('another', 'dimension'), ('another', 'planet'), ('flying', 'circus'), ('secret', 'laboratory'), ('the', 'government'), ('the', 'future'), ('the', 'past'), ('the', 'stars')], 'number_of_words': 2, 'max_length': 24}, 'of_noun_no_mod': {'type': 'words', 'words': ['chemistry', 'education', 'experiment', 'mathematics', 'psychology', 'reading', 'cubism', 'painting', 'advertising', 'agreement', 'climate', 'competition', 'effort', 'emphasis', 'foundation', 'judgment', 'memory', 'opportunity', 'perspective', 'priority', 'promise', 'teaching'], 'max_length': 13}, 'of_noun': {'type': 'words', 'words': ['anger', 'bliss', 'contentment', 'courage', 'ecstasy', 'excitement', 'faith', 'felicity', 'fury', 'gaiety', 'glee', 'glory', 'greatness', 'inspiration', 'jest', 'joy', 'happiness', 'holiness', 'love', 'merriment', 'passion', 'patience', 'peace', 'persistence', 'pleasure', 'pride', 'recreation', 'relaxation', 'romance', 'serenity', 'tranquility', 'apotheosis', 'chaos', 'energy', 'essence', 'eternity', 'excellence', 'experience', 'freedom', 'nirvana', 'order', 'perfection', 'spirit', 'variation', 'acceptance', 'brotherhood', 'criticism', 'culture', 'discourse', 'discussion', 'justice', 'piety', 'respect', 'security', 'support', 'tolerance', 'trust', 'warranty', 'abundance', 'admiration', 'assurance', 'authority', 'awe', 'certainty', 'control', 'domination', 'enterprise', 'fame', 'grandeur', 'influence', 'luxury', 'management', 'opposition', 'plenty', 'popularity', 'prestige', 'prosperity', 'reputation', 'reverence', 'reward', 'superiority', 'triumph', 'wealth', 'acumen', 'aptitude', 'art', 'artistry', 'competence', 'efficiency', 'expertise', 'finesse', 'genius', 'leadership', 'perception', 'skill', 'virtuosity', 'argument', 'debate', 'action', 'agility', 'amplitude', 'attack', 'charisma', 'chivalry', 'defense', 'defiance', 'devotion', 'dignity', 'endurance', 'exercise', 'force', 'fortitude', 'gallantry', 'health', 'honor', 'infinity', 'inquire', 'intensity', 'luck', 'mastery', 'might', 'opportunity', 'penetration', 'performance', 'pluck', 'potency', 'protection', 'prowess', 'resistance', 'serendipity', 'speed', 'stamina', 'strength', 'swiftness', 'temperance', 'tenacity', 'valor', 'vigor', 'vitality', 'will', 'advance', 'conversion', 'correction', 'development', 'diversity', 'elevation', 'enhancement', 'enrichment', 'enthusiasm', 'focus', 'fruition', 'growth', 'improvement', 'innovation', 'modernism', 'novelty', 'proficiency', 'progress', 'promotion', 'realization', 'refinement', 'renovation', 'revolution', 'success', 'tempering', 'upgrade', 'ampleness', 'completion', 'satiation', 'saturation', 'sufficiency', 'vastness', 'wholeness', 'attraction', 'beauty', 'bloom', 'cleaning', 'courtesy', 'glamour', 'elegance', 'fascination', 'kindness', 'joviality', 'politeness', 'refinement', 'symmetry', 'sympathy', 'tact', 'calibration', 'drama', 'economy', 'engineering', 'examination', 'philosophy', 'poetry', 'research', 'science', 'democracy', 'election', 'feminism', 'champagne', 'coffee', 'cookies', 'flowers', 'fragrance', 'honeydew', 'music', 'pizza', 'aurora', 'blizzard', 'current', 'dew', 'downpour', 'drizzle', 'hail', 'hurricane', 'lightning', 'rain', 'snow', 'storm', 'sunshine', 'tempest', 'thunder', 'tornado', 'typhoon', 'weather', 'wind', 'whirlwind', 'abracadabra', 'adventure', 'atheism', 'camouflage', 'destiny', 'endeavor', 'expression', 'fantasy', 'fertility', 'imagination', 'karma', 'masquerade', 'maturity', 'radiance', 'shopping', 'sorcery', 'unity', 'witchcraft', 'wizardry', 'wonder', 'youth', 'purring'], 'max_length': 13}, 'subj2': {'type': 'phrases', 'phrases': [('atlantic', 'puffin'), ('bank', 'swallow'), ('barn', 'owl'), ('barn', 'swallow'), ('barred', 'owl'), ('chimney', 'swift'), ('cliff', 'swallow'), ('emperor', 'goose'), ('harlequin', 'duck'), ('himalayan', 'snowcock'), ('hyacinth', 'macaw'), ('mangrove', 'cuckoo'), ('mute', 'swan'), ('northern', 'cardinal'), ('peregrine', 'falcon'), ('prairie', 'falcon'), ('red', 'cardinal'), ('snow', 'goose'), ('snowy', 'owl'), ('trumpeter', 'swan'), ('tufted', 'puffin'), ('whooper', 'swan'), ('whooping', 'crane'), ('fire', 'ant'), ('alpine', 'chipmunk'), ('beaked', 'whale'), ('bottlenose', 'dolphin'), ('clouded', 'leopard'), ('eared', 'seal'), ('elephant', 'seal'), ('feral', 'cat'), ('feral', 'dog'), ('feral', 'donkey'), ('feral', 'goat'), ('feral', 'horse'), ('feral', 'pig'), ('fur', 'seal'), ('grizzly', 'bear'), ('harbor', 'porpoise'), ('honey', 'badger'), ('humpback', 'whale'), ('killer', 'whale'), ('mountain', 'deer'), ('mountain', 'goat'), ('mountain', 'lion'), ('olympic', 'marmot'), ('pampas', 'deer'), ('pine', 'marten'), ('polynesian', 'rat'), ('rhesus', 'macaque'), ('river', 'dolphin'), ('sea', 'lion'), ('sea', 'otter'), ('snow', 'leopard'), ('sperm', 'whale'), ('spinner', 'dolphin'), ('vampire', 'bat'), ('gila', 'monster'), ('freshwater', 'crocodile'), ('saltwater', 'crocodile'), ('snapping', 'turtle'), ('walking', 'mushroom')], 'number_of_words': 2, 'max_length': 22}, 'adjective': {'type': 'words', 'words': ['acrid', 'ambrosial', 'amorphous', 'armored', 'aromatic', 'bald', 'blazing', 'boisterous', 'bouncy', 'brawny', 'bulky', 'camouflaged', 'caped', 'chubby', 'curvy', 'elastic', 'ethereal', 'fat', 'feathered', 'fiery', 'flashy', 'flat', 'fluffy', 'foamy', 'fragrant', 'furry', 'fuzzy', 'glaring', 'hairy', 'heavy', 'hissing', 'horned', 'icy', 'imaginary', 'invisible', 'lean', 'loud', 'loutish', 'lumpy', 'lush', 'masked', 'meaty', 'messy', 'misty', 'nebulous', 'noisy', 'nondescript', 'organic', 'purring', 'quiet', 'quirky', 'radiant', 'roaring', 'ruddy', 'rustling', 'screeching', 'shaggy', 'shapeless', 'shiny', 'silent', 'silky', 'singing', 'skinny', 'smooth', 'soft', 'spicy', 'spiked', 'statuesque', 'sticky', 'tacky', 'tall', 'tangible', 'tentacled', 'thick', 'thundering', 'venomous', 'warm', 'weightless', 'whispering', 'winged', 'wooden', 'adorable', 'affable', 'amazing', 'amiable', 'attractive', 'beautiful', 'calm', 'charming', 'cherubic', 'classic', 'classy', 'convivial', 'cordial', 'cuddly', 'curly', 'cute', 'debonair', 'elegant', 'famous', 'fresh', 'friendly', 'funny', 'gorgeous', 'graceful', 'gregarious', 'grinning', 'handsome', 'hilarious', 'hot', 'interesting', 'kind', 'laughing', 'lovely', 'meek', 'mellow', 'merciful', 'neat', 'nifty', 'notorious', 'poetic', 'pretty', 'refined', 'refreshing', 'sexy', 'smiling', 'sociable', 'spiffy', 'stylish', 'sweet', 'tactful', 'whimsical', 'abiding', 'accurate', 'adamant', 'adaptable', 'adventurous', 'alluring', 'aloof', 'ambitious', 'amusing', 'annoying', 'arrogant', 'aspiring', 'belligerent', 'benign', 'berserk', 'benevolent', 'bold', 'brave', 'cheerful', 'chirpy', 'cocky', 'congenial', 'courageous', 'cryptic', 'curious', 'daft', 'dainty', 'daring', 'defiant', 'delicate', 'delightful', 'determined', 'devout', 'didactic', 'diligent', 'discreet', 'dramatic', 'dynamic', 'eager', 'eccentric', 'elated', 'encouraging', 'enigmatic', 'enthusiastic', 'evasive', 'faithful', 'fair', 'fanatic', 'fearless', 'fervent', 'festive', 'fierce', 'fine', 'free', 'gabby', 'garrulous', 'gay', 'gentle', 'glistening', 'greedy', 'grumpy', 'happy', 'honest', 'hopeful', 'hospitable', 'impetuous', 'independent', 'industrious', 'innocent', 'intrepid', 'jolly', 'jovial', 'just', 'lively', 'loose', 'loyal', 'merry', 'modest', 'mysterious', 'nice', 'obedient', 'optimistic', 'orthodox', 'outgoing', 'outrageous', 'overjoyed', 'passionate', 'perky', 'placid', 'polite', 'positive', 'proud', 'prudent', 'puzzling', 'quixotic', 'quizzical', 'rebel', 'resolute', 'rampant', 'righteous', 'romantic', 'rough', 'rousing', 'sassy', 'satisfied', 'sly', 'sincere', 'snobbish', 'spirited', 'spry', 'stalwart', 'stirring', 'swinging', 'tasteful', 'thankful', 'tidy', 'tremendous', 'truthful', 'unselfish', 'upbeat', 'uppish', 'valiant', 'vehement', 'vengeful', 'vigorous', 'vivacious', 'zealous', 'zippy', 'able', 'adept', 'analytic', 'astute', 'attentive', 'brainy', 'busy', 'calculating', 'capable', 'careful', 'cautious', 'certain', 'clever', 'competent', 'conscious', 'cooperative', 'crafty', 'crazy', 'cunning', 'daffy', 'devious', 'discerning', 'efficient', 'expert', 'functional', 'gifted', 'helpful', 'enlightened', 'idealistic', 'impartial', 'industrious', 'ingenious', 'inquisitive', 'intelligent', 'inventive', 'judicious', 'keen', 'knowing', 'literate', 'logical', 'masterful', 'mindful', 'nonchalant', 'observant', 'omniscient', 'poised', 'practical', 'pragmatic', 'proficient', 'provocative', 'qualified', 'radical', 'rational', 'realistic', 'resourceful', 'savvy', 'sceptical', 'sensible', 'serious', 'shrewd', 'skilled', 'slick', 'slim', 'sloppy', 'smart', 'sophisticated', 'stoic', 'succinct', 'talented', 'thoughtful', 'tricky', 'unbiased', 'uptight', 'versatile', 'versed', 'visionary', 'wise', 'witty', 'accelerated', 'active', 'agile', 'athletic', 'dashing', 'deft', 'dexterous', 'energetic', 'fast', 'frisky', 'hasty', 'hypersonic', 'meteoric', 'mighty', 'muscular', 'nimble', 'nippy', 'powerful', 'prompt', 'quick', 'rapid', 'resilient', 'robust', 'rugged', 'solid', 'speedy', 'steadfast', 'steady', 'strong', 'sturdy', 'tireless', 'tough', 'unyielding', 'rich', 'wealthy', 'meticulous', 'precise', 'rigorous', 'scrupulous', 'strict', 'airborne', 'burrowing', 'crouching', 'flying', 'hidden', 'hopping', 'jumping', 'lurking', 'tunneling', 'warping', 'aboriginal', 'amphibian', 'aquatic', 'arboreal', 'polar', 'terrestrial', 'urban', 'accomplished', 'astonishing', 'authentic', 'awesome', 'delectable', 'excellent', 'exotic', 'exuberant', 'fabulous', 'fantastic', 'fascinating', 'flawless', 'fortunate', 'funky', 'godlike', 'glorious', 'groovy', 'honored', 'illustrious', 'imposing', 'important', 'impressive', 'incredible', 'invaluable', 'kickass', 'majestic', 'magnificent', 'marvellous', 'monumental', 'perfect', 'phenomenal', 'pompous', 'precious', 'premium', 'private', 'remarkable', 'spectacular', 'splendid', 'successful', 'wonderful', 'wondrous', 'offbeat', 'original', 'outstanding', 'quaint', 'unique', 'ancient', 'antique', 'prehistoric', 'primitive', 'abstract', 'acoustic', 'angelic', 'arcane', 'archetypal', 'augmented', 'auspicious', 'axiomatic', 'beneficial', 'bipedal', 'bizarre', 'complex', 'dancing', 'dangerous', 'demonic', 'divergent', 'economic', 'electric', 'elite', 'eminent', 'enchanted', 'esoteric', 'finicky', 'fractal', 'futuristic', 'gainful', 'hallowed', 'heavenly', 'heretic', 'holistic', 'hungry', 'hypnotic', 'hysterical', 'illegal', 'imperial', 'imported', 'impossible', 'inescapable', 'juicy', 'liberal', 'ludicrous', 'lyrical', 'magnetic', 'manipulative', 'mature', 'military', 'macho', 'married', 'melodic', 'natural', 'naughty', 'nocturnal', 'nostalgic', 'optimal', 'pastoral', 'peculiar', 'piquant', 'pristine', 'prophetic', 'psychedelic', 'quantum', 'rare', 'real', 'secret', 'simple', 'spectral', 'spiritual', 'stereotyped', 'stimulating', 'straight', 'strange', 'tested', 'therapeutic', 'true', 'ubiquitous', 'uncovered', 'unnatural', 'utopian', 'vagabond', 'vague', 'vegan', 'victorious', 'vigilant', 'voracious', 'wakeful', 'wandering', 'watchful', 'wild', 'bright', 'brilliant', 'colorful', 'crystal', 'dark', 'dazzling', 'fluorescent', 'glittering', 'glossy', 'gleaming', 'light', 'mottled', 'neon', 'opalescent', 'pastel', 'smoky', 'sparkling', 'spotted', 'striped', 'translucent', 'transparent', 'vivid'], 'max_length': 13}, 'animal': {'type': 'words', 'words': ['earthworm', 'leech', 'worm', 'scorpion', 'spider', 'tarantula', 'barnacle', 'crab', 'crayfish', 'lobster', 'pillbug', 'prawn', 'shrimp', 'ant', 'bee', 'beetle', 'bug', 'bumblebee', 'butterfly', 'caterpillar', 'cicada', 'cricket', 'dragonfly', 'earwig', 'firefly', 'grasshopper', 'honeybee', 'hornet', 'inchworm', 'ladybug', 'locust', 'mantis', 'mayfly', 'mosquito', 'moth', 'sawfly', 'silkworm', 'termite', 'wasp', 'woodlouse', 'centipede', 'millipede', 'pronghorn', 'antelope', 'bison', 'buffalo', 'bull', 'chamois', 'cow', 'gazelle', 'gaur', 'goat', 'ibex', 'impala', 'kudu', 'markhor', 'mouflon', 'muskox', 'nyala', 'sheep', 'wildebeest', 'yak', 'zebu', 'alpaca', 'camel', 'llama', 'vicugna', 'caribou', 'chital', 'deer', 'elk', 'moose', 'pudu', 'reindeer', 'sambar', 'wapiti', 'beluga', 'dolphin', 'narwhal', 'orca', 'porpoise', 'whale', 'donkey', 'horse', 'stallion', 'zebra', 'giraffe', 'okapi', 'hippo', 'rhino', 'boar', 'hog', 'pig', 'swine', 'warthog', 'peccary', 'buzzard', 'eagle', 'goshawk', 'harrier', 'hawk', 'vulture', 'duck', 'goose', 'swan', 'teal', 'bird', 'hummingbird', 'swift', 'kiwi', 'potoo', 'seriema', 'cassowary', 'emu', 'condor', 'auk', 'avocet', 'guillemot', 'kittiwake', 'puffin', 'seagull', 'skua', 'stork', 'dodo', 'dove', 'pigeon', 'kingfisher', 'tody', 'bustard', 'coua', 'coucal', 'cuckoo', 'koel', 'malkoha', 'roadrunner', 'kagu', 'caracara', 'falcon', 'kestrel', 'chachalaca', 'chicken', 'curassow', 'grouse', 'guan', 'junglefowl', 'partridge', 'peacock', 'pheasant', 'quail', 'rooster', 'turkey', 'loon', 'coot', 'crane', 'turaco', 'hoatzin', 'bullfinch', 'crow', 'jackdaw', 'jaybird', 'finch', 'lyrebird', 'magpie', 'myna', 'nightingale', 'nuthatch', 'oriole', 'oxpecker', 'raven', 'robin', 'rook', 'skylark', 'sparrow', 'starling', 'swallow', 'waxbill', 'wren', 'heron', 'ibis', 'jacamar', 'piculet', 'toucan', 'toucanet', 'woodpecker', 'flamingo', 'grebe', 'albatross', 'fulmar', 'petrel', 'spoonbill', 'ara', 'cockatoo', 'kakapo', 'lorikeet', 'macaw', 'parakeet', 'parrot', 'penguin', 'ostrich', 'boobook', 'owl', 'booby', 'cormorant', 'frigatebird', 'pelican', 'quetzal', 'trogon', 'axolotl', 'bullfrog', 'frog', 'newt', 'salamander', 'toad', 'angelfish', 'barracuda', 'carp', 'catfish', 'dogfish', 'goldfish', 'guppy', 'eel', 'flounder', 'herring', 'lionfish', 'mackerel', 'oarfish', 'perch', 'salmon', 'seahorse', 'sturgeon', 'sunfish', 'tench', 'trout', 'tuna', 'wrasse', 'sawfish', 'shark', 'stingray', 'jellyfish', 'alligator', 'caiman', 'crocodile', 'gharial', 'starfish', 'urchin', 'hedgehog', 'coyote', 'dingo', 'dog', 'fennec', 'fox', 'hound', 'jackal', 'tanuki', 'wolf', 'bobcat', 'caracal', 'cat', 'cougar', 'jaguar', 'jaguarundi', 'leopard', 'lion', 'lynx', 'manul', 'ocelot', 'panther', 'puma', 'serval', 'smilodon', 'tiger', 'wildcat', 'aardwolf', 'binturong', 'cheetah', 'civet', 'fossa', 'hyena', 'meerkat', 'mongoose', 'badger', 'coati', 'ermine', 'ferret', 'marten', 'mink', 'otter', 'polecat', 'skunk', 'stoat', 'weasel', 'wolverine', 'seal', 'walrus', 'raccoon', 'ringtail', 'bear', 'panda', 'bat', 'armadillo', 'elephant', 'mammoth', 'mastodon', 'mole', 'hyrax', 'bandicoot', 'bettong', 'cuscus', 'kangaroo', 'koala', 'numbat', 'quokka', 'quoll', 'wallaby', 'wombat', 'echidna', 'platypus', 'tapir', 'anteater', 'sloth', 'agouti', 'beaver', 'capybara', 'chinchilla', 'chipmunk', 'degu', 'dormouse', 'gerbil', 'gopher', 'groundhog', 'jackrabbit', 'jerboa', 'hamster', 'hare', 'lemming', 'marmot', 'mouse', 'muskrat', 'porcupine', 'rabbit', 'rat', 'squirrel', 'vole', 'ape', 'baboon', 'bonobo', 'capuchin', 'chimpanzee', 'galago', 'gibbon', 'gorilla', 'lemur', 'lori', 'macaque', 'mandrill', 'marmoset', 'monkey', 'orangutan', 'tamarin', 'tarsier', 'uakari', 'dugong', 'manatee', 'shrew', 'aardwark', 'clam', 'cockle', 'mussel', 'oyster', 'scallop', 'shellfish', 'ammonite', 'cuttlefish', 'nautilus', 'octopus', 'squid', 'limpet', 'slug', 'snail', 'sponge', 'tuatara', 'agama', 'chameleon', 'dragon', 'gecko', 'iguana', 'lizard', 'pogona', 'skink', 'adder', 'anaconda', 'asp', 'boa', 'cobra', 'copperhead', 'mamba', 'python', 'rattlesnake', 'sidewinder', 'snake', 'taipan', 'viper', 'tortoise', 'turtle', 'dinosaur', 'raptor', 'mushroom'], 'max_length': 13}, 'color': {'type': 'words', 'words': ['almond', 'amaranth', 'apricot', 'artichoke', 'auburn', 'azure', 'banana', 'beige', 'black', 'blond', 'blue', 'brown', 'burgundy', 'carmine', 'carrot', 'celadon', 'cerise', 'cerulean', 'charcoal', 'cherry', 'chestnut', 'chocolate', 'cinnamon', 'copper', 'cream', 'crimson', 'cyan', 'daffodil', 'dandelion', 'denim', 'ebony', 'eggplant', 'gray', 'ginger', 'green', 'indigo', 'infrared', 'jasmine', 'khaki', 'lavender', 'lilac', 'mauve', 'magenta', 'mahogany', 'maize', 'marigold', 'mustard', 'ochre', 'orange', 'papaya', 'peach', 'persimmon', 'pink', 'pistachio', 'pumpkin', 'purple', 'raspberry', 'red', 'rose', 'russet', 'saffron', 'sage', 'scarlet', 'sepia', 'silver', 'tan', 'tangerine', 'taupe', 'teal', 'tomato', 'turquoise', 'tuscan', 'ultramarine', 'ultraviolet', 'umber', 'vanilla', 'vermilion', 'violet', 'viridian', 'white', 'wine', 'wisteria', 'yellow', 'agate', 'amber', 'amethyst', 'aquamarine', 'asparagus', 'beryl', 'brass', 'bronze', 'cobalt', 'coral', 'cornflower', 'diamond', 'emerald', 'garnet', 'golden', 'granite', 'ivory', 'jade', 'jasper', 'lemon', 'lime', 'malachite', 'maroon', 'myrtle', 'nickel', 'olive', 'olivine', 'onyx', 'opal', 'orchid', 'pearl', 'peridot', 'platinum', 'quartz', 'ruby', 'sandy', 'sapphire', 'steel', 'thistle', 'topaz', 'tourmaline', 'tungsten', 'xanthic', 'zircon'], 'max_length': 13}, 'noun_adjective': {'type': 'words', 'words': ['fancy', 'magic', 'rainbow', 'woodoo'], 'max_length': 13}, 'animal_legendary': {'type': 'words', 'words': ['basilisk', 'chupacabra', 'dragon', 'griffin', 'pegasus', 'unicorn'], 'max_length': 13}, 'adjective_first': {'type': 'words', 'words': ['first', 'new'], 'max_length': 13}}
try:
for listdef in config.values():
if listdef['type'] == 'words':
listdef['words'] = [unicode(x) for x in listdef['words']]
elif listdef['type'] == 'phrases':
listdef['phrases'] = [tuple((unicode(y) for y in x)) for x in listdef['phrases']]
elif listdef['type'] == 'const':
listdef['value'] = unicode(listdef['value'])
except NameError:
pass |
def getQuestions(dir):
questions = []
with open(dir, 'r', encoding='utf-8') as f:
for line in f:
questions.append(line.strip())
return questions
def getTriples(dir):
triples = []
with open(dir, 'r', encoding='utf-8') as f:
for i, line in enumerate(f):
line_sp = line.strip()
line_list = line_sp.split('\t')
triples.append({
'id': line_list[0],
'triples': line_list[2]})
return triples
def getTriplesWithId(id, triples):
list = []
for triple in triples:
if triple['id'] == str(id):
list.append(triple['triples'])
return list
def format(x):
return x.strip()
| def get_questions(dir):
questions = []
with open(dir, 'r', encoding='utf-8') as f:
for line in f:
questions.append(line.strip())
return questions
def get_triples(dir):
triples = []
with open(dir, 'r', encoding='utf-8') as f:
for (i, line) in enumerate(f):
line_sp = line.strip()
line_list = line_sp.split('\t')
triples.append({'id': line_list[0], 'triples': line_list[2]})
return triples
def get_triples_with_id(id, triples):
list = []
for triple in triples:
if triple['id'] == str(id):
list.append(triple['triples'])
return list
def format(x):
return x.strip() |
class MyTooManyWhoisQuerisError(Exception):
pass
class MyWhoisBanError(Exception):
pass
| class Mytoomanywhoisqueriserror(Exception):
pass
class Mywhoisbanerror(Exception):
pass |
def simple(func):
func.__annotation__ = "Hello"
return func
@simple
def foo():
pass
def complex(msg):
def annotate(func):
func.__annotation__ = msg
return func
return annotate
@complex("Hi")
def bar():
pass
foo
bar
class C(object):
@staticmethod
def smeth(arg0, arg1):
arg0
arg1
@classmethod
def cmeth(cls, arg0):
cls
arg0
| def simple(func):
func.__annotation__ = 'Hello'
return func
@simple
def foo():
pass
def complex(msg):
def annotate(func):
func.__annotation__ = msg
return func
return annotate
@complex('Hi')
def bar():
pass
foo
bar
class C(object):
@staticmethod
def smeth(arg0, arg1):
arg0
arg1
@classmethod
def cmeth(cls, arg0):
cls
arg0 |
{
"targets": [
{
"target_name": "EspressoLogicMinimizer",
"cflags": ["-std=c99", "-Wno-misleading-indentation", "-Wno-unused-result", "-Wno-format-overflow", "-Wno-implicit-fallthrough"],
"sources": [
"bridge/addon.cc",
"bridge/bridge.c",
"espresso-src/black_white.c",
"espresso-src/canonical.c",
"espresso-src/cofactor.c",
"espresso-src/cols.c",
"espresso-src/compl.c",
"espresso-src/contain.c",
"espresso-src/cpu_time.c",
"espresso-src/cubestr.c",
"espresso-src/cvrin.c",
"espresso-src/cvrm.c",
"espresso-src/cvrmisc.c",
"espresso-src/cvrout.c",
"espresso-src/dominate.c",
"espresso-src/equiv.c",
"espresso-src/espresso.c",
"espresso-src/essen.c",
"espresso-src/essentiality.c",
"espresso-src/exact.c",
"espresso-src/expand.c",
"espresso-src/gasp.c",
"espresso-src/gimpel.c",
"espresso-src/globals.c",
"espresso-src/hack.c",
"espresso-src/indep.c",
"espresso-src/irred.c",
"espresso-src/map.c",
"espresso-src/matrix.c",
"espresso-src/mincov.c",
"espresso-src/opo.c",
"espresso-src/pair.c",
"espresso-src/part.c",
"espresso-src/primes.c",
"espresso-src/prtime.c",
"espresso-src/reduce.c",
"espresso-src/rows.c",
"espresso-src/set.c",
"espresso-src/setc.c",
"espresso-src/sharp.c",
"espresso-src/sigma.c",
"espresso-src/signature.c",
"espresso-src/signature_exact.c",
"espresso-src/sminterf.c",
"espresso-src/solution.c",
"espresso-src/sparse.c",
"espresso-src/unate.c",
"espresso-src/util_signature.c",
"espresso-src/verify.c"
],
"include_dirs" : [
"<!(node -e \"require('nan')\")",
"espresso-src"
]
}
]
}
| {'targets': [{'target_name': 'EspressoLogicMinimizer', 'cflags': ['-std=c99', '-Wno-misleading-indentation', '-Wno-unused-result', '-Wno-format-overflow', '-Wno-implicit-fallthrough'], 'sources': ['bridge/addon.cc', 'bridge/bridge.c', 'espresso-src/black_white.c', 'espresso-src/canonical.c', 'espresso-src/cofactor.c', 'espresso-src/cols.c', 'espresso-src/compl.c', 'espresso-src/contain.c', 'espresso-src/cpu_time.c', 'espresso-src/cubestr.c', 'espresso-src/cvrin.c', 'espresso-src/cvrm.c', 'espresso-src/cvrmisc.c', 'espresso-src/cvrout.c', 'espresso-src/dominate.c', 'espresso-src/equiv.c', 'espresso-src/espresso.c', 'espresso-src/essen.c', 'espresso-src/essentiality.c', 'espresso-src/exact.c', 'espresso-src/expand.c', 'espresso-src/gasp.c', 'espresso-src/gimpel.c', 'espresso-src/globals.c', 'espresso-src/hack.c', 'espresso-src/indep.c', 'espresso-src/irred.c', 'espresso-src/map.c', 'espresso-src/matrix.c', 'espresso-src/mincov.c', 'espresso-src/opo.c', 'espresso-src/pair.c', 'espresso-src/part.c', 'espresso-src/primes.c', 'espresso-src/prtime.c', 'espresso-src/reduce.c', 'espresso-src/rows.c', 'espresso-src/set.c', 'espresso-src/setc.c', 'espresso-src/sharp.c', 'espresso-src/sigma.c', 'espresso-src/signature.c', 'espresso-src/signature_exact.c', 'espresso-src/sminterf.c', 'espresso-src/solution.c', 'espresso-src/sparse.c', 'espresso-src/unate.c', 'espresso-src/util_signature.c', 'espresso-src/verify.c'], 'include_dirs': ['<!(node -e "require(\'nan\')")', 'espresso-src']}]} |
class Instance():
def __init__(self):
self.words=[]
self.labels=[]
self.words_size=0
self.words_index = []
self.label_index = [] | class Instance:
def __init__(self):
self.words = []
self.labels = []
self.words_size = 0
self.words_index = []
self.label_index = [] |
LEAGUE_IDS = {
"BL": 394,
"BL2": 395,
"BL3": 403,
"FL": 396,
"FL2": 397,
"EPL": 398,
"EL1": 425,
"LLIGA": 399,
"SD": 400,
"SA": 401,
"PPL": 402,
"DED": 404,
"CL": 405
}
| league_ids = {'BL': 394, 'BL2': 395, 'BL3': 403, 'FL': 396, 'FL2': 397, 'EPL': 398, 'EL1': 425, 'LLIGA': 399, 'SD': 400, 'SA': 401, 'PPL': 402, 'DED': 404, 'CL': 405} |
{
"targets": [
{
"target_name": "polyglot",
"sources": [ "polyglot.cpp" ]
}
]
}
| {'targets': [{'target_name': 'polyglot', 'sources': ['polyglot.cpp']}]} |
#7-8 & 7-9
# Create our orders list
sandwich_orders = ['ham', 'bologna','pastrami', 'cheese', 'blt', 'pastrami', 'turkey', 'pastrami']
finished_sandwiches = []
# Deli is out of pastrami, so we will remove all pastrami orders.
print("\nThe deli is out of pastrami sandwiches.")
while 'pastrami' in sandwich_orders:
sandwich_orders.remove('pastrami')
# Loop through the orders and make them
for sandwich in sandwich_orders:
print(f"I finished your {sandwich} sandwich. \n")
finished_sandwiches.append(sandwich)
print(finished_sandwiches)
#7-10 Polling users about dream vacations
# Set a flag so we can break when flag is False
flag = True
# Dictionary to store users name and dream vacation location
dream_vacations = {}
while flag:
name = input("\nWhat is your name? ")
destination = input("Where is your dream vacation location? ")
dream_vacations[name] = destination
poll_again = input("Would you like to poll another person? (yes/no)")
if poll_again == 'no':
flag = False
print("- - - Results - - -")
for name, location in dream_vacations.items():
print(f"{name.title()} would go to {location}.") | sandwich_orders = ['ham', 'bologna', 'pastrami', 'cheese', 'blt', 'pastrami', 'turkey', 'pastrami']
finished_sandwiches = []
print('\nThe deli is out of pastrami sandwiches.')
while 'pastrami' in sandwich_orders:
sandwich_orders.remove('pastrami')
for sandwich in sandwich_orders:
print(f'I finished your {sandwich} sandwich. \n')
finished_sandwiches.append(sandwich)
print(finished_sandwiches)
flag = True
dream_vacations = {}
while flag:
name = input('\nWhat is your name? ')
destination = input('Where is your dream vacation location? ')
dream_vacations[name] = destination
poll_again = input('Would you like to poll another person? (yes/no)')
if poll_again == 'no':
flag = False
print('- - - Results - - -')
for (name, location) in dream_vacations.items():
print(f'{name.title()} would go to {location}.') |
'''
--- Part Two ---
The Elves in accounting are thankful for your help; one of them even offers you a starfish coin they had left over from a past vacation.
They offer you a second one if you can find three numbers in your expense report that meet the same criteria.
Using the above example again, the three entries that sum to 2020 are 979, 366, and 675. Multiplying them together produces the answer, 241861950.
In your expense report, what is the product of the three entries that sum to 2020?
'''
# abrir y leer archivo
f = open ('input.txt','r')
mensaje = f.read()
f.close()
list_numbers = mensaje.split('\n')
for i in list_numbers:
for j in list_numbers:
for k in list_numbers:
if(int(i)+int(j)+int(k)==2020):
print(int(i)*int(j)*int(k)) | """
--- Part Two ---
The Elves in accounting are thankful for your help; one of them even offers you a starfish coin they had left over from a past vacation.
They offer you a second one if you can find three numbers in your expense report that meet the same criteria.
Using the above example again, the three entries that sum to 2020 are 979, 366, and 675. Multiplying them together produces the answer, 241861950.
In your expense report, what is the product of the three entries that sum to 2020?
"""
f = open('input.txt', 'r')
mensaje = f.read()
f.close()
list_numbers = mensaje.split('\n')
for i in list_numbers:
for j in list_numbers:
for k in list_numbers:
if int(i) + int(j) + int(k) == 2020:
print(int(i) * int(j) * int(k)) |
#http://code.activestate.com/recipes/52219-associating-multiple-values-with-each-key-in-a-dic/
#https://www.oreilly.com/library/view/python-cookbook/0596001673/ch01s06.html
def repeatedValue():
# this method allows duplicate values for the same key
d = dict()
# To add a key->value pair, do this:
#d.setdefault(key, []).append(value)
d.setdefault('a',[]).append('apple')
d.setdefault('b',[]).append('ball')
d.setdefault('c',[]).append('cat')
d.setdefault('a',[]).append('aeroplane')
d.setdefault('a',[]).append('anar')
d.setdefault('b',[]).append('balloon')
#aval = d['a']
print(d)
d['a'].remove('apple')
print(d)
def nonRepeatedValue():
example = {}
example.setdefault('a', set()).add('apple')
example.setdefault('b', set()).add('ball')
example.setdefault('a', set()).add('ant')
#example.setdefault('a', set()).add('apple')
#example.setdefault('c', {})['cat']=1
#example.setdefault('a', {})['ant']=1
#example.setdefault('a', {})['apple']=1
print(example)
d = example['a']
print(d)
if __name__ == '__main__':
#repeatedValue()
nonRepeatedValue()
| def repeated_value():
d = dict()
d.setdefault('a', []).append('apple')
d.setdefault('b', []).append('ball')
d.setdefault('c', []).append('cat')
d.setdefault('a', []).append('aeroplane')
d.setdefault('a', []).append('anar')
d.setdefault('b', []).append('balloon')
print(d)
d['a'].remove('apple')
print(d)
def non_repeated_value():
example = {}
example.setdefault('a', set()).add('apple')
example.setdefault('b', set()).add('ball')
example.setdefault('a', set()).add('ant')
print(example)
d = example['a']
print(d)
if __name__ == '__main__':
non_repeated_value() |
STATUS_ACTIVE = 1
STATUS_INACTIVE = 2
STATUS_PENDING = 3
STATUS_FAILED = 9
STATUS_DONE = 10
STATUS_DELETED = 11
STATUS_FLOW_OPEN = 1
STATUS_FLOW_PROCESSING = 2
STATUS_FLOW_PROCESSED = 3
STATUS_FLOW_COMMITTED = 4
STATUS_FLOW_ABORTED = 11
TAP_ACCESS_PUBLIC = 1
TAP_ACCESS_SUBSCRIBERS = 2
TAP_ACCESS_PRIVATE = 3
DATA_STATE_NOT_MATERIALIZED = 1
DATA_STATE_MATERIALIZED = 2
DATA_STATE_READ_ONLY = 3
DATA_STATE_REQUEST_REBUILD = 4
DATA_STATE_REBUILDING = 5
DATA_STATE_REQUEST_TRUNCATE = 6
TRX_TYPE_FLOW = 1
TRX_TYPE_CREDIT = 2
FLOW_UPLOAD = 1
FLOW_DOWNLOAD = 3
TAG_ENTITY_TYPE = 1
TAG_PRIVACY_TYPE = 2
TAG_FEED_TYPE = 3
DISPLAY_MODE_BUYER = 1
DISPLAY_MODE_SELLER = 2
DISPLAY_MODE_FULL = 3
| status_active = 1
status_inactive = 2
status_pending = 3
status_failed = 9
status_done = 10
status_deleted = 11
status_flow_open = 1
status_flow_processing = 2
status_flow_processed = 3
status_flow_committed = 4
status_flow_aborted = 11
tap_access_public = 1
tap_access_subscribers = 2
tap_access_private = 3
data_state_not_materialized = 1
data_state_materialized = 2
data_state_read_only = 3
data_state_request_rebuild = 4
data_state_rebuilding = 5
data_state_request_truncate = 6
trx_type_flow = 1
trx_type_credit = 2
flow_upload = 1
flow_download = 3
tag_entity_type = 1
tag_privacy_type = 2
tag_feed_type = 3
display_mode_buyer = 1
display_mode_seller = 2
display_mode_full = 3 |
# The following is just an example used in class. The actual code is below:
# running = True
# while running:
#
# try:
# query = input('Enter 1 to search phonebook, enter 2 to quit: ')
# except ValueError:
# print('Imput must be a number. Please try again.')
# continue
#
# if query == '1':
# print('Thank you.')
# elif query == '2':
# quit()
# else:
# print('I did not understand that')
# PHONEBOOK LAB
phonebook = {'Katie': {'name': 'Katie', 'number': '2109415792', 'phrase': 'friend'},
'Charlie': {'name': 'Charlie', 'number': '504699679', 'phrase': 'neighbor'},
'Chelsea': {'name': 'Chelsea', 'number': '2109415778', 'phrase': 'sister'},
'James': {'name': 'James', 'number': '5689412374', 'phrase': 'son'}}
running = True
while running:
try:
query = int(input('Enter 1 to create a contact, 2 to retrieve contact, 3 to update contact and 4 to delete contact: '))
except ValueError:
print('Imput must be a number. Please try again.')
continue
if query == 1:
add_name = str(input('Enter a name: ')).capitalize()
add_number = str(input('Enter a number: '))
add_phrase = str(input('Enter a phrase: '))
newdictionary = {'name': add_name, 'number': add_number, 'add_phrase': add_phrase}
phonebook.update(newdictionary)
print('Your new contact has been created successfully: ' + str(newdictionary.values()))
elif query == 2:
print('These are your options: ' + str(phonebook.keys()))
name = (str(input('Which contact do you want to retrieve? '))).capitalize()
if name in phonebook:
print(phonebook[name])
else:
print('There is no such name. Try again.')
elif query == 3:
upd_name = str(input('What name would you like to update? ')).capitalize()
del phonebook[upd_name]
new_name = str(input('Enter a name: ')).capitalize()
new_number = str(input('Enter a number: '))
new_phrase = str(input('Enter a phrase: '))
upd_dictionary = {'name': new_name, 'number': new_number, 'add_phrase': new_phrase}
phonebook.update(upd_dictionary)
print('Your contact has been updated successfully: ' + str(upd_dictionary.values()))
elif query == 4:
del_name = str(input('Which name would you like to delete?'))
del phonebook[del_name]
print(phonebook)
else:
print('Incorrect value. Please try again.') | phonebook = {'Katie': {'name': 'Katie', 'number': '2109415792', 'phrase': 'friend'}, 'Charlie': {'name': 'Charlie', 'number': '504699679', 'phrase': 'neighbor'}, 'Chelsea': {'name': 'Chelsea', 'number': '2109415778', 'phrase': 'sister'}, 'James': {'name': 'James', 'number': '5689412374', 'phrase': 'son'}}
running = True
while running:
try:
query = int(input('Enter 1 to create a contact, 2 to retrieve contact, 3 to update contact and 4 to delete contact: '))
except ValueError:
print('Imput must be a number. Please try again.')
continue
if query == 1:
add_name = str(input('Enter a name: ')).capitalize()
add_number = str(input('Enter a number: '))
add_phrase = str(input('Enter a phrase: '))
newdictionary = {'name': add_name, 'number': add_number, 'add_phrase': add_phrase}
phonebook.update(newdictionary)
print('Your new contact has been created successfully: ' + str(newdictionary.values()))
elif query == 2:
print('These are your options: ' + str(phonebook.keys()))
name = str(input('Which contact do you want to retrieve? ')).capitalize()
if name in phonebook:
print(phonebook[name])
else:
print('There is no such name. Try again.')
elif query == 3:
upd_name = str(input('What name would you like to update? ')).capitalize()
del phonebook[upd_name]
new_name = str(input('Enter a name: ')).capitalize()
new_number = str(input('Enter a number: '))
new_phrase = str(input('Enter a phrase: '))
upd_dictionary = {'name': new_name, 'number': new_number, 'add_phrase': new_phrase}
phonebook.update(upd_dictionary)
print('Your contact has been updated successfully: ' + str(upd_dictionary.values()))
elif query == 4:
del_name = str(input('Which name would you like to delete?'))
del phonebook[del_name]
print(phonebook)
else:
print('Incorrect value. Please try again.') |
class ParticleSettingsTextureSlot:
clump_factor = None
damp_factor = None
density_factor = None
field_factor = None
gravity_factor = None
kink_amp_factor = None
kink_freq_factor = None
length_factor = None
life_factor = None
mapping = None
mapping_x = None
mapping_y = None
mapping_z = None
object = None
rough_factor = None
size_factor = None
texture_coords = None
time_factor = None
use_map_clump = None
use_map_damp = None
use_map_density = None
use_map_field = None
use_map_gravity = None
use_map_kink_amp = None
use_map_kink_freq = None
use_map_length = None
use_map_life = None
use_map_rough = None
use_map_size = None
use_map_time = None
use_map_velocity = None
uv_layer = None
velocity_factor = None
| class Particlesettingstextureslot:
clump_factor = None
damp_factor = None
density_factor = None
field_factor = None
gravity_factor = None
kink_amp_factor = None
kink_freq_factor = None
length_factor = None
life_factor = None
mapping = None
mapping_x = None
mapping_y = None
mapping_z = None
object = None
rough_factor = None
size_factor = None
texture_coords = None
time_factor = None
use_map_clump = None
use_map_damp = None
use_map_density = None
use_map_field = None
use_map_gravity = None
use_map_kink_amp = None
use_map_kink_freq = None
use_map_length = None
use_map_life = None
use_map_rough = None
use_map_size = None
use_map_time = None
use_map_velocity = None
uv_layer = None
velocity_factor = None |
# Some globals gane defaults
DEFAULT_DICE_SIDES_NUMBER = 6 # Nb of side of the Dices
SCORING_DICE_VALUE = [1, 5] # List of the side values of the dice who trigger a standard score
SCORING_MULTIPLIER = [100, 50] # List of multiplier for standard score
THRESHOLD_BONUS = 3 # Threshold of the triggering for bonus in term of occurrence of the same slide value
STD_BONUS_MULTIPLIER = 100 # Standard multiplier for bonus
ACE_BONUS_MULTIPLIER = 1000 # Special multiplier for ace bonus
DEFAULT_DICES_NUMBER = 5 # Number of dices by default in the set
| default_dice_sides_number = 6
scoring_dice_value = [1, 5]
scoring_multiplier = [100, 50]
threshold_bonus = 3
std_bonus_multiplier = 100
ace_bonus_multiplier = 1000
default_dices_number = 5 |
#
# PySNMP MIB module HP-ICF-INST-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HP-ICF-INST-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:34:11 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)
#
OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
SingleValueConstraint, ConstraintsUnion, ValueRangeConstraint, ValueSizeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ConstraintsUnion", "ValueRangeConstraint", "ValueSizeConstraint", "ConstraintsIntersection")
hpSwitch, = mibBuilder.importSymbols("HP-ICF-OID", "hpSwitch")
ModuleCompliance, NotificationGroup, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup", "ObjectGroup")
Bits, TimeTicks, Counter32, Counter64, MibIdentifier, Unsigned32, NotificationType, ModuleIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, Gauge32, IpAddress, Integer32, iso, ObjectIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "TimeTicks", "Counter32", "Counter64", "MibIdentifier", "Unsigned32", "NotificationType", "ModuleIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Gauge32", "IpAddress", "Integer32", "iso", "ObjectIdentity")
TextualConvention, DisplayString, TruthValue = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString", "TruthValue")
hpicfInstMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 45))
hpicfInstMIB.setRevisions(('2007-09-07 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: hpicfInstMIB.setRevisionsDescriptions(('Initial revision.',))
if mibBuilder.loadTexts: hpicfInstMIB.setLastUpdated('200709070000Z')
if mibBuilder.loadTexts: hpicfInstMIB.setOrganization('HP Networking')
if mibBuilder.loadTexts: hpicfInstMIB.setContactInfo('Hewlett-Packard Company 8000 Foothills Blvd. Roseville, CA 95747')
if mibBuilder.loadTexts: hpicfInstMIB.setDescription('This MIB module contains HP proprietary definitions for Instrumentation.')
hpicfInstObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 45, 1))
hpicfInstConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 45, 2))
hpicfInstGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 45, 2, 1))
hpicfInstCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 45, 2, 2))
hpicfInstEnable = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 45, 1, 1), TruthValue().clone('true')).setMaxAccess("readonly")
if mibBuilder.loadTexts: hpicfInstEnable.setStatus('current')
if mibBuilder.loadTexts: hpicfInstEnable.setDescription('The operational status of Instrumentation on this switch.')
hpicfInstMaxMemMB = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 45, 1, 2), Integer32().clone(2)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hpicfInstMaxMemMB.setStatus('current')
if mibBuilder.loadTexts: hpicfInstMaxMemMB.setDescription('The maximum memory that can be used by Instrumentation, in megabytes.')
hpicfInstParameterTable = MibTable((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 45, 1, 3), )
if mibBuilder.loadTexts: hpicfInstParameterTable.setStatus('current')
if mibBuilder.loadTexts: hpicfInstParameterTable.setDescription('Values of monitored instrumentation parameters.')
hpicfInstParameterEntry = MibTableRow((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 45, 1, 3, 1), ).setIndexNames((0, "HP-ICF-INST-MIB", "hpicfInstParameterIndex"), (0, "HP-ICF-INST-MIB", "hpicfInstInterfaceIndex"), (0, "HP-ICF-INST-MIB", "hpicfInstIntervalIndex"))
if mibBuilder.loadTexts: hpicfInstParameterEntry.setStatus('current')
if mibBuilder.loadTexts: hpicfInstParameterEntry.setDescription('An entry in the hpicfInstParameterTable.')
hpicfInstParameterIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 45, 1, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)))
if mibBuilder.loadTexts: hpicfInstParameterIndex.setStatus('current')
if mibBuilder.loadTexts: hpicfInstParameterIndex.setDescription('The index of the parameter.')
hpicfInstInterfaceIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 45, 1, 3, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)))
if mibBuilder.loadTexts: hpicfInstInterfaceIndex.setStatus('current')
if mibBuilder.loadTexts: hpicfInstInterfaceIndex.setDescription('Interface index i.e. port number for per port parameters and 0 for global parameters.')
hpicfInstIntervalIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 45, 1, 3, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)))
if mibBuilder.loadTexts: hpicfInstIntervalIndex.setStatus('current')
if mibBuilder.loadTexts: hpicfInstIntervalIndex.setDescription('The index of the interval.')
hpicfInstParameterName = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 45, 1, 3, 1, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 20))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hpicfInstParameterName.setStatus('current')
if mibBuilder.loadTexts: hpicfInstParameterName.setDescription('The name of the parameter.')
hpicfInstIntervalName = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 45, 1, 3, 1, 5), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 20))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hpicfInstIntervalName.setStatus('current')
if mibBuilder.loadTexts: hpicfInstIntervalName.setDescription('The name of the interval.')
hpicfInstParameterValue = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 45, 1, 3, 1, 6), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hpicfInstParameterValue.setStatus('current')
if mibBuilder.loadTexts: hpicfInstParameterValue.setDescription('The current parameter value for the given interface and interval.')
hpicfInstParamValMin = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 45, 1, 3, 1, 7), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hpicfInstParamValMin.setStatus('current')
if mibBuilder.loadTexts: hpicfInstParamValMin.setDescription('The minimum value of the parameter for the given interface and interval.')
hpicfInstParamValMax = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 45, 1, 3, 1, 8), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hpicfInstParamValMax.setStatus('current')
if mibBuilder.loadTexts: hpicfInstParamValMax.setDescription('The maximum value of the parameter for the given interface and interval.')
hpicfInstBaseGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 45, 2, 1, 2)).setObjects(("HP-ICF-INST-MIB", "hpicfInstEnable"), ("HP-ICF-INST-MIB", "hpicfInstMaxMemMB"), ("HP-ICF-INST-MIB", "hpicfInstParameterName"), ("HP-ICF-INST-MIB", "hpicfInstIntervalName"), ("HP-ICF-INST-MIB", "hpicfInstParameterValue"), ("HP-ICF-INST-MIB", "hpicfInstParamValMin"), ("HP-ICF-INST-MIB", "hpicfInstParamValMax"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hpicfInstBaseGroup = hpicfInstBaseGroup.setStatus('current')
if mibBuilder.loadTexts: hpicfInstBaseGroup.setDescription('A collection of objects to support basic Instrumentation configuration on HP switches.')
hpicfInstBaseCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 45, 2, 2, 1)).setObjects(("HP-ICF-INST-MIB", "hpicfInstBaseGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hpicfInstBaseCompliance = hpicfInstBaseCompliance.setStatus('current')
if mibBuilder.loadTexts: hpicfInstBaseCompliance.setDescription('The compliance statement for HP switches running Instrumentation and implementing the HP-ICF-INST MIB.')
mibBuilder.exportSymbols("HP-ICF-INST-MIB", hpicfInstIntervalIndex=hpicfInstIntervalIndex, hpicfInstEnable=hpicfInstEnable, hpicfInstBaseGroup=hpicfInstBaseGroup, hpicfInstCompliances=hpicfInstCompliances, hpicfInstParameterEntry=hpicfInstParameterEntry, hpicfInstConformance=hpicfInstConformance, hpicfInstParameterName=hpicfInstParameterName, hpicfInstBaseCompliance=hpicfInstBaseCompliance, hpicfInstInterfaceIndex=hpicfInstInterfaceIndex, hpicfInstParamValMax=hpicfInstParamValMax, hpicfInstParameterTable=hpicfInstParameterTable, hpicfInstGroups=hpicfInstGroups, hpicfInstObjects=hpicfInstObjects, hpicfInstMaxMemMB=hpicfInstMaxMemMB, hpicfInstParameterValue=hpicfInstParameterValue, hpicfInstIntervalName=hpicfInstIntervalName, PYSNMP_MODULE_ID=hpicfInstMIB, hpicfInstMIB=hpicfInstMIB, hpicfInstParamValMin=hpicfInstParamValMin, hpicfInstParameterIndex=hpicfInstParameterIndex)
| (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_union, value_range_constraint, value_size_constraint, constraints_intersection) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'SingleValueConstraint', 'ConstraintsUnion', 'ValueRangeConstraint', 'ValueSizeConstraint', 'ConstraintsIntersection')
(hp_switch,) = mibBuilder.importSymbols('HP-ICF-OID', 'hpSwitch')
(module_compliance, notification_group, object_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup', 'ObjectGroup')
(bits, time_ticks, counter32, counter64, mib_identifier, unsigned32, notification_type, module_identity, mib_scalar, mib_table, mib_table_row, mib_table_column, gauge32, ip_address, integer32, iso, object_identity) = mibBuilder.importSymbols('SNMPv2-SMI', 'Bits', 'TimeTicks', 'Counter32', 'Counter64', 'MibIdentifier', 'Unsigned32', 'NotificationType', 'ModuleIdentity', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Gauge32', 'IpAddress', 'Integer32', 'iso', 'ObjectIdentity')
(textual_convention, display_string, truth_value) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString', 'TruthValue')
hpicf_inst_mib = module_identity((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 45))
hpicfInstMIB.setRevisions(('2007-09-07 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts:
hpicfInstMIB.setRevisionsDescriptions(('Initial revision.',))
if mibBuilder.loadTexts:
hpicfInstMIB.setLastUpdated('200709070000Z')
if mibBuilder.loadTexts:
hpicfInstMIB.setOrganization('HP Networking')
if mibBuilder.loadTexts:
hpicfInstMIB.setContactInfo('Hewlett-Packard Company 8000 Foothills Blvd. Roseville, CA 95747')
if mibBuilder.loadTexts:
hpicfInstMIB.setDescription('This MIB module contains HP proprietary definitions for Instrumentation.')
hpicf_inst_objects = mib_identifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 45, 1))
hpicf_inst_conformance = mib_identifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 45, 2))
hpicf_inst_groups = mib_identifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 45, 2, 1))
hpicf_inst_compliances = mib_identifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 45, 2, 2))
hpicf_inst_enable = mib_scalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 45, 1, 1), truth_value().clone('true')).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hpicfInstEnable.setStatus('current')
if mibBuilder.loadTexts:
hpicfInstEnable.setDescription('The operational status of Instrumentation on this switch.')
hpicf_inst_max_mem_mb = mib_scalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 45, 1, 2), integer32().clone(2)).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
hpicfInstMaxMemMB.setStatus('current')
if mibBuilder.loadTexts:
hpicfInstMaxMemMB.setDescription('The maximum memory that can be used by Instrumentation, in megabytes.')
hpicf_inst_parameter_table = mib_table((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 45, 1, 3))
if mibBuilder.loadTexts:
hpicfInstParameterTable.setStatus('current')
if mibBuilder.loadTexts:
hpicfInstParameterTable.setDescription('Values of monitored instrumentation parameters.')
hpicf_inst_parameter_entry = mib_table_row((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 45, 1, 3, 1)).setIndexNames((0, 'HP-ICF-INST-MIB', 'hpicfInstParameterIndex'), (0, 'HP-ICF-INST-MIB', 'hpicfInstInterfaceIndex'), (0, 'HP-ICF-INST-MIB', 'hpicfInstIntervalIndex'))
if mibBuilder.loadTexts:
hpicfInstParameterEntry.setStatus('current')
if mibBuilder.loadTexts:
hpicfInstParameterEntry.setDescription('An entry in the hpicfInstParameterTable.')
hpicf_inst_parameter_index = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 45, 1, 3, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 65535)))
if mibBuilder.loadTexts:
hpicfInstParameterIndex.setStatus('current')
if mibBuilder.loadTexts:
hpicfInstParameterIndex.setDescription('The index of the parameter.')
hpicf_inst_interface_index = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 45, 1, 3, 1, 2), integer32().subtype(subtypeSpec=value_range_constraint(1, 65535)))
if mibBuilder.loadTexts:
hpicfInstInterfaceIndex.setStatus('current')
if mibBuilder.loadTexts:
hpicfInstInterfaceIndex.setDescription('Interface index i.e. port number for per port parameters and 0 for global parameters.')
hpicf_inst_interval_index = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 45, 1, 3, 1, 3), integer32().subtype(subtypeSpec=value_range_constraint(1, 65535)))
if mibBuilder.loadTexts:
hpicfInstIntervalIndex.setStatus('current')
if mibBuilder.loadTexts:
hpicfInstIntervalIndex.setDescription('The index of the interval.')
hpicf_inst_parameter_name = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 45, 1, 3, 1, 4), display_string().subtype(subtypeSpec=value_size_constraint(0, 20))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hpicfInstParameterName.setStatus('current')
if mibBuilder.loadTexts:
hpicfInstParameterName.setDescription('The name of the parameter.')
hpicf_inst_interval_name = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 45, 1, 3, 1, 5), display_string().subtype(subtypeSpec=value_size_constraint(0, 20))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hpicfInstIntervalName.setStatus('current')
if mibBuilder.loadTexts:
hpicfInstIntervalName.setDescription('The name of the interval.')
hpicf_inst_parameter_value = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 45, 1, 3, 1, 6), unsigned32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hpicfInstParameterValue.setStatus('current')
if mibBuilder.loadTexts:
hpicfInstParameterValue.setDescription('The current parameter value for the given interface and interval.')
hpicf_inst_param_val_min = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 45, 1, 3, 1, 7), unsigned32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hpicfInstParamValMin.setStatus('current')
if mibBuilder.loadTexts:
hpicfInstParamValMin.setDescription('The minimum value of the parameter for the given interface and interval.')
hpicf_inst_param_val_max = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 45, 1, 3, 1, 8), unsigned32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hpicfInstParamValMax.setStatus('current')
if mibBuilder.loadTexts:
hpicfInstParamValMax.setDescription('The maximum value of the parameter for the given interface and interval.')
hpicf_inst_base_group = object_group((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 45, 2, 1, 2)).setObjects(('HP-ICF-INST-MIB', 'hpicfInstEnable'), ('HP-ICF-INST-MIB', 'hpicfInstMaxMemMB'), ('HP-ICF-INST-MIB', 'hpicfInstParameterName'), ('HP-ICF-INST-MIB', 'hpicfInstIntervalName'), ('HP-ICF-INST-MIB', 'hpicfInstParameterValue'), ('HP-ICF-INST-MIB', 'hpicfInstParamValMin'), ('HP-ICF-INST-MIB', 'hpicfInstParamValMax'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hpicf_inst_base_group = hpicfInstBaseGroup.setStatus('current')
if mibBuilder.loadTexts:
hpicfInstBaseGroup.setDescription('A collection of objects to support basic Instrumentation configuration on HP switches.')
hpicf_inst_base_compliance = module_compliance((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 45, 2, 2, 1)).setObjects(('HP-ICF-INST-MIB', 'hpicfInstBaseGroup'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hpicf_inst_base_compliance = hpicfInstBaseCompliance.setStatus('current')
if mibBuilder.loadTexts:
hpicfInstBaseCompliance.setDescription('The compliance statement for HP switches running Instrumentation and implementing the HP-ICF-INST MIB.')
mibBuilder.exportSymbols('HP-ICF-INST-MIB', hpicfInstIntervalIndex=hpicfInstIntervalIndex, hpicfInstEnable=hpicfInstEnable, hpicfInstBaseGroup=hpicfInstBaseGroup, hpicfInstCompliances=hpicfInstCompliances, hpicfInstParameterEntry=hpicfInstParameterEntry, hpicfInstConformance=hpicfInstConformance, hpicfInstParameterName=hpicfInstParameterName, hpicfInstBaseCompliance=hpicfInstBaseCompliance, hpicfInstInterfaceIndex=hpicfInstInterfaceIndex, hpicfInstParamValMax=hpicfInstParamValMax, hpicfInstParameterTable=hpicfInstParameterTable, hpicfInstGroups=hpicfInstGroups, hpicfInstObjects=hpicfInstObjects, hpicfInstMaxMemMB=hpicfInstMaxMemMB, hpicfInstParameterValue=hpicfInstParameterValue, hpicfInstIntervalName=hpicfInstIntervalName, PYSNMP_MODULE_ID=hpicfInstMIB, hpicfInstMIB=hpicfInstMIB, hpicfInstParamValMin=hpicfInstParamValMin, hpicfInstParameterIndex=hpicfInstParameterIndex) |
class Constants:
# Constants related to the core physics of the game
FIELD_LENGTH = 1800
FIELD_HEIGHT = 800
BALL_RADIUS = 8
NUM_PLAYERS = 5
GAME_LENGTH = 1800
GOAL_WIDTH = 20
MAX_BALL_VELOCITY = 10
MAX_PLAYER_VELOCITY = 5
NUM_PLAYERS = 5
PLAYER_RADIUS = 24
STARTING_POSITIONS = [[[200, 200], [200, 400], [500, 200], [500, 400], [800, 300]],
[[1600, 200], [1600, 400], [1300, 200], [1300, 400], [1000, 300]]]
| class Constants:
field_length = 1800
field_height = 800
ball_radius = 8
num_players = 5
game_length = 1800
goal_width = 20
max_ball_velocity = 10
max_player_velocity = 5
num_players = 5
player_radius = 24
starting_positions = [[[200, 200], [200, 400], [500, 200], [500, 400], [800, 300]], [[1600, 200], [1600, 400], [1300, 200], [1300, 400], [1000, 300]]] |
class Layer:
def __init__(self, name, parent):
self.name = name
self.parent = parent
self.children = []
def add_child(self, child):
self.children.append(child)
| class Layer:
def __init__(self, name, parent):
self.name = name
self.parent = parent
self.children = []
def add_child(self, child):
self.children.append(child) |
# Answer 1.
listy = [1,5,6,4,1,2,3,5]
sub_list = [1,1,5]
# print("Original List :" + str(listy))
# print("Original sub_list : " + str(sub_list))
flag = 0
# if(all(x in listy for x in sub_list)):
# flag = 1
if (set(sub_list).issubset(set(listy))):
flag = 1
if (flag):
print("It's a Match")
else:
print("It's Gone")
# Answer 2.
def checkPrimeNumbers(num):
# for num in range(2,2500):
count = 0
for i in range(2,num):
if num%i == 0:
count = 1
if (count == 0):
# print(num, "Prime no.")
return True
else:
return False
lst = list(range(1,2500))
isPrime = filter(checkPrimeNumbers, lst)
print("prime numbers between 1 - 2500:", list(isPrime))
# Answer 3)
def getCapitalize(*arg):
for word in arg:
string = word.split(" ")
capitalized_list = [capital.capitalize() for capital in string]
words = (" ").join(capitalized_list)
print(words)
getCapitalize("hey this is sai","I am in mumbai","teaching is my passion") | listy = [1, 5, 6, 4, 1, 2, 3, 5]
sub_list = [1, 1, 5]
flag = 0
if set(sub_list).issubset(set(listy)):
flag = 1
if flag:
print("It's a Match")
else:
print("It's Gone")
def check_prime_numbers(num):
count = 0
for i in range(2, num):
if num % i == 0:
count = 1
if count == 0:
return True
else:
return False
lst = list(range(1, 2500))
is_prime = filter(checkPrimeNumbers, lst)
print('prime numbers between 1 - 2500:', list(isPrime))
def get_capitalize(*arg):
for word in arg:
string = word.split(' ')
capitalized_list = [capital.capitalize() for capital in string]
words = ' '.join(capitalized_list)
print(words)
get_capitalize('hey this is sai', 'I am in mumbai', 'teaching is my passion') |
def event_handler(obj, event):
if event == lv.EVENT.VALUE_CHANGED:
print("State: %s" % ("Checked" if obj.is_checked() else "Unchecked"))
cb = lv.cb(lv.scr_act())
cb.set_text("I agree to terms and conditions.")
cb.align(None, lv.ALIGN.CENTER, 0, 0)
cb.set_event_cb(event_handler) | def event_handler(obj, event):
if event == lv.EVENT.VALUE_CHANGED:
print('State: %s' % ('Checked' if obj.is_checked() else 'Unchecked'))
cb = lv.cb(lv.scr_act())
cb.set_text('I agree to terms and conditions.')
cb.align(None, lv.ALIGN.CENTER, 0, 0)
cb.set_event_cb(event_handler) |
K, X = map(int, input().split())
out_list = []
for i in range(X-(K-1), X+(K)):
out_list.append(str(i))
print(" ".join(out_list))
| (k, x) = map(int, input().split())
out_list = []
for i in range(X - (K - 1), X + K):
out_list.append(str(i))
print(' '.join(out_list)) |
class Solution:
def minimumEffort(self, tasks: List[List[int]]) -> int:
tasks.sort(key=lambda x: x[1]-x[0])
answer=0
for actual, req in tasks:
answer=max(answer+actual,req)
return answer | class Solution:
def minimum_effort(self, tasks: List[List[int]]) -> int:
tasks.sort(key=lambda x: x[1] - x[0])
answer = 0
for (actual, req) in tasks:
answer = max(answer + actual, req)
return answer |
class ParserMeta(type):
registry = {}
def __new__(cls, name, bases, ns):
result = type.__new__(cls, name, bases, ns)
if name != 'Parser':
domains = ns['domains']
for domain in domains:
cls.registry[domain] = result
return result
class UnknownParser:
@staticmethod
def normalize_url(url):
return url
@staticmethod
def get_title(url):
# TODO: load URL, extract <title> tag
return ''
def get_parser(domain):
return ParserMeta.registry.get(domain, UnknownParser)
class Parser(metaclass=ParserMeta):
pass
class YouTube(Parser):
domains = ['youtube.com', 'youtube.de']
@staticmethod
def normalize_url(url):
pass
@staticmethod
def get_title(url):
pass
class BandCamp(Parser):
domains = ['bandcamp.com']
@staticmethod
def normalize_url(url):
pass
@staticmethod
def get_title(url):
pass
if __name__ == '__main__':
print(get_parser('youtube.com'))
print(get_parser('bandcamp.com'))
print(get_parser('meine-band.de'))
| class Parsermeta(type):
registry = {}
def __new__(cls, name, bases, ns):
result = type.__new__(cls, name, bases, ns)
if name != 'Parser':
domains = ns['domains']
for domain in domains:
cls.registry[domain] = result
return result
class Unknownparser:
@staticmethod
def normalize_url(url):
return url
@staticmethod
def get_title(url):
return ''
def get_parser(domain):
return ParserMeta.registry.get(domain, UnknownParser)
class Parser(metaclass=ParserMeta):
pass
class Youtube(Parser):
domains = ['youtube.com', 'youtube.de']
@staticmethod
def normalize_url(url):
pass
@staticmethod
def get_title(url):
pass
class Bandcamp(Parser):
domains = ['bandcamp.com']
@staticmethod
def normalize_url(url):
pass
@staticmethod
def get_title(url):
pass
if __name__ == '__main__':
print(get_parser('youtube.com'))
print(get_parser('bandcamp.com'))
print(get_parser('meine-band.de')) |
# Trabajando con ciclos for
x = 1
y = 12
z = 2
print("Mi nombre es ")
for item in range(x, y, z):
print(f"@Mangusoft se repetira {item}")
# if item == 3:
# break
| x = 1
y = 12
z = 2
print('Mi nombre es ')
for item in range(x, y, z):
print(f'@Mangusoft se repetira {item}') |
class Symbol:
def __init__(
self, lexeme, type, category, value, scope, extends, implements, params
):
self.__lexeme__ = lexeme
self.__type__ = type
self.__category__ = category
self.__value__ = value
self.__scope__ = scope
self.__extends__ = extends
self.__implements__ = implements
self.__params__ = params
@property
def lexeme(self):
return self.__lexeme__
@lexeme.setter
def lexeme(self, lexeme):
self.__lexeme__ = lexeme
@property
def type(self):
return self.__type__
@type.setter
def type(self, type):
self.__type__ = type
@property
def category(self):
return self.__category__
@category.setter
def category(self, category):
self.__category__ = category
@property
def value(self):
return self.__value__
@value.setter
def value(self, value):
self.__value__ = value
@property
def scope(self):
return self.__scope__
@scope.setter
def scope(self, scope):
self.__scope__ = scope
@property
def extends(self):
return self.__extends__
@extends.setter
def extends(self, extends):
self.__extends__ = extends
@property
def implements(self):
return self.__implements__
@implements.setter
def implements(self, implements):
self.__implements__ = implements
@property
def params(self):
return self.__params__
@params.setter
def params(self, params):
self.__params__ = params
| class Symbol:
def __init__(self, lexeme, type, category, value, scope, extends, implements, params):
self.__lexeme__ = lexeme
self.__type__ = type
self.__category__ = category
self.__value__ = value
self.__scope__ = scope
self.__extends__ = extends
self.__implements__ = implements
self.__params__ = params
@property
def lexeme(self):
return self.__lexeme__
@lexeme.setter
def lexeme(self, lexeme):
self.__lexeme__ = lexeme
@property
def type(self):
return self.__type__
@type.setter
def type(self, type):
self.__type__ = type
@property
def category(self):
return self.__category__
@category.setter
def category(self, category):
self.__category__ = category
@property
def value(self):
return self.__value__
@value.setter
def value(self, value):
self.__value__ = value
@property
def scope(self):
return self.__scope__
@scope.setter
def scope(self, scope):
self.__scope__ = scope
@property
def extends(self):
return self.__extends__
@extends.setter
def extends(self, extends):
self.__extends__ = extends
@property
def implements(self):
return self.__implements__
@implements.setter
def implements(self, implements):
self.__implements__ = implements
@property
def params(self):
return self.__params__
@params.setter
def params(self, params):
self.__params__ = params |
# Implement a method tht accepts 3 integer values "a, b and c".
# The method should return True if a triangle can be built with the sides of given length and False in any other case.
# All triangles must have surface greater than 0 to be accepted
def is_triangle(a, b, c):
return True if a+b>c and a+c>b and c+b>a else False
| def is_triangle(a, b, c):
return True if a + b > c and a + c > b and (c + b > a) else False |
number1 = input("Please enter a number and press enter: ")
number2 = input("Please enter another nunber and press enter ")
number1 = int(number1)
number2 = int(number2)
print("number1 + number2 =", number1+number2)
| number1 = input('Please enter a number and press enter: ')
number2 = input('Please enter another nunber and press enter ')
number1 = int(number1)
number2 = int(number2)
print('number1 + number2 =', number1 + number2) |
def solution(A, K):
shift = K % len(A)
if shift == 0:
return A
shifted_array = []
for i in range(-shift, len(A) - shift):
shifted_array.append(A[i])
return shifted_array
| def solution(A, K):
shift = K % len(A)
if shift == 0:
return A
shifted_array = []
for i in range(-shift, len(A) - shift):
shifted_array.append(A[i])
return shifted_array |
s = list(input())
a = "".join(s[:5])
b = "".join(s[6:13])
c = "".join(s[14:21])
print(a,b,c) | s = list(input())
a = ''.join(s[:5])
b = ''.join(s[6:13])
c = ''.join(s[14:21])
print(a, b, c) |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"Helpers": "Helpers.ipynb",
"notify": "Helpers.ipynb",
"keys": "Helpers.ipynb",
"scanDb": "Helpers.ipynb",
"toDf": "Helpers.ipynb",
"fromSeries": "Helpers.ipynb",
"fromDf": "Helpers.ipynb",
"fromDict": "Helpers.ipynb",
"toListDict": "Helpers.ipynb",
"toSeries": "Helpers.ipynb",
"setNoUpdate": "Helpers.ipynb",
"setUpdate": "Helpers.ipynb",
"DATABASE_TABLE_NAME": "database.ipynb",
"INVENTORY_BUCKET_NAME": "database.ipynb",
"INPUT_BUCKET_NAME": "database.ipynb",
"REGION": "database.ipynb",
"ACCESS_KEY_ID": "database.ipynb",
"SECRET_ACCESS_KEY": "database.ipynb",
"LINEKEY": "database.ipynb",
"createIndex": "KeySchema.ipynb",
"KeySchema": "KeySchema.ipynb",
"DBHASHLOCATION": "database.ipynb",
"DBCACHELOCATION": "database.ipynb",
"ALLDATAKEY": "S3.ipynb",
"DEFAULTKEYS": "S3.ipynb",
"S3Cache": "S3.ipynb",
"loadFromCache": "S3.ipynb",
"saveRemoteCache": "S3.ipynb",
"resetS3Cache": "S3.ipynb",
"BRANCH": "database.ipynb",
"VALUEUPDATESCHEMAURL": "Update.ipynb",
"Updater": "Update.ipynb",
"updateWithDict": "Update.ipynb",
"ValueUpdate2": "Update.ipynb",
"saveBatchToDynamodb": "Update.ipynb",
"saveBatchToDynamodb2": "Update.ipynb",
"valueUpdate2": "Update.ipynb",
"INTCOLS": "database.ipynb",
"ECOMMERCE_COL_LIST": "database.ipynb",
"ProductDatabase": "database.ipynb",
"cacheDb": "database.ipynb",
"lambdaDumpToS3": "database.ipynb",
"lambdaDumpOnlineS3": "database.ipynb",
"Product": "database.ipynb",
"ValueUpdate": "database.ipynb",
"chunks": "database.ipynb",
"lambdaUpdateProduct": "database.ipynb",
"updateS3Input": "database.ipynb",
"lambdaUpdateS3": "database.ipynb",
"ProductsFromList": "query.ipynb",
"lambdaProductsFromList": "database.ipynb",
"lambdaSingleQuery": "database.ipynb",
"lambdaAllQuery": "database.ipynb",
"lambdaAllQueryFeather": "database.ipynb",
"Querier": "query.ipynb",
"allQuery": "query.ipynb",
"productsFromList": "query.ipynb",
"singleProductQuery": "query.ipynb"}
modules = ["helpers.py",
"schema.py",
"s3.py",
"update.py",
"database.py",
"query.py"]
doc_url = "https://thanakijwanavit.github.io/villaProductDatabase/"
git_url = "https://github.com/thanakijwanavit/villaProductDatabase/tree/master/"
def custom_doc_links(name): return None
| __all__ = ['index', 'modules', 'custom_doc_links', 'git_url']
index = {'Helpers': 'Helpers.ipynb', 'notify': 'Helpers.ipynb', 'keys': 'Helpers.ipynb', 'scanDb': 'Helpers.ipynb', 'toDf': 'Helpers.ipynb', 'fromSeries': 'Helpers.ipynb', 'fromDf': 'Helpers.ipynb', 'fromDict': 'Helpers.ipynb', 'toListDict': 'Helpers.ipynb', 'toSeries': 'Helpers.ipynb', 'setNoUpdate': 'Helpers.ipynb', 'setUpdate': 'Helpers.ipynb', 'DATABASE_TABLE_NAME': 'database.ipynb', 'INVENTORY_BUCKET_NAME': 'database.ipynb', 'INPUT_BUCKET_NAME': 'database.ipynb', 'REGION': 'database.ipynb', 'ACCESS_KEY_ID': 'database.ipynb', 'SECRET_ACCESS_KEY': 'database.ipynb', 'LINEKEY': 'database.ipynb', 'createIndex': 'KeySchema.ipynb', 'KeySchema': 'KeySchema.ipynb', 'DBHASHLOCATION': 'database.ipynb', 'DBCACHELOCATION': 'database.ipynb', 'ALLDATAKEY': 'S3.ipynb', 'DEFAULTKEYS': 'S3.ipynb', 'S3Cache': 'S3.ipynb', 'loadFromCache': 'S3.ipynb', 'saveRemoteCache': 'S3.ipynb', 'resetS3Cache': 'S3.ipynb', 'BRANCH': 'database.ipynb', 'VALUEUPDATESCHEMAURL': 'Update.ipynb', 'Updater': 'Update.ipynb', 'updateWithDict': 'Update.ipynb', 'ValueUpdate2': 'Update.ipynb', 'saveBatchToDynamodb': 'Update.ipynb', 'saveBatchToDynamodb2': 'Update.ipynb', 'valueUpdate2': 'Update.ipynb', 'INTCOLS': 'database.ipynb', 'ECOMMERCE_COL_LIST': 'database.ipynb', 'ProductDatabase': 'database.ipynb', 'cacheDb': 'database.ipynb', 'lambdaDumpToS3': 'database.ipynb', 'lambdaDumpOnlineS3': 'database.ipynb', 'Product': 'database.ipynb', 'ValueUpdate': 'database.ipynb', 'chunks': 'database.ipynb', 'lambdaUpdateProduct': 'database.ipynb', 'updateS3Input': 'database.ipynb', 'lambdaUpdateS3': 'database.ipynb', 'ProductsFromList': 'query.ipynb', 'lambdaProductsFromList': 'database.ipynb', 'lambdaSingleQuery': 'database.ipynb', 'lambdaAllQuery': 'database.ipynb', 'lambdaAllQueryFeather': 'database.ipynb', 'Querier': 'query.ipynb', 'allQuery': 'query.ipynb', 'productsFromList': 'query.ipynb', 'singleProductQuery': 'query.ipynb'}
modules = ['helpers.py', 'schema.py', 's3.py', 'update.py', 'database.py', 'query.py']
doc_url = 'https://thanakijwanavit.github.io/villaProductDatabase/'
git_url = 'https://github.com/thanakijwanavit/villaProductDatabase/tree/master/'
def custom_doc_links(name):
return None |
def Contract_scalar_2x5(\
t0_6,t1_6,t2_6,t3_6,\
t0_5,t1_5,t2_5,t3_5,\
t0_4,t1_4,t2_4,t3_4,\
t0_3,t1_3,t2_3,t3_3,\
t0_2,t1_2,t2_2,t3_2,\
t0_1,t1_1,t2_1,t3_1,\
t0_0,t1_0,t2_0,t3_0,\
o1_5,o2_5,\
o1_4,o2_4,\
o1_3,o2_3,\
o1_2,o2_2,\
o1_1,o2_1\
):
##############################
# ./input/input_Lx2Ly5.dat
##############################
# (o1_2*(t1_2*((t0_2*((t1_1*((t1_1.conj()*o1_1)*(t1_0*(t0_0*t0_1))))*(t2_1*((o2_1*t2_1.conj())*(t2_0*(t3_0*t3_1))))))*(t1_2.conj()*(t2_2.conj()*((o2_2*t2_2)*(t3_2*(t0_3*(t1_3.conj()*((t1_3*o1_3)*(t2_3*((t2_3.conj()*o2_3)*(t3_3*(t0_4*(t1_4*((t1_4.conj()*o1_4)*(t2_4*((t2_4.conj()*o2_4)*(t3_4*((t2_5*((o2_5*t2_5.conj())*(t2_6*(t3_6*t3_5))))*(t1_5.conj()*((o1_5*t1_5)*(t0_5*(t0_6*t1_6))))))))))))))))))))))))
# cpu_cost= 3.22004e+13 memory= 4.00042e+10
# final_bond_order ()
##############################
return np.tensordot(
o1_2, np.tensordot(
t1_2, np.tensordot(
np.tensordot(
t0_2, np.tensordot(
np.tensordot(
t1_1, np.tensordot(
np.tensordot(
t1_1.conj(), o1_1, ([4], [1])
), np.tensordot(
t1_0, np.tensordot(
t0_0, t0_1, ([1], [0])
), ([1], [0])
), ([0, 3], [5, 2])
), ([0, 3, 4], [6, 4, 2])
), np.tensordot(
t2_1, np.tensordot(
np.tensordot(
o2_1, t2_1.conj(), ([1], [4])
), np.tensordot(
t2_0, np.tensordot(
t3_0, t3_1, ([0], [1])
), ([0], [0])
), ([3, 4], [5, 2])
), ([2, 3, 4], [6, 4, 0])
), ([1, 3, 4], [0, 2, 4])
), ([0], [2])
), np.tensordot(
t1_2.conj(), np.tensordot(
t2_2.conj(), np.tensordot(
np.tensordot(
o2_2, t2_2, ([0], [4])
), np.tensordot(
t3_2, np.tensordot(
t0_3, np.tensordot(
t1_3.conj(), np.tensordot(
np.tensordot(
t1_3, o1_3, ([4], [0])
), np.tensordot(
t2_3, np.tensordot(
np.tensordot(
t2_3.conj(), o2_3, ([4], [1])
), np.tensordot(
t3_3, np.tensordot(
t0_4, np.tensordot(
t1_4, np.tensordot(
np.tensordot(
t1_4.conj(), o1_4, ([4], [1])
), np.tensordot(
t2_4, np.tensordot(
np.tensordot(
t2_4.conj(), o2_4, ([4], [1])
), np.tensordot(
t3_4, np.tensordot(
np.tensordot(
t2_5, np.tensordot(
np.tensordot(
o2_5, t2_5.conj(), ([1], [4])
), np.tensordot(
t2_6, np.tensordot(
t3_6, t3_5, ([1], [0])
), ([1], [0])
), ([2, 3], [2, 5])
), ([1, 2, 4], [4, 6, 0])
), np.tensordot(
t1_5.conj(), np.tensordot(
np.tensordot(
o1_5, t1_5, ([0], [4])
), np.tensordot(
t0_5, np.tensordot(
t0_6, t1_6, ([1], [0])
), ([1], [0])
), ([1, 2], [1, 4])
), ([0, 1, 4], [4, 6, 0])
), ([0, 2, 4], [2, 0, 5])
), ([0], [2])
), ([1, 2], [4, 2])
), ([1, 2, 4], [5, 4, 2])
), ([1, 2], [5, 2])
), ([1, 2, 4], [7, 3, 2])
), ([1, 2, 3], [7, 0, 2])
), ([0], [5])
), ([1, 2], [7, 2])
), ([1, 2, 4], [8, 4, 2])
), ([1, 2], [6, 0])
), ([1, 2, 4], [8, 4, 2])
), ([1, 2, 3], [7, 2, 0])
), ([0], [5])
), ([2, 3], [6, 1])
), ([1, 2, 4], [8, 4, 0])
), ([1, 2], [6, 0])
), ([0, 2, 4, 5, 6, 7], [7, 0, 1, 5, 3, 6])
), ([0, 1, 2, 3], [0, 4, 3, 1])
), ([0, 1], [0, 1])
)
| def contract_scalar_2x5(t0_6, t1_6, t2_6, t3_6, t0_5, t1_5, t2_5, t3_5, t0_4, t1_4, t2_4, t3_4, t0_3, t1_3, t2_3, t3_3, t0_2, t1_2, t2_2, t3_2, t0_1, t1_1, t2_1, t3_1, t0_0, t1_0, t2_0, t3_0, o1_5, o2_5, o1_4, o2_4, o1_3, o2_3, o1_2, o2_2, o1_1, o2_1):
return np.tensordot(o1_2, np.tensordot(t1_2, np.tensordot(np.tensordot(t0_2, np.tensordot(np.tensordot(t1_1, np.tensordot(np.tensordot(t1_1.conj(), o1_1, ([4], [1])), np.tensordot(t1_0, np.tensordot(t0_0, t0_1, ([1], [0])), ([1], [0])), ([0, 3], [5, 2])), ([0, 3, 4], [6, 4, 2])), np.tensordot(t2_1, np.tensordot(np.tensordot(o2_1, t2_1.conj(), ([1], [4])), np.tensordot(t2_0, np.tensordot(t3_0, t3_1, ([0], [1])), ([0], [0])), ([3, 4], [5, 2])), ([2, 3, 4], [6, 4, 0])), ([1, 3, 4], [0, 2, 4])), ([0], [2])), np.tensordot(t1_2.conj(), np.tensordot(t2_2.conj(), np.tensordot(np.tensordot(o2_2, t2_2, ([0], [4])), np.tensordot(t3_2, np.tensordot(t0_3, np.tensordot(t1_3.conj(), np.tensordot(np.tensordot(t1_3, o1_3, ([4], [0])), np.tensordot(t2_3, np.tensordot(np.tensordot(t2_3.conj(), o2_3, ([4], [1])), np.tensordot(t3_3, np.tensordot(t0_4, np.tensordot(t1_4, np.tensordot(np.tensordot(t1_4.conj(), o1_4, ([4], [1])), np.tensordot(t2_4, np.tensordot(np.tensordot(t2_4.conj(), o2_4, ([4], [1])), np.tensordot(t3_4, np.tensordot(np.tensordot(t2_5, np.tensordot(np.tensordot(o2_5, t2_5.conj(), ([1], [4])), np.tensordot(t2_6, np.tensordot(t3_6, t3_5, ([1], [0])), ([1], [0])), ([2, 3], [2, 5])), ([1, 2, 4], [4, 6, 0])), np.tensordot(t1_5.conj(), np.tensordot(np.tensordot(o1_5, t1_5, ([0], [4])), np.tensordot(t0_5, np.tensordot(t0_6, t1_6, ([1], [0])), ([1], [0])), ([1, 2], [1, 4])), ([0, 1, 4], [4, 6, 0])), ([0, 2, 4], [2, 0, 5])), ([0], [2])), ([1, 2], [4, 2])), ([1, 2, 4], [5, 4, 2])), ([1, 2], [5, 2])), ([1, 2, 4], [7, 3, 2])), ([1, 2, 3], [7, 0, 2])), ([0], [5])), ([1, 2], [7, 2])), ([1, 2, 4], [8, 4, 2])), ([1, 2], [6, 0])), ([1, 2, 4], [8, 4, 2])), ([1, 2, 3], [7, 2, 0])), ([0], [5])), ([2, 3], [6, 1])), ([1, 2, 4], [8, 4, 0])), ([1, 2], [6, 0])), ([0, 2, 4, 5, 6, 7], [7, 0, 1, 5, 3, 6])), ([0, 1, 2, 3], [0, 4, 3, 1])), ([0, 1], [0, 1])) |
class TreeNode(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
# store the number of left child for each tree Node
self.num_of_left = 0
# store the max height difference
self.max_diff = float('-inf')
self.max_diff_node = None | class Treenode(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
self.num_of_left = 0
self.max_diff = float('-inf')
self.max_diff_node = None |
class Config(object):
VERSION = "0.1.1"
TEMPLATES_PATH = "config/"
HEADERS = "headers.template"
MAIL_FROM = "notify@example.com"
MAIL_TO = "root@example.org"
SUBJECT = "Mail from mailer.py\n\n"
TEMPLATE = "default.message"
| class Config(object):
version = '0.1.1'
templates_path = 'config/'
headers = 'headers.template'
mail_from = 'notify@example.com'
mail_to = 'root@example.org'
subject = 'Mail from mailer.py\n\n'
template = 'default.message' |
'''
Write a program which takes an array of n integers,
where A[i] denotes the maximum you can advance from
index l, and returns whether it is possible to advance
to the last index starting from the beginning of the array.
'''
def can_reach_end(array): # Time: O(n) | Space: O(1)
furthest_reached = 0
last_index = len(array) - 1
i = 0
while i <= furthest_reached and furthest_reached < last_index:
furthest_reached = max(furthest_reached, array[i] + i)
i += 1
return furthest_reached
assert(can_reach_end([3, 3, 1, 0, 2, 0, 1]) == 6)
assert(can_reach_end([3, 2, 0, 0, 2, 0, 1]) == 3)
assert(can_reach_end([3, 2, -1, 0, 2, 0, 1]) == 3)
| """
Write a program which takes an array of n integers,
where A[i] denotes the maximum you can advance from
index l, and returns whether it is possible to advance
to the last index starting from the beginning of the array.
"""
def can_reach_end(array):
furthest_reached = 0
last_index = len(array) - 1
i = 0
while i <= furthest_reached and furthest_reached < last_index:
furthest_reached = max(furthest_reached, array[i] + i)
i += 1
return furthest_reached
assert can_reach_end([3, 3, 1, 0, 2, 0, 1]) == 6
assert can_reach_end([3, 2, 0, 0, 2, 0, 1]) == 3
assert can_reach_end([3, 2, -1, 0, 2, 0, 1]) == 3 |
def pubkeys(obj):
keys = list()
for key in (key for key in dir(obj) if not key.startswith('_')):
keys.append(key)
return keys
| def pubkeys(obj):
keys = list()
for key in (key for key in dir(obj) if not key.startswith('_')):
keys.append(key)
return keys |
num_queries = int(input())
def executeQuery(num_queries):
stack = list()
string = ""
k = 0
for i in range(num_queries):
q = input().split()
if(q[0] == '4'):
string = stack.pop()
elif(q[0] == '1'):
stack.append(string)
string += q[1]
elif(q[0] == '2'):
str_len = len(string)
stack.append(string)
k = int(q[1])
if(str_len == k):
string = ""
else:
string = string[0:str_len - k]
else:
print(string[int(q[1]) - 1])
executeQuery(num_queries) | num_queries = int(input())
def execute_query(num_queries):
stack = list()
string = ''
k = 0
for i in range(num_queries):
q = input().split()
if q[0] == '4':
string = stack.pop()
elif q[0] == '1':
stack.append(string)
string += q[1]
elif q[0] == '2':
str_len = len(string)
stack.append(string)
k = int(q[1])
if str_len == k:
string = ''
else:
string = string[0:str_len - k]
else:
print(string[int(q[1]) - 1])
execute_query(num_queries) |
ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
with open("p022_names.txt") as f:
names = f.read().split(",")
names = [x.replace("\"", "") for x in names]
names.sort()
total = 0
for i, name in enumerate(names):
score = 0
for letter in name:
score += ALPHABET.index(letter) + 1
total += (i + 1) * score
print(total)
| alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
with open('p022_names.txt') as f:
names = f.read().split(',')
names = [x.replace('"', '') for x in names]
names.sort()
total = 0
for (i, name) in enumerate(names):
score = 0
for letter in name:
score += ALPHABET.index(letter) + 1
total += (i + 1) * score
print(total) |
# data = [1,2,3,4,5,6,7]
data = [2,1,4,6,7,5,3,9,10,8]
print(data)
def heap_min(data):
length = len(data)
for i in range(length-1,-1, -1):
if data[i] < data[i//2]:
data[i],data[i//2] = data[i//2],data[i]
return data
def sort(data):
ll = []
length = len(data)
for i in range(0,length):
data = heap_min(data[:])
ll.append(data[0])
del data[0]
print(data)
return ll
data = sort(data)
print(data)
| data = [2, 1, 4, 6, 7, 5, 3, 9, 10, 8]
print(data)
def heap_min(data):
length = len(data)
for i in range(length - 1, -1, -1):
if data[i] < data[i // 2]:
(data[i], data[i // 2]) = (data[i // 2], data[i])
return data
def sort(data):
ll = []
length = len(data)
for i in range(0, length):
data = heap_min(data[:])
ll.append(data[0])
del data[0]
print(data)
return ll
data = sort(data)
print(data) |
#Intersection: Given two (singly) linked lists, determine if the two lists intersect.
#Return the intersecting node. Note that the intersection is defined based on reference,
#not value. That is, if the kth node of the first linked list is the exact same node (by
#reference) as the jth node of the second linked list, then they are intersecting
#in Python i can compare objects its the same? A: yes
#Since i got classes i can pass the var by "reference" cause it will be the object
#The only way its possible is if the second linked list is at the end of the first one
# i.e 1->2->3->4->5->6 && 4->5->6 i cannot have and intersecting linked list in the middle
#of the other one cause then it wont point to the same next object and so on
#asuming that i could just traverse it until i find the first node
class LinkedList:
def __init__(self,value):
self.next=None
self.value=value
def add(self,value):
head = self
while head.next != None:
head = head.next
head.next= LinkedList(value)
def push(self,value):
new_head=LinkedList(value)
new_head.next=self
return new_head
def print(self):
head = self
while head.next != None:
print(head.value, end = '')
head = head.next
print(head.value)
def intersection(l1,l2): #O(n)
while l1:
if l1 == l2: # worst caseO(n)
return l1
l1=l1.next
return None
l = LinkedList(2)
l.add(3)
l.add(2)
l.add(1)
l.add(2)
l.add(5)
l.add(3)
l.add(7)
l.print() # 23212537
print(intersection(l,l.next.next.next).value) #1
l2 = LinkedList(2)
l2.add(3)
l2.add(2)
l2.add(1)
l2.add(2)
l2.add(5)
l2.add(3)
l2.add(7)
print(intersection(l,l2))#None
# Since i thought it was really easy i read some hints so i have to check if either l1
#intersects l2 or l2 intersects l1
def intersection2(l1,l2): #O(n+m)
l1cp=l1
while l1:
if l1 == l2: # worst case O(n)
return l1
l1=l1.next
while l2:
if l1cp ==l2: # worst case O(m)
return l2
l2=l2.next
return None
print(intersection2(l.next.next.next,l).value)#1
print(intersection2(l2,l))#None
print(intersection(l.next.next.next,l)) #None | class Linkedlist:
def __init__(self, value):
self.next = None
self.value = value
def add(self, value):
head = self
while head.next != None:
head = head.next
head.next = linked_list(value)
def push(self, value):
new_head = linked_list(value)
new_head.next = self
return new_head
def print(self):
head = self
while head.next != None:
print(head.value, end='')
head = head.next
print(head.value)
def intersection(l1, l2):
while l1:
if l1 == l2:
return l1
l1 = l1.next
return None
l = linked_list(2)
l.add(3)
l.add(2)
l.add(1)
l.add(2)
l.add(5)
l.add(3)
l.add(7)
l.print()
print(intersection(l, l.next.next.next).value)
l2 = linked_list(2)
l2.add(3)
l2.add(2)
l2.add(1)
l2.add(2)
l2.add(5)
l2.add(3)
l2.add(7)
print(intersection(l, l2))
def intersection2(l1, l2):
l1cp = l1
while l1:
if l1 == l2:
return l1
l1 = l1.next
while l2:
if l1cp == l2:
return l2
l2 = l2.next
return None
print(intersection2(l.next.next.next, l).value)
print(intersection2(l2, l))
print(intersection(l.next.next.next, l)) |
def factorial(a):
if a == 1:
return 1
else:
return (a * factorial(a-1))
num = 7
print("The factorial of", num, "is", factorial(num))
| def factorial(a):
if a == 1:
return 1
else:
return a * factorial(a - 1)
num = 7
print('The factorial of', num, 'is', factorial(num)) |
batch = [[1, 5, 6, 2], # shape (8,4)
[3, 2, 1, 3],
[5, 2, 1, 2],
[6, 4, 8, 4],
[2, 8, 5, 3],
[1, 1, 9, 4],
[6, 6, 0, 4],
[8, 7, 6, 4]]
# https://nnfs.io/lqw
# https://nnfs.io/vyu
# https://nnfs.io/jei
# https://nnfs.io/bkw
| batch = [[1, 5, 6, 2], [3, 2, 1, 3], [5, 2, 1, 2], [6, 4, 8, 4], [2, 8, 5, 3], [1, 1, 9, 4], [6, 6, 0, 4], [8, 7, 6, 4]] |
class Messenger(object):
def __init__(self, logger, messageDisplay):
self.logger = logger
self.messageDisplay = messageDisplay
#Test this...
def sendMessage(self, message):
self.logger.info(message)
def sendUpdate(self, message):
# this should update the button text -- probably does not belong on this object
self.logger.info(message)
def showSaveAndExit(self):
return self.messageDisplay.askquestion(
'Save And Quit', 'Would you like to save your changes?')
def showCardIsNotPaired(self):
self.messageDisplay.showinfo(
'Card Unassigned', 'Card is not currently assigned to a video')
def showCannotPairToInactiveVideos(self):
self.messageDisplay.showinfo('Video Is Not Active',
'This video\'s file wasn\'t found on the last scan. Please rescan, and pair again.')
def showCardScannedIsAKiller(self):
self.messageDisplay.showinfo(
'Kill Card', 'This card is currently assigned to kill the application.')
def showDefaultDeviceWarning(self):
self.messageDisplay.showwarning(
'No USB Set', 'Please select a USB as a source device and then perform a Scan and Update')
self.logger.warning('No USB device is set!')
def displayScanError(self, e):
self.messageDisplay.showerror('Error Occurred', 'Error: ' + str(e))
self.logger.error('Scan Failed: ' + str(e))
def showAbortScanMessage(self):
self.messageDisplay.showwarning(
'No Files Found', 'A scan failed to find any files.')
self.logger.warning('Empty Scan occurred when attempting a merge')
def showScanErrorMessage(self, e):
self.messageDisplay.showerror('Scan Failed', 'Scan error: ' + str(e))
self.logger.error(str(e))
# def showCurrentDeviceNotFoundWarning(self):
# self.messageDisplay.showwarning(
# 'Missing USB Source', 'WARNING: The current USB repository was not found among the available devices.')
# self.logger.warning(
# 'Current USB repository was not located in device scan!')
# def terminateWithCurrentDeviceNotFoundMsg(self):
# self.messageDisplay.showerror(
# 'No Devices Detected', 'No devices were detected including the current USB repository.\nPlease inspect USB device, or contact help.')
# self.logger.critical('Scanner detected no devices. Closing...')
# SUGGEST - Removal
# def terminateWithNoDeviceFailureMessage(self):
# self.messageDisplay.showerror(
# 'Storage Failure', 'No USB devices could be found, this editor will now close.')
# self.logger.critical('Failed to find any devices with any media. Closing...')
# SUGGEST - Removal
# def showImproperStorageWarning(self):
# self.messageDisplay.showerror(
# 'Improper Storage', 'Media files should not be stored in /media/pi.\nPlease move files to subfolder, or a USB device.')
# self.logger.error(
# 'User error: Files were stored on pi media root. Requested User Action...')
| class Messenger(object):
def __init__(self, logger, messageDisplay):
self.logger = logger
self.messageDisplay = messageDisplay
def send_message(self, message):
self.logger.info(message)
def send_update(self, message):
self.logger.info(message)
def show_save_and_exit(self):
return self.messageDisplay.askquestion('Save And Quit', 'Would you like to save your changes?')
def show_card_is_not_paired(self):
self.messageDisplay.showinfo('Card Unassigned', 'Card is not currently assigned to a video')
def show_cannot_pair_to_inactive_videos(self):
self.messageDisplay.showinfo('Video Is Not Active', "This video's file wasn't found on the last scan. Please rescan, and pair again.")
def show_card_scanned_is_a_killer(self):
self.messageDisplay.showinfo('Kill Card', 'This card is currently assigned to kill the application.')
def show_default_device_warning(self):
self.messageDisplay.showwarning('No USB Set', 'Please select a USB as a source device and then perform a Scan and Update')
self.logger.warning('No USB device is set!')
def display_scan_error(self, e):
self.messageDisplay.showerror('Error Occurred', 'Error: ' + str(e))
self.logger.error('Scan Failed: ' + str(e))
def show_abort_scan_message(self):
self.messageDisplay.showwarning('No Files Found', 'A scan failed to find any files.')
self.logger.warning('Empty Scan occurred when attempting a merge')
def show_scan_error_message(self, e):
self.messageDisplay.showerror('Scan Failed', 'Scan error: ' + str(e))
self.logger.error(str(e)) |
def welcome():
print("welcome to pyMassSpecTools")
def cli():
welcome()
| def welcome():
print('welcome to pyMassSpecTools')
def cli():
welcome() |
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
print(bcolors.OKBLUE + bcolors.BOLD + "Hello I am you calculator" + bcolors.ENDC)
button_first = input(bcolors.OKBLUE + bcolors.BOLD + "Type First Number: " + bcolors.ENDC)
print(bcolors.OKBLUE + bcolors.BOLD + "You chose " + button_first + bcolors.ENDC)
button_second = input(bcolors.OKBLUE + bcolors.BOLD + "Type Second Number: " + bcolors.ENDC)
print(bcolors.OKBLUE + bcolors.BOLD + "You chose " + button_second + bcolors.ENDC)
button_third = input(bcolors.OKBLUE + bcolors.BOLD + "Type + - * or /: " + bcolors.ENDC)
print(bcolors.OKBLUE + bcolors.BOLD + "You chose " + button_third + bcolors.ENDC)
if button_third == "+":
number1 = int(button_first) + int(button_second)
print(bcolors.OKBLUE + bcolors.BOLD + "You got: " + str(number1) + bcolors.ENDC)
elif button_third == "-":
number2 = int(button_first) - int(button_second)
print(bcolors.OKBLUE + bcolors.BOLD + "You got: " + str(number2) + bcolors.ENDC)
elif button_third == "*":
number3 = int(button_first) * int(button_second)
print(bcolors.OKBLUE + bcolors.BOLD + "You got: " + str(number3) + bcolors.ENDC)
elif button_third == "/":
number4 = int(button_first) / int(button_second)
print(bcolors.OKBLUE + bcolors.BOLD + "You got: " + str(number4) + bcolors.ENDC) | class Bcolors:
header = '\x1b[95m'
okblue = '\x1b[94m'
okcyan = '\x1b[96m'
okgreen = '\x1b[92m'
warning = '\x1b[93m'
fail = '\x1b[91m'
endc = '\x1b[0m'
bold = '\x1b[1m'
underline = '\x1b[4m'
print(bcolors.OKBLUE + bcolors.BOLD + 'Hello I am you calculator' + bcolors.ENDC)
button_first = input(bcolors.OKBLUE + bcolors.BOLD + 'Type First Number: ' + bcolors.ENDC)
print(bcolors.OKBLUE + bcolors.BOLD + 'You chose ' + button_first + bcolors.ENDC)
button_second = input(bcolors.OKBLUE + bcolors.BOLD + 'Type Second Number: ' + bcolors.ENDC)
print(bcolors.OKBLUE + bcolors.BOLD + 'You chose ' + button_second + bcolors.ENDC)
button_third = input(bcolors.OKBLUE + bcolors.BOLD + 'Type + - * or /: ' + bcolors.ENDC)
print(bcolors.OKBLUE + bcolors.BOLD + 'You chose ' + button_third + bcolors.ENDC)
if button_third == '+':
number1 = int(button_first) + int(button_second)
print(bcolors.OKBLUE + bcolors.BOLD + 'You got: ' + str(number1) + bcolors.ENDC)
elif button_third == '-':
number2 = int(button_first) - int(button_second)
print(bcolors.OKBLUE + bcolors.BOLD + 'You got: ' + str(number2) + bcolors.ENDC)
elif button_third == '*':
number3 = int(button_first) * int(button_second)
print(bcolors.OKBLUE + bcolors.BOLD + 'You got: ' + str(number3) + bcolors.ENDC)
elif button_third == '/':
number4 = int(button_first) / int(button_second)
print(bcolors.OKBLUE + bcolors.BOLD + 'You got: ' + str(number4) + bcolors.ENDC) |
'''
Created on 2014-11-30
@author: ouyangsiqi
'''
class Card:
'''
This class is the parking card
'''
__cardId = 0
__levelId = 0
__spaceId = 0
def __init__(self, cardId, levelId, spaceId):
'''
Constructor
'''
self.__cardId = cardId
self.__levelId = levelId
self.__spaceId = spaceId
def getCardId(self):
'''
The method to get the card id
'''
return self.__cardId
def getLevelId(self):
'''
The method to get the level id
'''
return self.__levelId
def getSpaceId(self):
'''
The method to get the space id
'''
return self.__spaceId
| """
Created on 2014-11-30
@author: ouyangsiqi
"""
class Card:
"""
This class is the parking card
"""
__card_id = 0
__level_id = 0
__space_id = 0
def __init__(self, cardId, levelId, spaceId):
"""
Constructor
"""
self.__cardId = cardId
self.__levelId = levelId
self.__spaceId = spaceId
def get_card_id(self):
"""
The method to get the card id
"""
return self.__cardId
def get_level_id(self):
"""
The method to get the level id
"""
return self.__levelId
def get_space_id(self):
"""
The method to get the space id
"""
return self.__spaceId |
ENTRY_POINT = 'right_angle_triangle'
#[PROMPT]
def right_angle_triangle(a, b, c):
'''
Given the lengths of the three sides of a triangle. Return True if the three
sides form a right-angled triangle, False otherwise.
A right-angled triangle is a triangle in which one angle is right angle or
90 degree.
Example:
right_angle_triangle(3, 4, 5) == True
right_angle_triangle(1, 2, 3) == False
'''
#[SOLUTION]
return a*a == b*b + c*c or b*b == a*a + c*c or c*c == a*a + b*b
#[CHECK]
def check(candidate):
# Check some simple cases
assert candidate(3, 4, 5) == True, "This prints if this assert fails 1 (good for debugging!)"
assert candidate(1, 2, 3) == False
assert candidate(10, 6, 8) == True
assert candidate(2, 2, 2) == False
assert candidate(7, 24, 25) == True
assert candidate(10, 5, 7) == False
assert candidate(5, 12, 13) == True
assert candidate(15, 8, 17) == True
assert candidate(48, 55, 73) == True
# Check some edge cases that are easy to work out by hand.
assert candidate(1, 1, 1) == False, "This prints if this assert fails 2 (also good for debugging!)"
assert candidate(2, 2, 10) == False
| entry_point = 'right_angle_triangle'
def right_angle_triangle(a, b, c):
"""
Given the lengths of the three sides of a triangle. Return True if the three
sides form a right-angled triangle, False otherwise.
A right-angled triangle is a triangle in which one angle is right angle or
90 degree.
Example:
right_angle_triangle(3, 4, 5) == True
right_angle_triangle(1, 2, 3) == False
"""
return a * a == b * b + c * c or b * b == a * a + c * c or c * c == a * a + b * b
def check(candidate):
assert candidate(3, 4, 5) == True, 'This prints if this assert fails 1 (good for debugging!)'
assert candidate(1, 2, 3) == False
assert candidate(10, 6, 8) == True
assert candidate(2, 2, 2) == False
assert candidate(7, 24, 25) == True
assert candidate(10, 5, 7) == False
assert candidate(5, 12, 13) == True
assert candidate(15, 8, 17) == True
assert candidate(48, 55, 73) == True
assert candidate(1, 1, 1) == False, 'This prints if this assert fails 2 (also good for debugging!)'
assert candidate(2, 2, 10) == False |
#!/usr/bin/env python
# To run the script put 'python ./script.py' in terminal
lines = [line.rstrip('\n') for line in open('sv_en.txt')]
svArray = []
enArray = []
for s in lines:
first,second = s.split(' = ')
svArray.append( first );
enArray.append( second );
thefile = open('en.txt', 'w')
for item in enArray:
print>>thefile, item+" = "
thefile.close()
thefile = open('sv.txt', 'w')
for item in svArray:
print>>thefile, item
thefile.close()
thefile = open('sv_en_backup', 'w')
for item in lines:
print>>thefile, item
thefile.close()
| lines = [line.rstrip('\n') for line in open('sv_en.txt')]
sv_array = []
en_array = []
for s in lines:
(first, second) = s.split(' = ')
svArray.append(first)
enArray.append(second)
thefile = open('en.txt', 'w')
for item in enArray:
(print >> thefile, item + ' = ')
thefile.close()
thefile = open('sv.txt', 'w')
for item in svArray:
(print >> thefile, item)
thefile.close()
thefile = open('sv_en_backup', 'w')
for item in lines:
(print >> thefile, item)
thefile.close() |
async def gotAddet(bot, guild):
sID = await bot.db.fetchval('SELECT sid FROM config.guild WHERE sid = $1', guild.id)
if sID is None:
query = "WITH exec0 AS (INSERT INTO config.guild (sid, sname) VALUES ($1, $2)) INSERT INTO config.modules (sid) VALUES ($1)"
await bot.db.execute(query, guild.id, guild.name)
else:
await bot.db.execute("UPDATE config.guild SET sname = $1 WHERE sid = $2", guild.name, guild.id)
| async def gotAddet(bot, guild):
s_id = await bot.db.fetchval('SELECT sid FROM config.guild WHERE sid = $1', guild.id)
if sID is None:
query = 'WITH exec0 AS (INSERT INTO config.guild (sid, sname) VALUES ($1, $2)) INSERT INTO config.modules (sid) VALUES ($1)'
await bot.db.execute(query, guild.id, guild.name)
else:
await bot.db.execute('UPDATE config.guild SET sname = $1 WHERE sid = $2', guild.name, guild.id) |
# -*- coding: utf-8 -*-
def main():
s = input()
f = int(s[:2])
l = int(s[2:])
if 1 <= f <= 12 and 1 <= l <= 12:
print('AMBIGUOUS')
elif 1 <= l <= 12:
print('YYMM')
elif 1 <= f <= 12:
print('MMYY')
else:
print('NA')
if __name__ == '__main__':
main()
| def main():
s = input()
f = int(s[:2])
l = int(s[2:])
if 1 <= f <= 12 and 1 <= l <= 12:
print('AMBIGUOUS')
elif 1 <= l <= 12:
print('YYMM')
elif 1 <= f <= 12:
print('MMYY')
else:
print('NA')
if __name__ == '__main__':
main() |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
atoms = {
'C': 1,
'H': 4,
'O': 1,
}
bonds = {
'C-O': 1,
'C-H': 3,
'O-H': 1,
}
linear = False
externalSymmetry = 1
spinMultiplicity = 2
opticalIsomers = 1 #confirmed
energy = {
'M08SO': QchemLog('ch3oh.out'),
}
geometry = QchemLog('ch3oh.out')
frequencies = QchemLog('ch3oh.out')
| atoms = {'C': 1, 'H': 4, 'O': 1}
bonds = {'C-O': 1, 'C-H': 3, 'O-H': 1}
linear = False
external_symmetry = 1
spin_multiplicity = 2
optical_isomers = 1
energy = {'M08SO': qchem_log('ch3oh.out')}
geometry = qchem_log('ch3oh.out')
frequencies = qchem_log('ch3oh.out') |
A = 'A'
B = 'B'
C = 'C'
D = 'D'
state = {}
action = None
model = {A: None, B: None, C: None, D: None} # Initially ignorant
RULE_ACTION = {
1: 'Suck',
2: 'Right',
3: 'NoOp'
}
rules = {
(A, 'Dirty'):1,
(B, 'Dirty'):1,
(C, 'Dirty'):1,
(D, 'Dirty'):1,
(A, 'Clean'):2,
(B, 'Clean'):2,
(C, 'Clean'):2,
(D, 'Clean'):2,
(A, B, C, D, 'Clean'):3
}
#Ex. rule (if location == A && Dirty then rule 1)
Enviroment = {
A: 'Dirty',
B: 'Dirty',
C: 'Dirty',
D: 'Dirty',
'Current': A
}
def INTERPRET_INPUT(input): # No interpretation
return input
def RULE_MATCH(state,rules): # Match rule for a given state
rule = rules.get(tuple(state))
return rule
def UPDATE_STATE(state, action, percept):
(location, status) = percept
state = percept
if model[A] == model[B] == model[C] == model[D] == 'Clean':
state = (A, B, C, D, 'Clean')
# Model consulted only for A and B clean
model[location] = status # Update the model state
return state
def REFLEX_AGENT_WITH_STATE(percept):
global state, action
state = UPDATE_STATE(state, action, percept)
rule = RULE_MATCH(state, rules)
action = RULE_ACTION[rule]
return action
def Sensors(): # Sense Enviroment
location = Enviroment['Current']
return (location, Enviroment[location])
def Actuators(action): # Modify Enviroment
location = Enviroment['Current']
if action == 'Suck':
Enviroment[location] = 'Clean'
elif action == 'Right' and location == A:
Enviroment['Current'] = B
elif action == 'Right' and location == B:
Enviroment['Current'] = C
elif action == 'Right' and location == C:
Enviroment['Current'] = D
elif action == 'Right' and location == D:
Enviroment['Current'] = A
def run(n): # run the agent through n steps
print(' Current New')
print('Location Status Action Location Status')
for i in range(1,n):
(location, status) = Sensors() # Sense Enviroment before action
print("{:12s}{:8s}".format(location, status), end='')
action = REFLEX_AGENT_WITH_STATE(Sensors())
Actuators(action)
(location, status) = Sensors() # Sense Enviroment after action
print("{:8s}{:12s}{:4s}".format(action, location, status))
run(20) | a = 'A'
b = 'B'
c = 'C'
d = 'D'
state = {}
action = None
model = {A: None, B: None, C: None, D: None}
rule_action = {1: 'Suck', 2: 'Right', 3: 'NoOp'}
rules = {(A, 'Dirty'): 1, (B, 'Dirty'): 1, (C, 'Dirty'): 1, (D, 'Dirty'): 1, (A, 'Clean'): 2, (B, 'Clean'): 2, (C, 'Clean'): 2, (D, 'Clean'): 2, (A, B, C, D, 'Clean'): 3}
enviroment = {A: 'Dirty', B: 'Dirty', C: 'Dirty', D: 'Dirty', 'Current': A}
def interpret_input(input):
return input
def rule_match(state, rules):
rule = rules.get(tuple(state))
return rule
def update_state(state, action, percept):
(location, status) = percept
state = percept
if model[A] == model[B] == model[C] == model[D] == 'Clean':
state = (A, B, C, D, 'Clean')
model[location] = status
return state
def reflex_agent_with_state(percept):
global state, action
state = update_state(state, action, percept)
rule = rule_match(state, rules)
action = RULE_ACTION[rule]
return action
def sensors():
location = Enviroment['Current']
return (location, Enviroment[location])
def actuators(action):
location = Enviroment['Current']
if action == 'Suck':
Enviroment[location] = 'Clean'
elif action == 'Right' and location == A:
Enviroment['Current'] = B
elif action == 'Right' and location == B:
Enviroment['Current'] = C
elif action == 'Right' and location == C:
Enviroment['Current'] = D
elif action == 'Right' and location == D:
Enviroment['Current'] = A
def run(n):
print(' Current New')
print('Location Status Action Location Status')
for i in range(1, n):
(location, status) = sensors()
print('{:12s}{:8s}'.format(location, status), end='')
action = reflex_agent_with_state(sensors())
actuators(action)
(location, status) = sensors()
print('{:8s}{:12s}{:4s}'.format(action, location, status))
run(20) |
class Config(object):
DEBUG = True
TESTING = True
# MySQL config
MYSQL_DATABASE_HOST = 'localhost'
MYSQL_DATABASE_PORT = 3306
MYSQL_DATABASE_USER = 'knoydart'
MYSQL_DATABASE_PASSWORD = '7xGFGzF8BbzsJFCd'
MYSQL_DATABASE_DB = 'knoydart'
MYSQL_DATABASE_CHARSET = 'utf8'
DATATAKER_HOST = '185.34.63.131'
DATATAKER_PORT = 7700
DATATAKER_PASS = 'q5DX5zZT2A'
| class Config(object):
debug = True
testing = True
mysql_database_host = 'localhost'
mysql_database_port = 3306
mysql_database_user = 'knoydart'
mysql_database_password = '7xGFGzF8BbzsJFCd'
mysql_database_db = 'knoydart'
mysql_database_charset = 'utf8'
datataker_host = '185.34.63.131'
datataker_port = 7700
datataker_pass = 'q5DX5zZT2A' |
def part1():
values = [[int(i) if i.isnumeric() else i for i in i.split(" ")] for i in open("input.txt","r").read().split("\n")]
depth = 0
horizontal = 0
for i in values:
if i[0] == "up":
depth -= i[1]
elif i[0] == "down":
depth += i[1]
elif i[0] == "forward":
horizontal += i[1]
return depth*horizontal
def part2():
values = [[int(i) if i.isnumeric() else i for i in i.split(" ")] for i in open("input.txt","r").read().split("\n")]
aim = 0
depth = 0
horizontal = 0
for i in values:
if i[0] == "up":
aim -= i[1]
elif i[0] == "down":
aim += i[1]
elif i[0] == "forward":
horizontal += i[1]
depth += aim * i[1]
return depth*horizontal
return total
print(f"answer to part1: {part1()}")
print(f"answer to part2: {part2()}")
| def part1():
values = [[int(i) if i.isnumeric() else i for i in i.split(' ')] for i in open('input.txt', 'r').read().split('\n')]
depth = 0
horizontal = 0
for i in values:
if i[0] == 'up':
depth -= i[1]
elif i[0] == 'down':
depth += i[1]
elif i[0] == 'forward':
horizontal += i[1]
return depth * horizontal
def part2():
values = [[int(i) if i.isnumeric() else i for i in i.split(' ')] for i in open('input.txt', 'r').read().split('\n')]
aim = 0
depth = 0
horizontal = 0
for i in values:
if i[0] == 'up':
aim -= i[1]
elif i[0] == 'down':
aim += i[1]
elif i[0] == 'forward':
horizontal += i[1]
depth += aim * i[1]
return depth * horizontal
return total
print(f'answer to part1: {part1()}')
print(f'answer to part2: {part2()}') |
class Resources:
class LoginPage:
USERNAME_FIELD_PLACEHOLDER = "Username"
PASSWORD_FIELD_PLACEHOLDER = "Password"
LOGIN_BUTTON_TEXT = "Login"
NON_EXISTING_USER_ERROR_TEXT = "Epic sadface: Username and password do not match any user in this service"
MISSING_USERNAME_ERROR_TEXT = "Epic sadface: Username is required"
MISSING_PASSWORD_ERROR_TEXT = "Epic sadface: Password is required"
LOCKED_OUT_USER_ERROR_TEXT = "Epic sadface: Sorry, this user has been locked out."
| class Resources:
class Loginpage:
username_field_placeholder = 'Username'
password_field_placeholder = 'Password'
login_button_text = 'Login'
non_existing_user_error_text = 'Epic sadface: Username and password do not match any user in this service'
missing_username_error_text = 'Epic sadface: Username is required'
missing_password_error_text = 'Epic sadface: Password is required'
locked_out_user_error_text = 'Epic sadface: Sorry, this user has been locked out.' |
def fun(liczby):
n = len(str(liczby))
dziel=1
tak = 10
suma = 0
cos = liczby
for x in range(0,n):
liczba=liczby%tak
liczby-=liczba
tak*=10
liczba/=dziel
suma+=liczba
dziel*=10
return int(suma)
print(fun(545435433))
| def fun(liczby):
n = len(str(liczby))
dziel = 1
tak = 10
suma = 0
cos = liczby
for x in range(0, n):
liczba = liczby % tak
liczby -= liczba
tak *= 10
liczba /= dziel
suma += liczba
dziel *= 10
return int(suma)
print(fun(545435433)) |
def largestNumber(n):
'''
Given an integer n, return the largest number that contains exactly n digits.
'''
return 10 ** n - 1
print(largestNumber(1))
print(largestNumber(5))
print(largestNumber(10))
| def largest_number(n):
"""
Given an integer n, return the largest number that contains exactly n digits.
"""
return 10 ** n - 1
print(largest_number(1))
print(largest_number(5))
print(largest_number(10)) |
# -*- coding: utf-8 -*-
class Solution:
def strStr(self, haystack, needle):
return haystack.find(needle)
if __name__ == '__main__':
solution = Solution()
assert 2 == solution.strStr('hello', 'll')
assert -1 == solution.strStr('aaaaa', 'bba')
assert 0 == solution.strStr('aaaaa', '')
| class Solution:
def str_str(self, haystack, needle):
return haystack.find(needle)
if __name__ == '__main__':
solution = solution()
assert 2 == solution.strStr('hello', 'll')
assert -1 == solution.strStr('aaaaa', 'bba')
assert 0 == solution.strStr('aaaaa', '') |
PARAMS = {
"default": {
"folders": ["INBOX"],
"csvdir": "./data",
"outdir": "./trained",
},
"suse-manager": {
"folders": ["INBOX/suse-manager"],
"csvdir": "./suse-manager-data",
"outdir": "./suse-manager-trained",
}
}
| params = {'default': {'folders': ['INBOX'], 'csvdir': './data', 'outdir': './trained'}, 'suse-manager': {'folders': ['INBOX/suse-manager'], 'csvdir': './suse-manager-data', 'outdir': './suse-manager-trained'}} |
#!/usr/bin/python3
SYMBOL_TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz12345678"+ \
"90 !?."
LEN_SYM_TABLE = len(SYMBOL_TABLE)
print("[+] Length of Symbol table is {}".format(LEN_SYM_TABLE))
def decrypt(c_message, key):
plaintext = []
for ch in c_message:
pos = SYMBOL_TABLE.find(ch)
if pos == -1:
plaintext.append(ch)
continue
if pos - key < 0:
pos = (pos - key) + LEN_SYM_TABLE
else:
pos = (pos - key)
plaintext.append(SYMBOL_TABLE[pos])
return ''.join(plaintext)
## bruteforce across keylength of SYMBOL_TABLE
def bruteForceCaeserCipher(message):
for key in range(LEN_SYM_TABLE):
print("Key: {} -- {}".format(key,decrypt(message,key)))
if __name__ == '__main__':
message = "avnl1olyD4l'ylDohww6DhzDjhuDil"
bruteForceCaeserCipher(message)
| symbol_table = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz12345678' + '90 !?.'
len_sym_table = len(SYMBOL_TABLE)
print('[+] Length of Symbol table is {}'.format(LEN_SYM_TABLE))
def decrypt(c_message, key):
plaintext = []
for ch in c_message:
pos = SYMBOL_TABLE.find(ch)
if pos == -1:
plaintext.append(ch)
continue
if pos - key < 0:
pos = pos - key + LEN_SYM_TABLE
else:
pos = pos - key
plaintext.append(SYMBOL_TABLE[pos])
return ''.join(plaintext)
def brute_force_caeser_cipher(message):
for key in range(LEN_SYM_TABLE):
print('Key: {} -- {}'.format(key, decrypt(message, key)))
if __name__ == '__main__':
message = "avnl1olyD4l'ylDohww6DhzDjhuDil"
brute_force_caeser_cipher(message) |
def try_describe_request(command):
if isinstance(command, list) and len(command) == 3:
command_type = command[0]
if command_type == 4:
player_key = command[1]
actions = command[2]
# known action samples
# [2, id, (target x, y), ?power]
# [1, id] - destruct
# [0, id, (x, y)] - change speed
return {
'command_type': command_type,
'player_key': player_key,
'actions': actions
}
else:
return command
return command
def try_describe_ship(ship):
if len(ship) != 8:
return ship
d = {}
d['role'] = ship[0]
d['id'] = ship[1]
d['pos'] = ship[2]
d['speed'] = ship[3]
d['params'] = {
'remaining fuely': ship[4][0],
'max shot power': ship[4][1],
'heat decrease rate': ship[4][2],
'ships count': ship[4][3],
}
d['heat'] = ship[5]
d['max heat'] = ship[6]
d['unk8'] = ship[7]
return d
def try_describe_game_state(state):
if len(state) != 3:
return state
d = {}
d['step'] = state[0]
d['unk2'] = state[1]
d['ships'] = [
{
'ship': try_describe_ship(block[0]),
'commands': block[1]
}
for block in state[2]]
return d
def try_describe_game_params(params):
if len(params) != 5:
return params
d = {}
d['max time'] = params[0]
d['is_defender'] = params[1]
d['unk3'] = params[2]
d['?planet params'] = params[3]
d['enemy init ship params?? (only attacker??)'] = params[4]
return d
def try_describe_response(response):
if isinstance(response, list) and len(response) == 4:
d = {}
d['success'] = response[0]
d['game_state'] = response[1]
d['game params'] = try_describe_game_params(response[2])
d['game state'] = try_describe_game_state(response[3])
return d
else:
return response
| def try_describe_request(command):
if isinstance(command, list) and len(command) == 3:
command_type = command[0]
if command_type == 4:
player_key = command[1]
actions = command[2]
return {'command_type': command_type, 'player_key': player_key, 'actions': actions}
else:
return command
return command
def try_describe_ship(ship):
if len(ship) != 8:
return ship
d = {}
d['role'] = ship[0]
d['id'] = ship[1]
d['pos'] = ship[2]
d['speed'] = ship[3]
d['params'] = {'remaining fuely': ship[4][0], 'max shot power': ship[4][1], 'heat decrease rate': ship[4][2], 'ships count': ship[4][3]}
d['heat'] = ship[5]
d['max heat'] = ship[6]
d['unk8'] = ship[7]
return d
def try_describe_game_state(state):
if len(state) != 3:
return state
d = {}
d['step'] = state[0]
d['unk2'] = state[1]
d['ships'] = [{'ship': try_describe_ship(block[0]), 'commands': block[1]} for block in state[2]]
return d
def try_describe_game_params(params):
if len(params) != 5:
return params
d = {}
d['max time'] = params[0]
d['is_defender'] = params[1]
d['unk3'] = params[2]
d['?planet params'] = params[3]
d['enemy init ship params?? (only attacker??)'] = params[4]
return d
def try_describe_response(response):
if isinstance(response, list) and len(response) == 4:
d = {}
d['success'] = response[0]
d['game_state'] = response[1]
d['game params'] = try_describe_game_params(response[2])
d['game state'] = try_describe_game_state(response[3])
return d
else:
return response |
# Day 10 - Search Insert Position
# Naive
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
for i, num in enumerate(nums):
if target <= num:
return i
return len(nums)
# Binary Search
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
l, r = 0, len(nums)
while l < r:
m = (l + r) // 2
if nums[m] < target:
l = m + 1
elif target <= nums[m]:
r = m
return l | class Solution:
def search_insert(self, nums: List[int], target: int) -> int:
for (i, num) in enumerate(nums):
if target <= num:
return i
return len(nums)
class Solution:
def search_insert(self, nums: List[int], target: int) -> int:
(l, r) = (0, len(nums))
while l < r:
m = (l + r) // 2
if nums[m] < target:
l = m + 1
elif target <= nums[m]:
r = m
return l |
# Copyright 2014 Rackspace
#
# 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.
LB_ALGORITHM_ROUND_ROBIN = 'ROUND_ROBIN'
LB_ALGORITHM_LEAST_CONNECTIONS = 'LEAST_CONNECTIONS'
LB_ALGORITHM_SOURCE_IP = 'SOURCE_IP'
SUPPORTED_LB_ALGORITHMS = (LB_ALGORITHM_LEAST_CONNECTIONS,
LB_ALGORITHM_ROUND_ROBIN,
LB_ALGORITHM_SOURCE_IP)
SESSION_PERSISTENCE_SOURCE_IP = 'SOURCE_IP'
SESSION_PERSISTENCE_HTTP_COOKIE = 'HTTP_COOKIE'
SESSION_PERSISTENCE_APP_COOKIE = 'APP_COOKIE'
SUPPORTED_SP_TYPES = (SESSION_PERSISTENCE_SOURCE_IP,
SESSION_PERSISTENCE_HTTP_COOKIE,
SESSION_PERSISTENCE_APP_COOKIE)
HEALTH_MONITOR_PING = 'PING'
HEALTH_MONITOR_TCP = 'TCP'
HEALTH_MONITOR_HTTP = 'HTTP'
HEALTH_MONITOR_HTTPS = 'HTTPS'
HEALTH_MONITOR_TLS_HELLO = 'TLS-HELLO'
HEALTH_MONITOR_UDP_CONNECT = 'UDP-CONNECT'
SUPPORTED_HEALTH_MONITOR_TYPES = (HEALTH_MONITOR_HTTP, HEALTH_MONITOR_HTTPS,
HEALTH_MONITOR_PING, HEALTH_MONITOR_TCP,
HEALTH_MONITOR_TLS_HELLO,
HEALTH_MONITOR_UDP_CONNECT)
HEALTH_MONITOR_HTTP_METHOD_GET = 'GET'
HEALTH_MONITOR_HTTP_METHOD_HEAD = 'HEAD'
HEALTH_MONITOR_HTTP_METHOD_POST = 'POST'
HEALTH_MONITOR_HTTP_METHOD_PUT = 'PUT'
HEALTH_MONITOR_HTTP_METHOD_DELETE = 'DELETE'
HEALTH_MONITOR_HTTP_METHOD_TRACE = 'TRACE'
HEALTH_MONITOR_HTTP_METHOD_OPTIONS = 'OPTIONS'
HEALTH_MONITOR_HTTP_METHOD_CONNECT = 'CONNECT'
HEALTH_MONITOR_HTTP_METHOD_PATCH = 'PATCH'
HEALTH_MONITOR_HTTP_DEFAULT_METHOD = HEALTH_MONITOR_HTTP_METHOD_GET
SUPPORTED_HEALTH_MONITOR_HTTP_METHODS = (
HEALTH_MONITOR_HTTP_METHOD_GET, HEALTH_MONITOR_HTTP_METHOD_HEAD,
HEALTH_MONITOR_HTTP_METHOD_POST, HEALTH_MONITOR_HTTP_METHOD_PUT,
HEALTH_MONITOR_HTTP_METHOD_DELETE, HEALTH_MONITOR_HTTP_METHOD_TRACE,
HEALTH_MONITOR_HTTP_METHOD_OPTIONS, HEALTH_MONITOR_HTTP_METHOD_CONNECT,
HEALTH_MONITOR_HTTP_METHOD_PATCH)
HEALTH_MONITOR_DEFAULT_EXPECTED_CODES = '200'
HEALTH_MONITOR_DEFAULT_URL_PATH = '/'
TYPE = 'type'
URL_PATH = 'url_path'
HTTP_METHOD = 'http_method'
EXPECTED_CODES = 'expected_codes'
DELAY = 'delay'
TIMEOUT = 'timeout'
MAX_RETRIES = 'max_retries'
RISE_THRESHOLD = 'rise_threshold'
UPDATE_STATS = 'UPDATE_STATS'
UPDATE_HEALTH = 'UPDATE_HEALTH'
PROTOCOL_TCP = 'TCP'
PROTOCOL_UDP = 'UDP'
PROTOCOL_HTTP = 'HTTP'
PROTOCOL_HTTPS = 'HTTPS'
PROTOCOL_TERMINATED_HTTPS = 'TERMINATED_HTTPS'
PROTOCOL_PROXY = 'PROXY'
SUPPORTED_PROTOCOLS = (PROTOCOL_TCP, PROTOCOL_HTTPS, PROTOCOL_HTTP,
PROTOCOL_TERMINATED_HTTPS, PROTOCOL_PROXY, PROTOCOL_UDP)
VALID_LISTENER_POOL_PROTOCOL_MAP = {
PROTOCOL_TCP: [PROTOCOL_HTTP, PROTOCOL_HTTPS,
PROTOCOL_PROXY, PROTOCOL_TCP],
PROTOCOL_HTTP: [PROTOCOL_HTTP, PROTOCOL_PROXY],
PROTOCOL_HTTPS: [PROTOCOL_HTTPS, PROTOCOL_PROXY, PROTOCOL_TCP],
PROTOCOL_TERMINATED_HTTPS: [PROTOCOL_HTTP, PROTOCOL_PROXY],
PROTOCOL_UDP: [PROTOCOL_UDP]}
# API Integer Ranges
MIN_PORT_NUMBER = 1
MAX_PORT_NUMBER = 65535
DEFAULT_CONNECTION_LIMIT = -1
MIN_CONNECTION_LIMIT = -1
DEFAULT_WEIGHT = 1
MIN_WEIGHT = 0
MAX_WEIGHT = 256
MIN_HM_RETRIES = 1
MAX_HM_RETRIES = 10
# 1 year: y d h m ms
MAX_TIMEOUT = 365 * 24 * 60 * 60 * 1000
MIN_TIMEOUT = 0
DEFAULT_TIMEOUT_CLIENT_DATA = 50000
DEFAULT_TIMEOUT_MEMBER_CONNECT = 5000
DEFAULT_TIMEOUT_MEMBER_DATA = 50000
DEFAULT_TIMEOUT_TCP_INSPECT = 0
# Note: The database Amphora table has a foreign key constraint against
# the provisioning_status table
# Amphora has been allocated to a load balancer
AMPHORA_ALLOCATED = 'ALLOCATED'
# Amphora is being built
AMPHORA_BOOTING = 'BOOTING'
# Amphora is ready to be allocated to a load balancer
AMPHORA_READY = 'READY'
ACTIVE = 'ACTIVE'
PENDING_DELETE = 'PENDING_DELETE'
PENDING_UPDATE = 'PENDING_UPDATE'
PENDING_CREATE = 'PENDING_CREATE'
DELETED = 'DELETED'
ERROR = 'ERROR'
SUPPORTED_PROVISIONING_STATUSES = (ACTIVE, AMPHORA_ALLOCATED,
AMPHORA_BOOTING, AMPHORA_READY,
PENDING_DELETE, PENDING_CREATE,
PENDING_UPDATE, DELETED, ERROR)
MUTABLE_STATUSES = (ACTIVE,)
DELETABLE_STATUSES = (ACTIVE, ERROR)
FAILOVERABLE_STATUSES = (ACTIVE, ERROR)
SUPPORTED_AMPHORA_STATUSES = (AMPHORA_ALLOCATED, AMPHORA_BOOTING, ERROR,
AMPHORA_READY, DELETED,
PENDING_CREATE, PENDING_DELETE)
ONLINE = 'ONLINE'
OFFLINE = 'OFFLINE'
DEGRADED = 'DEGRADED'
ERROR = 'ERROR'
DRAINING = 'DRAINING'
NO_MONITOR = 'NO_MONITOR'
OPERATING_STATUS = 'operating_status'
PROVISIONING_STATUS = 'provisioning_status'
SUPPORTED_OPERATING_STATUSES = (ONLINE, OFFLINE, DEGRADED, ERROR, DRAINING,
NO_MONITOR)
AMPHORA_VM = 'VM'
SUPPORTED_AMPHORA_TYPES = (AMPHORA_VM,)
# L7 constants
L7RULE_TYPE_HOST_NAME = 'HOST_NAME'
L7RULE_TYPE_PATH = 'PATH'
L7RULE_TYPE_FILE_TYPE = 'FILE_TYPE'
L7RULE_TYPE_HEADER = 'HEADER'
L7RULE_TYPE_COOKIE = 'COOKIE'
SUPPORTED_L7RULE_TYPES = (L7RULE_TYPE_HOST_NAME, L7RULE_TYPE_PATH,
L7RULE_TYPE_FILE_TYPE, L7RULE_TYPE_HEADER,
L7RULE_TYPE_COOKIE)
L7RULE_COMPARE_TYPE_REGEX = 'REGEX'
L7RULE_COMPARE_TYPE_STARTS_WITH = 'STARTS_WITH'
L7RULE_COMPARE_TYPE_ENDS_WITH = 'ENDS_WITH'
L7RULE_COMPARE_TYPE_CONTAINS = 'CONTAINS'
L7RULE_COMPARE_TYPE_EQUAL_TO = 'EQUAL_TO'
SUPPORTED_L7RULE_COMPARE_TYPES = (L7RULE_COMPARE_TYPE_REGEX,
L7RULE_COMPARE_TYPE_STARTS_WITH,
L7RULE_COMPARE_TYPE_ENDS_WITH,
L7RULE_COMPARE_TYPE_CONTAINS,
L7RULE_COMPARE_TYPE_EQUAL_TO)
L7POLICY_ACTION_REJECT = 'REJECT'
L7POLICY_ACTION_REDIRECT_TO_URL = 'REDIRECT_TO_URL'
L7POLICY_ACTION_REDIRECT_TO_POOL = 'REDIRECT_TO_POOL'
SUPPORTED_L7POLICY_ACTIONS = (L7POLICY_ACTION_REJECT,
L7POLICY_ACTION_REDIRECT_TO_URL,
L7POLICY_ACTION_REDIRECT_TO_POOL)
MIN_POLICY_POSITION = 1
# Largest a 32-bit integer can be, which is a limitation
# here if you're using MySQL, as most probably are. This just needs
# to be larger than any existing rule position numbers which will
# definitely be the case with 2147483647
MAX_POLICY_POSITION = 2147483647
# Testing showed haproxy config failed to parse after more than
# 53 rules per policy
MAX_L7RULES_PER_L7POLICY = 50
# See RFCs 2616, 2965, 6265, 7230: Should match characters valid in a
# http header or cookie name.
HTTP_HEADER_NAME_REGEX = r'\A[a-zA-Z0-9!#$%&\'*+-.^_`|~]+\Z'
# See RFCs 2616, 2965, 6265: Should match characters valid in a cookie value.
HTTP_COOKIE_VALUE_REGEX = r'\A[a-zA-Z0-9!#$%&\'()*+-./:<=>?@[\]^_`{|}~]+\Z'
# See RFC 7230: Should match characters valid in a header value.
HTTP_HEADER_VALUE_REGEX = (r'\A[a-zA-Z0-9'
r'!"#$%&\'()*+,-./:;<=>?@[\]^_`{|}~\\]+\Z')
# Also in RFC 7230: Should match characters valid in a header value
# when quoted with double quotes.
HTTP_QUOTED_HEADER_VALUE_REGEX = (r'\A"[a-zA-Z0-9 \t'
r'!"#$%&\'()*+,-./:;<=>?@[\]^_`{|}~\\]*"\Z')
# Task/Flow constants
AMPHORA = 'amphora'
FAILED_AMPHORA = 'failed_amphora'
FAILOVER_AMPHORA = 'failover_amphora'
AMPHORAE = 'amphorae'
AMPHORA_ID = 'amphora_id'
AMPHORA_INDEX = 'amphora_index'
FAILOVER_AMPHORA_ID = 'failover_amphora_id'
DELTA = 'delta'
DELTAS = 'deltas'
HEALTH_MON = 'health_mon'
HEALTH_MONITOR = 'health_monitor'
LISTENER = 'listener'
LISTENERS = 'listeners'
LISTENER_ID = 'listener_id'
LOADBALANCER = 'loadbalancer'
LOADBALANCERS = 'loadbalancers'
LOADBALANCER_ID = 'loadbalancer_id'
LOAD_BALANCER_ID = 'load_balancer_id'
SERVER_GROUP_ID = 'server_group_id'
ANTI_AFFINITY = 'anti-affinity'
SOFT_ANTI_AFFINITY = 'soft-anti-affinity'
MEMBER = 'member'
MEMBERS = 'members'
MEMBER_ID = 'member_id'
COMPUTE_ID = 'compute_id'
COMPUTE_OBJ = 'compute_obj'
AMP_DATA = 'amp_data'
AMPS_DATA = 'amps_data'
NICS = 'nics'
VIP = 'vip'
POOL = 'pool'
POOLS = 'pools'
POOL_CHILD_COUNT = 'pool_child_count'
POOL_ID = 'pool_id'
L7POLICY = 'l7policy'
L7RULE = 'l7rule'
OBJECT = 'object'
SERVER_PEM = 'server_pem'
UPDATE_DICT = 'update_dict'
VIP_NETWORK = 'vip_network'
AMPHORAE_NETWORK_CONFIG = 'amphorae_network_config'
ADDED_PORTS = 'added_ports'
PORTS = 'ports'
MEMBER_PORTS = 'member_ports'
LOADBALANCER_TOPOLOGY = 'topology'
HEALTHMONITORS = 'healthmonitors'
HEALTH_MONITOR_ID = 'health_monitor_id'
L7POLICIES = 'l7policies'
L7POLICY_ID = 'l7policy_id'
L7RULES = 'l7rules'
L7RULE_ID = 'l7rule_id'
LOAD_BALANCER_UPDATES = 'load_balancer_updates'
LISTENER_UPDATES = 'listener_updates'
POOL_UPDATES = 'pool_updates'
MEMBER_UPDATES = 'member_updates'
HEALTH_MONITOR_UPDATES = 'health_monitor_updates'
L7POLICY_UPDATES = 'l7policy_updates'
L7RULE_UPDATES = 'l7rule_updates'
TIMEOUT_DICT = 'timeout_dict'
REQ_CONN_TIMEOUT = 'req_conn_timeout'
REQ_READ_TIMEOUT = 'req_read_timeout'
CONN_MAX_RETRIES = 'conn_max_retries'
CONN_RETRY_INTERVAL = 'conn_retry_interval'
CERT_ROTATE_AMPHORA_FLOW = 'octavia-cert-rotate-amphora-flow'
CREATE_AMPHORA_FLOW = 'octavia-create-amphora-flow'
CREATE_AMPHORA_FOR_LB_FLOW = 'octavia-create-amp-for-lb-flow'
CREATE_HEALTH_MONITOR_FLOW = 'octavia-create-health-monitor-flow'
CREATE_LISTENER_FLOW = 'octavia-create-listener_flow'
PRE_CREATE_LOADBALANCER_FLOW = 'octavia-pre-create-loadbalancer-flow'
CREATE_SERVER_GROUP_FLOW = 'octavia-create-server-group-flow'
UPDATE_LB_SERVERGROUPID_FLOW = 'octavia-update-lb-server-group-id-flow'
CREATE_LISTENERS_FLOW = 'octavia-create-all-listeners-flow'
CREATE_LOADBALANCER_FLOW = 'octavia-create-loadbalancer-flow'
CREATE_LOADBALANCER_GRAPH_FLOW = 'octavia-create-loadbalancer-graph-flow'
CREATE_MEMBER_FLOW = 'octavia-create-member-flow'
CREATE_POOL_FLOW = 'octavia-create-pool-flow'
CREATE_L7POLICY_FLOW = 'octavia-create-l7policy-flow'
CREATE_L7RULE_FLOW = 'octavia-create-l7rule-flow'
DELETE_AMPHORA_FLOW = 'octavia-delete-amphora-flow'
DELETE_HEALTH_MONITOR_FLOW = 'octavia-delete-health-monitor-flow'
DELETE_LISTENER_FLOW = 'octavia-delete-listener_flow'
DELETE_LOADBALANCER_FLOW = 'octavia-delete-loadbalancer-flow'
DELETE_MEMBER_FLOW = 'octavia-delete-member-flow'
DELETE_POOL_FLOW = 'octavia-delete-pool-flow'
DELETE_L7POLICY_FLOW = 'octavia-delete-l7policy-flow'
DELETE_L7RULE_FLOW = 'octavia-delete-l7policy-flow'
FAILOVER_AMPHORA_FLOW = 'octavia-failover-amphora-flow'
LOADBALANCER_NETWORKING_SUBFLOW = 'octavia-new-loadbalancer-net-subflow'
UPDATE_HEALTH_MONITOR_FLOW = 'octavia-update-health-monitor-flow'
UPDATE_LISTENER_FLOW = 'octavia-update-listener-flow'
UPDATE_LOADBALANCER_FLOW = 'octavia-update-loadbalancer-flow'
UPDATE_MEMBER_FLOW = 'octavia-update-member-flow'
UPDATE_POOL_FLOW = 'octavia-update-pool-flow'
UPDATE_L7POLICY_FLOW = 'octavia-update-l7policy-flow'
UPDATE_L7RULE_FLOW = 'octavia-update-l7rule-flow'
UPDATE_AMPS_SUBFLOW = 'octavia-update-amps-subflow'
POST_MAP_AMP_TO_LB_SUBFLOW = 'octavia-post-map-amp-to-lb-subflow'
CREATE_AMP_FOR_LB_SUBFLOW = 'octavia-create-amp-for-lb-subflow'
GET_AMPHORA_FOR_LB_SUBFLOW = 'octavia-get-amphora-for-lb-subflow'
POST_LB_AMP_ASSOCIATION_SUBFLOW = (
'octavia-post-loadbalancer-amp_association-subflow')
MAP_LOADBALANCER_TO_AMPHORA = 'octavia-mapload-balancer-to-amphora'
RELOAD_AMPHORA = 'octavia-reload-amphora'
CREATE_AMPHORA_INDB = 'octavia-create-amphora-indb'
GENERATE_SERVER_PEM = 'octavia-generate-serverpem'
UPDATE_CERT_EXPIRATION = 'octavia-update-cert-expiration'
CERT_COMPUTE_CREATE = 'octavia-cert-compute-create'
COMPUTE_CREATE = 'octavia-compute-create'
UPDATE_AMPHORA_COMPUTEID = 'octavia-update-amphora-computeid'
MARK_AMPHORA_BOOTING_INDB = 'octavia-mark-amphora-booting-indb'
WAIT_FOR_AMPHORA = 'octavia-wait_for_amphora'
COMPUTE_WAIT = 'octavia-compute-wait'
UPDATE_AMPHORA_INFO = 'octavia-update-amphora-info'
AMPHORA_FINALIZE = 'octavia-amphora-finalize'
MARK_AMPHORA_ALLOCATED_INDB = 'octavia-mark-amphora-allocated-indb'
RELOADLOAD_BALANCER = 'octavia-reloadload-balancer'
MARK_LB_ACTIVE_INDB = 'octavia-mark-lb-active-indb'
MARK_AMP_MASTER_INDB = 'octavia-mark-amp-master-indb'
MARK_AMP_BACKUP_INDB = 'octavia-mark-amp-backup-indb'
MARK_AMP_STANDALONE_INDB = 'octavia-mark-amp-standalone-indb'
GET_VRRP_SUBFLOW = 'octavia-get-vrrp-subflow'
AMP_VRRP_UPDATE = 'octavia-amphora-vrrp-update'
AMP_VRRP_START = 'octavia-amphora-vrrp-start'
AMP_VRRP_STOP = 'octavia-amphora-vrrp-stop'
AMP_UPDATE_VRRP_INTF = 'octavia-amphora-update-vrrp-intf'
CREATE_VRRP_GROUP_FOR_LB = 'octavia-create-vrrp-group-for-lb'
CREATE_VRRP_SECURITY_RULES = 'octavia-create-vrrp-security-rules'
AMP_COMPUTE_CONNECTIVITY_WAIT = 'octavia-amp-compute-connectivity-wait'
AMP_LISTENER_UPDATE = 'octavia-amp-listeners-update'
GENERATE_SERVER_PEM_TASK = 'GenerateServerPEMTask'
# Batch Member Update constants
MEMBERS = 'members'
UNORDERED_MEMBER_UPDATES_FLOW = 'octavia-unordered-member-updates-flow'
UNORDERED_MEMBER_ACTIVE_FLOW = 'octavia-unordered-member-active-flow'
UPDATE_ATTRIBUTES_FLOW = 'octavia-update-attributes-flow'
DELETE_MODEL_OBJECT_FLOW = 'octavia-delete-model-object-flow'
BATCH_UPDATE_MEMBERS_FLOW = 'octavia-batch-update-members-flow'
MEMBER_TO_ERROR_ON_REVERT_FLOW = 'octavia-member-to-error-on-revert-flow'
DECREMENT_MEMBER_QUOTA_FLOW = 'octavia-decrement-member-quota-flow'
MARK_MEMBER_ACTIVE_INDB = 'octavia-mark-member-active-indb'
UPDATE_MEMBER_INDB = 'octavia-update-member-indb'
DELETE_MEMBER_INDB = 'octavia-delete-member-indb'
# Task Names
RELOAD_LB_AFTER_AMP_ASSOC = 'reload-lb-after-amp-assoc'
RELOAD_LB_AFTER_AMP_ASSOC_FULL_GRAPH = 'reload-lb-after-amp-assoc-full-graph'
RELOAD_LB_AFTER_PLUG_VIP = 'reload-lb-after-plug-vip'
NOVA_1 = '1.1'
NOVA_21 = '2.1'
NOVA_3 = '3'
NOVA_VERSIONS = (NOVA_1, NOVA_21, NOVA_3)
# Auth sections
SERVICE_AUTH = 'service_auth'
RPC_NAMESPACE_CONTROLLER_AGENT = 'controller'
# Build Type Priority
LB_CREATE_FAILOVER_PRIORITY = 20
LB_CREATE_NORMAL_PRIORITY = 40
LB_CREATE_SPARES_POOL_PRIORITY = 60
LB_CREATE_ADMIN_FAILOVER_PRIORITY = 80
BUILD_TYPE_PRIORITY = 'build_type_priority'
# Active standalone roles and topology
TOPOLOGY_SINGLE = 'SINGLE'
TOPOLOGY_ACTIVE_STANDBY = 'ACTIVE_STANDBY'
ROLE_MASTER = 'MASTER'
ROLE_BACKUP = 'BACKUP'
ROLE_STANDALONE = 'STANDALONE'
SUPPORTED_LB_TOPOLOGIES = (TOPOLOGY_ACTIVE_STANDBY, TOPOLOGY_SINGLE)
SUPPORTED_AMPHORA_ROLES = (ROLE_BACKUP, ROLE_MASTER, ROLE_STANDALONE)
TOPOLOGY_STATUS_OK = 'OK'
ROLE_MASTER_PRIORITY = 100
ROLE_BACKUP_PRIORITY = 90
VRRP_AUTH_DEFAULT = 'PASS'
VRRP_AUTH_AH = 'AH'
SUPPORTED_VRRP_AUTH = (VRRP_AUTH_DEFAULT, VRRP_AUTH_AH)
KEEPALIVED_CMD = '/usr/sbin/keepalived '
# The DEFAULT_VRRP_ID value needs to be variable for multi tenant support
# per amphora in the future
DEFAULT_VRRP_ID = 1
VRRP_PROTOCOL_NUM = 112
AUTH_HEADER_PROTOCOL_NUMBER = 51
TEMPLATES = '/templates'
AGENT_API_TEMPLATES = '/templates'
AGENT_CONF_TEMPLATE = 'amphora_agent_conf.template'
USER_DATA_CONFIG_DRIVE_TEMPLATE = 'user_data_config_drive.template'
OPEN = 'OPEN'
FULL = 'FULL'
# OPEN = HAProxy listener status nbconn < maxconn
# FULL = HAProxy listener status not nbconn < maxconn
HAPROXY_LISTENER_STATUSES = (OPEN, FULL)
UP = 'UP'
DOWN = 'DOWN'
# UP = HAProxy backend has working or no servers
# DOWN = HAProxy backend has no working servers
HAPROXY_BACKEND_STATUSES = (UP, DOWN)
DRAIN = 'DRAIN'
MAINT = 'MAINT'
NO_CHECK = 'no check'
# DRAIN = member is weight 0 and is in draining mode
# MAINT = member is downed for maintenance? not sure when this happens
# NO_CHECK = no health monitor is enabled
HAPROXY_MEMBER_STATUSES = (UP, DOWN, DRAIN, MAINT, NO_CHECK)
# Current maximum number of conccurent connections in HAProxy.
# This is limited by the systemd "LimitNOFILE" and
# the sysctl fs.file-max fs.nr_open settings in the image
HAPROXY_MAX_MAXCONN = 1000000
# Quota Constants
QUOTA_UNLIMITED = -1
MIN_QUOTA = QUOTA_UNLIMITED
MAX_QUOTA = 2000000000
API_VERSION = '0.5'
NOOP_EVENT_STREAMER = 'noop_event_streamer'
HAPROXY_BASE_PEER_PORT = 1025
KEEPALIVED_JINJA2_UPSTART = 'keepalived.upstart.j2'
KEEPALIVED_JINJA2_SYSTEMD = 'keepalived.systemd.j2'
KEEPALIVED_JINJA2_SYSVINIT = 'keepalived.sysvinit.j2'
CHECK_SCRIPT_CONF = 'keepalived_check_script.conf.j2'
KEEPALIVED_CHECK_SCRIPT = 'keepalived_lvs_check_script.sh.j2'
PLUGGED_INTERFACES = '/var/lib/octavia/plugged_interfaces'
HAPROXY_USER_GROUP_CFG = '/var/lib/octavia/haproxy-default-user-group.conf'
AMPHORA_NAMESPACE = 'amphora-haproxy'
# List of HTTP headers which are supported for insertion
SUPPORTED_HTTP_HEADERS = ['X-Forwarded-For',
'X-Forwarded-Port',
'X-Forwarded-Proto']
FLOW_DOC_TITLES = {'AmphoraFlows': 'Amphora Flows',
'LoadBalancerFlows': 'Load Balancer Flows',
'ListenerFlows': 'Listener Flows',
'PoolFlows': 'Pool Flows',
'MemberFlows': 'Member Flows',
'HealthMonitorFlows': 'Health Monitor Flows',
'L7PolicyFlows': 'Layer 7 Policy Flows',
'L7RuleFlows': 'Layer 7 Rule Flows'}
NETNS_PRIMARY_INTERFACE = 'eth1'
SYSCTL_CMD = '/sbin/sysctl'
AMP_ACTION_START = 'start'
AMP_ACTION_STOP = 'stop'
AMP_ACTION_RELOAD = 'reload'
AMP_ACTION_RESTART = 'restart'
GLANCE_IMAGE_ACTIVE = 'active'
INIT_SYSTEMD = 'systemd'
INIT_UPSTART = 'upstart'
INIT_SYSVINIT = 'sysvinit'
INIT_UNKOWN = 'unknown'
VALID_INIT_SYSTEMS = (INIT_SYSTEMD, INIT_SYSVINIT, INIT_UPSTART)
INIT_PATH = '/sbin/init'
SYSTEMD_DIR = '/usr/lib/systemd/system'
SYSVINIT_DIR = '/etc/init.d'
UPSTART_DIR = '/etc/init'
INIT_PROC_COMM_PATH = '/proc/1/comm'
KEEPALIVED_SYSTEMD = 'octavia-keepalived.service'
KEEPALIVED_SYSVINIT = 'octavia-keepalived'
KEEPALIVED_UPSTART = 'octavia-keepalived.conf'
KEEPALIVED_SYSTEMD_PREFIX = 'octavia-keepalivedlvs-%s.service'
KEEPALIVED_SYSVINIT_PREFIX = 'octavia-keepalivedlvs-%s'
KEEPALIVED_UPSTART_PREFIX = 'octavia-keepalivedlvs-%s.conf'
# Authentication
KEYSTONE = 'keystone'
NOAUTH = 'noauth'
TESTING = 'testing'
# Amphora distro-specific data
UBUNTU_AMP_NET_DIR_TEMPLATE = '/etc/netns/{netns}/network/interfaces.d/'
RH_AMP_NET_DIR_TEMPLATE = '/etc/netns/{netns}/sysconfig/network-scripts/'
UBUNTU = 'ubuntu'
CENTOS = 'centos'
# Pagination, sorting, filtering values
APPLICATION_JSON = 'application/json'
PAGINATION_HELPER = 'pagination_helper'
ASC = 'asc'
DESC = 'desc'
ALLOWED_SORT_DIR = (ASC, DESC)
DEFAULT_SORT_DIR = ASC
DEFAULT_SORT_KEYS = ['created_at', 'id']
DEFAULT_PAGE_SIZE = 1000
# RBAC
LOADBALANCER_API = 'os_load-balancer_api'
RULE_API_ADMIN = 'rule:load-balancer:admin'
RULE_API_READ = 'rule:load-balancer:read'
RULE_API_READ_GLOBAL = 'rule:load-balancer:read-global'
RULE_API_WRITE = 'rule:load-balancer:write'
RULE_API_READ_QUOTA = 'rule:load-balancer:read-quota'
RULE_API_READ_QUOTA_GLOBAL = 'rule:load-balancer:read-quota-global'
RULE_API_WRITE_QUOTA = 'rule:load-balancer:write-quota'
RBAC_LOADBALANCER = '{}:loadbalancer:'.format(LOADBALANCER_API)
RBAC_LISTENER = '{}:listener:'.format(LOADBALANCER_API)
RBAC_POOL = '{}:pool:'.format(LOADBALANCER_API)
RBAC_MEMBER = '{}:member:'.format(LOADBALANCER_API)
RBAC_HEALTHMONITOR = '{}:healthmonitor:'.format(LOADBALANCER_API)
RBAC_L7POLICY = '{}:l7policy:'.format(LOADBALANCER_API)
RBAC_L7RULE = '{}:l7rule:'.format(LOADBALANCER_API)
RBAC_QUOTA = '{}:quota:'.format(LOADBALANCER_API)
RBAC_AMPHORA = '{}:amphora:'.format(LOADBALANCER_API)
RBAC_PROVIDER = '{}:provider:'.format(LOADBALANCER_API)
RBAC_POST = 'post'
RBAC_PUT = 'put'
RBAC_PUT_FAILOVER = 'put_failover'
RBAC_DELETE = 'delete'
RBAC_GET_ONE = 'get_one'
RBAC_GET_ALL = 'get_all'
RBAC_GET_ALL_GLOBAL = 'get_all-global'
RBAC_GET_DEFAULTS = 'get_defaults'
RBAC_GET_STATS = 'get_stats'
RBAC_GET_STATUS = 'get_status'
# PROVIDERS
# TODO(johnsom) When providers are implemented, this should be removed.
OCTAVIA = 'octavia'
# FLAVORS
# TODO(johnsom) When flavors are implemented, this should be removed.
SUPPORTED_FLAVORS = ()
# systemctl commands
DISABLE = 'disable'
ENABLE = 'enable'
# systemd amphora netns service prefix
AMP_NETNS_SVC_PREFIX = 'amphora-netns'
| lb_algorithm_round_robin = 'ROUND_ROBIN'
lb_algorithm_least_connections = 'LEAST_CONNECTIONS'
lb_algorithm_source_ip = 'SOURCE_IP'
supported_lb_algorithms = (LB_ALGORITHM_LEAST_CONNECTIONS, LB_ALGORITHM_ROUND_ROBIN, LB_ALGORITHM_SOURCE_IP)
session_persistence_source_ip = 'SOURCE_IP'
session_persistence_http_cookie = 'HTTP_COOKIE'
session_persistence_app_cookie = 'APP_COOKIE'
supported_sp_types = (SESSION_PERSISTENCE_SOURCE_IP, SESSION_PERSISTENCE_HTTP_COOKIE, SESSION_PERSISTENCE_APP_COOKIE)
health_monitor_ping = 'PING'
health_monitor_tcp = 'TCP'
health_monitor_http = 'HTTP'
health_monitor_https = 'HTTPS'
health_monitor_tls_hello = 'TLS-HELLO'
health_monitor_udp_connect = 'UDP-CONNECT'
supported_health_monitor_types = (HEALTH_MONITOR_HTTP, HEALTH_MONITOR_HTTPS, HEALTH_MONITOR_PING, HEALTH_MONITOR_TCP, HEALTH_MONITOR_TLS_HELLO, HEALTH_MONITOR_UDP_CONNECT)
health_monitor_http_method_get = 'GET'
health_monitor_http_method_head = 'HEAD'
health_monitor_http_method_post = 'POST'
health_monitor_http_method_put = 'PUT'
health_monitor_http_method_delete = 'DELETE'
health_monitor_http_method_trace = 'TRACE'
health_monitor_http_method_options = 'OPTIONS'
health_monitor_http_method_connect = 'CONNECT'
health_monitor_http_method_patch = 'PATCH'
health_monitor_http_default_method = HEALTH_MONITOR_HTTP_METHOD_GET
supported_health_monitor_http_methods = (HEALTH_MONITOR_HTTP_METHOD_GET, HEALTH_MONITOR_HTTP_METHOD_HEAD, HEALTH_MONITOR_HTTP_METHOD_POST, HEALTH_MONITOR_HTTP_METHOD_PUT, HEALTH_MONITOR_HTTP_METHOD_DELETE, HEALTH_MONITOR_HTTP_METHOD_TRACE, HEALTH_MONITOR_HTTP_METHOD_OPTIONS, HEALTH_MONITOR_HTTP_METHOD_CONNECT, HEALTH_MONITOR_HTTP_METHOD_PATCH)
health_monitor_default_expected_codes = '200'
health_monitor_default_url_path = '/'
type = 'type'
url_path = 'url_path'
http_method = 'http_method'
expected_codes = 'expected_codes'
delay = 'delay'
timeout = 'timeout'
max_retries = 'max_retries'
rise_threshold = 'rise_threshold'
update_stats = 'UPDATE_STATS'
update_health = 'UPDATE_HEALTH'
protocol_tcp = 'TCP'
protocol_udp = 'UDP'
protocol_http = 'HTTP'
protocol_https = 'HTTPS'
protocol_terminated_https = 'TERMINATED_HTTPS'
protocol_proxy = 'PROXY'
supported_protocols = (PROTOCOL_TCP, PROTOCOL_HTTPS, PROTOCOL_HTTP, PROTOCOL_TERMINATED_HTTPS, PROTOCOL_PROXY, PROTOCOL_UDP)
valid_listener_pool_protocol_map = {PROTOCOL_TCP: [PROTOCOL_HTTP, PROTOCOL_HTTPS, PROTOCOL_PROXY, PROTOCOL_TCP], PROTOCOL_HTTP: [PROTOCOL_HTTP, PROTOCOL_PROXY], PROTOCOL_HTTPS: [PROTOCOL_HTTPS, PROTOCOL_PROXY, PROTOCOL_TCP], PROTOCOL_TERMINATED_HTTPS: [PROTOCOL_HTTP, PROTOCOL_PROXY], PROTOCOL_UDP: [PROTOCOL_UDP]}
min_port_number = 1
max_port_number = 65535
default_connection_limit = -1
min_connection_limit = -1
default_weight = 1
min_weight = 0
max_weight = 256
min_hm_retries = 1
max_hm_retries = 10
max_timeout = 365 * 24 * 60 * 60 * 1000
min_timeout = 0
default_timeout_client_data = 50000
default_timeout_member_connect = 5000
default_timeout_member_data = 50000
default_timeout_tcp_inspect = 0
amphora_allocated = 'ALLOCATED'
amphora_booting = 'BOOTING'
amphora_ready = 'READY'
active = 'ACTIVE'
pending_delete = 'PENDING_DELETE'
pending_update = 'PENDING_UPDATE'
pending_create = 'PENDING_CREATE'
deleted = 'DELETED'
error = 'ERROR'
supported_provisioning_statuses = (ACTIVE, AMPHORA_ALLOCATED, AMPHORA_BOOTING, AMPHORA_READY, PENDING_DELETE, PENDING_CREATE, PENDING_UPDATE, DELETED, ERROR)
mutable_statuses = (ACTIVE,)
deletable_statuses = (ACTIVE, ERROR)
failoverable_statuses = (ACTIVE, ERROR)
supported_amphora_statuses = (AMPHORA_ALLOCATED, AMPHORA_BOOTING, ERROR, AMPHORA_READY, DELETED, PENDING_CREATE, PENDING_DELETE)
online = 'ONLINE'
offline = 'OFFLINE'
degraded = 'DEGRADED'
error = 'ERROR'
draining = 'DRAINING'
no_monitor = 'NO_MONITOR'
operating_status = 'operating_status'
provisioning_status = 'provisioning_status'
supported_operating_statuses = (ONLINE, OFFLINE, DEGRADED, ERROR, DRAINING, NO_MONITOR)
amphora_vm = 'VM'
supported_amphora_types = (AMPHORA_VM,)
l7_rule_type_host_name = 'HOST_NAME'
l7_rule_type_path = 'PATH'
l7_rule_type_file_type = 'FILE_TYPE'
l7_rule_type_header = 'HEADER'
l7_rule_type_cookie = 'COOKIE'
supported_l7_rule_types = (L7RULE_TYPE_HOST_NAME, L7RULE_TYPE_PATH, L7RULE_TYPE_FILE_TYPE, L7RULE_TYPE_HEADER, L7RULE_TYPE_COOKIE)
l7_rule_compare_type_regex = 'REGEX'
l7_rule_compare_type_starts_with = 'STARTS_WITH'
l7_rule_compare_type_ends_with = 'ENDS_WITH'
l7_rule_compare_type_contains = 'CONTAINS'
l7_rule_compare_type_equal_to = 'EQUAL_TO'
supported_l7_rule_compare_types = (L7RULE_COMPARE_TYPE_REGEX, L7RULE_COMPARE_TYPE_STARTS_WITH, L7RULE_COMPARE_TYPE_ENDS_WITH, L7RULE_COMPARE_TYPE_CONTAINS, L7RULE_COMPARE_TYPE_EQUAL_TO)
l7_policy_action_reject = 'REJECT'
l7_policy_action_redirect_to_url = 'REDIRECT_TO_URL'
l7_policy_action_redirect_to_pool = 'REDIRECT_TO_POOL'
supported_l7_policy_actions = (L7POLICY_ACTION_REJECT, L7POLICY_ACTION_REDIRECT_TO_URL, L7POLICY_ACTION_REDIRECT_TO_POOL)
min_policy_position = 1
max_policy_position = 2147483647
max_l7_rules_per_l7_policy = 50
http_header_name_regex = "\\A[a-zA-Z0-9!#$%&\\'*+-.^_`|~]+\\Z"
http_cookie_value_regex = "\\A[a-zA-Z0-9!#$%&\\'()*+-./:<=>?@[\\]^_`{|}~]+\\Z"
http_header_value_regex = '\\A[a-zA-Z0-9!"#$%&\\\'()*+,-./:;<=>?@[\\]^_`{|}~\\\\]+\\Z'
http_quoted_header_value_regex = '\\A"[a-zA-Z0-9 \\t!"#$%&\\\'()*+,-./:;<=>?@[\\]^_`{|}~\\\\]*"\\Z'
amphora = 'amphora'
failed_amphora = 'failed_amphora'
failover_amphora = 'failover_amphora'
amphorae = 'amphorae'
amphora_id = 'amphora_id'
amphora_index = 'amphora_index'
failover_amphora_id = 'failover_amphora_id'
delta = 'delta'
deltas = 'deltas'
health_mon = 'health_mon'
health_monitor = 'health_monitor'
listener = 'listener'
listeners = 'listeners'
listener_id = 'listener_id'
loadbalancer = 'loadbalancer'
loadbalancers = 'loadbalancers'
loadbalancer_id = 'loadbalancer_id'
load_balancer_id = 'load_balancer_id'
server_group_id = 'server_group_id'
anti_affinity = 'anti-affinity'
soft_anti_affinity = 'soft-anti-affinity'
member = 'member'
members = 'members'
member_id = 'member_id'
compute_id = 'compute_id'
compute_obj = 'compute_obj'
amp_data = 'amp_data'
amps_data = 'amps_data'
nics = 'nics'
vip = 'vip'
pool = 'pool'
pools = 'pools'
pool_child_count = 'pool_child_count'
pool_id = 'pool_id'
l7_policy = 'l7policy'
l7_rule = 'l7rule'
object = 'object'
server_pem = 'server_pem'
update_dict = 'update_dict'
vip_network = 'vip_network'
amphorae_network_config = 'amphorae_network_config'
added_ports = 'added_ports'
ports = 'ports'
member_ports = 'member_ports'
loadbalancer_topology = 'topology'
healthmonitors = 'healthmonitors'
health_monitor_id = 'health_monitor_id'
l7_policies = 'l7policies'
l7_policy_id = 'l7policy_id'
l7_rules = 'l7rules'
l7_rule_id = 'l7rule_id'
load_balancer_updates = 'load_balancer_updates'
listener_updates = 'listener_updates'
pool_updates = 'pool_updates'
member_updates = 'member_updates'
health_monitor_updates = 'health_monitor_updates'
l7_policy_updates = 'l7policy_updates'
l7_rule_updates = 'l7rule_updates'
timeout_dict = 'timeout_dict'
req_conn_timeout = 'req_conn_timeout'
req_read_timeout = 'req_read_timeout'
conn_max_retries = 'conn_max_retries'
conn_retry_interval = 'conn_retry_interval'
cert_rotate_amphora_flow = 'octavia-cert-rotate-amphora-flow'
create_amphora_flow = 'octavia-create-amphora-flow'
create_amphora_for_lb_flow = 'octavia-create-amp-for-lb-flow'
create_health_monitor_flow = 'octavia-create-health-monitor-flow'
create_listener_flow = 'octavia-create-listener_flow'
pre_create_loadbalancer_flow = 'octavia-pre-create-loadbalancer-flow'
create_server_group_flow = 'octavia-create-server-group-flow'
update_lb_servergroupid_flow = 'octavia-update-lb-server-group-id-flow'
create_listeners_flow = 'octavia-create-all-listeners-flow'
create_loadbalancer_flow = 'octavia-create-loadbalancer-flow'
create_loadbalancer_graph_flow = 'octavia-create-loadbalancer-graph-flow'
create_member_flow = 'octavia-create-member-flow'
create_pool_flow = 'octavia-create-pool-flow'
create_l7_policy_flow = 'octavia-create-l7policy-flow'
create_l7_rule_flow = 'octavia-create-l7rule-flow'
delete_amphora_flow = 'octavia-delete-amphora-flow'
delete_health_monitor_flow = 'octavia-delete-health-monitor-flow'
delete_listener_flow = 'octavia-delete-listener_flow'
delete_loadbalancer_flow = 'octavia-delete-loadbalancer-flow'
delete_member_flow = 'octavia-delete-member-flow'
delete_pool_flow = 'octavia-delete-pool-flow'
delete_l7_policy_flow = 'octavia-delete-l7policy-flow'
delete_l7_rule_flow = 'octavia-delete-l7policy-flow'
failover_amphora_flow = 'octavia-failover-amphora-flow'
loadbalancer_networking_subflow = 'octavia-new-loadbalancer-net-subflow'
update_health_monitor_flow = 'octavia-update-health-monitor-flow'
update_listener_flow = 'octavia-update-listener-flow'
update_loadbalancer_flow = 'octavia-update-loadbalancer-flow'
update_member_flow = 'octavia-update-member-flow'
update_pool_flow = 'octavia-update-pool-flow'
update_l7_policy_flow = 'octavia-update-l7policy-flow'
update_l7_rule_flow = 'octavia-update-l7rule-flow'
update_amps_subflow = 'octavia-update-amps-subflow'
post_map_amp_to_lb_subflow = 'octavia-post-map-amp-to-lb-subflow'
create_amp_for_lb_subflow = 'octavia-create-amp-for-lb-subflow'
get_amphora_for_lb_subflow = 'octavia-get-amphora-for-lb-subflow'
post_lb_amp_association_subflow = 'octavia-post-loadbalancer-amp_association-subflow'
map_loadbalancer_to_amphora = 'octavia-mapload-balancer-to-amphora'
reload_amphora = 'octavia-reload-amphora'
create_amphora_indb = 'octavia-create-amphora-indb'
generate_server_pem = 'octavia-generate-serverpem'
update_cert_expiration = 'octavia-update-cert-expiration'
cert_compute_create = 'octavia-cert-compute-create'
compute_create = 'octavia-compute-create'
update_amphora_computeid = 'octavia-update-amphora-computeid'
mark_amphora_booting_indb = 'octavia-mark-amphora-booting-indb'
wait_for_amphora = 'octavia-wait_for_amphora'
compute_wait = 'octavia-compute-wait'
update_amphora_info = 'octavia-update-amphora-info'
amphora_finalize = 'octavia-amphora-finalize'
mark_amphora_allocated_indb = 'octavia-mark-amphora-allocated-indb'
reloadload_balancer = 'octavia-reloadload-balancer'
mark_lb_active_indb = 'octavia-mark-lb-active-indb'
mark_amp_master_indb = 'octavia-mark-amp-master-indb'
mark_amp_backup_indb = 'octavia-mark-amp-backup-indb'
mark_amp_standalone_indb = 'octavia-mark-amp-standalone-indb'
get_vrrp_subflow = 'octavia-get-vrrp-subflow'
amp_vrrp_update = 'octavia-amphora-vrrp-update'
amp_vrrp_start = 'octavia-amphora-vrrp-start'
amp_vrrp_stop = 'octavia-amphora-vrrp-stop'
amp_update_vrrp_intf = 'octavia-amphora-update-vrrp-intf'
create_vrrp_group_for_lb = 'octavia-create-vrrp-group-for-lb'
create_vrrp_security_rules = 'octavia-create-vrrp-security-rules'
amp_compute_connectivity_wait = 'octavia-amp-compute-connectivity-wait'
amp_listener_update = 'octavia-amp-listeners-update'
generate_server_pem_task = 'GenerateServerPEMTask'
members = 'members'
unordered_member_updates_flow = 'octavia-unordered-member-updates-flow'
unordered_member_active_flow = 'octavia-unordered-member-active-flow'
update_attributes_flow = 'octavia-update-attributes-flow'
delete_model_object_flow = 'octavia-delete-model-object-flow'
batch_update_members_flow = 'octavia-batch-update-members-flow'
member_to_error_on_revert_flow = 'octavia-member-to-error-on-revert-flow'
decrement_member_quota_flow = 'octavia-decrement-member-quota-flow'
mark_member_active_indb = 'octavia-mark-member-active-indb'
update_member_indb = 'octavia-update-member-indb'
delete_member_indb = 'octavia-delete-member-indb'
reload_lb_after_amp_assoc = 'reload-lb-after-amp-assoc'
reload_lb_after_amp_assoc_full_graph = 'reload-lb-after-amp-assoc-full-graph'
reload_lb_after_plug_vip = 'reload-lb-after-plug-vip'
nova_1 = '1.1'
nova_21 = '2.1'
nova_3 = '3'
nova_versions = (NOVA_1, NOVA_21, NOVA_3)
service_auth = 'service_auth'
rpc_namespace_controller_agent = 'controller'
lb_create_failover_priority = 20
lb_create_normal_priority = 40
lb_create_spares_pool_priority = 60
lb_create_admin_failover_priority = 80
build_type_priority = 'build_type_priority'
topology_single = 'SINGLE'
topology_active_standby = 'ACTIVE_STANDBY'
role_master = 'MASTER'
role_backup = 'BACKUP'
role_standalone = 'STANDALONE'
supported_lb_topologies = (TOPOLOGY_ACTIVE_STANDBY, TOPOLOGY_SINGLE)
supported_amphora_roles = (ROLE_BACKUP, ROLE_MASTER, ROLE_STANDALONE)
topology_status_ok = 'OK'
role_master_priority = 100
role_backup_priority = 90
vrrp_auth_default = 'PASS'
vrrp_auth_ah = 'AH'
supported_vrrp_auth = (VRRP_AUTH_DEFAULT, VRRP_AUTH_AH)
keepalived_cmd = '/usr/sbin/keepalived '
default_vrrp_id = 1
vrrp_protocol_num = 112
auth_header_protocol_number = 51
templates = '/templates'
agent_api_templates = '/templates'
agent_conf_template = 'amphora_agent_conf.template'
user_data_config_drive_template = 'user_data_config_drive.template'
open = 'OPEN'
full = 'FULL'
haproxy_listener_statuses = (OPEN, FULL)
up = 'UP'
down = 'DOWN'
haproxy_backend_statuses = (UP, DOWN)
drain = 'DRAIN'
maint = 'MAINT'
no_check = 'no check'
haproxy_member_statuses = (UP, DOWN, DRAIN, MAINT, NO_CHECK)
haproxy_max_maxconn = 1000000
quota_unlimited = -1
min_quota = QUOTA_UNLIMITED
max_quota = 2000000000
api_version = '0.5'
noop_event_streamer = 'noop_event_streamer'
haproxy_base_peer_port = 1025
keepalived_jinja2_upstart = 'keepalived.upstart.j2'
keepalived_jinja2_systemd = 'keepalived.systemd.j2'
keepalived_jinja2_sysvinit = 'keepalived.sysvinit.j2'
check_script_conf = 'keepalived_check_script.conf.j2'
keepalived_check_script = 'keepalived_lvs_check_script.sh.j2'
plugged_interfaces = '/var/lib/octavia/plugged_interfaces'
haproxy_user_group_cfg = '/var/lib/octavia/haproxy-default-user-group.conf'
amphora_namespace = 'amphora-haproxy'
supported_http_headers = ['X-Forwarded-For', 'X-Forwarded-Port', 'X-Forwarded-Proto']
flow_doc_titles = {'AmphoraFlows': 'Amphora Flows', 'LoadBalancerFlows': 'Load Balancer Flows', 'ListenerFlows': 'Listener Flows', 'PoolFlows': 'Pool Flows', 'MemberFlows': 'Member Flows', 'HealthMonitorFlows': 'Health Monitor Flows', 'L7PolicyFlows': 'Layer 7 Policy Flows', 'L7RuleFlows': 'Layer 7 Rule Flows'}
netns_primary_interface = 'eth1'
sysctl_cmd = '/sbin/sysctl'
amp_action_start = 'start'
amp_action_stop = 'stop'
amp_action_reload = 'reload'
amp_action_restart = 'restart'
glance_image_active = 'active'
init_systemd = 'systemd'
init_upstart = 'upstart'
init_sysvinit = 'sysvinit'
init_unkown = 'unknown'
valid_init_systems = (INIT_SYSTEMD, INIT_SYSVINIT, INIT_UPSTART)
init_path = '/sbin/init'
systemd_dir = '/usr/lib/systemd/system'
sysvinit_dir = '/etc/init.d'
upstart_dir = '/etc/init'
init_proc_comm_path = '/proc/1/comm'
keepalived_systemd = 'octavia-keepalived.service'
keepalived_sysvinit = 'octavia-keepalived'
keepalived_upstart = 'octavia-keepalived.conf'
keepalived_systemd_prefix = 'octavia-keepalivedlvs-%s.service'
keepalived_sysvinit_prefix = 'octavia-keepalivedlvs-%s'
keepalived_upstart_prefix = 'octavia-keepalivedlvs-%s.conf'
keystone = 'keystone'
noauth = 'noauth'
testing = 'testing'
ubuntu_amp_net_dir_template = '/etc/netns/{netns}/network/interfaces.d/'
rh_amp_net_dir_template = '/etc/netns/{netns}/sysconfig/network-scripts/'
ubuntu = 'ubuntu'
centos = 'centos'
application_json = 'application/json'
pagination_helper = 'pagination_helper'
asc = 'asc'
desc = 'desc'
allowed_sort_dir = (ASC, DESC)
default_sort_dir = ASC
default_sort_keys = ['created_at', 'id']
default_page_size = 1000
loadbalancer_api = 'os_load-balancer_api'
rule_api_admin = 'rule:load-balancer:admin'
rule_api_read = 'rule:load-balancer:read'
rule_api_read_global = 'rule:load-balancer:read-global'
rule_api_write = 'rule:load-balancer:write'
rule_api_read_quota = 'rule:load-balancer:read-quota'
rule_api_read_quota_global = 'rule:load-balancer:read-quota-global'
rule_api_write_quota = 'rule:load-balancer:write-quota'
rbac_loadbalancer = '{}:loadbalancer:'.format(LOADBALANCER_API)
rbac_listener = '{}:listener:'.format(LOADBALANCER_API)
rbac_pool = '{}:pool:'.format(LOADBALANCER_API)
rbac_member = '{}:member:'.format(LOADBALANCER_API)
rbac_healthmonitor = '{}:healthmonitor:'.format(LOADBALANCER_API)
rbac_l7_policy = '{}:l7policy:'.format(LOADBALANCER_API)
rbac_l7_rule = '{}:l7rule:'.format(LOADBALANCER_API)
rbac_quota = '{}:quota:'.format(LOADBALANCER_API)
rbac_amphora = '{}:amphora:'.format(LOADBALANCER_API)
rbac_provider = '{}:provider:'.format(LOADBALANCER_API)
rbac_post = 'post'
rbac_put = 'put'
rbac_put_failover = 'put_failover'
rbac_delete = 'delete'
rbac_get_one = 'get_one'
rbac_get_all = 'get_all'
rbac_get_all_global = 'get_all-global'
rbac_get_defaults = 'get_defaults'
rbac_get_stats = 'get_stats'
rbac_get_status = 'get_status'
octavia = 'octavia'
supported_flavors = ()
disable = 'disable'
enable = 'enable'
amp_netns_svc_prefix = 'amphora-netns' |
class Parent:
def __getitem__(self, idx):
return 0
class Child(Parent):
def index_super(self, idx):
return super()[idx]
kid = Child()
print(f'kid[0]: {kid[0]}')
print(f'kid.index_super(0): {kid.index_super(0)}') | class Parent:
def __getitem__(self, idx):
return 0
class Child(Parent):
def index_super(self, idx):
return super()[idx]
kid = child()
print(f'kid[0]: {kid[0]}')
print(f'kid.index_super(0): {kid.index_super(0)}') |
def run_training_loop():
dataset_reader = build_dataset_reader()
# These are a subclass of pytorch Datasets, with some allennlp-specific
# functionality added.
train_data, dev_data = read_data(dataset_reader)
vocab = build_vocab(train_data + dev_data)
model = build_model(vocab)
# This is the allennlp-specific functionality in the Dataset object;
# we need to be able convert strings in the data to integers, and this
# is how we do it.
train_data.index_with(vocab)
dev_data.index_with(vocab)
# These are again a subclass of pytorch DataLoaders, with an
# allennlp-specific collate function, that runs our indexing and
# batching code.
train_loader, dev_loader = build_data_loaders(train_data, dev_data)
# You obviously won't want to create a temporary file for your training
# results, but for execution in binder for this guide, we need to do this.
with tempfile.TemporaryDirectory() as serialization_dir:
trainer = build_trainer(
model,
serialization_dir,
train_loader,
dev_loader
)
print("Starting training")
trainer.train()
print("Finished training")
# The other `build_*` methods are things we've seen before, so they are
# in the setup section above.
def build_data_loaders(
train_data: torch.utils.data.Dataset,
dev_data: torch.utils.data.Dataset,
) -> Tuple[allennlp.data.DataLoader, allennlp.data.DataLoader]:
# Note that DataLoader is imported from allennlp above, *not* torch.
# We need to get the allennlp-specific collate function, which is
# what actually does indexing and batching.
train_loader = DataLoader(train_data, batch_size=8, shuffle=True)
dev_loader = DataLoader(dev_data, batch_size=8, shuffle=False)
return train_loader, dev_loader
def build_trainer(
model: Model,
serialization_dir: str,
train_loader: DataLoader,
dev_loader: DataLoader
) -> Trainer:
parameters = [
[n, p]
for n, p in model.named_parameters() if p.requires_grad
]
optimizer = AdamOptimizer(parameters)
trainer = GradientDescentTrainer(
model=model,
serialization_dir=serialization_dir,
data_loader=train_loader,
validation_data_loader=dev_loader,
num_epochs=5,
optimizer=optimizer,
)
return trainer
run_training_loop()
| def run_training_loop():
dataset_reader = build_dataset_reader()
(train_data, dev_data) = read_data(dataset_reader)
vocab = build_vocab(train_data + dev_data)
model = build_model(vocab)
train_data.index_with(vocab)
dev_data.index_with(vocab)
(train_loader, dev_loader) = build_data_loaders(train_data, dev_data)
with tempfile.TemporaryDirectory() as serialization_dir:
trainer = build_trainer(model, serialization_dir, train_loader, dev_loader)
print('Starting training')
trainer.train()
print('Finished training')
def build_data_loaders(train_data: torch.utils.data.Dataset, dev_data: torch.utils.data.Dataset) -> Tuple[allennlp.data.DataLoader, allennlp.data.DataLoader]:
train_loader = data_loader(train_data, batch_size=8, shuffle=True)
dev_loader = data_loader(dev_data, batch_size=8, shuffle=False)
return (train_loader, dev_loader)
def build_trainer(model: Model, serialization_dir: str, train_loader: DataLoader, dev_loader: DataLoader) -> Trainer:
parameters = [[n, p] for (n, p) in model.named_parameters() if p.requires_grad]
optimizer = adam_optimizer(parameters)
trainer = gradient_descent_trainer(model=model, serialization_dir=serialization_dir, data_loader=train_loader, validation_data_loader=dev_loader, num_epochs=5, optimizer=optimizer)
return trainer
run_training_loop() |
n, m = [int(tmp) for tmp in input().split()]
dic = {}
for cnt in range(n):
k, v = [tmp for tmp in input().split()]
dic[k] = v
words = input().split()
for word in words:
if word in dic:
print(dic[word], end=' kachal! ')
else:
print(end='kachal! ')
| (n, m) = [int(tmp) for tmp in input().split()]
dic = {}
for cnt in range(n):
(k, v) = [tmp for tmp in input().split()]
dic[k] = v
words = input().split()
for word in words:
if word in dic:
print(dic[word], end=' kachal! ')
else:
print(end='kachal! ') |
def is_superset(A, B, count):
if A == B or len(A) < len(B):
count = count
elif A.issuperset(B):
count = count + 1
return count
if __name__ == "__main__":
A = set(map(int, input().split())) # Set A elements
n = int(input()) # no. of other sets
count = 0
for i in range(n):
set_B = set(map(int, input().split()))
count = is_superset(A, set_B, count)
if count == n:
print(True, end="")
else:
print(False, end="")
# Input
# 1 2 3 4 5 6 7 8 9 10 11 12 23 45 84 78
# 2
# 1 2 3 4 5
# 100 11 12
# Output
# False
# Strict superset
# Set([1,3,4]) is a strict superset of set([1,3]).
# Set([1,3,4]) is not a strict superset of set([1,3,4]).
# Set([1,3,4]) is not a strict superset of set([1,3,5]).
| def is_superset(A, B, count):
if A == B or len(A) < len(B):
count = count
elif A.issuperset(B):
count = count + 1
return count
if __name__ == '__main__':
a = set(map(int, input().split()))
n = int(input())
count = 0
for i in range(n):
set_b = set(map(int, input().split()))
count = is_superset(A, set_B, count)
if count == n:
print(True, end='')
else:
print(False, end='') |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
def go() :
return {"id":10, "sequence":"chen"}
def go2(a,b,c):
return str({"id":b, "sequence":"chen"})
print('chen') | def go():
return {'id': 10, 'sequence': 'chen'}
def go2(a, b, c):
return str({'id': b, 'sequence': 'chen'})
print('chen') |
# Starting values (of global variables)
def get_response(text):
print("")
print(text)
selection = input()
return selection
class CoffeeMachine:
def __init__(self, w, m, b, c, dollars):
self.water = w
self.milk = m
self.beans = b
self.cups = c
self.money = dollars
def remaining(self):
print("")
print("The coffee machine has:")
print(str(self.water) + " of water")
print(str(self.milk) + " of milk")
print(str(self.beans) + " of coffee beans")
print(str(self.cups) + " of disposable cups")
print("$" + str(self.money) + " of money")
def enough(self, w, m, b, c):
# checks if there is enough stock for sale
if self.water - w < 0:
return "water"
elif self.milk - m < 0:
return "milk"
elif self.beans - b < 0:
return "beans"
elif self.cups - c < 0:
return "cups"
else:
return "ok"
def buy(self):
coffee_type = get_response("What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino: ")
if coffee_type == "1":
# Espresso:
resource = self.enough(250, 0, 16, 1)
if resource == "ok":
self.water -= 250
self.milk -= 0
self.beans -= 16
self.cups -= 1
self.money += 4
print("I have enough resources, making you a coffee!")
else:
print("Sorry, not enough " + resource + "!")
elif coffee_type == "2":
# Latte:
resource = self.enough(350, 75, 20, 1)
if resource == "ok":
self.water -= 350
self.milk -= 75
self.beans -= 20
self.cups -= 1
self.money += 7
print("I have enough resources, making you a coffee!")
else:
print("Sorry, not enough " + resource + "!")
elif coffee_type == "3":
# Cappuccino:
resource = self.enough(200, 100, 12, 1)
if resource == "ok":
self.water -= 200
self.milk -= 100
self.beans -= 12
self.cups -= 1
self.money += 6
print("I have enough resources, making you a coffee!")
else:
print("Sorry, not enough " + resource + "!")
def fill(self):
self.water += int(get_response("Write how many ml of water do you want to add: "))
self.milk += int(get_response("Write how many ml of milk do you want to add: "))
self.beans += int(get_response("Write how many grams of coffee beans do you want to add: "))
self.cups += int(get_response("Write how many disposable cups of coffee do you want to add: "))
def take(self):
print("I gave you $" + str(self.money))
self.money = 0
# Main programs
command = ""
machine = CoffeeMachine(400, 540, 120, 9, 550)
while command != "exit":
command = get_response("Write action (buy, fill, take, remaining, exit): ")
if command == "buy":
machine.buy()
elif command == "fill":
machine.fill()
elif command == "take":
machine.take()
elif command == "remaining":
machine.remaining()
| def get_response(text):
print('')
print(text)
selection = input()
return selection
class Coffeemachine:
def __init__(self, w, m, b, c, dollars):
self.water = w
self.milk = m
self.beans = b
self.cups = c
self.money = dollars
def remaining(self):
print('')
print('The coffee machine has:')
print(str(self.water) + ' of water')
print(str(self.milk) + ' of milk')
print(str(self.beans) + ' of coffee beans')
print(str(self.cups) + ' of disposable cups')
print('$' + str(self.money) + ' of money')
def enough(self, w, m, b, c):
if self.water - w < 0:
return 'water'
elif self.milk - m < 0:
return 'milk'
elif self.beans - b < 0:
return 'beans'
elif self.cups - c < 0:
return 'cups'
else:
return 'ok'
def buy(self):
coffee_type = get_response('What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino: ')
if coffee_type == '1':
resource = self.enough(250, 0, 16, 1)
if resource == 'ok':
self.water -= 250
self.milk -= 0
self.beans -= 16
self.cups -= 1
self.money += 4
print('I have enough resources, making you a coffee!')
else:
print('Sorry, not enough ' + resource + '!')
elif coffee_type == '2':
resource = self.enough(350, 75, 20, 1)
if resource == 'ok':
self.water -= 350
self.milk -= 75
self.beans -= 20
self.cups -= 1
self.money += 7
print('I have enough resources, making you a coffee!')
else:
print('Sorry, not enough ' + resource + '!')
elif coffee_type == '3':
resource = self.enough(200, 100, 12, 1)
if resource == 'ok':
self.water -= 200
self.milk -= 100
self.beans -= 12
self.cups -= 1
self.money += 6
print('I have enough resources, making you a coffee!')
else:
print('Sorry, not enough ' + resource + '!')
def fill(self):
self.water += int(get_response('Write how many ml of water do you want to add: '))
self.milk += int(get_response('Write how many ml of milk do you want to add: '))
self.beans += int(get_response('Write how many grams of coffee beans do you want to add: '))
self.cups += int(get_response('Write how many disposable cups of coffee do you want to add: '))
def take(self):
print('I gave you $' + str(self.money))
self.money = 0
command = ''
machine = coffee_machine(400, 540, 120, 9, 550)
while command != 'exit':
command = get_response('Write action (buy, fill, take, remaining, exit): ')
if command == 'buy':
machine.buy()
elif command == 'fill':
machine.fill()
elif command == 'take':
machine.take()
elif command == 'remaining':
machine.remaining() |
def encryptRailFence(text, key):
rail = [['\n' for i in range(len(text))]
for j in range(key)]
dir_down = False
row, col = 0, 0
for i in range(len(text)):
if (row == 0) or (row == key - 1):
dir_down = not dir_down
rail[row][col] = text[i]
col += 1
if dir_down:
row += 1
else:
row -= 1
result = []
for i in range(key):
for j in range(len(text)):
if rail[i][j] != '\n':
result.append(rail[i][j])
return("" . join(result))
def decryptRailFence(cipher, key):
rail = [['\n' for i in range(len(cipher))]
for j in range(key)]
dir_down = None
row, col = 0, 0
for i in range(len(cipher)):
if row == 0:
dir_down = True
if row == key - 1:
dir_down = False
rail[row][col] = '*'
col += 1
if dir_down:
row += 1
else:
row -= 1
index = 0
for i in range(key):
for j in range(len(cipher)):
if ((rail[i][j] == '*') and
(index < len(cipher))):
rail[i][j] = cipher[index]
index += 1
result = []
row, col = 0, 0
for i in range(len(cipher)):
# check the direction of flow
if row == 0:
dir_down = True
if row == key-1:
dir_down = False
if (rail[row][col] != '*'):
result.append(rail[row][col])
col += 1
if dir_down:
row += 1
else:
row -= 1
return("".join(result))
if __name__ == "__main__":
s=input("Enter the text:")
n=int(input("Key:"))
str=encryptRailFence(s, n)
print(f"Encrypted Text:{str}")
print(f"Decrypted Text:{decryptRailFence(str, n)}")
| def encrypt_rail_fence(text, key):
rail = [['\n' for i in range(len(text))] for j in range(key)]
dir_down = False
(row, col) = (0, 0)
for i in range(len(text)):
if row == 0 or row == key - 1:
dir_down = not dir_down
rail[row][col] = text[i]
col += 1
if dir_down:
row += 1
else:
row -= 1
result = []
for i in range(key):
for j in range(len(text)):
if rail[i][j] != '\n':
result.append(rail[i][j])
return ''.join(result)
def decrypt_rail_fence(cipher, key):
rail = [['\n' for i in range(len(cipher))] for j in range(key)]
dir_down = None
(row, col) = (0, 0)
for i in range(len(cipher)):
if row == 0:
dir_down = True
if row == key - 1:
dir_down = False
rail[row][col] = '*'
col += 1
if dir_down:
row += 1
else:
row -= 1
index = 0
for i in range(key):
for j in range(len(cipher)):
if rail[i][j] == '*' and index < len(cipher):
rail[i][j] = cipher[index]
index += 1
result = []
(row, col) = (0, 0)
for i in range(len(cipher)):
if row == 0:
dir_down = True
if row == key - 1:
dir_down = False
if rail[row][col] != '*':
result.append(rail[row][col])
col += 1
if dir_down:
row += 1
else:
row -= 1
return ''.join(result)
if __name__ == '__main__':
s = input('Enter the text:')
n = int(input('Key:'))
str = encrypt_rail_fence(s, n)
print(f'Encrypted Text:{str}')
print(f'Decrypted Text:{decrypt_rail_fence(str, n)}') |
array_a = [1, 2, 3, 5]
array_b = [4, 6, 7, 8]
def merge(array1, array2):
idx_a = 0
idx_b = 0
len_a = len(array1)
len_b = len(array2)
res = []
while True:
if array1[idx_a] > array2[idx_b]:
res.append(array2[idx_b])
idx_b += 1
else:
res.append(array1[idx_a])
idx_a += 1
if idx_a == len_a -1 or idx_b == len_b - 1:
break
if idx_b == len_b - 1:
return res + array1[idx_a:]
else:
return res + array2[idx_b:]
print(merge(array_a, array_b))
| array_a = [1, 2, 3, 5]
array_b = [4, 6, 7, 8]
def merge(array1, array2):
idx_a = 0
idx_b = 0
len_a = len(array1)
len_b = len(array2)
res = []
while True:
if array1[idx_a] > array2[idx_b]:
res.append(array2[idx_b])
idx_b += 1
else:
res.append(array1[idx_a])
idx_a += 1
if idx_a == len_a - 1 or idx_b == len_b - 1:
break
if idx_b == len_b - 1:
return res + array1[idx_a:]
else:
return res + array2[idx_b:]
print(merge(array_a, array_b)) |
class Scenario:
def __init__(self, start, end, mmap, dvmap, tc_id: int, park=None, side=0):
self.start = start
self.end = end
self.map = mmap
self.ID = str(tc_id)
self.park = park
self.dvmap = dvmap
self.side = side
def __str__(self):
return str(self.__class__) + ": " + str(self.__dict__) | class Scenario:
def __init__(self, start, end, mmap, dvmap, tc_id: int, park=None, side=0):
self.start = start
self.end = end
self.map = mmap
self.ID = str(tc_id)
self.park = park
self.dvmap = dvmap
self.side = side
def __str__(self):
return str(self.__class__) + ': ' + str(self.__dict__) |
# Loops
# Loops are repeating segments of code, and come in two types, while and for. Lets start with a "for" loop.
# "for" loops can be expressed in the following manner:
for i in range(0, 9):
print(i)
# For loops work by repeating until the loop has executed a specific number of times, or until all values in a data
# structure have been accessed. We will touch more on using for loops with data structures later in this lesson. But
# first, lets dissect what this code segment is doing.
# We first see the characters "for", which indicate to the computer that the following code will be a for loop.
# The next part of the code is known as the "iterable", and in this example, every time the code is run it will be
# increased in value by one.
# Following the iterable, we see what looks like a function, and it is! Don't worry about what it is too much, all
# you need to know right now is that it sets the range for this function, meaning that it sets the starting value, and
# the value at which the for loop will terminate at. This value is stored in the iterable "i". In the above example, the
# loop will stop when i reaches the value of 9, not before or after, but exactly on. This is checked at the start of
# each loop execution ("iteration").
# What follows the semicolon is what action the for loop will perform, in this case, it will simply print the current
# value of i. This value will increase with each iteration of the loop. i is increased by one at the end of each
# iteration.
# If you have a keen eye, you may have noticed that the loop only goes from zero to eight! You may think this is a
# bug, as (0, 9) is clearly specified as the range for the function, but you must remember lesson zero and how loops
# work. The value starts at zero, which is printed to console, and terminates at 9, which is checked at the beginning
# of each iteration. This means that nine would never be printed, as nine is the number at which the loop terminates at.
# If you count how many numbers are printed to console, you'll also notice nine numbers are there, since you began
# counting at zero.
exampleList = [
"This", "Is", "a", "Demonstration"
]
for i in exampleList:
print(i)
# In this loop, you'll see we have dropped range() in favor of a list! This means that the loop will execute until
# every value in the loop becomes "i". Since we are calling print() for each value, all of the strings stored inside
# the list will be printed to console. You can do many advanced things with this, as you will soon learn.
# While loops
condition = True
while condition:
print("Success")
condition = False
# While loops are a form of conditional statement, and will only run while the condition being checked against is
# True (by default), or anything you change it to. Many of the ways to interact with standard conditional statements
# also apply to while loops.
condition = False
while not condition:
print("Success")
condition = True
# And of course, strings work too!
exampleString = "rain"
while exampleString == "rain":
print("Success")
exampleString = "water"
# While loops are important, because they have no definite end. You may need to execute one block of code until a
# certain condition is met, for example, in web scraping, you may check a website until you find a certain block
# of text. You may also want to use while loops in user interfaces to continually ask questions, or to keep a certain
# block of code running in order to continually execute your program.
# To finish this lesson, try out both kinds of loops for yourself! Feel free to ask any questions.
| for i in range(0, 9):
print(i)
example_list = ['This', 'Is', 'a', 'Demonstration']
for i in exampleList:
print(i)
condition = True
while condition:
print('Success')
condition = False
condition = False
while not condition:
print('Success')
condition = True
example_string = 'rain'
while exampleString == 'rain':
print('Success')
example_string = 'water' |
# Given an integer array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3]....
#
# You may assume the input array always has a valid answer.
def wiggleSort(nums):
nums.sort()
mid = (len(nums) + 1) // 2
left, right = nums[:mid], nums[mid:]
nums[::2] = left[::-1]
nums[1::2] = right[::-1]
nums = [1,3,2,2,3,1]
wiggleSort(nums)
print(nums)
| def wiggle_sort(nums):
nums.sort()
mid = (len(nums) + 1) // 2
(left, right) = (nums[:mid], nums[mid:])
nums[::2] = left[::-1]
nums[1::2] = right[::-1]
nums = [1, 3, 2, 2, 3, 1]
wiggle_sort(nums)
print(nums) |
l = [1,2,3,4,5]
print(l)
def mul_by2(num):
return num*2
for result in map(mul_by2,l):
print(result)
| l = [1, 2, 3, 4, 5]
print(l)
def mul_by2(num):
return num * 2
for result in map(mul_by2, l):
print(result) |
new_npc_stats = {
'base_stats': {
'vit': 4,
'dex': 4,
'str': 4,
'int': 4,
'agility': 8,
'toughness': 9,
},
'stats': {
'max_hp': 'from vit', # vit*hp_per_vit + lvl*hp_per_lvl
'max_mana': 'from int?',
'armor': 'from str and toughness',
'magic_resistance': 'from toughness', # and int?
'speed': 'from dex and agility',
'dodge': 'from dex and speed',
'crit_chance': 'from dex',
'crit_dmg': 'from dex',
},
'storage': {
'equipped items': 'armor, weapons, ...',
'spell book': 'spells / abilities',
'potions': '', # in party?
'party': 'party instance'
},
'tracked_values': {
'ct': 1000, # when c reaches this, unit gets a turn
'c': 0, # holds current charge value - +speed each clock tick in battle
'status_effects': [],
'elemental_resistance': 0, # from items (and toughness?)
'hp': '',
'mana': '',
}
}
| new_npc_stats = {'base_stats': {'vit': 4, 'dex': 4, 'str': 4, 'int': 4, 'agility': 8, 'toughness': 9}, 'stats': {'max_hp': 'from vit', 'max_mana': 'from int?', 'armor': 'from str and toughness', 'magic_resistance': 'from toughness', 'speed': 'from dex and agility', 'dodge': 'from dex and speed', 'crit_chance': 'from dex', 'crit_dmg': 'from dex'}, 'storage': {'equipped items': 'armor, weapons, ...', 'spell book': 'spells / abilities', 'potions': '', 'party': 'party instance'}, 'tracked_values': {'ct': 1000, 'c': 0, 'status_effects': [], 'elemental_resistance': 0, 'hp': '', 'mana': ''}} |
#Create a function that accept a name and return reverse of this
def reverse_name(a):
reverse = ""
for i in a:
reverse = i + reverse
return reverse
name = input("Enter the NAME ")
result = reverse_name(name)
print("\nThe Reverse name is", result.title())
| def reverse_name(a):
reverse = ''
for i in a:
reverse = i + reverse
return reverse
name = input('Enter the NAME ')
result = reverse_name(name)
print('\nThe Reverse name is', result.title()) |
def generate(n, diff, left, right):
if n > 9: return
if n and (2 * abs(diff) <= n):
if n == 1:
generate(n - 1, diff, left, "0" + right)
generate(n - 1, diff, left, "1" + right)
if left != "":
generate(n - 2, diff, left + "0", right + "0")
generate(n - 2, diff - 1, left + "0", right + "1")
generate(n - 2, diff, left + "1", right + "1")
generate(n - 2, diff + 1, left + "1", right + "0")
if n == 0 and diff == 0:
print(left + right)
generate(int(input()), 0, "", "") | def generate(n, diff, left, right):
if n > 9:
return
if n and 2 * abs(diff) <= n:
if n == 1:
generate(n - 1, diff, left, '0' + right)
generate(n - 1, diff, left, '1' + right)
if left != '':
generate(n - 2, diff, left + '0', right + '0')
generate(n - 2, diff - 1, left + '0', right + '1')
generate(n - 2, diff, left + '1', right + '1')
generate(n - 2, diff + 1, left + '1', right + '0')
if n == 0 and diff == 0:
print(left + right)
generate(int(input()), 0, '', '') |
#!/usr/bin/python3
# coding=utf-8
class LoopNotFoundError(Exception):
def __init__(self, message):
super().__init__(message)
| class Loopnotfounderror(Exception):
def __init__(self, message):
super().__init__(message) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.