content
stringlengths 7
1.05M
| fixed_cases
stringlengths 1
1.28M
|
---|---|
# https://app.codesignal.com/arcade/intro/level-1/jwr339Kq6e3LQTsfa
# Write a function that returns the sum of two numbers.
def add(param1: int = 0, param2: int = 0) -> int:
if (
isinstance(param1, int)
and isinstance(param2, int)
and -1000 <= param1 <= 1000
and -1000 <= param2 <= 1000
):
return param1 + param2
return 0
|
def add(param1: int=0, param2: int=0) -> int:
if isinstance(param1, int) and isinstance(param2, int) and (-1000 <= param1 <= 1000) and (-1000 <= param2 <= 1000):
return param1 + param2
return 0
|
n=int(input())
cus=[int(input()) for i in range(n)]
m=int(input())
price=[int(input()) for i in range(m)]
price.sort(reverse=True)
cus.sort(reverse=True)
answer=0
C,P=0,0
while C<n and P<m:
if cus[C]>=price[P]:
answer+=price[P]
C+=1
P+=1
else:
P+=1
print(answer)
|
n = int(input())
cus = [int(input()) for i in range(n)]
m = int(input())
price = [int(input()) for i in range(m)]
price.sort(reverse=True)
cus.sort(reverse=True)
answer = 0
(c, p) = (0, 0)
while C < n and P < m:
if cus[C] >= price[P]:
answer += price[P]
c += 1
p += 1
else:
p += 1
print(answer)
|
# https://adventofcode.com/2021/day/17#part2
def solve(target):
(x1, x2), (y1, y2) = target
count = 0
for i in range(-1000, 1000): # wew, try bruteforce
for j in range(1, x2+1):
hit = check(j, i, target)
if hit:
count += 1
return count
def check(a, b, target):
(x1, x2), (y1, y2) = target
x, y = 0, 0
vx, vy = a, b
while True:
# Update current position
x = x + vx
y = y + vy
# Update velocity change after this step
vx = vx - 1 if vx > 0 else 0 if vx == 0 else vx + 1
vy = vy - 1
if x >= x1 and x <= x2 and y >= y1 and y <= y2:
return True
if x > x2 or y < y1:
return False
def input_processing(content):
content = content[len('target area: '):]
x_coords, y_coords = content.split(',')
x1, x2 = x_coords.strip()[len('x='):].split('..')
y1, y2 = y_coords.strip()[len('y='):].split('..')
return ((int(x1), int(x2)), (int(y1), int(y2)))
if __name__ == '__main__':
f = open('input.txt')
target = input_processing(f.read())
print(target)
res = solve(target)
print(res)
|
def solve(target):
((x1, x2), (y1, y2)) = target
count = 0
for i in range(-1000, 1000):
for j in range(1, x2 + 1):
hit = check(j, i, target)
if hit:
count += 1
return count
def check(a, b, target):
((x1, x2), (y1, y2)) = target
(x, y) = (0, 0)
(vx, vy) = (a, b)
while True:
x = x + vx
y = y + vy
vx = vx - 1 if vx > 0 else 0 if vx == 0 else vx + 1
vy = vy - 1
if x >= x1 and x <= x2 and (y >= y1) and (y <= y2):
return True
if x > x2 or y < y1:
return False
def input_processing(content):
content = content[len('target area: '):]
(x_coords, y_coords) = content.split(',')
(x1, x2) = x_coords.strip()[len('x='):].split('..')
(y1, y2) = y_coords.strip()[len('y='):].split('..')
return ((int(x1), int(x2)), (int(y1), int(y2)))
if __name__ == '__main__':
f = open('input.txt')
target = input_processing(f.read())
print(target)
res = solve(target)
print(res)
|
vegetables = [
{
"type":"fruit",
"items":[
{
"color":"green",
"items":[
"kiwi",
"grape"
]
},
{
"color":"red",
"items":[
"strawberry",
"apple"
]
}
]
},
{
"type":"vegs",
"items":[
{
"color":"green",
"items":[
"lettuce"
]
},
{
"color":"red",
"items":[
"pepper",
]
}
]
}
]
a = list(filter(lambda i: i[ 'type' ] == 'fruit', vegetables))
print (a[0]['items'][0]['items'][0])
|
vegetables = [{'type': 'fruit', 'items': [{'color': 'green', 'items': ['kiwi', 'grape']}, {'color': 'red', 'items': ['strawberry', 'apple']}]}, {'type': 'vegs', 'items': [{'color': 'green', 'items': ['lettuce']}, {'color': 'red', 'items': ['pepper']}]}]
a = list(filter(lambda i: i['type'] == 'fruit', vegetables))
print(a[0]['items'][0]['items'][0])
|
__all__ = ["reservation", "user_info", "calendar"]
for _import in __all__:
__import__(f"{__package__}.{_import}")
|
__all__ = ['reservation', 'user_info', 'calendar']
for _import in __all__:
__import__(f'{__package__}.{_import}')
|
# Generated by h2py from Include\scintilla.h
# Included from BaseTsd.h
def HandleToUlong(h): return HandleToULong(h)
def UlongToHandle(ul): return ULongToHandle(ul)
def UlongToPtr(ul): return ULongToPtr(ul)
def UintToPtr(ui): return UIntToPtr(ui)
INVALID_POSITION = -1
SCI_START = 2000
SCI_OPTIONAL_START = 3000
SCI_LEXER_START = 4000
SCI_ADDTEXT = 2001
SCI_ADDSTYLEDTEXT = 2002
SCI_INSERTTEXT = 2003
SCI_CLEARALL = 2004
SCI_CLEARDOCUMENTSTYLE = 2005
SCI_GETLENGTH = 2006
SCI_GETCHARAT = 2007
SCI_GETCURRENTPOS = 2008
SCI_GETANCHOR = 2009
SCI_GETSTYLEAT = 2010
SCI_REDO = 2011
SCI_SETUNDOCOLLECTION = 2012
SCI_SELECTALL = 2013
SCI_SETSAVEPOINT = 2014
SCI_GETSTYLEDTEXT = 2015
SCI_CANREDO = 2016
SCI_MARKERLINEFROMHANDLE = 2017
SCI_MARKERDELETEHANDLE = 2018
SCI_GETUNDOCOLLECTION = 2019
SCWS_INVISIBLE = 0
SCWS_VISIBLEALWAYS = 1
SCWS_VISIBLEAFTERINDENT = 2
SCI_GETVIEWWS = 2020
SCI_SETVIEWWS = 2021
SCI_POSITIONFROMPOINT = 2022
SCI_POSITIONFROMPOINTCLOSE = 2023
SCI_GOTOLINE = 2024
SCI_GOTOPOS = 2025
SCI_SETANCHOR = 2026
SCI_GETCURLINE = 2027
SCI_GETENDSTYLED = 2028
SC_EOL_CRLF = 0
SC_EOL_CR = 1
SC_EOL_LF = 2
SCI_CONVERTEOLS = 2029
SCI_GETEOLMODE = 2030
SCI_SETEOLMODE = 2031
SCI_STARTSTYLING = 2032
SCI_SETSTYLING = 2033
SCI_GETBUFFEREDDRAW = 2034
SCI_SETBUFFEREDDRAW = 2035
SCI_SETTABWIDTH = 2036
SCI_GETTABWIDTH = 2121
SC_CP_UTF8 = 65001
SC_CP_DBCS = 1
SCI_SETCODEPAGE = 2037
SCI_SETUSEPALETTE = 2039
MARKER_MAX = 31
SC_MARK_CIRCLE = 0
SC_MARK_ROUNDRECT = 1
SC_MARK_ARROW = 2
SC_MARK_SMALLRECT = 3
SC_MARK_SHORTARROW = 4
SC_MARK_EMPTY = 5
SC_MARK_ARROWDOWN = 6
SC_MARK_MINUS = 7
SC_MARK_PLUS = 8
SC_MARK_VLINE = 9
SC_MARK_LCORNER = 10
SC_MARK_TCORNER = 11
SC_MARK_BOXPLUS = 12
SC_MARK_BOXPLUSCONNECTED = 13
SC_MARK_BOXMINUS = 14
SC_MARK_BOXMINUSCONNECTED = 15
SC_MARK_LCORNERCURVE = 16
SC_MARK_TCORNERCURVE = 17
SC_MARK_CIRCLEPLUS = 18
SC_MARK_CIRCLEPLUSCONNECTED = 19
SC_MARK_CIRCLEMINUS = 20
SC_MARK_CIRCLEMINUSCONNECTED = 21
SC_MARK_BACKGROUND = 22
SC_MARK_DOTDOTDOT = 23
SC_MARK_ARROWS = 24
SC_MARK_PIXMAP = 25
SC_MARK_CHARACTER = 10000
SC_MARKNUM_FOLDEREND = 25
SC_MARKNUM_FOLDEROPENMID = 26
SC_MARKNUM_FOLDERMIDTAIL = 27
SC_MARKNUM_FOLDERTAIL = 28
SC_MARKNUM_FOLDERSUB = 29
SC_MARKNUM_FOLDER = 30
SC_MARKNUM_FOLDEROPEN = 31
SC_MASK_FOLDERS = (-33554432)
SCI_MARKERDEFINE = 2040
SCI_MARKERSETFORE = 2041
SCI_MARKERSETBACK = 2042
SCI_MARKERADD = 2043
SCI_MARKERDELETE = 2044
SCI_MARKERDELETEALL = 2045
SCI_MARKERGET = 2046
SCI_MARKERNEXT = 2047
SCI_MARKERPREVIOUS = 2048
SCI_MARKERDEFINEPIXMAP = 2049
SC_MARGIN_SYMBOL = 0
SC_MARGIN_NUMBER = 1
SCI_SETMARGINTYPEN = 2240
SCI_GETMARGINTYPEN = 2241
SCI_SETMARGINWIDTHN = 2242
SCI_GETMARGINWIDTHN = 2243
SCI_SETMARGINMASKN = 2244
SCI_GETMARGINMASKN = 2245
SCI_SETMARGINSENSITIVEN = 2246
SCI_GETMARGINSENSITIVEN = 2247
STYLE_DEFAULT = 32
STYLE_LINENUMBER = 33
STYLE_BRACELIGHT = 34
STYLE_BRACEBAD = 35
STYLE_CONTROLCHAR = 36
STYLE_INDENTGUIDE = 37
STYLE_LASTPREDEFINED = 39
STYLE_MAX = 127
SC_CHARSET_ANSI = 0
SC_CHARSET_DEFAULT = 1
SC_CHARSET_BALTIC = 186
SC_CHARSET_CHINESEBIG5 = 136
SC_CHARSET_EASTEUROPE = 238
SC_CHARSET_GB2312 = 134
SC_CHARSET_GREEK = 161
SC_CHARSET_HANGUL = 129
SC_CHARSET_MAC = 77
SC_CHARSET_OEM = 255
SC_CHARSET_RUSSIAN = 204
SC_CHARSET_SHIFTJIS = 128
SC_CHARSET_SYMBOL = 2
SC_CHARSET_TURKISH = 162
SC_CHARSET_JOHAB = 130
SC_CHARSET_HEBREW = 177
SC_CHARSET_ARABIC = 178
SC_CHARSET_VIETNAMESE = 163
SC_CHARSET_THAI = 222
SCI_STYLECLEARALL = 2050
SCI_STYLESETFORE = 2051
SCI_STYLESETBACK = 2052
SCI_STYLESETBOLD = 2053
SCI_STYLESETITALIC = 2054
SCI_STYLESETSIZE = 2055
SCI_STYLESETFONT = 2056
SCI_STYLESETEOLFILLED = 2057
SCI_STYLERESETDEFAULT = 2058
SCI_STYLESETUNDERLINE = 2059
SC_CASE_MIXED = 0
SC_CASE_UPPER = 1
SC_CASE_LOWER = 2
SCI_STYLESETCASE = 2060
SCI_STYLESETCHARACTERSET = 2066
SCI_STYLESETHOTSPOT = 2409
SCI_SETSELFORE = 2067
SCI_SETSELBACK = 2068
SCI_SETCARETFORE = 2069
SCI_ASSIGNCMDKEY = 2070
SCI_CLEARCMDKEY = 2071
SCI_CLEARALLCMDKEYS = 2072
SCI_SETSTYLINGEX = 2073
SCI_STYLESETVISIBLE = 2074
SCI_GETCARETPERIOD = 2075
SCI_SETCARETPERIOD = 2076
SCI_SETWORDCHARS = 2077
SCI_BEGINUNDOACTION = 2078
SCI_ENDUNDOACTION = 2079
INDIC_MAX = 7
INDIC_PLAIN = 0
INDIC_SQUIGGLE = 1
INDIC_TT = 2
INDIC_DIAGONAL = 3
INDIC_STRIKE = 4
INDIC_HIDDEN = 5
INDIC_BOX = 6
INDIC0_MASK = 0x20
INDIC1_MASK = 0x40
INDIC2_MASK = 0x80
INDICS_MASK = 0xE0
SCI_INDICSETSTYLE = 2080
SCI_INDICGETSTYLE = 2081
SCI_INDICSETFORE = 2082
SCI_INDICGETFORE = 2083
SCI_SETWHITESPACEFORE = 2084
SCI_SETWHITESPACEBACK = 2085
SCI_SETSTYLEBITS = 2090
SCI_GETSTYLEBITS = 2091
SCI_SETLINESTATE = 2092
SCI_GETLINESTATE = 2093
SCI_GETMAXLINESTATE = 2094
SCI_GETCARETLINEVISIBLE = 2095
SCI_SETCARETLINEVISIBLE = 2096
SCI_GETCARETLINEBACK = 2097
SCI_SETCARETLINEBACK = 2098
SCI_STYLESETCHANGEABLE = 2099
SCI_AUTOCSHOW = 2100
SCI_AUTOCCANCEL = 2101
SCI_AUTOCACTIVE = 2102
SCI_AUTOCPOSSTART = 2103
SCI_AUTOCCOMPLETE = 2104
SCI_AUTOCSTOPS = 2105
SCI_AUTOCSETSEPARATOR = 2106
SCI_AUTOCGETSEPARATOR = 2107
SCI_AUTOCSELECT = 2108
SCI_AUTOCSETCANCELATSTART = 2110
SCI_AUTOCGETCANCELATSTART = 2111
SCI_AUTOCSETFILLUPS = 2112
SCI_AUTOCSETCHOOSESINGLE = 2113
SCI_AUTOCGETCHOOSESINGLE = 2114
SCI_AUTOCSETIGNORECASE = 2115
SCI_AUTOCGETIGNORECASE = 2116
SCI_USERLISTSHOW = 2117
SCI_AUTOCSETAUTOHIDE = 2118
SCI_AUTOCGETAUTOHIDE = 2119
SCI_AUTOCSETDROPRESTOFWORD = 2270
SCI_AUTOCGETDROPRESTOFWORD = 2271
SCI_REGISTERIMAGE = 2405
SCI_CLEARREGISTEREDIMAGES = 2408
SCI_AUTOCGETTYPESEPARATOR = 2285
SCI_AUTOCSETTYPESEPARATOR = 2286
SCI_SETINDENT = 2122
SCI_GETINDENT = 2123
SCI_SETUSETABS = 2124
SCI_GETUSETABS = 2125
SCI_SETLINEINDENTATION = 2126
SCI_GETLINEINDENTATION = 2127
SCI_GETLINEINDENTPOSITION = 2128
SCI_GETCOLUMN = 2129
SCI_SETHSCROLLBAR = 2130
SCI_GETHSCROLLBAR = 2131
SCI_SETINDENTATIONGUIDES = 2132
SCI_GETINDENTATIONGUIDES = 2133
SCI_SETHIGHLIGHTGUIDE = 2134
SCI_GETHIGHLIGHTGUIDE = 2135
SCI_GETLINEENDPOSITION = 2136
SCI_GETCODEPAGE = 2137
SCI_GETCARETFORE = 2138
SCI_GETUSEPALETTE = 2139
SCI_GETREADONLY = 2140
SCI_SETCURRENTPOS = 2141
SCI_SETSELECTIONSTART = 2142
SCI_GETSELECTIONSTART = 2143
SCI_SETSELECTIONEND = 2144
SCI_GETSELECTIONEND = 2145
SCI_SETPRINTMAGNIFICATION = 2146
SCI_GETPRINTMAGNIFICATION = 2147
SC_PRINT_NORMAL = 0
SC_PRINT_INVERTLIGHT = 1
SC_PRINT_BLACKONWHITE = 2
SC_PRINT_COLOURONWHITE = 3
SC_PRINT_COLOURONWHITEDEFAULTBG = 4
SCI_SETPRINTCOLOURMODE = 2148
SCI_GETPRINTCOLOURMODE = 2149
SCFIND_WHOLEWORD = 2
SCFIND_MATCHCASE = 4
SCFIND_WORDSTART = 0x00100000
SCFIND_REGEXP = 0x00200000
SCFIND_POSIX = 0x00400000
SCI_FINDTEXT = 2150
SCI_FORMATRANGE = 2151
SCI_GETFIRSTVISIBLELINE = 2152
SCI_GETLINE = 2153
SCI_GETLINECOUNT = 2154
SCI_SETMARGINLEFT = 2155
SCI_GETMARGINLEFT = 2156
SCI_SETMARGINRIGHT = 2157
SCI_GETMARGINRIGHT = 2158
SCI_GETMODIFY = 2159
SCI_SETSEL = 2160
SCI_GETSELTEXT = 2161
SCI_GETTEXTRANGE = 2162
SCI_HIDESELECTION = 2163
SCI_POINTXFROMPOSITION = 2164
SCI_POINTYFROMPOSITION = 2165
SCI_LINEFROMPOSITION = 2166
SCI_POSITIONFROMLINE = 2167
SCI_LINESCROLL = 2168
SCI_SCROLLCARET = 2169
SCI_REPLACESEL = 2170
SCI_SETREADONLY = 2171
SCI_NULL = 2172
SCI_CANPASTE = 2173
SCI_CANUNDO = 2174
SCI_EMPTYUNDOBUFFER = 2175
SCI_UNDO = 2176
SCI_CUT = 2177
SCI_COPY = 2178
SCI_PASTE = 2179
SCI_CLEAR = 2180
SCI_SETTEXT = 2181
SCI_GETTEXT = 2182
SCI_GETTEXTLENGTH = 2183
SCI_GETDIRECTFUNCTION = 2184
SCI_GETDIRECTPOINTER = 2185
SCI_SETOVERTYPE = 2186
SCI_GETOVERTYPE = 2187
SCI_SETCARETWIDTH = 2188
SCI_GETCARETWIDTH = 2189
SCI_SETTARGETSTART = 2190
SCI_GETTARGETSTART = 2191
SCI_SETTARGETEND = 2192
SCI_GETTARGETEND = 2193
SCI_REPLACETARGET = 2194
SCI_REPLACETARGETRE = 2195
SCI_SEARCHINTARGET = 2197
SCI_SETSEARCHFLAGS = 2198
SCI_GETSEARCHFLAGS = 2199
SCI_CALLTIPSHOW = 2200
SCI_CALLTIPCANCEL = 2201
SCI_CALLTIPACTIVE = 2202
SCI_CALLTIPPOSSTART = 2203
SCI_CALLTIPSETHLT = 2204
SCI_CALLTIPSETBACK = 2205
SCI_CALLTIPSETFORE = 2206
SCI_CALLTIPSETFOREHLT = 2207
SCI_VISIBLEFROMDOCLINE = 2220
SCI_DOCLINEFROMVISIBLE = 2221
SC_FOLDLEVELBASE = 0x400
SC_FOLDLEVELWHITEFLAG = 0x1000
SC_FOLDLEVELHEADERFLAG = 0x2000
SC_FOLDLEVELBOXHEADERFLAG = 0x4000
SC_FOLDLEVELBOXFOOTERFLAG = 0x8000
SC_FOLDLEVELCONTRACTED = 0x10000
SC_FOLDLEVELUNINDENT = 0x20000
SC_FOLDLEVELNUMBERMASK = 0x0FFF
SCI_SETFOLDLEVEL = 2222
SCI_GETFOLDLEVEL = 2223
SCI_GETLASTCHILD = 2224
SCI_GETFOLDPARENT = 2225
SCI_SHOWLINES = 2226
SCI_HIDELINES = 2227
SCI_GETLINEVISIBLE = 2228
SCI_SETFOLDEXPANDED = 2229
SCI_GETFOLDEXPANDED = 2230
SCI_TOGGLEFOLD = 2231
SCI_ENSUREVISIBLE = 2232
SC_FOLDFLAG_LINEBEFORE_EXPANDED = 0x0002
SC_FOLDFLAG_LINEBEFORE_CONTRACTED = 0x0004
SC_FOLDFLAG_LINEAFTER_EXPANDED = 0x0008
SC_FOLDFLAG_LINEAFTER_CONTRACTED = 0x0010
SC_FOLDFLAG_LEVELNUMBERS = 0x0040
SC_FOLDFLAG_BOX = 0x0001
SCI_SETFOLDFLAGS = 2233
SCI_ENSUREVISIBLEENFORCEPOLICY = 2234
SCI_SETTABINDENTS = 2260
SCI_GETTABINDENTS = 2261
SCI_SETBACKSPACEUNINDENTS = 2262
SCI_GETBACKSPACEUNINDENTS = 2263
SC_TIME_FOREVER = 10000000
SCI_SETMOUSEDWELLTIME = 2264
SCI_GETMOUSEDWELLTIME = 2265
SCI_WORDSTARTPOSITION = 2266
SCI_WORDENDPOSITION = 2267
SC_WRAP_NONE = 0
SC_WRAP_WORD = 1
SCI_SETWRAPMODE = 2268
SCI_GETWRAPMODE = 2269
SC_CACHE_NONE = 0
SC_CACHE_CARET = 1
SC_CACHE_PAGE = 2
SC_CACHE_DOCUMENT = 3
SCI_SETLAYOUTCACHE = 2272
SCI_GETLAYOUTCACHE = 2273
SCI_SETSCROLLWIDTH = 2274
SCI_GETSCROLLWIDTH = 2275
SCI_TEXTWIDTH = 2276
SCI_SETENDATLASTLINE = 2277
SCI_GETENDATLASTLINE = 2278
SCI_TEXTHEIGHT = 2279
SCI_SETVSCROLLBAR = 2280
SCI_GETVSCROLLBAR = 2281
SCI_APPENDTEXT = 2282
SCI_GETTWOPHASEDRAW = 2283
SCI_SETTWOPHASEDRAW = 2284
SCI_TARGETFROMSELECTION = 2287
SCI_LINESJOIN = 2288
SCI_LINESSPLIT = 2289
SCI_SETFOLDMARGINCOLOUR = 2290
SCI_SETFOLDMARGINHICOLOUR = 2291
SCI_LINEDOWN = 2300
SCI_LINEDOWNEXTEND = 2301
SCI_LINEUP = 2302
SCI_LINEUPEXTEND = 2303
SCI_CHARLEFT = 2304
SCI_CHARLEFTEXTEND = 2305
SCI_CHARRIGHT = 2306
SCI_CHARRIGHTEXTEND = 2307
SCI_WORDLEFT = 2308
SCI_WORDLEFTEXTEND = 2309
SCI_WORDRIGHT = 2310
SCI_WORDRIGHTEXTEND = 2311
SCI_HOME = 2312
SCI_HOMEEXTEND = 2313
SCI_LINEEND = 2314
SCI_LINEENDEXTEND = 2315
SCI_DOCUMENTSTART = 2316
SCI_DOCUMENTSTARTEXTEND = 2317
SCI_DOCUMENTEND = 2318
SCI_DOCUMENTENDEXTEND = 2319
SCI_PAGEUP = 2320
SCI_PAGEUPEXTEND = 2321
SCI_PAGEDOWN = 2322
SCI_PAGEDOWNEXTEND = 2323
SCI_EDITTOGGLEOVERTYPE = 2324
SCI_CANCEL = 2325
SCI_DELETEBACK = 2326
SCI_TAB = 2327
SCI_BACKTAB = 2328
SCI_NEWLINE = 2329
SCI_FORMFEED = 2330
SCI_VCHOME = 2331
SCI_VCHOMEEXTEND = 2332
SCI_ZOOMIN = 2333
SCI_ZOOMOUT = 2334
SCI_DELWORDLEFT = 2335
SCI_DELWORDRIGHT = 2336
SCI_LINECUT = 2337
SCI_LINEDELETE = 2338
SCI_LINETRANSPOSE = 2339
SCI_LINEDUPLICATE = 2404
SCI_LOWERCASE = 2340
SCI_UPPERCASE = 2341
SCI_LINESCROLLDOWN = 2342
SCI_LINESCROLLUP = 2343
SCI_DELETEBACKNOTLINE = 2344
SCI_HOMEDISPLAY = 2345
SCI_HOMEDISPLAYEXTEND = 2346
SCI_LINEENDDISPLAY = 2347
SCI_LINEENDDISPLAYEXTEND = 2348
SCI_HOMEWRAP = 2349
SCI_HOMEWRAPEXTEND = 2450
SCI_LINEENDWRAP = 2451
SCI_LINEENDWRAPEXTEND = 2452
SCI_VCHOMEWRAP = 2453
SCI_VCHOMEWRAPEXTEND = 2454
SCI_LINECOPY = 2455
SCI_MOVECARETINSIDEVIEW = 2401
SCI_LINELENGTH = 2350
SCI_BRACEHIGHLIGHT = 2351
SCI_BRACEBADLIGHT = 2352
SCI_BRACEMATCH = 2353
SCI_GETVIEWEOL = 2355
SCI_SETVIEWEOL = 2356
SCI_GETDOCPOINTER = 2357
SCI_SETDOCPOINTER = 2358
SCI_SETMODEVENTMASK = 2359
EDGE_NONE = 0
EDGE_LINE = 1
EDGE_BACKGROUND = 2
SCI_GETEDGECOLUMN = 2360
SCI_SETEDGECOLUMN = 2361
SCI_GETEDGEMODE = 2362
SCI_SETEDGEMODE = 2363
SCI_GETEDGECOLOUR = 2364
SCI_SETEDGECOLOUR = 2365
SCI_SEARCHANCHOR = 2366
SCI_SEARCHNEXT = 2367
SCI_SEARCHPREV = 2368
SCI_LINESONSCREEN = 2370
SCI_USEPOPUP = 2371
SCI_SELECTIONISRECTANGLE = 2372
SCI_SETZOOM = 2373
SCI_GETZOOM = 2374
SCI_CREATEDOCUMENT = 2375
SCI_ADDREFDOCUMENT = 2376
SCI_RELEASEDOCUMENT = 2377
SCI_GETMODEVENTMASK = 2378
SCI_SETFOCUS = 2380
SCI_GETFOCUS = 2381
SCI_SETSTATUS = 2382
SCI_GETSTATUS = 2383
SCI_SETMOUSEDOWNCAPTURES = 2384
SCI_GETMOUSEDOWNCAPTURES = 2385
SC_CURSORNORMAL = -1
SC_CURSORWAIT = 4
SCI_SETCURSOR = 2386
SCI_GETCURSOR = 2387
SCI_SETCONTROLCHARSYMBOL = 2388
SCI_GETCONTROLCHARSYMBOL = 2389
SCI_WORDPARTLEFT = 2390
SCI_WORDPARTLEFTEXTEND = 2391
SCI_WORDPARTRIGHT = 2392
SCI_WORDPARTRIGHTEXTEND = 2393
VISIBLE_SLOP = 0x01
VISIBLE_STRICT = 0x04
SCI_SETVISIBLEPOLICY = 2394
SCI_DELLINELEFT = 2395
SCI_DELLINERIGHT = 2396
SCI_SETXOFFSET = 2397
SCI_GETXOFFSET = 2398
SCI_CHOOSECARETX = 2399
SCI_GRABFOCUS = 2400
CARET_SLOP = 0x01
CARET_STRICT = 0x04
CARET_JUMPS = 0x10
CARET_EVEN = 0x08
SCI_SETXCARETPOLICY = 2402
SCI_SETYCARETPOLICY = 2403
SCI_SETPRINTWRAPMODE = 2406
SCI_GETPRINTWRAPMODE = 2407
SCI_SETHOTSPOTACTIVEFORE = 2410
SCI_SETHOTSPOTACTIVEBACK = 2411
SCI_SETHOTSPOTACTIVEUNDERLINE = 2412
SCI_SETHOTSPOTSINGLELINE = 2421
SCI_PARADOWN = 2413
SCI_PARADOWNEXTEND = 2414
SCI_PARAUP = 2415
SCI_PARAUPEXTEND = 2416
SCI_POSITIONBEFORE = 2417
SCI_POSITIONAFTER = 2418
SCI_COPYRANGE = 2419
SCI_COPYTEXT = 2420
SC_SEL_STREAM = 0
SC_SEL_RECTANGLE = 1
SC_SEL_LINES = 2
SCI_SETSELECTIONMODE = 2422
SCI_GETSELECTIONMODE = 2423
SCI_GETLINESELSTARTPOSITION = 2424
SCI_GETLINESELENDPOSITION = 2425
SCI_LINEDOWNRECTEXTEND = 2426
SCI_LINEUPRECTEXTEND = 2427
SCI_CHARLEFTRECTEXTEND = 2428
SCI_CHARRIGHTRECTEXTEND = 2429
SCI_HOMERECTEXTEND = 2430
SCI_VCHOMERECTEXTEND = 2431
SCI_LINEENDRECTEXTEND = 2432
SCI_PAGEUPRECTEXTEND = 2433
SCI_PAGEDOWNRECTEXTEND = 2434
SCI_STUTTEREDPAGEUP = 2435
SCI_STUTTEREDPAGEUPEXTEND = 2436
SCI_STUTTEREDPAGEDOWN = 2437
SCI_STUTTEREDPAGEDOWNEXTEND = 2438
SCI_WORDLEFTEND = 2439
SCI_WORDLEFTENDEXTEND = 2440
SCI_WORDRIGHTEND = 2441
SCI_WORDRIGHTENDEXTEND = 2442
SCI_SETWHITESPACECHARS = 2443
SCI_SETCHARSDEFAULT = 2444
SCI_STARTRECORD = 3001
SCI_STOPRECORD = 3002
SCI_SETLEXER = 4001
SCI_GETLEXER = 4002
SCI_COLOURISE = 4003
SCI_SETPROPERTY = 4004
KEYWORDSET_MAX = 8
SCI_SETKEYWORDS = 4005
SCI_SETLEXERLANGUAGE = 4006
SCI_LOADLEXERLIBRARY = 4007
SC_MOD_INSERTTEXT = 0x1
SC_MOD_DELETETEXT = 0x2
SC_MOD_CHANGESTYLE = 0x4
SC_MOD_CHANGEFOLD = 0x8
SC_PERFORMED_USER = 0x10
SC_PERFORMED_UNDO = 0x20
SC_PERFORMED_REDO = 0x40
SC_LASTSTEPINUNDOREDO = 0x100
SC_MOD_CHANGEMARKER = 0x200
SC_MOD_BEFOREINSERT = 0x400
SC_MOD_BEFOREDELETE = 0x800
SC_MODEVENTMASKALL = 0xF77
SCEN_CHANGE = 768
SCEN_SETFOCUS = 512
SCEN_KILLFOCUS = 256
SCK_DOWN = 300
SCK_UP = 301
SCK_LEFT = 302
SCK_RIGHT = 303
SCK_HOME = 304
SCK_END = 305
SCK_PRIOR = 306
SCK_NEXT = 307
SCK_DELETE = 308
SCK_INSERT = 309
SCK_ESCAPE = 7
SCK_BACK = 8
SCK_TAB = 9
SCK_RETURN = 13
SCK_ADD = 310
SCK_SUBTRACT = 311
SCK_DIVIDE = 312
SCMOD_SHIFT = 1
SCMOD_CTRL = 2
SCMOD_ALT = 4
SCN_STYLENEEDED = 2000
SCN_CHARADDED = 2001
SCN_SAVEPOINTREACHED = 2002
SCN_SAVEPOINTLEFT = 2003
SCN_MODIFYATTEMPTRO = 2004
SCN_KEY = 2005
SCN_DOUBLECLICK = 2006
SCN_UPDATEUI = 2007
SCN_MODIFIED = 2008
SCN_MACRORECORD = 2009
SCN_MARGINCLICK = 2010
SCN_NEEDSHOWN = 2011
SCN_PAINTED = 2013
SCN_USERLISTSELECTION = 2014
SCN_URIDROPPED = 2015
SCN_DWELLSTART = 2016
SCN_DWELLEND = 2017
SCN_ZOOM = 2018
SCN_HOTSPOTCLICK = 2019
SCN_HOTSPOTDOUBLECLICK = 2020
SCN_CALLTIPCLICK = 2021
SCI_SETCARETPOLICY = 2369
CARET_CENTER = 0x02
CARET_XEVEN = 0x08
CARET_XJUMPS = 0x10
SCN_POSCHANGED = 2012
SCN_CHECKBRACE = 2007
# Generated by h2py from Include\scilexer.h
SCLEX_CONTAINER = 0
SCLEX_NULL = 1
SCLEX_PYTHON = 2
SCLEX_CPP = 3
SCLEX_HTML = 4
SCLEX_XML = 5
SCLEX_PERL = 6
SCLEX_SQL = 7
SCLEX_VB = 8
SCLEX_PROPERTIES = 9
SCLEX_ERRORLIST = 10
SCLEX_MAKEFILE = 11
SCLEX_BATCH = 12
SCLEX_XCODE = 13
SCLEX_LATEX = 14
SCLEX_LUA = 15
SCLEX_DIFF = 16
SCLEX_CONF = 17
SCLEX_PASCAL = 18
SCLEX_AVE = 19
SCLEX_ADA = 20
SCLEX_LISP = 21
SCLEX_RUBY = 22
SCLEX_EIFFEL = 23
SCLEX_EIFFELKW = 24
SCLEX_TCL = 25
SCLEX_NNCRONTAB = 26
SCLEX_BULLANT = 27
SCLEX_VBSCRIPT = 28
SCLEX_ASP = 29
SCLEX_PHP = 30
SCLEX_BAAN = 31
SCLEX_MATLAB = 32
SCLEX_SCRIPTOL = 33
SCLEX_ASM = 34
SCLEX_CPPNOCASE = 35
SCLEX_FORTRAN = 36
SCLEX_F77 = 37
SCLEX_CSS = 38
SCLEX_POV = 39
SCLEX_LOUT = 40
SCLEX_ESCRIPT = 41
SCLEX_PS = 42
SCLEX_NSIS = 43
SCLEX_MMIXAL = 44
SCLEX_CLW = 45
SCLEX_CLWNOCASE = 46
SCLEX_LOT = 47
SCLEX_YAML = 48
SCLEX_TEX = 49
SCLEX_METAPOST = 50
SCLEX_POWERBASIC = 51
SCLEX_FORTH = 52
SCLEX_ERLANG = 53
SCLEX_AUTOMATIC = 1000
SCE_P_DEFAULT = 0
SCE_P_COMMENTLINE = 1
SCE_P_NUMBER = 2
SCE_P_STRING = 3
SCE_P_CHARACTER = 4
SCE_P_WORD = 5
SCE_P_TRIPLE = 6
SCE_P_TRIPLEDOUBLE = 7
SCE_P_CLASSNAME = 8
SCE_P_DEFNAME = 9
SCE_P_OPERATOR = 10
SCE_P_IDENTIFIER = 11
SCE_P_COMMENTBLOCK = 12
SCE_P_STRINGEOL = 13
SCE_C_DEFAULT = 0
SCE_C_COMMENT = 1
SCE_C_COMMENTLINE = 2
SCE_C_COMMENTDOC = 3
SCE_C_NUMBER = 4
SCE_C_WORD = 5
SCE_C_STRING = 6
SCE_C_CHARACTER = 7
SCE_C_UUID = 8
SCE_C_PREPROCESSOR = 9
SCE_C_OPERATOR = 10
SCE_C_IDENTIFIER = 11
SCE_C_STRINGEOL = 12
SCE_C_VERBATIM = 13
SCE_C_REGEX = 14
SCE_C_COMMENTLINEDOC = 15
SCE_C_WORD2 = 16
SCE_C_COMMENTDOCKEYWORD = 17
SCE_C_COMMENTDOCKEYWORDERROR = 18
SCE_C_GLOBALCLASS = 19
SCE_H_DEFAULT = 0
SCE_H_TAG = 1
SCE_H_TAGUNKNOWN = 2
SCE_H_ATTRIBUTE = 3
SCE_H_ATTRIBUTEUNKNOWN = 4
SCE_H_NUMBER = 5
SCE_H_DOUBLESTRING = 6
SCE_H_SINGLESTRING = 7
SCE_H_OTHER = 8
SCE_H_COMMENT = 9
SCE_H_ENTITY = 10
SCE_H_TAGEND = 11
SCE_H_XMLSTART = 12
SCE_H_XMLEND = 13
SCE_H_SCRIPT = 14
SCE_H_ASP = 15
SCE_H_ASPAT = 16
SCE_H_CDATA = 17
SCE_H_QUESTION = 18
SCE_H_VALUE = 19
SCE_H_XCCOMMENT = 20
SCE_H_SGML_DEFAULT = 21
SCE_H_SGML_COMMAND = 22
SCE_H_SGML_1ST_PARAM = 23
SCE_H_SGML_DOUBLESTRING = 24
SCE_H_SGML_SIMPLESTRING = 25
SCE_H_SGML_ERROR = 26
SCE_H_SGML_SPECIAL = 27
SCE_H_SGML_ENTITY = 28
SCE_H_SGML_COMMENT = 29
SCE_H_SGML_1ST_PARAM_COMMENT = 30
SCE_H_SGML_BLOCK_DEFAULT = 31
SCE_HJ_START = 40
SCE_HJ_DEFAULT = 41
SCE_HJ_COMMENT = 42
SCE_HJ_COMMENTLINE = 43
SCE_HJ_COMMENTDOC = 44
SCE_HJ_NUMBER = 45
SCE_HJ_WORD = 46
SCE_HJ_KEYWORD = 47
SCE_HJ_DOUBLESTRING = 48
SCE_HJ_SINGLESTRING = 49
SCE_HJ_SYMBOLS = 50
SCE_HJ_STRINGEOL = 51
SCE_HJ_REGEX = 52
SCE_HJA_START = 55
SCE_HJA_DEFAULT = 56
SCE_HJA_COMMENT = 57
SCE_HJA_COMMENTLINE = 58
SCE_HJA_COMMENTDOC = 59
SCE_HJA_NUMBER = 60
SCE_HJA_WORD = 61
SCE_HJA_KEYWORD = 62
SCE_HJA_DOUBLESTRING = 63
SCE_HJA_SINGLESTRING = 64
SCE_HJA_SYMBOLS = 65
SCE_HJA_STRINGEOL = 66
SCE_HJA_REGEX = 67
SCE_HB_START = 70
SCE_HB_DEFAULT = 71
SCE_HB_COMMENTLINE = 72
SCE_HB_NUMBER = 73
SCE_HB_WORD = 74
SCE_HB_STRING = 75
SCE_HB_IDENTIFIER = 76
SCE_HB_STRINGEOL = 77
SCE_HBA_START = 80
SCE_HBA_DEFAULT = 81
SCE_HBA_COMMENTLINE = 82
SCE_HBA_NUMBER = 83
SCE_HBA_WORD = 84
SCE_HBA_STRING = 85
SCE_HBA_IDENTIFIER = 86
SCE_HBA_STRINGEOL = 87
SCE_HP_START = 90
SCE_HP_DEFAULT = 91
SCE_HP_COMMENTLINE = 92
SCE_HP_NUMBER = 93
SCE_HP_STRING = 94
SCE_HP_CHARACTER = 95
SCE_HP_WORD = 96
SCE_HP_TRIPLE = 97
SCE_HP_TRIPLEDOUBLE = 98
SCE_HP_CLASSNAME = 99
SCE_HP_DEFNAME = 100
SCE_HP_OPERATOR = 101
SCE_HP_IDENTIFIER = 102
SCE_HPA_START = 105
SCE_HPA_DEFAULT = 106
SCE_HPA_COMMENTLINE = 107
SCE_HPA_NUMBER = 108
SCE_HPA_STRING = 109
SCE_HPA_CHARACTER = 110
SCE_HPA_WORD = 111
SCE_HPA_TRIPLE = 112
SCE_HPA_TRIPLEDOUBLE = 113
SCE_HPA_CLASSNAME = 114
SCE_HPA_DEFNAME = 115
SCE_HPA_OPERATOR = 116
SCE_HPA_IDENTIFIER = 117
SCE_HPHP_DEFAULT = 118
SCE_HPHP_HSTRING = 119
SCE_HPHP_SIMPLESTRING = 120
SCE_HPHP_WORD = 121
SCE_HPHP_NUMBER = 122
SCE_HPHP_VARIABLE = 123
SCE_HPHP_COMMENT = 124
SCE_HPHP_COMMENTLINE = 125
SCE_HPHP_HSTRING_VARIABLE = 126
SCE_HPHP_OPERATOR = 127
SCE_PL_DEFAULT = 0
SCE_PL_ERROR = 1
SCE_PL_COMMENTLINE = 2
SCE_PL_POD = 3
SCE_PL_NUMBER = 4
SCE_PL_WORD = 5
SCE_PL_STRING = 6
SCE_PL_CHARACTER = 7
SCE_PL_PUNCTUATION = 8
SCE_PL_PREPROCESSOR = 9
SCE_PL_OPERATOR = 10
SCE_PL_IDENTIFIER = 11
SCE_PL_SCALAR = 12
SCE_PL_ARRAY = 13
SCE_PL_HASH = 14
SCE_PL_SYMBOLTABLE = 15
SCE_PL_REGEX = 17
SCE_PL_REGSUBST = 18
SCE_PL_LONGQUOTE = 19
SCE_PL_BACKTICKS = 20
SCE_PL_DATASECTION = 21
SCE_PL_HERE_DELIM = 22
SCE_PL_HERE_Q = 23
SCE_PL_HERE_QQ = 24
SCE_PL_HERE_QX = 25
SCE_PL_STRING_Q = 26
SCE_PL_STRING_QQ = 27
SCE_PL_STRING_QX = 28
SCE_PL_STRING_QR = 29
SCE_PL_STRING_QW = 30
SCE_B_DEFAULT = 0
SCE_B_COMMENT = 1
SCE_B_NUMBER = 2
SCE_B_KEYWORD = 3
SCE_B_STRING = 4
SCE_B_PREPROCESSOR = 5
SCE_B_OPERATOR = 6
SCE_B_IDENTIFIER = 7
SCE_B_DATE = 8
SCE_PROPS_DEFAULT = 0
SCE_PROPS_COMMENT = 1
SCE_PROPS_SECTION = 2
SCE_PROPS_ASSIGNMENT = 3
SCE_PROPS_DEFVAL = 4
SCE_L_DEFAULT = 0
SCE_L_COMMAND = 1
SCE_L_TAG = 2
SCE_L_MATH = 3
SCE_L_COMMENT = 4
SCE_LUA_DEFAULT = 0
SCE_LUA_COMMENT = 1
SCE_LUA_COMMENTLINE = 2
SCE_LUA_COMMENTDOC = 3
SCE_LUA_NUMBER = 4
SCE_LUA_WORD = 5
SCE_LUA_STRING = 6
SCE_LUA_CHARACTER = 7
SCE_LUA_LITERALSTRING = 8
SCE_LUA_PREPROCESSOR = 9
SCE_LUA_OPERATOR = 10
SCE_LUA_IDENTIFIER = 11
SCE_LUA_STRINGEOL = 12
SCE_LUA_WORD2 = 13
SCE_LUA_WORD3 = 14
SCE_LUA_WORD4 = 15
SCE_LUA_WORD5 = 16
SCE_LUA_WORD6 = 17
SCE_LUA_WORD7 = 18
SCE_LUA_WORD8 = 19
SCE_ERR_DEFAULT = 0
SCE_ERR_PYTHON = 1
SCE_ERR_GCC = 2
SCE_ERR_MS = 3
SCE_ERR_CMD = 4
SCE_ERR_BORLAND = 5
SCE_ERR_PERL = 6
SCE_ERR_NET = 7
SCE_ERR_LUA = 8
SCE_ERR_CTAG = 9
SCE_ERR_DIFF_CHANGED = 10
SCE_ERR_DIFF_ADDITION = 11
SCE_ERR_DIFF_DELETION = 12
SCE_ERR_DIFF_MESSAGE = 13
SCE_ERR_PHP = 14
SCE_ERR_ELF = 15
SCE_ERR_IFC = 16
SCE_BAT_DEFAULT = 0
SCE_BAT_COMMENT = 1
SCE_BAT_WORD = 2
SCE_BAT_LABEL = 3
SCE_BAT_HIDE = 4
SCE_BAT_COMMAND = 5
SCE_BAT_IDENTIFIER = 6
SCE_BAT_OPERATOR = 7
SCE_MAKE_DEFAULT = 0
SCE_MAKE_COMMENT = 1
SCE_MAKE_PREPROCESSOR = 2
SCE_MAKE_IDENTIFIER = 3
SCE_MAKE_OPERATOR = 4
SCE_MAKE_TARGET = 5
SCE_MAKE_IDEOL = 9
SCE_DIFF_DEFAULT = 0
SCE_DIFF_COMMENT = 1
SCE_DIFF_COMMAND = 2
SCE_DIFF_HEADER = 3
SCE_DIFF_POSITION = 4
SCE_DIFF_DELETED = 5
SCE_DIFF_ADDED = 6
SCE_CONF_DEFAULT = 0
SCE_CONF_COMMENT = 1
SCE_CONF_NUMBER = 2
SCE_CONF_IDENTIFIER = 3
SCE_CONF_EXTENSION = 4
SCE_CONF_PARAMETER = 5
SCE_CONF_STRING = 6
SCE_CONF_OPERATOR = 7
SCE_CONF_IP = 8
SCE_CONF_DIRECTIVE = 9
SCE_AVE_DEFAULT = 0
SCE_AVE_COMMENT = 1
SCE_AVE_NUMBER = 2
SCE_AVE_WORD = 3
SCE_AVE_STRING = 6
SCE_AVE_ENUM = 7
SCE_AVE_STRINGEOL = 8
SCE_AVE_IDENTIFIER = 9
SCE_AVE_OPERATOR = 10
SCE_AVE_WORD1 = 11
SCE_AVE_WORD2 = 12
SCE_AVE_WORD3 = 13
SCE_AVE_WORD4 = 14
SCE_AVE_WORD5 = 15
SCE_AVE_WORD6 = 16
SCE_ADA_DEFAULT = 0
SCE_ADA_WORD = 1
SCE_ADA_IDENTIFIER = 2
SCE_ADA_NUMBER = 3
SCE_ADA_DELIMITER = 4
SCE_ADA_CHARACTER = 5
SCE_ADA_CHARACTEREOL = 6
SCE_ADA_STRING = 7
SCE_ADA_STRINGEOL = 8
SCE_ADA_LABEL = 9
SCE_ADA_COMMENTLINE = 10
SCE_ADA_ILLEGAL = 11
SCE_BAAN_DEFAULT = 0
SCE_BAAN_COMMENT = 1
SCE_BAAN_COMMENTDOC = 2
SCE_BAAN_NUMBER = 3
SCE_BAAN_WORD = 4
SCE_BAAN_STRING = 5
SCE_BAAN_PREPROCESSOR = 6
SCE_BAAN_OPERATOR = 7
SCE_BAAN_IDENTIFIER = 8
SCE_BAAN_STRINGEOL = 9
SCE_BAAN_WORD2 = 10
SCE_LISP_DEFAULT = 0
SCE_LISP_COMMENT = 1
SCE_LISP_NUMBER = 2
SCE_LISP_KEYWORD = 3
SCE_LISP_STRING = 6
SCE_LISP_STRINGEOL = 8
SCE_LISP_IDENTIFIER = 9
SCE_LISP_OPERATOR = 10
SCE_EIFFEL_DEFAULT = 0
SCE_EIFFEL_COMMENTLINE = 1
SCE_EIFFEL_NUMBER = 2
SCE_EIFFEL_WORD = 3
SCE_EIFFEL_STRING = 4
SCE_EIFFEL_CHARACTER = 5
SCE_EIFFEL_OPERATOR = 6
SCE_EIFFEL_IDENTIFIER = 7
SCE_EIFFEL_STRINGEOL = 8
SCE_NNCRONTAB_DEFAULT = 0
SCE_NNCRONTAB_COMMENT = 1
SCE_NNCRONTAB_TASK = 2
SCE_NNCRONTAB_SECTION = 3
SCE_NNCRONTAB_KEYWORD = 4
SCE_NNCRONTAB_MODIFIER = 5
SCE_NNCRONTAB_ASTERISK = 6
SCE_NNCRONTAB_NUMBER = 7
SCE_NNCRONTAB_STRING = 8
SCE_NNCRONTAB_ENVIRONMENT = 9
SCE_NNCRONTAB_IDENTIFIER = 10
SCE_FORTH_DEFAULT = 0
SCE_FORTH_COMMENT = 1
SCE_FORTH_COMMENT_ML = 2
SCE_FORTH_IDENTIFIER = 3
SCE_FORTH_CONTROL = 4
SCE_FORTH_KEYWORD = 5
SCE_FORTH_DEFWORD = 6
SCE_FORTH_PREWORD1 = 7
SCE_FORTH_PREWORD2 = 8
SCE_FORTH_NUMBER = 9
SCE_FORTH_STRING = 10
SCE_FORTH_LOCALE = 11
SCE_MATLAB_DEFAULT = 0
SCE_MATLAB_COMMENT = 1
SCE_MATLAB_COMMAND = 2
SCE_MATLAB_NUMBER = 3
SCE_MATLAB_KEYWORD = 4
SCE_MATLAB_STRING = 5
SCE_MATLAB_OPERATOR = 6
SCE_MATLAB_IDENTIFIER = 7
SCE_SCRIPTOL_DEFAULT = 0
SCE_SCRIPTOL_WHITE = 1
SCE_SCRIPTOL_COMMENTLINE = 2
SCE_SCRIPTOL_PERSISTENT = 3
SCE_SCRIPTOL_CSTYLE = 4
SCE_SCRIPTOL_COMMENTBLOCK = 5
SCE_SCRIPTOL_NUMBER = 6
SCE_SCRIPTOL_STRING = 7
SCE_SCRIPTOL_CHARACTER = 8
SCE_SCRIPTOL_STRINGEOL = 9
SCE_SCRIPTOL_KEYWORD = 10
SCE_SCRIPTOL_OPERATOR = 11
SCE_SCRIPTOL_IDENTIFIER = 12
SCE_SCRIPTOL_TRIPLE = 13
SCE_SCRIPTOL_CLASSNAME = 14
SCE_SCRIPTOL_PREPROCESSOR = 15
SCE_ASM_DEFAULT = 0
SCE_ASM_COMMENT = 1
SCE_ASM_NUMBER = 2
SCE_ASM_STRING = 3
SCE_ASM_OPERATOR = 4
SCE_ASM_IDENTIFIER = 5
SCE_ASM_CPUINSTRUCTION = 6
SCE_ASM_MATHINSTRUCTION = 7
SCE_ASM_REGISTER = 8
SCE_ASM_DIRECTIVE = 9
SCE_ASM_DIRECTIVEOPERAND = 10
SCE_ASM_COMMENTBLOCK = 11
SCE_ASM_CHARACTER = 12
SCE_ASM_STRINGEOL = 13
SCE_ASM_EXTINSTRUCTION = 14
SCE_F_DEFAULT = 0
SCE_F_COMMENT = 1
SCE_F_NUMBER = 2
SCE_F_STRING1 = 3
SCE_F_STRING2 = 4
SCE_F_STRINGEOL = 5
SCE_F_OPERATOR = 6
SCE_F_IDENTIFIER = 7
SCE_F_WORD = 8
SCE_F_WORD2 = 9
SCE_F_WORD3 = 10
SCE_F_PREPROCESSOR = 11
SCE_F_OPERATOR2 = 12
SCE_F_LABEL = 13
SCE_F_CONTINUATION = 14
SCE_CSS_DEFAULT = 0
SCE_CSS_TAG = 1
SCE_CSS_CLASS = 2
SCE_CSS_PSEUDOCLASS = 3
SCE_CSS_UNKNOWN_PSEUDOCLASS = 4
SCE_CSS_OPERATOR = 5
SCE_CSS_IDENTIFIER = 6
SCE_CSS_UNKNOWN_IDENTIFIER = 7
SCE_CSS_VALUE = 8
SCE_CSS_COMMENT = 9
SCE_CSS_ID = 10
SCE_CSS_IMPORTANT = 11
SCE_CSS_DIRECTIVE = 12
SCE_CSS_DOUBLESTRING = 13
SCE_CSS_SINGLESTRING = 14
SCE_POV_DEFAULT = 0
SCE_POV_COMMENT = 1
SCE_POV_COMMENTLINE = 2
SCE_POV_NUMBER = 3
SCE_POV_OPERATOR = 4
SCE_POV_IDENTIFIER = 5
SCE_POV_STRING = 6
SCE_POV_STRINGEOL = 7
SCE_POV_DIRECTIVE = 8
SCE_POV_BADDIRECTIVE = 9
SCE_POV_WORD2 = 10
SCE_POV_WORD3 = 11
SCE_POV_WORD4 = 12
SCE_POV_WORD5 = 13
SCE_POV_WORD6 = 14
SCE_POV_WORD7 = 15
SCE_POV_WORD8 = 16
SCE_LOUT_DEFAULT = 0
SCE_LOUT_COMMENT = 1
SCE_LOUT_NUMBER = 2
SCE_LOUT_WORD = 3
SCE_LOUT_WORD2 = 4
SCE_LOUT_WORD3 = 5
SCE_LOUT_WORD4 = 6
SCE_LOUT_STRING = 7
SCE_LOUT_OPERATOR = 8
SCE_LOUT_IDENTIFIER = 9
SCE_LOUT_STRINGEOL = 10
SCE_ESCRIPT_DEFAULT = 0
SCE_ESCRIPT_COMMENT = 1
SCE_ESCRIPT_COMMENTLINE = 2
SCE_ESCRIPT_COMMENTDOC = 3
SCE_ESCRIPT_NUMBER = 4
SCE_ESCRIPT_WORD = 5
SCE_ESCRIPT_STRING = 6
SCE_ESCRIPT_OPERATOR = 7
SCE_ESCRIPT_IDENTIFIER = 8
SCE_ESCRIPT_BRACE = 9
SCE_ESCRIPT_WORD2 = 10
SCE_ESCRIPT_WORD3 = 11
SCE_PS_DEFAULT = 0
SCE_PS_COMMENT = 1
SCE_PS_DSC_COMMENT = 2
SCE_PS_DSC_VALUE = 3
SCE_PS_NUMBER = 4
SCE_PS_NAME = 5
SCE_PS_KEYWORD = 6
SCE_PS_LITERAL = 7
SCE_PS_IMMEVAL = 8
SCE_PS_PAREN_ARRAY = 9
SCE_PS_PAREN_DICT = 10
SCE_PS_PAREN_PROC = 11
SCE_PS_TEXT = 12
SCE_PS_HEXSTRING = 13
SCE_PS_BASE85STRING = 14
SCE_PS_BADSTRINGCHAR = 15
SCE_NSIS_DEFAULT = 0
SCE_NSIS_COMMENT = 1
SCE_NSIS_STRINGDQ = 2
SCE_NSIS_STRINGLQ = 3
SCE_NSIS_STRINGRQ = 4
SCE_NSIS_FUNCTION = 5
SCE_NSIS_VARIABLE = 6
SCE_NSIS_LABEL = 7
SCE_NSIS_USERDEFINED = 8
SCE_NSIS_SECTIONDEF = 9
SCE_NSIS_SUBSECTIONDEF = 10
SCE_NSIS_IFDEFINEDEF = 11
SCE_NSIS_MACRODEF = 12
SCE_NSIS_STRINGVAR = 13
SCE_MMIXAL_LEADWS = 0
SCE_MMIXAL_COMMENT = 1
SCE_MMIXAL_LABEL = 2
SCE_MMIXAL_OPCODE = 3
SCE_MMIXAL_OPCODE_PRE = 4
SCE_MMIXAL_OPCODE_VALID = 5
SCE_MMIXAL_OPCODE_UNKNOWN = 6
SCE_MMIXAL_OPCODE_POST = 7
SCE_MMIXAL_OPERANDS = 8
SCE_MMIXAL_NUMBER = 9
SCE_MMIXAL_REF = 10
SCE_MMIXAL_CHAR = 11
SCE_MMIXAL_STRING = 12
SCE_MMIXAL_REGISTER = 13
SCE_MMIXAL_HEX = 14
SCE_MMIXAL_OPERATOR = 15
SCE_MMIXAL_SYMBOL = 16
SCE_MMIXAL_INCLUDE = 17
SCE_CLW_DEFAULT = 0
SCE_CLW_LABEL = 1
SCE_CLW_COMMENT = 2
SCE_CLW_STRING = 3
SCE_CLW_USER_IDENTIFIER = 4
SCE_CLW_INTEGER_CONSTANT = 5
SCE_CLW_REAL_CONSTANT = 6
SCE_CLW_PICTURE_STRING = 7
SCE_CLW_KEYWORD = 8
SCE_CLW_COMPILER_DIRECTIVE = 9
SCE_CLW_BUILTIN_PROCEDURES_FUNCTION = 10
SCE_CLW_STRUCTURE_DATA_TYPE = 11
SCE_CLW_ATTRIBUTE = 12
SCE_CLW_STANDARD_EQUATE = 13
SCE_CLW_ERROR = 14
SCE_LOT_DEFAULT = 0
SCE_LOT_HEADER = 1
SCE_LOT_BREAK = 2
SCE_LOT_SET = 3
SCE_LOT_PASS = 4
SCE_LOT_FAIL = 5
SCE_LOT_ABORT = 6
SCE_YAML_DEFAULT = 0
SCE_YAML_COMMENT = 1
SCE_YAML_IDENTIFIER = 2
SCE_YAML_KEYWORD = 3
SCE_YAML_NUMBER = 4
SCE_YAML_REFERENCE = 5
SCE_YAML_DOCUMENT = 6
SCE_YAML_TEXT = 7
SCE_YAML_ERROR = 8
SCE_TEX_DEFAULT = 0
SCE_TEX_SPECIAL = 1
SCE_TEX_GROUP = 2
SCE_TEX_SYMBOL = 3
SCE_TEX_COMMAND = 4
SCE_TEX_TEXT = 5
SCE_METAPOST_DEFAULT = 0
SCE_METAPOST_SPECIAL = 1
SCE_METAPOST_GROUP = 2
SCE_METAPOST_SYMBOL = 3
SCE_METAPOST_COMMAND = 4
SCE_METAPOST_TEXT = 5
SCE_METAPOST_EXTRA = 6
SCE_ERLANG_DEFAULT = 0
SCE_ERLANG_COMMENT = 1
SCE_ERLANG_VARIABLE = 2
SCE_ERLANG_NUMBER = 3
SCE_ERLANG_KEYWORD = 4
SCE_ERLANG_STRING = 5
SCE_ERLANG_OPERATOR = 6
SCE_ERLANG_ATOM = 7
SCE_ERLANG_FUNCTION_NAME = 8
SCE_ERLANG_CHARACTER = 9
SCE_ERLANG_MACRO = 10
SCE_ERLANG_RECORD = 11
SCE_ERLANG_SEPARATOR = 12
SCE_ERLANG_NODE_NAME = 13
SCE_ERLANG_UNKNOWN = 31
|
def handle_to_ulong(h):
return handle_to_u_long(h)
def ulong_to_handle(ul):
return u_long_to_handle(ul)
def ulong_to_ptr(ul):
return u_long_to_ptr(ul)
def uint_to_ptr(ui):
return u_int_to_ptr(ui)
invalid_position = -1
sci_start = 2000
sci_optional_start = 3000
sci_lexer_start = 4000
sci_addtext = 2001
sci_addstyledtext = 2002
sci_inserttext = 2003
sci_clearall = 2004
sci_cleardocumentstyle = 2005
sci_getlength = 2006
sci_getcharat = 2007
sci_getcurrentpos = 2008
sci_getanchor = 2009
sci_getstyleat = 2010
sci_redo = 2011
sci_setundocollection = 2012
sci_selectall = 2013
sci_setsavepoint = 2014
sci_getstyledtext = 2015
sci_canredo = 2016
sci_markerlinefromhandle = 2017
sci_markerdeletehandle = 2018
sci_getundocollection = 2019
scws_invisible = 0
scws_visiblealways = 1
scws_visibleafterindent = 2
sci_getviewws = 2020
sci_setviewws = 2021
sci_positionfrompoint = 2022
sci_positionfrompointclose = 2023
sci_gotoline = 2024
sci_gotopos = 2025
sci_setanchor = 2026
sci_getcurline = 2027
sci_getendstyled = 2028
sc_eol_crlf = 0
sc_eol_cr = 1
sc_eol_lf = 2
sci_converteols = 2029
sci_geteolmode = 2030
sci_seteolmode = 2031
sci_startstyling = 2032
sci_setstyling = 2033
sci_getbuffereddraw = 2034
sci_setbuffereddraw = 2035
sci_settabwidth = 2036
sci_gettabwidth = 2121
sc_cp_utf8 = 65001
sc_cp_dbcs = 1
sci_setcodepage = 2037
sci_setusepalette = 2039
marker_max = 31
sc_mark_circle = 0
sc_mark_roundrect = 1
sc_mark_arrow = 2
sc_mark_smallrect = 3
sc_mark_shortarrow = 4
sc_mark_empty = 5
sc_mark_arrowdown = 6
sc_mark_minus = 7
sc_mark_plus = 8
sc_mark_vline = 9
sc_mark_lcorner = 10
sc_mark_tcorner = 11
sc_mark_boxplus = 12
sc_mark_boxplusconnected = 13
sc_mark_boxminus = 14
sc_mark_boxminusconnected = 15
sc_mark_lcornercurve = 16
sc_mark_tcornercurve = 17
sc_mark_circleplus = 18
sc_mark_circleplusconnected = 19
sc_mark_circleminus = 20
sc_mark_circleminusconnected = 21
sc_mark_background = 22
sc_mark_dotdotdot = 23
sc_mark_arrows = 24
sc_mark_pixmap = 25
sc_mark_character = 10000
sc_marknum_folderend = 25
sc_marknum_folderopenmid = 26
sc_marknum_foldermidtail = 27
sc_marknum_foldertail = 28
sc_marknum_foldersub = 29
sc_marknum_folder = 30
sc_marknum_folderopen = 31
sc_mask_folders = -33554432
sci_markerdefine = 2040
sci_markersetfore = 2041
sci_markersetback = 2042
sci_markeradd = 2043
sci_markerdelete = 2044
sci_markerdeleteall = 2045
sci_markerget = 2046
sci_markernext = 2047
sci_markerprevious = 2048
sci_markerdefinepixmap = 2049
sc_margin_symbol = 0
sc_margin_number = 1
sci_setmargintypen = 2240
sci_getmargintypen = 2241
sci_setmarginwidthn = 2242
sci_getmarginwidthn = 2243
sci_setmarginmaskn = 2244
sci_getmarginmaskn = 2245
sci_setmarginsensitiven = 2246
sci_getmarginsensitiven = 2247
style_default = 32
style_linenumber = 33
style_bracelight = 34
style_bracebad = 35
style_controlchar = 36
style_indentguide = 37
style_lastpredefined = 39
style_max = 127
sc_charset_ansi = 0
sc_charset_default = 1
sc_charset_baltic = 186
sc_charset_chinesebig5 = 136
sc_charset_easteurope = 238
sc_charset_gb2312 = 134
sc_charset_greek = 161
sc_charset_hangul = 129
sc_charset_mac = 77
sc_charset_oem = 255
sc_charset_russian = 204
sc_charset_shiftjis = 128
sc_charset_symbol = 2
sc_charset_turkish = 162
sc_charset_johab = 130
sc_charset_hebrew = 177
sc_charset_arabic = 178
sc_charset_vietnamese = 163
sc_charset_thai = 222
sci_styleclearall = 2050
sci_stylesetfore = 2051
sci_stylesetback = 2052
sci_stylesetbold = 2053
sci_stylesetitalic = 2054
sci_stylesetsize = 2055
sci_stylesetfont = 2056
sci_styleseteolfilled = 2057
sci_styleresetdefault = 2058
sci_stylesetunderline = 2059
sc_case_mixed = 0
sc_case_upper = 1
sc_case_lower = 2
sci_stylesetcase = 2060
sci_stylesetcharacterset = 2066
sci_stylesethotspot = 2409
sci_setselfore = 2067
sci_setselback = 2068
sci_setcaretfore = 2069
sci_assigncmdkey = 2070
sci_clearcmdkey = 2071
sci_clearallcmdkeys = 2072
sci_setstylingex = 2073
sci_stylesetvisible = 2074
sci_getcaretperiod = 2075
sci_setcaretperiod = 2076
sci_setwordchars = 2077
sci_beginundoaction = 2078
sci_endundoaction = 2079
indic_max = 7
indic_plain = 0
indic_squiggle = 1
indic_tt = 2
indic_diagonal = 3
indic_strike = 4
indic_hidden = 5
indic_box = 6
indic0_mask = 32
indic1_mask = 64
indic2_mask = 128
indics_mask = 224
sci_indicsetstyle = 2080
sci_indicgetstyle = 2081
sci_indicsetfore = 2082
sci_indicgetfore = 2083
sci_setwhitespacefore = 2084
sci_setwhitespaceback = 2085
sci_setstylebits = 2090
sci_getstylebits = 2091
sci_setlinestate = 2092
sci_getlinestate = 2093
sci_getmaxlinestate = 2094
sci_getcaretlinevisible = 2095
sci_setcaretlinevisible = 2096
sci_getcaretlineback = 2097
sci_setcaretlineback = 2098
sci_stylesetchangeable = 2099
sci_autocshow = 2100
sci_autoccancel = 2101
sci_autocactive = 2102
sci_autocposstart = 2103
sci_autoccomplete = 2104
sci_autocstops = 2105
sci_autocsetseparator = 2106
sci_autocgetseparator = 2107
sci_autocselect = 2108
sci_autocsetcancelatstart = 2110
sci_autocgetcancelatstart = 2111
sci_autocsetfillups = 2112
sci_autocsetchoosesingle = 2113
sci_autocgetchoosesingle = 2114
sci_autocsetignorecase = 2115
sci_autocgetignorecase = 2116
sci_userlistshow = 2117
sci_autocsetautohide = 2118
sci_autocgetautohide = 2119
sci_autocsetdroprestofword = 2270
sci_autocgetdroprestofword = 2271
sci_registerimage = 2405
sci_clearregisteredimages = 2408
sci_autocgettypeseparator = 2285
sci_autocsettypeseparator = 2286
sci_setindent = 2122
sci_getindent = 2123
sci_setusetabs = 2124
sci_getusetabs = 2125
sci_setlineindentation = 2126
sci_getlineindentation = 2127
sci_getlineindentposition = 2128
sci_getcolumn = 2129
sci_sethscrollbar = 2130
sci_gethscrollbar = 2131
sci_setindentationguides = 2132
sci_getindentationguides = 2133
sci_sethighlightguide = 2134
sci_gethighlightguide = 2135
sci_getlineendposition = 2136
sci_getcodepage = 2137
sci_getcaretfore = 2138
sci_getusepalette = 2139
sci_getreadonly = 2140
sci_setcurrentpos = 2141
sci_setselectionstart = 2142
sci_getselectionstart = 2143
sci_setselectionend = 2144
sci_getselectionend = 2145
sci_setprintmagnification = 2146
sci_getprintmagnification = 2147
sc_print_normal = 0
sc_print_invertlight = 1
sc_print_blackonwhite = 2
sc_print_colouronwhite = 3
sc_print_colouronwhitedefaultbg = 4
sci_setprintcolourmode = 2148
sci_getprintcolourmode = 2149
scfind_wholeword = 2
scfind_matchcase = 4
scfind_wordstart = 1048576
scfind_regexp = 2097152
scfind_posix = 4194304
sci_findtext = 2150
sci_formatrange = 2151
sci_getfirstvisibleline = 2152
sci_getline = 2153
sci_getlinecount = 2154
sci_setmarginleft = 2155
sci_getmarginleft = 2156
sci_setmarginright = 2157
sci_getmarginright = 2158
sci_getmodify = 2159
sci_setsel = 2160
sci_getseltext = 2161
sci_gettextrange = 2162
sci_hideselection = 2163
sci_pointxfromposition = 2164
sci_pointyfromposition = 2165
sci_linefromposition = 2166
sci_positionfromline = 2167
sci_linescroll = 2168
sci_scrollcaret = 2169
sci_replacesel = 2170
sci_setreadonly = 2171
sci_null = 2172
sci_canpaste = 2173
sci_canundo = 2174
sci_emptyundobuffer = 2175
sci_undo = 2176
sci_cut = 2177
sci_copy = 2178
sci_paste = 2179
sci_clear = 2180
sci_settext = 2181
sci_gettext = 2182
sci_gettextlength = 2183
sci_getdirectfunction = 2184
sci_getdirectpointer = 2185
sci_setovertype = 2186
sci_getovertype = 2187
sci_setcaretwidth = 2188
sci_getcaretwidth = 2189
sci_settargetstart = 2190
sci_gettargetstart = 2191
sci_settargetend = 2192
sci_gettargetend = 2193
sci_replacetarget = 2194
sci_replacetargetre = 2195
sci_searchintarget = 2197
sci_setsearchflags = 2198
sci_getsearchflags = 2199
sci_calltipshow = 2200
sci_calltipcancel = 2201
sci_calltipactive = 2202
sci_calltipposstart = 2203
sci_calltipsethlt = 2204
sci_calltipsetback = 2205
sci_calltipsetfore = 2206
sci_calltipsetforehlt = 2207
sci_visiblefromdocline = 2220
sci_doclinefromvisible = 2221
sc_foldlevelbase = 1024
sc_foldlevelwhiteflag = 4096
sc_foldlevelheaderflag = 8192
sc_foldlevelboxheaderflag = 16384
sc_foldlevelboxfooterflag = 32768
sc_foldlevelcontracted = 65536
sc_foldlevelunindent = 131072
sc_foldlevelnumbermask = 4095
sci_setfoldlevel = 2222
sci_getfoldlevel = 2223
sci_getlastchild = 2224
sci_getfoldparent = 2225
sci_showlines = 2226
sci_hidelines = 2227
sci_getlinevisible = 2228
sci_setfoldexpanded = 2229
sci_getfoldexpanded = 2230
sci_togglefold = 2231
sci_ensurevisible = 2232
sc_foldflag_linebefore_expanded = 2
sc_foldflag_linebefore_contracted = 4
sc_foldflag_lineafter_expanded = 8
sc_foldflag_lineafter_contracted = 16
sc_foldflag_levelnumbers = 64
sc_foldflag_box = 1
sci_setfoldflags = 2233
sci_ensurevisibleenforcepolicy = 2234
sci_settabindents = 2260
sci_gettabindents = 2261
sci_setbackspaceunindents = 2262
sci_getbackspaceunindents = 2263
sc_time_forever = 10000000
sci_setmousedwelltime = 2264
sci_getmousedwelltime = 2265
sci_wordstartposition = 2266
sci_wordendposition = 2267
sc_wrap_none = 0
sc_wrap_word = 1
sci_setwrapmode = 2268
sci_getwrapmode = 2269
sc_cache_none = 0
sc_cache_caret = 1
sc_cache_page = 2
sc_cache_document = 3
sci_setlayoutcache = 2272
sci_getlayoutcache = 2273
sci_setscrollwidth = 2274
sci_getscrollwidth = 2275
sci_textwidth = 2276
sci_setendatlastline = 2277
sci_getendatlastline = 2278
sci_textheight = 2279
sci_setvscrollbar = 2280
sci_getvscrollbar = 2281
sci_appendtext = 2282
sci_gettwophasedraw = 2283
sci_settwophasedraw = 2284
sci_targetfromselection = 2287
sci_linesjoin = 2288
sci_linessplit = 2289
sci_setfoldmargincolour = 2290
sci_setfoldmarginhicolour = 2291
sci_linedown = 2300
sci_linedownextend = 2301
sci_lineup = 2302
sci_lineupextend = 2303
sci_charleft = 2304
sci_charleftextend = 2305
sci_charright = 2306
sci_charrightextend = 2307
sci_wordleft = 2308
sci_wordleftextend = 2309
sci_wordright = 2310
sci_wordrightextend = 2311
sci_home = 2312
sci_homeextend = 2313
sci_lineend = 2314
sci_lineendextend = 2315
sci_documentstart = 2316
sci_documentstartextend = 2317
sci_documentend = 2318
sci_documentendextend = 2319
sci_pageup = 2320
sci_pageupextend = 2321
sci_pagedown = 2322
sci_pagedownextend = 2323
sci_edittoggleovertype = 2324
sci_cancel = 2325
sci_deleteback = 2326
sci_tab = 2327
sci_backtab = 2328
sci_newline = 2329
sci_formfeed = 2330
sci_vchome = 2331
sci_vchomeextend = 2332
sci_zoomin = 2333
sci_zoomout = 2334
sci_delwordleft = 2335
sci_delwordright = 2336
sci_linecut = 2337
sci_linedelete = 2338
sci_linetranspose = 2339
sci_lineduplicate = 2404
sci_lowercase = 2340
sci_uppercase = 2341
sci_linescrolldown = 2342
sci_linescrollup = 2343
sci_deletebacknotline = 2344
sci_homedisplay = 2345
sci_homedisplayextend = 2346
sci_lineenddisplay = 2347
sci_lineenddisplayextend = 2348
sci_homewrap = 2349
sci_homewrapextend = 2450
sci_lineendwrap = 2451
sci_lineendwrapextend = 2452
sci_vchomewrap = 2453
sci_vchomewrapextend = 2454
sci_linecopy = 2455
sci_movecaretinsideview = 2401
sci_linelength = 2350
sci_bracehighlight = 2351
sci_bracebadlight = 2352
sci_bracematch = 2353
sci_getvieweol = 2355
sci_setvieweol = 2356
sci_getdocpointer = 2357
sci_setdocpointer = 2358
sci_setmodeventmask = 2359
edge_none = 0
edge_line = 1
edge_background = 2
sci_getedgecolumn = 2360
sci_setedgecolumn = 2361
sci_getedgemode = 2362
sci_setedgemode = 2363
sci_getedgecolour = 2364
sci_setedgecolour = 2365
sci_searchanchor = 2366
sci_searchnext = 2367
sci_searchprev = 2368
sci_linesonscreen = 2370
sci_usepopup = 2371
sci_selectionisrectangle = 2372
sci_setzoom = 2373
sci_getzoom = 2374
sci_createdocument = 2375
sci_addrefdocument = 2376
sci_releasedocument = 2377
sci_getmodeventmask = 2378
sci_setfocus = 2380
sci_getfocus = 2381
sci_setstatus = 2382
sci_getstatus = 2383
sci_setmousedowncaptures = 2384
sci_getmousedowncaptures = 2385
sc_cursornormal = -1
sc_cursorwait = 4
sci_setcursor = 2386
sci_getcursor = 2387
sci_setcontrolcharsymbol = 2388
sci_getcontrolcharsymbol = 2389
sci_wordpartleft = 2390
sci_wordpartleftextend = 2391
sci_wordpartright = 2392
sci_wordpartrightextend = 2393
visible_slop = 1
visible_strict = 4
sci_setvisiblepolicy = 2394
sci_dellineleft = 2395
sci_dellineright = 2396
sci_setxoffset = 2397
sci_getxoffset = 2398
sci_choosecaretx = 2399
sci_grabfocus = 2400
caret_slop = 1
caret_strict = 4
caret_jumps = 16
caret_even = 8
sci_setxcaretpolicy = 2402
sci_setycaretpolicy = 2403
sci_setprintwrapmode = 2406
sci_getprintwrapmode = 2407
sci_sethotspotactivefore = 2410
sci_sethotspotactiveback = 2411
sci_sethotspotactiveunderline = 2412
sci_sethotspotsingleline = 2421
sci_paradown = 2413
sci_paradownextend = 2414
sci_paraup = 2415
sci_paraupextend = 2416
sci_positionbefore = 2417
sci_positionafter = 2418
sci_copyrange = 2419
sci_copytext = 2420
sc_sel_stream = 0
sc_sel_rectangle = 1
sc_sel_lines = 2
sci_setselectionmode = 2422
sci_getselectionmode = 2423
sci_getlineselstartposition = 2424
sci_getlineselendposition = 2425
sci_linedownrectextend = 2426
sci_lineuprectextend = 2427
sci_charleftrectextend = 2428
sci_charrightrectextend = 2429
sci_homerectextend = 2430
sci_vchomerectextend = 2431
sci_lineendrectextend = 2432
sci_pageuprectextend = 2433
sci_pagedownrectextend = 2434
sci_stutteredpageup = 2435
sci_stutteredpageupextend = 2436
sci_stutteredpagedown = 2437
sci_stutteredpagedownextend = 2438
sci_wordleftend = 2439
sci_wordleftendextend = 2440
sci_wordrightend = 2441
sci_wordrightendextend = 2442
sci_setwhitespacechars = 2443
sci_setcharsdefault = 2444
sci_startrecord = 3001
sci_stoprecord = 3002
sci_setlexer = 4001
sci_getlexer = 4002
sci_colourise = 4003
sci_setproperty = 4004
keywordset_max = 8
sci_setkeywords = 4005
sci_setlexerlanguage = 4006
sci_loadlexerlibrary = 4007
sc_mod_inserttext = 1
sc_mod_deletetext = 2
sc_mod_changestyle = 4
sc_mod_changefold = 8
sc_performed_user = 16
sc_performed_undo = 32
sc_performed_redo = 64
sc_laststepinundoredo = 256
sc_mod_changemarker = 512
sc_mod_beforeinsert = 1024
sc_mod_beforedelete = 2048
sc_modeventmaskall = 3959
scen_change = 768
scen_setfocus = 512
scen_killfocus = 256
sck_down = 300
sck_up = 301
sck_left = 302
sck_right = 303
sck_home = 304
sck_end = 305
sck_prior = 306
sck_next = 307
sck_delete = 308
sck_insert = 309
sck_escape = 7
sck_back = 8
sck_tab = 9
sck_return = 13
sck_add = 310
sck_subtract = 311
sck_divide = 312
scmod_shift = 1
scmod_ctrl = 2
scmod_alt = 4
scn_styleneeded = 2000
scn_charadded = 2001
scn_savepointreached = 2002
scn_savepointleft = 2003
scn_modifyattemptro = 2004
scn_key = 2005
scn_doubleclick = 2006
scn_updateui = 2007
scn_modified = 2008
scn_macrorecord = 2009
scn_marginclick = 2010
scn_needshown = 2011
scn_painted = 2013
scn_userlistselection = 2014
scn_uridropped = 2015
scn_dwellstart = 2016
scn_dwellend = 2017
scn_zoom = 2018
scn_hotspotclick = 2019
scn_hotspotdoubleclick = 2020
scn_calltipclick = 2021
sci_setcaretpolicy = 2369
caret_center = 2
caret_xeven = 8
caret_xjumps = 16
scn_poschanged = 2012
scn_checkbrace = 2007
sclex_container = 0
sclex_null = 1
sclex_python = 2
sclex_cpp = 3
sclex_html = 4
sclex_xml = 5
sclex_perl = 6
sclex_sql = 7
sclex_vb = 8
sclex_properties = 9
sclex_errorlist = 10
sclex_makefile = 11
sclex_batch = 12
sclex_xcode = 13
sclex_latex = 14
sclex_lua = 15
sclex_diff = 16
sclex_conf = 17
sclex_pascal = 18
sclex_ave = 19
sclex_ada = 20
sclex_lisp = 21
sclex_ruby = 22
sclex_eiffel = 23
sclex_eiffelkw = 24
sclex_tcl = 25
sclex_nncrontab = 26
sclex_bullant = 27
sclex_vbscript = 28
sclex_asp = 29
sclex_php = 30
sclex_baan = 31
sclex_matlab = 32
sclex_scriptol = 33
sclex_asm = 34
sclex_cppnocase = 35
sclex_fortran = 36
sclex_f77 = 37
sclex_css = 38
sclex_pov = 39
sclex_lout = 40
sclex_escript = 41
sclex_ps = 42
sclex_nsis = 43
sclex_mmixal = 44
sclex_clw = 45
sclex_clwnocase = 46
sclex_lot = 47
sclex_yaml = 48
sclex_tex = 49
sclex_metapost = 50
sclex_powerbasic = 51
sclex_forth = 52
sclex_erlang = 53
sclex_automatic = 1000
sce_p_default = 0
sce_p_commentline = 1
sce_p_number = 2
sce_p_string = 3
sce_p_character = 4
sce_p_word = 5
sce_p_triple = 6
sce_p_tripledouble = 7
sce_p_classname = 8
sce_p_defname = 9
sce_p_operator = 10
sce_p_identifier = 11
sce_p_commentblock = 12
sce_p_stringeol = 13
sce_c_default = 0
sce_c_comment = 1
sce_c_commentline = 2
sce_c_commentdoc = 3
sce_c_number = 4
sce_c_word = 5
sce_c_string = 6
sce_c_character = 7
sce_c_uuid = 8
sce_c_preprocessor = 9
sce_c_operator = 10
sce_c_identifier = 11
sce_c_stringeol = 12
sce_c_verbatim = 13
sce_c_regex = 14
sce_c_commentlinedoc = 15
sce_c_word2 = 16
sce_c_commentdockeyword = 17
sce_c_commentdockeyworderror = 18
sce_c_globalclass = 19
sce_h_default = 0
sce_h_tag = 1
sce_h_tagunknown = 2
sce_h_attribute = 3
sce_h_attributeunknown = 4
sce_h_number = 5
sce_h_doublestring = 6
sce_h_singlestring = 7
sce_h_other = 8
sce_h_comment = 9
sce_h_entity = 10
sce_h_tagend = 11
sce_h_xmlstart = 12
sce_h_xmlend = 13
sce_h_script = 14
sce_h_asp = 15
sce_h_aspat = 16
sce_h_cdata = 17
sce_h_question = 18
sce_h_value = 19
sce_h_xccomment = 20
sce_h_sgml_default = 21
sce_h_sgml_command = 22
sce_h_sgml_1_st_param = 23
sce_h_sgml_doublestring = 24
sce_h_sgml_simplestring = 25
sce_h_sgml_error = 26
sce_h_sgml_special = 27
sce_h_sgml_entity = 28
sce_h_sgml_comment = 29
sce_h_sgml_1_st_param_comment = 30
sce_h_sgml_block_default = 31
sce_hj_start = 40
sce_hj_default = 41
sce_hj_comment = 42
sce_hj_commentline = 43
sce_hj_commentdoc = 44
sce_hj_number = 45
sce_hj_word = 46
sce_hj_keyword = 47
sce_hj_doublestring = 48
sce_hj_singlestring = 49
sce_hj_symbols = 50
sce_hj_stringeol = 51
sce_hj_regex = 52
sce_hja_start = 55
sce_hja_default = 56
sce_hja_comment = 57
sce_hja_commentline = 58
sce_hja_commentdoc = 59
sce_hja_number = 60
sce_hja_word = 61
sce_hja_keyword = 62
sce_hja_doublestring = 63
sce_hja_singlestring = 64
sce_hja_symbols = 65
sce_hja_stringeol = 66
sce_hja_regex = 67
sce_hb_start = 70
sce_hb_default = 71
sce_hb_commentline = 72
sce_hb_number = 73
sce_hb_word = 74
sce_hb_string = 75
sce_hb_identifier = 76
sce_hb_stringeol = 77
sce_hba_start = 80
sce_hba_default = 81
sce_hba_commentline = 82
sce_hba_number = 83
sce_hba_word = 84
sce_hba_string = 85
sce_hba_identifier = 86
sce_hba_stringeol = 87
sce_hp_start = 90
sce_hp_default = 91
sce_hp_commentline = 92
sce_hp_number = 93
sce_hp_string = 94
sce_hp_character = 95
sce_hp_word = 96
sce_hp_triple = 97
sce_hp_tripledouble = 98
sce_hp_classname = 99
sce_hp_defname = 100
sce_hp_operator = 101
sce_hp_identifier = 102
sce_hpa_start = 105
sce_hpa_default = 106
sce_hpa_commentline = 107
sce_hpa_number = 108
sce_hpa_string = 109
sce_hpa_character = 110
sce_hpa_word = 111
sce_hpa_triple = 112
sce_hpa_tripledouble = 113
sce_hpa_classname = 114
sce_hpa_defname = 115
sce_hpa_operator = 116
sce_hpa_identifier = 117
sce_hphp_default = 118
sce_hphp_hstring = 119
sce_hphp_simplestring = 120
sce_hphp_word = 121
sce_hphp_number = 122
sce_hphp_variable = 123
sce_hphp_comment = 124
sce_hphp_commentline = 125
sce_hphp_hstring_variable = 126
sce_hphp_operator = 127
sce_pl_default = 0
sce_pl_error = 1
sce_pl_commentline = 2
sce_pl_pod = 3
sce_pl_number = 4
sce_pl_word = 5
sce_pl_string = 6
sce_pl_character = 7
sce_pl_punctuation = 8
sce_pl_preprocessor = 9
sce_pl_operator = 10
sce_pl_identifier = 11
sce_pl_scalar = 12
sce_pl_array = 13
sce_pl_hash = 14
sce_pl_symboltable = 15
sce_pl_regex = 17
sce_pl_regsubst = 18
sce_pl_longquote = 19
sce_pl_backticks = 20
sce_pl_datasection = 21
sce_pl_here_delim = 22
sce_pl_here_q = 23
sce_pl_here_qq = 24
sce_pl_here_qx = 25
sce_pl_string_q = 26
sce_pl_string_qq = 27
sce_pl_string_qx = 28
sce_pl_string_qr = 29
sce_pl_string_qw = 30
sce_b_default = 0
sce_b_comment = 1
sce_b_number = 2
sce_b_keyword = 3
sce_b_string = 4
sce_b_preprocessor = 5
sce_b_operator = 6
sce_b_identifier = 7
sce_b_date = 8
sce_props_default = 0
sce_props_comment = 1
sce_props_section = 2
sce_props_assignment = 3
sce_props_defval = 4
sce_l_default = 0
sce_l_command = 1
sce_l_tag = 2
sce_l_math = 3
sce_l_comment = 4
sce_lua_default = 0
sce_lua_comment = 1
sce_lua_commentline = 2
sce_lua_commentdoc = 3
sce_lua_number = 4
sce_lua_word = 5
sce_lua_string = 6
sce_lua_character = 7
sce_lua_literalstring = 8
sce_lua_preprocessor = 9
sce_lua_operator = 10
sce_lua_identifier = 11
sce_lua_stringeol = 12
sce_lua_word2 = 13
sce_lua_word3 = 14
sce_lua_word4 = 15
sce_lua_word5 = 16
sce_lua_word6 = 17
sce_lua_word7 = 18
sce_lua_word8 = 19
sce_err_default = 0
sce_err_python = 1
sce_err_gcc = 2
sce_err_ms = 3
sce_err_cmd = 4
sce_err_borland = 5
sce_err_perl = 6
sce_err_net = 7
sce_err_lua = 8
sce_err_ctag = 9
sce_err_diff_changed = 10
sce_err_diff_addition = 11
sce_err_diff_deletion = 12
sce_err_diff_message = 13
sce_err_php = 14
sce_err_elf = 15
sce_err_ifc = 16
sce_bat_default = 0
sce_bat_comment = 1
sce_bat_word = 2
sce_bat_label = 3
sce_bat_hide = 4
sce_bat_command = 5
sce_bat_identifier = 6
sce_bat_operator = 7
sce_make_default = 0
sce_make_comment = 1
sce_make_preprocessor = 2
sce_make_identifier = 3
sce_make_operator = 4
sce_make_target = 5
sce_make_ideol = 9
sce_diff_default = 0
sce_diff_comment = 1
sce_diff_command = 2
sce_diff_header = 3
sce_diff_position = 4
sce_diff_deleted = 5
sce_diff_added = 6
sce_conf_default = 0
sce_conf_comment = 1
sce_conf_number = 2
sce_conf_identifier = 3
sce_conf_extension = 4
sce_conf_parameter = 5
sce_conf_string = 6
sce_conf_operator = 7
sce_conf_ip = 8
sce_conf_directive = 9
sce_ave_default = 0
sce_ave_comment = 1
sce_ave_number = 2
sce_ave_word = 3
sce_ave_string = 6
sce_ave_enum = 7
sce_ave_stringeol = 8
sce_ave_identifier = 9
sce_ave_operator = 10
sce_ave_word1 = 11
sce_ave_word2 = 12
sce_ave_word3 = 13
sce_ave_word4 = 14
sce_ave_word5 = 15
sce_ave_word6 = 16
sce_ada_default = 0
sce_ada_word = 1
sce_ada_identifier = 2
sce_ada_number = 3
sce_ada_delimiter = 4
sce_ada_character = 5
sce_ada_charactereol = 6
sce_ada_string = 7
sce_ada_stringeol = 8
sce_ada_label = 9
sce_ada_commentline = 10
sce_ada_illegal = 11
sce_baan_default = 0
sce_baan_comment = 1
sce_baan_commentdoc = 2
sce_baan_number = 3
sce_baan_word = 4
sce_baan_string = 5
sce_baan_preprocessor = 6
sce_baan_operator = 7
sce_baan_identifier = 8
sce_baan_stringeol = 9
sce_baan_word2 = 10
sce_lisp_default = 0
sce_lisp_comment = 1
sce_lisp_number = 2
sce_lisp_keyword = 3
sce_lisp_string = 6
sce_lisp_stringeol = 8
sce_lisp_identifier = 9
sce_lisp_operator = 10
sce_eiffel_default = 0
sce_eiffel_commentline = 1
sce_eiffel_number = 2
sce_eiffel_word = 3
sce_eiffel_string = 4
sce_eiffel_character = 5
sce_eiffel_operator = 6
sce_eiffel_identifier = 7
sce_eiffel_stringeol = 8
sce_nncrontab_default = 0
sce_nncrontab_comment = 1
sce_nncrontab_task = 2
sce_nncrontab_section = 3
sce_nncrontab_keyword = 4
sce_nncrontab_modifier = 5
sce_nncrontab_asterisk = 6
sce_nncrontab_number = 7
sce_nncrontab_string = 8
sce_nncrontab_environment = 9
sce_nncrontab_identifier = 10
sce_forth_default = 0
sce_forth_comment = 1
sce_forth_comment_ml = 2
sce_forth_identifier = 3
sce_forth_control = 4
sce_forth_keyword = 5
sce_forth_defword = 6
sce_forth_preword1 = 7
sce_forth_preword2 = 8
sce_forth_number = 9
sce_forth_string = 10
sce_forth_locale = 11
sce_matlab_default = 0
sce_matlab_comment = 1
sce_matlab_command = 2
sce_matlab_number = 3
sce_matlab_keyword = 4
sce_matlab_string = 5
sce_matlab_operator = 6
sce_matlab_identifier = 7
sce_scriptol_default = 0
sce_scriptol_white = 1
sce_scriptol_commentline = 2
sce_scriptol_persistent = 3
sce_scriptol_cstyle = 4
sce_scriptol_commentblock = 5
sce_scriptol_number = 6
sce_scriptol_string = 7
sce_scriptol_character = 8
sce_scriptol_stringeol = 9
sce_scriptol_keyword = 10
sce_scriptol_operator = 11
sce_scriptol_identifier = 12
sce_scriptol_triple = 13
sce_scriptol_classname = 14
sce_scriptol_preprocessor = 15
sce_asm_default = 0
sce_asm_comment = 1
sce_asm_number = 2
sce_asm_string = 3
sce_asm_operator = 4
sce_asm_identifier = 5
sce_asm_cpuinstruction = 6
sce_asm_mathinstruction = 7
sce_asm_register = 8
sce_asm_directive = 9
sce_asm_directiveoperand = 10
sce_asm_commentblock = 11
sce_asm_character = 12
sce_asm_stringeol = 13
sce_asm_extinstruction = 14
sce_f_default = 0
sce_f_comment = 1
sce_f_number = 2
sce_f_string1 = 3
sce_f_string2 = 4
sce_f_stringeol = 5
sce_f_operator = 6
sce_f_identifier = 7
sce_f_word = 8
sce_f_word2 = 9
sce_f_word3 = 10
sce_f_preprocessor = 11
sce_f_operator2 = 12
sce_f_label = 13
sce_f_continuation = 14
sce_css_default = 0
sce_css_tag = 1
sce_css_class = 2
sce_css_pseudoclass = 3
sce_css_unknown_pseudoclass = 4
sce_css_operator = 5
sce_css_identifier = 6
sce_css_unknown_identifier = 7
sce_css_value = 8
sce_css_comment = 9
sce_css_id = 10
sce_css_important = 11
sce_css_directive = 12
sce_css_doublestring = 13
sce_css_singlestring = 14
sce_pov_default = 0
sce_pov_comment = 1
sce_pov_commentline = 2
sce_pov_number = 3
sce_pov_operator = 4
sce_pov_identifier = 5
sce_pov_string = 6
sce_pov_stringeol = 7
sce_pov_directive = 8
sce_pov_baddirective = 9
sce_pov_word2 = 10
sce_pov_word3 = 11
sce_pov_word4 = 12
sce_pov_word5 = 13
sce_pov_word6 = 14
sce_pov_word7 = 15
sce_pov_word8 = 16
sce_lout_default = 0
sce_lout_comment = 1
sce_lout_number = 2
sce_lout_word = 3
sce_lout_word2 = 4
sce_lout_word3 = 5
sce_lout_word4 = 6
sce_lout_string = 7
sce_lout_operator = 8
sce_lout_identifier = 9
sce_lout_stringeol = 10
sce_escript_default = 0
sce_escript_comment = 1
sce_escript_commentline = 2
sce_escript_commentdoc = 3
sce_escript_number = 4
sce_escript_word = 5
sce_escript_string = 6
sce_escript_operator = 7
sce_escript_identifier = 8
sce_escript_brace = 9
sce_escript_word2 = 10
sce_escript_word3 = 11
sce_ps_default = 0
sce_ps_comment = 1
sce_ps_dsc_comment = 2
sce_ps_dsc_value = 3
sce_ps_number = 4
sce_ps_name = 5
sce_ps_keyword = 6
sce_ps_literal = 7
sce_ps_immeval = 8
sce_ps_paren_array = 9
sce_ps_paren_dict = 10
sce_ps_paren_proc = 11
sce_ps_text = 12
sce_ps_hexstring = 13
sce_ps_base85_string = 14
sce_ps_badstringchar = 15
sce_nsis_default = 0
sce_nsis_comment = 1
sce_nsis_stringdq = 2
sce_nsis_stringlq = 3
sce_nsis_stringrq = 4
sce_nsis_function = 5
sce_nsis_variable = 6
sce_nsis_label = 7
sce_nsis_userdefined = 8
sce_nsis_sectiondef = 9
sce_nsis_subsectiondef = 10
sce_nsis_ifdefinedef = 11
sce_nsis_macrodef = 12
sce_nsis_stringvar = 13
sce_mmixal_leadws = 0
sce_mmixal_comment = 1
sce_mmixal_label = 2
sce_mmixal_opcode = 3
sce_mmixal_opcode_pre = 4
sce_mmixal_opcode_valid = 5
sce_mmixal_opcode_unknown = 6
sce_mmixal_opcode_post = 7
sce_mmixal_operands = 8
sce_mmixal_number = 9
sce_mmixal_ref = 10
sce_mmixal_char = 11
sce_mmixal_string = 12
sce_mmixal_register = 13
sce_mmixal_hex = 14
sce_mmixal_operator = 15
sce_mmixal_symbol = 16
sce_mmixal_include = 17
sce_clw_default = 0
sce_clw_label = 1
sce_clw_comment = 2
sce_clw_string = 3
sce_clw_user_identifier = 4
sce_clw_integer_constant = 5
sce_clw_real_constant = 6
sce_clw_picture_string = 7
sce_clw_keyword = 8
sce_clw_compiler_directive = 9
sce_clw_builtin_procedures_function = 10
sce_clw_structure_data_type = 11
sce_clw_attribute = 12
sce_clw_standard_equate = 13
sce_clw_error = 14
sce_lot_default = 0
sce_lot_header = 1
sce_lot_break = 2
sce_lot_set = 3
sce_lot_pass = 4
sce_lot_fail = 5
sce_lot_abort = 6
sce_yaml_default = 0
sce_yaml_comment = 1
sce_yaml_identifier = 2
sce_yaml_keyword = 3
sce_yaml_number = 4
sce_yaml_reference = 5
sce_yaml_document = 6
sce_yaml_text = 7
sce_yaml_error = 8
sce_tex_default = 0
sce_tex_special = 1
sce_tex_group = 2
sce_tex_symbol = 3
sce_tex_command = 4
sce_tex_text = 5
sce_metapost_default = 0
sce_metapost_special = 1
sce_metapost_group = 2
sce_metapost_symbol = 3
sce_metapost_command = 4
sce_metapost_text = 5
sce_metapost_extra = 6
sce_erlang_default = 0
sce_erlang_comment = 1
sce_erlang_variable = 2
sce_erlang_number = 3
sce_erlang_keyword = 4
sce_erlang_string = 5
sce_erlang_operator = 6
sce_erlang_atom = 7
sce_erlang_function_name = 8
sce_erlang_character = 9
sce_erlang_macro = 10
sce_erlang_record = 11
sce_erlang_separator = 12
sce_erlang_node_name = 13
sce_erlang_unknown = 31
|
#
# @lc app=leetcode id=970 lang=python3
#
# [970] Powerful Integers
#
# @lc code=start
class Solution(object):
def powerfulIntegers(self, x, y, bound):
"""
:type x: int
:type y: int
:type bound: int
:rtype: List[int]
"""
r = []
if bound < 2:
return r
else:
i = 0
while x ** i + y ** 0 <= bound:
j = 0
while x ** i + y ** j <= bound:
r.append(x ** i + y ** j)
if y == 1:
break
j += 1
if x == 1:
break
i += 1
return set(r)
# @lc code=end
|
class Solution(object):
def powerful_integers(self, x, y, bound):
"""
:type x: int
:type y: int
:type bound: int
:rtype: List[int]
"""
r = []
if bound < 2:
return r
else:
i = 0
while x ** i + y ** 0 <= bound:
j = 0
while x ** i + y ** j <= bound:
r.append(x ** i + y ** j)
if y == 1:
break
j += 1
if x == 1:
break
i += 1
return set(r)
|
class Environment():
"""
This is used as an input to contruct the graph.
"""
def __init__(self, names, matrix, alpha, prop):
self.names = names # Names of Subclone Colony (List)
self.relations = matrix # Adj Matrix representing relations
self.alpha = alpha
self.prop = prop
def log(self):
print('Logging Environment:')
items = [f' --> {d}' for d in zip(self.names, self.alpha, self.prop)]
for i in items:
print(i)
print(20 * '-*')
def get_env_data(self):
return [d for d in zip(self.names, self.alpha, self.prop)]
|
class Environment:
"""
This is used as an input to contruct the graph.
"""
def __init__(self, names, matrix, alpha, prop):
self.names = names
self.relations = matrix
self.alpha = alpha
self.prop = prop
def log(self):
print('Logging Environment:')
items = [f' --> {d}' for d in zip(self.names, self.alpha, self.prop)]
for i in items:
print(i)
print(20 * '-*')
def get_env_data(self):
return [d for d in zip(self.names, self.alpha, self.prop)]
|
"""Toyota Connected Services API exceptions."""
class ToyotaLocaleNotValid(Exception):
"""Raise if locale string is not valid."""
class ToyotaLoginError(Exception):
"""Raise if a login error happens."""
class ToyotaInvalidToken(Exception):
"""Raise if token is invalid"""
class ToyotaInvalidUsername(Exception):
"""Raise if username is invalid"""
class ToyotaRegionNotSupported(Exception):
"""Raise if region is not supported"""
class ToyotaApiError(Exception):
"""Raise if a API error occurres."""
class ToyotaInternalError(Exception):
"""Raise if an internal server error occurres from Toyota."""
|
"""Toyota Connected Services API exceptions."""
class Toyotalocalenotvalid(Exception):
"""Raise if locale string is not valid."""
class Toyotaloginerror(Exception):
"""Raise if a login error happens."""
class Toyotainvalidtoken(Exception):
"""Raise if token is invalid"""
class Toyotainvalidusername(Exception):
"""Raise if username is invalid"""
class Toyotaregionnotsupported(Exception):
"""Raise if region is not supported"""
class Toyotaapierror(Exception):
"""Raise if a API error occurres."""
class Toyotainternalerror(Exception):
"""Raise if an internal server error occurres from Toyota."""
|
#!/usr/bin/env python3
# https://codeforces.com/problemset/problem/1296/A
def odd(a,n):
odd1 = a[0]%2
if odd1==1 and n%2==1:
return 'YES'
for i in range(1,n):
if a[i]%2 != odd1:
return 'YES'
return 'NO'
t = int(input())
for _ in range(t):
n = int(input())
al = list(map(int,input().split()))
print(odd(al,n))
|
def odd(a, n):
odd1 = a[0] % 2
if odd1 == 1 and n % 2 == 1:
return 'YES'
for i in range(1, n):
if a[i] % 2 != odd1:
return 'YES'
return 'NO'
t = int(input())
for _ in range(t):
n = int(input())
al = list(map(int, input().split()))
print(odd(al, n))
|
def play_game(turns, start, nodes, max_cup_label):
current_cup = start_label
move = 0
while move < turns:
# Snip out a sub graph of length 3
sub_graph_start = nodes[current_cup]
pickup = []
cur = sub_graph_start
for _ in range(3):
pickup.append(cur)
cur = nodes[cur]
# Find the next destination cup
dest_cup = current_cup - 1
while dest_cup in pickup or dest_cup < 1:
dest_cup -= 1
if dest_cup < 1:
dest_cup = max_cup_label
# remove subgraph, by updating nodes
nodes[current_cup] = cur
# Put back in after dest_cup
temp = nodes[dest_cup]
nodes[dest_cup] = sub_graph_start
nodes[nodes[nodes[sub_graph_start]]] = temp
# Move onto the next cup
current_cup = cur
move += 1
#### PART 1
day23_input = [int(x) for x in "389125467"]
#day23_input = [int(x) for x in "562893147"]
start_label = day23_input[0]
# Create the mapping node -> node
nodes = {day23_input[0]: day23_input[1]}
for x in range(1, len(day23_input)-1):
nodes[day23_input[x]] = day23_input[x+1]
# Create the cycle
nodes[day23_input[-1]] = day23_input[0]
play_game(100, start_label, nodes, max(day23_input))
# Solution
start = nodes[1]
nums = []
for _ in range(len(day23_input)-1):
nums.append(str(start))
start = nodes[start]
print("part 1", "".join(nums))
#### PART 2
#day23_input = [int(x) for x in "389125467"]
day23_input = [int(x) for x in "562893147"]
max_cup_label = max(day23_input)
start_label = day23_input[0]
nodes = { day23_input[0]: day23_input[1]}
for x in range(1, len(day23_input)-1):
nodes[day23_input[x]] = day23_input[x+1]
for i in range(max_cup_label+1,1000000+1):
nodes[i] = i+1
# connect the two graphs
nodes[day23_input[-1]] = max_cup_label+1
# make it cyclical
nodes[1000000] = start_label
play_game(10000000, start_label, nodes, 1000000)
# Part 2
print("part 2", nodes[1] * nodes[nodes[1]])
|
def play_game(turns, start, nodes, max_cup_label):
current_cup = start_label
move = 0
while move < turns:
sub_graph_start = nodes[current_cup]
pickup = []
cur = sub_graph_start
for _ in range(3):
pickup.append(cur)
cur = nodes[cur]
dest_cup = current_cup - 1
while dest_cup in pickup or dest_cup < 1:
dest_cup -= 1
if dest_cup < 1:
dest_cup = max_cup_label
nodes[current_cup] = cur
temp = nodes[dest_cup]
nodes[dest_cup] = sub_graph_start
nodes[nodes[nodes[sub_graph_start]]] = temp
current_cup = cur
move += 1
day23_input = [int(x) for x in '389125467']
start_label = day23_input[0]
nodes = {day23_input[0]: day23_input[1]}
for x in range(1, len(day23_input) - 1):
nodes[day23_input[x]] = day23_input[x + 1]
nodes[day23_input[-1]] = day23_input[0]
play_game(100, start_label, nodes, max(day23_input))
start = nodes[1]
nums = []
for _ in range(len(day23_input) - 1):
nums.append(str(start))
start = nodes[start]
print('part 1', ''.join(nums))
day23_input = [int(x) for x in '562893147']
max_cup_label = max(day23_input)
start_label = day23_input[0]
nodes = {day23_input[0]: day23_input[1]}
for x in range(1, len(day23_input) - 1):
nodes[day23_input[x]] = day23_input[x + 1]
for i in range(max_cup_label + 1, 1000000 + 1):
nodes[i] = i + 1
nodes[day23_input[-1]] = max_cup_label + 1
nodes[1000000] = start_label
play_game(10000000, start_label, nodes, 1000000)
print('part 2', nodes[1] * nodes[nodes[1]])
|
listTotal = []
listPar = []
listImpar = []
for c in range(1, 21):
n = int(input("Digite um numero: "))
if n % 2 == 0:
listTotal.append(n)
listPar.append(n)
else:
listImpar.append(n)
listTotal.append(n)
print(f'{listTotal}\n{listPar}\n{listImpar}')
|
list_total = []
list_par = []
list_impar = []
for c in range(1, 21):
n = int(input('Digite um numero: '))
if n % 2 == 0:
listTotal.append(n)
listPar.append(n)
else:
listImpar.append(n)
listTotal.append(n)
print(f'{listTotal}\n{listPar}\n{listImpar}')
|
# Copyright (c) 2018 Huawei Technologies Co., Ltd.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
class SDKException(Exception):
def __init__(self, code=None, message=None):
self._code = code
self._message = message
def __str__(self):
return "[SDKException] Message:%s Code:%s ." % (self.message,
self.code)
@property
def code(self):
return self._code
@property
def message(self):
return self._message
class EndpointResolveException(SDKException):
def __init__(self, message):
message = "Failed to resolve endpoint: {}".format(message)
super(EndpointResolveException, self).__init__(code=None,
message=message)
class ValueException(SDKException):
def __init__(self, message):
message = "Unexpected parameters are specified: {}.".format(message)
super(ValueException, self).__init__(code=None,
message=message)
class RequestException(SDKException):
def __init__(self, message):
message = "Failed to proceed request to service " \
"endpoint, could be a low level error: {}.".format(message)
super(RequestException, self).__init__(code=None,
message=message)
class AuthException(SDKException):
def __init__(self, message, credential):
message = "Failed to authorize with provided " \
"information {}, message: {}.".format(credential, message)
super(AuthException, self).__init__(code=None,
message=message)
class InvalidConfigException(SDKException):
def __init__(self, message):
message = "Invalid configurations: {}.".format(message)
super(SDKException, self).__init__(code=None, message=message)
|
class Sdkexception(Exception):
def __init__(self, code=None, message=None):
self._code = code
self._message = message
def __str__(self):
return '[SDKException] Message:%s Code:%s .' % (self.message, self.code)
@property
def code(self):
return self._code
@property
def message(self):
return self._message
class Endpointresolveexception(SDKException):
def __init__(self, message):
message = 'Failed to resolve endpoint: {}'.format(message)
super(EndpointResolveException, self).__init__(code=None, message=message)
class Valueexception(SDKException):
def __init__(self, message):
message = 'Unexpected parameters are specified: {}.'.format(message)
super(ValueException, self).__init__(code=None, message=message)
class Requestexception(SDKException):
def __init__(self, message):
message = 'Failed to proceed request to service endpoint, could be a low level error: {}.'.format(message)
super(RequestException, self).__init__(code=None, message=message)
class Authexception(SDKException):
def __init__(self, message, credential):
message = 'Failed to authorize with provided information {}, message: {}.'.format(credential, message)
super(AuthException, self).__init__(code=None, message=message)
class Invalidconfigexception(SDKException):
def __init__(self, message):
message = 'Invalid configurations: {}.'.format(message)
super(SDKException, self).__init__(code=None, message=message)
|
# Definition for singly-linked list with a random pointer.
# class RandomListNode(object):
# def __init__(self, x):
# self.label = x
# self.next = None
# self.random = None
class Solution(object):
def copyRandomList(self, head):
"""
:type head: RandomListNode
:rtype: RandomListNode
"""
if head is None:
return None
# append copy node behind its orignal one
# 1 -> 1' -> 2 -> 2' -> .... -> n -> n' -> None
current = head
while (current is not None):
node = RandomListNode(current.label)
node.next = current.next
current.next = node
current = current.next.next
# copy random pointers
current = head
while(current is not None):
if current.random is not None:
current.next.random = current.random.next
current = current.next.next
# construct new linked list
new_head = head.next
new_cur = new_head
old_cur = head
while(new_cur is not None):
old_cur.next = new_cur.next
if new_cur.next is not None:
new_cur.next = new_cur.next.next
new_cur = new_cur.next
old_cur = old_cur.next
return new_head
|
class Solution(object):
def copy_random_list(self, head):
"""
:type head: RandomListNode
:rtype: RandomListNode
"""
if head is None:
return None
current = head
while current is not None:
node = random_list_node(current.label)
node.next = current.next
current.next = node
current = current.next.next
current = head
while current is not None:
if current.random is not None:
current.next.random = current.random.next
current = current.next.next
new_head = head.next
new_cur = new_head
old_cur = head
while new_cur is not None:
old_cur.next = new_cur.next
if new_cur.next is not None:
new_cur.next = new_cur.next.next
new_cur = new_cur.next
old_cur = old_cur.next
return new_head
|
class A:
def f1(self):
print("F1 is working")
def f2(self):
print("F2 is working")
class B():
def f3(self):
print("F3 is working")
def f4(self):
print("F4 is working")
class C(A,B): #Multiple Inheriatance
def f5(self):
print("F5 is working")
a1=A()
a1.f1()
a1.f2()
b1=B()
b1.f3()
b1.f4() #calling inherit method from A f4
c1=C()
c1.f5() #Inherits from A<-B<-C
c1.f1()
|
class A:
def f1(self):
print('F1 is working')
def f2(self):
print('F2 is working')
class B:
def f3(self):
print('F3 is working')
def f4(self):
print('F4 is working')
class C(A, B):
def f5(self):
print('F5 is working')
a1 = a()
a1.f1()
a1.f2()
b1 = b()
b1.f3()
b1.f4()
c1 = c()
c1.f5()
c1.f1()
|
# Input Cases
t = int(input("\nTotal Test Cases : "))
for i in range(1,t+1):
print(f"\n------------ CASE #{i} -------------")
n = int(input("\nTotal Items : "))
m = int(input("Max Capacity : "))
v = [int(i) for i in input("\nValues : ").split(" ")]
w = [int(i) for i in input("Weights : ").split(" ")]
# Tabulation (DP)
dp = [[0 for x in range(m+1)] for x in range(n+1)]
for i in range(n+1):
for j in range(m+1):
if i == 0 or j == 0:
dp[i][j] = 0
elif w[i-1]<=j:
dp[i][j] = max(dp[i-1][j],dp[i-1][j-w[i-1]]+v[i-1])
else:
dp[i][j] = dp[i-1][j]
print(f"\nMax Value Picked : {dp[n][m]}")
|
t = int(input('\nTotal Test Cases : '))
for i in range(1, t + 1):
print(f'\n------------ CASE #{i} -------------')
n = int(input('\nTotal Items : '))
m = int(input('Max Capacity : '))
v = [int(i) for i in input('\nValues : ').split(' ')]
w = [int(i) for i in input('Weights : ').split(' ')]
dp = [[0 for x in range(m + 1)] for x in range(n + 1)]
for i in range(n + 1):
for j in range(m + 1):
if i == 0 or j == 0:
dp[i][j] = 0
elif w[i - 1] <= j:
dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - w[i - 1]] + v[i - 1])
else:
dp[i][j] = dp[i - 1][j]
print(f'\nMax Value Picked : {dp[n][m]}')
|
# https://www.hackerrank.com/challenges/candies/problem
n = int(input())
arr = [int(input()) for _ in range(n)]
candies = [1] * n
for i in range(1, n):
if arr[i - 1] < arr[i]:
candies[i] = candies[i - 1] + 1
for i in range(n - 2, -1, -1):
if arr[i + 1] < arr[i]:
if i - 1 >= 0 and arr[i - 1] < arr[i]:
candies[i] = max(candies[i + 1], candies[i - 1]) + 1
else:
candies[i] = candies[i + 1] + 1
print(sum(candies))
|
n = int(input())
arr = [int(input()) for _ in range(n)]
candies = [1] * n
for i in range(1, n):
if arr[i - 1] < arr[i]:
candies[i] = candies[i - 1] + 1
for i in range(n - 2, -1, -1):
if arr[i + 1] < arr[i]:
if i - 1 >= 0 and arr[i - 1] < arr[i]:
candies[i] = max(candies[i + 1], candies[i - 1]) + 1
else:
candies[i] = candies[i + 1] + 1
print(sum(candies))
|
"""A simple example for how to replace the provided artifact macro"""
load("@mabel//rules/maven_deps:mabel.bzl", "artifact")
def g_artifact(coordinate):
return artifact(coordinate = coordinate, repositories = ["https://maven.google.com/"], type = "naive")
|
"""A simple example for how to replace the provided artifact macro"""
load('@mabel//rules/maven_deps:mabel.bzl', 'artifact')
def g_artifact(coordinate):
return artifact(coordinate=coordinate, repositories=['https://maven.google.com/'], type='naive')
|
class DataFragment(object):
def length(self):
return 0;
class ConstDataFragment(object):
def __init__(self, name, data):
self.data = data
self.name = name
def length(self):
return len(self.data)
class ChoiceDataFragment(object):
def __init__(self):
pass
class StatisticsDataFragment(object):
@staticmethod
def create_length_statistics(name, depends):
pass
@staticmethod
def create_cs_statistics(name, depends):
pass
def __init__(self,name, depends):
self.name = name
self.depends = depends
class FixedLengthDataFragment(object):
def __init__(self, name, length, default_value):
self.name = name
self.length = length
self.default_value = default_value
class VariableDataFragment(object):
def __init__(self, name, depends):
self.name = name
self.depends = depends
# receive_str+="68 10 01 02 03 04 05 06 07 81 16 90 1F 96 00 55 55 05 2C 00 55 55 05 2C 00 00 00 00 00 00 00 00 00 26 16"
class CJT188Protocol(object):
def __init__(self):
self.name = "CJT188"
self.fragments = []
self.add_fragment(ConstDataFragment("head", chr(0x68)))
self.add_fragment(ConstDataFragment("type", chr(0x01)))
self.add_fragment(FixedLengthDataFragment("address", 7, chr(0xaa) * 7))
self.add_fragment(FixedLengthDataFragment("cmd", 1, chr(0x02)))
self.add_fragment(StatisticsDataFragment.create_length_statistics("length", 1, ("didunit",)))
self.add_fragment(VariableDataFragment("didunit", "length"))
self.add_fragment(StatisticsDataFragment.create_cs_statistics("cs", 1, ("head", "type", "address", "cmd", "didunit")))
self.add_fragment(ConstDataFragment("tail", chr(0x16)))
def add_fragment(self, fragment):
self.fragments.append(fragment)
|
class Datafragment(object):
def length(self):
return 0
class Constdatafragment(object):
def __init__(self, name, data):
self.data = data
self.name = name
def length(self):
return len(self.data)
class Choicedatafragment(object):
def __init__(self):
pass
class Statisticsdatafragment(object):
@staticmethod
def create_length_statistics(name, depends):
pass
@staticmethod
def create_cs_statistics(name, depends):
pass
def __init__(self, name, depends):
self.name = name
self.depends = depends
class Fixedlengthdatafragment(object):
def __init__(self, name, length, default_value):
self.name = name
self.length = length
self.default_value = default_value
class Variabledatafragment(object):
def __init__(self, name, depends):
self.name = name
self.depends = depends
class Cjt188Protocol(object):
def __init__(self):
self.name = 'CJT188'
self.fragments = []
self.add_fragment(const_data_fragment('head', chr(104)))
self.add_fragment(const_data_fragment('type', chr(1)))
self.add_fragment(fixed_length_data_fragment('address', 7, chr(170) * 7))
self.add_fragment(fixed_length_data_fragment('cmd', 1, chr(2)))
self.add_fragment(StatisticsDataFragment.create_length_statistics('length', 1, ('didunit',)))
self.add_fragment(variable_data_fragment('didunit', 'length'))
self.add_fragment(StatisticsDataFragment.create_cs_statistics('cs', 1, ('head', 'type', 'address', 'cmd', 'didunit')))
self.add_fragment(const_data_fragment('tail', chr(22)))
def add_fragment(self, fragment):
self.fragments.append(fragment)
|
""" There is a ball in a maze with empty spaces (represented as 0) and walls
(represented as 1). The ball can go through the empty spaces by rolling up,
down, left or right, but it won't stop rolling until hitting a wall. When the
ball stops, it could choose the next direction.
Given the maze, the ball's start position and the destination, where start =
[startrow, startcol] and destination = [destinationrow, destinationcol],
return true if the ball can stop at the destination, otherwise return false.
You may assume that the borders of the maze are all walls (see examples)
IDEA:
almost pure BFS, with additional code to calc stable position
"""
class Solution490:
pass
|
""" There is a ball in a maze with empty spaces (represented as 0) and walls
(represented as 1). The ball can go through the empty spaces by rolling up,
down, left or right, but it won't stop rolling until hitting a wall. When the
ball stops, it could choose the next direction.
Given the maze, the ball's start position and the destination, where start =
[startrow, startcol] and destination = [destinationrow, destinationcol],
return true if the ball can stop at the destination, otherwise return false.
You may assume that the borders of the maze are all walls (see examples)
IDEA:
almost pure BFS, with additional code to calc stable position
"""
class Solution490:
pass
|
class HttpStyleUriParser(UriParser):
"""
A customizable parser based on the HTTP scheme.
HttpStyleUriParser()
"""
|
class Httpstyleuriparser(UriParser):
"""
A customizable parser based on the HTTP scheme.
HttpStyleUriParser()
"""
|
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 5 19:13:44 2018
@author: farhan
"""
def draw(n):
if n == 1:
print('''
------
| |
| |
------
''')
if n ==2:
print('''
------
| |
| |
------
|
|
|
|
''')
if n == 3:
print('''
------
| |
| |
------
|
/|
/ |
|
''')
if n == 4:
print('''
------
| |
| |
------
|
/|\
/ | \
|
''')
if n == 5:
print('''
------
| |
| |
------
|
/|\
/ | \
|
/
/
''')
if n == 6:
print('''
------
| |
| |
------
|
/|\
/ | \
|
/ \
/ \
''')
|
"""
Created on Mon Feb 5 19:13:44 2018
@author: farhan
"""
def draw(n):
if n == 1:
print(' \n ------\n | |\n | |\n ------\n ')
if n == 2:
print(' \n ------\n | |\n | |\n ------\n |\n |\n |\n |\n \n ')
if n == 3:
print(' \n ------\n | |\n | |\n ------\n |\n /|\n / |\n |\n \n ')
if n == 4:
print('\n ------\n | |\n | |\n ------\n |\n /|\\ \n / | \\ \n |\n \n ')
if n == 5:
print(' \n ------\n | |\n | |\n ------\n |\n /|\\ \n / | \\ \n | \n / \n / \n ')
if n == 6:
print(' \n ------\n | |\n | |\n ------\n |\n /|\\ \n / | \\ \n |\n / \\ \n / \\ \n ')
|
class SecretsManager:
_boto3 = None
_environment = None
_secrets_manager = None
def __init__(self, boto3, environment):
self._boto3 = boto3
self._environment = environment
if not self._environment.get('AWS_REGION', True):
raise ValueError("To use secrets manager you must use set the 'AWS_REGION' environment variable")
self._secrets_manager = self._boto3.client('secretsmanager', region_name=self._environment.get('AWS_REGION'))
def get(self, secret_id, version_id=None, version_stage=None):
calling_parameters = {
'SecretId': secret_id,
'VersionId': version_id,
'VersionStage': version_stage,
}
calling_parameters = {key: value for (key, value) in calling_parameters.items() if value}
result = self._secrets_manager.get_secret_value(**calling_parameters)
if result.get('SecretString'):
return result.get('SecretString')
return result.get('SecretBinary')
def list_secrets(self, path):
raise NotImplementedError()
def update(self, path, value):
raise NotImplementedError()
|
class Secretsmanager:
_boto3 = None
_environment = None
_secrets_manager = None
def __init__(self, boto3, environment):
self._boto3 = boto3
self._environment = environment
if not self._environment.get('AWS_REGION', True):
raise value_error("To use secrets manager you must use set the 'AWS_REGION' environment variable")
self._secrets_manager = self._boto3.client('secretsmanager', region_name=self._environment.get('AWS_REGION'))
def get(self, secret_id, version_id=None, version_stage=None):
calling_parameters = {'SecretId': secret_id, 'VersionId': version_id, 'VersionStage': version_stage}
calling_parameters = {key: value for (key, value) in calling_parameters.items() if value}
result = self._secrets_manager.get_secret_value(**calling_parameters)
if result.get('SecretString'):
return result.get('SecretString')
return result.get('SecretBinary')
def list_secrets(self, path):
raise not_implemented_error()
def update(self, path, value):
raise not_implemented_error()
|
'''
Let's play the minesweeper game (Wikipedia, online game)!
You are given a 2D char matrix representing the game board. 'M' represents an unrevealed mine, 'E' represents an unrevealed empty square, 'B' represents a revealed blank square that has no adjacent (above, below, left, right, and all 4 diagonals) mines, digit ('1' to '8') represents how many mines are adjacent to this revealed square, and finally 'X' represents a revealed mine.
Now given the next click position (row and column indices) among all the unrevealed squares ('M' or 'E'), return the board after revealing this position according to the following rules:
If a mine ('M') is revealed, then the game is over - change it to 'X'.
If an empty square ('E') with no adjacent mines is revealed, then change it to revealed blank ('B') and all of its adjacent unrevealed squares should be revealed recursively.
If an empty square ('E') with at least one adjacent mine is revealed, then change it to a digit ('1' to '8') representing the number of adjacent mines.
Return the board when no more squares will be revealed.
Example 1:
Input:
[['E', 'E', 'E', 'E', 'E'],
['E', 'E', 'M', 'E', 'E'],
['E', 'E', 'E', 'E', 'E'],
['E', 'E', 'E', 'E', 'E']]
Click : [3,0]
Output:
[['B', '1', 'E', '1', 'B'],
['B', '1', 'M', '1', 'B'],
['B', '1', '1', '1', 'B'],
['B', 'B', 'B', 'B', 'B']]
Explanation:
Example 2:
Input:
[['B', '1', 'E', '1', 'B'],
['B', '1', 'M', '1', 'B'],
['B', '1', '1', '1', 'B'],
['B', 'B', 'B', 'B', 'B']]
Click : [1,2]
Output:
[['B', '1', 'E', '1', 'B'],
['B', '1', 'X', '1', 'B'],
['B', '1', '1', '1', 'B'],
['B', 'B', 'B', 'B', 'B']]
Explanation:
Note:
The range of the input matrix's height and width is [1,50].
The click position will only be an unrevealed square ('M' or 'E'), which also means the input board contains at least one clickable square.
The input board won't be a stage when game is over (some mines have been revealed).
For simplicity, not mentioned rules should be ignored in this problem. For example, you don't need to reveal all the unrevealed mines when the game is over, consider any cases that you will win the game or flag any squares.
'''
class Solution(object):
def updateBoard(self, board, click):
"""
:type board: List[List[str]]
:type click: List[int]
:rtype: List[List[str]]
"""
grid = [[board[i][j] for j in xrange(len(board[i]))] for i in xrange(len(board))]
if grid[click[0]][click[1]] == 'M':
grid[click[0]][click[1]] = 'X'
else:
# get number of mines in neighbors for each cell
count = [[0 for j in xrange(len(board[i]))] for i in xrange(len(board))]
for x in xrange(len(board)):
for y in xrange(len(board[i])):
tmp = 0
for i, j in [(0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, -1), (-1, 1)]:
xx, yy = x+i, y+j
if 0 <= xx < len(board) and 0 <= yy < len(board[0]):
if board[xx][yy] == 'M':
tmp += 1
count[x][y] = tmp
vec = [(click)]
while vec:
next_vec = []
for x, y in vec:
if grid[x][y] == 'E':
if count[x][y] == 0:
grid[x][y] = 'B'
for i, j in [(0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, -1), (-1, 1)]:
xx, yy = x+i, y+j
if 0 <= xx < len(board) and 0 <= yy < len(board[0]):
if grid[xx][yy] == 'E':
next_vec.append((xx, yy))
else:
grid[x][y] = str(count[x][y])
vec = next_vec
return grid
|
"""
Let's play the minesweeper game (Wikipedia, online game)!
You are given a 2D char matrix representing the game board. 'M' represents an unrevealed mine, 'E' represents an unrevealed empty square, 'B' represents a revealed blank square that has no adjacent (above, below, left, right, and all 4 diagonals) mines, digit ('1' to '8') represents how many mines are adjacent to this revealed square, and finally 'X' represents a revealed mine.
Now given the next click position (row and column indices) among all the unrevealed squares ('M' or 'E'), return the board after revealing this position according to the following rules:
If a mine ('M') is revealed, then the game is over - change it to 'X'.
If an empty square ('E') with no adjacent mines is revealed, then change it to revealed blank ('B') and all of its adjacent unrevealed squares should be revealed recursively.
If an empty square ('E') with at least one adjacent mine is revealed, then change it to a digit ('1' to '8') representing the number of adjacent mines.
Return the board when no more squares will be revealed.
Example 1:
Input:
[['E', 'E', 'E', 'E', 'E'],
['E', 'E', 'M', 'E', 'E'],
['E', 'E', 'E', 'E', 'E'],
['E', 'E', 'E', 'E', 'E']]
Click : [3,0]
Output:
[['B', '1', 'E', '1', 'B'],
['B', '1', 'M', '1', 'B'],
['B', '1', '1', '1', 'B'],
['B', 'B', 'B', 'B', 'B']]
Explanation:
Example 2:
Input:
[['B', '1', 'E', '1', 'B'],
['B', '1', 'M', '1', 'B'],
['B', '1', '1', '1', 'B'],
['B', 'B', 'B', 'B', 'B']]
Click : [1,2]
Output:
[['B', '1', 'E', '1', 'B'],
['B', '1', 'X', '1', 'B'],
['B', '1', '1', '1', 'B'],
['B', 'B', 'B', 'B', 'B']]
Explanation:
Note:
The range of the input matrix's height and width is [1,50].
The click position will only be an unrevealed square ('M' or 'E'), which also means the input board contains at least one clickable square.
The input board won't be a stage when game is over (some mines have been revealed).
For simplicity, not mentioned rules should be ignored in this problem. For example, you don't need to reveal all the unrevealed mines when the game is over, consider any cases that you will win the game or flag any squares.
"""
class Solution(object):
def update_board(self, board, click):
"""
:type board: List[List[str]]
:type click: List[int]
:rtype: List[List[str]]
"""
grid = [[board[i][j] for j in xrange(len(board[i]))] for i in xrange(len(board))]
if grid[click[0]][click[1]] == 'M':
grid[click[0]][click[1]] = 'X'
else:
count = [[0 for j in xrange(len(board[i]))] for i in xrange(len(board))]
for x in xrange(len(board)):
for y in xrange(len(board[i])):
tmp = 0
for (i, j) in [(0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, -1), (-1, 1)]:
(xx, yy) = (x + i, y + j)
if 0 <= xx < len(board) and 0 <= yy < len(board[0]):
if board[xx][yy] == 'M':
tmp += 1
count[x][y] = tmp
vec = [click]
while vec:
next_vec = []
for (x, y) in vec:
if grid[x][y] == 'E':
if count[x][y] == 0:
grid[x][y] = 'B'
for (i, j) in [(0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, -1), (-1, 1)]:
(xx, yy) = (x + i, y + j)
if 0 <= xx < len(board) and 0 <= yy < len(board[0]):
if grid[xx][yy] == 'E':
next_vec.append((xx, yy))
else:
grid[x][y] = str(count[x][y])
vec = next_vec
return grid
|
_base_ = "./FlowNet512_1.5AugCosyAAEGray_AdamW_ClipGrad_AvgMaxMin_Pbr_01_ape.py"
OUTPUT_DIR = "output/deepim/lmPbrSO/FlowNet512_1.5AugCosyAAEGray_AdamW_ClipGrad_AvgMaxMin_lmPbr_SO/cat"
DATASETS = dict(TRAIN=("lm_pbr_cat_train",), TEST=("lm_real_cat_test",))
# bbnc10
# objects cat Avg(1)
# ad_2 21.06 21.06
# ad_5 62.67 62.67
# ad_10 92.61 92.61
# rete_2 78.04 78.04
# rete_5 99.20 99.20
# rete_10 100.00 100.00
# re_2 78.34 78.34
# re_5 99.20 99.20
# re_10 100.00 100.00
# te_2 99.10 99.10
# te_5 100.00 100.00
# te_10 100.00 100.00
# proj_2 85.83 85.83
# proj_5 99.10 99.10
# proj_10 100.00 100.00
# re 1.49 1.49
# te 0.01 0.01
|
_base_ = './FlowNet512_1.5AugCosyAAEGray_AdamW_ClipGrad_AvgMaxMin_Pbr_01_ape.py'
output_dir = 'output/deepim/lmPbrSO/FlowNet512_1.5AugCosyAAEGray_AdamW_ClipGrad_AvgMaxMin_lmPbr_SO/cat'
datasets = dict(TRAIN=('lm_pbr_cat_train',), TEST=('lm_real_cat_test',))
|
# -*- coding: utf-8 -*-
# index.urls
def make_rules():
return []
all_views = {}
|
def make_rules():
return []
all_views = {}
|
data = input()
forum_dict = {}
while not data == 'filter':
topic = data.split(' -> ')[0]
hashtags = data.split(' -> ')[1].split(', ')
if topic in forum_dict.keys():
forum_dict[topic].extend(hashtags)
else:
forum_dict[topic] = hashtags
data = input()
hashtags_reg = input().split(', ')
for topic, hashtags in forum_dict.items():
unique_tags_list = sorted(set(hashtags), key=hashtags.index)
forum_dict[topic] = unique_tags_list
hashtags_reg_set = set(hashtags_reg)
if hashtags_reg_set.issubset(hashtags):
print(f'{topic} | ', end='')
print(f'''{", ".join(list(map(lambda x:'#'+x, unique_tags_list)))}''')
|
data = input()
forum_dict = {}
while not data == 'filter':
topic = data.split(' -> ')[0]
hashtags = data.split(' -> ')[1].split(', ')
if topic in forum_dict.keys():
forum_dict[topic].extend(hashtags)
else:
forum_dict[topic] = hashtags
data = input()
hashtags_reg = input().split(', ')
for (topic, hashtags) in forum_dict.items():
unique_tags_list = sorted(set(hashtags), key=hashtags.index)
forum_dict[topic] = unique_tags_list
hashtags_reg_set = set(hashtags_reg)
if hashtags_reg_set.issubset(hashtags):
print(f'{topic} | ', end='')
print(f"{', '.join(list(map(lambda x: '#' + x, unique_tags_list)))}")
|
def fector(x: int):
if x == 0:
return 1
else:
return x * fector(x - 1)
N = int(input())
print(fector(N))
|
def fector(x: int):
if x == 0:
return 1
else:
return x * fector(x - 1)
n = int(input())
print(fector(N))
|
filename=os.path.join(path,'Output','Data','xls','WALIS_spreadsheet.xlsx')
print('Your file will be created in {} '.format(path+'/Output/Data/'))
###### Prepare messages for the readme ######
# First cell
date_string = date.strftime("%d %m %Y")
msg1='This file was exported from WALIS on '+date_string
# Second cell
msg2= ("The data in this file were compiled in WALIS, the World Atlas of Last Interglacial Shorelines. "
"WALIS is a product of the ERC project WARMCOASTS (ERC-StG-802414). "
"Bugs and suggestions for improvements can be sent to [email protected]")
# Third cell
if not Summary.empty:
bit1=(" - Summary RSL datapoints: RSL datapoints from stratigraphic records, U-Series from corals and U-Series from speleothems. Rows with common RSL ID (but different ages available) are highlighted with alternating gray and white colors. \n")
else:
bit1=("")
if not useries_corals_RSL.empty:
bit2=(" - RSL from single coral: RSL datapoints from dated corals, for which paleo water depth is estimated \n")
else:
bit2=("")
if not useries_speleo_RSL.empty:
bit3=(" - RSL from single speleothem: RSL datapoints from dated speleothems, for which paleo RSL is estimated \n")
else:
bit3=("")
if not RSL_Datapoints.empty:
bit4=(" - RSL proxies: RSL indicators from stratigraphic information, with grouped age details \n")
else:
bit4=("")
if not RSL_Ind.empty:
bit5=(" - RSL indicators: list of types of RSL indicators used in the 'RSL proxies' sheet \n")
else:
bit5=("")
if not vrt_meas.empty:
bit6=(" - Elevation measurement techniques: list of elevation survey methods used both in the 'RSL proxies' sheet and in the elevation fields of dated samples \n")
else:
bit6=("")
if not hrz_meas.empty:
bit7=(" - Geographic positioning: list of geographic positioning methods used in the 'RSL proxies' sheet \n")
else:
bit7=("")
if not sl_datum.empty:
bit8=(" - Sea level datums: list of datums used both in the 'RSL proxies' sheet and in the datums fields of dated samples \n")
else:
bit8=("")
if not useries_corals.empty:
bit9=(" - U-Series (corals): list of all the coral samples dated with U-Series. This sheet contains all U-Series coral ages created by the user or falling within the region of interest, all U-Series coral ages reported in the 'RSL proxies' sheet and all the U-Series coral ages used as age banchmarks to AAR ages contained in the 'RSL proxies tab' \n")
else:
bit9=("")
if not useries_moll.empty:
bit10=(" - U-Series (mollusks): list of all the mollusks (or algae) samples dated with U-Series. This sheet contains all U-Series mollusk/algal ages created by the user or falling within the region of interest, all U-Series mollusk/algal ages reported in the 'RSL proxies' sheet and all the U-Series mollusk/algal ages used as age banchmarks to AAR ages contained in the 'RSL proxies tab' \n")
else:
bit10=("")
if not useries_oolite.empty:
bit10a=(" - U-Series (mollusks): list of all the mollusks (or algae) samples dated with U-Series. This sheet contains all U-Series mollusk/algal ages created by the user or falling within the region of interest, all U-Series mollusk/algal ages reported in the 'RSL proxies' sheet and all the U-Series mollusk/algal ages used as age banchmarks to AAR ages contained in the 'RSL proxies tab' \n")
else:
bit10a=("")
if not useries_speleo.empty:
bit11=(" - U-Series (speleothems): list of all the speleothem samples dated with U-Series. This sheet contains all U-Series speleothem ages created by the user or falling within the region of interest, all U-Series speleothem ages reported in the 'RSL proxies' sheet and all the U-Series speleothem ages used as age banchmarks to AAR ages contained in the 'RSL proxies tab' \n")
else:
bit11=("")
if not aar.empty:
bit12=(" - Amino Acid Racemization: list of all the samples dated with AAR. This sheet contains all AAR ages created by the user or falling within the region of interest and all AAR ages reported in the 'RSL proxies' sheet. \n")
else:
bit12=("")
if not esr.empty:
bit13=(" - Electron Spin Resonance: list of all the samples dated with ESR. This sheet contains all ESR ages created by the user or falling within the region of interest, all ESR ages reported in the 'RSL proxies' sheet and all the ESR ages used as age banchmarks to AAR ages contained in the 'RSL proxies tab' \n")
else:
bit13=("")
if not lum.empty:
bit14=(" - Luminescence: list of all the samples dated with luminescence. This sheet contains all luminescence ages created by the user or falling within the region of interest, all luminescence ages reported in the 'RSL proxies' sheet and all the luminescence ages used as age banchmarks to AAR ages contained in the 'RSL proxies tab' \n")
else:
bit14=(" ")
if not strat.empty:
bit15=(" - Chronostratigraphy: list of all the chronostratigraphic age constraints. This sheet contains all constraints created by the user or falling within the region of interest, all chronostratigraphic constraints reported in the 'RSL proxies' sheet and all the chronostratigraphic constraints ages used as age banchmarks to AAR ages contained in the 'RSL proxies tab' \n")
else:
bit15=("")
if not other.empty:
bit16=(" - Other age constraints: list of all the other age constraints. This sheet contains all constraints created by the user or falling within the region of interest and all other age constraints reported in the 'RSL proxies' sheet \n")
else:
bit16=("")
bit17=(" - References: list of all references contained in the culled database. \n")
msg3= ("The sheets in this file contain the following information (if available): \n"+bit1+bit2+bit3+bit4+bit5+bit6+bit7+bit8+bit9+bit10+bit10a+bit11+bit12+bit13+bit14+bit15+bit16+bit17)
#Fourth cell
msg4= ("Information on each field can be found at: https://walis-help.readthedocs.io/en/latest/ \n"
"Information on WALIS (Including data download) can be found at: https://warmcoasts.eu/world-atlas.html \n")
#Fifth cell
people=str(user_contrib_df['index'].values.tolist()).replace("'", '').replace("[", '').replace("]", '')
msg5=("Suggested acknowledgments: The data used in this study were [extracted from / compiled in] WALIS, a sea-level database interface developed by the ERC Starting Grant WARMCOASTS (ERC-StG-802414), in collaboration with PALSEA (PAGES / INQUA) working group. The database structure was designed by A. Rovere, D. Ryan, T. Lorscheid, A. Dutton, P. Chutcharavan, D. Brill, N. Jankowski, D. Mueller, M. Bartz, E. Gowan and K. Cohen. The data points used in this study were contributed to WALIS by: "+people+" (in order of numbers of records inserted).")
#Create and give format to xls file
writer = pd.ExcelWriter(filename, engine='xlsxwriter',options={'strings_to_numbers': True,'strings_to_formulas': False})
workbook=writer.book
wrap = workbook.add_format({'text_wrap': True, 'valign':'vcenter','align':'center'})
wrap2 = workbook.add_format({'text_wrap': True, 'valign':'vcenter','align':'left'})
header_format = workbook.add_format({'bold': True,'text_wrap': True,'valign': 'vcenter','align':'center','fg_color':'#C0C0C0','border': 1})
###### Write the readme in the first sheet ######
column_names = ['WALIS spreadsheet']
df = pd.DataFrame(columns = column_names)
df.to_excel(writer, sheet_name='README',index=False)
worksheet = writer.sheets['README']
worksheet.write('A2', msg1)
worksheet.write('A4', msg2)
worksheet.write('A6', msg3)
worksheet.write_string('A8', msg4)
worksheet.write_string('A9', msg5)
worksheet.set_column('A:A',180,wrap2)
###### Summary sheets ######
Summary=Summary.sort_values(by=['Nation','WALIS_ID'])
#Create Summary sheet
if not Summary.empty:
filename_csv=os.path.join(path,'Output','Data','csv','Summary.csv')
Summary.to_csv(filename_csv,index = False,encoding='utf-8-sig')
Summary.to_excel(writer, sheet_name='Summary of RSL datapoints',index=False)
worksheet = writer.sheets['Summary of RSL datapoints']
worksheet.set_column('A:XFD',20,wrap)
worksheet.set_column('ZZ:ZZ',0,wrap)
worksheet.set_column('AB:AB', 30,wrap)
for row in range(1, 10000):
worksheet.set_row(row, 50)
worksheet.freeze_panes(1, 4)
# Write the column headers with the defined format.
for col_num, value in enumerate(Summary.columns.values):
worksheet.write(0, col_num, value, header_format)
index = Summary.index
number_of_rows = len(index)
worksheet.write('AF2', 0)
for k in range(3, number_of_rows+2):
i=k-1
k=str(k)
i=str(i)
cell='ZZ'+k
formula='=MOD(IF(A'+k+'=A'+i+',0,1)+ZZ'+i+',2)'
worksheet.write_formula(cell,formula)
format1 = workbook.add_format({'bg_color': '#D3D3D3'})
worksheet.conditional_format("$A$1:$ZZ$%d" % (number_of_rows+1),{"type": "formula","criteria": '=INDIRECT("ZZ"&ROW())=0',"format": format1})
###### RSL datapoints from U-Series ######
#RSL from corals
useries_corals_RSL = useries_corals_RSL.sort_values(by=['Analysis ID'])
if not useries_corals_RSL.empty:
filename_csv=os.path.join(path,'Output','Data','csv','RSL_from_single_coral.csv')
useries_corals_RSL.to_csv(filename_csv,index = False,encoding='utf-8-sig')
useries_corals_RSL.to_excel(writer, sheet_name='RSL from single coral',index=False)
#Define fields for corals
worksheet = writer.sheets['RSL from single coral']
worksheet.set_column('A:ZZ',20,wrap)
for row in range(1, 5000):
worksheet.set_row(row, 45)
worksheet.freeze_panes(1, 1)
# Write the column headers with the defined format.
for col_num, value in enumerate(useries_corals_RSL.columns.values):
worksheet.write(0, col_num, value, header_format)
###### RSL datapoints from Speleothems ######
useries_speleo_RSL = useries_speleo_RSL.sort_values(by=['Analysis ID'])
if not useries_speleo_RSL.empty:
filename_csv=os.path.join(path,'Output','Data','csv','RSL_from_single_speleothem.csv')
useries_corals_RSL.to_csv(filename_csv,index = False,encoding='utf-8-sig')
useries_speleo_RSL.to_excel(writer, sheet_name='RSL from single speleothem',index=False)
#Define fields for corals
worksheet = writer.sheets['RSL from single speleothem']
worksheet.set_column('A:ZZ',20,wrap)
for row in range(1, 5000):
worksheet.set_row(row, 45)
worksheet.freeze_panes(1, 1)
# Write the column headers with the defined format.
for col_num, value in enumerate(useries_speleo_RSL.columns.values):
worksheet.write(0, col_num, value, header_format)
###### RSL datapoints ######
if not RSL_Datapoints.empty:
RSL_Datapoints.sort_values(by=['Nation','Region'],inplace=True)
filename_csv=os.path.join(path,'Output','Data','csv','RSL_proxies.csv')
RSL_Datapoints.to_csv(filename_csv,index = False,encoding='utf-8-sig')
RSL_Datapoints.to_excel(writer, sheet_name='RSL proxies',index=False)
worksheet = writer.sheets['RSL proxies']
worksheet.set_column('A:XFD',20,wrap)
for row in range(1, 10000):
worksheet.set_row(row, 50)
worksheet.freeze_panes(1, 1)
# Add a header format.
header_format = workbook.add_format({'bold': True,'text_wrap': True,'valign': 'vcenter','align':'center',
'fg_color':'#C0C0C0','border': 1})
# Write the column headers with the defined format.
for col_num, value in enumerate(RSL_Datapoints.columns.values):
worksheet.write(0, col_num, value, header_format)
###### RSL indicators ######
if not RSL_Ind.empty:
filename_csv=os.path.join(path,'Output','Data','csv','RSL_indicators.csv')
RSL_Ind.to_csv(filename_csv,index = False,encoding='utf-8-sig')
RSL_Ind=RSL_Ind.sort_values(by=['Name of RSL indicator'])
RSL_Ind.to_excel(writer, sheet_name='RSL indicators',index=False)
worksheet = writer.sheets['RSL indicators']
worksheet.set_column('A:K',50,wrap)
for row in range(1, 5000):
worksheet.set_row(row, 80)
worksheet.freeze_panes(1, 1)
# Write the column headers with the defined format.
for col_num, value in enumerate(RSL_Ind.columns.values):
worksheet.write(0, col_num, value, header_format)
###### Elevation measurement techniques ######
if not vrt_meas.empty:
vrt_meas=vrt_meas.sort_values(by=['Measurement technique'])
vrt_meas.reset_index(inplace=True,drop=True)
filename_csv=os.path.join(path,'Output','Data','csv','Elevation_measurement.csv')
vrt_meas.to_csv(filename_csv,index = False,encoding='utf-8-sig')
vrt_meas.to_excel(writer, sheet_name='Elevation measurement',index=False)
worksheet = writer.sheets['Elevation measurement']
worksheet.set_column('A:G',50,wrap)
for row in range(1, 5000):
worksheet.set_row(row, 80)
worksheet.freeze_panes(1, 1)
# Write the column headers with the defined format.
for col_num, value in enumerate(vrt_meas.columns.values):
worksheet.write(0, col_num, value, header_format)
###### Geographic positioning techniques ######
if not hrz_meas.empty:
hrz_meas=hrz_meas.sort_values(by=['Measurement technique'])
filename_csv=os.path.join(path,'Output','Data','csv','Geographic_positioning.csv')
hrz_meas.to_csv(filename_csv,index = False,encoding='utf-8-sig')
hrz_meas.to_excel(writer,sheet_name='Geographic positioning',index=False)
worksheet = writer.sheets['Geographic positioning']
worksheet.set_column('A:G',50,wrap)
for row in range(1, 5000):
worksheet.set_row(row, 80)
worksheet.freeze_panes(1, 1)
# Write the column headers with the defined format.
for col_num, value in enumerate(hrz_meas.columns.values):
worksheet.write(0, col_num, value, header_format)
###### Sea level datum ######
if not sl_datum.empty:
sl_datum=sl_datum.sort_values(by=['Datum name'])
filename_csv=os.path.join(path,'Output','Data','csv','Sea_level_datums.csv')
sl_datum.to_csv(filename_csv,index = False,encoding='utf-8-sig')
sl_datum.to_excel(writer,sheet_name='Sea level datums',index=False)
worksheet = writer.sheets['Sea level datums']
worksheet.set_column('A:H',50,wrap)
for row in range(1, 5000):
worksheet.set_row(row, 80)
worksheet.freeze_panes(1, 1)
# Write the column headers with the defined format.
for col_num, value in enumerate(sl_datum.columns.values):
worksheet.write(0, col_num, value, header_format)
###### U-Series ######
#Corals
useries_corals=useries_corals.sort_values(by=['Analysis ID'])
if not useries_corals.empty:
filename_csv=os.path.join(path,'Output','Data','csv','USeries_corals.csv')
useries_corals.to_csv(filename_csv,index = False,encoding='utf-8-sig')
useries_corals.to_excel(writer, sheet_name='U-Series (corals)',index=False)
#Define fields for corals
worksheet = writer.sheets['U-Series (corals)']
worksheet.set_column('A:ZZ',20,wrap)
for row in range(1, 5000):
worksheet.set_row(row, 45)
worksheet.freeze_panes(1, 1)
# Write the column headers with the defined format.
for col_num, value in enumerate(useries_corals.columns.values):
worksheet.write(0, col_num, value, header_format)
#Mollusks
useries_moll = useries_moll.sort_values(by=['Analysis ID'])
if not useries_moll.empty:
filename_csv=os.path.join(path,'Output','Data','csv','USeries_mollusks.csv')
useries_moll.to_csv(filename_csv,index = False,encoding='utf-8-sig')
useries_moll.to_excel(writer,sheet_name='U-Series (mollusks)',index=False)
#Define fields for mollusks
worksheet = writer.sheets['U-Series (mollusks)']
worksheet.set_column('A:ZZ',20,wrap)
for row in range(1, 5000):
worksheet.set_row(row, 45)
worksheet.freeze_panes(1, 1)
# Write the column headers with the defined format.
for col_num, value in enumerate(useries_moll.columns.values):
worksheet.write(0, col_num, value, header_format)
#Speleothem
useries_speleo = useries_speleo.sort_values(by=['Analysis ID'])
if not useries_speleo.empty:
filename_csv=os.path.join(path,'Output','Data','csv','USeries_speleo.csv')
useries_speleo.to_csv(filename_csv,index = False,encoding='utf-8-sig')
useries_speleo.to_excel(writer,sheet_name='U-Series (speleothems)',index=False)
#Define fields for mollusks
worksheet = writer.sheets['U-Series (speleothems)']
worksheet.set_column('A:ZZ',20,wrap)
for row in range(1, 5000):
worksheet.set_row(row, 45)
worksheet.freeze_panes(1, 1)
# Write the column headers with the defined format.
for col_num, value in enumerate(useries_speleo.columns.values):
worksheet.write(0, col_num, value, header_format)
#Oolites
useries_oolite = useries_oolite.sort_values(by=['Analysis ID'])
if not useries_oolite.empty:
filename_csv=os.path.join(path,'Output','Data','csv','USeries_oolite.csv')
useries_oolite.to_csv(filename_csv,index = False,encoding='utf-8-sig')
useries_oolite.to_excel(writer,sheet_name='U-Series (Oolites)',index=False)
#Define fields for mollusks
worksheet = writer.sheets['U-Series (Oolites)']
worksheet.set_column('A:ZZ',20,wrap)
for row in range(1, 5000):
worksheet.set_row(row, 45)
worksheet.freeze_panes(1, 1)
# Write the column headers with the defined format.
for col_num, value in enumerate(useries_oolite.columns.values):
worksheet.write(0, col_num, value, header_format)
###### AAR ######
aar=aar.sort_values(by=['Analysis ID'])
if not aar.empty:
filename_csv=os.path.join(path,'Output','Data','csv','Amino_Acid_Racemization.csv')
aar.to_csv(filename_csv,index = False,encoding='utf-8-sig')
aar.to_excel(writer, sheet_name='Amino Acid Racemization',index=False)
# Write the column headers with the defined format.
worksheet = writer.sheets['Amino Acid Racemization']
worksheet.set_column('A:ZZ',20,wrap)
for row in range(1, 5000):
worksheet.set_row(row, 45)
worksheet.freeze_panes(1, 1)
for col_num, value in enumerate(aar.columns.values):
worksheet.write(0, col_num, value, header_format)
###### ESR ######
esr=esr.sort_values(by=['Analysis ID'])
if not esr.empty:
filename_csv=os.path.join(path,'Output','Data','csv','Electron_Spin_Resonance.csv')
esr.to_csv(filename_csv,index = False,encoding='utf-8-sig')
esr.to_excel(writer, sheet_name='Electron Spin Resonance',index=False)
# Write the column headers with the defined format.
worksheet = writer.sheets['Electron Spin Resonance']
worksheet.set_column('A:ZZ',20,wrap)
for row in range(1, 5000):
worksheet.set_row(row, 45)
worksheet.freeze_panes(1, 1)
for col_num, value in enumerate(esr.columns.values):
worksheet.write(0, col_num, value, header_format)
###### LUM ######
lum=lum.sort_values(by=['Analysis ID'])
if not lum.empty:
filename_csv=os.path.join(path,'Output','Data','csv','Luminescence.csv')
lum.to_csv(filename_csv,index = False,encoding='utf-8-sig')
lum.to_excel(writer, sheet_name='Luminescence',index=False)
# Write the column headers with the defined format.
worksheet = writer.sheets['Luminescence']
worksheet.set_column('A:ZZ',20,wrap)
for row in range(1, 5000):
worksheet.set_row(row, 45)
worksheet.freeze_panes(1, 1)
for col_num, value in enumerate(lum.columns.values):
worksheet.write(0, col_num, value, header_format)
###### Stratigraphic constraints ######
strat=strat.sort_values(by=['Chronostratigraphy ID'])
if not strat.empty:
filename_csv=os.path.join(path,'Output','Data','csv','Chronostratigrapy.csv')
strat.to_csv(filename_csv,index = False,encoding='utf-8-sig')
strat.to_excel(writer, sheet_name='Chronostratigraphy',index=False)
# Write the column headers with the defined format.
worksheet = writer.sheets['Chronostratigraphy']
worksheet.set_column('A:ZZ',20,wrap)
for row in range(1, 5000):
worksheet.set_row(row, 45)
worksheet.freeze_panes(1, 1)
for col_num, value in enumerate(strat.columns.values):
worksheet.write(0, col_num, value, header_format)
###### Other constraints ######
other=other.sort_values(by=['WALIS Other chronology ID'])
if not other.empty:
filename_csv=os.path.join(path,'Output','Data','csv','Other_age_constraints.csv')
other.to_csv(filename_csv,index = False,encoding='utf-8-sig')
other.to_excel(writer, sheet_name='Other age constraints',index=False)
# Write the column headers with the defined format.
worksheet = writer.sheets['Other age constraints']
worksheet.set_column('A:ZZ',20,wrap)
for row in range(1, 5000):
worksheet.set_row(row, 45)
worksheet.freeze_panes(1, 1)
for col_num, value in enumerate(other.columns.values):
worksheet.write(0, col_num, value, header_format)
###### References_query ######
References_query.drop(columns=['Abstract'],inplace=True)
References_query=References_query.sort_values(by=['Reference'])
if not References_query.empty:
filename_csv=os.path.join(path,'Output','Data','csv','References.csv')
References_query.to_csv(filename_csv,index = False,encoding='utf-8-sig')
References_query.to_excel(writer, sheet_name='References',index=False)
# Write the column headers with the defined format.
worksheet = writer.sheets['References']
worksheet.set_column('A:A', 15,wrap)
worksheet.set_column('B:B', 35,wrap)
worksheet.set_column('C:C', 150,wrap)
worksheet.set_column('D:D', 30,wrap)
worksheet.set_column('E:E', 10,wrap)
worksheet.set_column('F:ZZ', 30,wrap)
worksheet.freeze_panes(1, 1)
for col_num, value in enumerate(References_query.columns.values):
worksheet.write(0, col_num, value, header_format)
writer.save()
|
filename = os.path.join(path, 'Output', 'Data', 'xls', 'WALIS_spreadsheet.xlsx')
print('Your file will be created in {} '.format(path + '/Output/Data/'))
date_string = date.strftime('%d %m %Y')
msg1 = 'This file was exported from WALIS on ' + date_string
msg2 = 'The data in this file were compiled in WALIS, the World Atlas of Last Interglacial Shorelines. WALIS is a product of the ERC project WARMCOASTS (ERC-StG-802414). Bugs and suggestions for improvements can be sent to [email protected]'
if not Summary.empty:
bit1 = ' - Summary RSL datapoints: RSL datapoints from stratigraphic records, U-Series from corals and U-Series from speleothems. Rows with common RSL ID (but different ages available) are highlighted with alternating gray and white colors. \n'
else:
bit1 = ''
if not useries_corals_RSL.empty:
bit2 = ' - RSL from single coral: RSL datapoints from dated corals, for which paleo water depth is estimated \n'
else:
bit2 = ''
if not useries_speleo_RSL.empty:
bit3 = ' - RSL from single speleothem: RSL datapoints from dated speleothems, for which paleo RSL is estimated \n'
else:
bit3 = ''
if not RSL_Datapoints.empty:
bit4 = ' - RSL proxies: RSL indicators from stratigraphic information, with grouped age details \n'
else:
bit4 = ''
if not RSL_Ind.empty:
bit5 = " - RSL indicators: list of types of RSL indicators used in the 'RSL proxies' sheet \n"
else:
bit5 = ''
if not vrt_meas.empty:
bit6 = " - Elevation measurement techniques: list of elevation survey methods used both in the 'RSL proxies' sheet and in the elevation fields of dated samples \n"
else:
bit6 = ''
if not hrz_meas.empty:
bit7 = " - Geographic positioning: list of geographic positioning methods used in the 'RSL proxies' sheet \n"
else:
bit7 = ''
if not sl_datum.empty:
bit8 = " - Sea level datums: list of datums used both in the 'RSL proxies' sheet and in the datums fields of dated samples \n"
else:
bit8 = ''
if not useries_corals.empty:
bit9 = " - U-Series (corals): list of all the coral samples dated with U-Series. This sheet contains all U-Series coral ages created by the user or falling within the region of interest, all U-Series coral ages reported in the 'RSL proxies' sheet and all the U-Series coral ages used as age banchmarks to AAR ages contained in the 'RSL proxies tab' \n"
else:
bit9 = ''
if not useries_moll.empty:
bit10 = " - U-Series (mollusks): list of all the mollusks (or algae) samples dated with U-Series. This sheet contains all U-Series mollusk/algal ages created by the user or falling within the region of interest, all U-Series mollusk/algal ages reported in the 'RSL proxies' sheet and all the U-Series mollusk/algal ages used as age banchmarks to AAR ages contained in the 'RSL proxies tab' \n"
else:
bit10 = ''
if not useries_oolite.empty:
bit10a = " - U-Series (mollusks): list of all the mollusks (or algae) samples dated with U-Series. This sheet contains all U-Series mollusk/algal ages created by the user or falling within the region of interest, all U-Series mollusk/algal ages reported in the 'RSL proxies' sheet and all the U-Series mollusk/algal ages used as age banchmarks to AAR ages contained in the 'RSL proxies tab' \n"
else:
bit10a = ''
if not useries_speleo.empty:
bit11 = " - U-Series (speleothems): list of all the speleothem samples dated with U-Series. This sheet contains all U-Series speleothem ages created by the user or falling within the region of interest, all U-Series speleothem ages reported in the 'RSL proxies' sheet and all the U-Series speleothem ages used as age banchmarks to AAR ages contained in the 'RSL proxies tab' \n"
else:
bit11 = ''
if not aar.empty:
bit12 = " - Amino Acid Racemization: list of all the samples dated with AAR. This sheet contains all AAR ages created by the user or falling within the region of interest and all AAR ages reported in the 'RSL proxies' sheet. \n"
else:
bit12 = ''
if not esr.empty:
bit13 = " - Electron Spin Resonance: list of all the samples dated with ESR. This sheet contains all ESR ages created by the user or falling within the region of interest, all ESR ages reported in the 'RSL proxies' sheet and all the ESR ages used as age banchmarks to AAR ages contained in the 'RSL proxies tab' \n"
else:
bit13 = ''
if not lum.empty:
bit14 = " - Luminescence: list of all the samples dated with luminescence. This sheet contains all luminescence ages created by the user or falling within the region of interest, all luminescence ages reported in the 'RSL proxies' sheet and all the luminescence ages used as age banchmarks to AAR ages contained in the 'RSL proxies tab' \n"
else:
bit14 = ' '
if not strat.empty:
bit15 = " - Chronostratigraphy: list of all the chronostratigraphic age constraints. This sheet contains all constraints created by the user or falling within the region of interest, all chronostratigraphic constraints reported in the 'RSL proxies' sheet and all the chronostratigraphic constraints ages used as age banchmarks to AAR ages contained in the 'RSL proxies tab' \n"
else:
bit15 = ''
if not other.empty:
bit16 = " - Other age constraints: list of all the other age constraints. This sheet contains all constraints created by the user or falling within the region of interest and all other age constraints reported in the 'RSL proxies' sheet \n"
else:
bit16 = ''
bit17 = ' - References: list of all references contained in the culled database. \n'
msg3 = 'The sheets in this file contain the following information (if available): \n' + bit1 + bit2 + bit3 + bit4 + bit5 + bit6 + bit7 + bit8 + bit9 + bit10 + bit10a + bit11 + bit12 + bit13 + bit14 + bit15 + bit16 + bit17
msg4 = 'Information on each field can be found at: https://walis-help.readthedocs.io/en/latest/ \nInformation on WALIS (Including data download) can be found at: https://warmcoasts.eu/world-atlas.html \n'
people = str(user_contrib_df['index'].values.tolist()).replace("'", '').replace('[', '').replace(']', '')
msg5 = 'Suggested acknowledgments: The data used in this study were [extracted from / compiled in] WALIS, a sea-level database interface developed by the ERC Starting Grant WARMCOASTS (ERC-StG-802414), in collaboration with PALSEA (PAGES / INQUA) working group. The database structure was designed by A. Rovere, D. Ryan, T. Lorscheid, A. Dutton, P. Chutcharavan, D. Brill, N. Jankowski, D. Mueller, M. Bartz, E. Gowan and K. Cohen. The data points used in this study were contributed to WALIS by: ' + people + ' (in order of numbers of records inserted).'
writer = pd.ExcelWriter(filename, engine='xlsxwriter', options={'strings_to_numbers': True, 'strings_to_formulas': False})
workbook = writer.book
wrap = workbook.add_format({'text_wrap': True, 'valign': 'vcenter', 'align': 'center'})
wrap2 = workbook.add_format({'text_wrap': True, 'valign': 'vcenter', 'align': 'left'})
header_format = workbook.add_format({'bold': True, 'text_wrap': True, 'valign': 'vcenter', 'align': 'center', 'fg_color': '#C0C0C0', 'border': 1})
column_names = ['WALIS spreadsheet']
df = pd.DataFrame(columns=column_names)
df.to_excel(writer, sheet_name='README', index=False)
worksheet = writer.sheets['README']
worksheet.write('A2', msg1)
worksheet.write('A4', msg2)
worksheet.write('A6', msg3)
worksheet.write_string('A8', msg4)
worksheet.write_string('A9', msg5)
worksheet.set_column('A:A', 180, wrap2)
summary = Summary.sort_values(by=['Nation', 'WALIS_ID'])
if not Summary.empty:
filename_csv = os.path.join(path, 'Output', 'Data', 'csv', 'Summary.csv')
Summary.to_csv(filename_csv, index=False, encoding='utf-8-sig')
Summary.to_excel(writer, sheet_name='Summary of RSL datapoints', index=False)
worksheet = writer.sheets['Summary of RSL datapoints']
worksheet.set_column('A:XFD', 20, wrap)
worksheet.set_column('ZZ:ZZ', 0, wrap)
worksheet.set_column('AB:AB', 30, wrap)
for row in range(1, 10000):
worksheet.set_row(row, 50)
worksheet.freeze_panes(1, 4)
for (col_num, value) in enumerate(Summary.columns.values):
worksheet.write(0, col_num, value, header_format)
index = Summary.index
number_of_rows = len(index)
worksheet.write('AF2', 0)
for k in range(3, number_of_rows + 2):
i = k - 1
k = str(k)
i = str(i)
cell = 'ZZ' + k
formula = '=MOD(IF(A' + k + '=A' + i + ',0,1)+ZZ' + i + ',2)'
worksheet.write_formula(cell, formula)
format1 = workbook.add_format({'bg_color': '#D3D3D3'})
worksheet.conditional_format('$A$1:$ZZ$%d' % (number_of_rows + 1), {'type': 'formula', 'criteria': '=INDIRECT("ZZ"&ROW())=0', 'format': format1})
useries_corals_rsl = useries_corals_RSL.sort_values(by=['Analysis ID'])
if not useries_corals_RSL.empty:
filename_csv = os.path.join(path, 'Output', 'Data', 'csv', 'RSL_from_single_coral.csv')
useries_corals_RSL.to_csv(filename_csv, index=False, encoding='utf-8-sig')
useries_corals_RSL.to_excel(writer, sheet_name='RSL from single coral', index=False)
worksheet = writer.sheets['RSL from single coral']
worksheet.set_column('A:ZZ', 20, wrap)
for row in range(1, 5000):
worksheet.set_row(row, 45)
worksheet.freeze_panes(1, 1)
for (col_num, value) in enumerate(useries_corals_RSL.columns.values):
worksheet.write(0, col_num, value, header_format)
useries_speleo_rsl = useries_speleo_RSL.sort_values(by=['Analysis ID'])
if not useries_speleo_RSL.empty:
filename_csv = os.path.join(path, 'Output', 'Data', 'csv', 'RSL_from_single_speleothem.csv')
useries_corals_RSL.to_csv(filename_csv, index=False, encoding='utf-8-sig')
useries_speleo_RSL.to_excel(writer, sheet_name='RSL from single speleothem', index=False)
worksheet = writer.sheets['RSL from single speleothem']
worksheet.set_column('A:ZZ', 20, wrap)
for row in range(1, 5000):
worksheet.set_row(row, 45)
worksheet.freeze_panes(1, 1)
for (col_num, value) in enumerate(useries_speleo_RSL.columns.values):
worksheet.write(0, col_num, value, header_format)
if not RSL_Datapoints.empty:
RSL_Datapoints.sort_values(by=['Nation', 'Region'], inplace=True)
filename_csv = os.path.join(path, 'Output', 'Data', 'csv', 'RSL_proxies.csv')
RSL_Datapoints.to_csv(filename_csv, index=False, encoding='utf-8-sig')
RSL_Datapoints.to_excel(writer, sheet_name='RSL proxies', index=False)
worksheet = writer.sheets['RSL proxies']
worksheet.set_column('A:XFD', 20, wrap)
for row in range(1, 10000):
worksheet.set_row(row, 50)
worksheet.freeze_panes(1, 1)
header_format = workbook.add_format({'bold': True, 'text_wrap': True, 'valign': 'vcenter', 'align': 'center', 'fg_color': '#C0C0C0', 'border': 1})
for (col_num, value) in enumerate(RSL_Datapoints.columns.values):
worksheet.write(0, col_num, value, header_format)
if not RSL_Ind.empty:
filename_csv = os.path.join(path, 'Output', 'Data', 'csv', 'RSL_indicators.csv')
RSL_Ind.to_csv(filename_csv, index=False, encoding='utf-8-sig')
rsl__ind = RSL_Ind.sort_values(by=['Name of RSL indicator'])
RSL_Ind.to_excel(writer, sheet_name='RSL indicators', index=False)
worksheet = writer.sheets['RSL indicators']
worksheet.set_column('A:K', 50, wrap)
for row in range(1, 5000):
worksheet.set_row(row, 80)
worksheet.freeze_panes(1, 1)
for (col_num, value) in enumerate(RSL_Ind.columns.values):
worksheet.write(0, col_num, value, header_format)
if not vrt_meas.empty:
vrt_meas = vrt_meas.sort_values(by=['Measurement technique'])
vrt_meas.reset_index(inplace=True, drop=True)
filename_csv = os.path.join(path, 'Output', 'Data', 'csv', 'Elevation_measurement.csv')
vrt_meas.to_csv(filename_csv, index=False, encoding='utf-8-sig')
vrt_meas.to_excel(writer, sheet_name='Elevation measurement', index=False)
worksheet = writer.sheets['Elevation measurement']
worksheet.set_column('A:G', 50, wrap)
for row in range(1, 5000):
worksheet.set_row(row, 80)
worksheet.freeze_panes(1, 1)
for (col_num, value) in enumerate(vrt_meas.columns.values):
worksheet.write(0, col_num, value, header_format)
if not hrz_meas.empty:
hrz_meas = hrz_meas.sort_values(by=['Measurement technique'])
filename_csv = os.path.join(path, 'Output', 'Data', 'csv', 'Geographic_positioning.csv')
hrz_meas.to_csv(filename_csv, index=False, encoding='utf-8-sig')
hrz_meas.to_excel(writer, sheet_name='Geographic positioning', index=False)
worksheet = writer.sheets['Geographic positioning']
worksheet.set_column('A:G', 50, wrap)
for row in range(1, 5000):
worksheet.set_row(row, 80)
worksheet.freeze_panes(1, 1)
for (col_num, value) in enumerate(hrz_meas.columns.values):
worksheet.write(0, col_num, value, header_format)
if not sl_datum.empty:
sl_datum = sl_datum.sort_values(by=['Datum name'])
filename_csv = os.path.join(path, 'Output', 'Data', 'csv', 'Sea_level_datums.csv')
sl_datum.to_csv(filename_csv, index=False, encoding='utf-8-sig')
sl_datum.to_excel(writer, sheet_name='Sea level datums', index=False)
worksheet = writer.sheets['Sea level datums']
worksheet.set_column('A:H', 50, wrap)
for row in range(1, 5000):
worksheet.set_row(row, 80)
worksheet.freeze_panes(1, 1)
for (col_num, value) in enumerate(sl_datum.columns.values):
worksheet.write(0, col_num, value, header_format)
useries_corals = useries_corals.sort_values(by=['Analysis ID'])
if not useries_corals.empty:
filename_csv = os.path.join(path, 'Output', 'Data', 'csv', 'USeries_corals.csv')
useries_corals.to_csv(filename_csv, index=False, encoding='utf-8-sig')
useries_corals.to_excel(writer, sheet_name='U-Series (corals)', index=False)
worksheet = writer.sheets['U-Series (corals)']
worksheet.set_column('A:ZZ', 20, wrap)
for row in range(1, 5000):
worksheet.set_row(row, 45)
worksheet.freeze_panes(1, 1)
for (col_num, value) in enumerate(useries_corals.columns.values):
worksheet.write(0, col_num, value, header_format)
useries_moll = useries_moll.sort_values(by=['Analysis ID'])
if not useries_moll.empty:
filename_csv = os.path.join(path, 'Output', 'Data', 'csv', 'USeries_mollusks.csv')
useries_moll.to_csv(filename_csv, index=False, encoding='utf-8-sig')
useries_moll.to_excel(writer, sheet_name='U-Series (mollusks)', index=False)
worksheet = writer.sheets['U-Series (mollusks)']
worksheet.set_column('A:ZZ', 20, wrap)
for row in range(1, 5000):
worksheet.set_row(row, 45)
worksheet.freeze_panes(1, 1)
for (col_num, value) in enumerate(useries_moll.columns.values):
worksheet.write(0, col_num, value, header_format)
useries_speleo = useries_speleo.sort_values(by=['Analysis ID'])
if not useries_speleo.empty:
filename_csv = os.path.join(path, 'Output', 'Data', 'csv', 'USeries_speleo.csv')
useries_speleo.to_csv(filename_csv, index=False, encoding='utf-8-sig')
useries_speleo.to_excel(writer, sheet_name='U-Series (speleothems)', index=False)
worksheet = writer.sheets['U-Series (speleothems)']
worksheet.set_column('A:ZZ', 20, wrap)
for row in range(1, 5000):
worksheet.set_row(row, 45)
worksheet.freeze_panes(1, 1)
for (col_num, value) in enumerate(useries_speleo.columns.values):
worksheet.write(0, col_num, value, header_format)
useries_oolite = useries_oolite.sort_values(by=['Analysis ID'])
if not useries_oolite.empty:
filename_csv = os.path.join(path, 'Output', 'Data', 'csv', 'USeries_oolite.csv')
useries_oolite.to_csv(filename_csv, index=False, encoding='utf-8-sig')
useries_oolite.to_excel(writer, sheet_name='U-Series (Oolites)', index=False)
worksheet = writer.sheets['U-Series (Oolites)']
worksheet.set_column('A:ZZ', 20, wrap)
for row in range(1, 5000):
worksheet.set_row(row, 45)
worksheet.freeze_panes(1, 1)
for (col_num, value) in enumerate(useries_oolite.columns.values):
worksheet.write(0, col_num, value, header_format)
aar = aar.sort_values(by=['Analysis ID'])
if not aar.empty:
filename_csv = os.path.join(path, 'Output', 'Data', 'csv', 'Amino_Acid_Racemization.csv')
aar.to_csv(filename_csv, index=False, encoding='utf-8-sig')
aar.to_excel(writer, sheet_name='Amino Acid Racemization', index=False)
worksheet = writer.sheets['Amino Acid Racemization']
worksheet.set_column('A:ZZ', 20, wrap)
for row in range(1, 5000):
worksheet.set_row(row, 45)
worksheet.freeze_panes(1, 1)
for (col_num, value) in enumerate(aar.columns.values):
worksheet.write(0, col_num, value, header_format)
esr = esr.sort_values(by=['Analysis ID'])
if not esr.empty:
filename_csv = os.path.join(path, 'Output', 'Data', 'csv', 'Electron_Spin_Resonance.csv')
esr.to_csv(filename_csv, index=False, encoding='utf-8-sig')
esr.to_excel(writer, sheet_name='Electron Spin Resonance', index=False)
worksheet = writer.sheets['Electron Spin Resonance']
worksheet.set_column('A:ZZ', 20, wrap)
for row in range(1, 5000):
worksheet.set_row(row, 45)
worksheet.freeze_panes(1, 1)
for (col_num, value) in enumerate(esr.columns.values):
worksheet.write(0, col_num, value, header_format)
lum = lum.sort_values(by=['Analysis ID'])
if not lum.empty:
filename_csv = os.path.join(path, 'Output', 'Data', 'csv', 'Luminescence.csv')
lum.to_csv(filename_csv, index=False, encoding='utf-8-sig')
lum.to_excel(writer, sheet_name='Luminescence', index=False)
worksheet = writer.sheets['Luminescence']
worksheet.set_column('A:ZZ', 20, wrap)
for row in range(1, 5000):
worksheet.set_row(row, 45)
worksheet.freeze_panes(1, 1)
for (col_num, value) in enumerate(lum.columns.values):
worksheet.write(0, col_num, value, header_format)
strat = strat.sort_values(by=['Chronostratigraphy ID'])
if not strat.empty:
filename_csv = os.path.join(path, 'Output', 'Data', 'csv', 'Chronostratigrapy.csv')
strat.to_csv(filename_csv, index=False, encoding='utf-8-sig')
strat.to_excel(writer, sheet_name='Chronostratigraphy', index=False)
worksheet = writer.sheets['Chronostratigraphy']
worksheet.set_column('A:ZZ', 20, wrap)
for row in range(1, 5000):
worksheet.set_row(row, 45)
worksheet.freeze_panes(1, 1)
for (col_num, value) in enumerate(strat.columns.values):
worksheet.write(0, col_num, value, header_format)
other = other.sort_values(by=['WALIS Other chronology ID'])
if not other.empty:
filename_csv = os.path.join(path, 'Output', 'Data', 'csv', 'Other_age_constraints.csv')
other.to_csv(filename_csv, index=False, encoding='utf-8-sig')
other.to_excel(writer, sheet_name='Other age constraints', index=False)
worksheet = writer.sheets['Other age constraints']
worksheet.set_column('A:ZZ', 20, wrap)
for row in range(1, 5000):
worksheet.set_row(row, 45)
worksheet.freeze_panes(1, 1)
for (col_num, value) in enumerate(other.columns.values):
worksheet.write(0, col_num, value, header_format)
References_query.drop(columns=['Abstract'], inplace=True)
references_query = References_query.sort_values(by=['Reference'])
if not References_query.empty:
filename_csv = os.path.join(path, 'Output', 'Data', 'csv', 'References.csv')
References_query.to_csv(filename_csv, index=False, encoding='utf-8-sig')
References_query.to_excel(writer, sheet_name='References', index=False)
worksheet = writer.sheets['References']
worksheet.set_column('A:A', 15, wrap)
worksheet.set_column('B:B', 35, wrap)
worksheet.set_column('C:C', 150, wrap)
worksheet.set_column('D:D', 30, wrap)
worksheet.set_column('E:E', 10, wrap)
worksheet.set_column('F:ZZ', 30, wrap)
worksheet.freeze_panes(1, 1)
for (col_num, value) in enumerate(References_query.columns.values):
worksheet.write(0, col_num, value, header_format)
writer.save()
|
board_bounding_box = [[[-1245, -795], [-410, 310], [-455, 500.0]],\
[[-1245, -795], [-410, 310], [-545, 500.0]],\
[[-1245, -595], [-410, 310], [-585, 500.0]],\
[[-1345, -595], [-410, 310], [-642, 500.0]]]
min_point_before_moving = [[-1245, -354.048022, -417],\
[-1201.1969772, -300, -539],\
[-1155, -248.09308728, -570],\
[-1145, -373.39387246, -642]]
def distorb0(points):
points[:,0] = (points[:,0] + 0.04 * points[:,1] + 0.05 * points[:,2])*1.02
points[:,1] = (points[:,1] - 0.1 * points[:,2] - 0.03 * points[:,0]) * 0.9239
points[:,2] = (points[:,1]*0.07 + points[:,2]) * 1.1
return points
def distorb1(points):
points[:,0] = (points[:,0] + 0.13 * points[:,2]) * 0.98
points[:,1] = (points[:,1] + 0.02 * points[:,0]- 0.10 * points[:,2]) * 1.09
points[:,2] = points[:,2] * 1.02146386
return points
def distorb2(points):
points[:,0] = (points[:,0] - 0.1 * points[:,1] + 0.1 *points[:,2]) * 1.035
points[:,1] = (points[:,1] + 0 * points[:,0] + 0.03 * points[:,2]) * 1.02
points[:,2] = (points[:,2] + 0.07 * points[:,0] + 0*points[:,1]) * 0.99
points[:] = points[:] - points.min(axis = 0)
return points
def distorb3(points):
points[:,0] = (points[:,0] - 0 * points[:,1] + 0.05 * points[:,2]) * 1.09627
points[:,1] = (points[:,1] - 0.08 * points[:,0] - 0.05 * points[:,2]) * 1.0126
points[:,2] = (points[:,2] + 0 * points[:,1]- 0 * points [:,0]) * 0.92
return points
distorb_function_list = [distorb0,distorb1,distorb2,distorb3]
Jointlists = ["-54.259,48.396,-73.360,116.643,0,0",\
"-79.785,60.523,-45.213,89.762,0,0",\
"-132.513,67.412,-61.807,44.201,0,0",\
"-159.362,-28.596,-132.738,40.801,0,0",\
"-87.73,22.19,-68.21,86.53,0,0"]
Jointlists2 = ["-65,42,-82,78,10,123",\
"-83,41,-72,1,-12,177",\
"-103,45,-70,1,-12,177",\
"-120,49,-61,3,-18,158",
"0,0,0,0,0,0",\
"0,-30,-60,0,30,0",\
"-20,-40,-90,0,50,-20"]
#for scanning inside the blue tape area
Jointlists3 = ["-46.210,55.918,-49.154,-132.490,12.763,-15.858",\
"-87.449,70.578,-19.635,-173.968,21.964,-14.013",\
"-123.609,44.375,-67.215,-181.781,1.13,-35.786",\
"-87.859,-16.706,-142.57,-173.117,-61.720,-3.253"]
|
board_bounding_box = [[[-1245, -795], [-410, 310], [-455, 500.0]], [[-1245, -795], [-410, 310], [-545, 500.0]], [[-1245, -595], [-410, 310], [-585, 500.0]], [[-1345, -595], [-410, 310], [-642, 500.0]]]
min_point_before_moving = [[-1245, -354.048022, -417], [-1201.1969772, -300, -539], [-1155, -248.09308728, -570], [-1145, -373.39387246, -642]]
def distorb0(points):
points[:, 0] = (points[:, 0] + 0.04 * points[:, 1] + 0.05 * points[:, 2]) * 1.02
points[:, 1] = (points[:, 1] - 0.1 * points[:, 2] - 0.03 * points[:, 0]) * 0.9239
points[:, 2] = (points[:, 1] * 0.07 + points[:, 2]) * 1.1
return points
def distorb1(points):
points[:, 0] = (points[:, 0] + 0.13 * points[:, 2]) * 0.98
points[:, 1] = (points[:, 1] + 0.02 * points[:, 0] - 0.1 * points[:, 2]) * 1.09
points[:, 2] = points[:, 2] * 1.02146386
return points
def distorb2(points):
points[:, 0] = (points[:, 0] - 0.1 * points[:, 1] + 0.1 * points[:, 2]) * 1.035
points[:, 1] = (points[:, 1] + 0 * points[:, 0] + 0.03 * points[:, 2]) * 1.02
points[:, 2] = (points[:, 2] + 0.07 * points[:, 0] + 0 * points[:, 1]) * 0.99
points[:] = points[:] - points.min(axis=0)
return points
def distorb3(points):
points[:, 0] = (points[:, 0] - 0 * points[:, 1] + 0.05 * points[:, 2]) * 1.09627
points[:, 1] = (points[:, 1] - 0.08 * points[:, 0] - 0.05 * points[:, 2]) * 1.0126
points[:, 2] = (points[:, 2] + 0 * points[:, 1] - 0 * points[:, 0]) * 0.92
return points
distorb_function_list = [distorb0, distorb1, distorb2, distorb3]
jointlists = ['-54.259,48.396,-73.360,116.643,0,0', '-79.785,60.523,-45.213,89.762,0,0', '-132.513,67.412,-61.807,44.201,0,0', '-159.362,-28.596,-132.738,40.801,0,0', '-87.73,22.19,-68.21,86.53,0,0']
jointlists2 = ['-65,42,-82,78,10,123', '-83,41,-72,1,-12,177', '-103,45,-70,1,-12,177', '-120,49,-61,3,-18,158', '0,0,0,0,0,0', '0,-30,-60,0,30,0', '-20,-40,-90,0,50,-20']
jointlists3 = ['-46.210,55.918,-49.154,-132.490,12.763,-15.858', '-87.449,70.578,-19.635,-173.968,21.964,-14.013', '-123.609,44.375,-67.215,-181.781,1.13,-35.786', '-87.859,-16.706,-142.57,-173.117,-61.720,-3.253']
|
"""Semantic versioning for the package qtools3."""
VERSION = (0, 3, 6)
__version__ = '.'.join(map(str, VERSION))
|
"""Semantic versioning for the package qtools3."""
version = (0, 3, 6)
__version__ = '.'.join(map(str, VERSION))
|
class Door:
status = 'undefined'
def __init__(self, number, status, lock):
self.number = number
self.status = status
self.lock = lock
def open(self):
"""Door opened"""
if self.lock == 'unlocked':
self.status = 'opened'
def close(self):
"""Door closed"""
self.status = 'closed'
def onLock(self):
"""Door locked"""
self.lock = 'locked'
def unLock(self):
"""Door unlocked"""
self.lock = 'unlocked'
@classmethod
def knock(cls):
print("Knock!")
door1 = Door(1, 'closed', 'unlocked')
door1.open()
print(door1.status)
door1.close()
print(door1.status)
door1.onLock()
print(door1.lock)
door1.open()
print(door1.status)
door1.unLock()
door1.open()
print(door1.status)
class ColouredDoor:
def __init__(self, number, colour, status='closed'):
self.number = number
self.status = status
self.colour = colour
def open(self):
"""Door opened"""
self.status = 'opened'
def close(self):
"""Door closed"""
self.status = 'closed'
cdoor1 = ColouredDoor(1, 'opened', 'black')
print(cdoor1.colour)
cdoor1.colour = 'white'
print(cdoor1.colour)
cdoor2 = ColouredDoor(2, 'orange')
print(cdoor2.colour)
cdoor2.status
print(cdoor2.status)
cdoor2.open()
print(cdoor2.status)
class ToggleDoor:
def __init__(self, number, status):
self.number = number
self.status = status
def toggle(self):
"""Door toggled"""
tog_dict = {'closed': 'opened', 'opened': 'closed'}
self.status = tog_dict[self.status]
tdoors1 = ToggleDoor(1, 'opened')
print(tdoors1.status)
tdoors1.toggle()
print(tdoors1.status)
door1 = Door(1, 'closed', 'locked')
door1.knock()
|
class Door:
status = 'undefined'
def __init__(self, number, status, lock):
self.number = number
self.status = status
self.lock = lock
def open(self):
"""Door opened"""
if self.lock == 'unlocked':
self.status = 'opened'
def close(self):
"""Door closed"""
self.status = 'closed'
def on_lock(self):
"""Door locked"""
self.lock = 'locked'
def un_lock(self):
"""Door unlocked"""
self.lock = 'unlocked'
@classmethod
def knock(cls):
print('Knock!')
door1 = door(1, 'closed', 'unlocked')
door1.open()
print(door1.status)
door1.close()
print(door1.status)
door1.onLock()
print(door1.lock)
door1.open()
print(door1.status)
door1.unLock()
door1.open()
print(door1.status)
class Coloureddoor:
def __init__(self, number, colour, status='closed'):
self.number = number
self.status = status
self.colour = colour
def open(self):
"""Door opened"""
self.status = 'opened'
def close(self):
"""Door closed"""
self.status = 'closed'
cdoor1 = coloured_door(1, 'opened', 'black')
print(cdoor1.colour)
cdoor1.colour = 'white'
print(cdoor1.colour)
cdoor2 = coloured_door(2, 'orange')
print(cdoor2.colour)
cdoor2.status
print(cdoor2.status)
cdoor2.open()
print(cdoor2.status)
class Toggledoor:
def __init__(self, number, status):
self.number = number
self.status = status
def toggle(self):
"""Door toggled"""
tog_dict = {'closed': 'opened', 'opened': 'closed'}
self.status = tog_dict[self.status]
tdoors1 = toggle_door(1, 'opened')
print(tdoors1.status)
tdoors1.toggle()
print(tdoors1.status)
door1 = door(1, 'closed', 'locked')
door1.knock()
|
# generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/home/icefire/ws/src/gscam/include;/usr/include/gstreamer-1.0;/usr/include/glib-2.0;/usr/lib/aarch64-linux-gnu/glib-2.0/include".split(';') if "/home/icefire/ws/src/gscam/include;/usr/include/gstreamer-1.0;/usr/include/glib-2.0;/usr/lib/aarch64-linux-gnu/glib-2.0/include" != "" else []
PROJECT_CATKIN_DEPENDS = "roscpp;nodelet;image_transport;sensor_msgs;camera_calibration_parsers;camera_info_manager".replace(';', ' ')
PKG_CONFIG_LIBRARIES_WITH_PREFIX = "-lgscam;-lgstapp-1.0;-lgstbase-1.0;-lgstreamer-1.0;-lgobject-2.0;-lglib-2.0".split(';') if "-lgscam;-lgstapp-1.0;-lgstbase-1.0;-lgstreamer-1.0;-lgobject-2.0;-lglib-2.0" != "" else []
PROJECT_NAME = "gscam"
PROJECT_SPACE_DIR = "/home/icefire/ws/devel"
PROJECT_VERSION = "1.0.1"
|
catkin_package_prefix = ''
project_pkg_config_include_dirs = '/home/icefire/ws/src/gscam/include;/usr/include/gstreamer-1.0;/usr/include/glib-2.0;/usr/lib/aarch64-linux-gnu/glib-2.0/include'.split(';') if '/home/icefire/ws/src/gscam/include;/usr/include/gstreamer-1.0;/usr/include/glib-2.0;/usr/lib/aarch64-linux-gnu/glib-2.0/include' != '' else []
project_catkin_depends = 'roscpp;nodelet;image_transport;sensor_msgs;camera_calibration_parsers;camera_info_manager'.replace(';', ' ')
pkg_config_libraries_with_prefix = '-lgscam;-lgstapp-1.0;-lgstbase-1.0;-lgstreamer-1.0;-lgobject-2.0;-lglib-2.0'.split(';') if '-lgscam;-lgstapp-1.0;-lgstbase-1.0;-lgstreamer-1.0;-lgobject-2.0;-lglib-2.0' != '' else []
project_name = 'gscam'
project_space_dir = '/home/icefire/ws/devel'
project_version = '1.0.1'
|
_NORMALIZING_FLOWS = {}
class RegisterFlow(object):
"""Decorator to registor NormalizingFlow classes.
Parameters
----------
flow_cls_name : str
name of the NormalizingFlow class. This will be used in the
`get_flow` method as the key for the class.
Usage
-----
>>> @flow_lib.RegisterFlow('MyFlow')
>>> class MyFlow(NormalizingFlow)
>>> ...
"""
def __init__(self, flow_cls_name):
self._key = flow_cls_name
def __call__(self, flow_cls):
if not hasattr(flow_cls, 'transform'):
raise TypeError("flow_cls must implement a `transform` method, "
"recieved %s" % flow_cls)
if self._key in _NORMALIZING_FLOWS:
raise ValueError("%s has already been registered to : %s"
% (self._key, _NORMALIZING_FLOWS[self._key]))
_NORMALIZING_FLOWS[self._key] = flow_cls
return flow_cls
def _registered_flow(name):
"""Get the normalizing flow class registered to `name`."""
return _NORMALIZING_FLOWS.get(name, None)
def get_flow(name, n_iter=2, random_state=123):
flow_class = _registered_flow(name)
if flow_class is None:
raise NotImplementedError(
"No Normalizing Flow registered with name %s" % name)
return flow_class(n_iter=n_iter, random_state=random_state)
|
_normalizing_flows = {}
class Registerflow(object):
"""Decorator to registor NormalizingFlow classes.
Parameters
----------
flow_cls_name : str
name of the NormalizingFlow class. This will be used in the
`get_flow` method as the key for the class.
Usage
-----
>>> @flow_lib.RegisterFlow('MyFlow')
>>> class MyFlow(NormalizingFlow)
>>> ...
"""
def __init__(self, flow_cls_name):
self._key = flow_cls_name
def __call__(self, flow_cls):
if not hasattr(flow_cls, 'transform'):
raise type_error('flow_cls must implement a `transform` method, recieved %s' % flow_cls)
if self._key in _NORMALIZING_FLOWS:
raise value_error('%s has already been registered to : %s' % (self._key, _NORMALIZING_FLOWS[self._key]))
_NORMALIZING_FLOWS[self._key] = flow_cls
return flow_cls
def _registered_flow(name):
"""Get the normalizing flow class registered to `name`."""
return _NORMALIZING_FLOWS.get(name, None)
def get_flow(name, n_iter=2, random_state=123):
flow_class = _registered_flow(name)
if flow_class is None:
raise not_implemented_error('No Normalizing Flow registered with name %s' % name)
return flow_class(n_iter=n_iter, random_state=random_state)
|
n = int(input())
ans = (n * (n + 1)) // 2
ans = 4 * ans
ans = ans - 4 * n
ans = 1 + ans
print(ans)
|
n = int(input())
ans = n * (n + 1) // 2
ans = 4 * ans
ans = ans - 4 * n
ans = 1 + ans
print(ans)
|
# ------------------------------
# 486. Predict the Winner
#
# Description:
# Given an array of scores that are non-negative integers. Player 1 picks one of the numbers from either end of the array followed by the player 2 and then player 1 and so on. Each time a player picks a number, that number will not be available for the next player. This continues until all the scores have been chosen. The player with the maximum score wins.
# Given an array of scores, predict whether player 1 is the winner. You can assume each player plays to maximize his score.
#
# Example 1:
# Input: [1, 5, 2]
# Output: False
# Explanation: Initially, player 1 can choose between 1 and 2.
# If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2).
# So, final score of player 1 is 1 + 2 = 3, and player 2 is 5.
# Hence, player 1 will never be the winner and you need to return False.
#
# Note:
# 1 <= length of the array <= 20.
# Any scores in the given array are non-negative integers and will not exceed 10,000,000.
# If the scores of both players are equal, then player 1 is still the winner.
#
# Version: 1.0
# 10/17/18 by Jianfa
# ------------------------------
class Solution:
def PredictTheWinner(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
# Dynamic Programming solution
# O(n^2) space complexity, O(n^2) time complexity
if len(nums) == 1:
return True
dp = [[-1 for _ in range(len(nums))] for _ in range(len(nums))]
currSum = sum(nums)
player1 = self.helper(nums, dp, currSum, 0, len(nums) - 1)
player2 = currSum - player1
return player1 >= player2
def helper(self, nums, dp, currSum, s, e):
# Return the max price for one player when he starts to pick number between nums[s] and nums[e]
if s == e:
dp[s][e] = nums[s]
return dp[s][e]
if dp[s+1][e] >= 0: # candidate1: dp[s][e] = nums[s] + dp[s+1][e]
maxCandidate1 = currSum - dp[s+1][e]
else:
maxCandidate1 = currSum - self.helper(nums, dp, currSum - nums[s], s+1, e)
if dp[s][e-1] >= 0: # candidate2: dp[s][e] = nums[e] + dp[s][e-1]
maxCandidate2 = currSum - dp[s][e-1]
else:
maxCandidate2 = currSum - self.helper(nums, dp, currSum - nums[e], s, e-1)
dp[s][e] = max(maxCandidate1, maxCandidate2)
return dp[s][e]
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Dynamic programming solution.
|
class Solution:
def predict_the_winner(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if len(nums) == 1:
return True
dp = [[-1 for _ in range(len(nums))] for _ in range(len(nums))]
curr_sum = sum(nums)
player1 = self.helper(nums, dp, currSum, 0, len(nums) - 1)
player2 = currSum - player1
return player1 >= player2
def helper(self, nums, dp, currSum, s, e):
if s == e:
dp[s][e] = nums[s]
return dp[s][e]
if dp[s + 1][e] >= 0:
max_candidate1 = currSum - dp[s + 1][e]
else:
max_candidate1 = currSum - self.helper(nums, dp, currSum - nums[s], s + 1, e)
if dp[s][e - 1] >= 0:
max_candidate2 = currSum - dp[s][e - 1]
else:
max_candidate2 = currSum - self.helper(nums, dp, currSum - nums[e], s, e - 1)
dp[s][e] = max(maxCandidate1, maxCandidate2)
return dp[s][e]
if __name__ == '__main__':
test = solution()
|
def power_supply(network: list[list], plant: dict, lis=None) -> set:
if not lis: lis = []
net = network.copy()
for key, value in plant.items():
for [a, b] in tuple(net):
if key in [a, b]:
net.remove([a, b])
if value > 0:
lis.append(a if key == b else b)
if value > 1:
power_supply(net, {lis[-1]: value - 1}, lis)
return set([item for net in network for item in net]) - set(lis) - set(plant.keys())
# def power_supply(network, power_plants):
# out = {x for y in network for x in y}
# queue = list(power_plants.items())
# for k, v in ((x, y) for x, y in queue if y >= 0):
# queue += [(j if k == i else i, v-1) for i, j in network if k in (i, j)]
# out -= {k}
# return out
if __name__ == '__main__':
print(power_supply([['p0', 'c1'], ['p0', 'c2'], ['p0', 'c3'],
['p0', 'c4'], ['c4', 'c9'], ['c4', 'c10'],
['c10', 'c11'], ['c11', 'p12'], ['c2', 'c5'],
['c2', 'c6'], ['c5', 'c7'], ['c5', 'p8']],
{'p0': 1, 'p12': 4, 'p8': 1})) # set(['c0', 'c3']
|
def power_supply(network: list[list], plant: dict, lis=None) -> set:
if not lis:
lis = []
net = network.copy()
for (key, value) in plant.items():
for [a, b] in tuple(net):
if key in [a, b]:
net.remove([a, b])
if value > 0:
lis.append(a if key == b else b)
if value > 1:
power_supply(net, {lis[-1]: value - 1}, lis)
return set([item for net in network for item in net]) - set(lis) - set(plant.keys())
if __name__ == '__main__':
print(power_supply([['p0', 'c1'], ['p0', 'c2'], ['p0', 'c3'], ['p0', 'c4'], ['c4', 'c9'], ['c4', 'c10'], ['c10', 'c11'], ['c11', 'p12'], ['c2', 'c5'], ['c2', 'c6'], ['c5', 'c7'], ['c5', 'p8']], {'p0': 1, 'p12': 4, 'p8': 1}))
|
class Contact:
all_contacts = []
def __init__(self, name, email):
self.name = name
self.email = email
Contact.all_contacts.append(self)
class Supplier(Contact):
def order(self, order):
print("if this were a real system we would send " f"{order} order to {self.name}")
|
class Contact:
all_contacts = []
def __init__(self, name, email):
self.name = name
self.email = email
Contact.all_contacts.append(self)
class Supplier(Contact):
def order(self, order):
print(f'if this were a real system we would send {order} order to {self.name}')
|
'''
Created on Oct 22, 2018
@author: casey
'''
class Segment(object):
#
# * Segments make up the tree. There is a base segment, then a root segment, then the tree expands into internal segments, until it gets to leaf segments.
# * These segment types make it easier to traverse the tree during building and during evaluation
#
def __init__(self, l=0):
self.left = l
self.right = -1
self.link = None
def set_link(self, link):
self.link = link
def get_link(self):
return self.link
def get_left(self):
return self.left
def get_right(self):
return -1
def put(self, branch, w):
return None
def find_index(self, word):
return 0
def find_branch(self, ind):
return None
def set_count(self, d):
pass
def get_count(self):
return 0.0
def span(self):
return self.get_right() - self.get_left()
def increment(self, d):
pass
def num_children(self):
return 0
def __str__(self):
return str((self.__class__.__name__, self.left, self.right, str(self.link)))
class InternalSegment(Segment):
def __init__(self, l):
super(InternalSegment, self).__init__(l)
self.children = dict()
self.set_count(0.0)
def find_branch(self, w):
if len(self.children) == 0:
return None
i = self.find_index(w)
if i == -2:
return None
return self.children[i]
def find_index(self, i):
if i in self.children:
return i
return -2
def get_right(self):
return self.children[self.right].get_left()
def update_count(self):
self.set_count(0.0)
for s in self.children.keys():
self.increment(self.children[s].get_count())
def get_count(self):
return self.count
def set_count(self, d):
self.count = d
def increment(self, d):
self.count += d
def num_children(self):
return len(self.children)
def put(self, branch, w):
i = self.find_index(w)
if i == -2:
if len(self.children) == 0: self.right = w
self.children[w] = branch
return None
else:
old = self.children[w]
self.children[w] = branch
return old
class RootSegment(InternalSegment):
def __init__(self, text):
super(RootSegment, self).__init__(-1)
self.text = text
def get_right(self):
return 0
def increment(self, d):
pass
def get_count(self):
return self.text.size()
class BaseSegment(InternalSegment):
def __init__(self, root):
super(BaseSegment, self).__init__(-2)
self.root = root
def find_branch(self, word):
return self.root
class LeafSegment(Segment):
def __init__(self, text, l):
super(LeafSegment, self).__init__(l)
self.text = text
def get_right(self):
return self.text.size()
def num_children(self):
return 0
def find_index(self, word):
return -2
def get_count(self):
return 1.0
def find_branch(self, word):
return None
|
"""
Created on Oct 22, 2018
@author: casey
"""
class Segment(object):
def __init__(self, l=0):
self.left = l
self.right = -1
self.link = None
def set_link(self, link):
self.link = link
def get_link(self):
return self.link
def get_left(self):
return self.left
def get_right(self):
return -1
def put(self, branch, w):
return None
def find_index(self, word):
return 0
def find_branch(self, ind):
return None
def set_count(self, d):
pass
def get_count(self):
return 0.0
def span(self):
return self.get_right() - self.get_left()
def increment(self, d):
pass
def num_children(self):
return 0
def __str__(self):
return str((self.__class__.__name__, self.left, self.right, str(self.link)))
class Internalsegment(Segment):
def __init__(self, l):
super(InternalSegment, self).__init__(l)
self.children = dict()
self.set_count(0.0)
def find_branch(self, w):
if len(self.children) == 0:
return None
i = self.find_index(w)
if i == -2:
return None
return self.children[i]
def find_index(self, i):
if i in self.children:
return i
return -2
def get_right(self):
return self.children[self.right].get_left()
def update_count(self):
self.set_count(0.0)
for s in self.children.keys():
self.increment(self.children[s].get_count())
def get_count(self):
return self.count
def set_count(self, d):
self.count = d
def increment(self, d):
self.count += d
def num_children(self):
return len(self.children)
def put(self, branch, w):
i = self.find_index(w)
if i == -2:
if len(self.children) == 0:
self.right = w
self.children[w] = branch
return None
else:
old = self.children[w]
self.children[w] = branch
return old
class Rootsegment(InternalSegment):
def __init__(self, text):
super(RootSegment, self).__init__(-1)
self.text = text
def get_right(self):
return 0
def increment(self, d):
pass
def get_count(self):
return self.text.size()
class Basesegment(InternalSegment):
def __init__(self, root):
super(BaseSegment, self).__init__(-2)
self.root = root
def find_branch(self, word):
return self.root
class Leafsegment(Segment):
def __init__(self, text, l):
super(LeafSegment, self).__init__(l)
self.text = text
def get_right(self):
return self.text.size()
def num_children(self):
return 0
def find_index(self, word):
return -2
def get_count(self):
return 1.0
def find_branch(self, word):
return None
|
class SingleLinkedNode:
def __init__(self, datum):
"""Node in a single linked list
:param datum: the datum associated with this node
"""
self.next_node = None
self.datum = datum
def __str__(self):
return "datum={}; next={}".format(
self.datum,
"None" if self.next_node is None else self.next_node.datum)
def __lt__(self, other):
return self.datum < other.datum
def __eq__(self, other):
return self.datum == other.datum
def __hash__(self):
return hash(self.datum)
class DoubleLinkedNode(SingleLinkedNode):
def __init__(self, datum=None):
"""Node in a doubly linked list"""
super().__init__(datum)
self.previous_node = None
def __str__(self):
return "previous={}; {}".format(
"None" if self.previous_node is None else self.previous_node.datum,
super().__str__())
|
class Singlelinkednode:
def __init__(self, datum):
"""Node in a single linked list
:param datum: the datum associated with this node
"""
self.next_node = None
self.datum = datum
def __str__(self):
return 'datum={}; next={}'.format(self.datum, 'None' if self.next_node is None else self.next_node.datum)
def __lt__(self, other):
return self.datum < other.datum
def __eq__(self, other):
return self.datum == other.datum
def __hash__(self):
return hash(self.datum)
class Doublelinkednode(SingleLinkedNode):
def __init__(self, datum=None):
"""Node in a doubly linked list"""
super().__init__(datum)
self.previous_node = None
def __str__(self):
return 'previous={}; {}'.format('None' if self.previous_node is None else self.previous_node.datum, super().__str__())
|
num = int(input("enter the number"))
for i in range(2,num):
if num%i==0:
print("not prime")
break
else:
print("prime")
|
num = int(input('enter the number'))
for i in range(2, num):
if num % i == 0:
print('not prime')
break
else:
print('prime')
|
class TicTacToe:
def __init__(self):
self.tab = ['.','.','.','.','.','.','.','.','.','.']
def curr_state(self): #obecny stan tablicy
return ''.join(self.tab)
def postaw_znak_o(self, x, y): #interfejs dla stawiania znaku przez gracza
if x < 0 or x > 2 or y < 0 or y > 2 or self.tab[ x + (y*3) ] != '.': return 1 #kod bledu 1 - podano zla liczbe
self.tab[ x + (y*3) ] = 'O'
self.tab[9] = 'O'
return 0
def wyswietl_tab(self): #wyswietla tablice
for i in range(0, 7, 3):
print( self.tab[ i : (i+3) ] )
def reset(self):
self.tab = ['.','.','.','.','.','.','.','.','.','.']
def check_state(self, state): #sprawdza wygrana
# 1 = wygral x, 0 = remis, -1 = wygral O, -2
for i in range(0, 7, 3):
if state[i:(i+3)] == ['X', 'X', 'X']: return 1
if state[i:(i+3)] == ['O', 'O', 'O']: return -1
for i in range(0,3):
if state[i] == 'X' and state[(i+3)] == 'X' and state[(i+6)] == 'X': return 1
if state[i] == 'O' and state[(i+3)] == 'O' and state[(i+6)] == 'O': return -1
if state[0] == 'X' and state[4] == 'X' and state[8] == 'X': return 1
elif state[0] == 'O' and state[4] == 'O' and state[8] == 'O': return -1
elif state[2] == 'X' and state[4] == 'X' and state[6] == 'X': return 1
elif state[2] == 'O' and state[4] == 'O' and state[6] == 'O': return -1
elif '.' not in state: return 0 #w razie remisu return 0
return -2
def next_state_x(self): #wyswietl mozliwe stany dla gracza x
possibilities = []
for i in range(0, 9):
if self.tab[i] == '.':
possibility = []
possibility.extend(self.tab)
possibility[9] = 'X'
possibility[i] = 'X'
possibilities.append(''.join(possibility))
return possibilities
#wyswietl mozliwe nastepne stany dla state przyjmuje stan jako string
def next_state_x_for(self, state):
state = list(state)
possibilities = []
for i in range(0, 9):
if state[i] == '.':
possibility = []
possibility.extend(self.tab)
possibility[9] = 'X'
possibility[i] = 'X'
possibilities.append(''.join(possibility))
return possibilities
#zasadnicza roznica miedzy obydwiema powyzszymi funkcjami jest taka ze ta
#pierwsza dziala dla game.tab a druga dla dowolnego stanu, napisalem ja
#poniewaz musze dostac kolejne stany po danym w rekurencyjnym policy evaluation
def next_state_o(self): #wyswietl mozliwe stany dla gracza o
possibilities = []
for i in range(0,9):
if self.tab[i] == '.':
possibility = []
possibility.extend(self.tab)
possibility[9] = 'O'
possibility[i] = 'O'
possibilities.append(''.join(possibility))
return possibilities
|
class Tictactoe:
def __init__(self):
self.tab = ['.', '.', '.', '.', '.', '.', '.', '.', '.', '.']
def curr_state(self):
return ''.join(self.tab)
def postaw_znak_o(self, x, y):
if x < 0 or x > 2 or y < 0 or (y > 2) or (self.tab[x + y * 3] != '.'):
return 1
self.tab[x + y * 3] = 'O'
self.tab[9] = 'O'
return 0
def wyswietl_tab(self):
for i in range(0, 7, 3):
print(self.tab[i:i + 3])
def reset(self):
self.tab = ['.', '.', '.', '.', '.', '.', '.', '.', '.', '.']
def check_state(self, state):
for i in range(0, 7, 3):
if state[i:i + 3] == ['X', 'X', 'X']:
return 1
if state[i:i + 3] == ['O', 'O', 'O']:
return -1
for i in range(0, 3):
if state[i] == 'X' and state[i + 3] == 'X' and (state[i + 6] == 'X'):
return 1
if state[i] == 'O' and state[i + 3] == 'O' and (state[i + 6] == 'O'):
return -1
if state[0] == 'X' and state[4] == 'X' and (state[8] == 'X'):
return 1
elif state[0] == 'O' and state[4] == 'O' and (state[8] == 'O'):
return -1
elif state[2] == 'X' and state[4] == 'X' and (state[6] == 'X'):
return 1
elif state[2] == 'O' and state[4] == 'O' and (state[6] == 'O'):
return -1
elif '.' not in state:
return 0
return -2
def next_state_x(self):
possibilities = []
for i in range(0, 9):
if self.tab[i] == '.':
possibility = []
possibility.extend(self.tab)
possibility[9] = 'X'
possibility[i] = 'X'
possibilities.append(''.join(possibility))
return possibilities
def next_state_x_for(self, state):
state = list(state)
possibilities = []
for i in range(0, 9):
if state[i] == '.':
possibility = []
possibility.extend(self.tab)
possibility[9] = 'X'
possibility[i] = 'X'
possibilities.append(''.join(possibility))
return possibilities
def next_state_o(self):
possibilities = []
for i in range(0, 9):
if self.tab[i] == '.':
possibility = []
possibility.extend(self.tab)
possibility[9] = 'O'
possibility[i] = 'O'
possibilities.append(''.join(possibility))
return possibilities
|
ERR_EXCEED_LIMIT = "Not enough space"
class NotEnoughSpace(Exception):
pass
|
err_exceed_limit = 'Not enough space'
class Notenoughspace(Exception):
pass
|
class SeriesField(object):
def __init__(self):
self.series = []
def add_serie(self, serie):
self.series.append(serie)
def to_javascript(self):
jsc = "series: ["
for s in self.series:
jsc += s.to_javascript() + "," # the last comma is accepted by javascript, no need to ignore
jsc += "]"
return jsc
|
class Seriesfield(object):
def __init__(self):
self.series = []
def add_serie(self, serie):
self.series.append(serie)
def to_javascript(self):
jsc = 'series: ['
for s in self.series:
jsc += s.to_javascript() + ','
jsc += ']'
return jsc
|
self.description = "conflict 'db vs db'"
sp1 = pmpkg("pkg1", "1.0-2")
sp1.conflicts = ["pkg2"]
self.addpkg2db("sync", sp1);
sp2 = pmpkg("pkg2", "1.0-2")
self.addpkg2db("sync", sp2)
lp1 = pmpkg("pkg1")
self.addpkg2db("local", lp1)
lp2 = pmpkg("pkg2")
self.addpkg2db("local", lp2)
self.args = "-S %s --ask=4" % " ".join([p.name for p in (sp1, sp2)])
self.addrule("PACMAN_RETCODE=1")
self.addrule("PKG_EXIST=pkg1")
self.addrule("PKG_EXIST=pkg2")
|
self.description = "conflict 'db vs db'"
sp1 = pmpkg('pkg1', '1.0-2')
sp1.conflicts = ['pkg2']
self.addpkg2db('sync', sp1)
sp2 = pmpkg('pkg2', '1.0-2')
self.addpkg2db('sync', sp2)
lp1 = pmpkg('pkg1')
self.addpkg2db('local', lp1)
lp2 = pmpkg('pkg2')
self.addpkg2db('local', lp2)
self.args = '-S %s --ask=4' % ' '.join([p.name for p in (sp1, sp2)])
self.addrule('PACMAN_RETCODE=1')
self.addrule('PKG_EXIST=pkg1')
self.addrule('PKG_EXIST=pkg2')
|
# To check a number is prime or not
num = int(input("Enter a number: "))
check = 0
if(num>=0):
for i in range(1,num+1):
if( (num % i) == 0 ):
check=check+1
if(check==2):
print(num,"is a prime number.")
else:
print(num,"is not a prime number.");
else:
print("========Please Enter a positive number=======")
|
num = int(input('Enter a number: '))
check = 0
if num >= 0:
for i in range(1, num + 1):
if num % i == 0:
check = check + 1
if check == 2:
print(num, 'is a prime number.')
else:
print(num, 'is not a prime number.')
else:
print('========Please Enter a positive number=======')
|
def func1():
pass
def func2():
pass
a = b = func1
b()
a = b = func2
a()
|
def func1():
pass
def func2():
pass
a = b = func1
b()
a = b = func2
a()
|
n=int(input());f=True
if n!=3: f=False
a=set()
for _ in range(n):
b,c=map(int,input().split())
a.add(b);a.add(c)
if a!={1,3,4}:
f=False
print((f) and 'Wa-pa-pa-pa-pa-pa-pow!' or 'Woof-meow-tweet-squeek')
|
n = int(input())
f = True
if n != 3:
f = False
a = set()
for _ in range(n):
(b, c) = map(int, input().split())
a.add(b)
a.add(c)
if a != {1, 3, 4}:
f = False
print(f and 'Wa-pa-pa-pa-pa-pa-pow!' or 'Woof-meow-tweet-squeek')
|
numeros = []
for i in range(1, 1000001):
numeros.append(i)
for numero in numeros:
print(numero)
|
numeros = []
for i in range(1, 1000001):
numeros.append(i)
for numero in numeros:
print(numero)
|
# Event: LCCS Python Fundamental Skills Workshop
# Date: Dec 2018
# Author: Joe English, PDST
# eMail: [email protected]
# Purpose: A program to demonstrate recursion
# A recursive function to add up the first n numbers.
# Example: The sum of the first 5 numbers is 5 + the sum of the first 4 numbers
# So, the sum of the first n numbers is n + the sum of the first n-1 numbers
def sumOfN(n):
if n == 0:
return 0
return n + sumOfN(n-1)
# Call the function to test it
answer = sumOfN(5)
print(answer)
|
def sum_of_n(n):
if n == 0:
return 0
return n + sum_of_n(n - 1)
answer = sum_of_n(5)
print(answer)
|
# Problem: https://docs.google.com/document/d/1Sz1cWKsiQzQUOjC76TzFcOQGYEZIPvQuWg6NjQ0B6VA/edit?usp=sharing
def print_roman(number):
dict = {1:"I", 4:"IV", 5:"V", 9:"IX", 10:"X", 40:"XL", 50:"L",
90:"XC", 100:"C", 400:"CD", 500:"D", 900:"CM", 1000:"M"}
for i in sorted(dict, reverse = True):
result = number // i
number %= i
while result:
print(dict[i], end = "")
result -= 1
print_roman(int(input()))
|
def print_roman(number):
dict = {1: 'I', 4: 'IV', 5: 'V', 9: 'IX', 10: 'X', 40: 'XL', 50: 'L', 90: 'XC', 100: 'C', 400: 'CD', 500: 'D', 900: 'CM', 1000: 'M'}
for i in sorted(dict, reverse=True):
result = number // i
number %= i
while result:
print(dict[i], end='')
result -= 1
print_roman(int(input()))
|
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def maxDepth(self, p, d=0):
if p is None:
return 0
d = d + 1
d_left = self.maxDepth(p.left, d)
d_right = self.maxDepth(p.right, d)
return max(d, d_left, d_right)
p = TreeNode(1)
p.left = TreeNode(2)
p.right = TreeNode(3)
p.right.right = TreeNode(4)
slu = Solution()
print(slu.maxDepth(p))
|
class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def max_depth(self, p, d=0):
if p is None:
return 0
d = d + 1
d_left = self.maxDepth(p.left, d)
d_right = self.maxDepth(p.right, d)
return max(d, d_left, d_right)
p = tree_node(1)
p.left = tree_node(2)
p.right = tree_node(3)
p.right.right = tree_node(4)
slu = solution()
print(slu.maxDepth(p))
|
# why does this expression cause problems and what is the fix
# helen o'shea
# 20210203
try:
message = 'I have eaten ' + 99 +' burritos.'
except:
message = 'I have eaten ' + str(99) +' burritos.'
print(message)
|
try:
message = 'I have eaten ' + 99 + ' burritos.'
except:
message = 'I have eaten ' + str(99) + ' burritos.'
print(message)
|
seconds = 365 * 24 * 60 * 60
for year in [1, 2, 5, 10]:
print(seconds * year)
|
seconds = 365 * 24 * 60 * 60
for year in [1, 2, 5, 10]:
print(seconds * year)
|
"""
my_rectangle = {
# Coordinates of bottom-left corner
'left_x' : 1,
'bottom_y' : 1,
# Width and height
'width' : 6,
'height' : 3,
}
"""
def find_overlap(point1, length1, point2, length2):
# get the highest_start_point as the max of point1 and point2
highest_start_point = max(point1, point2)
# get the lowest_end_point as the min of point1 plus length1
# and point2 plus length2
lowest_end_point = min(point1 + length1, point2 + length2)
# if highest_start_point greater than or equal to lowest_end_point
if highest_start_point >= lowest_end_point:
# return a tuple of two Nones
return (None, None)
# set overlap_length to the difference between
# lowest_end_point and highest_start_point
overlap_length = lowest_end_point - highest_start_point
# return a tuple of highest_start_point and overlap_length
return (highest_start_point, overlap_length)
def find_rectangular_overlap(rect1, rect2):
# initialize left_x and width by destructuring the return value of
# find_overlap passing in left_x and width of rect1 and rect2
left_x, width = find_overlap(
rect1['left_x'], rect1['width'], rect2['left_x'], rect2['width'])
# initialize bottom_y and height by destructuring the return value of
# find_overlap passing in bottom_y and height of rect1 and rect2
bottom_y, height = find_overlap(
rect1['bottom_y'], rect1['height'], rect2['bottom_y'], rect2['height'])
# if left_x and bottom_y are None
if left_x is None or bottom_y is None:
# return an object with None for all required properties
return {
'left_x': None,
'bottom_y': None,
'width': None,
'height': None,
}
# return an object with with the return values of find_overlap
return {
'left_x': left_x,
'bottom_y': bottom_y,
'width': width,
'height': height,
}
|
"""
my_rectangle = {
# Coordinates of bottom-left corner
'left_x' : 1,
'bottom_y' : 1,
# Width and height
'width' : 6,
'height' : 3,
}
"""
def find_overlap(point1, length1, point2, length2):
highest_start_point = max(point1, point2)
lowest_end_point = min(point1 + length1, point2 + length2)
if highest_start_point >= lowest_end_point:
return (None, None)
overlap_length = lowest_end_point - highest_start_point
return (highest_start_point, overlap_length)
def find_rectangular_overlap(rect1, rect2):
(left_x, width) = find_overlap(rect1['left_x'], rect1['width'], rect2['left_x'], rect2['width'])
(bottom_y, height) = find_overlap(rect1['bottom_y'], rect1['height'], rect2['bottom_y'], rect2['height'])
if left_x is None or bottom_y is None:
return {'left_x': None, 'bottom_y': None, 'width': None, 'height': None}
return {'left_x': left_x, 'bottom_y': bottom_y, 'width': width, 'height': height}
|
# ------------------------- DESAFIO 005 -------------------------
# Programa para mostrar na tela o sucessor e antecessor de um numero digitado
num = int(input('Digite um Numero: '))
suc = num + 1
ant = num - 1
print('Abaixo seguem os numeros conforme na ordem: \n Antecessor / Numedo Digitado / Sucessor \n {:^10} / {:^15} / {:^8}'.format(ant,num,suc))
|
num = int(input('Digite um Numero: '))
suc = num + 1
ant = num - 1
print('Abaixo seguem os numeros conforme na ordem: \n Antecessor / Numedo Digitado / Sucessor \n {:^10} / {:^15} / {:^8}'.format(ant, num, suc))
|
# -*- coding: utf-8 -*-
"""
REFUSE
Simple cross-plattform ctypes bindings for libfuse / FUSE for macOS / WinFsp
https://github.com/pleiszenburg/refuse
src/refuse/__init__.py: Package root
Copyright (C) 2008-2020 refuse contributors
<LICENSE_BLOCK>
The contents of this file are subject to the Internet Systems Consortium (ISC)
license ("ISC license" or "License"). You may not use this file except in
compliance with the License. You may obtain a copy of the License at
https://opensource.org/licenses/ISC
https://github.com/pleiszenburg/refuse/blob/master/LICENSE
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the
specific language governing rights and limitations under the License.
</LICENSE_BLOCK>
"""
|
"""
REFUSE
Simple cross-plattform ctypes bindings for libfuse / FUSE for macOS / WinFsp
https://github.com/pleiszenburg/refuse
src/refuse/__init__.py: Package root
Copyright (C) 2008-2020 refuse contributors
<LICENSE_BLOCK>
The contents of this file are subject to the Internet Systems Consortium (ISC)
license ("ISC license" or "License"). You may not use this file except in
compliance with the License. You may obtain a copy of the License at
https://opensource.org/licenses/ISC
https://github.com/pleiszenburg/refuse/blob/master/LICENSE
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the
specific language governing rights and limitations under the License.
</LICENSE_BLOCK>
"""
|
# COUNT BY
# This function takes two arguments:
# A list with items to be counted
# The function the list will be mapped to
# This function uses the properties inherent in objects
# to create a new property for each unique value, then
# increase the count of that property each time that
# element appears in the list.
def count_by(arr, fn=lambda x: x):
key = {}
for el in map(fn, arr):
key[el] = 0 if el not in key else key[el]
key[el] += 1
return key
print(count_by(['one','two','three'], len))
# returns {3: 2, 5: 1}
|
def count_by(arr, fn=lambda x: x):
key = {}
for el in map(fn, arr):
key[el] = 0 if el not in key else key[el]
key[el] += 1
return key
print(count_by(['one', 'two', 'three'], len))
|
N, A, B = map(int, input().split())
if (B - A) % 2 == 0:
print('Alice')
else:
print('Borys')
|
(n, a, b) = map(int, input().split())
if (B - A) % 2 == 0:
print('Alice')
else:
print('Borys')
|
"""
RabbitMQ concepts
"""
def Graphic_shape():
return "none"
def Graphic_colorfill():
return "#FFCC66"
def Graphic_colorbg():
return "#FFCC66"
def Graphic_border():
return 2
def Graphic_is_rounded():
return True
# managementUrl = rabbitmq.ManagementUrlPrefix(configNam)
# managementUrl = rabbitmq.ManagementUrlPrefix(configNam,"users",namUser)
# managementUrl = rabbitmq.ManagementUrlPrefix(configNam,"vhosts",namVHost)
# managementUrl = rabbitmq.ManagementUrlPrefix(configNam,"exchanges",namVHost,namExchange)
# managementUrl = rabbitmq.ManagementUrlPrefix(configNam,"queues",namVHost,namQ)
# managementUrl = "http://" + configNam + "/#/queues/" + "%2F" + "/" + namQueue
# managementUrl = "http://" + configNam + "/#/vhosts/" + "%2F"
# managementUrl = "http://" + configNam + "/#/users/" + namUser
# managementUrl = "http://" + configNam + "/#/users/" + namUser
def ManagementUrlPrefix(config_nam, key="vhosts", name_key1="", name_key2=""):
pre_prefix = "http://" + config_nam + "/#/"
if not key:
return pre_prefix
if key == "users":
return pre_prefix + "users/" + name_key1
# It is a virtual host name.
if name_key1 == "/":
effective_v_host = "%2F"
else:
effective_v_host = name_key1
effective_v_host = effective_v_host.lower() # RFC4343
vhost_prefix = pre_prefix + key + "/" + effective_v_host
if key in ["vhosts", "connections"]:
return vhost_prefix
return vhost_prefix + "/" + name_key2
|
"""
RabbitMQ concepts
"""
def graphic_shape():
return 'none'
def graphic_colorfill():
return '#FFCC66'
def graphic_colorbg():
return '#FFCC66'
def graphic_border():
return 2
def graphic_is_rounded():
return True
def management_url_prefix(config_nam, key='vhosts', name_key1='', name_key2=''):
pre_prefix = 'http://' + config_nam + '/#/'
if not key:
return pre_prefix
if key == 'users':
return pre_prefix + 'users/' + name_key1
if name_key1 == '/':
effective_v_host = '%2F'
else:
effective_v_host = name_key1
effective_v_host = effective_v_host.lower()
vhost_prefix = pre_prefix + key + '/' + effective_v_host
if key in ['vhosts', 'connections']:
return vhost_prefix
return vhost_prefix + '/' + name_key2
|
#
# PySNMP MIB module HPN-ICF-ISSU-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPN-ICF-ISSU-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:39:30 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, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueRangeConstraint, ValueSizeConstraint, SingleValueConstraint, ConstraintsIntersection, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsIntersection", "ConstraintsUnion")
hpnicfCommon, = mibBuilder.importSymbols("HPN-ICF-OID-MIB", "hpnicfCommon")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
Gauge32, Bits, Counter32, MibScalar, MibTable, MibTableRow, MibTableColumn, ObjectIdentity, IpAddress, TimeTicks, MibIdentifier, iso, Counter64, NotificationType, ModuleIdentity, Integer32, Unsigned32 = mibBuilder.importSymbols("SNMPv2-SMI", "Gauge32", "Bits", "Counter32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ObjectIdentity", "IpAddress", "TimeTicks", "MibIdentifier", "iso", "Counter64", "NotificationType", "ModuleIdentity", "Integer32", "Unsigned32")
TextualConvention, RowStatus, TruthValue, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "RowStatus", "TruthValue", "DisplayString")
hpnicfIssuUpgrade = ModuleIdentity((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133))
hpnicfIssuUpgrade.setRevisions(('2013-01-15 15:36',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: hpnicfIssuUpgrade.setRevisionsDescriptions(('Initial version of this MIB module. Added hpnicfIssuUpgradeImageTable hpnicfIssuOp hpnicfIssuCompatibleResult hpnicfIssuTestResultTable hpnicfIssuUpgradeResultTable',))
if mibBuilder.loadTexts: hpnicfIssuUpgrade.setLastUpdated('201301151536Z')
if mibBuilder.loadTexts: hpnicfIssuUpgrade.setOrganization('')
if mibBuilder.loadTexts: hpnicfIssuUpgrade.setContactInfo('')
if mibBuilder.loadTexts: hpnicfIssuUpgrade.setDescription("This MIB provides objects for upgrading images on modules in the system, objects for showing the result of an upgrade operation, and objects for showing the result of a test operation. To perform an upgrade operation, a management application must first read the hpnicfIssuUpgradeImageTable table and use the information in other tables, as explained below. You can configure a new image name for each image type as listed in hpnicfIssuUpgradeImageTable. The system will use this image on the particular module at the next reboot. The management application used to perform an upgrade operation must first check if an upgrade operation is already in progress in the system. This is done by reading the hpnicfIssuOpType ('none' indicates that no other upgrade operation is in progress. Any other value indicates that an upgrade is already in progress and a new upgrade operation is not allowed. To start an 'install' operation, the user must first perform a 'test' operation to examine the version compatibility between the given set of images and the running images. Only if the result of the 'test' operation is 'success' can the user proceed to do an install operation. The table hpnicfIssuTestResultTable provides the result of the 'test' operation performed by using hpnicfIssuOpType. The table hpnicfIssuUpgradeResultTable provides the result of the 'install' operation performed by using hpnicfIssuOpType. ")
hpnicfIssuUpgradeMibObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1))
hpnicfIssuUpgradeGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 1))
hpnicfIssuUpgradeImageTable = MibTable((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 1, 1), )
if mibBuilder.loadTexts: hpnicfIssuUpgradeImageTable.setStatus('current')
if mibBuilder.loadTexts: hpnicfIssuUpgradeImageTable.setDescription('A table listing the image variable types that exist in the device.')
hpnicfIssuUpgradeImageEntry = MibTableRow((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 1, 1, 1), ).setIndexNames((0, "HPN-ICF-ISSU-MIB", "hpnicfIssuUpgradeImageIndex"))
if mibBuilder.loadTexts: hpnicfIssuUpgradeImageEntry.setStatus('current')
if mibBuilder.loadTexts: hpnicfIssuUpgradeImageEntry.setDescription('An hpnicfIssuUpgradeImageEntry entry. Each entry provides an image variable type that exists in the device.')
hpnicfIssuUpgradeImageIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647)))
if mibBuilder.loadTexts: hpnicfIssuUpgradeImageIndex.setStatus('current')
if mibBuilder.loadTexts: hpnicfIssuUpgradeImageIndex.setDescription('Index of each image.')
hpnicfIssuUpgradeImageType = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 1, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("boot", 1), ("system", 2), ("feature", 3), ("ipe", 4)))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hpnicfIssuUpgradeImageType.setStatus('current')
if mibBuilder.loadTexts: hpnicfIssuUpgradeImageType.setDescription("Types of images that the system can run. The value of this object has four image variables names - 'boot', 'system', 'feature' and 'ipe'. This table will then list these four strings as follows: hpnicfIssuUpgradeImageType boot system feature IPE The user can assign images (using hpnicfIssuUpgradeImageURL) to these variables and the system will use the assigned images to boot.")
hpnicfIssuUpgradeImageURL = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 1, 1, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 127))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hpnicfIssuUpgradeImageURL.setStatus('current')
if mibBuilder.loadTexts: hpnicfIssuUpgradeImageURL.setDescription('This object contains the path of the image of this entity.')
hpnicfIssuUpgradeImageRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 1, 1, 1, 4), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hpnicfIssuUpgradeImageRowStatus.setStatus('current')
if mibBuilder.loadTexts: hpnicfIssuUpgradeImageRowStatus.setDescription('Row-status of image table.')
hpnicfIssuOp = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 1, 2))
hpnicfIssuOpType = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 1, 2, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("none", 1), ("done", 2), ("test", 3), ("install", 4), ("rollback", 5))).clone('none')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hpnicfIssuOpType.setStatus('current')
if mibBuilder.loadTexts: hpnicfIssuOpType.setDescription("Command to be executed. The 'test' command must be performed before the 'install' command can be executed. The 'install' command is allowed only if a read of this object returns 'test' and the value of object hpnicfIssuOpStatus is 'success'. Command Remarks none If the user sets this object to 'none', the agent will return a success without performing an upgrade operation. done If this object returns any value other than 'none', setting this to 'done' will do the required cleanup of the previous upgrade operation and get the system ready for a new upgrade operation. test Check the version compatibility and upgrade method for the given set of image files. install For all the image entities listed in the hpnicfIssuUpgradeImageTable, perform the required upgrade operation listed in that table. rollback Abort the current 'install' operation and roll back to the previous version. ")
hpnicfIssuImageFileOverwrite = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 1, 2, 2), TruthValue().clone('true')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hpnicfIssuImageFileOverwrite.setStatus('current')
if mibBuilder.loadTexts: hpnicfIssuImageFileOverwrite.setDescription('If you want to overwrite the existing file, set the value of this object to enable. Otherwise, set the value of this object to disable.')
hpnicfIssuOpTrapEnable = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 1, 2, 3), TruthValue().clone('true')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hpnicfIssuOpTrapEnable.setStatus('current')
if mibBuilder.loadTexts: hpnicfIssuOpTrapEnable.setDescription('If you want to enable the trap, set the value of this object to enable. Otherwise, set the value of this object to disable.')
hpnicfIssuOpStatus = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 1, 2, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("none", 1), ("failure", 2), ("inProgress", 3), ("success", 4), ("rollbackInProgress", 5), ("rollbackSuccess", 6))).clone('none')).setMaxAccess("readonly")
if mibBuilder.loadTexts: hpnicfIssuOpStatus.setStatus('current')
if mibBuilder.loadTexts: hpnicfIssuOpStatus.setDescription('Status of the specified operation. none - No operation was performed. failure - Specified operation has failed. inProgress - Specified operation is in progress. success - Specified operation completed successfully. rollbackInProgress - Rollback operation is in progress. rollbackSuccess - Rollback operation completed successfully. ')
hpnicfIssuFailedReason = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 1, 2, 5), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hpnicfIssuFailedReason.setStatus('current')
if mibBuilder.loadTexts: hpnicfIssuFailedReason.setDescription("Indicates the the cause of 'failure' state of the object 'hpnicfIssuOpStatus'. This object would be a null string if the value of 'hpnicfIssuOpStatus' is not 'failure'.")
hpnicfIssuOpTimeCompleted = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 1, 2, 6), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hpnicfIssuOpTimeCompleted.setStatus('current')
if mibBuilder.loadTexts: hpnicfIssuOpTimeCompleted.setDescription("Indicates the time when the upgrade operation was completed. This object would be a null string if hpnicfIssuOpType is 'none'. ")
hpnicfIssuLastOpType = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 1, 2, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("none", 1), ("done", 2), ("test", 3), ("install", 4), ("rollback", 5))).clone('none')).setMaxAccess("readonly")
if mibBuilder.loadTexts: hpnicfIssuLastOpType.setStatus('current')
if mibBuilder.loadTexts: hpnicfIssuLastOpType.setDescription("This object indicates the previous hpnicfIssuOp value. It will be updated after a new hpnicfIssuOp is set and delivered to the upgrade process. Command Remarks none If the user sets this object to 'none', agent will return a success without performing an upgrade operation. done If this object returns any value other than 'none', setting this to 'done' will do the required cleanup of the previous upgrade operation and get the system ready for a new upgrade operation. test Check the version compatibility and upgrade method for the given set of image files. install For all the image entities listed in the hpnicfIssuUpgradeImageTable, perform the required upgrade operation listed in that table. rollback Abort the current install operation and roll back to the previous version. ")
hpnicfIssuLastOpStatus = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 1, 2, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("none", 1), ("failure", 2), ("inProgress", 3), ("success", 4), ("rollbackInProgress", 5), ("rollbackSuccess", 6))).clone('none')).setMaxAccess("readonly")
if mibBuilder.loadTexts: hpnicfIssuLastOpStatus.setStatus('current')
if mibBuilder.loadTexts: hpnicfIssuLastOpStatus.setDescription('This object indicates previous hpnicfIssuOpStatus value. It will be updated after new hpnicfIssuOp is set and delivered to upgrade process. none - No operation was performed. failure - Specified operation has failed. inProgress - Specified operation is active. success - Specified operation completed successfully. rollbackInProgress - Rollback operation is in progress. rollbackSuccess - Rollback operation completed successfully. ')
hpnicfIssuLastOpFailedReason = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 1, 2, 9), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hpnicfIssuLastOpFailedReason.setStatus('current')
if mibBuilder.loadTexts: hpnicfIssuLastOpFailedReason.setDescription("Indicates the cause of 'failure' state of the object 'hpnicfIssuOpStatus'. This object would be a null string if the value of 'hpnicfIssuOpStatus' is not 'failure'. The value will be updated when new hpnicfIssuOp is set and delivered to the upgrade process.")
hpnicfIssuLastOpTimeCompleted = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 1, 2, 10), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hpnicfIssuLastOpTimeCompleted.setStatus('current')
if mibBuilder.loadTexts: hpnicfIssuLastOpTimeCompleted.setDescription('Indicates the previous hpnicfIssuOpTimeCompleted value. The value will be updated when new hpnicfIssuOp is set and delivered to the upgrade process.')
hpnicfIssuUpgradeResultGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 2))
hpnicfIssuCompatibleResult = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 2, 1))
hpnicfIssuCompatibleResultStatus = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 2, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("none", 1), ("inCompatible", 2), ("compatible", 3), ("failure", 4))).clone('none')).setMaxAccess("readonly")
if mibBuilder.loadTexts: hpnicfIssuCompatibleResultStatus.setStatus('current')
if mibBuilder.loadTexts: hpnicfIssuCompatibleResultStatus.setDescription('Specifies whether the images provided in hpnicfIssuUpgradeImageTable are compatible with each other as far as this module is concerned. none - No operation was performed. inCompatible - The images provided are compatible and can be run on this module. compatible - The images provided are incompatible and can be run on this module. failure - Failed to get the compatibility. ')
hpnicfIssuCompatibleResultFailedReason = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 2, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hpnicfIssuCompatibleResultFailedReason.setStatus('current')
if mibBuilder.loadTexts: hpnicfIssuCompatibleResultFailedReason.setDescription("Indicates the cause of 'failure' state of the object 'hpnicfIssuCompatibleResultStatus'. This object would be a null string if the value of 'hpnicfIssuCompatibleResultStatus' is not 'failure'.")
hpnicfIssuTestResultTable = MibTable((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 2, 2), )
if mibBuilder.loadTexts: hpnicfIssuTestResultTable.setStatus('current')
if mibBuilder.loadTexts: hpnicfIssuTestResultTable.setDescription('Shows the result of the test operation, from which you can see the upgrade method.')
hpnicfIssuTestResultEntry = MibTableRow((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 2, 2, 1), ).setIndexNames((0, "HPN-ICF-ISSU-MIB", "hpnicfIssuTestResultIndex"))
if mibBuilder.loadTexts: hpnicfIssuTestResultEntry.setStatus('current')
if mibBuilder.loadTexts: hpnicfIssuTestResultEntry.setDescription('An hpnicfIssuTestResultEntry entry. Each entry provides the test result of a card in the device.')
hpnicfIssuTestResultIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 2, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)))
if mibBuilder.loadTexts: hpnicfIssuTestResultIndex.setStatus('current')
if mibBuilder.loadTexts: hpnicfIssuTestResultIndex.setDescription('Internal index, not accessible.')
hpnicfIssuTestDeviceChassisID = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 2, 2, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hpnicfIssuTestDeviceChassisID.setStatus('current')
if mibBuilder.loadTexts: hpnicfIssuTestDeviceChassisID.setDescription('Chassis ID of the card.')
hpnicfIssuTestDeviceSlotID = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 2, 2, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hpnicfIssuTestDeviceSlotID.setStatus('current')
if mibBuilder.loadTexts: hpnicfIssuTestDeviceSlotID.setDescription('Slot ID of the card.')
hpnicfIssuTestDeviceCpuID = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 2, 2, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 7))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hpnicfIssuTestDeviceCpuID.setStatus('current')
if mibBuilder.loadTexts: hpnicfIssuTestDeviceCpuID.setDescription('CPU ID of the card.')
hpnicfIssuTestDeviceUpgradeWay = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 2, 2, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7))).clone(namedValues=NamedValues(("none", 1), ("reboot", 2), ("sequenceReboot", 3), ("issuReboot", 4), ("serviceUpgrade", 5), ("fileUpgrade", 6), ("incompatibleUpgrade", 7))).clone('none')).setMaxAccess("readonly")
if mibBuilder.loadTexts: hpnicfIssuTestDeviceUpgradeWay.setStatus('current')
if mibBuilder.loadTexts: hpnicfIssuTestDeviceUpgradeWay.setDescription('Upgrade method of the device. none - No operation was performed. reboot - The upgrade method of this device is Reboot. sequenceReboot - The upgrade method of this device is SequenceReboot. issuReboot - The upgrade method of this device is IssuReboot. serviceUpgrade - The upgrade method of this device is ServiceReboot. fileUpgrade - The upgrade method of this device is FileReboot. incompatibleUpgrade - The upgrade method of this device is IncompatibleUpgrade. ')
hpnicfIssuUpgradeResultTable = MibTable((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 2, 3), )
if mibBuilder.loadTexts: hpnicfIssuUpgradeResultTable.setStatus('current')
if mibBuilder.loadTexts: hpnicfIssuUpgradeResultTable.setDescription('Shows the result of the install operation.')
hpnicfIssuUpgradeResultEntry = MibTableRow((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 2, 3, 1), ).setIndexNames((0, "HPN-ICF-ISSU-MIB", "hpnicfIssuUpgradeResultIndex"))
if mibBuilder.loadTexts: hpnicfIssuUpgradeResultEntry.setStatus('current')
if mibBuilder.loadTexts: hpnicfIssuUpgradeResultEntry.setDescription('An hpnicfIssuUpgradeResultEntry entry. Each entry provides the upgrade result of a card in the device.')
hpnicfIssuUpgradeResultIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 2, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)))
if mibBuilder.loadTexts: hpnicfIssuUpgradeResultIndex.setStatus('current')
if mibBuilder.loadTexts: hpnicfIssuUpgradeResultIndex.setDescription('Internal Index, not accessible.')
hpnicfIssuUpgradeDeviceChassisID = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 2, 3, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hpnicfIssuUpgradeDeviceChassisID.setStatus('current')
if mibBuilder.loadTexts: hpnicfIssuUpgradeDeviceChassisID.setDescription('Chassis ID of the card.')
hpnicfIssuUpgradeDeviceSlotID = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 2, 3, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hpnicfIssuUpgradeDeviceSlotID.setStatus('current')
if mibBuilder.loadTexts: hpnicfIssuUpgradeDeviceSlotID.setDescription('Slot ID of the card.')
hpnicfIssuUpgradeDeviceCpuID = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 2, 3, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 7))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hpnicfIssuUpgradeDeviceCpuID.setStatus('current')
if mibBuilder.loadTexts: hpnicfIssuUpgradeDeviceCpuID.setDescription('CPU ID of the card.')
hpnicfIssuUpgradeState = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 2, 3, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9))).clone(namedValues=NamedValues(("init", 1), ("loading", 2), ("loaded", 3), ("switching", 4), ("switchover", 5), ("committing", 6), ("committed", 7), ("rollbacking", 8), ("rollbacked", 9)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hpnicfIssuUpgradeState.setStatus('current')
if mibBuilder.loadTexts: hpnicfIssuUpgradeState.setDescription('Upgrade status of the device. init -The current status of the device is Init. loading -The current status of the device is Loading. loaded -The current status of the device is Loaded. switching -The current status of the device is Switching. switchover -The current status of the device is Switchover. committing -The current status of the device is Committing. committed -The current status of the device is Committed. rollbacking -The current status of the device is Rollbacking. rollbacked -The current status of the device is Rollbacked. ')
hpnicfIssuDeviceUpgradeWay = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 2, 3, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7))).clone(namedValues=NamedValues(("none", 1), ("reboot", 2), ("sequenceReboot", 3), ("issuReboot", 4), ("serviceUpgrade", 5), ("fileUpgrade", 6), ("incompatibleUpgrade", 7)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hpnicfIssuDeviceUpgradeWay.setStatus('current')
if mibBuilder.loadTexts: hpnicfIssuDeviceUpgradeWay.setDescription('Upgrade method of the card. none - No operation was performed. reboot - The upgrade method of this device is Reboot. sequenceReboot - The upgrade method of this device is SequenceReboot. issuReboot - The upgrade method of this device is IssuReboot. serviceUpgrade - The upgrade method of this device is ServiceReboot. fileUpgrade - The upgrade method of this device is FileReboot. incompatibleUpgrade - The upgrade method of this device is IncompatibleUpgrade. ')
hpnicfIssuUpgradeDeviceStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 2, 3, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("waitingUpgrade", 1), ("inProcess", 2), ("success", 3), ("failure", 4)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hpnicfIssuUpgradeDeviceStatus.setStatus('current')
if mibBuilder.loadTexts: hpnicfIssuUpgradeDeviceStatus.setDescription('Upgrade status of the device.')
hpnicfIssuUpgradeFailedReason = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 2, 3, 1, 8), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hpnicfIssuUpgradeFailedReason.setStatus('current')
if mibBuilder.loadTexts: hpnicfIssuUpgradeFailedReason.setDescription("Indicates the cause of 'failure' state of the object 'hpnicfIssuUpgradeDeviceStatus'. This object would be a null string if the value of 'hpnicfIssuCompatibleResultStatus' is not 'failure'.")
hpnicfIssuUpgradeNotify = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 2))
hpnicfIssuUpgradeTrapPrefix = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 2, 0))
hpnicfIssuUpgradeOpCompletionNotify = NotificationType((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 2, 0, 1)).setObjects(("HPN-ICF-ISSU-MIB", "hpnicfIssuOpType"), ("HPN-ICF-ISSU-MIB", "hpnicfIssuOpStatus"), ("HPN-ICF-ISSU-MIB", "hpnicfIssuFailedReason"), ("HPN-ICF-ISSU-MIB", "hpnicfIssuOpTimeCompleted"))
if mibBuilder.loadTexts: hpnicfIssuUpgradeOpCompletionNotify.setStatus('current')
if mibBuilder.loadTexts: hpnicfIssuUpgradeOpCompletionNotify.setDescription('An hpnicfIssuUpgradeOpCompletionNotify is sent at the completion of upgrade operation denoted by hpnicfIssuOp object, if such a notification was requested when the operation was initiated. hpnicfIssuOpType indicates the type of the operation. hpnicfIssuOpStatus indicates the result of the operation. hpnicfIssuFailedReason indicates the operation failure reason. hpnicfIssuOpTimeCompleted indicates the time when the operation was completed.')
mibBuilder.exportSymbols("HPN-ICF-ISSU-MIB", hpnicfIssuUpgradeImageRowStatus=hpnicfIssuUpgradeImageRowStatus, hpnicfIssuImageFileOverwrite=hpnicfIssuImageFileOverwrite, hpnicfIssuOpTrapEnable=hpnicfIssuOpTrapEnable, hpnicfIssuUpgradeFailedReason=hpnicfIssuUpgradeFailedReason, hpnicfIssuUpgradeImageType=hpnicfIssuUpgradeImageType, hpnicfIssuUpgradeImageTable=hpnicfIssuUpgradeImageTable, hpnicfIssuOpStatus=hpnicfIssuOpStatus, hpnicfIssuTestResultTable=hpnicfIssuTestResultTable, hpnicfIssuUpgradeDeviceStatus=hpnicfIssuUpgradeDeviceStatus, hpnicfIssuCompatibleResultFailedReason=hpnicfIssuCompatibleResultFailedReason, hpnicfIssuUpgradeImageEntry=hpnicfIssuUpgradeImageEntry, hpnicfIssuCompatibleResult=hpnicfIssuCompatibleResult, hpnicfIssuUpgradeImageURL=hpnicfIssuUpgradeImageURL, hpnicfIssuOpType=hpnicfIssuOpType, hpnicfIssuUpgradeMibObjects=hpnicfIssuUpgradeMibObjects, hpnicfIssuOp=hpnicfIssuOp, hpnicfIssuUpgradeDeviceChassisID=hpnicfIssuUpgradeDeviceChassisID, hpnicfIssuUpgradeResultEntry=hpnicfIssuUpgradeResultEntry, hpnicfIssuUpgradeNotify=hpnicfIssuUpgradeNotify, hpnicfIssuLastOpType=hpnicfIssuLastOpType, hpnicfIssuTestDeviceUpgradeWay=hpnicfIssuTestDeviceUpgradeWay, hpnicfIssuUpgradeImageIndex=hpnicfIssuUpgradeImageIndex, hpnicfIssuUpgradeOpCompletionNotify=hpnicfIssuUpgradeOpCompletionNotify, hpnicfIssuUpgradeResultGroup=hpnicfIssuUpgradeResultGroup, hpnicfIssuUpgradeDeviceSlotID=hpnicfIssuUpgradeDeviceSlotID, hpnicfIssuOpTimeCompleted=hpnicfIssuOpTimeCompleted, hpnicfIssuLastOpTimeCompleted=hpnicfIssuLastOpTimeCompleted, hpnicfIssuUpgradeTrapPrefix=hpnicfIssuUpgradeTrapPrefix, hpnicfIssuTestDeviceChassisID=hpnicfIssuTestDeviceChassisID, hpnicfIssuDeviceUpgradeWay=hpnicfIssuDeviceUpgradeWay, hpnicfIssuUpgrade=hpnicfIssuUpgrade, PYSNMP_MODULE_ID=hpnicfIssuUpgrade, hpnicfIssuTestResultIndex=hpnicfIssuTestResultIndex, hpnicfIssuUpgradeDeviceCpuID=hpnicfIssuUpgradeDeviceCpuID, hpnicfIssuUpgradeState=hpnicfIssuUpgradeState, hpnicfIssuLastOpFailedReason=hpnicfIssuLastOpFailedReason, hpnicfIssuLastOpStatus=hpnicfIssuLastOpStatus, hpnicfIssuTestDeviceSlotID=hpnicfIssuTestDeviceSlotID, hpnicfIssuTestDeviceCpuID=hpnicfIssuTestDeviceCpuID, hpnicfIssuCompatibleResultStatus=hpnicfIssuCompatibleResultStatus, hpnicfIssuUpgradeGroup=hpnicfIssuUpgradeGroup, hpnicfIssuFailedReason=hpnicfIssuFailedReason, hpnicfIssuUpgradeResultTable=hpnicfIssuUpgradeResultTable, hpnicfIssuUpgradeResultIndex=hpnicfIssuUpgradeResultIndex, hpnicfIssuTestResultEntry=hpnicfIssuTestResultEntry)
|
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, value_size_constraint, single_value_constraint, constraints_intersection, constraints_union) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'ValueSizeConstraint', 'SingleValueConstraint', 'ConstraintsIntersection', 'ConstraintsUnion')
(hpnicf_common,) = mibBuilder.importSymbols('HPN-ICF-OID-MIB', 'hpnicfCommon')
(notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance')
(gauge32, bits, counter32, mib_scalar, mib_table, mib_table_row, mib_table_column, object_identity, ip_address, time_ticks, mib_identifier, iso, counter64, notification_type, module_identity, integer32, unsigned32) = mibBuilder.importSymbols('SNMPv2-SMI', 'Gauge32', 'Bits', 'Counter32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'ObjectIdentity', 'IpAddress', 'TimeTicks', 'MibIdentifier', 'iso', 'Counter64', 'NotificationType', 'ModuleIdentity', 'Integer32', 'Unsigned32')
(textual_convention, row_status, truth_value, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'RowStatus', 'TruthValue', 'DisplayString')
hpnicf_issu_upgrade = module_identity((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133))
hpnicfIssuUpgrade.setRevisions(('2013-01-15 15:36',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts:
hpnicfIssuUpgrade.setRevisionsDescriptions(('Initial version of this MIB module. Added hpnicfIssuUpgradeImageTable hpnicfIssuOp hpnicfIssuCompatibleResult hpnicfIssuTestResultTable hpnicfIssuUpgradeResultTable',))
if mibBuilder.loadTexts:
hpnicfIssuUpgrade.setLastUpdated('201301151536Z')
if mibBuilder.loadTexts:
hpnicfIssuUpgrade.setOrganization('')
if mibBuilder.loadTexts:
hpnicfIssuUpgrade.setContactInfo('')
if mibBuilder.loadTexts:
hpnicfIssuUpgrade.setDescription("This MIB provides objects for upgrading images on modules in the system, objects for showing the result of an upgrade operation, and objects for showing the result of a test operation. To perform an upgrade operation, a management application must first read the hpnicfIssuUpgradeImageTable table and use the information in other tables, as explained below. You can configure a new image name for each image type as listed in hpnicfIssuUpgradeImageTable. The system will use this image on the particular module at the next reboot. The management application used to perform an upgrade operation must first check if an upgrade operation is already in progress in the system. This is done by reading the hpnicfIssuOpType ('none' indicates that no other upgrade operation is in progress. Any other value indicates that an upgrade is already in progress and a new upgrade operation is not allowed. To start an 'install' operation, the user must first perform a 'test' operation to examine the version compatibility between the given set of images and the running images. Only if the result of the 'test' operation is 'success' can the user proceed to do an install operation. The table hpnicfIssuTestResultTable provides the result of the 'test' operation performed by using hpnicfIssuOpType. The table hpnicfIssuUpgradeResultTable provides the result of the 'install' operation performed by using hpnicfIssuOpType. ")
hpnicf_issu_upgrade_mib_objects = mib_identifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1))
hpnicf_issu_upgrade_group = mib_identifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 1))
hpnicf_issu_upgrade_image_table = mib_table((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 1, 1))
if mibBuilder.loadTexts:
hpnicfIssuUpgradeImageTable.setStatus('current')
if mibBuilder.loadTexts:
hpnicfIssuUpgradeImageTable.setDescription('A table listing the image variable types that exist in the device.')
hpnicf_issu_upgrade_image_entry = mib_table_row((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 1, 1, 1)).setIndexNames((0, 'HPN-ICF-ISSU-MIB', 'hpnicfIssuUpgradeImageIndex'))
if mibBuilder.loadTexts:
hpnicfIssuUpgradeImageEntry.setStatus('current')
if mibBuilder.loadTexts:
hpnicfIssuUpgradeImageEntry.setDescription('An hpnicfIssuUpgradeImageEntry entry. Each entry provides an image variable type that exists in the device.')
hpnicf_issu_upgrade_image_index = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 1, 1, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 2147483647)))
if mibBuilder.loadTexts:
hpnicfIssuUpgradeImageIndex.setStatus('current')
if mibBuilder.loadTexts:
hpnicfIssuUpgradeImageIndex.setDescription('Index of each image.')
hpnicf_issu_upgrade_image_type = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 1, 1, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4))).clone(namedValues=named_values(('boot', 1), ('system', 2), ('feature', 3), ('ipe', 4)))).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
hpnicfIssuUpgradeImageType.setStatus('current')
if mibBuilder.loadTexts:
hpnicfIssuUpgradeImageType.setDescription("Types of images that the system can run. The value of this object has four image variables names - 'boot', 'system', 'feature' and 'ipe'. This table will then list these four strings as follows: hpnicfIssuUpgradeImageType boot system feature IPE The user can assign images (using hpnicfIssuUpgradeImageURL) to these variables and the system will use the assigned images to boot.")
hpnicf_issu_upgrade_image_url = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 1, 1, 1, 3), display_string().subtype(subtypeSpec=value_size_constraint(1, 127))).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
hpnicfIssuUpgradeImageURL.setStatus('current')
if mibBuilder.loadTexts:
hpnicfIssuUpgradeImageURL.setDescription('This object contains the path of the image of this entity.')
hpnicf_issu_upgrade_image_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 1, 1, 1, 4), row_status()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
hpnicfIssuUpgradeImageRowStatus.setStatus('current')
if mibBuilder.loadTexts:
hpnicfIssuUpgradeImageRowStatus.setDescription('Row-status of image table.')
hpnicf_issu_op = mib_identifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 1, 2))
hpnicf_issu_op_type = mib_scalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 1, 2, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5))).clone(namedValues=named_values(('none', 1), ('done', 2), ('test', 3), ('install', 4), ('rollback', 5))).clone('none')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
hpnicfIssuOpType.setStatus('current')
if mibBuilder.loadTexts:
hpnicfIssuOpType.setDescription("Command to be executed. The 'test' command must be performed before the 'install' command can be executed. The 'install' command is allowed only if a read of this object returns 'test' and the value of object hpnicfIssuOpStatus is 'success'. Command Remarks none If the user sets this object to 'none', the agent will return a success without performing an upgrade operation. done If this object returns any value other than 'none', setting this to 'done' will do the required cleanup of the previous upgrade operation and get the system ready for a new upgrade operation. test Check the version compatibility and upgrade method for the given set of image files. install For all the image entities listed in the hpnicfIssuUpgradeImageTable, perform the required upgrade operation listed in that table. rollback Abort the current 'install' operation and roll back to the previous version. ")
hpnicf_issu_image_file_overwrite = mib_scalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 1, 2, 2), truth_value().clone('true')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
hpnicfIssuImageFileOverwrite.setStatus('current')
if mibBuilder.loadTexts:
hpnicfIssuImageFileOverwrite.setDescription('If you want to overwrite the existing file, set the value of this object to enable. Otherwise, set the value of this object to disable.')
hpnicf_issu_op_trap_enable = mib_scalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 1, 2, 3), truth_value().clone('true')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
hpnicfIssuOpTrapEnable.setStatus('current')
if mibBuilder.loadTexts:
hpnicfIssuOpTrapEnable.setDescription('If you want to enable the trap, set the value of this object to enable. Otherwise, set the value of this object to disable.')
hpnicf_issu_op_status = mib_scalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 1, 2, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6))).clone(namedValues=named_values(('none', 1), ('failure', 2), ('inProgress', 3), ('success', 4), ('rollbackInProgress', 5), ('rollbackSuccess', 6))).clone('none')).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hpnicfIssuOpStatus.setStatus('current')
if mibBuilder.loadTexts:
hpnicfIssuOpStatus.setDescription('Status of the specified operation. none - No operation was performed. failure - Specified operation has failed. inProgress - Specified operation is in progress. success - Specified operation completed successfully. rollbackInProgress - Rollback operation is in progress. rollbackSuccess - Rollback operation completed successfully. ')
hpnicf_issu_failed_reason = mib_scalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 1, 2, 5), display_string().subtype(subtypeSpec=value_size_constraint(0, 255))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hpnicfIssuFailedReason.setStatus('current')
if mibBuilder.loadTexts:
hpnicfIssuFailedReason.setDescription("Indicates the the cause of 'failure' state of the object 'hpnicfIssuOpStatus'. This object would be a null string if the value of 'hpnicfIssuOpStatus' is not 'failure'.")
hpnicf_issu_op_time_completed = mib_scalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 1, 2, 6), display_string().subtype(subtypeSpec=value_size_constraint(0, 255))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hpnicfIssuOpTimeCompleted.setStatus('current')
if mibBuilder.loadTexts:
hpnicfIssuOpTimeCompleted.setDescription("Indicates the time when the upgrade operation was completed. This object would be a null string if hpnicfIssuOpType is 'none'. ")
hpnicf_issu_last_op_type = mib_scalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 1, 2, 7), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5))).clone(namedValues=named_values(('none', 1), ('done', 2), ('test', 3), ('install', 4), ('rollback', 5))).clone('none')).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hpnicfIssuLastOpType.setStatus('current')
if mibBuilder.loadTexts:
hpnicfIssuLastOpType.setDescription("This object indicates the previous hpnicfIssuOp value. It will be updated after a new hpnicfIssuOp is set and delivered to the upgrade process. Command Remarks none If the user sets this object to 'none', agent will return a success without performing an upgrade operation. done If this object returns any value other than 'none', setting this to 'done' will do the required cleanup of the previous upgrade operation and get the system ready for a new upgrade operation. test Check the version compatibility and upgrade method for the given set of image files. install For all the image entities listed in the hpnicfIssuUpgradeImageTable, perform the required upgrade operation listed in that table. rollback Abort the current install operation and roll back to the previous version. ")
hpnicf_issu_last_op_status = mib_scalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 1, 2, 8), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6))).clone(namedValues=named_values(('none', 1), ('failure', 2), ('inProgress', 3), ('success', 4), ('rollbackInProgress', 5), ('rollbackSuccess', 6))).clone('none')).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hpnicfIssuLastOpStatus.setStatus('current')
if mibBuilder.loadTexts:
hpnicfIssuLastOpStatus.setDescription('This object indicates previous hpnicfIssuOpStatus value. It will be updated after new hpnicfIssuOp is set and delivered to upgrade process. none - No operation was performed. failure - Specified operation has failed. inProgress - Specified operation is active. success - Specified operation completed successfully. rollbackInProgress - Rollback operation is in progress. rollbackSuccess - Rollback operation completed successfully. ')
hpnicf_issu_last_op_failed_reason = mib_scalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 1, 2, 9), display_string().subtype(subtypeSpec=value_size_constraint(0, 255))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hpnicfIssuLastOpFailedReason.setStatus('current')
if mibBuilder.loadTexts:
hpnicfIssuLastOpFailedReason.setDescription("Indicates the cause of 'failure' state of the object 'hpnicfIssuOpStatus'. This object would be a null string if the value of 'hpnicfIssuOpStatus' is not 'failure'. The value will be updated when new hpnicfIssuOp is set and delivered to the upgrade process.")
hpnicf_issu_last_op_time_completed = mib_scalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 1, 2, 10), display_string().subtype(subtypeSpec=value_size_constraint(0, 255))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hpnicfIssuLastOpTimeCompleted.setStatus('current')
if mibBuilder.loadTexts:
hpnicfIssuLastOpTimeCompleted.setDescription('Indicates the previous hpnicfIssuOpTimeCompleted value. The value will be updated when new hpnicfIssuOp is set and delivered to the upgrade process.')
hpnicf_issu_upgrade_result_group = mib_identifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 2))
hpnicf_issu_compatible_result = mib_identifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 2, 1))
hpnicf_issu_compatible_result_status = mib_scalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 2, 1, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4))).clone(namedValues=named_values(('none', 1), ('inCompatible', 2), ('compatible', 3), ('failure', 4))).clone('none')).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hpnicfIssuCompatibleResultStatus.setStatus('current')
if mibBuilder.loadTexts:
hpnicfIssuCompatibleResultStatus.setDescription('Specifies whether the images provided in hpnicfIssuUpgradeImageTable are compatible with each other as far as this module is concerned. none - No operation was performed. inCompatible - The images provided are compatible and can be run on this module. compatible - The images provided are incompatible and can be run on this module. failure - Failed to get the compatibility. ')
hpnicf_issu_compatible_result_failed_reason = mib_scalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 2, 1, 2), display_string().subtype(subtypeSpec=value_size_constraint(0, 255))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hpnicfIssuCompatibleResultFailedReason.setStatus('current')
if mibBuilder.loadTexts:
hpnicfIssuCompatibleResultFailedReason.setDescription("Indicates the cause of 'failure' state of the object 'hpnicfIssuCompatibleResultStatus'. This object would be a null string if the value of 'hpnicfIssuCompatibleResultStatus' is not 'failure'.")
hpnicf_issu_test_result_table = mib_table((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 2, 2))
if mibBuilder.loadTexts:
hpnicfIssuTestResultTable.setStatus('current')
if mibBuilder.loadTexts:
hpnicfIssuTestResultTable.setDescription('Shows the result of the test operation, from which you can see the upgrade method.')
hpnicf_issu_test_result_entry = mib_table_row((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 2, 2, 1)).setIndexNames((0, 'HPN-ICF-ISSU-MIB', 'hpnicfIssuTestResultIndex'))
if mibBuilder.loadTexts:
hpnicfIssuTestResultEntry.setStatus('current')
if mibBuilder.loadTexts:
hpnicfIssuTestResultEntry.setDescription('An hpnicfIssuTestResultEntry entry. Each entry provides the test result of a card in the device.')
hpnicf_issu_test_result_index = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 2, 2, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 65535)))
if mibBuilder.loadTexts:
hpnicfIssuTestResultIndex.setStatus('current')
if mibBuilder.loadTexts:
hpnicfIssuTestResultIndex.setDescription('Internal index, not accessible.')
hpnicf_issu_test_device_chassis_id = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 2, 2, 1, 2), integer32().subtype(subtypeSpec=value_range_constraint(0, 255))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hpnicfIssuTestDeviceChassisID.setStatus('current')
if mibBuilder.loadTexts:
hpnicfIssuTestDeviceChassisID.setDescription('Chassis ID of the card.')
hpnicf_issu_test_device_slot_id = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 2, 2, 1, 3), integer32().subtype(subtypeSpec=value_range_constraint(0, 255))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hpnicfIssuTestDeviceSlotID.setStatus('current')
if mibBuilder.loadTexts:
hpnicfIssuTestDeviceSlotID.setDescription('Slot ID of the card.')
hpnicf_issu_test_device_cpu_id = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 2, 2, 1, 4), integer32().subtype(subtypeSpec=value_range_constraint(0, 7))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hpnicfIssuTestDeviceCpuID.setStatus('current')
if mibBuilder.loadTexts:
hpnicfIssuTestDeviceCpuID.setDescription('CPU ID of the card.')
hpnicf_issu_test_device_upgrade_way = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 2, 2, 1, 5), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6, 7))).clone(namedValues=named_values(('none', 1), ('reboot', 2), ('sequenceReboot', 3), ('issuReboot', 4), ('serviceUpgrade', 5), ('fileUpgrade', 6), ('incompatibleUpgrade', 7))).clone('none')).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hpnicfIssuTestDeviceUpgradeWay.setStatus('current')
if mibBuilder.loadTexts:
hpnicfIssuTestDeviceUpgradeWay.setDescription('Upgrade method of the device. none - No operation was performed. reboot - The upgrade method of this device is Reboot. sequenceReboot - The upgrade method of this device is SequenceReboot. issuReboot - The upgrade method of this device is IssuReboot. serviceUpgrade - The upgrade method of this device is ServiceReboot. fileUpgrade - The upgrade method of this device is FileReboot. incompatibleUpgrade - The upgrade method of this device is IncompatibleUpgrade. ')
hpnicf_issu_upgrade_result_table = mib_table((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 2, 3))
if mibBuilder.loadTexts:
hpnicfIssuUpgradeResultTable.setStatus('current')
if mibBuilder.loadTexts:
hpnicfIssuUpgradeResultTable.setDescription('Shows the result of the install operation.')
hpnicf_issu_upgrade_result_entry = mib_table_row((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 2, 3, 1)).setIndexNames((0, 'HPN-ICF-ISSU-MIB', 'hpnicfIssuUpgradeResultIndex'))
if mibBuilder.loadTexts:
hpnicfIssuUpgradeResultEntry.setStatus('current')
if mibBuilder.loadTexts:
hpnicfIssuUpgradeResultEntry.setDescription('An hpnicfIssuUpgradeResultEntry entry. Each entry provides the upgrade result of a card in the device.')
hpnicf_issu_upgrade_result_index = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 2, 3, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 65535)))
if mibBuilder.loadTexts:
hpnicfIssuUpgradeResultIndex.setStatus('current')
if mibBuilder.loadTexts:
hpnicfIssuUpgradeResultIndex.setDescription('Internal Index, not accessible.')
hpnicf_issu_upgrade_device_chassis_id = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 2, 3, 1, 2), integer32().subtype(subtypeSpec=value_range_constraint(0, 255))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hpnicfIssuUpgradeDeviceChassisID.setStatus('current')
if mibBuilder.loadTexts:
hpnicfIssuUpgradeDeviceChassisID.setDescription('Chassis ID of the card.')
hpnicf_issu_upgrade_device_slot_id = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 2, 3, 1, 3), integer32().subtype(subtypeSpec=value_range_constraint(0, 255))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hpnicfIssuUpgradeDeviceSlotID.setStatus('current')
if mibBuilder.loadTexts:
hpnicfIssuUpgradeDeviceSlotID.setDescription('Slot ID of the card.')
hpnicf_issu_upgrade_device_cpu_id = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 2, 3, 1, 4), integer32().subtype(subtypeSpec=value_range_constraint(0, 7))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hpnicfIssuUpgradeDeviceCpuID.setStatus('current')
if mibBuilder.loadTexts:
hpnicfIssuUpgradeDeviceCpuID.setDescription('CPU ID of the card.')
hpnicf_issu_upgrade_state = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 2, 3, 1, 5), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6, 7, 8, 9))).clone(namedValues=named_values(('init', 1), ('loading', 2), ('loaded', 3), ('switching', 4), ('switchover', 5), ('committing', 6), ('committed', 7), ('rollbacking', 8), ('rollbacked', 9)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hpnicfIssuUpgradeState.setStatus('current')
if mibBuilder.loadTexts:
hpnicfIssuUpgradeState.setDescription('Upgrade status of the device. init -The current status of the device is Init. loading -The current status of the device is Loading. loaded -The current status of the device is Loaded. switching -The current status of the device is Switching. switchover -The current status of the device is Switchover. committing -The current status of the device is Committing. committed -The current status of the device is Committed. rollbacking -The current status of the device is Rollbacking. rollbacked -The current status of the device is Rollbacked. ')
hpnicf_issu_device_upgrade_way = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 2, 3, 1, 6), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6, 7))).clone(namedValues=named_values(('none', 1), ('reboot', 2), ('sequenceReboot', 3), ('issuReboot', 4), ('serviceUpgrade', 5), ('fileUpgrade', 6), ('incompatibleUpgrade', 7)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hpnicfIssuDeviceUpgradeWay.setStatus('current')
if mibBuilder.loadTexts:
hpnicfIssuDeviceUpgradeWay.setDescription('Upgrade method of the card. none - No operation was performed. reboot - The upgrade method of this device is Reboot. sequenceReboot - The upgrade method of this device is SequenceReboot. issuReboot - The upgrade method of this device is IssuReboot. serviceUpgrade - The upgrade method of this device is ServiceReboot. fileUpgrade - The upgrade method of this device is FileReboot. incompatibleUpgrade - The upgrade method of this device is IncompatibleUpgrade. ')
hpnicf_issu_upgrade_device_status = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 2, 3, 1, 7), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4))).clone(namedValues=named_values(('waitingUpgrade', 1), ('inProcess', 2), ('success', 3), ('failure', 4)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hpnicfIssuUpgradeDeviceStatus.setStatus('current')
if mibBuilder.loadTexts:
hpnicfIssuUpgradeDeviceStatus.setDescription('Upgrade status of the device.')
hpnicf_issu_upgrade_failed_reason = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 1, 2, 3, 1, 8), display_string().subtype(subtypeSpec=value_size_constraint(0, 255))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hpnicfIssuUpgradeFailedReason.setStatus('current')
if mibBuilder.loadTexts:
hpnicfIssuUpgradeFailedReason.setDescription("Indicates the cause of 'failure' state of the object 'hpnicfIssuUpgradeDeviceStatus'. This object would be a null string if the value of 'hpnicfIssuCompatibleResultStatus' is not 'failure'.")
hpnicf_issu_upgrade_notify = mib_identifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 2))
hpnicf_issu_upgrade_trap_prefix = mib_identifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 2, 0))
hpnicf_issu_upgrade_op_completion_notify = notification_type((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 133, 2, 0, 1)).setObjects(('HPN-ICF-ISSU-MIB', 'hpnicfIssuOpType'), ('HPN-ICF-ISSU-MIB', 'hpnicfIssuOpStatus'), ('HPN-ICF-ISSU-MIB', 'hpnicfIssuFailedReason'), ('HPN-ICF-ISSU-MIB', 'hpnicfIssuOpTimeCompleted'))
if mibBuilder.loadTexts:
hpnicfIssuUpgradeOpCompletionNotify.setStatus('current')
if mibBuilder.loadTexts:
hpnicfIssuUpgradeOpCompletionNotify.setDescription('An hpnicfIssuUpgradeOpCompletionNotify is sent at the completion of upgrade operation denoted by hpnicfIssuOp object, if such a notification was requested when the operation was initiated. hpnicfIssuOpType indicates the type of the operation. hpnicfIssuOpStatus indicates the result of the operation. hpnicfIssuFailedReason indicates the operation failure reason. hpnicfIssuOpTimeCompleted indicates the time when the operation was completed.')
mibBuilder.exportSymbols('HPN-ICF-ISSU-MIB', hpnicfIssuUpgradeImageRowStatus=hpnicfIssuUpgradeImageRowStatus, hpnicfIssuImageFileOverwrite=hpnicfIssuImageFileOverwrite, hpnicfIssuOpTrapEnable=hpnicfIssuOpTrapEnable, hpnicfIssuUpgradeFailedReason=hpnicfIssuUpgradeFailedReason, hpnicfIssuUpgradeImageType=hpnicfIssuUpgradeImageType, hpnicfIssuUpgradeImageTable=hpnicfIssuUpgradeImageTable, hpnicfIssuOpStatus=hpnicfIssuOpStatus, hpnicfIssuTestResultTable=hpnicfIssuTestResultTable, hpnicfIssuUpgradeDeviceStatus=hpnicfIssuUpgradeDeviceStatus, hpnicfIssuCompatibleResultFailedReason=hpnicfIssuCompatibleResultFailedReason, hpnicfIssuUpgradeImageEntry=hpnicfIssuUpgradeImageEntry, hpnicfIssuCompatibleResult=hpnicfIssuCompatibleResult, hpnicfIssuUpgradeImageURL=hpnicfIssuUpgradeImageURL, hpnicfIssuOpType=hpnicfIssuOpType, hpnicfIssuUpgradeMibObjects=hpnicfIssuUpgradeMibObjects, hpnicfIssuOp=hpnicfIssuOp, hpnicfIssuUpgradeDeviceChassisID=hpnicfIssuUpgradeDeviceChassisID, hpnicfIssuUpgradeResultEntry=hpnicfIssuUpgradeResultEntry, hpnicfIssuUpgradeNotify=hpnicfIssuUpgradeNotify, hpnicfIssuLastOpType=hpnicfIssuLastOpType, hpnicfIssuTestDeviceUpgradeWay=hpnicfIssuTestDeviceUpgradeWay, hpnicfIssuUpgradeImageIndex=hpnicfIssuUpgradeImageIndex, hpnicfIssuUpgradeOpCompletionNotify=hpnicfIssuUpgradeOpCompletionNotify, hpnicfIssuUpgradeResultGroup=hpnicfIssuUpgradeResultGroup, hpnicfIssuUpgradeDeviceSlotID=hpnicfIssuUpgradeDeviceSlotID, hpnicfIssuOpTimeCompleted=hpnicfIssuOpTimeCompleted, hpnicfIssuLastOpTimeCompleted=hpnicfIssuLastOpTimeCompleted, hpnicfIssuUpgradeTrapPrefix=hpnicfIssuUpgradeTrapPrefix, hpnicfIssuTestDeviceChassisID=hpnicfIssuTestDeviceChassisID, hpnicfIssuDeviceUpgradeWay=hpnicfIssuDeviceUpgradeWay, hpnicfIssuUpgrade=hpnicfIssuUpgrade, PYSNMP_MODULE_ID=hpnicfIssuUpgrade, hpnicfIssuTestResultIndex=hpnicfIssuTestResultIndex, hpnicfIssuUpgradeDeviceCpuID=hpnicfIssuUpgradeDeviceCpuID, hpnicfIssuUpgradeState=hpnicfIssuUpgradeState, hpnicfIssuLastOpFailedReason=hpnicfIssuLastOpFailedReason, hpnicfIssuLastOpStatus=hpnicfIssuLastOpStatus, hpnicfIssuTestDeviceSlotID=hpnicfIssuTestDeviceSlotID, hpnicfIssuTestDeviceCpuID=hpnicfIssuTestDeviceCpuID, hpnicfIssuCompatibleResultStatus=hpnicfIssuCompatibleResultStatus, hpnicfIssuUpgradeGroup=hpnicfIssuUpgradeGroup, hpnicfIssuFailedReason=hpnicfIssuFailedReason, hpnicfIssuUpgradeResultTable=hpnicfIssuUpgradeResultTable, hpnicfIssuUpgradeResultIndex=hpnicfIssuUpgradeResultIndex, hpnicfIssuTestResultEntry=hpnicfIssuTestResultEntry)
|
def factorial(n):
total = 1
for i in range(1, n+1):
total *= i
return total
if __name__ == '__main__':
f = factorial(10)
print(f)
|
def factorial(n):
total = 1
for i in range(1, n + 1):
total *= i
return total
if __name__ == '__main__':
f = factorial(10)
print(f)
|
# encoding=utf-8
class LazyDB(object):
def __init__(self):
self.exists = 5
def __getattr__(self, name):
value = 'Value for %s' %name
setattr(self,name,value)
return value
data = LazyDB()
print('Before',data.__dict__)
print('foo',data.foo)
print('After',data.__dict__)
class LogginglazyDB(LazyDB):
def __getattr__(self, name):
print('Called __getattr__(%s)' %name)
return super().__getattr__(name)
data = LogginglazyDB()
print('exists:',data.exists)
print('foo:',data.foo)
print('foo:',data.foo)
class ValidatingDB(object):
def __init__(self):
self.exists = 5
def __getattribute__(self, name):
print('Called__getattribute__(%s)'% name)
try:
return super().__getattribute__(name)
except AttributeError:
value = 'Value for %s' %name
setattr(self,name,value)
return value
data = ValidatingDB()
print('exists:',data.exists)
print('foo:',data.foo)
print('foo:',data.foo)
class MissingPropertyDB(object):
def __getattr__(self, item):
if item == "bad_name":
raise AttributeError('%s is missing' %item)
#
# data = MissingPropertyDB()
# data.bad_name
class SavingDB(object):
def __setattr__(self, key, value):
super().__setattr__(key,value)
class LoggingSavingDB(object):
def __setattr__(self, key, value):
print('called __setattr__(%s,%r)' %(key,value))
super().__setattr__(key,value)
data = LoggingSavingDB()
print('before',data.__dict__)
data.foo = 5
print('after',data.__dict__)
data.foo = 7
print('Finally',data.__dict__)
class BrokenDictionaryDB(object):
def __init__(self,data):
self._data = data
def __getattribute__(self, item):
print('called __getattibute__(%s)' %item)
return self._data[item]
|
class Lazydb(object):
def __init__(self):
self.exists = 5
def __getattr__(self, name):
value = 'Value for %s' % name
setattr(self, name, value)
return value
data = lazy_db()
print('Before', data.__dict__)
print('foo', data.foo)
print('After', data.__dict__)
class Logginglazydb(LazyDB):
def __getattr__(self, name):
print('Called __getattr__(%s)' % name)
return super().__getattr__(name)
data = logginglazy_db()
print('exists:', data.exists)
print('foo:', data.foo)
print('foo:', data.foo)
class Validatingdb(object):
def __init__(self):
self.exists = 5
def __getattribute__(self, name):
print('Called__getattribute__(%s)' % name)
try:
return super().__getattribute__(name)
except AttributeError:
value = 'Value for %s' % name
setattr(self, name, value)
return value
data = validating_db()
print('exists:', data.exists)
print('foo:', data.foo)
print('foo:', data.foo)
class Missingpropertydb(object):
def __getattr__(self, item):
if item == 'bad_name':
raise attribute_error('%s is missing' % item)
class Savingdb(object):
def __setattr__(self, key, value):
super().__setattr__(key, value)
class Loggingsavingdb(object):
def __setattr__(self, key, value):
print('called __setattr__(%s,%r)' % (key, value))
super().__setattr__(key, value)
data = logging_saving_db()
print('before', data.__dict__)
data.foo = 5
print('after', data.__dict__)
data.foo = 7
print('Finally', data.__dict__)
class Brokendictionarydb(object):
def __init__(self, data):
self._data = data
def __getattribute__(self, item):
print('called __getattibute__(%s)' % item)
return self._data[item]
|
"""
A sentence S is given, composed of words separated by spaces. Each word
consists of lowercase and uppercase letters only.
We would like to convert the sentence to "Goat Latin"
(a made-up language similar to Pig Latin.)
The rules of Goat Latin are as follows:
- If a word begins with a vowel (a, e, i, o, or u), append "ma" to the
end of the word.
For example, the word 'apple' becomes 'applema'.
- If a word begins with a consonant (i.e. not a vowel), remove the
first letter and append it to the end, then add "ma".
For example, the word "goat" becomes "oatgma".
- Add one letter 'a' to the end of each word per its word index in the
sentence, starting with 1.
For example, the first word gets "a" added to the end, the second
word gets "aa" added to the end and so on.
Return the final sentence representing the conversion from S to Goat
Latin.
Example:
Input: "I speak Goat Latin"
Output: "Imaa peaksmaaa oatGmaaaa atinLmaaaaa"
Example:
Input: "The quick brown fox jumped over the lazy dog"
Output: "heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa
hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa"
Notes:
- S contains only uppercase, lowercase and spaces. Exactly one space
between each word.
- 1 <= S.length <= 150.
"""
#Difficulty: Easy
#99 / 99 test cases passed.
#Runtime: 24 ms
#Memory Usage: 13.9 MB
#Runtime: 24 ms, faster than 94.44% of Python3 online submissions for Goat Latin.
#Memory Usage: 13.9 MB, less than 42.39% of Python3 online submissions for Goat Latin.
class Solution:
def toGoatLatin(self, S: str) -> str:
words = S.split(' ')
length = len(words)
vowels = ('a', 'e', 'i', 'o', 'u')
for i in range(length):
if words[i][0].lower() in vowels:
words[i] += 'ma'+ 'a' * (i + 1)
else:
words[i] = words[i][1:] + words[i][0] + 'ma'+ 'a' * (i + 1)
return ' '.join(words)
|
"""
A sentence S is given, composed of words separated by spaces. Each word
consists of lowercase and uppercase letters only.
We would like to convert the sentence to "Goat Latin"
(a made-up language similar to Pig Latin.)
The rules of Goat Latin are as follows:
- If a word begins with a vowel (a, e, i, o, or u), append "ma" to the
end of the word.
For example, the word 'apple' becomes 'applema'.
- If a word begins with a consonant (i.e. not a vowel), remove the
first letter and append it to the end, then add "ma".
For example, the word "goat" becomes "oatgma".
- Add one letter 'a' to the end of each word per its word index in the
sentence, starting with 1.
For example, the first word gets "a" added to the end, the second
word gets "aa" added to the end and so on.
Return the final sentence representing the conversion from S to Goat
Latin.
Example:
Input: "I speak Goat Latin"
Output: "Imaa peaksmaaa oatGmaaaa atinLmaaaaa"
Example:
Input: "The quick brown fox jumped over the lazy dog"
Output: "heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa
hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa"
Notes:
- S contains only uppercase, lowercase and spaces. Exactly one space
between each word.
- 1 <= S.length <= 150.
"""
class Solution:
def to_goat_latin(self, S: str) -> str:
words = S.split(' ')
length = len(words)
vowels = ('a', 'e', 'i', 'o', 'u')
for i in range(length):
if words[i][0].lower() in vowels:
words[i] += 'ma' + 'a' * (i + 1)
else:
words[i] = words[i][1:] + words[i][0] + 'ma' + 'a' * (i + 1)
return ' '.join(words)
|
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Copyright 2012 California Institute of Technology. ALL RIGHTS RESERVED.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# United States Government Sponsorship acknowledged. This software is subject to
# U.S. export control laws and regulations and has been classified as 'EAR99 NLR'
# (No [Export] License Required except when exporting to an embargoed country,
# end user, or in support of a prohibited end use). By downloading this software,
# the user agrees to comply with all applicable U.S. export laws and regulations.
# The user has the responsibility to obtain export licenses, or other export
# authority as may be required before exporting this software to any 'EAR99'
# embargoed foreign country or citizen of those countries.
#
# Author: Eric Belz
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""Some specialized arithmetic exceptions for
Vector and Affine Spaces.
"""
## \namespace geo::exceptions
## <a href="http://docs.python.org/2/library/exceptions.html">Exceptions</a>
## for Vector and Affines spaces.
## Base class for geometric errors
class GeometricException(ArithmeticError):
"""A base class- not to be raised"""
pass
## A reminder to treat geometric objects properly.
class NonCovariantOperation(GeometricException):
"""Raise when you do something that is silly[1], like adding
a Scalar to a Vector\.
[1]Silly: (adj.) syn: non-covariant"""
pass
## A reminder that Affine space are affine, and vector spaces are not.
class AffineSpaceError(GeometricException):
"""Raised when you forget the points in an affine space are
not vector in a vector space, and visa versa"""
pass
## A catch-all for overlaoded operations getting non-sense.
class UndefinedGeometricOperation(GeometricException):
"""This will raised if you get do an opeation that has been defined for
a Tensor/Affine/Coordinate argument, but you just have a non-sense
combinabtion, like vector**vector.
"""
pass
## This function should make a generic error message
def error_message(op, left, right):
"""message = error_message(op, left, right)
op is a method or a function
left is a geo object
right is probably a geo object.
message is what did not work
"""
return "%s(%s, %s)"%(op.__name__,
left.__class__.__name__,
right.__class__.__name__)
|
"""Some specialized arithmetic exceptions for
Vector and Affine Spaces.
"""
class Geometricexception(ArithmeticError):
"""A base class- not to be raised"""
pass
class Noncovariantoperation(GeometricException):
"""Raise when you do something that is silly[1], like adding
a Scalar to a Vector\\.
[1]Silly: (adj.) syn: non-covariant"""
pass
class Affinespaceerror(GeometricException):
"""Raised when you forget the points in an affine space are
not vector in a vector space, and visa versa"""
pass
class Undefinedgeometricoperation(GeometricException):
"""This will raised if you get do an opeation that has been defined for
a Tensor/Affine/Coordinate argument, but you just have a non-sense
combinabtion, like vector**vector.
"""
pass
def error_message(op, left, right):
"""message = error_message(op, left, right)
op is a method or a function
left is a geo object
right is probably a geo object.
message is what did not work
"""
return '%s(%s, %s)' % (op.__name__, left.__class__.__name__, right.__class__.__name__)
|
class Solution:
def singleNonDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
c=0
for num in nums:
c=c^num
return c
|
class Solution:
def single_non_duplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
c = 0
for num in nums:
c = c ^ num
return c
|
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 20 23:18:03 2019
@author: NOTEBOOK
"""
def main():
speed = int(input('What is the speed of the vehicle in mph? '))
hours = int(input('How many hours has it traveled? '))
print('Hour\t\tDistance traveled(Miles)')
print('-------------------------------------')
for num in range(hours):
distance = speed *(num + 1)
print (num + 1,'\t\t\t',distance)
main()
|
"""
Created on Fri Dec 20 23:18:03 2019
@author: NOTEBOOK
"""
def main():
speed = int(input('What is the speed of the vehicle in mph? '))
hours = int(input('How many hours has it traveled? '))
print('Hour\t\tDistance traveled(Miles)')
print('-------------------------------------')
for num in range(hours):
distance = speed * (num + 1)
print(num + 1, '\t\t\t', distance)
main()
|
class Params(object):
""" Params object """
def __init__(self):
self._params = set()
self._undefined_params = set()
@property
def params(self) -> set:
return self._params
@property
def defined_params(self) -> set:
return self._params ^ self._undefined_params
@property
def undefined_params(self) -> set:
return self._undefined_params
def add_param(self, name: str):
self._params.add(name)
def add_undefined_param(self, name: str):
self._undefined_params.add(name)
def to_dict(self):
""" Returns a dict of params """
resp = {}
for param in self._params:
resp[param] = getattr(self, param)
return resp
|
class Params(object):
""" Params object """
def __init__(self):
self._params = set()
self._undefined_params = set()
@property
def params(self) -> set:
return self._params
@property
def defined_params(self) -> set:
return self._params ^ self._undefined_params
@property
def undefined_params(self) -> set:
return self._undefined_params
def add_param(self, name: str):
self._params.add(name)
def add_undefined_param(self, name: str):
self._undefined_params.add(name)
def to_dict(self):
""" Returns a dict of params """
resp = {}
for param in self._params:
resp[param] = getattr(self, param)
return resp
|
winClass = window.get_active_class()
if winClass not in ("code.Code", "emacs.Emacs"):
# Regular window
keyboard.send_keys('<home>')
keyboard.send_keys('<shift>+<end>')
else:
# VS Code
keyboard.send_keys('<ctrl>+l')
|
win_class = window.get_active_class()
if winClass not in ('code.Code', 'emacs.Emacs'):
keyboard.send_keys('<home>')
keyboard.send_keys('<shift>+<end>')
else:
keyboard.send_keys('<ctrl>+l')
|
#! /usr/bin/env python
###############################################################################
# esp8266_MicroPy_main_boilerplate.py
#
# base main.py boilerplate code for MicroPython running on the esp8266
# Copy relevant parts and/or file with desired settings into main.py on the esp8266
#
# The main.py file will run immediately after boot.py
# As you might expect, the main part of your code should be here
#
# Created: 06/04/16
# - Joshua Vaughan
# - [email protected]
# - http://www.ucs.louisiana.edu/~jev9637
#
# Modified:
# *
#
###############################################################################
# just blink the LED every 1s to indicate we made it into the main.py file
while True:
time.sleep(1)
pin.value(not pin.value()) # Toggle the LED while trying to connect
time.sleep(1)
|
while True:
time.sleep(1)
pin.value(not pin.value())
time.sleep(1)
|
class Angel:
color = "white"
feature = "wings"
home = "Heaven"
class Demon:
color = "red"
feature = "horns"
home = "Hell"
my_angel = Angel()
print(my_angel.color)
print(my_angel.feature)
print(my_angel.home)
my_demon = Demon()
print(my_demon.color)
print(my_demon.feature)
print(my_demon.home)
|
class Angel:
color = 'white'
feature = 'wings'
home = 'Heaven'
class Demon:
color = 'red'
feature = 'horns'
home = 'Hell'
my_angel = angel()
print(my_angel.color)
print(my_angel.feature)
print(my_angel.home)
my_demon = demon()
print(my_demon.color)
print(my_demon.feature)
print(my_demon.home)
|
# uninhm
# https://codeforces.com/contest/1419/problem/A
# greedy
def hasmodulo(s, a):
for i in s:
if int(i) % 2 == a:
return True
return False
for _ in range(int(input())):
n = int(input())
s = input()
if n % 2 == 0:
if hasmodulo(s[1::2], 0):
print(2)
else:
print(1)
else:
if hasmodulo(s[0::2], 1):
print(1)
else:
print(2)
|
def hasmodulo(s, a):
for i in s:
if int(i) % 2 == a:
return True
return False
for _ in range(int(input())):
n = int(input())
s = input()
if n % 2 == 0:
if hasmodulo(s[1::2], 0):
print(2)
else:
print(1)
elif hasmodulo(s[0::2], 1):
print(1)
else:
print(2)
|
agent = dict(
type='TD3_BC',
batch_size=256,
gamma=0.95,
update_coeff=0.005,
policy_update_interval=2,
alpha=2.5,
)
log_level = 'INFO'
eval_cfg = dict(
type='Evaluation',
num=10,
num_procs=1,
use_hidden_state=False,
start_state=None,
save_traj=True,
save_video=True,
use_log=False,
)
train_mfrl_cfg = dict(
on_policy=False,
)
|
agent = dict(type='TD3_BC', batch_size=256, gamma=0.95, update_coeff=0.005, policy_update_interval=2, alpha=2.5)
log_level = 'INFO'
eval_cfg = dict(type='Evaluation', num=10, num_procs=1, use_hidden_state=False, start_state=None, save_traj=True, save_video=True, use_log=False)
train_mfrl_cfg = dict(on_policy=False)
|
# https://codeforces.com/contest/1270/problem/B
# https://codeforces.com/contest/1270/submission/68220722
# https://github.com/miloszlakomy/competitive/tree/master/codeforces/1270B
def solve(A):
for cand in range(len(A)-1):
if abs(A[cand] - A[cand+1]) >= 2:
return cand, cand+2
return None
t = int(input())
for _ in range(t):
_ = input() # n
A = [int(x) for x in input().split()]
ans = solve(A)
if ans is None:
print("NO")
else:
print("YES")
start, end = ans
print(start+1, end)
|
def solve(A):
for cand in range(len(A) - 1):
if abs(A[cand] - A[cand + 1]) >= 2:
return (cand, cand + 2)
return None
t = int(input())
for _ in range(t):
_ = input()
a = [int(x) for x in input().split()]
ans = solve(A)
if ans is None:
print('NO')
else:
print('YES')
(start, end) = ans
print(start + 1, end)
|
class CustomConstant(object):
"""
Simple class for custom constants such as NULL, NOT_FOUND, etc.
Each object is obviously unique, so it is simple to do an equality
check. Each object can be configured with string, int, float,
and boolean values, as well as attributes.
"""
def __init__(self, **config):
self.__strValue = config.get("strValue", None)
self.__intValue = config.get("intValue", None)
self.__floatValue = config.get("floatValue", None)
self.__boolValue = config.get("boolValue", None)
for configKey in config:
setattr(self, configKey, config[configKey])
def __int__(self):
if self.__intValue == None:
if self.__floatValue == None:
raise TypeError
return int(self.__floatValue)
return self.__intValue
def __float__(self):
if self.__floatValue == None:
if self.__intValue == None:
raise TypeError
return float(self.__intValue)
return self.__floatValue
def __bool__(self):
if self.__boolValue == None:
if self.__intValue == None:
if self.__floatValue == None:
raise TypeError
return bool(self.__floatValue)
return bool(self.__intValue)
return self.__boolValue
def __str__(self):
if self.__strValue == None:
sParts = []
if self.__intValue: sParts.append(str(self.__intValue))
if self.__floatValue: sParts.append(str(self.__floatValue))
if self.__boolValue: sParts.append(str(self.__boolValue))
return "/".join(sParts)
return self.__strValue
def __repr__(self):
return "Constant(%s)" % str(self)
|
class Customconstant(object):
"""
Simple class for custom constants such as NULL, NOT_FOUND, etc.
Each object is obviously unique, so it is simple to do an equality
check. Each object can be configured with string, int, float,
and boolean values, as well as attributes.
"""
def __init__(self, **config):
self.__strValue = config.get('strValue', None)
self.__intValue = config.get('intValue', None)
self.__floatValue = config.get('floatValue', None)
self.__boolValue = config.get('boolValue', None)
for config_key in config:
setattr(self, configKey, config[configKey])
def __int__(self):
if self.__intValue == None:
if self.__floatValue == None:
raise TypeError
return int(self.__floatValue)
return self.__intValue
def __float__(self):
if self.__floatValue == None:
if self.__intValue == None:
raise TypeError
return float(self.__intValue)
return self.__floatValue
def __bool__(self):
if self.__boolValue == None:
if self.__intValue == None:
if self.__floatValue == None:
raise TypeError
return bool(self.__floatValue)
return bool(self.__intValue)
return self.__boolValue
def __str__(self):
if self.__strValue == None:
s_parts = []
if self.__intValue:
sParts.append(str(self.__intValue))
if self.__floatValue:
sParts.append(str(self.__floatValue))
if self.__boolValue:
sParts.append(str(self.__boolValue))
return '/'.join(sParts)
return self.__strValue
def __repr__(self):
return 'Constant(%s)' % str(self)
|
def identity(x):
return x
def with_max_length(max_length):
return lambda x: x[:max_length] if x else x
def identity_or_none(x):
return None if not x else x
def tipo_de_pessoa(x):
return "J" if x == "PJ" else "F"
def cnpj(x, tipo_pessoa):
return x if tipo_pessoa == "PJ" else None
def cpf(x, tipo_pessoa):
return None if tipo_pessoa == "PJ" else x
def fn_tipo_de_produto(tipos_mapping, tipo_default):
return lambda x: tipos_mapping.get(x, tipo_default)
def constantly(x):
return lambda n: x
def _or(x, y):
return x or y
def strtimestamp_to_strdate(x):
return None if not x else x.split(" ")[0]
def seq_generator():
seq = [0]
def generator(x):
seq[0] += 1
return seq[0]
return generator
def find_and_get(items, attr, result_attr, convert_before_filter=lambda x: x):
def _find_and_get(value):
try:
x = convert_before_filter(value)
found = next(filter(lambda i: i.get(attr) == x, items))
return found.get(result_attr)
except StopIteration:
return None
return _find_and_get
|
def identity(x):
return x
def with_max_length(max_length):
return lambda x: x[:max_length] if x else x
def identity_or_none(x):
return None if not x else x
def tipo_de_pessoa(x):
return 'J' if x == 'PJ' else 'F'
def cnpj(x, tipo_pessoa):
return x if tipo_pessoa == 'PJ' else None
def cpf(x, tipo_pessoa):
return None if tipo_pessoa == 'PJ' else x
def fn_tipo_de_produto(tipos_mapping, tipo_default):
return lambda x: tipos_mapping.get(x, tipo_default)
def constantly(x):
return lambda n: x
def _or(x, y):
return x or y
def strtimestamp_to_strdate(x):
return None if not x else x.split(' ')[0]
def seq_generator():
seq = [0]
def generator(x):
seq[0] += 1
return seq[0]
return generator
def find_and_get(items, attr, result_attr, convert_before_filter=lambda x: x):
def _find_and_get(value):
try:
x = convert_before_filter(value)
found = next(filter(lambda i: i.get(attr) == x, items))
return found.get(result_attr)
except StopIteration:
return None
return _find_and_get
|
a = 1
b = 2
c = 3
tmp=a
a=b
b=tmp
tmp=c
c=b
b=tmp
|
a = 1
b = 2
c = 3
tmp = a
a = b
b = tmp
tmp = c
c = b
b = tmp
|
expected_output = {
"cdp": {
"index": {
1: {
"capability": "R S C",
"device_id": "Device_With_A_Particularly_Long_Name",
"hold_time": 134,
"local_interface": "GigabitEthernet1",
"platform": "N9K-9000v",
"port_id": "Ethernet0/0",
},
2: {
"capability": "S I",
"device_id": "another_device_with_a_long_name",
"hold_time": 141,
"local_interface": "TwentyFiveGigE1/0/3",
"platform": "WS-C3850-",
"port_id": "TenGigabitEthernet1/1/4",
},
}
}
}
|
expected_output = {'cdp': {'index': {1: {'capability': 'R S C', 'device_id': 'Device_With_A_Particularly_Long_Name', 'hold_time': 134, 'local_interface': 'GigabitEthernet1', 'platform': 'N9K-9000v', 'port_id': 'Ethernet0/0'}, 2: {'capability': 'S I', 'device_id': 'another_device_with_a_long_name', 'hold_time': 141, 'local_interface': 'TwentyFiveGigE1/0/3', 'platform': 'WS-C3850-', 'port_id': 'TenGigabitEthernet1/1/4'}}}}
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def oddEvenList(self, head: ListNode) -> ListNode:
if not head or not head.next: return head
odd = odd_head = head
even = even_head = head.next
while even and even.next:
odd.next = even.next
odd = odd.next
even.next = odd.next
even = even.next
odd.next = even_head
return odd_head
|
class Solution:
def odd_even_list(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
odd = odd_head = head
even = even_head = head.next
while even and even.next:
odd.next = even.next
odd = odd.next
even.next = odd.next
even = even.next
odd.next = even_head
return odd_head
|
class Solution:
def decodeString(self, s: str) -> str:
stack = []
stack.append([1, ""])
num = 0
for l in s:
if l.isdigit():
num = num * 10 + ord(l) - ord('0')
elif l == '[':
stack.append([num, ""])
num = 0
elif l == ']':
stack[-2][1] += stack[-1][0] * stack[-1][1]
stack.pop()
else:
stack[-1][1] += l
return stack[0][1]
|
class Solution:
def decode_string(self, s: str) -> str:
stack = []
stack.append([1, ''])
num = 0
for l in s:
if l.isdigit():
num = num * 10 + ord(l) - ord('0')
elif l == '[':
stack.append([num, ''])
num = 0
elif l == ']':
stack[-2][1] += stack[-1][0] * stack[-1][1]
stack.pop()
else:
stack[-1][1] += l
return stack[0][1]
|
# Time: O(n)
# Space: O(1)
class Solution(object):
def countGoodRectangles(self, rectangles):
"""
:type rectangles: List[List[int]]
:rtype: int
"""
result = mx = 0
for l, w in rectangles:
side = min(l, w)
if side > mx:
result, mx = 1, side
elif side == mx:
result += 1
return result
|
class Solution(object):
def count_good_rectangles(self, rectangles):
"""
:type rectangles: List[List[int]]
:rtype: int
"""
result = mx = 0
for (l, w) in rectangles:
side = min(l, w)
if side > mx:
(result, mx) = (1, side)
elif side == mx:
result += 1
return result
|
pizzas = ['Supreme', 'Stuffed Crust', 'Buffalo Chicken']
friendpizzas = pizzas[:]
pizzas.append("Eggs Benedict Pizza")
friendpizzas.append("Eggs Florentine Pizza")
print("My favorite pizzas are:")
print(pizzas)
print("My friend's favorite pizzas are:")
print(friendpizzas)
|
pizzas = ['Supreme', 'Stuffed Crust', 'Buffalo Chicken']
friendpizzas = pizzas[:]
pizzas.append('Eggs Benedict Pizza')
friendpizzas.append('Eggs Florentine Pizza')
print('My favorite pizzas are:')
print(pizzas)
print("My friend's favorite pizzas are:")
print(friendpizzas)
|
# In a 2D grid from (0, 0) to (N-1, N-1), every cell contains a 1, except those cells in the given list mines which are 0. What is the largest axis-aligned plus sign of 1s contained in the grid? Return the order of the plus sign. If there is none, return 0.
#
# An "axis-aligned plus sign of 1s of order k" has some center grid[x][y] = 1 along with 4 arms of length k-1 going up, down, left, and right, and made of 1s. This is demonstrated in the diagrams below. Note that there could be 0s or 1s beyond the arms of the plus sign, only the relevant area of the plus sign is checked for 1s.
#
# Examples of Axis-Aligned Plus Signs of Order k:
#
# Order 1:
# 000
# 010
# 000
#
# Order 2:
# 00000
# 00100
# 01110
# 00100
# 00000
#
# Order 3:
# 0000000
# 0001000
# 0001000
# 0111110
# 0001000
# 0001000
# 0000000
# Example 1:
#
# Input: N = 5, mines = [[4, 2]]
# Output: 2
# Explanation:
# 11111
# 11111
# 11111
# 11111
# 11011
# In the above grid, the largest plus sign can only be order 2. One of them is marked in bold.
# Example 2:
#
# Input: N = 2, mines = []
# Output: 1
# Explanation:
# There is no plus sign of order 2, but there is of order 1.
# Example 3:
#
# Input: N = 1, mines = [[0, 0]]
# Output: 0
# Explanation:
# There is no plus sign, so return 0.
# Note:
#
# N will be an integer in the range [1, 500].
# mines will have length at most 5000.
# mines[i] will be length 2 and consist of integers in the range [0, N-1].
# (Additionally, programs submitted in C, C++, or C# will be judged with a slightly smaller time limit.)
class Solution(object):
def orderOfLargestPlusSign(self, N, mines):
"""
:type N: int
:type mines: List[List[int]]
:rtype: int
"""
dp = [[1] * N for _ in range(N)]
for [x, y] in mines:
dp[x][y] = 0
|
class Solution(object):
def order_of_largest_plus_sign(self, N, mines):
"""
:type N: int
:type mines: List[List[int]]
:rtype: int
"""
dp = [[1] * N for _ in range(N)]
for [x, y] in mines:
dp[x][y] = 0
|
# EDA: Airplanes - Q3
def plot_airplane_type_over_europe(gdf, airplane="B17",
years=[1940, 1941 ,1942, 1943, 1944, 1945],
kdp=False, aoi=europe):
fig = plt.figure(figsize=(16,12))
for e, y in enumerate(years):
_gdf = gdf.loc[(gdf["year"]==y) & (gdf["Aircraft Series"]==airplane)].copy()
_gdf.Country.replace(np.nan, "unknown", inplace=True)
ax = fig.add_subplot(3,2,e+1)
ax.set_aspect('equal')
aoi.plot(ax=ax, facecolor='lightgray', edgecolor="white")
if _gdf.shape[0] > 2:
if kdp:
sns.kdeplot(_gdf['Target Longitude'], _gdf['Target Latitude'],
cmap="viridis", shade=True, shade_lowest=False, bw=0.25, ax=ax)
else:
_gdf.plot(ax=ax, marker='o', cmap='Set1', categorical=True,
column='Country', legend=True, markersize=5, alpha=1)
ax.set_title("Year: " + str(y), size=16)
plt.tight_layout()
plt.suptitle("Attacks of airplane {} for different years".format(airplane), size=22)
plt.subplots_adjust(top=0.92)
return fig, ax
# run
plot_airplane_type_over_europe(df_airpl, airplane="B17", kdp=False);
|
def plot_airplane_type_over_europe(gdf, airplane='B17', years=[1940, 1941, 1942, 1943, 1944, 1945], kdp=False, aoi=europe):
fig = plt.figure(figsize=(16, 12))
for (e, y) in enumerate(years):
_gdf = gdf.loc[(gdf['year'] == y) & (gdf['Aircraft Series'] == airplane)].copy()
_gdf.Country.replace(np.nan, 'unknown', inplace=True)
ax = fig.add_subplot(3, 2, e + 1)
ax.set_aspect('equal')
aoi.plot(ax=ax, facecolor='lightgray', edgecolor='white')
if _gdf.shape[0] > 2:
if kdp:
sns.kdeplot(_gdf['Target Longitude'], _gdf['Target Latitude'], cmap='viridis', shade=True, shade_lowest=False, bw=0.25, ax=ax)
else:
_gdf.plot(ax=ax, marker='o', cmap='Set1', categorical=True, column='Country', legend=True, markersize=5, alpha=1)
ax.set_title('Year: ' + str(y), size=16)
plt.tight_layout()
plt.suptitle('Attacks of airplane {} for different years'.format(airplane), size=22)
plt.subplots_adjust(top=0.92)
return (fig, ax)
plot_airplane_type_over_europe(df_airpl, airplane='B17', kdp=False)
|
class BaseRelationship:
def __init__(self, name, repository, model, paginated_menu=None):
self.name = name
self.repository = repository
self.model = model
self.paginated_menu = paginated_menu
class OneToManyRelationship(BaseRelationship):
def __init__(self, related_name, name, repository, model, paginated_menu=None):
super().__init__(name, repository, model, paginated_menu)
self.related_name = related_name
|
class Baserelationship:
def __init__(self, name, repository, model, paginated_menu=None):
self.name = name
self.repository = repository
self.model = model
self.paginated_menu = paginated_menu
class Onetomanyrelationship(BaseRelationship):
def __init__(self, related_name, name, repository, model, paginated_menu=None):
super().__init__(name, repository, model, paginated_menu)
self.related_name = related_name
|
#! /usr/bin/env python3
def next_permutation(seq):
k = len(seq) - 1
# Find the largest index k such that a[k] < a[k + 1].
while k >= 0:
if seq[k - 1] >= seq[k]:
k -= 1
else:
k -= 1
break
# No such index exists, the permutation is the last permutation.
if k == -1:
raise StopIteration("Reached final permutation.")
l = len(seq) - 1
# Find the largest index l greater than k such that a[k] < a[l].
while l >= k:
if seq[l] > seq[k]:
break
else:
l -= 1
# Swap the value of a[k] with that of a[l].
seq[l], seq[k] = seq[k], seq[l]
# Reverse the sequence from a[k + 1] up to and including the final element.
seq = seq[:k+1] + seq[k+1:][::-1]
return seq
if __name__ == "__main__":
sequence = [1, 2, 3]
while True:
print(sequence)
sequence = next_permutation(sequence)
|
def next_permutation(seq):
k = len(seq) - 1
while k >= 0:
if seq[k - 1] >= seq[k]:
k -= 1
else:
k -= 1
break
if k == -1:
raise stop_iteration('Reached final permutation.')
l = len(seq) - 1
while l >= k:
if seq[l] > seq[k]:
break
else:
l -= 1
(seq[l], seq[k]) = (seq[k], seq[l])
seq = seq[:k + 1] + seq[k + 1:][::-1]
return seq
if __name__ == '__main__':
sequence = [1, 2, 3]
while True:
print(sequence)
sequence = next_permutation(sequence)
|
#!/usr/bin/env python3
"""RZFeeser | Alta3 Research
nesting an if-statement inside of a for loop"""
farms = [{"name": "NE Farm", "agriculture": ["sheep", "cows", "pigs", "chickens", "llamas", "cats"]},
{"name": "W Farm", "agriculture": ["pigs", "chickens", "llamas"]},
{"name": "SE Farm", "agriculture": ["chickens", "carrots", "celery"]}]
for farm in farms:
print(f'{farm["name"]} has the following animals: ')
animals = farm["agriculture"]
for animal in animals:
print(animal)
print("\n")
print("\nOur loop had ended.")
|
"""RZFeeser | Alta3 Research
nesting an if-statement inside of a for loop"""
farms = [{'name': 'NE Farm', 'agriculture': ['sheep', 'cows', 'pigs', 'chickens', 'llamas', 'cats']}, {'name': 'W Farm', 'agriculture': ['pigs', 'chickens', 'llamas']}, {'name': 'SE Farm', 'agriculture': ['chickens', 'carrots', 'celery']}]
for farm in farms:
print(f"{farm['name']} has the following animals: ")
animals = farm['agriculture']
for animal in animals:
print(animal)
print('\n')
print('\nOur loop had ended.')
|
"""
Meijer, Erik - The Curse of the Excluded Middle
DOI:10.1145/2605176
CACM vol.57 no.06
"""
def less_than_30(n):
check = n < 30
print('%d < 30 : %s' % (n, check))
return check
def more_than_20(n):
check = n > 20
print('%d > 20 : %s' % (n, check))
return check
l = [1, 25, 40, 5, 23]
q0 = (n for n in l if less_than_30(n))
q1 = (n for n in q0 if more_than_20(n))
for n in q1:
print('-> %d' % n)
|
"""
Meijer, Erik - The Curse of the Excluded Middle
DOI:10.1145/2605176
CACM vol.57 no.06
"""
def less_than_30(n):
check = n < 30
print('%d < 30 : %s' % (n, check))
return check
def more_than_20(n):
check = n > 20
print('%d > 20 : %s' % (n, check))
return check
l = [1, 25, 40, 5, 23]
q0 = (n for n in l if less_than_30(n))
q1 = (n for n in q0 if more_than_20(n))
for n in q1:
print('-> %d' % n)
|
a=25
b=5
print("division is ",(a/b))
print("division success")
|
a = 25
b = 5
print('division is ', a / b)
print('division success')
|
name1 = "Atilla"
name2 = "atilla"
name3 = "ATILLA"
name4 = "AtiLLa"
## Common string functions
print("capitalize",name1.capitalize())
print("capitalize",name2.capitalize())
print("capitalize",name3.capitalize())
print("capitalize",name4.capitalize())
# ends with
if name1.endswith("x"):
print("name1 ends with x char")
else:
print("name1 does not end with x char")
if name1.endswith("a"):
print("name1 ends with a char")
else:
print("name1 does not end with a char")
|
name1 = 'Atilla'
name2 = 'atilla'
name3 = 'ATILLA'
name4 = 'AtiLLa'
print('capitalize', name1.capitalize())
print('capitalize', name2.capitalize())
print('capitalize', name3.capitalize())
print('capitalize', name4.capitalize())
if name1.endswith('x'):
print('name1 ends with x char')
else:
print('name1 does not end with x char')
if name1.endswith('a'):
print('name1 ends with a char')
else:
print('name1 does not end with a char')
|
# --==[ Settings ]==--
# General
mod = 'mod4'
terminal = 'st'
browser = 'firefox'
file_manager = 'thunar'
font = 'SauceCodePro Nerd Font Medium'
wallpaper = '~/wallpapers/wp1.png'
# Weather
location = {'Mexico': 'Mexico'}
city = 'Mexico City, MX'
# Hardware [/sys/class]
net = 'wlp2s0'
backlight = 'radeon_bl0'
# Color Schemes
colorscheme = 'material_ocean'
|
mod = 'mod4'
terminal = 'st'
browser = 'firefox'
file_manager = 'thunar'
font = 'SauceCodePro Nerd Font Medium'
wallpaper = '~/wallpapers/wp1.png'
location = {'Mexico': 'Mexico'}
city = 'Mexico City, MX'
net = 'wlp2s0'
backlight = 'radeon_bl0'
colorscheme = 'material_ocean'
|
"""678. Valid Parenthesis String
https://leetcode.com/problems/valid-parenthesis-string/
"""
class Solution:
def check_valid_string(self, s: str) -> bool:
left_stack, star_stack = [], []
for i, c in enumerate(s):
if c == '(':
left_stack.append(i)
elif c == '*':
star_stack.append(i)
else:
if left_stack:
left_stack.pop()
elif star_stack:
star_stack.pop()
else:
return False
if len(left_stack) > len(star_stack):
return False
i, j = 0, len(star_stack) - len(left_stack)
while i < len(left_stack):
if left_stack[i] > star_stack[j]:
return False
i += 1
j += 1
return True
|
"""678. Valid Parenthesis String
https://leetcode.com/problems/valid-parenthesis-string/
"""
class Solution:
def check_valid_string(self, s: str) -> bool:
(left_stack, star_stack) = ([], [])
for (i, c) in enumerate(s):
if c == '(':
left_stack.append(i)
elif c == '*':
star_stack.append(i)
elif left_stack:
left_stack.pop()
elif star_stack:
star_stack.pop()
else:
return False
if len(left_stack) > len(star_stack):
return False
(i, j) = (0, len(star_stack) - len(left_stack))
while i < len(left_stack):
if left_stack[i] > star_stack[j]:
return False
i += 1
j += 1
return True
|
class Solution:
def isValid(self, s: str) -> bool:
stack = []
for i in s:
if i == ')' or i == ']' or i == '}':
if not stack or stack[-1] != i:
return False
stack.pop()
else:
if i == '(':
stack.append(')')
if i == '[':
stack.append(']')
if i == '{':
stack.append('}')
return not stack
|
class Solution:
def is_valid(self, s: str) -> bool:
stack = []
for i in s:
if i == ')' or i == ']' or i == '}':
if not stack or stack[-1] != i:
return False
stack.pop()
else:
if i == '(':
stack.append(')')
if i == '[':
stack.append(']')
if i == '{':
stack.append('}')
return not stack
|
SEARCH_PARAMS = {
"Sect1": "PTO2",
"Sect2": "HITOFF",
"p": "1",
"u": "/netahtml/PTO/search-adv.html",
"r": "0",
"f": "S",
"l": "50",
"d": "PG01",
"Query": "query",
}
SEARCH_FIELDS = {
"document_number": "DN",
"publication_date": "PD",
"title": "TTL",
"abstract": "ABST",
"claims": "ACLM",
"specification": "SPEC",
"current_us_classification": "CCL",
"current_cpc_classification": "CPC",
"current_cpc_classification_class": "CPCL",
"international_classification": "ICL",
"application_serial_number": "APN",
"application_date": "APD",
"application_type": "APT",
"government_interest": "GOVT",
"patent_family_id": "FMID",
"parent_case_information": "PARN",
"related_us_app._data": "RLAP",
"related_application_filing_date": "RLFD",
"foreign_priority": "PRIR",
"priority_filing_date": "PRAD",
"pct_information": "PCT",
"pct_filing_date": "PTAD",
"pct_national_stage_filing_date": "PT3D",
"prior_published_document_date": "PPPD",
"inventor_name": "IN",
"inventor_city": "IC",
"inventor_state": "IS",
"inventor_country": "ICN",
"applicant_name": "AANM",
"applicant_city": "AACI",
"applicant_state": "AAST",
"applicant_country": "AACO",
"applicant_type": "AAAT",
"assignee_name": "AN",
"assignee_city": "AC",
"assignee_state": "AS",
"assignee_country": "ACN",
}
SEARCH_URL = "https://appft.uspto.gov/netacgi/nph-Parser"
PUBLICATION_URL = (
"https://appft.uspto.gov/netacgi/nph-Parser?Sect1=PTO1&"
"Sect2=HITOFF&d=PG01&p=1&u=%2Fnetahtml%2FPTO%2Fsrchnum.html&r=1&f=G&l=50&"
"s1=%22{publication_number}%22.PGNR.&OS=DN/{publication_number}&RS=DN/{publication_number}"
)
|
search_params = {'Sect1': 'PTO2', 'Sect2': 'HITOFF', 'p': '1', 'u': '/netahtml/PTO/search-adv.html', 'r': '0', 'f': 'S', 'l': '50', 'd': 'PG01', 'Query': 'query'}
search_fields = {'document_number': 'DN', 'publication_date': 'PD', 'title': 'TTL', 'abstract': 'ABST', 'claims': 'ACLM', 'specification': 'SPEC', 'current_us_classification': 'CCL', 'current_cpc_classification': 'CPC', 'current_cpc_classification_class': 'CPCL', 'international_classification': 'ICL', 'application_serial_number': 'APN', 'application_date': 'APD', 'application_type': 'APT', 'government_interest': 'GOVT', 'patent_family_id': 'FMID', 'parent_case_information': 'PARN', 'related_us_app._data': 'RLAP', 'related_application_filing_date': 'RLFD', 'foreign_priority': 'PRIR', 'priority_filing_date': 'PRAD', 'pct_information': 'PCT', 'pct_filing_date': 'PTAD', 'pct_national_stage_filing_date': 'PT3D', 'prior_published_document_date': 'PPPD', 'inventor_name': 'IN', 'inventor_city': 'IC', 'inventor_state': 'IS', 'inventor_country': 'ICN', 'applicant_name': 'AANM', 'applicant_city': 'AACI', 'applicant_state': 'AAST', 'applicant_country': 'AACO', 'applicant_type': 'AAAT', 'assignee_name': 'AN', 'assignee_city': 'AC', 'assignee_state': 'AS', 'assignee_country': 'ACN'}
search_url = 'https://appft.uspto.gov/netacgi/nph-Parser'
publication_url = 'https://appft.uspto.gov/netacgi/nph-Parser?Sect1=PTO1&Sect2=HITOFF&d=PG01&p=1&u=%2Fnetahtml%2FPTO%2Fsrchnum.html&r=1&f=G&l=50&s1=%22{publication_number}%22.PGNR.&OS=DN/{publication_number}&RS=DN/{publication_number}'
|
# Variable Selection Linear Model
Baseline = ['price_lag_1', 'price3_lag_1',
'target_lag_1', 'target3_lag_1',
'tstd_lag_1']
Lags = ['item_id_price_lag_1', 'item_id_price3_lag_1',
'item_id_target_lag_1', 'item_id_target3_lag_1',
'item_id_tstd_lag_1', 'price_lag_1', 'price3_lag_1',
'shop_id_price_lag_1', 'shop_id_price3_lag_1',
'shop_id_target_lag_1', 'shop_id_target3_lag_1',
'shop_id_tstd_lag_1', 'target_lag_1', 'target3_lag_1',
'tstd_lag_1']
Shocks = ['item_id_price_lag_1', 'item_id_price3_lag_1',
'item_id_target_lag_1', 'item_id_target3_lag_1',
'item_id_tstd_lag_1', 'price_lag_1', 'price3_lag_1',
'shop_id_price_lag_1', 'shop_id_price3_lag_1',
'shop_id_target_lag_1', 'shop_id_target3_lag_1',
'shop_id_tstd_lag_1', 'target_lag_1', 'target3_lag_1',
'tstd_lag_1', 'targetchg', 'pricechg']
Date = ['item_id_price_lag_1', 'item_id_price3_lag_1',
'item_id_target_lag_1', 'item_id_target3_lag_1',
'item_id_tstd_lag_1', 'price_lag_1', 'price3_lag_1',
'shop_id_price_lag_1', 'shop_id_price3_lag_1',
'shop_id_target_lag_1', 'shop_id_target3_lag_1',
'shop_id_tstd_lag_1', 'target_lag_1', 'target3_lag_1',
'tstd_lag_1', 'date_encode', 'targetchg', 'pricechg']
All = ['item_id_price_lag_1', 'item_id_price3_lag_1',
'item_id_target_lag_1', 'item_id_target3_lag_1',
'item_id_tstd_lag_1', 'price_lag_1', 'price3_lag_1',
'shop_id_price_lag_1', 'shop_id_price3_lag_1',
'shop_id_target_lag_1', 'shop_id_target3_lag_1',
'shop_id_tstd_lag_1', 'target_lag_1', 'target3_lag_1',
'tstd_lag_1', 'item_encode', 'category_encode', 'shop_encode',
'city_encode', 'date_encode', 'itemstore_encode', 'targetchg',
'pricechg']
|
baseline = ['price_lag_1', 'price3_lag_1', 'target_lag_1', 'target3_lag_1', 'tstd_lag_1']
lags = ['item_id_price_lag_1', 'item_id_price3_lag_1', 'item_id_target_lag_1', 'item_id_target3_lag_1', 'item_id_tstd_lag_1', 'price_lag_1', 'price3_lag_1', 'shop_id_price_lag_1', 'shop_id_price3_lag_1', 'shop_id_target_lag_1', 'shop_id_target3_lag_1', 'shop_id_tstd_lag_1', 'target_lag_1', 'target3_lag_1', 'tstd_lag_1']
shocks = ['item_id_price_lag_1', 'item_id_price3_lag_1', 'item_id_target_lag_1', 'item_id_target3_lag_1', 'item_id_tstd_lag_1', 'price_lag_1', 'price3_lag_1', 'shop_id_price_lag_1', 'shop_id_price3_lag_1', 'shop_id_target_lag_1', 'shop_id_target3_lag_1', 'shop_id_tstd_lag_1', 'target_lag_1', 'target3_lag_1', 'tstd_lag_1', 'targetchg', 'pricechg']
date = ['item_id_price_lag_1', 'item_id_price3_lag_1', 'item_id_target_lag_1', 'item_id_target3_lag_1', 'item_id_tstd_lag_1', 'price_lag_1', 'price3_lag_1', 'shop_id_price_lag_1', 'shop_id_price3_lag_1', 'shop_id_target_lag_1', 'shop_id_target3_lag_1', 'shop_id_tstd_lag_1', 'target_lag_1', 'target3_lag_1', 'tstd_lag_1', 'date_encode', 'targetchg', 'pricechg']
all = ['item_id_price_lag_1', 'item_id_price3_lag_1', 'item_id_target_lag_1', 'item_id_target3_lag_1', 'item_id_tstd_lag_1', 'price_lag_1', 'price3_lag_1', 'shop_id_price_lag_1', 'shop_id_price3_lag_1', 'shop_id_target_lag_1', 'shop_id_target3_lag_1', 'shop_id_tstd_lag_1', 'target_lag_1', 'target3_lag_1', 'tstd_lag_1', 'item_encode', 'category_encode', 'shop_encode', 'city_encode', 'date_encode', 'itemstore_encode', 'targetchg', 'pricechg']
|
path = "."
# Set this to True to fully unlock all maps
# Set this to False to erase all map progress
useFullMaps = True
def reverse_endianness_block2(block):
even = block[::2]
odd = block[1::2]
res = []
for e, o in zip(even, odd):
res += [o, e]
return res
# Initiate base file
data = None
saveFile = [0]*257678
saveFile[:4] = [0x42, 0x4c, 0x48, 0x54]
saveFile[0x67] = 0x01
# Copy over character unlock flags
with open(path+"/PCF01.ngd", 'rb') as f:
data = f.read()
saveFile[0x5:0x3d] = data[0x1:0x39] # Extract only relevant part
# Copy over achievement status flags
with open(path+"/PAM01.ngd", 'rb') as f:
data = f.read()
saveFile[0x68:0x0d0] = data[0x00:0x68] # Extract regular disk part
saveFile[0xd6:0x10a] = data[0x6e:0xa2] # Extract plus disk part
# Copy over achievement notification status flags
with open(path+"/PAC01.ngd", 'rb') as f:
data = f.read()
saveFile[0x130:0x198] = data[0x00:0x68] # Extract regular disk part
saveFile[0x19e:0x1d2] = data[0x6e:0xa2] # Extract plus disk part
# Copy over bestiary information
with open(path+"/PKO01.ngd", 'rb') as f:
data = f.read()
saveFile[0x2c2:0x4c22] = data[0xca:0x4a2a]
saveFile[0x2c2:0x4c22] = reverse_endianness_block2(saveFile[0x2c2:0x4c22])
# Copy over party formation
with open(path+"/PPC01.ngd", 'rb') as f:
data = f.read()
saveFile[0x5018:0x5024] = data[:] # All bytes are relevant
# Copy over misc information from game
with open(path+"/PEX01.ngd", 'rb') as f:
data = f.read()
offset = 0x540c
saveFile[offset+0x00:offset+0x08] = data[0x00:0x08][::-1] # Cumulative EXP
saveFile[offset+0x08:offset+0x10] = data[0x08:0x10][::-1] # Cumulative Money
saveFile[offset+0x10:offset+0x18] = data[0x10:0x18][::-1] # Current money
saveFile[offset+0x18:offset+0x20] = data[0x18:0x20][::-1] # Number of battles
saveFile[offset+0x20:offset+0x24] = data[0x20:0x24][::-1] # Number of game overs
saveFile[offset+0x24:offset+0x28] = data[0x24:0x28][::-1] # Play time in seconds
saveFile[offset+0x28:offset+0x2c] = data[0x28:0x2c][::-1] # Number of treasures
saveFile[offset+0x2c:offset+0x30] = data[0x2c:0x30][::-1] # Number of crafts
saveFile[offset+0x30:offset+0x34] = data[0x30:0x34][::-1] # Unused data
saveFile[offset+0x34] = data[0x34] # Highest floor
saveFile[offset+0x35:offset+0x39] = data[0x35:0x39][::-1] # Number of locked treasures
saveFile[offset+0x39:offset+0x3d] = data[0x39:0x3d][::-1] # Number of escaped battles
saveFile[offset+0x3d:offset+0x41] = data[0x3d:0x41][::-1] # Number of dungeon enters
saveFile[offset+0x41:offset+0x45] = data[0x41:0x45][::-1] # Number of item drops
saveFile[offset+0x45:offset+0x49] = data[0x45:0x49][::-1] # Number of FOEs killed
saveFile[offset+0x49:offset+0x51] = data[0x49:0x51][::-1] # Number of steps taken
saveFile[offset+0x51:offset+0x59] = data[0x51:0x59][::-1] # Money spent on shop
saveFile[offset+0x59:offset+0x61] = data[0x59:0x61][::-1] # Money sold on shop
saveFile[offset+0x61:offset+0x69] = data[0x61:0x69][::-1] # Most EXP from 1 dive
saveFile[offset+0x69:offset+0x71] = data[0x69:0x71][::-1] # Most Money from 1 dive
saveFile[offset+0x71:offset+0x75] = data[0x71:0x75][::-1] # Most Drops from 1 dive
saveFile[offset+0x75] = data[0x75] # Unknown data
saveFile[offset+0x76:offset+0x7e] = data[0x76:0x7e][::-1] # Number of library enhances
saveFile[offset+0x7e:offset+0x82] = data[0x7e:0x82][::-1] # Highest battle streak
saveFile[offset+0x82:offset+0x86] = data[0x82:0x86][::-1] # Highest escape streak
saveFile[offset+0x86] = data[0x86] # Hard mode flag
saveFile[offset+0x87] = data[0x87] # IC enabled flag
# saveFile[offset+0x88:offset+0xae] = data[0x88:0xae] # Unknown data
saveFile[offset+0xae:offset+0xb2] = data[0xae:0xb2][::-1] # IC floor
saveFile[offset+0xb2:offset+0xb6] = data[0xb2:0xb6][::-1] # Number of akyuu trades
saveFile[offset+0xb6:offset+0xba] = data[0xb6:0xba][::-1] # Unknown data
# Copy over event flags
with open(path+"/EVF01.ngd", 'rb') as f:
data = f.read()
saveFile[0x54c6:0x68b2] = data[0x0:0x13ec] # Extract only relevant part
# Copy over item discovery flags
with open(path+"/EEF01.ngd", 'rb') as f:
data = f.read()
saveFile[0x7bd7:0x7c13] = data[0x001:0x03d] # Extract main equips
saveFile[0x7c9f:0x7d8f] = data[0x0c9:0x1b9] # Extract sub equips
saveFile[0x7dcb:0x7e2f] = data[0x1f5:0x259] # Extract materials
saveFile[0x7ef7:0x7fab] = data[0x321:0x3d5] # Extract special items
# Copy over item inventory count
with open(path+"/EEN01.ngd", 'rb') as f:
data = f.read()
saveFile[0x83a8:0x8420] = data[0x002:0x07a] # Extract main equips
saveFile[0x8538:0x8718] = data[0x192:0x372] # Extract sub equips
saveFile[0x8790:0x8858] = data[0x3ea:0x4b2] # Extract materials
saveFile[0x89e8:0x8b50] = data[0x642:0x7aa] # Extract special items
saveFile[0x83a8:0x8420] = reverse_endianness_block2(saveFile[0x83a8:0x8420])
saveFile[0x8538:0x8718] = reverse_endianness_block2(saveFile[0x8538:0x8718])
saveFile[0x8790:0x8858] = reverse_endianness_block2(saveFile[0x8790:0x8858])
saveFile[0x89e8:0x8b50] = reverse_endianness_block2(saveFile[0x89e8:0x8b50])
# Copy over character data
offset = 0x9346
for i in range(1, 57):
str_i = "0"+str(i) if i < 10 else str(i)
with open(path+"/C"+str_i+".ngd", 'rb') as f:
data = f.read()
saveFile[offset+0x000:offset+0x004] = data[0x000:0x004][::-1] # Level
saveFile[offset+0x004:offset+0x00c] = data[0x004:0x00c][::-1] # EXP
for s in range(14): # HP -> SPD, then FIR -> PHY
start = 0xc + (s*4)
end = start + 4
saveFile[offset+start:offset+end] = data[start:end][::-1] # Library level
for s in range(6): # HP -> SPD
start = 0x44 + (s*4)
end = start + 4
saveFile[offset+start:offset+end] = data[start:end][::-1] # Level up bonus
saveFile[offset+0x05c:offset+0x060] = data[0x05c:0x060][::-1] # Subclass
for s in range(40): # 12 boost, 6 empty, 2 exp, 10 personal, 10 spells
start = 0x60 + (s*2)
end = start + 2
saveFile[offset+start:offset+end] = data[start:end][::-1] # Skill level
for s in range(20): # 10 passives, 10 spells
start = 0xb0 + (s*2)
end = start + 2
saveFile[offset+start:offset+end] = data[start:end][::-1] # Subclass skill level
for s in range(12): # HP, MP, TP, ATK -> SPD, ACC, EVA, AFF, RES
start = 0xd8 + (s*1)
end = start + 1
saveFile[offset+start:offset+end] = data[start:end][::-1] # Tome flags
for s in range(8): # HP, MP, TP, ATK -> SPD
start = 0xe4 + (s*1)
end = start + 1
saveFile[offset+start:offset+end] = data[start:end][::-1] # Boost flags
saveFile[offset+0x0ec:offset+0x0ee] = data[0x0ed:0x0ef][::-1] # Unused skill points
saveFile[offset+0x0ee:offset+0x0f2] = data[0x0f0:0x0f4][::-1] # Unused level up bonus
for s in range(8): # HP, MP, TP, ATK -> SPD
start = 0xf2 + (s*2)
end = start + 2
saveFile[offset+start:offset+end] = data[start+2:end+2][::-1] # Gem count
saveFile[offset+0x102] = data[0x104] # Used training manuals
saveFile[offset+0x103:offset+0x107] = data[0x105:0x109][::-1] # BP count
for s in range(4): # main, 3 sub equips
start = 0x107 + (s*2)
end = start + 2
saveFile[offset+start:offset+end] = data[start+2:end+2][::-1] # Equip ID
offset += 0x10f
# Fully unlock maps
if (useFullMaps):
saveFile[0x0ce8e:0x2ae8e] = [0x55]*0x1e000 # 30 floors
saveFile[0x33e8e:0x3ee8e] = [0x55]*0xb000 # 11 underground floors
# A decrypted file for debugging
with open(path+"/result-decrypted.dat", 'wb') as f:
f.write(bytes(saveFile))
saveFile = [((i & 0xff) ^ c) for i, c in enumerate(saveFile)]
# The final file
with open(path+"/result.dat", 'wb') as f:
f.write(bytes(saveFile))
|
path = '.'
use_full_maps = True
def reverse_endianness_block2(block):
even = block[::2]
odd = block[1::2]
res = []
for (e, o) in zip(even, odd):
res += [o, e]
return res
data = None
save_file = [0] * 257678
saveFile[:4] = [66, 76, 72, 84]
saveFile[103] = 1
with open(path + '/PCF01.ngd', 'rb') as f:
data = f.read()
saveFile[5:61] = data[1:57]
with open(path + '/PAM01.ngd', 'rb') as f:
data = f.read()
saveFile[104:208] = data[0:104]
saveFile[214:266] = data[110:162]
with open(path + '/PAC01.ngd', 'rb') as f:
data = f.read()
saveFile[304:408] = data[0:104]
saveFile[414:466] = data[110:162]
with open(path + '/PKO01.ngd', 'rb') as f:
data = f.read()
saveFile[706:19490] = data[202:18986]
saveFile[706:19490] = reverse_endianness_block2(saveFile[706:19490])
with open(path + '/PPC01.ngd', 'rb') as f:
data = f.read()
saveFile[20504:20516] = data[:]
with open(path + '/PEX01.ngd', 'rb') as f:
data = f.read()
offset = 21516
saveFile[offset + 0:offset + 8] = data[0:8][::-1]
saveFile[offset + 8:offset + 16] = data[8:16][::-1]
saveFile[offset + 16:offset + 24] = data[16:24][::-1]
saveFile[offset + 24:offset + 32] = data[24:32][::-1]
saveFile[offset + 32:offset + 36] = data[32:36][::-1]
saveFile[offset + 36:offset + 40] = data[36:40][::-1]
saveFile[offset + 40:offset + 44] = data[40:44][::-1]
saveFile[offset + 44:offset + 48] = data[44:48][::-1]
saveFile[offset + 48:offset + 52] = data[48:52][::-1]
saveFile[offset + 52] = data[52]
saveFile[offset + 53:offset + 57] = data[53:57][::-1]
saveFile[offset + 57:offset + 61] = data[57:61][::-1]
saveFile[offset + 61:offset + 65] = data[61:65][::-1]
saveFile[offset + 65:offset + 69] = data[65:69][::-1]
saveFile[offset + 69:offset + 73] = data[69:73][::-1]
saveFile[offset + 73:offset + 81] = data[73:81][::-1]
saveFile[offset + 81:offset + 89] = data[81:89][::-1]
saveFile[offset + 89:offset + 97] = data[89:97][::-1]
saveFile[offset + 97:offset + 105] = data[97:105][::-1]
saveFile[offset + 105:offset + 113] = data[105:113][::-1]
saveFile[offset + 113:offset + 117] = data[113:117][::-1]
saveFile[offset + 117] = data[117]
saveFile[offset + 118:offset + 126] = data[118:126][::-1]
saveFile[offset + 126:offset + 130] = data[126:130][::-1]
saveFile[offset + 130:offset + 134] = data[130:134][::-1]
saveFile[offset + 134] = data[134]
saveFile[offset + 135] = data[135]
saveFile[offset + 174:offset + 178] = data[174:178][::-1]
saveFile[offset + 178:offset + 182] = data[178:182][::-1]
saveFile[offset + 182:offset + 186] = data[182:186][::-1]
with open(path + '/EVF01.ngd', 'rb') as f:
data = f.read()
saveFile[21702:26802] = data[0:5100]
with open(path + '/EEF01.ngd', 'rb') as f:
data = f.read()
saveFile[31703:31763] = data[1:61]
saveFile[31903:32143] = data[201:441]
saveFile[32203:32303] = data[501:601]
saveFile[32503:32683] = data[801:981]
with open(path + '/EEN01.ngd', 'rb') as f:
data = f.read()
saveFile[33704:33824] = data[2:122]
saveFile[34104:34584] = data[402:882]
saveFile[34704:34904] = data[1002:1202]
saveFile[35304:35664] = data[1602:1962]
saveFile[33704:33824] = reverse_endianness_block2(saveFile[33704:33824])
saveFile[34104:34584] = reverse_endianness_block2(saveFile[34104:34584])
saveFile[34704:34904] = reverse_endianness_block2(saveFile[34704:34904])
saveFile[35304:35664] = reverse_endianness_block2(saveFile[35304:35664])
offset = 37702
for i in range(1, 57):
str_i = '0' + str(i) if i < 10 else str(i)
with open(path + '/C' + str_i + '.ngd', 'rb') as f:
data = f.read()
saveFile[offset + 0:offset + 4] = data[0:4][::-1]
saveFile[offset + 4:offset + 12] = data[4:12][::-1]
for s in range(14):
start = 12 + s * 4
end = start + 4
saveFile[offset + start:offset + end] = data[start:end][::-1]
for s in range(6):
start = 68 + s * 4
end = start + 4
saveFile[offset + start:offset + end] = data[start:end][::-1]
saveFile[offset + 92:offset + 96] = data[92:96][::-1]
for s in range(40):
start = 96 + s * 2
end = start + 2
saveFile[offset + start:offset + end] = data[start:end][::-1]
for s in range(20):
start = 176 + s * 2
end = start + 2
saveFile[offset + start:offset + end] = data[start:end][::-1]
for s in range(12):
start = 216 + s * 1
end = start + 1
saveFile[offset + start:offset + end] = data[start:end][::-1]
for s in range(8):
start = 228 + s * 1
end = start + 1
saveFile[offset + start:offset + end] = data[start:end][::-1]
saveFile[offset + 236:offset + 238] = data[237:239][::-1]
saveFile[offset + 238:offset + 242] = data[240:244][::-1]
for s in range(8):
start = 242 + s * 2
end = start + 2
saveFile[offset + start:offset + end] = data[start + 2:end + 2][::-1]
saveFile[offset + 258] = data[260]
saveFile[offset + 259:offset + 263] = data[261:265][::-1]
for s in range(4):
start = 263 + s * 2
end = start + 2
saveFile[offset + start:offset + end] = data[start + 2:end + 2][::-1]
offset += 271
if useFullMaps:
saveFile[52878:175758] = [85] * 122880
saveFile[212622:257678] = [85] * 45056
with open(path + '/result-decrypted.dat', 'wb') as f:
f.write(bytes(saveFile))
save_file = [i & 255 ^ c for (i, c) in enumerate(saveFile)]
with open(path + '/result.dat', 'wb') as f:
f.write(bytes(saveFile))
|
# -*- coding: utf-8 -*-
class Screen:
def __init__(self, dim):
self.arena = []
self.dimx = dim[0]+2
self.dimy = dim[1]+2
for x in range(self.dimx):
self.arena.append([])
for y in range(self.dimy):
if x == 0 or x == (self.dimx-1):
self.arena[x].append('-')
elif y == 0 or y == (self.dimy-1):
self.arena[x].append('|')
else:
self.arena[x].append(' ')
def draw(self, ch, pos):
if self.inValidRange(pos):
self.arena[pos[0]][pos[1]] = ch
return True
return False
def clear(self):
for x in range(self.dimx):
for y in range(self.dimy):
if x == 0 or x == (self.dimx-1):
self.arena[x][y] = '-'
elif y == 0 or y == (self.dimy-1):
self.arena[x][y] = '|'
else:
self.arena[x][y] = ' '
def inValidRange(self, pos):
return pos[0] > 0 and pos[0] < (self.dimx-1) and pos[1] > 0 and pos[1] < (self.dimy-1)
def __str__(self):
tmp = ""
for i in range(self.dimx):
for j in self.arena[i]:
tmp += j
tmp += '\n'
return tmp
|
class Screen:
def __init__(self, dim):
self.arena = []
self.dimx = dim[0] + 2
self.dimy = dim[1] + 2
for x in range(self.dimx):
self.arena.append([])
for y in range(self.dimy):
if x == 0 or x == self.dimx - 1:
self.arena[x].append('-')
elif y == 0 or y == self.dimy - 1:
self.arena[x].append('|')
else:
self.arena[x].append(' ')
def draw(self, ch, pos):
if self.inValidRange(pos):
self.arena[pos[0]][pos[1]] = ch
return True
return False
def clear(self):
for x in range(self.dimx):
for y in range(self.dimy):
if x == 0 or x == self.dimx - 1:
self.arena[x][y] = '-'
elif y == 0 or y == self.dimy - 1:
self.arena[x][y] = '|'
else:
self.arena[x][y] = ' '
def in_valid_range(self, pos):
return pos[0] > 0 and pos[0] < self.dimx - 1 and (pos[1] > 0) and (pos[1] < self.dimy - 1)
def __str__(self):
tmp = ''
for i in range(self.dimx):
for j in self.arena[i]:
tmp += j
tmp += '\n'
return tmp
|
def strategy(history, memory):
"""
Tit-for-tat, except we punish them N times in a row if this is the Nth time they've
initiated a defection.
memory: (initiatedDefections, remainingPunitiveDefections)
"""
if memory is not None and memory[1] > 0:
choice = 0
memory = (memory[0], memory[1] - 1)
return choice, memory
num_rounds = history.shape[1]
opponents_last_move = history[1, -1] if num_rounds >= 1 else 1
our_last_move = history[0, -1] if num_rounds >= 1 else 1
our_second_last_move = history[0, -2] if num_rounds >= 2 else 1
opponent_initiated_defection = (
opponents_last_move == 0 and our_last_move == 1 and our_second_last_move == 1
)
choice = 0 if opponent_initiated_defection else 1
if choice == 0:
memory = (1, 0) if memory is None else (memory[0] + 1, memory[0])
return choice, memory
|
def strategy(history, memory):
"""
Tit-for-tat, except we punish them N times in a row if this is the Nth time they've
initiated a defection.
memory: (initiatedDefections, remainingPunitiveDefections)
"""
if memory is not None and memory[1] > 0:
choice = 0
memory = (memory[0], memory[1] - 1)
return (choice, memory)
num_rounds = history.shape[1]
opponents_last_move = history[1, -1] if num_rounds >= 1 else 1
our_last_move = history[0, -1] if num_rounds >= 1 else 1
our_second_last_move = history[0, -2] if num_rounds >= 2 else 1
opponent_initiated_defection = opponents_last_move == 0 and our_last_move == 1 and (our_second_last_move == 1)
choice = 0 if opponent_initiated_defection else 1
if choice == 0:
memory = (1, 0) if memory is None else (memory[0] + 1, memory[0])
return (choice, memory)
|
"""
Simple config file
"""
class Config(object):
DEBUG = False
TESTING = False
SECRET_KEY = b'' # TODO
SQLALCHEMY_DATABASE_URI = 'sqlite:///database.db'
SQLALCHEMY_TRACK_MODIFICATIONS = False
class Dev(Config):
DEBUG = True
TESTING = True
SQLALCHEMY_TRACK_MODIFICATIONS = True
|
"""
Simple config file
"""
class Config(object):
debug = False
testing = False
secret_key = b''
sqlalchemy_database_uri = 'sqlite:///database.db'
sqlalchemy_track_modifications = False
class Dev(Config):
debug = True
testing = True
sqlalchemy_track_modifications = True
|
#!/usr/bin/env python
"""
Github: https://github.com/Jiezhi/myleetcode
Created on 2019-03-25
Leetcode:
"""
def func(x):
return x + 1
def test_answer():
assert func(3) == 4
|
"""
Github: https://github.com/Jiezhi/myleetcode
Created on 2019-03-25
Leetcode:
"""
def func(x):
return x + 1
def test_answer():
assert func(3) == 4
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.