content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
boxes = """cvfueihajytpmrdkgsxfqplbxn cbzueihajytnmrdkgtxfqplbwn cvzucihajytomrdkgstfqplqwn cvzueilajytomrdkgsxfqwnbwn cvzueihajytomrdkgsgwqphbwn wuzuerhajytomrdkgsxfqplbwn cyzueifajybomrdkgsxfqplbwn cvzueihajxtomrdkgpxfqplmwn ivzfevhajytomrdkgsxfqplbwn cvzueihajytomrdlgsxfqphbbn uvzueihajjtomrdkgsxfqpobwn cvzupihajytomrdkgsxfqplpwe cvzueihajyvomrdkgsxfqplbrl cczueihajytomrdkgsnfqpxbwn cvzueigajytdmrdkgsxyqplbwn cvzujihljytomrdkgsxuqplbwn cvzueisajytomrddgsxkqplbwn cvzneihajytomrdkgsgaqplbwn cvzueihajytomrdkgsinmplbwn cveueihajyromrdkgsxfqplown cypueihajytotrdkgzxfqplbwn cvzuoihajytomvdqgsxfqplbwn cvzuekhejytwmrdkgsxfqplbwn cvzseihajytomrdkgsxfqgmbwn cvfuhihajytomrdkgsxfqplbwi cvzueihujxtomrdkgsufqplbwn cvzueihdjytomrdogsxfqplbwh cvzueihdjyfohrdkgsxfqplbwn cvtudihajytolrdkgsxfqplbwn cvzueihajytymrdkgshzqplbwn cvzuebhajytomxdkgsxfqplbwt cvzulihajyxomrdkgsbfqplbwn cvzueihajywomrdkgsxfqplbts cvzueihajytouodkdsxfqplbwn cvzueihajytomgdkgqxfqklbwn cvzubihajytomvdkgsxfqplmwn cvhueihajyyocrdkgsxfqplbwn zvzueihajytourdkgsxflplbwn cvzbeihajytomadkgsxfoplbwn cvzueihajytomrdkgnxfqplbsl cvfueihajftkmrdkgsxfqplbwn cvzuexhajytomryugsxfqplbwn cvzueihajytomsckgsxfqalbwn cvzuexhajytomrdkbsxfqpluwn cvzueihajytbmrtkgsxwqplbwn cvzueihajytomrdigsxfqqlbsn cvzweihajytomydkgsxfmplbwn bvzteihajytimrdkgsxfqplbwn cvzueihajytpmrdkgsxfcpbbwn cvzueigsjltomrdkgsxfqplbwn cvzueihajytomrikgsxfopldwn cvzueihajstomrdkgsxfqplgon cvzueimajytomrnkxsxfqplbwn cvzleihagatomrdkgsxfqplbwn cvbueihajotomrdkgsxfqjlbwn cvzueihajytomrdkgsxfqppnvn hvzueihajytomrdkghxfkplbwn cvzueigajytxmrdkgsxfqplbjn cvzueihaaxtokrdkgsxfqplbwn cvzueihajyeomrdkgujfqplbwn cvzueiwajpoomrdkgsxfqplbwn cvzieidtjytomrdkgsxfqplbwn cvzueihalytomrakbsxfqplbwn wtzueihajytomrdkgsxfqplbwq cvzuelhaiytomrdkgsxfqplcwn cvzueihajytomrdkgsxfqslswd cvzueihajytomrykgssfqplbon cvzueihfjytovrdegsxfqplbwn cvzueihajytomldqgsxfqplbwy cvzleihjjytomrtkgsxfqplbwn cvzueihaldtomrdtgsxfqplbwn cvzueihajytzmrdkgsxfeplqwn cvzueihrjytomddkgsxfqpgbwn cyzulihajytokrdkgsxfqplbwn cvsueihajytoordfgsxfqplbwn fvzueyhajytomrdkgaxfqplbwn cczueihajytobrdkgsefqplbwn cvzueihajytomcdrgscfqplbwn cvzuexhajyvomrdkgssfqplbwn cvzsmihajyiomrdkgsxfqplbwn cvzzeihajttomrdkgsxzqplbwn cvzseihajytomrdkgsxfqpebvn cvzueihajgthmrdkgsbfqplbwn ruzueihajytomrdkgsxfqphbwn cvzueihajytofrdkgsnfrplbwn cvzuetdajytojrdkgsxfqplbwn fvzueihajytomrdkghxfqpobwn cvzueihsjytomrdkgsxfqglbxn cvzueihajytowrdkgsxfqpsbun cvzteihaiytomrdkfsxfqplbwn cvzueihajytkmrdkrsxfqplvwn cvzueihajyoomrdkasxfqjlbwn lvzurihajytkmrdkgsxfqplbwn cvzueihajyyomrdagsxfqelbwn cvfueihajytomrdkgsxfqplbbx cvwueihajytommdkgkxfqplbwn cvzucicajytomrdkgsxcqplbwn dvzueihahytgmrdkgsxfqplbwn cvzuechajytomrdkgsxfqelwwn cvzuekhajytomrdkgsxknplbwn cvtueihajytomphkgsxfqplbwn cvzueihabytnzrdkgsxfqplbwn cvzusihajytomrdkgfxfqplban cvfueihajytomcdfgsxfqplbwn mvzueihapytomrdkgsxfdplbwn cvzueihajytomhdkgsxmqppbwn jvsueihajytomrdkgsxfqplbln cvzujihajybomrdkgsxtqplbwn cvzuekhawytomrdkgsxfqplbwc svzueihanytomrdogsxfqplbwn cvzujihajytodrdkgslfqplbwn cvgdeihajytorrdkgsxfqplbwn cvzbeihajytoprdkgsxfqplbyn cvzueihkyytomjdkgsxfqplbwn cvzuelhojytomrdkgsxfqjlbwn evzueihajytimrdkgsxfqpsbwn cvzueihajydomrdkjsxfqplbjn ovzteihajytosrdkgsxfqplbwn cvzueihajyaomrdzgsxfqplbgn cvzuewhajmtomrdkgsufqplbwn cvzueihajqtomhukgsxfqplbwn cvzueihajytomzqkgsxfqplbwk cazuewhakytomrdkgsxfqplbwn clzueihatytomrdkgzxfqplbwn dvzueihajytomqdkgsxfqpnbwn cvzueidajdtomrdkgsxtqplbwn cvzueihabytowrdkgsxoqplbwn cvzujihwjytomrdkgsxeqplbwn cvtuedhajytomrdkgsxfqplbbn cvzueihajcgomrdkgsxfqplswn cvzuephajyiomrdngsxfqplbwn cvzueihajythmqdkgsxfqplbwf cvzueitajytomrdkgsxfepvbwn cvzueihajytomydkgsxfqplvwb dvzueshajytomrddgsxfqplbwn cvzueihajytomrdkgvxfqpwben cvzueihajytomrdkgvxfpplwwn cvzuefhajftomrdkgsxfqrlbwn cvzueihajytpmrvkgsxfqplbcn cvzueihajytohrdkgsxfqxnbwn cvzueihajytomrdposxfqulbwn cozueihajytomrpkgsxfqrlbwn cvzuuihaxytomrdkgsxfqplbtn cvzueihajytomrbzgsxyqplbwn cveueihajyxoqrdkgsxfqplbwn cvzueihajytomrkkgsxfqptbrn cvzuezhajatomrdkssxfqplbwn cpzueihajytomrdkgsxfhplbwo lviueihajytomrekgsxfqplbwn cvzueihwjytomrdkusxfyplbwn cvzgeihajytomwdkgsxfrplbwn cvzsejhzjytomrdkgsxfqplbwn cvzuuihajytomrdkgsxfqdlbwz cvzjeihajytomrdugsxftplbwn cvzueihaxytomrrkgsxfmplbwn cvzueihajgtomrdhgsxfqplwwn cvzulihajytomedkgsxfqplewn cvzueivajytomrdkmsxfqplbwc cvzuervajytomrdkgsxfwplbwn cvzuemhcjytomrdkgslfqplbwn cvzyerhauytomrdkgsxfqplbwn cvzueihaoytomrdkgsyfqplewn cvzueihanytomrdkgsafkplbwn cvzueihajvtomrdugsxfqpcbwn chzueihajytamrdxgsxfqplbwn cvzueihalytomrdsgsxfqplbln cvzueihajytoyaykgsxfqplbwn tlzueihajyeomrdkgsxfqplbwn cvpueihajytbmrdkgsxfxplbwn cvzueihajytomjdkgsxuqplkwn cvzueihajygomrdkgkxfqplbwg cvzueihajhtomrdkgbxsqplbwn cvzurihajytomrdkgsafqplbwx cdzuezhajytomrdkgsxrqplbwn cvbueihajytotrwkgsxfqplbwn cwzkeihajytomrdkgsxfqplbwh cvzheihajytolrikgsxfqplbwn cozuevhajytomrdkgkxfqplbwn chzueihajytomrjkgsxfqulbwn cvzueihkjyromrdkgsxvqplbwn cvzveihajytomrdkgsxpqplnwn cvzueihajytoirdkgsxfqihbwn cvoueihajytomrdkgsxfqpdawn pvzueihajytomrdkgnxfqplbfn cvzueihakytomxdkgssfqplbwn cvzueivajytomrdbgsxaqplbwn cvzueihajytokrdkgszrqplbwn cvzuevhajytomrdkgsxgqplbwi cvzueihajylomrdkgsxflplbpn hvzueihajytomvdkgsxfqplgwn cvzleihajytymrrkgsxfqplbwn crzueieajytomrdkgsxfqplbon cszueihajytomrdlgqxfqplbwn cvzueihacytomrdkgsxfjblbwn cvzreihajytomrdkgsxfqplzun cvzurihajytomrdkgsxiqplawn uvzueihajyhovrdkgsxfqplbwn cvzueihajyqodrdkgssfqplbwn cvzwiihrjytomrdkgsxfqplbwn cqzueihajytomrdkgjxfqplban cvmueihajytoordkgsxfqplbyn cypueihajytomrdkgzxfqplbwn cvzueihajykomrdkgsmfqplbtn cvzueidajytimrdkgsxfqpdbwn cvzheihajytomrdkgsxfqpfewn dvzueihajytumrdzgsxfqplbwn cvzueixajytomrdkgsvfqplgwn cvzuevhzjyzomrdkgsxfqplbwn cvyeeihajytomrdkgsxnqplbwn cvzueihajytomrdkggtpqplbwn cvzceiyajytomrdkgexfqplbwn cvzuelhajyyomrdkzsxfqplbwn cvzhzihajygomrdkgsxfqplbwn cvzueihwjytomrdkgsgfqplbrn cvzsevhajytomrdkgqxfqplbwn cvzueiuajytomrdkgsxfppebwn nvzueihajytemrdkgsxwqplbwn cvzueihajytocgdkgsxfqvlbwn cczusihajytomrdkgsxfqplbpn cmzueihajytomrdkbsxwqplbwn cvzumfdajytomrdkgsxfqplbwn cvzueihcjytomrdkgsxfqplbkl cvzueihajytomawknsxfqplbwn kvzueihijytomrdkgsxdqplbwn cdzutihajytomrdkgsxfkplbwn cvzufihadylomrdkgsxfqplbwn cvzueihajytomrgkxsxfqphbwn cvzuewhajyzomrdkgsxfqelbwn cvzueihajytomrdkgqxfqelbwc cvzueshajyoomrdkgsxfqflbwn cvzueihajyromrekgixfqplbwn chzugihajytomrdkgsxfqplawn cvzueihajytomrdkgsxfhpmbwy cvzueihacytodxdkgsxfqplbwn cvzurihajytourdkgsdfqplbwn cvzzeihmjytomrddgsxfqplbwn cvzucyhajygomrdkgsxfqplbwn ckzueihzjytomrdkgsxwqplbwn cvlueihajmtozrdkgsxfqplbwn cvzkeihajytomrdkgsxfqclbwc cvzueihajytomrdkgsxgdplbwa cvzueihyjytoxrdkgcxfqplbwn cvzueizavytomfdkgsxfqplbwn cvzueihajwtosrdkgsxfqllbwn cvzueihajytomrdaksxfqpllwn cvzuuihojytombdkgsxfqplbwn cvzuiibajytpmrdkgsxfqplbwn cvzueihajyuomydkgsxfqplzwn cvzueihajytimrmkgsxfqplfwn cvzueihajytomrdkgzxfqpljwo""" boxes = boxes.split("\n") def has_two(s): d = {} for c in s: d[c] = d.get(c, 0) + 1 return(2 in d.values()) def has_three(s): d = {} for c in s: d[c] = d.get(c, 0) + 1 return(3 in d.values()) twos = sum(map(int, map(has_two, boxes))) # for each box, get has_two, convert to 0/1 and sum threes = sum(map(int, map(has_three, boxes))) # same for threes checksum = twos * threes def has_match(ss): d = {} for s in ss: for ri in range(0, len(s)): c = s[:ri] + s[ri+1:] d[(c,ri)] = d.get((c,ri), 0) + 1 for key in d: if d[key] == 2: return(key, d) return(None, d) match, matchd = has_match(boxes)
boxes = 'cvfueihajytpmrdkgsxfqplbxn\ncbzueihajytnmrdkgtxfqplbwn\ncvzucihajytomrdkgstfqplqwn\ncvzueilajytomrdkgsxfqwnbwn\ncvzueihajytomrdkgsgwqphbwn\nwuzuerhajytomrdkgsxfqplbwn\ncyzueifajybomrdkgsxfqplbwn\ncvzueihajxtomrdkgpxfqplmwn\nivzfevhajytomrdkgsxfqplbwn\ncvzueihajytomrdlgsxfqphbbn\nuvzueihajjtomrdkgsxfqpobwn\ncvzupihajytomrdkgsxfqplpwe\ncvzueihajyvomrdkgsxfqplbrl\ncczueihajytomrdkgsnfqpxbwn\ncvzueigajytdmrdkgsxyqplbwn\ncvzujihljytomrdkgsxuqplbwn\ncvzueisajytomrddgsxkqplbwn\ncvzneihajytomrdkgsgaqplbwn\ncvzueihajytomrdkgsinmplbwn\ncveueihajyromrdkgsxfqplown\ncypueihajytotrdkgzxfqplbwn\ncvzuoihajytomvdqgsxfqplbwn\ncvzuekhejytwmrdkgsxfqplbwn\ncvzseihajytomrdkgsxfqgmbwn\ncvfuhihajytomrdkgsxfqplbwi\ncvzueihujxtomrdkgsufqplbwn\ncvzueihdjytomrdogsxfqplbwh\ncvzueihdjyfohrdkgsxfqplbwn\ncvtudihajytolrdkgsxfqplbwn\ncvzueihajytymrdkgshzqplbwn\ncvzuebhajytomxdkgsxfqplbwt\ncvzulihajyxomrdkgsbfqplbwn\ncvzueihajywomrdkgsxfqplbts\ncvzueihajytouodkdsxfqplbwn\ncvzueihajytomgdkgqxfqklbwn\ncvzubihajytomvdkgsxfqplmwn\ncvhueihajyyocrdkgsxfqplbwn\nzvzueihajytourdkgsxflplbwn\ncvzbeihajytomadkgsxfoplbwn\ncvzueihajytomrdkgnxfqplbsl\ncvfueihajftkmrdkgsxfqplbwn\ncvzuexhajytomryugsxfqplbwn\ncvzueihajytomsckgsxfqalbwn\ncvzuexhajytomrdkbsxfqpluwn\ncvzueihajytbmrtkgsxwqplbwn\ncvzueihajytomrdigsxfqqlbsn\ncvzweihajytomydkgsxfmplbwn\nbvzteihajytimrdkgsxfqplbwn\ncvzueihajytpmrdkgsxfcpbbwn\ncvzueigsjltomrdkgsxfqplbwn\ncvzueihajytomrikgsxfopldwn\ncvzueihajstomrdkgsxfqplgon\ncvzueimajytomrnkxsxfqplbwn\ncvzleihagatomrdkgsxfqplbwn\ncvbueihajotomrdkgsxfqjlbwn\ncvzueihajytomrdkgsxfqppnvn\nhvzueihajytomrdkghxfkplbwn\ncvzueigajytxmrdkgsxfqplbjn\ncvzueihaaxtokrdkgsxfqplbwn\ncvzueihajyeomrdkgujfqplbwn\ncvzueiwajpoomrdkgsxfqplbwn\ncvzieidtjytomrdkgsxfqplbwn\ncvzueihalytomrakbsxfqplbwn\nwtzueihajytomrdkgsxfqplbwq\ncvzuelhaiytomrdkgsxfqplcwn\ncvzueihajytomrdkgsxfqslswd\ncvzueihajytomrykgssfqplbon\ncvzueihfjytovrdegsxfqplbwn\ncvzueihajytomldqgsxfqplbwy\ncvzleihjjytomrtkgsxfqplbwn\ncvzueihaldtomrdtgsxfqplbwn\ncvzueihajytzmrdkgsxfeplqwn\ncvzueihrjytomddkgsxfqpgbwn\ncyzulihajytokrdkgsxfqplbwn\ncvsueihajytoordfgsxfqplbwn\nfvzueyhajytomrdkgaxfqplbwn\ncczueihajytobrdkgsefqplbwn\ncvzueihajytomcdrgscfqplbwn\ncvzuexhajyvomrdkgssfqplbwn\ncvzsmihajyiomrdkgsxfqplbwn\ncvzzeihajttomrdkgsxzqplbwn\ncvzseihajytomrdkgsxfqpebvn\ncvzueihajgthmrdkgsbfqplbwn\nruzueihajytomrdkgsxfqphbwn\ncvzueihajytofrdkgsnfrplbwn\ncvzuetdajytojrdkgsxfqplbwn\nfvzueihajytomrdkghxfqpobwn\ncvzueihsjytomrdkgsxfqglbxn\ncvzueihajytowrdkgsxfqpsbun\ncvzteihaiytomrdkfsxfqplbwn\ncvzueihajytkmrdkrsxfqplvwn\ncvzueihajyoomrdkasxfqjlbwn\nlvzurihajytkmrdkgsxfqplbwn\ncvzueihajyyomrdagsxfqelbwn\ncvfueihajytomrdkgsxfqplbbx\ncvwueihajytommdkgkxfqplbwn\ncvzucicajytomrdkgsxcqplbwn\ndvzueihahytgmrdkgsxfqplbwn\ncvzuechajytomrdkgsxfqelwwn\ncvzuekhajytomrdkgsxknplbwn\ncvtueihajytomphkgsxfqplbwn\ncvzueihabytnzrdkgsxfqplbwn\ncvzusihajytomrdkgfxfqplban\ncvfueihajytomcdfgsxfqplbwn\nmvzueihapytomrdkgsxfdplbwn\ncvzueihajytomhdkgsxmqppbwn\njvsueihajytomrdkgsxfqplbln\ncvzujihajybomrdkgsxtqplbwn\ncvzuekhawytomrdkgsxfqplbwc\nsvzueihanytomrdogsxfqplbwn\ncvzujihajytodrdkgslfqplbwn\ncvgdeihajytorrdkgsxfqplbwn\ncvzbeihajytoprdkgsxfqplbyn\ncvzueihkyytomjdkgsxfqplbwn\ncvzuelhojytomrdkgsxfqjlbwn\nevzueihajytimrdkgsxfqpsbwn\ncvzueihajydomrdkjsxfqplbjn\novzteihajytosrdkgsxfqplbwn\ncvzueihajyaomrdzgsxfqplbgn\ncvzuewhajmtomrdkgsufqplbwn\ncvzueihajqtomhukgsxfqplbwn\ncvzueihajytomzqkgsxfqplbwk\ncazuewhakytomrdkgsxfqplbwn\nclzueihatytomrdkgzxfqplbwn\ndvzueihajytomqdkgsxfqpnbwn\ncvzueidajdtomrdkgsxtqplbwn\ncvzueihabytowrdkgsxoqplbwn\ncvzujihwjytomrdkgsxeqplbwn\ncvtuedhajytomrdkgsxfqplbbn\ncvzueihajcgomrdkgsxfqplswn\ncvzuephajyiomrdngsxfqplbwn\ncvzueihajythmqdkgsxfqplbwf\ncvzueitajytomrdkgsxfepvbwn\ncvzueihajytomydkgsxfqplvwb\ndvzueshajytomrddgsxfqplbwn\ncvzueihajytomrdkgvxfqpwben\ncvzueihajytomrdkgvxfpplwwn\ncvzuefhajftomrdkgsxfqrlbwn\ncvzueihajytpmrvkgsxfqplbcn\ncvzueihajytohrdkgsxfqxnbwn\ncvzueihajytomrdposxfqulbwn\ncozueihajytomrpkgsxfqrlbwn\ncvzuuihaxytomrdkgsxfqplbtn\ncvzueihajytomrbzgsxyqplbwn\ncveueihajyxoqrdkgsxfqplbwn\ncvzueihajytomrkkgsxfqptbrn\ncvzuezhajatomrdkssxfqplbwn\ncpzueihajytomrdkgsxfhplbwo\nlviueihajytomrekgsxfqplbwn\ncvzueihwjytomrdkusxfyplbwn\ncvzgeihajytomwdkgsxfrplbwn\ncvzsejhzjytomrdkgsxfqplbwn\ncvzuuihajytomrdkgsxfqdlbwz\ncvzjeihajytomrdugsxftplbwn\ncvzueihaxytomrrkgsxfmplbwn\ncvzueihajgtomrdhgsxfqplwwn\ncvzulihajytomedkgsxfqplewn\ncvzueivajytomrdkmsxfqplbwc\ncvzuervajytomrdkgsxfwplbwn\ncvzuemhcjytomrdkgslfqplbwn\ncvzyerhauytomrdkgsxfqplbwn\ncvzueihaoytomrdkgsyfqplewn\ncvzueihanytomrdkgsafkplbwn\ncvzueihajvtomrdugsxfqpcbwn\nchzueihajytamrdxgsxfqplbwn\ncvzueihalytomrdsgsxfqplbln\ncvzueihajytoyaykgsxfqplbwn\ntlzueihajyeomrdkgsxfqplbwn\ncvpueihajytbmrdkgsxfxplbwn\ncvzueihajytomjdkgsxuqplkwn\ncvzueihajygomrdkgkxfqplbwg\ncvzueihajhtomrdkgbxsqplbwn\ncvzurihajytomrdkgsafqplbwx\ncdzuezhajytomrdkgsxrqplbwn\ncvbueihajytotrwkgsxfqplbwn\ncwzkeihajytomrdkgsxfqplbwh\ncvzheihajytolrikgsxfqplbwn\ncozuevhajytomrdkgkxfqplbwn\nchzueihajytomrjkgsxfqulbwn\ncvzueihkjyromrdkgsxvqplbwn\ncvzveihajytomrdkgsxpqplnwn\ncvzueihajytoirdkgsxfqihbwn\ncvoueihajytomrdkgsxfqpdawn\npvzueihajytomrdkgnxfqplbfn\ncvzueihakytomxdkgssfqplbwn\ncvzueivajytomrdbgsxaqplbwn\ncvzueihajytokrdkgszrqplbwn\ncvzuevhajytomrdkgsxgqplbwi\ncvzueihajylomrdkgsxflplbpn\nhvzueihajytomvdkgsxfqplgwn\ncvzleihajytymrrkgsxfqplbwn\ncrzueieajytomrdkgsxfqplbon\ncszueihajytomrdlgqxfqplbwn\ncvzueihacytomrdkgsxfjblbwn\ncvzreihajytomrdkgsxfqplzun\ncvzurihajytomrdkgsxiqplawn\nuvzueihajyhovrdkgsxfqplbwn\ncvzueihajyqodrdkgssfqplbwn\ncvzwiihrjytomrdkgsxfqplbwn\ncqzueihajytomrdkgjxfqplban\ncvmueihajytoordkgsxfqplbyn\ncypueihajytomrdkgzxfqplbwn\ncvzueihajykomrdkgsmfqplbtn\ncvzueidajytimrdkgsxfqpdbwn\ncvzheihajytomrdkgsxfqpfewn\ndvzueihajytumrdzgsxfqplbwn\ncvzueixajytomrdkgsvfqplgwn\ncvzuevhzjyzomrdkgsxfqplbwn\ncvyeeihajytomrdkgsxnqplbwn\ncvzueihajytomrdkggtpqplbwn\ncvzceiyajytomrdkgexfqplbwn\ncvzuelhajyyomrdkzsxfqplbwn\ncvzhzihajygomrdkgsxfqplbwn\ncvzueihwjytomrdkgsgfqplbrn\ncvzsevhajytomrdkgqxfqplbwn\ncvzueiuajytomrdkgsxfppebwn\nnvzueihajytemrdkgsxwqplbwn\ncvzueihajytocgdkgsxfqvlbwn\ncczusihajytomrdkgsxfqplbpn\ncmzueihajytomrdkbsxwqplbwn\ncvzumfdajytomrdkgsxfqplbwn\ncvzueihcjytomrdkgsxfqplbkl\ncvzueihajytomawknsxfqplbwn\nkvzueihijytomrdkgsxdqplbwn\ncdzutihajytomrdkgsxfkplbwn\ncvzufihadylomrdkgsxfqplbwn\ncvzueihajytomrgkxsxfqphbwn\ncvzuewhajyzomrdkgsxfqelbwn\ncvzueihajytomrdkgqxfqelbwc\ncvzueshajyoomrdkgsxfqflbwn\ncvzueihajyromrekgixfqplbwn\nchzugihajytomrdkgsxfqplawn\ncvzueihajytomrdkgsxfhpmbwy\ncvzueihacytodxdkgsxfqplbwn\ncvzurihajytourdkgsdfqplbwn\ncvzzeihmjytomrddgsxfqplbwn\ncvzucyhajygomrdkgsxfqplbwn\nckzueihzjytomrdkgsxwqplbwn\ncvlueihajmtozrdkgsxfqplbwn\ncvzkeihajytomrdkgsxfqclbwc\ncvzueihajytomrdkgsxgdplbwa\ncvzueihyjytoxrdkgcxfqplbwn\ncvzueizavytomfdkgsxfqplbwn\ncvzueihajwtosrdkgsxfqllbwn\ncvzueihajytomrdaksxfqpllwn\ncvzuuihojytombdkgsxfqplbwn\ncvzuiibajytpmrdkgsxfqplbwn\ncvzueihajyuomydkgsxfqplzwn\ncvzueihajytimrmkgsxfqplfwn\ncvzueihajytomrdkgzxfqpljwo' boxes = boxes.split('\n') def has_two(s): d = {} for c in s: d[c] = d.get(c, 0) + 1 return 2 in d.values() def has_three(s): d = {} for c in s: d[c] = d.get(c, 0) + 1 return 3 in d.values() twos = sum(map(int, map(has_two, boxes))) threes = sum(map(int, map(has_three, boxes))) checksum = twos * threes def has_match(ss): d = {} for s in ss: for ri in range(0, len(s)): c = s[:ri] + s[ri + 1:] d[c, ri] = d.get((c, ri), 0) + 1 for key in d: if d[key] == 2: return (key, d) return (None, d) (match, matchd) = has_match(boxes)
# T Y P E O F V E R B S def pert_subjective_verbs(texts_tokens): total_verbs = 0 total_subj_verbs = 0 return def pert_report_verbs(text_tokens): return def pert_factive_verbs(text_tokens): return def pert_imperative_commands(text_tokens): return
def pert_subjective_verbs(texts_tokens): total_verbs = 0 total_subj_verbs = 0 return def pert_report_verbs(text_tokens): return def pert_factive_verbs(text_tokens): return def pert_imperative_commands(text_tokens): return
""" AnalysisPipeline operators """ class AnalysisOperation: """ An analysis task performed by an AnalysisPipeline. This is an internal class that facilitates keeping track of a function, arguments, and keyword arguments that together represent a single operation in a pipeline. Parameters ---------- function : callable A function that minimally accepts a :class:`~ytree.data_structures.tree_node.TreeNode` object. The function may also accept additional positional and keyword arguments. """ def __init__(self, function, *args, **kwargs): self.function = function self.args = args self.kwargs = kwargs def __call__(self, target): return self.function(target, *self.args, **self.kwargs)
""" AnalysisPipeline operators """ class Analysisoperation: """ An analysis task performed by an AnalysisPipeline. This is an internal class that facilitates keeping track of a function, arguments, and keyword arguments that together represent a single operation in a pipeline. Parameters ---------- function : callable A function that minimally accepts a :class:`~ytree.data_structures.tree_node.TreeNode` object. The function may also accept additional positional and keyword arguments. """ def __init__(self, function, *args, **kwargs): self.function = function self.args = args self.kwargs = kwargs def __call__(self, target): return self.function(target, *self.args, **self.kwargs)
load("@rules_python//python:defs.bzl", "py_test") pycoverage_requirements = [ "//tools/pycoverage", ] def pycoverage(name, deps): if not name or not deps: fail("Arguments 'name' and 'deps' are required") py_test( name = name, main = "pycoverage_runner.py", srcs = ["//tools/pycoverage:pycoverage_runner"], imports = ["."], args = deps, deps = depset(direct = deps + pycoverage_requirements).to_list(), )
load('@rules_python//python:defs.bzl', 'py_test') pycoverage_requirements = ['//tools/pycoverage'] def pycoverage(name, deps): if not name or not deps: fail("Arguments 'name' and 'deps' are required") py_test(name=name, main='pycoverage_runner.py', srcs=['//tools/pycoverage:pycoverage_runner'], imports=['.'], args=deps, deps=depset(direct=deps + pycoverage_requirements).to_list())
filename = "test2.txt" tree = [None]*16 with open(filename) as f: line = f.readline().strip().strip('[]') for c in line: if c == ',': continue for line in f: n = line.strip().strip('[]') print(n)
filename = 'test2.txt' tree = [None] * 16 with open(filename) as f: line = f.readline().strip().strip('[]') for c in line: if c == ',': continue for line in f: n = line.strip().strip('[]') print(n)
class Solution: def searchMatrix(self, matrix, target): i, j, r = 0, len(matrix[0]) - 1, len(matrix) while i < r and j >= 0: if matrix[i][j] == target: return True elif matrix[i][j] > target: j -= 1 elif matrix[i][j] < target: i += 1 return False
class Solution: def search_matrix(self, matrix, target): (i, j, r) = (0, len(matrix[0]) - 1, len(matrix)) while i < r and j >= 0: if matrix[i][j] == target: return True elif matrix[i][j] > target: j -= 1 elif matrix[i][j] < target: i += 1 return False
def setUpModule() -> None: print("[Module sserender Test Start]") def tearDownModule() -> None: print("[Module sserender Test End]")
def set_up_module() -> None: print('[Module sserender Test Start]') def tear_down_module() -> None: print('[Module sserender Test End]')
print('begin program') # This program says hello and asks for my name. print('Hello, World!') print('What is your name?') myName = input() print('It is good to meet you, ' + myName) print('end program')
print('begin program') print('Hello, World!') print('What is your name?') my_name = input() print('It is good to meet you, ' + myName) print('end program')
""" Mehmet Said Turken 180401030""" dosya = open("veriler.txt.txt", "r") veri = [] for i in dosya.read().split(): veri.append(int(i)) n = len(veri) yitoplam = sum(veri) def x_degerleri(list, n): valuex = [] for i in range(13): x = 0 for k in range(n): x += (k+1)**i valuex.append(x) return valuex def toplam_xiyi(list, n): toplam_xiyi = [] for i in range(7): xiyi = 0 for k in range(n): xiyi += ((k+1)**i)*(list[k]) toplam_xiyi.append(xiyi) return toplam_xiyi def gaussyontemi(matris): #EBD (en buyuk deger)--- EBS(en buyuk satir) n = len(matris) for i in range(0, n): EBD = abs(matris[i][i]) EBS = i for k in range(i + 1, n): if abs(matris[k][i]) >EBD: EBD = abs(matris[k][i]) EBS = k for k in range(i, n + 1): temp = matris[EBS][k] matris[EBS][k] = matris[i][k] matris[i][k] = temp for k in range(i + 1, n): c = -matris[k][i] / matris[i][i] for j in range(i, n + 1): if i == j: matris[k][j] = 0 else: matris[k][j] += c * matris[i][j] son = [0 for i in range(n)] for i in range(n - 1, -1, -1): son[i] =matris[i][n] / matris[i][i] for k in range(i - 1, -1, -1): matris[k][n] -= matris[k][i] * son[i] return son #polinomlarin denklemlere yaklastirip katsayilarin return edildigi fonksiyon def liste_cozum(list, n): cozum = [] for i in range(2, 8): degerler = [] for j in range(i): degerler.append([]) for k in range(i): degerler[j].append(x_degerleri(list, n)[k + j]) degerler[j].append(toplam_xiyi(list, n)[j]) if j == i - 1: cozum.append(gaussyontemi(degerler)) degerler.clear() return cozum def deger_st(x, veri, n, yitoplam): #St nin degerini bulacagimiz fonksiyon y_ort = yitoplam / n st = 0 for i in range(n): st += (veri[i] - y_ort) ** 2 return st def sr_korelasyon(x, veri, n, yitoplam): #sr'yi buluyoruz,korelasyon katsayilarini donduruyoruz. sr = 0 for i in range(n): hesaplama = 0 hesaplama += x[0] for j in range(1, len(x)): hesaplama += x[j] * (i + 1) ** j sr += (veri[i] - hesaplama) ** 2 return ((deger_st(x, veri, n, yitoplam) - sr) / deger_st(x, veri, n, yitoplam)) ** (1/2) def korelasyon_list(korelasyon_degerleri, veri, n, yitoplam): deger = [] for i in korelasyon_degerleri: deger.append(sr_korelasyon(i, veri, n, yitoplam)) return deger def optimaldeger(korelasyon_degerleri, veri, n, yitoplam): a = korelasyon_list(korelasyon_degerleri, veri, n, yitoplam) ilk = 150 list = [] for i in range(len(a)): degerr = abs(1-a[i]) if int(degerr) < 0: degerr *= -1 if degerr < ilk: ilk = degerr list.clear() list.append((i+1, a[i])) return list def yaz(): filenew = open("sonuc.txt", "w+") filenew.write("*tum degerler icin**" + "\n") a = 0 for i in liste_cozum(veri, n): filenew.write("\t"+ str(a+1) + ". derece"+ "\n") b = 0 for k in i: filenew.write(str(b+1) + ". deger = " + str(k)+"\n") b += 1 filenew.write("Korelasyon = " + str(korelasyon_list(liste_cozum(veri, n), veri, n, yitoplam)[a])+"\n") a += 1 filenew.write("\n*En uygun polinom ve korelasyon degeri = " + str( optimaldeger(liste_cozum(veri, n), veri, n, yitoplam)[0]) + "*\n") for j in range(len(veri)): a = 0 newlist = [] if(j + 10 > len(veri)): break for l in range(j, j+10): newlist.append(veri[l]) filenew.write("*" + str(j+1) + " ile " + str(j+10) + " arasindaki degerler icin*") filenew.write("\n*En uygun polinom ve korelasyon degeri = " + str( optimaldeger(liste_cozum(newlist, len(newlist)), newlist, len(newlist), sum(newlist))[0]) + "*\n") bas = 1 bit = 10 a = 0 for j in range(len(veri)): newlist = [] if ((bit*a)+10 > len(veri)): break for l in range((bas*a*10), bit*a + 9): newlist.append(veri[l]) filenew.write("**" + str(bas*a*10) + " ile " + str(bit*a + 9) + " arasindaki degerler icin**") filenew.write("\n*En uygun polinom ve korelasyon degeri = " + str(optimaldeger(liste_cozum(newlist, len(newlist)), newlist, len(newlist), sum(newlist))[0]) + "*\n") a += 1 filenew.close() yaz()
""" Mehmet Said Turken 180401030""" dosya = open('veriler.txt.txt', 'r') veri = [] for i in dosya.read().split(): veri.append(int(i)) n = len(veri) yitoplam = sum(veri) def x_degerleri(list, n): valuex = [] for i in range(13): x = 0 for k in range(n): x += (k + 1) ** i valuex.append(x) return valuex def toplam_xiyi(list, n): toplam_xiyi = [] for i in range(7): xiyi = 0 for k in range(n): xiyi += (k + 1) ** i * list[k] toplam_xiyi.append(xiyi) return toplam_xiyi def gaussyontemi(matris): n = len(matris) for i in range(0, n): ebd = abs(matris[i][i]) ebs = i for k in range(i + 1, n): if abs(matris[k][i]) > EBD: ebd = abs(matris[k][i]) ebs = k for k in range(i, n + 1): temp = matris[EBS][k] matris[EBS][k] = matris[i][k] matris[i][k] = temp for k in range(i + 1, n): c = -matris[k][i] / matris[i][i] for j in range(i, n + 1): if i == j: matris[k][j] = 0 else: matris[k][j] += c * matris[i][j] son = [0 for i in range(n)] for i in range(n - 1, -1, -1): son[i] = matris[i][n] / matris[i][i] for k in range(i - 1, -1, -1): matris[k][n] -= matris[k][i] * son[i] return son def liste_cozum(list, n): cozum = [] for i in range(2, 8): degerler = [] for j in range(i): degerler.append([]) for k in range(i): degerler[j].append(x_degerleri(list, n)[k + j]) degerler[j].append(toplam_xiyi(list, n)[j]) if j == i - 1: cozum.append(gaussyontemi(degerler)) degerler.clear() return cozum def deger_st(x, veri, n, yitoplam): y_ort = yitoplam / n st = 0 for i in range(n): st += (veri[i] - y_ort) ** 2 return st def sr_korelasyon(x, veri, n, yitoplam): sr = 0 for i in range(n): hesaplama = 0 hesaplama += x[0] for j in range(1, len(x)): hesaplama += x[j] * (i + 1) ** j sr += (veri[i] - hesaplama) ** 2 return ((deger_st(x, veri, n, yitoplam) - sr) / deger_st(x, veri, n, yitoplam)) ** (1 / 2) def korelasyon_list(korelasyon_degerleri, veri, n, yitoplam): deger = [] for i in korelasyon_degerleri: deger.append(sr_korelasyon(i, veri, n, yitoplam)) return deger def optimaldeger(korelasyon_degerleri, veri, n, yitoplam): a = korelasyon_list(korelasyon_degerleri, veri, n, yitoplam) ilk = 150 list = [] for i in range(len(a)): degerr = abs(1 - a[i]) if int(degerr) < 0: degerr *= -1 if degerr < ilk: ilk = degerr list.clear() list.append((i + 1, a[i])) return list def yaz(): filenew = open('sonuc.txt', 'w+') filenew.write('*tum degerler icin**' + '\n') a = 0 for i in liste_cozum(veri, n): filenew.write('\t' + str(a + 1) + '. derece' + '\n') b = 0 for k in i: filenew.write(str(b + 1) + '. deger = ' + str(k) + '\n') b += 1 filenew.write('Korelasyon = ' + str(korelasyon_list(liste_cozum(veri, n), veri, n, yitoplam)[a]) + '\n') a += 1 filenew.write('\n*En uygun polinom ve korelasyon degeri = ' + str(optimaldeger(liste_cozum(veri, n), veri, n, yitoplam)[0]) + '*\n') for j in range(len(veri)): a = 0 newlist = [] if j + 10 > len(veri): break for l in range(j, j + 10): newlist.append(veri[l]) filenew.write('*' + str(j + 1) + ' ile ' + str(j + 10) + ' arasindaki degerler icin*') filenew.write('\n*En uygun polinom ve korelasyon degeri = ' + str(optimaldeger(liste_cozum(newlist, len(newlist)), newlist, len(newlist), sum(newlist))[0]) + '*\n') bas = 1 bit = 10 a = 0 for j in range(len(veri)): newlist = [] if bit * a + 10 > len(veri): break for l in range(bas * a * 10, bit * a + 9): newlist.append(veri[l]) filenew.write('**' + str(bas * a * 10) + ' ile ' + str(bit * a + 9) + ' arasindaki degerler icin**') filenew.write('\n*En uygun polinom ve korelasyon degeri = ' + str(optimaldeger(liste_cozum(newlist, len(newlist)), newlist, len(newlist), sum(newlist))[0]) + '*\n') a += 1 filenew.close() yaz()
#!/usr/bin/env python ''' primes.py @author: Lorenzo Cipriani <lorenzo1974@gmail.com> @contact: https://www.linkedin.com/in/lorenzocipriani @since: 2017-10-23 @see: ''' primesToFind = 1000000 num = 0 found = 0 def isPrime(num): if num > 1: for i in range(2, num): if (num % i) == 0: return False else: return True else: return False if __name__ == '__main__': print("Search for the first {} prime numbers:".format(primesToFind)) primesList = [] while primesToFind > 0: num += 1 if isPrime(num): primesList.append(num) found += 1 print(found, num) primesToFind -= 1
""" primes.py @author: Lorenzo Cipriani <lorenzo1974@gmail.com> @contact: https://www.linkedin.com/in/lorenzocipriani @since: 2017-10-23 @see: """ primes_to_find = 1000000 num = 0 found = 0 def is_prime(num): if num > 1: for i in range(2, num): if num % i == 0: return False else: return True else: return False if __name__ == '__main__': print('Search for the first {} prime numbers:'.format(primesToFind)) primes_list = [] while primesToFind > 0: num += 1 if is_prime(num): primesList.append(num) found += 1 print(found, num) primes_to_find -= 1
class ExportingTemplate(): def __init__(self, exporting_template_name=None, channel=None, target_sample_rate=None, duration=None, created_date=None, modified_date=None, id=None): self.exporting_template_name = exporting_template_name self.channel = channel self.target_sample_rate = target_sample_rate self.duration = duration self.created_date = created_date self.modified_date = modified_date self.id = id # getting the values @property def value(self): # print('Getting value') return self.exp_tem_name, self.channel, self.target_sample_rate, self.duration, self.created_date, self.modified_date, self.id # setting the values @value.setter def value(self, exporting_template_name, channel, target_sample_rate, duration, created_date, modified_date, id): self.exporting_template_name = exporting_template_name self.target_sample_rate = target_sample_rate self.duration = duration self.created_date = created_date self.modified_date = modified_date self.id = id self.channel = channel # deleting the values @value.deleter def value(self): # print('Deleting value') del self.exporting_template_name, self.channel, self.target_sample_rate, self.duration, self.created_date, self.modified_date, self.id
class Exportingtemplate: def __init__(self, exporting_template_name=None, channel=None, target_sample_rate=None, duration=None, created_date=None, modified_date=None, id=None): self.exporting_template_name = exporting_template_name self.channel = channel self.target_sample_rate = target_sample_rate self.duration = duration self.created_date = created_date self.modified_date = modified_date self.id = id @property def value(self): return (self.exp_tem_name, self.channel, self.target_sample_rate, self.duration, self.created_date, self.modified_date, self.id) @value.setter def value(self, exporting_template_name, channel, target_sample_rate, duration, created_date, modified_date, id): self.exporting_template_name = exporting_template_name self.target_sample_rate = target_sample_rate self.duration = duration self.created_date = created_date self.modified_date = modified_date self.id = id self.channel = channel @value.deleter def value(self): del self.exporting_template_name, self.channel, self.target_sample_rate, self.duration, self.created_date, self.modified_date, self.id
# -*- coding: utf-8 -*- """ indico_payment_stripe ~~~~~~~~~~~~~~~~~~~~~ Indico plugin for Stripe payment support. :license: MIT """ RELEASE = False __version_info__ = ('0', '0', '1') __version__ = '.'.join(__version_info__) __version__ += '-dev' if not RELEASE else '' __author__ = 'NeIC' __homepage__ = 'https://github.com/neicnordic/indico-plugin-stripe'
""" indico_payment_stripe ~~~~~~~~~~~~~~~~~~~~~ Indico plugin for Stripe payment support. :license: MIT """ release = False __version_info__ = ('0', '0', '1') __version__ = '.'.join(__version_info__) __version__ += '-dev' if not RELEASE else '' __author__ = 'NeIC' __homepage__ = 'https://github.com/neicnordic/indico-plugin-stripe'
# Based on container/push.bzl from rules_docker # Also based on pkg/pkg.bzl from bazel_tools # Copyright 2015, 2017 The Bazel Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. load("@io_bazel_rules_docker//container:layer_tools.bzl", _get_layers = "get_from_target") def _quote(filename, protect = "="): """Quote the filename, by escaping = by \\= and \\ by \\""" return filename.replace("\\", "\\\\").replace(protect, "\\" + protect) def _impl(ctx): image = _get_layers(ctx, ctx.label.name, ctx.attr.image) blobsums = image.get("blobsum", []) blobs = image.get("zipped_layer", []) config = image["config"] manifest = image["manifest"] tarball = image.get("legacy") base = ctx.attr.folder mapping = {} if tarball: print("Pushing an image based on a tarball can be very " + "expensive. If the image is the output of a " + "docker_build, consider dropping the '.tar' extension. " + "If the image is checked in, consider using " + "docker_import instead.") mapping[base + "/tarball"] = tarball if config: mapping[base + "/config"] = config if manifest: mapping[base + "/manifest"] = manifest for i, f in enumerate(blobsums): mapping[base + "/digest." + str(i)] = f for i, f in enumerate(blobs): mapping[base + "/layer." + str(i)] = f # Start building the arguments. args = [ "--output=" + ctx.outputs.out.path, "--directory=/", "--mode=0644", "--owner=0.0", "--owner_name=.", ] file_inputs = [] for f_dest_path, target in mapping.items(): target_files = [target] # .files.to_list() if len(target_files) != 1: fail("Each input must describe exactly one file.", attr = "files") file_inputs += target_files args.append("--file=%s=%s" % (_quote(target_files[0].path), f_dest_path)) arg_file = ctx.actions.declare_file(ctx.label.name + ".args") ctx.actions.write(arg_file, "\n".join(args)) ctx.actions.run( inputs = file_inputs + [arg_file], executable = ctx.executable.build_tar, arguments = ["--flagfile", arg_file.path], outputs = [ctx.outputs.out], mnemonic = "TarOCI", use_default_shell_env = True, ) oci_to_tar = rule( attrs = { "folder": attr.string( mandatory = True, ), "image": attr.label( allow_single_file = [".tar"], mandatory = True, doc = "The label of the image to push.", ), # Implicit dependencies. "build_tar": attr.label( default = Label("@bazel_tools//tools/build_defs/pkg:build_tar"), cfg = "host", executable = True, allow_files = True, ), }, implementation = _impl, outputs = { "out": "%{name}.tar", }, )
load('@io_bazel_rules_docker//container:layer_tools.bzl', _get_layers='get_from_target') def _quote(filename, protect='='): """Quote the filename, by escaping = by \\= and \\ by \\""" return filename.replace('\\', '\\\\').replace(protect, '\\' + protect) def _impl(ctx): image = _get_layers(ctx, ctx.label.name, ctx.attr.image) blobsums = image.get('blobsum', []) blobs = image.get('zipped_layer', []) config = image['config'] manifest = image['manifest'] tarball = image.get('legacy') base = ctx.attr.folder mapping = {} if tarball: print('Pushing an image based on a tarball can be very ' + 'expensive. If the image is the output of a ' + "docker_build, consider dropping the '.tar' extension. " + 'If the image is checked in, consider using ' + 'docker_import instead.') mapping[base + '/tarball'] = tarball if config: mapping[base + '/config'] = config if manifest: mapping[base + '/manifest'] = manifest for (i, f) in enumerate(blobsums): mapping[base + '/digest.' + str(i)] = f for (i, f) in enumerate(blobs): mapping[base + '/layer.' + str(i)] = f args = ['--output=' + ctx.outputs.out.path, '--directory=/', '--mode=0644', '--owner=0.0', '--owner_name=.'] file_inputs = [] for (f_dest_path, target) in mapping.items(): target_files = [target] if len(target_files) != 1: fail('Each input must describe exactly one file.', attr='files') file_inputs += target_files args.append('--file=%s=%s' % (_quote(target_files[0].path), f_dest_path)) arg_file = ctx.actions.declare_file(ctx.label.name + '.args') ctx.actions.write(arg_file, '\n'.join(args)) ctx.actions.run(inputs=file_inputs + [arg_file], executable=ctx.executable.build_tar, arguments=['--flagfile', arg_file.path], outputs=[ctx.outputs.out], mnemonic='TarOCI', use_default_shell_env=True) oci_to_tar = rule(attrs={'folder': attr.string(mandatory=True), 'image': attr.label(allow_single_file=['.tar'], mandatory=True, doc='The label of the image to push.'), 'build_tar': attr.label(default=label('@bazel_tools//tools/build_defs/pkg:build_tar'), cfg='host', executable=True, allow_files=True)}, implementation=_impl, outputs={'out': '%{name}.tar'})
# Given an array of strings strs, group the anagrams together. You can return the answer in any order. # An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. # Example 1: # Input: strs = ["eat","tea","tan","ate","nat","bat"] # Output: [["bat"],["nat","tan"],["ate","eat","tea"]] # Example 2: # Input: strs = [""] # Output: [[""]] # Example 3: # Input: strs = ["a"] # Output: [["a"]] # Constraints: # 1 <= strs.length <= 104 # 0 <= strs[i].length <= 100 # strs[i] consists of lower-case English letters. class Solution: def groupAnagrams(self, strs): result = [] lst = [] for i in strs: a = sorted(i) if a in lst: x = lst.index(a) result[x].append(i) else: lst.append(a) result.append([i]) return result
class Solution: def group_anagrams(self, strs): result = [] lst = [] for i in strs: a = sorted(i) if a in lst: x = lst.index(a) result[x].append(i) else: lst.append(a) result.append([i]) return result
instructions = [] for line in open('input.txt', 'r').readlines(): readline = line.strip() instructions.append((readline[0], int(readline[1:]))) directions = { 'E': [1, 0], 'S': [0, -1], 'W': [-1, 0], 'N': [0, 1], } direction = 'E' x, y = 0, 0 for action, value in instructions: if action in [*directions]: x += directions[action][0] * value y += directions[action][1] * value elif action in ['L', 'R']: idx = [*directions].index(direction) idx += (-1 if action == 'L' else 1) * (value // 90) direction = [*directions][idx % 4] elif action == 'F': x += directions[direction][0] * value y += directions[direction][1] * value print(abs(x) + abs(y))
instructions = [] for line in open('input.txt', 'r').readlines(): readline = line.strip() instructions.append((readline[0], int(readline[1:]))) directions = {'E': [1, 0], 'S': [0, -1], 'W': [-1, 0], 'N': [0, 1]} direction = 'E' (x, y) = (0, 0) for (action, value) in instructions: if action in [*directions]: x += directions[action][0] * value y += directions[action][1] * value elif action in ['L', 'R']: idx = [*directions].index(direction) idx += (-1 if action == 'L' else 1) * (value // 90) direction = [*directions][idx % 4] elif action == 'F': x += directions[direction][0] * value y += directions[direction][1] * value print(abs(x) + abs(y))
a = [ 1, 2, 3, 4, 5 ] print(a) print(a[0]) for i in range(len(a)): print(a[i]) a.append(10) a.append(20) print(a)
a = [1, 2, 3, 4, 5] print(a) print(a[0]) for i in range(len(a)): print(a[i]) a.append(10) a.append(20) print(a)
def buble_sort(nums): for i in range(1, len(nums)): if nums[i] < nums[i - 1]: nums[i], nums[i - 1] = nums[i - 1], nums[i] def check_sort(nums): for i in range(1, len(nums)): if nums[i] < nums[i - 1]: return False return True def main(): count_nums = int(input()) nums = list(map(int, input().split())) if check_sort(nums): print(*nums) else: while not check_sort(nums): buble_sort(nums) print(*nums) if __name__ == '__main__': main()
def buble_sort(nums): for i in range(1, len(nums)): if nums[i] < nums[i - 1]: (nums[i], nums[i - 1]) = (nums[i - 1], nums[i]) def check_sort(nums): for i in range(1, len(nums)): if nums[i] < nums[i - 1]: return False return True def main(): count_nums = int(input()) nums = list(map(int, input().split())) if check_sort(nums): print(*nums) else: while not check_sort(nums): buble_sort(nums) print(*nums) if __name__ == '__main__': main()
def temperature_statistics(t): mean = sum(t)/len(t) return mean, (sum((val-mean)**2 for val in t)/len(t))**0.5 print(temperature_statistics([4.4, 4.2, 7.0, 12.9, 18.5, 23.5, 26.4, 26.3, 22.5, 16.6, 11.2, 7.3]))
def temperature_statistics(t): mean = sum(t) / len(t) return (mean, (sum(((val - mean) ** 2 for val in t)) / len(t)) ** 0.5) print(temperature_statistics([4.4, 4.2, 7.0, 12.9, 18.5, 23.5, 26.4, 26.3, 22.5, 16.6, 11.2, 7.3]))
"""Top-level package for diffcalc-core.""" __author__ = """Diamond Light Source Ltd. - Scientific Software""" __email__ = "scientificsoftware@diamond.ac.uk" __version__ = "0.3.0"
"""Top-level package for diffcalc-core.""" __author__ = 'Diamond Light Source Ltd. - Scientific Software' __email__ = 'scientificsoftware@diamond.ac.uk' __version__ = '0.3.0'
# Helper function to print out relation between losses and network parameters # loss_list given as: [(name, loss_variable), ...] # named_parameters_list using pytorch function named_parameters(): [(name, network.named_parameters()), ...] def print_loss_params_relation(loss_list, named_parameters_list): loss_variables = {} for name, loss in loss_list: if loss.grad_fn is None: variables_ = [] else: def recursive_sub(loss): r = [] if hasattr(loss, 'next_functions'): for el, _ in loss.next_functions: if el is None: continue if hasattr(el, 'variable'): r.append(el.variable) else: r += recursive_sub(el) return r variables_ = recursive_sub(loss=loss.grad_fn) loss_variables[name] = variables_ # Assign params to networks and check for affection max_char_length = 0 affected_network_params = {} for network_name, named_parameters in named_parameters_list: affected_params = {} for n, p in named_parameters: # Ignore bias since this will just duplicate the outcome if (p.requires_grad) and ('bias' not in n): for loss_name in loss_variables.keys(): # Skip if loss_name is already existing in affected params if n in affected_params.keys() and loss_name in affected_params[n]: continue # Iterate through all variables for v in loss_variables[loss_name]: if v.shape == p.shape and (v.data == p.data).all(): if n in affected_params.keys(): affected_params[n].append(loss_name) else: affected_params[n] = [loss_name] max_char_length = len(n) if len(n) > max_char_length else max_char_length # Exit for after assigning loss name to param break affected_network_params[network_name] = affected_params # Print out for network_name in affected_network_params.keys(): print(f'Affected Params for {network_name}:') if len(affected_network_params[network_name].keys()) == 0: print('\t-') else: for p_name in affected_network_params[network_name].keys(): print(f'\t{p_name}:{" " * (max_char_length - len(p_name))}\t{affected_network_params[network_name][p_name]}') print('')
def print_loss_params_relation(loss_list, named_parameters_list): loss_variables = {} for (name, loss) in loss_list: if loss.grad_fn is None: variables_ = [] else: def recursive_sub(loss): r = [] if hasattr(loss, 'next_functions'): for (el, _) in loss.next_functions: if el is None: continue if hasattr(el, 'variable'): r.append(el.variable) else: r += recursive_sub(el) return r variables_ = recursive_sub(loss=loss.grad_fn) loss_variables[name] = variables_ max_char_length = 0 affected_network_params = {} for (network_name, named_parameters) in named_parameters_list: affected_params = {} for (n, p) in named_parameters: if p.requires_grad and 'bias' not in n: for loss_name in loss_variables.keys(): if n in affected_params.keys() and loss_name in affected_params[n]: continue for v in loss_variables[loss_name]: if v.shape == p.shape and (v.data == p.data).all(): if n in affected_params.keys(): affected_params[n].append(loss_name) else: affected_params[n] = [loss_name] max_char_length = len(n) if len(n) > max_char_length else max_char_length break affected_network_params[network_name] = affected_params for network_name in affected_network_params.keys(): print(f'Affected Params for {network_name}:') if len(affected_network_params[network_name].keys()) == 0: print('\t-') else: for p_name in affected_network_params[network_name].keys(): print(f"\t{p_name}:{' ' * (max_char_length - len(p_name))}\t{affected_network_params[network_name][p_name]}") print('')
# %% [287. Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number/) class Solution: def findDuplicate(self, nums: List[int]) -> int: for i, v in enumerate(nums, 1): if v in nums[i:]: return v
class Solution: def find_duplicate(self, nums: List[int]) -> int: for (i, v) in enumerate(nums, 1): if v in nums[i:]: return v
def staircase(n): asteriscos = 1 # Write your code here for espacios in range(n, 0, -1): for i in range (espacios): print(' ', end='') for j in range(asteriscos): print('*', end='') print() asteriscos+=2 staircase(7)
def staircase(n): asteriscos = 1 for espacios in range(n, 0, -1): for i in range(espacios): print(' ', end='') for j in range(asteriscos): print('*', end='') print() asteriscos += 2 staircase(7)
#!/usr/bin/env python class Host(object): def __init__(self, name, groups,region, image, tags, size, meta=None): self.name = name self.groups = groups self.meta = meta or {} self.region = region self.image = image self.tags = tags self.size = size swifty_hosts = [ Host( name='swifty-gw-iac', region = 'ams3', image = 'ubuntu-18-04-x64', size = "s-2vcpu-4gb", tags = 'iac', groups=['gw'], meta={ 'vpn_ip': '192.168.0.1', 'public_dns': 'api.infra-ci.swifty.cloud', 'tinc_hostname': 'swygw' } ), Host( name='swifty-mw-iac', region = 'ams3', image = 'ubuntu-18-04-x64', size = "s-2vcpu-4gb", tags = 'iac', groups=['mw'], meta={ 'vpn_ip': '192.168.0.2', 'public_dns': 's3.infra-ci.swifty.cloud', 'tinc_hostname': 'swymw' } ), Host( name='swifty-dashboard-iac', region = 'ams3', image = 'ubuntu-18-04-x64', size = "s-1vcpu-2gb", tags = 'iac', groups=['ui'], meta={ 'vpn_ip': '192.168.0.3', 'public_dns': 'dashboard.infra-ci.swifty.cloud', 'tinc_hostname': 'swyui' } ), Host( name='swifty-connector-iac', region = 'ams3', image = 'ubuntu-18-04-x64', size = "s-1vcpu-2gb", tags = 'iac', groups=['connector'], meta={ 'vpn_ip': '192.168.0.4', 'public_dns': 'connector.infra-ci.swifty.cloud', 'tinc_hostname': 'swyconnector' } ), Host( name='swifty-worker0-iac', region = 'ams3', image = 'ubuntu-18-04-x64', size = "s-2vcpu-4gb", tags = 'iac', groups=['worker'], meta={ 'vpn_ip': '192.168.0.5', 'public_dns': 'worker0.infra-ci.swifty.cloud', 'tinc_hostname': 'swyworker0' } ), Host( name='swifty-worker1-iac', region = 'ams3', image = 'ubuntu-18-04-x64', size = "s-2vcpu-4gb", tags = 'iac', groups=['worker'], meta={ 'vpn_ip': '192.168.0.6', 'public_dns': 'worker1.infra-ci.swifty.cloud', 'tinc_hostname': 'swyworker1' } ), ]
class Host(object): def __init__(self, name, groups, region, image, tags, size, meta=None): self.name = name self.groups = groups self.meta = meta or {} self.region = region self.image = image self.tags = tags self.size = size swifty_hosts = [host(name='swifty-gw-iac', region='ams3', image='ubuntu-18-04-x64', size='s-2vcpu-4gb', tags='iac', groups=['gw'], meta={'vpn_ip': '192.168.0.1', 'public_dns': 'api.infra-ci.swifty.cloud', 'tinc_hostname': 'swygw'}), host(name='swifty-mw-iac', region='ams3', image='ubuntu-18-04-x64', size='s-2vcpu-4gb', tags='iac', groups=['mw'], meta={'vpn_ip': '192.168.0.2', 'public_dns': 's3.infra-ci.swifty.cloud', 'tinc_hostname': 'swymw'}), host(name='swifty-dashboard-iac', region='ams3', image='ubuntu-18-04-x64', size='s-1vcpu-2gb', tags='iac', groups=['ui'], meta={'vpn_ip': '192.168.0.3', 'public_dns': 'dashboard.infra-ci.swifty.cloud', 'tinc_hostname': 'swyui'}), host(name='swifty-connector-iac', region='ams3', image='ubuntu-18-04-x64', size='s-1vcpu-2gb', tags='iac', groups=['connector'], meta={'vpn_ip': '192.168.0.4', 'public_dns': 'connector.infra-ci.swifty.cloud', 'tinc_hostname': 'swyconnector'}), host(name='swifty-worker0-iac', region='ams3', image='ubuntu-18-04-x64', size='s-2vcpu-4gb', tags='iac', groups=['worker'], meta={'vpn_ip': '192.168.0.5', 'public_dns': 'worker0.infra-ci.swifty.cloud', 'tinc_hostname': 'swyworker0'}), host(name='swifty-worker1-iac', region='ams3', image='ubuntu-18-04-x64', size='s-2vcpu-4gb', tags='iac', groups=['worker'], meta={'vpn_ip': '192.168.0.6', 'public_dns': 'worker1.infra-ci.swifty.cloud', 'tinc_hostname': 'swyworker1'})]
''' Given an array of meeting time intervals intervals where intervals[i] = [starti, endi], return the minimum number of conference rooms required. Example 1: Input: intervals = [[0,30],[5,10],[15,20]] Output: 2 Example 2: Input: intervals = [[7,10],[2,4]] Output: 1 ''' #Approach 1: Priority Queues ''' Algorithm A) Sort the given meetings by their start time. B) Initialize a new min-heap and add the first meeting's ending time to the heap. We simply need to keep track of the ending times as that tells us when a meeting room will get free. C) For every meeting room check if the minimum element of the heap i.e. the room at the top of the heap is free or not. D) If the room is free, then we extract the topmost element and add it back with the ending time of the current meeting we are processing. E) If not, then we allocate a new room and add it to the heap. F) After processing all the meetings, the size of the heap will tell us the number of rooms allocated. This will be the minimum number of rooms needed to accommodate all the meetings. ''' class Solution(object): def minMeetingRooms(self, intervals): # MIN Heap (Priority QUEUE) TC (NLOGN), SPACE (N) if not intervals: return 0 intervals, res = sorted(intervals, key=lambda elem:elem[0]), [] # Add and create room for first meeting heapq.heappush(res, intervals[0][1]) # for rest of meeting rooms for elem in intervals[1:]: # if room due to free up the earliest is free, assign room to this meeting if res[0] <= elem[0]: heapq.heappop(res) #if new room assign then add to heap. If old room allocated, then add to heap with updated end time heapq.heappush(res, elem[1]) # size of heap minimum rooms required return len(res) #Approach 2: Chronological Ordering ''' Algorithm A) Separate out the start times and the end times in their separate arrays. B) Sort the start times and the end times separately. Note that this will mess up the original correspondence of start times and end times. They will be treated individually now. C) We consider two pointers: s_ptr and e_ptr which refer to start pointer and end pointer. The start pointer simply iterates over all the meetings and the end pointer helps us track if a meeting has ended and if we can reuse a room. D) When considering a specific meeting pointed to by s_ptr, we check if this start timing is greater than the meeting pointed to by e_ptr. E) If this is the case then that would mean some meeting has ended by the time the meeting at s_ptr had to start. So we can reuse one of the rooms. Otherwise, we have to allocate a new room. If a meeting has indeed ended i.e. if start[s_ptr] >= end[e_ptr], then we increment e_ptr. F) Repeat this process until s_ptr processes all of the meetings. ''' class Solution(object): def minMeetingRooms(self, intervals): # Chronocial Ordering TC (NLOGN) and Space (N) if not intervals: return 0 res = 0 #sort start and end time start_time = sorted([elem[0] for elem in intervals]) end_time = sorted([elem[1] for elem in intervals]) # define two pointer start_ptr, end_ptr = 0, 0 # untill all meeting room assigned while start_ptr < len(intervals): #if there is meeting ended by time the meeting at start_ptr starts if start_time[start_ptr] >= end_time[end_ptr]: # FreeUp rooma nd increment end_ptr res -= 1 end_ptr += 1 #if room got free then res += 1 wouldn't effective. res would remains same in that case. If room will not free then increase room res += 1 start_ptr += 1 return res
""" Given an array of meeting time intervals intervals where intervals[i] = [starti, endi], return the minimum number of conference rooms required. Example 1: Input: intervals = [[0,30],[5,10],[15,20]] Output: 2 Example 2: Input: intervals = [[7,10],[2,4]] Output: 1 """ "\nAlgorithm\n\nA) Sort the given meetings by their start time.\nB) Initialize a new min-heap and add the first meeting's ending time to the heap. We simply need to keep track of the ending times as that tells us when a meeting room will\nget free.\nC) For every meeting room check if the minimum element of the heap i.e. the room at the top of the heap is free or not.\nD) If the room is free, then we extract the topmost element and add it back with the ending time of the current meeting we are processing.\nE) If not, then we allocate a new room and add it to the heap.\nF) After processing all the meetings, the size of the heap will tell us the number of rooms allocated. \nThis will be the minimum number of rooms needed to accommodate all the meetings.\n" class Solution(object): def min_meeting_rooms(self, intervals): if not intervals: return 0 (intervals, res) = (sorted(intervals, key=lambda elem: elem[0]), []) heapq.heappush(res, intervals[0][1]) for elem in intervals[1:]: if res[0] <= elem[0]: heapq.heappop(res) heapq.heappush(res, elem[1]) return len(res) '\nAlgorithm\n\nA) Separate out the start times and the end times in their separate arrays.\nB) Sort the start times and the end times separately. Note that this will mess up the original correspondence of start times and end times.\nThey will be treated individually now.\nC) We consider two pointers: s_ptr and e_ptr which refer to start pointer and end pointer. \nThe start pointer simply iterates over all the meetings and the end pointer helps us track if a meeting has ended and if we can reuse a room.\nD) When considering a specific meeting pointed to by s_ptr, we check if this start timing is greater than the meeting pointed to by e_ptr. \nE) If this is the case then that would mean some meeting has ended by the time the meeting at s_ptr had to start. So we can reuse one of the rooms. Otherwise, we have to allocate a new room.\nIf a meeting has indeed ended i.e. if start[s_ptr] >= end[e_ptr], then we increment e_ptr.\nF) Repeat this process until s_ptr processes all of the meetings.\n' class Solution(object): def min_meeting_rooms(self, intervals): if not intervals: return 0 res = 0 start_time = sorted([elem[0] for elem in intervals]) end_time = sorted([elem[1] for elem in intervals]) (start_ptr, end_ptr) = (0, 0) while start_ptr < len(intervals): if start_time[start_ptr] >= end_time[end_ptr]: res -= 1 end_ptr += 1 res += 1 start_ptr += 1 return res
#!/usr/bin/env python3.5 #-*- coding: utf-8 -*- def foo(s): n = int(s) assert n != 0, 'n is zero!' return 10 / n def main(): foo('0') main()
def foo(s): n = int(s) assert n != 0, 'n is zero!' return 10 / n def main(): foo('0') main()
# -*- coding: UTF-8 -*- # # You are given an n x n 2D matrix representing an image. # # Rotate the image by 90 degrees (clockwise). # # Note: # You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. # # Example 1: # # Given input matrix = # [ # [1,2,3], # [4,5,6], # [7,8,9] # ], # # rotate the input matrix in-place such that it becomes: # [ # [7,4,1], # [8,5,2], # [9,6,3] # ] # Example 2: # # Given input matrix = # [ # [ 5, 1, 9,11], # [ 2, 4, 8,10], # [13, 3, 6, 7], # [15,14,12,16] # ], # # rotate the input matrix in-place such that it becomes: # [ # [15,13, 2, 5], # [14, 3, 4, 1], # [12, 6, 8, 9], # [16, 7,10,11] # ] # # Python, Python3 all accepted. class RotateImage: def rotate(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ length = len(matrix) for i in range(length // 2): j = length - 1 - i cache = matrix[i] matrix[i] = matrix[j] matrix[j] = cache for i in range(length): for j in range(i + 1, length): cache = matrix[i][j] matrix[i][j] = matrix[j][i] matrix[j][i] = cache
class Rotateimage: def rotate(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ length = len(matrix) for i in range(length // 2): j = length - 1 - i cache = matrix[i] matrix[i] = matrix[j] matrix[j] = cache for i in range(length): for j in range(i + 1, length): cache = matrix[i][j] matrix[i][j] = matrix[j][i] matrix[j][i] = cache
class Libro: def __init__(self, paginas, tapa,nombre, autor, genero, isbn): self.paginas = paginas self.tapa = tapa self.nombre= nombre self.autor = autor self.genero = genero self.isbn = isbn def set_nombre(self,nombre): self.nombre = nombre def set_paginas(self,paginas): self.paginas = paginas def set_tapa(self,tapa): self.tapa = tapa def set_autor(self,autor): self.autor = autor def set_genero(self,genero): self.genero = genero def set_isbn(self,isbn): self.isbn = isbn
class Libro: def __init__(self, paginas, tapa, nombre, autor, genero, isbn): self.paginas = paginas self.tapa = tapa self.nombre = nombre self.autor = autor self.genero = genero self.isbn = isbn def set_nombre(self, nombre): self.nombre = nombre def set_paginas(self, paginas): self.paginas = paginas def set_tapa(self, tapa): self.tapa = tapa def set_autor(self, autor): self.autor = autor def set_genero(self, genero): self.genero = genero def set_isbn(self, isbn): self.isbn = isbn
# # @lc app=leetcode id=68 lang=python3 # # [68] Text Justification # class Solution: def split(self, words: List[str], maxWidth: int) -> List[List[str]]: if not words: return [] lines, cur_len = [[words[0]]], len(words[0]) for w in words[1:]: if cur_len + 1 + len(w) <= maxWidth: lines[-1].append(w) cur_len += 1 + len(w) else: lines.append([w]) cur_len = len(w) return lines def justify(self, words: List[str], width: int, full: bool = False) -> str: word_len = sum(map(len, words)) space_len = width - word_len space_cnt = len(words) - 1 if space_cnt == 0: return words[0] + ' ' * space_len if full: return ' '.join(words) + ' ' * (space_len - space_cnt) space_sizes = [0] * (space_cnt + 1) while space_cnt > 0: sz = space_len // space_cnt space_sizes[space_cnt - 1] = sz space_len -= sz space_cnt -= 1 return ''.join(w + ' ' * sz for w, sz in zip(words, space_sizes)) def fullJustify(self, words: List[str], maxWidth: int) -> List[str]: lines = self.split(words, maxWidth) lines[-1] = self.justify(lines[-1], maxWidth, full=True) for i in range(len(lines) - 1): lines[i] = self.justify(lines[i], maxWidth) return lines
class Solution: def split(self, words: List[str], maxWidth: int) -> List[List[str]]: if not words: return [] (lines, cur_len) = ([[words[0]]], len(words[0])) for w in words[1:]: if cur_len + 1 + len(w) <= maxWidth: lines[-1].append(w) cur_len += 1 + len(w) else: lines.append([w]) cur_len = len(w) return lines def justify(self, words: List[str], width: int, full: bool=False) -> str: word_len = sum(map(len, words)) space_len = width - word_len space_cnt = len(words) - 1 if space_cnt == 0: return words[0] + ' ' * space_len if full: return ' '.join(words) + ' ' * (space_len - space_cnt) space_sizes = [0] * (space_cnt + 1) while space_cnt > 0: sz = space_len // space_cnt space_sizes[space_cnt - 1] = sz space_len -= sz space_cnt -= 1 return ''.join((w + ' ' * sz for (w, sz) in zip(words, space_sizes))) def full_justify(self, words: List[str], maxWidth: int) -> List[str]: lines = self.split(words, maxWidth) lines[-1] = self.justify(lines[-1], maxWidth, full=True) for i in range(len(lines) - 1): lines[i] = self.justify(lines[i], maxWidth) return lines
""" Build microservices with Python """ __author__ = "Vlad Calin" __email__ = "vlad.s.calin@gmail.com" __version__ = "0.12.0"
""" Build microservices with Python """ __author__ = 'Vlad Calin' __email__ = 'vlad.s.calin@gmail.com' __version__ = '0.12.0'
# # Copyright 2020- IBM Inc. All rights reserved # SPDX-License-Identifier: Apache2.0 # class K8sNamespace: """ Represents a K8s Namespace, storing its name and labels """ def __init__(self, name): self.name = name self.labels = {} # Storing the namespace labels in a dict as key-value pairs def __eq__(self, other): if isinstance(other, K8sNamespace): return self.name == other.name return NotImplemented def __hash__(self): return hash(self.name) def __str__(self): return self.name def set_label(self, key, value): """ Add/update a namespace label :param str key: The label key :param str value: The label value :return: None """ self.labels[key] = value
class K8Snamespace: """ Represents a K8s Namespace, storing its name and labels """ def __init__(self, name): self.name = name self.labels = {} def __eq__(self, other): if isinstance(other, K8sNamespace): return self.name == other.name return NotImplemented def __hash__(self): return hash(self.name) def __str__(self): return self.name def set_label(self, key, value): """ Add/update a namespace label :param str key: The label key :param str value: The label value :return: None """ self.labels[key] = value
class Solution(object): def numEquivDominoPairs(self, dominoes): """ :type dominoes: List[List[int]] :rtype: int """ hashmap = dict() for a, b in dominoes: key = tuple([min(a, b), max(a, b)]) hashmap[key] = hashmap.setdefault(key, 0) + 1 count = 0 for v in hashmap.values(): count += v * (v - 1) return count // 2
class Solution(object): def num_equiv_domino_pairs(self, dominoes): """ :type dominoes: List[List[int]] :rtype: int """ hashmap = dict() for (a, b) in dominoes: key = tuple([min(a, b), max(a, b)]) hashmap[key] = hashmap.setdefault(key, 0) + 1 count = 0 for v in hashmap.values(): count += v * (v - 1) return count // 2
def update_data(hyper_params): return dict( train=dict( samples_per_gpu=hyper_params['batch_size'], workers_per_gpu=hyper_params['workers_per_gpu'], dataset=dict( root_dir=hyper_params['dataset_root'], cifar_type=hyper_params['dataset_name'], noise_mode=hyper_params['noise_mode'], noise_ratio=hyper_params['noise_ratio'] ) ), test=dict( samples_per_gpu=hyper_params['batch_size'] * 4, workers_per_gpu=hyper_params['workers_per_gpu'], dataset=dict( root_dir=hyper_params['dataset_root'], cifar_type=hyper_params['dataset_name'] ) ), eval=dict( samples_per_gpu=hyper_params['batch_size'] * 4, workers_per_gpu=hyper_params['workers_per_gpu'], ) ) def update_openset_data(hyper_params): return dict( train=dict( samples_per_gpu=hyper_params['batch_size'], workers_per_gpu=hyper_params['workers_per_gpu'], dataset=dict( root_dir=hyper_params['dataset_root'], cifar_type=hyper_params['dataset_name'], noise_mode=hyper_params['noise_mode'], noise_ratio=hyper_params['noise_ratio'], ood_noise_name=hyper_params['ood_noise_name'], ood_noise_root_dir=hyper_params['ood_noise_root_dir'], ood_noise_num=hyper_params['ood_noise_num_train'] ) ), test=dict( samples_per_gpu=hyper_params['batch_size'] * 4, workers_per_gpu=hyper_params['workers_per_gpu'], dataset=dict( root_dir=hyper_params['dataset_root'], cifar_type=hyper_params['dataset_name'], ood_noise_name=hyper_params['ood_noise_name'], ood_noise_root_dir=hyper_params['ood_noise_root_dir'], ood_noise_num=hyper_params['ood_noise_num_test'] ) ), eval=dict( samples_per_gpu=hyper_params['batch_size'] * 4, workers_per_gpu=hyper_params['workers_per_gpu'], ) ) def update_webvision_data(hyper_params): return dict( train=dict( samples_per_gpu=hyper_params['batch_size'], workers_per_gpu=hyper_params['workers_per_gpu'], ), test=dict( samples_per_gpu=hyper_params['batch_size'] * 4, workers_per_gpu=hyper_params['workers_per_gpu'], ), eval=dict( samples_per_gpu=hyper_params['batch_size'] * 4, workers_per_gpu=hyper_params['workers_per_gpu'], ), imagenet=dict( samples_per_gpu=hyper_params['batch_size'] * 4, workers_per_gpu=8, ) ) def update_model(hyper_params): return dict( head=dict(num_classes=hyper_params['num_classes'], out_feat_dim=hyper_params['feature_dim']), num_classes=hyper_params['num_classes'], alpha=hyper_params['alpha'], data_parallel=hyper_params['data_parallel'] ) def update_solver(hyper_params): return dict( hyper_params=hyper_params, optimizer=dict(lr=hyper_params['lr'], weight_decay=hyper_params.get('weight_decay') or 5e-4), lr_scheduler=dict(T_max=hyper_params['max_epochs']), max_epochs=hyper_params['max_epochs'], )
def update_data(hyper_params): return dict(train=dict(samples_per_gpu=hyper_params['batch_size'], workers_per_gpu=hyper_params['workers_per_gpu'], dataset=dict(root_dir=hyper_params['dataset_root'], cifar_type=hyper_params['dataset_name'], noise_mode=hyper_params['noise_mode'], noise_ratio=hyper_params['noise_ratio'])), test=dict(samples_per_gpu=hyper_params['batch_size'] * 4, workers_per_gpu=hyper_params['workers_per_gpu'], dataset=dict(root_dir=hyper_params['dataset_root'], cifar_type=hyper_params['dataset_name'])), eval=dict(samples_per_gpu=hyper_params['batch_size'] * 4, workers_per_gpu=hyper_params['workers_per_gpu'])) def update_openset_data(hyper_params): return dict(train=dict(samples_per_gpu=hyper_params['batch_size'], workers_per_gpu=hyper_params['workers_per_gpu'], dataset=dict(root_dir=hyper_params['dataset_root'], cifar_type=hyper_params['dataset_name'], noise_mode=hyper_params['noise_mode'], noise_ratio=hyper_params['noise_ratio'], ood_noise_name=hyper_params['ood_noise_name'], ood_noise_root_dir=hyper_params['ood_noise_root_dir'], ood_noise_num=hyper_params['ood_noise_num_train'])), test=dict(samples_per_gpu=hyper_params['batch_size'] * 4, workers_per_gpu=hyper_params['workers_per_gpu'], dataset=dict(root_dir=hyper_params['dataset_root'], cifar_type=hyper_params['dataset_name'], ood_noise_name=hyper_params['ood_noise_name'], ood_noise_root_dir=hyper_params['ood_noise_root_dir'], ood_noise_num=hyper_params['ood_noise_num_test'])), eval=dict(samples_per_gpu=hyper_params['batch_size'] * 4, workers_per_gpu=hyper_params['workers_per_gpu'])) def update_webvision_data(hyper_params): return dict(train=dict(samples_per_gpu=hyper_params['batch_size'], workers_per_gpu=hyper_params['workers_per_gpu']), test=dict(samples_per_gpu=hyper_params['batch_size'] * 4, workers_per_gpu=hyper_params['workers_per_gpu']), eval=dict(samples_per_gpu=hyper_params['batch_size'] * 4, workers_per_gpu=hyper_params['workers_per_gpu']), imagenet=dict(samples_per_gpu=hyper_params['batch_size'] * 4, workers_per_gpu=8)) def update_model(hyper_params): return dict(head=dict(num_classes=hyper_params['num_classes'], out_feat_dim=hyper_params['feature_dim']), num_classes=hyper_params['num_classes'], alpha=hyper_params['alpha'], data_parallel=hyper_params['data_parallel']) def update_solver(hyper_params): return dict(hyper_params=hyper_params, optimizer=dict(lr=hyper_params['lr'], weight_decay=hyper_params.get('weight_decay') or 0.0005), lr_scheduler=dict(T_max=hyper_params['max_epochs']), max_epochs=hyper_params['max_epochs'])
class Person: def __init__(self, name, age=21, gender='unspecified', occupation='unspecified'): self.name = name self.gender = gender self.occupation = occupation if age >= 0 and age <= 120: self.age = age else: self.age = 21 def greets(self, greeter): return f'Hello, {greeter}! My name is {self.name}, nice to meet you!' def had_birthday(self): self.age += 1 def set_gender(self, gender): self.gender = gender def get_gender(self): return self.gender
class Person: def __init__(self, name, age=21, gender='unspecified', occupation='unspecified'): self.name = name self.gender = gender self.occupation = occupation if age >= 0 and age <= 120: self.age = age else: self.age = 21 def greets(self, greeter): return f'Hello, {greeter}! My name is {self.name}, nice to meet you!' def had_birthday(self): self.age += 1 def set_gender(self, gender): self.gender = gender def get_gender(self): return self.gender
""" Test group missing the last item .. pii: Group 2 - Annotation 1 .. pii_types: id, name """
""" Test group missing the last item .. pii: Group 2 - Annotation 1 .. pii_types: id, name """
def obj_sort_by_lambda(obj_list, lmbd): new_obj_list = obj_list.copy() new_obj_list.sort(key=lmbd) return new_obj_list def obj_sort_by_property_name(obj_list, prop_name): return obj_sort_by_lambda(obj_list, lambda x:getattr(x, prop_name)) def obj_list_decrypt(obj_list, enc): new_obj_list = [] for obj in obj_list: new_obj_list.append(obj.decrypt(enc)) return new_obj_list
def obj_sort_by_lambda(obj_list, lmbd): new_obj_list = obj_list.copy() new_obj_list.sort(key=lmbd) return new_obj_list def obj_sort_by_property_name(obj_list, prop_name): return obj_sort_by_lambda(obj_list, lambda x: getattr(x, prop_name)) def obj_list_decrypt(obj_list, enc): new_obj_list = [] for obj in obj_list: new_obj_list.append(obj.decrypt(enc)) return new_obj_list
# -*- coding: utf-8 -*- """Top-level package for appliapps.""" __author__ = """Lars Malmstroem""" __email__ = 'lars@malmstroem.net' __version__ = '0.1.0'
"""Top-level package for appliapps.""" __author__ = 'Lars Malmstroem' __email__ = 'lars@malmstroem.net' __version__ = '0.1.0'
class InvalidUrl(Exception): pass class UnableToGetPage(Exception): pass class UnableToGetUploadTime(Exception): pass class UnableToGetApproximateNum(Exception): pass
class Invalidurl(Exception): pass class Unabletogetpage(Exception): pass class Unabletogetuploadtime(Exception): pass class Unabletogetapproximatenum(Exception): pass
# ******************************************************************************************* # ******************************************************************************************* # # Name : error.py # Purpose : Error class # Date : 13th November 2021 # Author : Paul Robson (paul@robsons.org.uk) # # ******************************************************************************************* # ******************************************************************************************* # ******************************************************************************************* # # HPL Exception # # ******************************************************************************************* class HPLException(Exception): def __str__(self): msg = Exception.__str__(self) return msg if HPLException.LINE <= 0 else "{0} ({1}:{2})".format(msg,HPLException.FILE,HPLException.LINE) HPLException.FILE = None HPLException.LINE = 0 if __name__ == '__main__': x = HPLException("Error !!") print(">>",str(x)) raise x
class Hplexception(Exception): def __str__(self): msg = Exception.__str__(self) return msg if HPLException.LINE <= 0 else '{0} ({1}:{2})'.format(msg, HPLException.FILE, HPLException.LINE) HPLException.FILE = None HPLException.LINE = 0 if __name__ == '__main__': x = hpl_exception('Error !!') print('>>', str(x)) raise x
# coding=utf-8 worker_thread_pool = None key_loading_thread_pool = None key_holder = None is_debug = False is_debug_requests = False is_no_validate = False is_only_validate_key = False is_override = False is_preview_filename = False is_resize = False thread_num = 1 src_dir = None dest_dir = None filename_pattern = None filename_replace = None resize_method = None width = None height = None
worker_thread_pool = None key_loading_thread_pool = None key_holder = None is_debug = False is_debug_requests = False is_no_validate = False is_only_validate_key = False is_override = False is_preview_filename = False is_resize = False thread_num = 1 src_dir = None dest_dir = None filename_pattern = None filename_replace = None resize_method = None width = None height = None
from_ = 1 to_ = 999901 # to_ = 1 output_file = open("result.txt", "w", encoding="utf-8") for i in range(from_, to_ + 1, 100): input_file = open("allTags/" + str(i) + ".txt", "r", encoding="utf-8") data = input_file.read() ind = 0 for j in range(100): ind = data.find("class=\"i-tag\"", ind) data = data[ind+1:] x = data.find("#") y = data.find("<", x) tag = data[x + 1:y] data = data[y:] output_file.write(tag + "," + str(i + j) + '\n') input_file.close() output_file.close()
from_ = 1 to_ = 999901 output_file = open('result.txt', 'w', encoding='utf-8') for i in range(from_, to_ + 1, 100): input_file = open('allTags/' + str(i) + '.txt', 'r', encoding='utf-8') data = input_file.read() ind = 0 for j in range(100): ind = data.find('class="i-tag"', ind) data = data[ind + 1:] x = data.find('#') y = data.find('<', x) tag = data[x + 1:y] data = data[y:] output_file.write(tag + ',' + str(i + j) + '\n') input_file.close() output_file.close()
#!/usr/bin/env python3 ''' In this question , we are going to find the longest common substring, among two given substrings. in order to solve this question we will be making use of dynamic programming. so we will create a matrix with all 0s in the initial row and column Step 1: we need to initialise a matrix with size len(String)+1, len(string)+1. Step 2: once you initialise matrix you can start comparing the letter of each string''' def LongestCommonSubstring(X,Y,m,n): LCSmatrix=[[0 for k in range(n+1)] for l in range(m+1)] result=0 for i in range(m+1): for j in range(n+1): if(i==0 or j==0): LCSmatrix[i][j]=0 elif (X[i-1]==Y[j-1]) : LCSmatrix[i][j]=LCSmatrix[i-1][j-1]+1 result= max(result, LCSmatrix[i][j]) else: LCSmatrix[i][j]=0 return result X = 'HELLO' Y = 'HELLOS' m = len(X) n = len(Y) print('Length of Longest Common Substring is', LongestCommonSubstring(X, Y, m, n))
""" In this question , we are going to find the longest common substring, among two given substrings. in order to solve this question we will be making use of dynamic programming. so we will create a matrix with all 0s in the initial row and column Step 1: we need to initialise a matrix with size len(String)+1, len(string)+1. Step 2: once you initialise matrix you can start comparing the letter of each string""" def longest_common_substring(X, Y, m, n): lc_smatrix = [[0 for k in range(n + 1)] for l in range(m + 1)] result = 0 for i in range(m + 1): for j in range(n + 1): if i == 0 or j == 0: LCSmatrix[i][j] = 0 elif X[i - 1] == Y[j - 1]: LCSmatrix[i][j] = LCSmatrix[i - 1][j - 1] + 1 result = max(result, LCSmatrix[i][j]) else: LCSmatrix[i][j] = 0 return result x = 'HELLO' y = 'HELLOS' m = len(X) n = len(Y) print('Length of Longest Common Substring is', longest_common_substring(X, Y, m, n))
''' Author : Govind Patidar DateTime : 10/07/2020 11:30AM File : AllPageLocators ''' class AllPageLocators(): def __init__(self, driver): ''' :param driver: ''' self.driver = driver '''Home page locator''' # get XPATH current temperature text text_curr_temp = '/html/body/div/div[1]/h2' # get ID current temperature value curr_temp = "temperature" # get XPATH moisturizes text moisturizes = '/html/body/div/div[3]/div[1]/p' # get XPATH buy moisturizes buy_moisturizes = '/html/body/div/div[3]/div[1]/a/button' # get XPATH sunscreens text sunscreens = '/html/body/div/div[3]/div[2]/p' # get XPATH buy sunscreens buy_sunscreens = '/html/body/div/div[3]/div[2]/a/button' '''Checkout page locator''' # get ID in add to cart items add_cart = 'cart' # get ID total amount total_amount = 'total' # get XPATH pay with cart button pay = '/html/body/div[1]/div[3]/form/button/span' '''Payment page''' # get XPATH payment page email = '//input[@type="email"]' cardNo = '//input[@type="tel"]' date = '//input[@placeholder="MM / YY"]' cvc = '//input[@placeholder="CVC"]' zip = '//input[@placeholder="ZIP Code"]' paynow = '//*[@id="container"]/section/span[2]/div/div/main/form/nav/div/div/div/button' '''Payment done''' pay_success = '/html/body/div/div[1]/h2' pay_text = '/html/body/div/div[2]/p'
""" Author : Govind Patidar DateTime : 10/07/2020 11:30AM File : AllPageLocators """ class Allpagelocators: def __init__(self, driver): """ :param driver: """ self.driver = driver 'Home page locator' text_curr_temp = '/html/body/div/div[1]/h2' curr_temp = 'temperature' moisturizes = '/html/body/div/div[3]/div[1]/p' buy_moisturizes = '/html/body/div/div[3]/div[1]/a/button' sunscreens = '/html/body/div/div[3]/div[2]/p' buy_sunscreens = '/html/body/div/div[3]/div[2]/a/button' 'Checkout page locator' add_cart = 'cart' total_amount = 'total' pay = '/html/body/div[1]/div[3]/form/button/span' 'Payment page' email = '//input[@type="email"]' card_no = '//input[@type="tel"]' date = '//input[@placeholder="MM / YY"]' cvc = '//input[@placeholder="CVC"]' zip = '//input[@placeholder="ZIP Code"]' paynow = '//*[@id="container"]/section/span[2]/div/div/main/form/nav/div/div/div/button' 'Payment done' pay_success = '/html/body/div/div[1]/h2' pay_text = '/html/body/div/div[2]/p'
word = input() out = '' prev = '' # remove same letters which are the same as the previous for x in word: if x != prev: out+=x prev = x print(out)
word = input() out = '' prev = '' for x in word: if x != prev: out += x prev = x print(out)
# # PySNMP MIB module TPLINK-IPADDR-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TPLINK-IPADDR-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:17:29 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, ConstraintsIntersection, SingleValueConstraint, ConstraintsUnion, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsIntersection", "SingleValueConstraint", "ConstraintsUnion", "ValueSizeConstraint") ifIndex, = mibBuilder.importSymbols("IF-MIB", "ifIndex") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") MibScalar, MibTable, MibTableRow, MibTableColumn, Bits, MibIdentifier, iso, Counter32, Unsigned32, TimeTicks, Gauge32, ObjectIdentity, Integer32, IpAddress, NotificationType, ModuleIdentity, Counter64 = mibBuilder.importSymbols("SNMPv2-SMI", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Bits", "MibIdentifier", "iso", "Counter32", "Unsigned32", "TimeTicks", "Gauge32", "ObjectIdentity", "Integer32", "IpAddress", "NotificationType", "ModuleIdentity", "Counter64") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") tplinkMgmt, = mibBuilder.importSymbols("TPLINK-MIB", "tplinkMgmt") TPRowStatus, = mibBuilder.importSymbols("TPLINK-TC-MIB", "TPRowStatus") class TpInterfaceMode(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3)) namedValues = NamedValues(("none", 0), ("manual", 1), ("dhcp", 2), ("bootp", 3)) class TpInterfaceMode2(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1)) namedValues = NamedValues(("none", 0), ("manual", 1)) class TpPortLinkMode(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1)) namedValues = NamedValues(("bridge", 0), ("route", 1)) tplinkIpAddrMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 11863, 6, 6)) tplinkIpAddrMIB.setRevisions(('2012-12-13 09:30',)) if mibBuilder.loadTexts: tplinkIpAddrMIB.setLastUpdated('201212130930Z') if mibBuilder.loadTexts: tplinkIpAddrMIB.setOrganization('TPLINK') tplinkIpAddrMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1)) tplinkIpAddrNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 11863, 6, 6, 2)) tpInterfaceConfig = MibIdentifier((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1)) tpVlanInterfaceTable = MibTable((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 1), ) if mibBuilder.loadTexts: tpVlanInterfaceTable.setStatus('current') tpVlanInterfaceConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 1, 1), ).setIndexNames((0, "TPLINK-IPADDR-MIB", "tpVlanInterfaceVlanId"), (0, "TPLINK-IPADDR-MIB", "tpVlanInterfaceIp"), (0, "TPLINK-IPADDR-MIB", "tpVlanInterfaceSecondary")) if mibBuilder.loadTexts: tpVlanInterfaceConfigEntry.setStatus('current') tpVlanInterfaceVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 1, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: tpVlanInterfaceVlanId.setStatus('current') tpVlanInterfaceSecondary = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 1, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: tpVlanInterfaceSecondary.setStatus('current') tpVlanInterfaceMode = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 1, 1, 3), TpInterfaceMode()).setMaxAccess("readcreate") if mibBuilder.loadTexts: tpVlanInterfaceMode.setStatus('current') tpVlanInterfaceIp = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 1, 1, 4), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: tpVlanInterfaceIp.setStatus('current') tpVlanInterfaceMsk = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 1, 1, 5), IpAddress()).setMaxAccess("readcreate") if mibBuilder.loadTexts: tpVlanInterfaceMsk.setStatus('current') tpVlanInterfaceName = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 1, 1, 6), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 20))).setMaxAccess("readcreate") if mibBuilder.loadTexts: tpVlanInterfaceName.setStatus('current') tpVlanInterfaceStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 1, 1, 7), TPRowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: tpVlanInterfaceStatus.setStatus('current') tpLoopbackInterfaceTable = MibTable((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 2), ) if mibBuilder.loadTexts: tpLoopbackInterfaceTable.setStatus('current') tpLoopbackInterfaceConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 2, 1), ).setIndexNames((0, "TPLINK-IPADDR-MIB", "tpLoopbackInterfaceId"), (0, "TPLINK-IPADDR-MIB", "tpLoopbackInterfaceIp"), (0, "TPLINK-IPADDR-MIB", "tpLoopbackInterfaceSecondary")) if mibBuilder.loadTexts: tpLoopbackInterfaceConfigEntry.setStatus('current') tpLoopbackInterfaceId = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 2, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: tpLoopbackInterfaceId.setStatus('current') tpLoopbackInterfaceSecondary = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 2, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: tpLoopbackInterfaceSecondary.setStatus('current') tpLoopbackInterfaceMode = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 2, 1, 3), TpInterfaceMode2()).setMaxAccess("readcreate") if mibBuilder.loadTexts: tpLoopbackInterfaceMode.setStatus('current') tpLoopbackInterfaceIp = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 2, 1, 4), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: tpLoopbackInterfaceIp.setStatus('current') tpLoopbackInterfaceMsk = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 2, 1, 5), IpAddress()).setMaxAccess("readcreate") if mibBuilder.loadTexts: tpLoopbackInterfaceMsk.setStatus('current') tpLoopbackInterfaceName = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 2, 1, 6), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 20))).setMaxAccess("readcreate") if mibBuilder.loadTexts: tpLoopbackInterfaceName.setStatus('current') tpLoopbackInterfaceStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 2, 1, 7), TPRowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: tpLoopbackInterfaceStatus.setStatus('current') tpRoutedPortTable = MibTable((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 3), ) if mibBuilder.loadTexts: tpRoutedPortTable.setStatus('current') tpRoutedPortConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 3, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"), (0, "TPLINK-IPADDR-MIB", "tpRoutedPortIp"), (0, "TPLINK-IPADDR-MIB", "tpRoutedPortSecondary")) if mibBuilder.loadTexts: tpRoutedPortConfigEntry.setStatus('current') tpRoutedPortId = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 3, 1, 1), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 16))).setMaxAccess("readonly") if mibBuilder.loadTexts: tpRoutedPortId.setStatus('current') tpRoutedPortSecondary = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 3, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: tpRoutedPortSecondary.setStatus('current') tpRoutedPortMode = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 3, 1, 3), TpInterfaceMode()).setMaxAccess("readcreate") if mibBuilder.loadTexts: tpRoutedPortMode.setStatus('current') tpRoutedPortIp = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 3, 1, 4), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: tpRoutedPortIp.setStatus('current') tpRoutedPortMsk = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 3, 1, 5), IpAddress()).setMaxAccess("readcreate") if mibBuilder.loadTexts: tpRoutedPortMsk.setStatus('current') tpRoutedPortName = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 3, 1, 6), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 20))).setMaxAccess("readcreate") if mibBuilder.loadTexts: tpRoutedPortName.setStatus('current') tpRoutedPortStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 3, 1, 7), TPRowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: tpRoutedPortStatus.setStatus('current') tpPortChannelTable = MibTable((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 4), ) if mibBuilder.loadTexts: tpPortChannelTable.setStatus('current') tpPortChannelConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 4, 1), ).setIndexNames((0, "TPLINK-IPADDR-MIB", "tpPortChannelId"), (0, "TPLINK-IPADDR-MIB", "tpPortChannelIp"), (0, "TPLINK-IPADDR-MIB", "tpPortChannelSecondary")) if mibBuilder.loadTexts: tpPortChannelConfigEntry.setStatus('current') tpPortChannelId = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 4, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: tpPortChannelId.setStatus('current') tpPortChannelSecondary = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 4, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: tpPortChannelSecondary.setStatus('current') tpPortChannelMode = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 4, 1, 3), TpInterfaceMode()).setMaxAccess("readcreate") if mibBuilder.loadTexts: tpPortChannelMode.setStatus('current') tpPortChannelIp = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 4, 1, 4), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: tpPortChannelIp.setStatus('current') tpPortChannelMsk = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 4, 1, 5), IpAddress()).setMaxAccess("readcreate") if mibBuilder.loadTexts: tpPortChannelMsk.setStatus('current') tpPortChannelName = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 4, 1, 6), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 20))).setMaxAccess("readcreate") if mibBuilder.loadTexts: tpPortChannelName.setStatus('current') tpPortChannelStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 4, 1, 7), TPRowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: tpPortChannelStatus.setStatus('current') mibBuilder.exportSymbols("TPLINK-IPADDR-MIB", tpVlanInterfaceMode=tpVlanInterfaceMode, tpPortChannelIp=tpPortChannelIp, tpRoutedPortIp=tpRoutedPortIp, tpPortChannelSecondary=tpPortChannelSecondary, tpVlanInterfaceVlanId=tpVlanInterfaceVlanId, tpLoopbackInterfaceId=tpLoopbackInterfaceId, tplinkIpAddrMIB=tplinkIpAddrMIB, tpVlanInterfaceMsk=tpVlanInterfaceMsk, tpInterfaceConfig=tpInterfaceConfig, TpInterfaceMode=TpInterfaceMode, tpLoopbackInterfaceName=tpLoopbackInterfaceName, tpRoutedPortSecondary=tpRoutedPortSecondary, tpPortChannelMsk=tpPortChannelMsk, tpRoutedPortStatus=tpRoutedPortStatus, tpRoutedPortId=tpRoutedPortId, tpPortChannelMode=tpPortChannelMode, tpVlanInterfaceConfigEntry=tpVlanInterfaceConfigEntry, tpRoutedPortConfigEntry=tpRoutedPortConfigEntry, tpRoutedPortMode=tpRoutedPortMode, TpInterfaceMode2=TpInterfaceMode2, tpRoutedPortMsk=tpRoutedPortMsk, tpLoopbackInterfaceConfigEntry=tpLoopbackInterfaceConfigEntry, tpPortChannelName=tpPortChannelName, tplinkIpAddrNotifications=tplinkIpAddrNotifications, tpLoopbackInterfaceMsk=tpLoopbackInterfaceMsk, tpVlanInterfaceTable=tpVlanInterfaceTable, tpVlanInterfaceName=tpVlanInterfaceName, tpVlanInterfaceStatus=tpVlanInterfaceStatus, PYSNMP_MODULE_ID=tplinkIpAddrMIB, tpPortChannelTable=tpPortChannelTable, tpLoopbackInterfaceStatus=tpLoopbackInterfaceStatus, tpPortChannelStatus=tpPortChannelStatus, tpRoutedPortTable=tpRoutedPortTable, tpPortChannelConfigEntry=tpPortChannelConfigEntry, tpLoopbackInterfaceIp=tpLoopbackInterfaceIp, tpRoutedPortName=tpRoutedPortName, tpPortChannelId=tpPortChannelId, TpPortLinkMode=TpPortLinkMode, tplinkIpAddrMIBObjects=tplinkIpAddrMIBObjects, tpVlanInterfaceIp=tpVlanInterfaceIp, tpLoopbackInterfaceSecondary=tpLoopbackInterfaceSecondary, tpVlanInterfaceSecondary=tpVlanInterfaceSecondary, tpLoopbackInterfaceTable=tpLoopbackInterfaceTable, tpLoopbackInterfaceMode=tpLoopbackInterfaceMode)
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, constraints_intersection, single_value_constraint, constraints_union, value_size_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'ConstraintsIntersection', 'SingleValueConstraint', 'ConstraintsUnion', 'ValueSizeConstraint') (if_index,) = mibBuilder.importSymbols('IF-MIB', 'ifIndex') (module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup') (mib_scalar, mib_table, mib_table_row, mib_table_column, bits, mib_identifier, iso, counter32, unsigned32, time_ticks, gauge32, object_identity, integer32, ip_address, notification_type, module_identity, counter64) = mibBuilder.importSymbols('SNMPv2-SMI', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Bits', 'MibIdentifier', 'iso', 'Counter32', 'Unsigned32', 'TimeTicks', 'Gauge32', 'ObjectIdentity', 'Integer32', 'IpAddress', 'NotificationType', 'ModuleIdentity', 'Counter64') (display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention') (tplink_mgmt,) = mibBuilder.importSymbols('TPLINK-MIB', 'tplinkMgmt') (tp_row_status,) = mibBuilder.importSymbols('TPLINK-TC-MIB', 'TPRowStatus') class Tpinterfacemode(TextualConvention, Integer32): status = 'current' subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(0, 1, 2, 3)) named_values = named_values(('none', 0), ('manual', 1), ('dhcp', 2), ('bootp', 3)) class Tpinterfacemode2(TextualConvention, Integer32): status = 'current' subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(0, 1)) named_values = named_values(('none', 0), ('manual', 1)) class Tpportlinkmode(TextualConvention, Integer32): status = 'current' subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(0, 1)) named_values = named_values(('bridge', 0), ('route', 1)) tplink_ip_addr_mib = module_identity((1, 3, 6, 1, 4, 1, 11863, 6, 6)) tplinkIpAddrMIB.setRevisions(('2012-12-13 09:30',)) if mibBuilder.loadTexts: tplinkIpAddrMIB.setLastUpdated('201212130930Z') if mibBuilder.loadTexts: tplinkIpAddrMIB.setOrganization('TPLINK') tplink_ip_addr_mib_objects = mib_identifier((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1)) tplink_ip_addr_notifications = mib_identifier((1, 3, 6, 1, 4, 1, 11863, 6, 6, 2)) tp_interface_config = mib_identifier((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1)) tp_vlan_interface_table = mib_table((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 1)) if mibBuilder.loadTexts: tpVlanInterfaceTable.setStatus('current') tp_vlan_interface_config_entry = mib_table_row((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 1, 1)).setIndexNames((0, 'TPLINK-IPADDR-MIB', 'tpVlanInterfaceVlanId'), (0, 'TPLINK-IPADDR-MIB', 'tpVlanInterfaceIp'), (0, 'TPLINK-IPADDR-MIB', 'tpVlanInterfaceSecondary')) if mibBuilder.loadTexts: tpVlanInterfaceConfigEntry.setStatus('current') tp_vlan_interface_vlan_id = mib_table_column((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 1, 1, 1), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: tpVlanInterfaceVlanId.setStatus('current') tp_vlan_interface_secondary = mib_table_column((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 1, 1, 2), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: tpVlanInterfaceSecondary.setStatus('current') tp_vlan_interface_mode = mib_table_column((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 1, 1, 3), tp_interface_mode()).setMaxAccess('readcreate') if mibBuilder.loadTexts: tpVlanInterfaceMode.setStatus('current') tp_vlan_interface_ip = mib_table_column((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 1, 1, 4), ip_address()).setMaxAccess('readonly') if mibBuilder.loadTexts: tpVlanInterfaceIp.setStatus('current') tp_vlan_interface_msk = mib_table_column((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 1, 1, 5), ip_address()).setMaxAccess('readcreate') if mibBuilder.loadTexts: tpVlanInterfaceMsk.setStatus('current') tp_vlan_interface_name = mib_table_column((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 1, 1, 6), octet_string().subtype(subtypeSpec=value_size_constraint(0, 20))).setMaxAccess('readcreate') if mibBuilder.loadTexts: tpVlanInterfaceName.setStatus('current') tp_vlan_interface_status = mib_table_column((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 1, 1, 7), tp_row_status()).setMaxAccess('readcreate') if mibBuilder.loadTexts: tpVlanInterfaceStatus.setStatus('current') tp_loopback_interface_table = mib_table((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 2)) if mibBuilder.loadTexts: tpLoopbackInterfaceTable.setStatus('current') tp_loopback_interface_config_entry = mib_table_row((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 2, 1)).setIndexNames((0, 'TPLINK-IPADDR-MIB', 'tpLoopbackInterfaceId'), (0, 'TPLINK-IPADDR-MIB', 'tpLoopbackInterfaceIp'), (0, 'TPLINK-IPADDR-MIB', 'tpLoopbackInterfaceSecondary')) if mibBuilder.loadTexts: tpLoopbackInterfaceConfigEntry.setStatus('current') tp_loopback_interface_id = mib_table_column((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 2, 1, 1), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: tpLoopbackInterfaceId.setStatus('current') tp_loopback_interface_secondary = mib_table_column((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 2, 1, 2), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: tpLoopbackInterfaceSecondary.setStatus('current') tp_loopback_interface_mode = mib_table_column((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 2, 1, 3), tp_interface_mode2()).setMaxAccess('readcreate') if mibBuilder.loadTexts: tpLoopbackInterfaceMode.setStatus('current') tp_loopback_interface_ip = mib_table_column((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 2, 1, 4), ip_address()).setMaxAccess('readonly') if mibBuilder.loadTexts: tpLoopbackInterfaceIp.setStatus('current') tp_loopback_interface_msk = mib_table_column((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 2, 1, 5), ip_address()).setMaxAccess('readcreate') if mibBuilder.loadTexts: tpLoopbackInterfaceMsk.setStatus('current') tp_loopback_interface_name = mib_table_column((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 2, 1, 6), octet_string().subtype(subtypeSpec=value_size_constraint(0, 20))).setMaxAccess('readcreate') if mibBuilder.loadTexts: tpLoopbackInterfaceName.setStatus('current') tp_loopback_interface_status = mib_table_column((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 2, 1, 7), tp_row_status()).setMaxAccess('readcreate') if mibBuilder.loadTexts: tpLoopbackInterfaceStatus.setStatus('current') tp_routed_port_table = mib_table((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 3)) if mibBuilder.loadTexts: tpRoutedPortTable.setStatus('current') tp_routed_port_config_entry = mib_table_row((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 3, 1)).setIndexNames((0, 'IF-MIB', 'ifIndex'), (0, 'TPLINK-IPADDR-MIB', 'tpRoutedPortIp'), (0, 'TPLINK-IPADDR-MIB', 'tpRoutedPortSecondary')) if mibBuilder.loadTexts: tpRoutedPortConfigEntry.setStatus('current') tp_routed_port_id = mib_table_column((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 3, 1, 1), octet_string().subtype(subtypeSpec=value_size_constraint(0, 16))).setMaxAccess('readonly') if mibBuilder.loadTexts: tpRoutedPortId.setStatus('current') tp_routed_port_secondary = mib_table_column((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 3, 1, 2), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: tpRoutedPortSecondary.setStatus('current') tp_routed_port_mode = mib_table_column((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 3, 1, 3), tp_interface_mode()).setMaxAccess('readcreate') if mibBuilder.loadTexts: tpRoutedPortMode.setStatus('current') tp_routed_port_ip = mib_table_column((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 3, 1, 4), ip_address()).setMaxAccess('readonly') if mibBuilder.loadTexts: tpRoutedPortIp.setStatus('current') tp_routed_port_msk = mib_table_column((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 3, 1, 5), ip_address()).setMaxAccess('readcreate') if mibBuilder.loadTexts: tpRoutedPortMsk.setStatus('current') tp_routed_port_name = mib_table_column((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 3, 1, 6), octet_string().subtype(subtypeSpec=value_size_constraint(0, 20))).setMaxAccess('readcreate') if mibBuilder.loadTexts: tpRoutedPortName.setStatus('current') tp_routed_port_status = mib_table_column((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 3, 1, 7), tp_row_status()).setMaxAccess('readcreate') if mibBuilder.loadTexts: tpRoutedPortStatus.setStatus('current') tp_port_channel_table = mib_table((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 4)) if mibBuilder.loadTexts: tpPortChannelTable.setStatus('current') tp_port_channel_config_entry = mib_table_row((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 4, 1)).setIndexNames((0, 'TPLINK-IPADDR-MIB', 'tpPortChannelId'), (0, 'TPLINK-IPADDR-MIB', 'tpPortChannelIp'), (0, 'TPLINK-IPADDR-MIB', 'tpPortChannelSecondary')) if mibBuilder.loadTexts: tpPortChannelConfigEntry.setStatus('current') tp_port_channel_id = mib_table_column((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 4, 1, 1), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: tpPortChannelId.setStatus('current') tp_port_channel_secondary = mib_table_column((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 4, 1, 2), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: tpPortChannelSecondary.setStatus('current') tp_port_channel_mode = mib_table_column((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 4, 1, 3), tp_interface_mode()).setMaxAccess('readcreate') if mibBuilder.loadTexts: tpPortChannelMode.setStatus('current') tp_port_channel_ip = mib_table_column((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 4, 1, 4), ip_address()).setMaxAccess('readonly') if mibBuilder.loadTexts: tpPortChannelIp.setStatus('current') tp_port_channel_msk = mib_table_column((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 4, 1, 5), ip_address()).setMaxAccess('readcreate') if mibBuilder.loadTexts: tpPortChannelMsk.setStatus('current') tp_port_channel_name = mib_table_column((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 4, 1, 6), octet_string().subtype(subtypeSpec=value_size_constraint(0, 20))).setMaxAccess('readcreate') if mibBuilder.loadTexts: tpPortChannelName.setStatus('current') tp_port_channel_status = mib_table_column((1, 3, 6, 1, 4, 1, 11863, 6, 6, 1, 1, 4, 1, 7), tp_row_status()).setMaxAccess('readcreate') if mibBuilder.loadTexts: tpPortChannelStatus.setStatus('current') mibBuilder.exportSymbols('TPLINK-IPADDR-MIB', tpVlanInterfaceMode=tpVlanInterfaceMode, tpPortChannelIp=tpPortChannelIp, tpRoutedPortIp=tpRoutedPortIp, tpPortChannelSecondary=tpPortChannelSecondary, tpVlanInterfaceVlanId=tpVlanInterfaceVlanId, tpLoopbackInterfaceId=tpLoopbackInterfaceId, tplinkIpAddrMIB=tplinkIpAddrMIB, tpVlanInterfaceMsk=tpVlanInterfaceMsk, tpInterfaceConfig=tpInterfaceConfig, TpInterfaceMode=TpInterfaceMode, tpLoopbackInterfaceName=tpLoopbackInterfaceName, tpRoutedPortSecondary=tpRoutedPortSecondary, tpPortChannelMsk=tpPortChannelMsk, tpRoutedPortStatus=tpRoutedPortStatus, tpRoutedPortId=tpRoutedPortId, tpPortChannelMode=tpPortChannelMode, tpVlanInterfaceConfigEntry=tpVlanInterfaceConfigEntry, tpRoutedPortConfigEntry=tpRoutedPortConfigEntry, tpRoutedPortMode=tpRoutedPortMode, TpInterfaceMode2=TpInterfaceMode2, tpRoutedPortMsk=tpRoutedPortMsk, tpLoopbackInterfaceConfigEntry=tpLoopbackInterfaceConfigEntry, tpPortChannelName=tpPortChannelName, tplinkIpAddrNotifications=tplinkIpAddrNotifications, tpLoopbackInterfaceMsk=tpLoopbackInterfaceMsk, tpVlanInterfaceTable=tpVlanInterfaceTable, tpVlanInterfaceName=tpVlanInterfaceName, tpVlanInterfaceStatus=tpVlanInterfaceStatus, PYSNMP_MODULE_ID=tplinkIpAddrMIB, tpPortChannelTable=tpPortChannelTable, tpLoopbackInterfaceStatus=tpLoopbackInterfaceStatus, tpPortChannelStatus=tpPortChannelStatus, tpRoutedPortTable=tpRoutedPortTable, tpPortChannelConfigEntry=tpPortChannelConfigEntry, tpLoopbackInterfaceIp=tpLoopbackInterfaceIp, tpRoutedPortName=tpRoutedPortName, tpPortChannelId=tpPortChannelId, TpPortLinkMode=TpPortLinkMode, tplinkIpAddrMIBObjects=tplinkIpAddrMIBObjects, tpVlanInterfaceIp=tpVlanInterfaceIp, tpLoopbackInterfaceSecondary=tpLoopbackInterfaceSecondary, tpVlanInterfaceSecondary=tpVlanInterfaceSecondary, tpLoopbackInterfaceTable=tpLoopbackInterfaceTable, tpLoopbackInterfaceMode=tpLoopbackInterfaceMode)
""" Write a method/function DISPLAYWORDS() in python to read lines from a text file STORY.TXT, using read function and display those words, which are less than 4 characters. """ F = open("story.txt", "r") value = F.read() lines = value.split() count = 0 for i in lines: if len(i) < 4: print(i) count += 1 else: pass print("The total number of words with length less than 4 are", count)
""" Write a method/function DISPLAYWORDS() in python to read lines from a text file STORY.TXT, using read function and display those words, which are less than 4 characters. """ f = open('story.txt', 'r') value = F.read() lines = value.split() count = 0 for i in lines: if len(i) < 4: print(i) count += 1 else: pass print('The total number of words with length less than 4 are', count)
#Programa que leia um nome completo e diga o primeiro e ultimo nome nome = input('Digite seu nome completo: ').title() splt = nome.split() print(splt[0],splt[-1])
nome = input('Digite seu nome completo: ').title() splt = nome.split() print(splt[0], splt[-1])
name = "chris alan" name = name.title() name = "1 w 2 r 3g" # Complete the solve function below. def solve(string): """ Capitalizing function """ list_strings = string.rstrip().split(" ") result = "" for item in list_strings: if item[0].isalpha(): item = item.title() result += item + " " return result.strip()
name = 'chris alan' name = name.title() name = '1 w 2 r 3g' def solve(string): """ Capitalizing function """ list_strings = string.rstrip().split(' ') result = '' for item in list_strings: if item[0].isalpha(): item = item.title() result += item + ' ' return result.strip()
def binary_search(ary, tar): head = 0 tail = len(ary) - 1 found = False while head <= tail and not found: mid = (head + tail) / 2 if ary[mid] == tar: found = True elif ary[mid] < tar: head = mid + 1 elif ary[mid] > tar: tail = mid - 1 return found def binary_search_recursive(ary, tar): if len(ary) == 0: return False mid = len(ary) / 2 if ary[mid] == tar: return True elif ary[mid] < tar: return binary_search_recursive(ary[mid+1:], tar) elif ary[mid] > tar: return binary_search_recursive(ary[:mid], tar) a = [1, 2, 3, 4, 5, 6, 7, 8, 9] print(binary_search(a, 0)) print(binary_search(a, 1)) print(binary_search(a, 3)) print(binary_search(a, 4)) print(binary_search(a, 11)) print(binary_search_recursive(a, 0)) print(binary_search_recursive(a, 1)) print(binary_search_recursive(a, 3)) print(binary_search_recursive(a, 4)) print(binary_search_recursive(a, 11))
def binary_search(ary, tar): head = 0 tail = len(ary) - 1 found = False while head <= tail and (not found): mid = (head + tail) / 2 if ary[mid] == tar: found = True elif ary[mid] < tar: head = mid + 1 elif ary[mid] > tar: tail = mid - 1 return found def binary_search_recursive(ary, tar): if len(ary) == 0: return False mid = len(ary) / 2 if ary[mid] == tar: return True elif ary[mid] < tar: return binary_search_recursive(ary[mid + 1:], tar) elif ary[mid] > tar: return binary_search_recursive(ary[:mid], tar) a = [1, 2, 3, 4, 5, 6, 7, 8, 9] print(binary_search(a, 0)) print(binary_search(a, 1)) print(binary_search(a, 3)) print(binary_search(a, 4)) print(binary_search(a, 11)) print(binary_search_recursive(a, 0)) print(binary_search_recursive(a, 1)) print(binary_search_recursive(a, 3)) print(binary_search_recursive(a, 4)) print(binary_search_recursive(a, 11))
# example solution. # You are not expected to make a nice plotting function, # you can simply call plt.imshow a number of times and observe print(faces.DESCR) # this shows there are 40 classes, 10 samples per class print(faces.target) #the targets i.e. classes print(np.unique(faces.target).shape) # another way to see n_classes X = faces.images y = faces.target fig = plt.figure(figsize=(16,5)) idxs = [0,1,2, 11,12,13, 40,41] for i,k in enumerate(idxs): ax=fig.add_subplot(2,4,i+1) ax.imshow(X[k]) ax.set_title(f"target={y[k]}") # looking at a few plots shows that each target is a single person.
print(faces.DESCR) print(faces.target) print(np.unique(faces.target).shape) x = faces.images y = faces.target fig = plt.figure(figsize=(16, 5)) idxs = [0, 1, 2, 11, 12, 13, 40, 41] for (i, k) in enumerate(idxs): ax = fig.add_subplot(2, 4, i + 1) ax.imshow(X[k]) ax.set_title(f'target={y[k]}')
#python 3.5.2 def areAnagram(firstWord, secondWord): firstList = list(firstWord) secondList = list(secondWord) result = True if len(firstList) == len(secondList) and result: #Sort both list alphabetically firstList.sort() secondList.sort() i = 0 length = len(firstList) while i < length : if firstList[i] != secondList[i]: result = False i = i + 1 else: result = False return result # Checking same word (Result should be True) print ( 'Is "earth" and "earth" an anagram ?' , areAnagram('earth','earth') ) # Checking two anagrams (Result should be True) print ( 'Is "heart" and "earth" an anagram ?' , areAnagram('heart','earth') ) # Checking two words that are not anagrams (Result should be False) print ( 'Is "eartj" and "earth" an anagram ?' , areAnagram('eartj','earth') ) # Checking not the same number of characters (Result should be False) print ( 'Is "eart" and "earth" an anagram ?' , areAnagram('eart','earth') ) # Checking more than one of the same characters (Result should be False) print ( 'Is "eearth" and "earth" an anagram ?' , areAnagram('eearth','earth') ) ''' OUTPUT: Is "earth" and "earth" an anagram ? True Is "heart" and "earth" an anagram ? True Is "eartj" and "earth" an anagram ? False Is "eart" and "earth" an anagram ? False Is "eearth" and "earth" an anagram ? False '''
def are_anagram(firstWord, secondWord): first_list = list(firstWord) second_list = list(secondWord) result = True if len(firstList) == len(secondList) and result: firstList.sort() secondList.sort() i = 0 length = len(firstList) while i < length: if firstList[i] != secondList[i]: result = False i = i + 1 else: result = False return result print('Is "earth" and "earth" an anagram ?', are_anagram('earth', 'earth')) print('Is "heart" and "earth" an anagram ?', are_anagram('heart', 'earth')) print('Is "eartj" and "earth" an anagram ?', are_anagram('eartj', 'earth')) print('Is "eart" and "earth" an anagram ?', are_anagram('eart', 'earth')) print('Is "eearth" and "earth" an anagram ?', are_anagram('eearth', 'earth')) '\nOUTPUT:\n\nIs "earth" and "earth" an anagram ? True\nIs "heart" and "earth" an anagram ? True\nIs "eartj" and "earth" an anagram ? False\nIs "eart" and "earth" an anagram ? False\nIs "eearth" and "earth" an anagram ? False\n'
#!/bin/zsh ''' Regex Search Write a program that opens all .txt files in a folder and searches for any line that matches a user-supplied regular expression. The results should be printed to the screen. '''
""" Regex Search Write a program that opens all .txt files in a folder and searches for any line that matches a user-supplied regular expression. The results should be printed to the screen. """
''' Q1. Write a python code for creating a password for E-Aadhar card. The details used are the first 4 letters of your name, date and month of your birth. The task is to generate a password with the lambda function and display it.''' name = input("Input your name (as on your Aadhar)\n") dob = input("Please enter your dob in this order : 'ddmmyyyy'\n") first = lambda name: name[:4] last = lambda dob: dob[4:] pw = first(name) + last(dob) print("Your password is ",pw)
""" Q1. Write a python code for creating a password for E-Aadhar card. The details used are the first 4 letters of your name, date and month of your birth. The task is to generate a password with the lambda function and display it.""" name = input('Input your name (as on your Aadhar)\n') dob = input("Please enter your dob in this order : 'ddmmyyyy'\n") first = lambda name: name[:4] last = lambda dob: dob[4:] pw = first(name) + last(dob) print('Your password is ', pw)
# Follow up for N-Queens problem. # Now, instead outputting board configurations, return the total number of distinct solutions. class Solution(object): result = 0 def totalNQueens(self, n): """ :type n: int :rtype: int """ cols = [] self.search(n, cols) return self.result def search(self, n, cols): if len(cols) == n: self.result += 1 return for col in range(n): if not self.isValid(cols, col): continue self.search(n, cols + [col]) def isValid(self, cols, col): currentRowNumber = len(cols) for i in range(currentRowNumber): # same column if cols[i] == col: return False # left-top to right-bottom if i - cols[i] == currentRowNumber - col: return False # right-top to left-bottom if i + cols[i] == currentRowNumber + col: return False return True
class Solution(object): result = 0 def total_n_queens(self, n): """ :type n: int :rtype: int """ cols = [] self.search(n, cols) return self.result def search(self, n, cols): if len(cols) == n: self.result += 1 return for col in range(n): if not self.isValid(cols, col): continue self.search(n, cols + [col]) def is_valid(self, cols, col): current_row_number = len(cols) for i in range(currentRowNumber): if cols[i] == col: return False if i - cols[i] == currentRowNumber - col: return False if i + cols[i] == currentRowNumber + col: return False return True
# !/usr/bin/env python # coding: utf-8 ''' Description: '''
""" Description: """
# -*- coding: utf-8 -*- """ PRTG Exceptions """ class PrtgException(Exception): """ Base PRTG Exception """ pass class PrtgBadRequest(PrtgException): """ Bad request """ pass class PrtgBadTarget(PrtgException): """ Invalid target """ pass class PrtgUnknownResponse(PrtgException): """ Unknown response """ pass class PrtgTooManyChannelsInSensorData(PrtgException): """ Too many channels in sensor data """ pass class PrtgUnsupportedHTTPMethod(PrtgException): """ UnsupportedHTTPMethod """ pass
""" PRTG Exceptions """ class Prtgexception(Exception): """ Base PRTG Exception """ pass class Prtgbadrequest(PrtgException): """ Bad request """ pass class Prtgbadtarget(PrtgException): """ Invalid target """ pass class Prtgunknownresponse(PrtgException): """ Unknown response """ pass class Prtgtoomanychannelsinsensordata(PrtgException): """ Too many channels in sensor data """ pass class Prtgunsupportedhttpmethod(PrtgException): """ UnsupportedHTTPMethod """ pass
def getSampleMetadata(catalogName, tagName, digest): return { 'schemaVersion': 2, 'mediaType': 'application/vnd.docker.distribution.manifest.v2+json', 'config': { 'mediaType': 'application/vnd.docker.container.image.v1+json', 'size': 1111, 'digest': digest }, 'layers': [ { 'mediaType': 'application/vnd.docker.image.rootfs.diff.tar.gzip', 'size': 123, 'digest': 'sha256:e6c96db7181be991f19a9fb6975cdbbd73c65f4a2681348e63a141a2192a5f10' }, { 'mediaType': 'application/vnd.docker.image.rootfs.diff.tar.gzip', 'size': 123, 'digest': 'sha256:8985e402e050840450bd9d60b20a9bec70d57a507b33a85e5c3b3caf2e0ada6e' }, { 'mediaType': 'application/vnd.docker.image.rootfs.diff.tar.gzip', 'size': 23, 'digest': 'sha256:78986f489cfa0d72ea6e357ab3e81a9d5ebdb9cf4797a41eb49bdefe579f1b01' } ] }
def get_sample_metadata(catalogName, tagName, digest): return {'schemaVersion': 2, 'mediaType': 'application/vnd.docker.distribution.manifest.v2+json', 'config': {'mediaType': 'application/vnd.docker.container.image.v1+json', 'size': 1111, 'digest': digest}, 'layers': [{'mediaType': 'application/vnd.docker.image.rootfs.diff.tar.gzip', 'size': 123, 'digest': 'sha256:e6c96db7181be991f19a9fb6975cdbbd73c65f4a2681348e63a141a2192a5f10'}, {'mediaType': 'application/vnd.docker.image.rootfs.diff.tar.gzip', 'size': 123, 'digest': 'sha256:8985e402e050840450bd9d60b20a9bec70d57a507b33a85e5c3b3caf2e0ada6e'}, {'mediaType': 'application/vnd.docker.image.rootfs.diff.tar.gzip', 'size': 23, 'digest': 'sha256:78986f489cfa0d72ea6e357ab3e81a9d5ebdb9cf4797a41eb49bdefe579f1b01'}]}
class Solution: def count(self, s, target): ans = 0 for i in s: if i == target: ans += 1 return ans def findMaxForm(self, strs: List[str], m: int, n: int) -> int: dp = [[0 for i in range(n+1)] for j in range(m+1)] for s in strs: zero = self.count(s, '0') one = self.count(s, '1') for i in range(m, zero-1, -1): for j in range(n, one-1, -1): dp[i][j] = max(dp[i][j], dp[i-zero][j-one]+1) return dp[m][n]
class Solution: def count(self, s, target): ans = 0 for i in s: if i == target: ans += 1 return ans def find_max_form(self, strs: List[str], m: int, n: int) -> int: dp = [[0 for i in range(n + 1)] for j in range(m + 1)] for s in strs: zero = self.count(s, '0') one = self.count(s, '1') for i in range(m, zero - 1, -1): for j in range(n, one - 1, -1): dp[i][j] = max(dp[i][j], dp[i - zero][j - one] + 1) return dp[m][n]
# remove nth node from end # https://leetcode.com/problems/remove-nth-node-from-end-of-list/ # brute # create a new linked list without that element # Time O(n) # Space O(n) # optimal # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: if(head.next == None): return None start = ListNode() start.next = head slow = fast = start for i in range(1, n+1): fast = fast.next while(fast.next != None): fast = fast.next slow = slow.next slow.next = slow.next.next return start.next
class Listnode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def remove_nth_from_end(self, head: ListNode, n: int) -> ListNode: if head.next == None: return None start = list_node() start.next = head slow = fast = start for i in range(1, n + 1): fast = fast.next while fast.next != None: fast = fast.next slow = slow.next slow.next = slow.next.next return start.next
def readFile(fileName): try: with open(fileName,'r') as f: print (f.read()) except FileNotFoundError: print (f'File {fileName} is not found') readFile('1.txt') readFile('2.txt') readFile('3.txt')
def read_file(fileName): try: with open(fileName, 'r') as f: print(f.read()) except FileNotFoundError: print(f'File {fileName} is not found') read_file('1.txt') read_file('2.txt') read_file('3.txt')
''' In this simple assignment you are given a number and have to make it negative. But maybe the number is already negative? Examples: make_negative(1); # return -1 make_negative(-5); # return -5 make_negative(0); # return 0 Notes: * The number can be negative already, in which case no change is required. * Zero (0) is not checked for any specific sign. Negative zeros make no mathematical sense. ''' def make_negative(number): return number * -1 if number > 0 else number
""" In this simple assignment you are given a number and have to make it negative. But maybe the number is already negative? Examples: make_negative(1); # return -1 make_negative(-5); # return -5 make_negative(0); # return 0 Notes: * The number can be negative already, in which case no change is required. * Zero (0) is not checked for any specific sign. Negative zeros make no mathematical sense. """ def make_negative(number): return number * -1 if number > 0 else number
cards = {'SPADE' : ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13'], 'HEART' : ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13'], 'CLUB' : ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13'], 'DIAMOND' : ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13'] }
cards = {'SPADE': ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13'], 'HEART': ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13'], 'CLUB': ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13'], 'DIAMOND': ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13']}
CR_ATTACHMENT_AVAILABLE = 'cr_available' CR_ATTACHMENT_REQUEST = 'cr_request' TRR_ATTACHMENT_AVAILABLE = 'trr_available' TRR_ATTACHMENT_REQUEST = 'trr_request' ATTACHMENT_TYPE_CHOICES = [ [CR_ATTACHMENT_AVAILABLE, 'CR attachment available'], [CR_ATTACHMENT_REQUEST, 'CR attachment request'], [TRR_ATTACHMENT_AVAILABLE, 'TRR attachment available'], [TRR_ATTACHMENT_REQUEST, 'TRR attachment request'], ]
cr_attachment_available = 'cr_available' cr_attachment_request = 'cr_request' trr_attachment_available = 'trr_available' trr_attachment_request = 'trr_request' attachment_type_choices = [[CR_ATTACHMENT_AVAILABLE, 'CR attachment available'], [CR_ATTACHMENT_REQUEST, 'CR attachment request'], [TRR_ATTACHMENT_AVAILABLE, 'TRR attachment available'], [TRR_ATTACHMENT_REQUEST, 'TRR attachment request']]
# Description: Sample Code to Run mypy # Variables without types i:int = 200 f:float = 2.34 str = "Hello" # A function without type annotations def greet(name:str)-> str: return str + " " + name if __name__ == '__main__': greet("Dilbert")
i: int = 200 f: float = 2.34 str = 'Hello' def greet(name: str) -> str: return str + ' ' + name if __name__ == '__main__': greet('Dilbert')
class GameObject: def __init__(self, *, x=0, y=0, size=None): self.x = x self.y = y self.size = size self.half_width = self.size[0] / 2. def to_rect(self): """Return the gameobject to be display by qs.anim""" return [[self.x, self.y], self.size] def update(self): """Update the game object every frame""" pass def reset_values(self, *, x=0, y=0, size=None): self.x = x self.y = y self.size = size self.half_width = self.size[0] / 2. class Crab(GameObject): def __init__(self, x, y, size, min_x=0, max_x=800): GameObject.__init__(self, x=x, y=y, size=size) # super() is not supported by pyckitup 0.1 self.speed = 15 self.min_x = min_x - self.size[0] # take into account sprite size self.max_x = max_x self.move_smoother = 0.9 def go_left(self, coefficient=1): self.x -= (self.speed * coefficient) ** self.move_smoother self.x = max(self.min_x, self.x) def go_right(self, coefficient=1): self.x += (self.speed * coefficient) ** self.move_smoother self.x = min(self.max_x, self.x) def refresh_position_on_platform(self, platform): self.y = platform.y - self.size[1] def can_catch_water_bubble(self, water_bubble): y_diff = water_bubble.y - self.y - 15 if y_diff < 0: # Handmade abs for performances y_diff = -y_diff if y_diff > 40: return False # Hack for performances x_diff = water_bubble.x - (self.x + self.half_width) if x_diff < 0: x_diff = -x_diff return x_diff + y_diff < 40 class Platform(GameObject): """Platform on which the crab is standing""" max_height = 580 min_up = 10 max_up = 30 min_down = 10 max_down = 100 def __init__(self, x, y, size, screen_height): GameObject.__init__(self, x=x, y=y, size=size) self.y_target = y self.screen_height = screen_height def refresh_height(self): if self.y < self.y_target: self.y += 1 elif self.y > self.y_target: self.y -= 1 def go_up(self): up_by = self.min_up + (self.y_target / self.screen_height * (self.max_up - self.min_up)) self.y_target -= up_by def go_down(self): down_by = self.min_down + (1. - self.y_target / self.screen_height) * (self.max_down - self.min_down) self.y_target += down_by self.y_target = min(self.y_target, self.max_height) class WaterBubble(GameObject): def __init__(self, x, y, size, radius): GameObject.__init__(self, x=x, y=y, size=size) self.speed = 5 self.radius = radius def update(self): self.y += self.speed def is_below(self, gameobject): return self.y >= gameobject.y + self.radius def reset_values(self, *, x=0, y=0, size=None, radius=0): GameObject.reset_values(self, x=x, y=y, size=size) self.radius = radius class WaterBubblePool: """Pool of water bubble used to avoid creating/destroying object in repetition""" def __init__(self): self.unused_water_bubble = [] def add(self, water_bubble): self.unused_water_bubble.append(water_bubble) def get(self, **kwargs): if len(self.unused_water_bubble) > 1: water_bubble = self.unused_water_bubble.pop() water_bubble.reset_values(**kwargs) return water_bubble else: return WaterBubble(**kwargs)
class Gameobject: def __init__(self, *, x=0, y=0, size=None): self.x = x self.y = y self.size = size self.half_width = self.size[0] / 2.0 def to_rect(self): """Return the gameobject to be display by qs.anim""" return [[self.x, self.y], self.size] def update(self): """Update the game object every frame""" pass def reset_values(self, *, x=0, y=0, size=None): self.x = x self.y = y self.size = size self.half_width = self.size[0] / 2.0 class Crab(GameObject): def __init__(self, x, y, size, min_x=0, max_x=800): GameObject.__init__(self, x=x, y=y, size=size) self.speed = 15 self.min_x = min_x - self.size[0] self.max_x = max_x self.move_smoother = 0.9 def go_left(self, coefficient=1): self.x -= (self.speed * coefficient) ** self.move_smoother self.x = max(self.min_x, self.x) def go_right(self, coefficient=1): self.x += (self.speed * coefficient) ** self.move_smoother self.x = min(self.max_x, self.x) def refresh_position_on_platform(self, platform): self.y = platform.y - self.size[1] def can_catch_water_bubble(self, water_bubble): y_diff = water_bubble.y - self.y - 15 if y_diff < 0: y_diff = -y_diff if y_diff > 40: return False x_diff = water_bubble.x - (self.x + self.half_width) if x_diff < 0: x_diff = -x_diff return x_diff + y_diff < 40 class Platform(GameObject): """Platform on which the crab is standing""" max_height = 580 min_up = 10 max_up = 30 min_down = 10 max_down = 100 def __init__(self, x, y, size, screen_height): GameObject.__init__(self, x=x, y=y, size=size) self.y_target = y self.screen_height = screen_height def refresh_height(self): if self.y < self.y_target: self.y += 1 elif self.y > self.y_target: self.y -= 1 def go_up(self): up_by = self.min_up + self.y_target / self.screen_height * (self.max_up - self.min_up) self.y_target -= up_by def go_down(self): down_by = self.min_down + (1.0 - self.y_target / self.screen_height) * (self.max_down - self.min_down) self.y_target += down_by self.y_target = min(self.y_target, self.max_height) class Waterbubble(GameObject): def __init__(self, x, y, size, radius): GameObject.__init__(self, x=x, y=y, size=size) self.speed = 5 self.radius = radius def update(self): self.y += self.speed def is_below(self, gameobject): return self.y >= gameobject.y + self.radius def reset_values(self, *, x=0, y=0, size=None, radius=0): GameObject.reset_values(self, x=x, y=y, size=size) self.radius = radius class Waterbubblepool: """Pool of water bubble used to avoid creating/destroying object in repetition""" def __init__(self): self.unused_water_bubble = [] def add(self, water_bubble): self.unused_water_bubble.append(water_bubble) def get(self, **kwargs): if len(self.unused_water_bubble) > 1: water_bubble = self.unused_water_bubble.pop() water_bubble.reset_values(**kwargs) return water_bubble else: return water_bubble(**kwargs)
"""Top-level package for ZotUtil.""" __author__ = """Cheng Cui""" __email__ = "cheng.cui.95@gmail.com" __version__ = "0.1.1"
"""Top-level package for ZotUtil.""" __author__ = 'Cheng Cui' __email__ = 'cheng.cui.95@gmail.com' __version__ = '0.1.1'
numbers = [1,45,31,12,60] for number in numbers: if number % 8 == 0: # Reject the list print("The numbers are unacceptable") break else: print("List okay!")
numbers = [1, 45, 31, 12, 60] for number in numbers: if number % 8 == 0: print('The numbers are unacceptable') break else: print('List okay!')
class WeatherResponse(object): """ Specifies the response to be sent for one weather object. """ def __init__(self, *args, **kwargs): """ Set values for object. :param args: :param kwargs: """ self.temp = kwargs.get("temp", None) self.temp_units = kwargs.get("temp_units", "C") self.max_temp = kwargs.get("max_temp", None) self.min_temp = kwargs.get("min_temp", None) self.code = kwargs.get("code", None) self.condensed = kwargs.get("condensed", None) self.description = kwargs.get("description", None) self.icon = kwargs.get("icon", None) self.humidity = kwargs.get("humidity", None) self.humidity_units = kwargs.get("humidity_units", "%") self.pressure = kwargs.get("pressure", None) self.pressure_units = kwargs.get("pressure_units", "hPa") def to_json(self): """ Return WeatherResponse object as python dictionary. :return: """ return self.__dict__
class Weatherresponse(object): """ Specifies the response to be sent for one weather object. """ def __init__(self, *args, **kwargs): """ Set values for object. :param args: :param kwargs: """ self.temp = kwargs.get('temp', None) self.temp_units = kwargs.get('temp_units', 'C') self.max_temp = kwargs.get('max_temp', None) self.min_temp = kwargs.get('min_temp', None) self.code = kwargs.get('code', None) self.condensed = kwargs.get('condensed', None) self.description = kwargs.get('description', None) self.icon = kwargs.get('icon', None) self.humidity = kwargs.get('humidity', None) self.humidity_units = kwargs.get('humidity_units', '%') self.pressure = kwargs.get('pressure', None) self.pressure_units = kwargs.get('pressure_units', 'hPa') def to_json(self): """ Return WeatherResponse object as python dictionary. :return: """ return self.__dict__
file = "01.data.txt" f = open(file) data = f.read() f.close() lines = data.split("\n") readings = [] for line in lines: readings.append(int(line)) print(readings) # count all the increases # have a counter counter = 0 # each time number icreases increment the counter for i in range(1, len(readings)): previous = readings[i - 1] current = readings[i] # compare previous to current is_greater = current > previous if is_greater: counter += 1 #print("{} {} {} {}".format(i, previous, current, is_greater)) print("Part 1") print(counter) # have a counter counter = 0 for i in range(3, len(readings)): a = readings[i - 3] b = readings[i - 2] c = readings[i - 1] d = readings[i] previous = a + b + c current = b + c + d # compare previous to current is_greater = current > previous if is_greater: counter += 1 #print("{} {} {} {}".format(i, previous, current, is_greater)) print("Part 2") print(counter)
file = '01.data.txt' f = open(file) data = f.read() f.close() lines = data.split('\n') readings = [] for line in lines: readings.append(int(line)) print(readings) counter = 0 for i in range(1, len(readings)): previous = readings[i - 1] current = readings[i] is_greater = current > previous if is_greater: counter += 1 print('Part 1') print(counter) counter = 0 for i in range(3, len(readings)): a = readings[i - 3] b = readings[i - 2] c = readings[i - 1] d = readings[i] previous = a + b + c current = b + c + d is_greater = current > previous if is_greater: counter += 1 print('Part 2') print(counter)
class EmptyDiscretizeFunctionError(ValueError): """Raise in place of empty discretize function when loading dataset.""" def __init__(self): message = self.message() super(EmptyDiscretizeFunctionError, self).__init__(message) @staticmethod def message(): return "Please pass discretization method in DataModel contructor when using discretize = True." class NotFittedError(ValueError): """Raise if predict is called before fit.""" def __init__(self, class_name): message = self.message(class_name) super(NotFittedError, self).__init__(message) @staticmethod def message(class_name): return ("This instance of " + class_name + " has not been fitted yet. Please call " "'fit' before you call 'predict'.") class NotEvaluatedError(ValueError): """Raise if get_f_score is called before evaluate.""" def __init__(self, class_name): message = self.message(class_name) super(NotEvaluatedError, self).__init__(message) @staticmethod def message(class_name): return ("This instance of " + class_name + " has not been evaluate yet. Please call " "'evaluate' before you call 'get_f_score'.")
class Emptydiscretizefunctionerror(ValueError): """Raise in place of empty discretize function when loading dataset.""" def __init__(self): message = self.message() super(EmptyDiscretizeFunctionError, self).__init__(message) @staticmethod def message(): return 'Please pass discretization method in DataModel contructor when using discretize = True.' class Notfittederror(ValueError): """Raise if predict is called before fit.""" def __init__(self, class_name): message = self.message(class_name) super(NotFittedError, self).__init__(message) @staticmethod def message(class_name): return 'This instance of ' + class_name + " has not been fitted yet. Please call 'fit' before you call 'predict'." class Notevaluatederror(ValueError): """Raise if get_f_score is called before evaluate.""" def __init__(self, class_name): message = self.message(class_name) super(NotEvaluatedError, self).__init__(message) @staticmethod def message(class_name): return 'This instance of ' + class_name + " has not been evaluate yet. Please call 'evaluate' before you call 'get_f_score'."
""" spam ~~~~ Toy functions for testing. """ def spam_eggs(): pass def spam_bacon(): pass def spam_baked_beans(): pass
""" spam ~~~~ Toy functions for testing. """ def spam_eggs(): pass def spam_bacon(): pass def spam_baked_beans(): pass
''' Machine Learning * Machine Learning is making the computer learn from studying data and statistics. * Machine Learning is a step into the direction of artificial intelligence (AI). * Machine Learning is a program that analyses data and learns to predict the outcome. Where To Start? * In this tutorial we will go back to mathematics and study statistics, and how to calculate important numbers based on data sets. * We will also learn how to use various Python modules to get the answers we need. * And we will learn how to make functions that are able to predict the outcome based on what we have learned. '''
""" Machine Learning * Machine Learning is making the computer learn from studying data and statistics. * Machine Learning is a step into the direction of artificial intelligence (AI). * Machine Learning is a program that analyses data and learns to predict the outcome. Where To Start? * In this tutorial we will go back to mathematics and study statistics, and how to calculate important numbers based on data sets. * We will also learn how to use various Python modules to get the answers we need. * And we will learn how to make functions that are able to predict the outcome based on what we have learned. """
class Subscriber: """ Class that defines a subscriber to a specific event """ def __init__(self, callback_method, program, event_type, object_id): self._callback_method = callback_method self._program = program self._event_type = event_type self._object_id = object_id def match(self, program, event_type, object_id): """ Looks for a subscriber to a specific event :param program: The program as defined in Program class :param event_type: The event type (NOTE_ON, NOTE_OFF, CTRL or PGM_CHG) :param object_id: The knob, pad or program change ID """ match = False if self._program == program and self._event_type == event_type and self._object_id == object_id: match = True return match def notify(self, program, object_id, data): """ Call the subscriber (subscribed method of an object) and send available data if any :param program: The program as defined in Program class :param object_id: The knob, pad or program change ID :param data: The data to send to the subscriber for processing if any """ if data == None: self._callback_method([program, object_id]) else: self._callback_method([program, object_id, data])
class Subscriber: """ Class that defines a subscriber to a specific event """ def __init__(self, callback_method, program, event_type, object_id): self._callback_method = callback_method self._program = program self._event_type = event_type self._object_id = object_id def match(self, program, event_type, object_id): """ Looks for a subscriber to a specific event :param program: The program as defined in Program class :param event_type: The event type (NOTE_ON, NOTE_OFF, CTRL or PGM_CHG) :param object_id: The knob, pad or program change ID """ match = False if self._program == program and self._event_type == event_type and (self._object_id == object_id): match = True return match def notify(self, program, object_id, data): """ Call the subscriber (subscribed method of an object) and send available data if any :param program: The program as defined in Program class :param object_id: The knob, pad or program change ID :param data: The data to send to the subscriber for processing if any """ if data == None: self._callback_method([program, object_id]) else: self._callback_method([program, object_id, data])
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"expand_dim_to_3": "00_core.ipynb", "parametric_ellipse": "00_core.ipynb", "elliplise": "00_core.ipynb", "EllipticalSeparabilityFilter": "00_core.ipynb"} modules = ["core.py"] doc_url = "https://AtomScott.github.io/circle_finder/" git_url = "https://github.com/AtomScott/circle_finder/tree/master/" def custom_doc_links(name): return None
__all__ = ['index', 'modules', 'custom_doc_links', 'git_url'] index = {'expand_dim_to_3': '00_core.ipynb', 'parametric_ellipse': '00_core.ipynb', 'elliplise': '00_core.ipynb', 'EllipticalSeparabilityFilter': '00_core.ipynb'} modules = ['core.py'] doc_url = 'https://AtomScott.github.io/circle_finder/' git_url = 'https://github.com/AtomScott/circle_finder/tree/master/' def custom_doc_links(name): return None
LOG = [] def flush_log(filename): with open(filename, 'w') as logfile: for l in LOG: logfile.write("%s\n" % l) def log_message(msg): LOG.append(msg)
log = [] def flush_log(filename): with open(filename, 'w') as logfile: for l in LOG: logfile.write('%s\n' % l) def log_message(msg): LOG.append(msg)
is_correct = executor_result["is_correct"] test_feedback = executor_result["test_feedback"] test_comments = executor_result["test_comments"] congrats = executor_result["congrats"] feedback = "" output = (test_comments + "\n" + test_feedback).strip() if output == "": output = "No issues!" if is_correct: feedback = congrats else: feedback = "Not quite. Take a look at the feedback area for some pointers." grade_result["correct"] = is_correct grade_result["feedback"] = feedback grade_result["comment"] = output
is_correct = executor_result['is_correct'] test_feedback = executor_result['test_feedback'] test_comments = executor_result['test_comments'] congrats = executor_result['congrats'] feedback = '' output = (test_comments + '\n' + test_feedback).strip() if output == '': output = 'No issues!' if is_correct: feedback = congrats else: feedback = 'Not quite. Take a look at the feedback area for some pointers.' grade_result['correct'] = is_correct grade_result['feedback'] = feedback grade_result['comment'] = output
""" Given an array of integers nums and an integer threshold, we will choose a positive integer divisor and divide all the array by it and sum the result of the division. Find the smallest divisor such that the result mentioned above is less than or equal to threshold. Each result of division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5). It is guaranteed that there will be an answer. Example: Input: nums = [1,2,5,9], threshold = 6 Output: 5 Explanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1. If the divisor is 4 we can get a sum to 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2). Example: Input: nums = [2,3,5,7,11], threshold = 11 Output: 3 Example: Input: nums = [19], threshold = 5 Output: 4 Constraints: - 1 <= nums.length <= 5 * 10^4 - 1 <= nums[i] <= 10^6 - nums.length <= threshold <= 10^6 """ #Difficulty: Medium #61 / 61 test cases passed. #Runtime: 364 ms #Memory Usage: 20 MB #Runtime: 364 ms, faster than 88.71% of Python3 online submissions for Find the Smallest Divisor Given a Threshold. #Memory Usage: 20 MB, less than 79.06% of Python3 online submissions for Find the Smallest Divisor Given a Threshold. class Solution: def smallestDivisor(self, nums: List[int], threshold: int) -> int: l = 1 r = max(nums) while l < r: m = (l+r) // 2 result = sum([1 + n//m if n%m else n//m for n in nums]) if result > threshold: l = m + 1 else: r = m return l
""" Given an array of integers nums and an integer threshold, we will choose a positive integer divisor and divide all the array by it and sum the result of the division. Find the smallest divisor such that the result mentioned above is less than or equal to threshold. Each result of division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5). It is guaranteed that there will be an answer. Example: Input: nums = [1,2,5,9], threshold = 6 Output: 5 Explanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1. If the divisor is 4 we can get a sum to 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2). Example: Input: nums = [2,3,5,7,11], threshold = 11 Output: 3 Example: Input: nums = [19], threshold = 5 Output: 4 Constraints: - 1 <= nums.length <= 5 * 10^4 - 1 <= nums[i] <= 10^6 - nums.length <= threshold <= 10^6 """ class Solution: def smallest_divisor(self, nums: List[int], threshold: int) -> int: l = 1 r = max(nums) while l < r: m = (l + r) // 2 result = sum([1 + n // m if n % m else n // m for n in nums]) if result > threshold: l = m + 1 else: r = m return l
""" Manages the character's self regeneration. -- Author : DrLarck Last update : 18/07/19 """ # charcter regen class Character_regen: """ Manages the character's self regeneration. - Attribute : `health` : Represents the health regen per turn. `ki` : Represents the ki regen per turn. """ # attribute def __init__(self): self.health = 0 self.ki = 0
""" Manages the character's self regeneration. -- Author : DrLarck Last update : 18/07/19 """ class Character_Regen: """ Manages the character's self regeneration. - Attribute : `health` : Represents the health regen per turn. `ki` : Represents the ki regen per turn. """ def __init__(self): self.health = 0 self.ki = 0
## \file OutputFormat.py # \author Dong Chen # \brief Provides the function for writing outputs ## \brief Writes the output values to output.txt # \param theta dependent variables (rad) def write_output(theta): outputfile = open("output.txt", "w") print("theta = ", end="", file=outputfile) print(theta, file=outputfile) outputfile.close()
def write_output(theta): outputfile = open('output.txt', 'w') print('theta = ', end='', file=outputfile) print(theta, file=outputfile) outputfile.close()
# LevPy: A Python JSON level-loader # for easier level abstraction # in text-based py games # Copyright (c) Finn Lancaster 2021 # Please Keep in mind that the JSONvar name must # also be the same as the function that # contains more data on it in LevPy.py # Valid JSON, names can be anything, with data after the # colon. The name must match your calls for mainLoop # in LevPy.py. See example for more detail JSONvar = '{"":""}'
jso_nvar = '{"":""}'
class Solution: def isHappy(self, n): """ :type n: int :rtype: bool """ func = lambda x : sum(int(ch) ** 2 for ch in str(x)) seen = set() while True: if n == 1: return True if n in seen: return False seen.add(n) n = func(n)
class Solution: def is_happy(self, n): """ :type n: int :rtype: bool """ func = lambda x: sum((int(ch) ** 2 for ch in str(x))) seen = set() while True: if n == 1: return True if n in seen: return False seen.add(n) n = func(n)
# STACKS, QUEUES & HEAPS # Stacks ''' A stack is a last in first out (LIFO) data structure. - Push an item onto the stack - Pop an item out of the stack All push and pop operations are to/from the top of the stack. The only way to access the bottom items in the stack is to first remove all items above it Peek - getting an item on top of the stack without removing it Clear - clear all items from the stack Use Cases Undo - tracks which commands have been executed. Pop the last command off the command stack to undo it e.g pop the last command to undo bold. The program has to keep track of which command you have executed in which order. Each time you execute a common, it pushes that command onto the stack so that it has a record of it. If you hit the undo button, it will pop the last command off the stack and reverse that command '''
""" A stack is a last in first out (LIFO) data structure. - Push an item onto the stack - Pop an item out of the stack All push and pop operations are to/from the top of the stack. The only way to access the bottom items in the stack is to first remove all items above it Peek - getting an item on top of the stack without removing it Clear - clear all items from the stack Use Cases Undo - tracks which commands have been executed. Pop the last command off the command stack to undo it e.g pop the last command to undo bold. The program has to keep track of which command you have executed in which order. Each time you execute a common, it pushes that command onto the stack so that it has a record of it. If you hit the undo button, it will pop the last command off the stack and reverse that command """
SETTINGS = { 'app': { 'schema': 'http://', 'host': 'localhost', 'port': 9000 } }
settings = {'app': {'schema': 'http://', 'host': 'localhost', 'port': 9000}}
__name__ = "python-crud" __version__ = "0.1.3" __author__ = "Derek Merck" __author_email__ = "derek.merck@ufl.edu" __desc__ = "CRUD endpoint API with Python", __url__ = "https://github.com/derekmerck/pycrud",
__name__ = 'python-crud' __version__ = '0.1.3' __author__ = 'Derek Merck' __author_email__ = 'derek.merck@ufl.edu' __desc__ = ('CRUD endpoint API with Python',) __url__ = ('https://github.com/derekmerck/pycrud',)
""" .. module:: build_features.py :synopsis: """
""" .. module:: build_features.py :synopsis: """
#!/usr/bin/env python __author__ = "Kishori M Konwar" __copyright__ = "Copyright 2013, MetaPathways" __credits__ = ["r"] __version__ = "1.0" __maintainer__ = "Kishori M Konwar" __status__ = "Release" exit_code=0
__author__ = 'Kishori M Konwar' __copyright__ = 'Copyright 2013, MetaPathways' __credits__ = ['r'] __version__ = '1.0' __maintainer__ = 'Kishori M Konwar' __status__ = 'Release' exit_code = 0
edges = { (1,'q'):1 } accepting = [1] def fsmsim(string, current, edges, accepting): if string == "": return current in accepting else: letter = string[0] if (current, letter) in edges: destination = edges[(current, letter)] remaining_string = string[1:] return fsmsim(remaining_string, destination, edges, accepting) else: return False print(fsmsim("",1,edges,accepting))
edges = {(1, 'q'): 1} accepting = [1] def fsmsim(string, current, edges, accepting): if string == '': return current in accepting else: letter = string[0] if (current, letter) in edges: destination = edges[current, letter] remaining_string = string[1:] return fsmsim(remaining_string, destination, edges, accepting) else: return False print(fsmsim('', 1, edges, accepting))
class Solution(object): def flipAndInvertImage(self, A): for row in A: for i in xrange((len(row) + 1) / 2): # ~ operator (not operator) x*-1-1 <- gets the element on the oposite side row[i], row[~i] = ~row[~i] ^ 1, row[i] ^ 1 return A
class Solution(object): def flip_and_invert_image(self, A): for row in A: for i in xrange((len(row) + 1) / 2): (row[i], row[~i]) = (~row[~i] ^ 1, row[i] ^ 1) return A
class Employee: num_of_emps = 0 raise_amt = 1.04 def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = str(first + '.' + last + '@company.com').lower() # see that we don't need to input all the # attributes. Some of them could be created using algorithms like we did here. Employee.num_of_emps += 1 def fullname(self): return '{} {}'.format(self.first, self.last) def apply_raise(self): self.pay = int(self.pay * self.raise_amt) @classmethod # this class method will change the value of the raise_amt. def set_raise_amt(cls, amount): cls.raise_amt = amount @classmethod # this class method will took a string and transform into a new instance of the class. In this case # it will create a new employee. def from_string(cls, emp_str): first, last, pay = emp_str.split('-') return cls(first, last, pay) emp_1 = Employee('Corey', 'Schafer', 50000) emp_2 = Employee('Test', 'User', 60000) Employee.set_raise_amt(1.05) print(Employee.raise_amt) print(emp_1.raise_amt) print(emp_2.raise_amt) emp_str_1 = 'John-Doe-70000' emp_str_2 = 'Steve-Smith-30000' emp_str_3 = 'Jane-Doe-90000' new_emp_1 = Employee.from_string(emp_str_1) print(new_emp_1) print(new_emp_1.email) print(new_emp_1.pay)
class Employee: num_of_emps = 0 raise_amt = 1.04 def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = str(first + '.' + last + '@company.com').lower() Employee.num_of_emps += 1 def fullname(self): return '{} {}'.format(self.first, self.last) def apply_raise(self): self.pay = int(self.pay * self.raise_amt) @classmethod def set_raise_amt(cls, amount): cls.raise_amt = amount @classmethod def from_string(cls, emp_str): (first, last, pay) = emp_str.split('-') return cls(first, last, pay) emp_1 = employee('Corey', 'Schafer', 50000) emp_2 = employee('Test', 'User', 60000) Employee.set_raise_amt(1.05) print(Employee.raise_amt) print(emp_1.raise_amt) print(emp_2.raise_amt) emp_str_1 = 'John-Doe-70000' emp_str_2 = 'Steve-Smith-30000' emp_str_3 = 'Jane-Doe-90000' new_emp_1 = Employee.from_string(emp_str_1) print(new_emp_1) print(new_emp_1.email) print(new_emp_1.pay)
numbers_of_electrons = int(input()) electrons = [] cell_number = 1 while numbers_of_electrons > 0: possible_electrons = 2*cell_number**2 if possible_electrons > numbers_of_electrons: electrons.append(numbers_of_electrons) break electrons.append(possible_electrons) numbers_of_electrons -= possible_electrons cell_number +=1 print(electrons)
numbers_of_electrons = int(input()) electrons = [] cell_number = 1 while numbers_of_electrons > 0: possible_electrons = 2 * cell_number ** 2 if possible_electrons > numbers_of_electrons: electrons.append(numbers_of_electrons) break electrons.append(possible_electrons) numbers_of_electrons -= possible_electrons cell_number += 1 print(electrons)
# Jerry Landeros def userInput(): number = int(input("Please enter a number: ")) return number def primeChecker(number): if number > 1: for i in range(2, number): if (number % i) == 0: print(number, "is not a prime number.") break else: print(number, "is a prime number.") else: print(number, "is not a prime number.") # return aPrime, notPrime pass # def printResults(number): # print(number, " is a prime number") def repeat(): repeatProgram = input("Do you want to play again? (Y or N) ") print("\n") if repeatProgram.upper() == "Y": pass elif repeatProgram.upper() == "N": print("Thank you for playing!") quit() # quit() else: print("Please enter Y or N.") repeat() def main(): while True: number = userInput() primeChecker(number) # printResults(number) repeat() main()
def user_input(): number = int(input('Please enter a number: ')) return number def prime_checker(number): if number > 1: for i in range(2, number): if number % i == 0: print(number, 'is not a prime number.') break else: print(number, 'is a prime number.') else: print(number, 'is not a prime number.') pass def repeat(): repeat_program = input('Do you want to play again? (Y or N) ') print('\n') if repeatProgram.upper() == 'Y': pass elif repeatProgram.upper() == 'N': print('Thank you for playing!') quit() else: print('Please enter Y or N.') repeat() def main(): while True: number = user_input() prime_checker(number) repeat() main()
def print_welcome(): return """ <h1>Hello world!</h1> <p> <h3>This API is intended for FoodExplorer application.</h2> """ def print_man(): return """ <h3>api/v1/food</h3> <p>POST method</p> <p>form data berisi image</p> <h3>api/v1/food?q={query}</h3> <p>GET method</p> <p>search food using text</p> <p>nyari pake query</p> <h3>api/v1/food/all</h3> <p>GET method</p> <p>get all food in the database</p> <p>ambil semua data</p> <h3>api/v1/food/<int:food_id>/detail</h3> <p>GET method</p> <p>get food details based on id</p> <p>pake path berupa id-nya food</p> <h3>api/v1/food/<int:food_id>/location?latitude={latitude}&longitude={longitude}</h3> <p>GET method</p> <p>get food stores based on id</p> <p>pake path berupa id-nya food</p> """
def print_welcome(): return '\n<h1>Hello world!</h1>\n<p>\n<h3>This API is intended for FoodExplorer application.</h2>\n\n' def print_man(): return '\n <h3>api/v1/food</h3>\n <p>POST method</p>\n <p>form data berisi image</p>\n\n <h3>api/v1/food?q={query}</h3>\n <p>GET method</p>\n <p>search food using text</p>\n <p>nyari pake query</p>\n\n <h3>api/v1/food/all</h3>\n <p>GET method</p>\n <p>get all food in the database</p>\n <p>ambil semua data</p>\n\n <h3>api/v1/food/<int:food_id>/detail</h3>\n <p>GET method</p>\n <p>get food details based on id</p>\n <p>pake path berupa id-nya food</p>\n\n <h3>api/v1/food/<int:food_id>/location?latitude={latitude}&longitude={longitude}</h3>\n <p>GET method</p>\n <p>get food stores based on id</p>\n <p>pake path berupa id-nya food</p>\n '
"""Solution to 2.7: Intersection.""" def intersect(list_one, list_two): length_one = len(list_one) length_two = len(list_two) diff = abs(length_one - length_two) head_one = list_one.head head_two = list_two.head while range(max(length_one, length_two)): if diff > 0: diff -= 1 if length_one > length_two: head_one = head_one.next_node else: head_two = head_two.next_node else: if head_one is head_two: return head_one head_one = head_one.next_node head_two = head_two.next_node
"""Solution to 2.7: Intersection.""" def intersect(list_one, list_two): length_one = len(list_one) length_two = len(list_two) diff = abs(length_one - length_two) head_one = list_one.head head_two = list_two.head while range(max(length_one, length_two)): if diff > 0: diff -= 1 if length_one > length_two: head_one = head_one.next_node else: head_two = head_two.next_node else: if head_one is head_two: return head_one head_one = head_one.next_node head_two = head_two.next_node
_base_ = [ '../_base_/models/deeplabv3_unet_s5-d16.py', './dataset.py', '../_base_/default_runtime.py', './schedule_20k.py' ] model = dict( decode_head=dict( num_classes=2,loss_decode=dict( _delete_=True, type='LovaszLoss', loss_weight=1.0, per_image=True) # type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0, class_weight=[0.25, 0.25, 0.5]) ), # loss_decode=dict( # _delete_=True, type='FocalDiceLoss', loss_weight=1.0, focal_weight=0.75) # ), auxiliary_head=dict( num_classes=2, loss_decode=dict( _delete_=True, type='LovaszLoss', loss_weight=0.4, per_image=True) # type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0, class_weight=[0.25, 0.25, 0.5]) ), # loss_decode=dict( # _delete_=True, type='FocalDiceLoss', loss_weight=0.4, focal_weight=0.75) # ), test_cfg=dict(crop_size=(128, 128), stride=(85, 85))) evaluation = dict(metric='mDice') checkpoint_config = dict(max_keep_ckpts=5)
_base_ = ['../_base_/models/deeplabv3_unet_s5-d16.py', './dataset.py', '../_base_/default_runtime.py', './schedule_20k.py'] model = dict(decode_head=dict(num_classes=2, loss_decode=dict(_delete_=True, type='LovaszLoss', loss_weight=1.0, per_image=True)), auxiliary_head=dict(num_classes=2, loss_decode=dict(_delete_=True, type='LovaszLoss', loss_weight=0.4, per_image=True)), test_cfg=dict(crop_size=(128, 128), stride=(85, 85))) evaluation = dict(metric='mDice') checkpoint_config = dict(max_keep_ckpts=5)
# Copyright (c) 2019-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # def f_gold ( arr , n ) : if ( n == 1 ) : return True i = 1 for i in range ( 1 , n ) : if arr [ i - 1 ] < arr [ i ] : if ( i == n ) : return True j = i while ( arr [ j ] < arr [ j - 1 ] ) : if ( i > 1 and arr [ j ] < arr [ i - 2 ] ) : return False j += 1 if ( j == n ) : return True k = j if ( arr [ k ] < arr [ i - 1 ] ) : return False while ( k > 1 and k < n ) : if ( arr [ k ] < arr [ k - 1 ] ) : return False k += 1 return True #TOFILL if __name__ == '__main__': param = [ ([1,2,5,4,3],5,), ([1,2,4,5,3],5,), ([1,1,0,0],4,), ([5, 99, 40, 33, 61, 4, 64, 92, 28, 27, 21, 35, 40, 79, 10, 20, 76, 87, 80, 15, 57, 39, 96, 98, 99, 72, 72, 50, 61, 39, 35, 70, 27],32,), ([-98, -92, -86, -58, -22, -12, 0, 26],6,), ([0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0],24,), ([6, 10, 27, 30, 40, 47, 49, 55, 59, 60, 68, 82, 91],8,), ([36, 56, -56, 94, 52, -82, 88, -62, 70, -94, 38, 10, -78, 66, -94, -72, 18, 96, -72, 88, -6, 48, 6, -88, 64, -96, -40, 8, 36, 36, -90, -68, -20, -76, 22, -92],30,), ([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],31,), ([2, 5, 42, 28, 47, 26, 88, 16, 30, 30, 36, 49, 21, 95, 99, 21, 41, 52, 57, 39, 69, 2, 42, 22, 55, 92, 64, 27, 95, 71, 19, 38, 40, 65, 7, 21, 29, 38, 13, 11, 41, 54, 38, 40, 35, 51, 88],46,) ] n_success = 0 for i, parameters_set in enumerate(param): if f_filled(*parameters_set) == f_gold(*parameters_set): n_success+=1 print("#Results: %i, %i" % (n_success, len(param)))
def f_gold(arr, n): if n == 1: return True i = 1 for i in range(1, n): if arr[i - 1] < arr[i]: if i == n: return True j = i while arr[j] < arr[j - 1]: if i > 1 and arr[j] < arr[i - 2]: return False j += 1 if j == n: return True k = j if arr[k] < arr[i - 1]: return False while k > 1 and k < n: if arr[k] < arr[k - 1]: return False k += 1 return True if __name__ == '__main__': param = [([1, 2, 5, 4, 3], 5), ([1, 2, 4, 5, 3], 5), ([1, 1, 0, 0], 4), ([5, 99, 40, 33, 61, 4, 64, 92, 28, 27, 21, 35, 40, 79, 10, 20, 76, 87, 80, 15, 57, 39, 96, 98, 99, 72, 72, 50, 61, 39, 35, 70, 27], 32), ([-98, -92, -86, -58, -22, -12, 0, 26], 6), ([0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0], 24), ([6, 10, 27, 30, 40, 47, 49, 55, 59, 60, 68, 82, 91], 8), ([36, 56, -56, 94, 52, -82, 88, -62, 70, -94, 38, 10, -78, 66, -94, -72, 18, 96, -72, 88, -6, 48, 6, -88, 64, -96, -40, 8, 36, 36, -90, -68, -20, -76, 22, -92], 30), ([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 31), ([2, 5, 42, 28, 47, 26, 88, 16, 30, 30, 36, 49, 21, 95, 99, 21, 41, 52, 57, 39, 69, 2, 42, 22, 55, 92, 64, 27, 95, 71, 19, 38, 40, 65, 7, 21, 29, 38, 13, 11, 41, 54, 38, 40, 35, 51, 88], 46)] n_success = 0 for (i, parameters_set) in enumerate(param): if f_filled(*parameters_set) == f_gold(*parameters_set): n_success += 1 print('#Results: %i, %i' % (n_success, len(param)))
# Maria O Sullivan # Project Euler 5 # https://projecteuler.net/problem=5 i = 20 while 1: i+=20 #i remainder 11 equals 0 if i%11==0 and i%12==0 and i%13==0 and i%14==0 and i%15==0\ and i%15==0 and i%16==0 and i%17==0 and i%18==0 and i%19==0: print(i) break
i = 20 while 1: i += 20 if i % 11 == 0 and i % 12 == 0 and (i % 13 == 0) and (i % 14 == 0) and (i % 15 == 0) and (i % 15 == 0) and (i % 16 == 0) and (i % 17 == 0) and (i % 18 == 0) and (i % 19 == 0): print(i) break
# # Problem: Create a function that takes a message as a list of characters and reverses the order of the words # in-place. # # For example: # message = [ 'c', 'a', 'k', 'e', ' ', # 'p', 'o', 'u', 'n', 'd', ' ', # 's', 't', 'e', 'a', 'l' ] # # reverse_words(message) # # print ''.join(message) --- prints "steal pound cake" # def reverse_characters(chars, start_index, end_index): while start_index < end_index: chars[start_index], chars[end_index] = chars[end_index], chars[start_index] start_index += 1 end_index -= 1 def reverse_words(chars): """ Solution: Reverse each character to get the words in the right order, then re-reverse each word. Complexity: Time: O(n) (twice) Space: O(1) """ reverse_characters(chars, 0, len(chars) - 1) start_index = 0 for i, char in enumerate(chars): if char == ' ' or i == len(chars) - 1: # If we find a space, set end index to previous index, otherwise we're at the end of our list # and leave it at the last index end_index = i - 1 if char == ' ' else i reverse_characters(chars, start_index, end_index) start_index = i + 1
def reverse_characters(chars, start_index, end_index): while start_index < end_index: (chars[start_index], chars[end_index]) = (chars[end_index], chars[start_index]) start_index += 1 end_index -= 1 def reverse_words(chars): """ Solution: Reverse each character to get the words in the right order, then re-reverse each word. Complexity: Time: O(n) (twice) Space: O(1) """ reverse_characters(chars, 0, len(chars) - 1) start_index = 0 for (i, char) in enumerate(chars): if char == ' ' or i == len(chars) - 1: end_index = i - 1 if char == ' ' else i reverse_characters(chars, start_index, end_index) start_index = i + 1
""" Copyright 2018 Akshit Grover 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 ListenerCountReached(Exception): def __init__(self, count = 0, event = ""): self.__listenerCount = count self.__eventName = event def string(self): return "\nListenerCountReached: Maximum Listener count '{}' reached for event '{}'\n".format(self.__listenerCount, self.__eventName) pass def errorHandler(err): print(err.string())
""" Copyright 2018 Akshit Grover 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 Listenercountreached(Exception): def __init__(self, count=0, event=''): self.__listenerCount = count self.__eventName = event def string(self): return "\nListenerCountReached: Maximum Listener count '{}' reached for event '{}'\n".format(self.__listenerCount, self.__eventName) pass def error_handler(err): print(err.string())
class TreeNode: def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right def __repr__(self): return str(self.data) def insert(self, data): """ - If value is less then root node, find empty leaf and insert into left - If value is greater than root node, find empty leaf and insert into right :param data: :return: """ if data: if data < self.data: if self.left is None: print(f"{data} inserted into left side of {self.data}") self.left = TreeNode(data=data) else: self.left.insert(data=data) else: if self.right is None: print(f"{data} inserted into right side of {self.data}") self.right = TreeNode(data=data) else: self.right.insert(data=data) # Depth First Search def inorder(root: TreeNode): if root: inorder(root.left) print(root, end=" ") inorder(root.right) if __name__ == "__main__": t = TreeNode(25) t.insert(15) t.insert(50) t.insert(10) t.insert(22) t.insert(35) t.insert(70) t.insert(4) t.insert(12) t.insert(18) t.insert(24) t.insert(31) t.insert(44) t.insert(66) t.insert(90) inorder(t)
class Treenode: def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right def __repr__(self): return str(self.data) def insert(self, data): """ - If value is less then root node, find empty leaf and insert into left - If value is greater than root node, find empty leaf and insert into right :param data: :return: """ if data: if data < self.data: if self.left is None: print(f'{data} inserted into left side of {self.data}') self.left = tree_node(data=data) else: self.left.insert(data=data) elif self.right is None: print(f'{data} inserted into right side of {self.data}') self.right = tree_node(data=data) else: self.right.insert(data=data) def inorder(root: TreeNode): if root: inorder(root.left) print(root, end=' ') inorder(root.right) if __name__ == '__main__': t = tree_node(25) t.insert(15) t.insert(50) t.insert(10) t.insert(22) t.insert(35) t.insert(70) t.insert(4) t.insert(12) t.insert(18) t.insert(24) t.insert(31) t.insert(44) t.insert(66) t.insert(90) inorder(t)
HTML_CODE_OPEN = "<code>" HTML_CODE_CLOSE = "</code>" HTML_NEW_LINE = "\n" ETH_NULL_ADDRESS = '0x0000000000000000000000000000000000000000' ETH_WETH_ADDRESS = "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"
html_code_open = '<code>' html_code_close = '</code>' html_new_line = '\n' eth_null_address = '0x0000000000000000000000000000000000000000' eth_weth_address = '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2'
question_data = [ {"category": "Science & Nature", "type": "boolean", "difficulty": "medium", "question": "The Neanderthals were a direct ancestor of modern humans.", "correct_answer": "False", "incorrect_answers": ["True"]}, {"category": "Science & Nature", "type": "boolean", "difficulty": "medium", "question": "The Doppler effect applies to light.", "correct_answer": "True", "incorrect_answers": ["False"]}, {"category": "Science & Nature", "type": "boolean", "difficulty": "medium", "question": "Chickens can live without a head.", "correct_answer": "True", "incorrect_answers": ["False"]}, {"category": "Science & Nature", "type": "boolean", "difficulty": "medium", "question": "The &quot;Gympie Stinger&quot; is the deadliest plant in the world.", "correct_answer": "False", "incorrect_answers": ["True"]}, {"category": "Science & Nature", "type": "boolean", "difficulty": "medium", "question": "Like with the Neanderthals, Homo sapiens sapiens also interbred with the Denisovans.", "correct_answer": "True", "incorrect_answers": ["False"]}, {"category": "Science & Nature", "type": "boolean", "difficulty": "medium", "question": "Type 1 diabetes is a result of the liver working improperly.", "correct_answer": "False", "incorrect_answers": ["True"]}, {"category": "Science & Nature", "type": "boolean", "difficulty": "medium", "question": "Anatomy considers the forms of macroscopic structures such as organs and organ systems.", "correct_answer": "True", "incorrect_answers": ["False"]}, {"category": "Science & Nature", "type": "boolean", "difficulty": "medium", "question": "In the periodic table, Potassium&#039;s symbol is the letter K.", "correct_answer": "True", "incorrect_answers": ["False"]}, {"category": "Science & Nature", "type": "boolean", "difficulty": "medium", "question": "The most frequent subconscious activity repeated by the human body is blinking.", "correct_answer": "False", "incorrect_answers": ["True"]}, {"category": "Science & Nature", "type": "boolean", "difficulty": "medium", "question": "&quot;Tachycardia&quot; or &quot;Tachyarrhythmia&quot; refers to a resting heart-rate near or over 100 BPM.", "correct_answer": "True", "incorrect_answers": ["False"]} ]
question_data = [{'category': 'Science & Nature', 'type': 'boolean', 'difficulty': 'medium', 'question': 'The Neanderthals were a direct ancestor of modern humans.', 'correct_answer': 'False', 'incorrect_answers': ['True']}, {'category': 'Science & Nature', 'type': 'boolean', 'difficulty': 'medium', 'question': 'The Doppler effect applies to light.', 'correct_answer': 'True', 'incorrect_answers': ['False']}, {'category': 'Science & Nature', 'type': 'boolean', 'difficulty': 'medium', 'question': 'Chickens can live without a head.', 'correct_answer': 'True', 'incorrect_answers': ['False']}, {'category': 'Science & Nature', 'type': 'boolean', 'difficulty': 'medium', 'question': 'The &quot;Gympie Stinger&quot; is the deadliest plant in the world.', 'correct_answer': 'False', 'incorrect_answers': ['True']}, {'category': 'Science & Nature', 'type': 'boolean', 'difficulty': 'medium', 'question': 'Like with the Neanderthals, Homo sapiens sapiens also interbred with the Denisovans.', 'correct_answer': 'True', 'incorrect_answers': ['False']}, {'category': 'Science & Nature', 'type': 'boolean', 'difficulty': 'medium', 'question': 'Type 1 diabetes is a result of the liver working improperly.', 'correct_answer': 'False', 'incorrect_answers': ['True']}, {'category': 'Science & Nature', 'type': 'boolean', 'difficulty': 'medium', 'question': 'Anatomy considers the forms of macroscopic structures such as organs and organ systems.', 'correct_answer': 'True', 'incorrect_answers': ['False']}, {'category': 'Science & Nature', 'type': 'boolean', 'difficulty': 'medium', 'question': 'In the periodic table, Potassium&#039;s symbol is the letter K.', 'correct_answer': 'True', 'incorrect_answers': ['False']}, {'category': 'Science & Nature', 'type': 'boolean', 'difficulty': 'medium', 'question': 'The most frequent subconscious activity repeated by the human body is blinking.', 'correct_answer': 'False', 'incorrect_answers': ['True']}, {'category': 'Science & Nature', 'type': 'boolean', 'difficulty': 'medium', 'question': '&quot;Tachycardia&quot; or &quot;Tachyarrhythmia&quot; refers to a resting heart-rate near or over 100 BPM.', 'correct_answer': 'True', 'incorrect_answers': ['False']}]